_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
090a24c2f6d39aab032d02335daaa77c24e7ab8dee236092d4dd65a6ad444020
fragnix/fragnix
GHC.Enum.hs
{-# LINE 1 "GHC.Enum.hs" #-} # LANGUAGE Trustworthy # # LANGUAGE CPP , NoImplicitPrelude , BangPatterns , MagicHash # {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | Module : Copyright : ( c ) The University of Glasgow , 1992 - 2002 -- License : see libraries/base/LICENSE -- -- Maintainer : -- Stability : internal Portability : non - portable ( GHC extensions ) -- The ' ' and ' Bounded ' classes . -- ----------------------------------------------------------------------------- module GHC.Enum( Bounded(..), Enum(..), boundedEnumFrom, boundedEnumFromThen, toEnumError, fromEnumError, succError, predError, Instances for Bounded and : ( ) , , Int ) where import GHC.Base hiding ( many ) import GHC.Char import GHC.Integer import GHC.Num import GHC.Show default () -- Double isn't available yet -- | The 'Bounded' class is used to name the upper and lower limits of a type . ' ' is not a superclass of ' Bounded ' since types that are not -- totally ordered may also have upper and lower bounds. -- The ' Bounded ' class may be derived for any enumeration type ; ' ' is the first constructor listed in the @data@ declaration and ' maxBound ' is the last . -- 'Bounded' may also be derived for single-constructor datatypes whose -- constituent types are in 'Bounded'. class Bounded a where minBound, maxBound :: a | Class ' ' defines operations on sequentially ordered types . -- The @enumFrom@ ... methods are used in 's translation of -- arithmetic sequences. -- Instances of ' ' may be derived for any enumeration type ( types -- whose constructors have no fields). The nullary constructors are assumed to be numbered left - to - right by ' fromEnum ' from @0@ through @n-1@. See Chapter 10 of the /Haskell Report/ for more details . -- For any type that is an instance of class ' Bounded ' as well as ' ' , -- the following should hold: -- * The calls @'succ ' ' maxBound'@ and @'pred ' ' minBound'@ should result in -- a runtime error. -- -- * 'fromEnum' and 'toEnum' should give a runtime error if the -- result value is not representable in the result type. For example , @'toEnum ' 7 : : ' Bool'@ is an error . -- -- * 'enumFrom' and 'enumFromThen' should be defined with an implicit bound, -- thus: -- > enumFrom x = enumFromTo x maxBound > enumFromThen x y = enumFromThenTo x y bound -- > where > bound | fromEnum y > = fromEnum x = maxBound > | otherwise = -- class Enum a where | the successor of a value . For numeric types , ' succ ' adds 1 . succ :: a -> a | the predecessor of a value . For numeric types , ' pred ' subtracts 1 . pred :: a -> a -- | Convert from an 'Int'. toEnum :: Int -> a -- | Convert to an 'Int'. -- It is implementation-dependent what 'fromEnum' returns when -- applied to a value that is too large to fit in an 'Int'. fromEnum :: a -> Int | Used in Haskell 's translation of @[n .. ]@. enumFrom :: a -> [a] | Used in Haskell 's translation of @[n , n' .. ]@. enumFromThen :: a -> a -> [a] | Used in Haskell 's translation of @[n .. m]@. enumFromTo :: a -> a -> [a] | Used in Haskell 's translation of @[n , n' .. m]@. enumFromThenTo :: a -> a -> a -> [a] succ = toEnum . (+ 1) . fromEnum pred = toEnum . (subtract 1) . fromEnum enumFrom x = map toEnum [fromEnum x ..] enumFromThen x y = map toEnum [fromEnum x, fromEnum y ..] enumFromTo x y = map toEnum [fromEnum x .. fromEnum y] enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y] -- Default methods for bounded enumerations boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)] boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFromThen n1 n2 | i_n2 >= i_n1 = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)] | otherwise = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)] where i_n1 = fromEnum n1 i_n2 = fromEnum n2 ------------------------------------------------------------------------ -- Helper functions ------------------------------------------------------------------------ {-# NOINLINE toEnumError #-} toEnumError :: (Show a) => String -> Int -> (a,a) -> b toEnumError inst_ty i bnds = errorWithoutStackTrace $ "Enum.toEnum{" ++ inst_ty ++ "}: tag (" ++ show i ++ ") is outside of bounds " ++ show bnds {-# NOINLINE fromEnumError #-} fromEnumError :: (Show a) => String -> a -> b fromEnumError inst_ty x = errorWithoutStackTrace $ "Enum.fromEnum{" ++ inst_ty ++ "}: value (" ++ show x ++ ") is outside of Int's bounds " ++ show (minBound::Int, maxBound::Int) # NOINLINE succError # succError :: String -> a succError inst_ty = errorWithoutStackTrace $ "Enum.succ{" ++ inst_ty ++ "}: tried to take `succ' of maxBound" # NOINLINE predError # predError :: String -> a predError inst_ty = errorWithoutStackTrace $ "Enum.pred{" ++ inst_ty ++ "}: tried to take `pred' of minBound" ------------------------------------------------------------------------ Tuples ------------------------------------------------------------------------ instance Bounded () where minBound = () maxBound = () instance Enum () where succ _ = errorWithoutStackTrace "Prelude.Enum.().succ: bad argument" pred _ = errorWithoutStackTrace "Prelude.Enum.().pred: bad argument" toEnum x | x == 0 = () | otherwise = errorWithoutStackTrace "Prelude.Enum.().toEnum: bad argument" fromEnum () = 0 enumFrom () = [()] enumFromThen () () = let many = ():many in many enumFromTo () () = [()] enumFromThenTo () () () = let many = ():many in many Report requires instances up to 15 instance (Bounded a, Bounded b) => Bounded (a,b) where minBound = (minBound, minBound) maxBound = (maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where minBound = (minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where minBound = (minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a,b,c,d,e) where minBound = (minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f) => Bounded (a,b,c,d,e,f) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g) => Bounded (a,b,c,d,e,f,g) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h) => Bounded (a,b,c,d,e,f,g,h) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i) => Bounded (a,b,c,d,e,f,g,h,i) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j) => Bounded (a,b,c,d,e,f,g,h,i,j) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k) => Bounded (a,b,c,d,e,f,g,h,i,j,k) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n, Bounded o) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) ------------------------------------------------------------------------ -- Bool ------------------------------------------------------------------------ instance Bounded Bool where minBound = False maxBound = True instance Enum Bool where succ False = True succ True = errorWithoutStackTrace "Prelude.Enum.Bool.succ: bad argument" pred True = False pred False = errorWithoutStackTrace "Prelude.Enum.Bool.pred: bad argument" toEnum n | n == 0 = False | n == 1 = True | otherwise = errorWithoutStackTrace "Prelude.Enum.Bool.toEnum: bad argument" fromEnum False = 0 fromEnum True = 1 -- Use defaults for the rest enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen ------------------------------------------------------------------------ -- Ordering ------------------------------------------------------------------------ instance Bounded Ordering where minBound = LT maxBound = GT instance Enum Ordering where succ LT = EQ succ EQ = GT succ GT = errorWithoutStackTrace "Prelude.Enum.Ordering.succ: bad argument" pred GT = EQ pred EQ = LT pred LT = errorWithoutStackTrace "Prelude.Enum.Ordering.pred: bad argument" toEnum n | n == 0 = LT | n == 1 = EQ | n == 2 = GT toEnum _ = errorWithoutStackTrace "Prelude.Enum.Ordering.toEnum: bad argument" fromEnum LT = 0 fromEnum EQ = 1 fromEnum GT = 2 -- Use defaults for the rest enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen ------------------------------------------------------------------------ -- Char ------------------------------------------------------------------------ instance Bounded Char where minBound = '\0' maxBound = '\x10FFFF' instance Enum Char where succ (C# c#) | isTrue# (ord# c# /=# 0x10FFFF#) = C# (chr# (ord# c# +# 1#)) | otherwise = errorWithoutStackTrace ("Prelude.Enum.Char.succ: bad argument") pred (C# c#) | isTrue# (ord# c# /=# 0#) = C# (chr# (ord# c# -# 1#)) | otherwise = errorWithoutStackTrace ("Prelude.Enum.Char.pred: bad argument") toEnum = chr fromEnum = ord # INLINE enumFrom # enumFrom (C# x) = eftChar (ord# x) 0x10FFFF# -- Blarg: technically I guess enumFrom isn't strict! # INLINE enumFromTo # enumFromTo (C# x) (C# y) = eftChar (ord# x) (ord# y) # INLINE enumFromThen # enumFromThen (C# x1) (C# x2) = efdChar (ord# x1) (ord# x2) {-# INLINE enumFromThenTo #-} enumFromThenTo (C# x1) (C# x2) (C# y) = efdtChar (ord# x1) (ord# x2) (ord# y) See Note [ How the rules work ] # RULES " eftChar " [ ~1 ] forall x y. eftChar x y = build ( \c n - > eftCharFB c n x y ) " efdChar " [ ~1 ] forall x1 x2 . efdChar x1 x2 = build ( \ c n - > efdCharFB c n x1 x2 ) " efdtChar " [ ~1 ] forall x1 x2 l. efdtChar x1 x2 l = build ( \ c n - > efdtCharFB c n x1 x2 l ) " eftCharList " [ 1 ] eftCharFB ( :) [ ] = eftChar " efdCharList " [ 1 ] efdCharFB ( :) [ ] = efdChar " efdtCharList " [ 1 ] efdtCharFB ( :) [ ] = efdtChar # "eftChar" [~1] forall x y. eftChar x y = build (\c n -> eftCharFB c n x y) "efdChar" [~1] forall x1 x2. efdChar x1 x2 = build (\ c n -> efdCharFB c n x1 x2) "efdtChar" [~1] forall x1 x2 l. efdtChar x1 x2 l = build (\ c n -> efdtCharFB c n x1 x2 l) "eftCharList" [1] eftCharFB (:) [] = eftChar "efdCharList" [1] efdCharFB (:) [] = efdChar "efdtCharList" [1] efdtCharFB (:) [] = efdtChar #-} We can do better than for because we do n't have hassles about arithmetic overflow at maxBound {-# INLINE [0] eftCharFB #-} eftCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a eftCharFB c n x0 y = go x0 where go x | isTrue# (x ># y) = n | otherwise = C# (chr# x) `c` go (x +# 1#) # NOINLINE [ 1 ] eftChar # eftChar :: Int# -> Int# -> String eftChar x y | isTrue# (x ># y ) = [] | otherwise = C# (chr# x) : eftChar (x +# 1#) y -- For enumFromThenTo we give up on inlining {-# NOINLINE [0] efdCharFB #-} efdCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a efdCharFB c n x1 x2 | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta 0x10FFFF# | otherwise = go_dn_char_fb c n x1 delta 0# where !delta = x2 -# x1 # NOINLINE [ 1 ] efdChar # efdChar :: Int# -> Int# -> String efdChar x1 x2 | isTrue# (delta >=# 0#) = go_up_char_list x1 delta 0x10FFFF# | otherwise = go_dn_char_list x1 delta 0# where !delta = x2 -# x1 {-# NOINLINE [0] efdtCharFB #-} efdtCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a efdtCharFB c n x1 x2 lim | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta lim | otherwise = go_dn_char_fb c n x1 delta lim where !delta = x2 -# x1 {-# NOINLINE [1] efdtChar #-} efdtChar :: Int# -> Int# -> Int# -> String efdtChar x1 x2 lim | isTrue# (delta >=# 0#) = go_up_char_list x1 delta lim | otherwise = go_dn_char_list x1 delta lim where !delta = x2 -# x1 go_up_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a go_up_char_fb c n x0 delta lim = go_up x0 where go_up x | isTrue# (x ># lim) = n | otherwise = C# (chr# x) `c` go_up (x +# delta) go_dn_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a go_dn_char_fb c n x0 delta lim = go_dn x0 where go_dn x | isTrue# (x <# lim) = n | otherwise = C# (chr# x) `c` go_dn (x +# delta) go_up_char_list :: Int# -> Int# -> Int# -> String go_up_char_list x0 delta lim = go_up x0 where go_up x | isTrue# (x ># lim) = [] | otherwise = C# (chr# x) : go_up (x +# delta) go_dn_char_list :: Int# -> Int# -> Int# -> String go_dn_char_list x0 delta lim = go_dn x0 where go_dn x | isTrue# (x <# lim) = [] | otherwise = C# (chr# x) : go_dn (x +# delta) ------------------------------------------------------------------------ -- Int ------------------------------------------------------------------------ Be careful about these instances . ( a ) remember that you have to count down as well as up e.g. [ 13,12 .. 0 ] ( b ) be careful of Int overflow ( c ) remember that is bounded , so [ 1 .. ] terminates at maxInt Be careful about these instances. (a) remember that you have to count down as well as up e.g. [13,12..0] (b) be careful of Int overflow (c) remember that Int is bounded, so [1..] terminates at maxInt -} instance Bounded Int where minBound = minInt maxBound = maxInt instance Enum Int where succ x | x == maxBound = errorWithoutStackTrace "Prelude.Enum.succ{Int}: tried to take `succ' of maxBound" | otherwise = x + 1 pred x | x == minBound = errorWithoutStackTrace "Prelude.Enum.pred{Int}: tried to take `pred' of minBound" | otherwise = x - 1 toEnum x = x fromEnum x = x # INLINE enumFrom # enumFrom (I# x) = eftInt x maxInt# where !(I# maxInt#) = maxInt -- Blarg: technically I guess enumFrom isn't strict! # INLINE enumFromTo # enumFromTo (I# x) (I# y) = eftInt x y # INLINE enumFromThen # enumFromThen (I# x1) (I# x2) = efdInt x1 x2 {-# INLINE enumFromThenTo #-} enumFromThenTo (I# x1) (I# x2) (I# y) = efdtInt x1 x2 y ----------------------------------------------------- eftInt and eftIntFB deal with [ a .. b ] , which is the -- most common form, so we take a lot of care -- In particular, we have rules for deforestation # RULES " eftInt " [ ~1 ] forall x y. eftInt x y = build ( \ c n - > eftIntFB c n x y ) " eftIntList " [ 1 ] eftIntFB ( :) [ ] = eftInt # "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y) "eftIntList" [1] eftIntFB (:) [] = eftInt #-} Note [ How the rules work ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Phase 2 : eftInt --- > build . eftIntFB * Phase 1 : inline build ; eftIntFB ( :) -- > eftInt * Phase 0 : optionally inline eftInt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Phase 2: eftInt ---> build . eftIntFB * Phase 1: inline build; eftIntFB (:) --> eftInt * Phase 0: optionally inline eftInt -} # NOINLINE [ 1 ] eftInt # eftInt :: Int# -> Int# -> [Int] -- [x1..x2] eftInt x0 y | isTrue# (x0 ># y) = [] | otherwise = go x0 where go x = I# x : if isTrue# (x ==# y) then [] else go (x +# 1#) {-# INLINE [0] eftIntFB #-} eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r eftIntFB c n x0 y | isTrue# (x0 ># y) = n | otherwise = go x0 where go x = I# x `c` if isTrue# (x ==# y) then n else go (x +# 1#) Watch out for y = maxBound ; hence = = , not > Be very careful not to have more than one " c " -- so that when eftInfFB is inlined we can inline -- whatever is bound to "c" ----------------------------------------------------- -- efdInt and efdtInt deal with [a,b..] and [a,b..c]. -- The code is more complicated because of worries about Int overflow. See Note [ How the rules work ] # RULES " efdtInt " [ ~1 ] forall x1 x2 y. efdtInt x1 x2 y = build ( \ c n - > efdtIntFB c n x1 x2 y ) " efdtIntUpList " [ 1 ] efdtIntFB ( :) [ ] = efdtInt # "efdtInt" [~1] forall x1 x2 y. efdtInt x1 x2 y = build (\ c n -> efdtIntFB c n x1 x2 y) "efdtIntUpList" [1] efdtIntFB (:) [] = efdtInt #-} efdInt :: Int# -> Int# -> [Int] [ x1,x2 .. maxInt ] efdInt x1 x2 | isTrue# (x2 >=# x1) = case maxInt of I# y -> efdtIntUp x1 x2 y | otherwise = case minInt of I# y -> efdtIntDn x1 x2 y # NOINLINE [ 1 ] efdtInt # efdtInt :: Int# -> Int# -> Int# -> [Int] [ .. y ] efdtInt x1 x2 y | isTrue# (x2 >=# x1) = efdtIntUp x1 x2 y | otherwise = efdtIntDn x1 x2 y {-# INLINE [0] efdtIntFB #-} efdtIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r efdtIntFB c n x1 x2 y | isTrue# (x2 >=# x1) = efdtIntUpFB c n x1 x2 y | otherwise = efdtIntDnFB c n x1 x2 y -- Requires x2 >= x1 efdtIntUp :: Int# -> Int# -> Int# -> [Int] efdtIntUp x1 x2 y -- Be careful about overflow! | isTrue# (y <# x2) = if isTrue# (y <# x1) then [] else [I# x1] | otherwise = -- Common case: x1 <= x2 <= y > = 0 !y' = y -# delta -- x1 <= y' <= y; hence y' is representable -- Invariant: x <= y -- Note that: z <= y' => z + delta won't overflow -- so we are guaranteed not to overflow if/when we recurse go_up x | isTrue# (x ># y') = [I# x] | otherwise = I# x : go_up (x +# delta) in I# x1 : go_up x2 -- Requires x2 >= x1 efdtIntUpFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r efdtIntUpFB c n x1 x2 y -- Be careful about overflow! | isTrue# (y <# x2) = if isTrue# (y <# x1) then n else I# x1 `c` n | otherwise = -- Common case: x1 <= x2 <= y > = 0 !y' = y -# delta -- x1 <= y' <= y; hence y' is representable -- Invariant: x <= y -- Note that: z <= y' => z + delta won't overflow -- so we are guaranteed not to overflow if/when we recurse go_up x | isTrue# (x ># y') = I# x `c` n | otherwise = I# x `c` go_up (x +# delta) in I# x1 `c` go_up x2 -- Requires x2 <= x1 efdtIntDn :: Int# -> Int# -> Int# -> [Int] efdtIntDn x1 x2 y -- Be careful about underflow! | isTrue# (y ># x2) = if isTrue# (y ># x1) then [] else [I# x1] | otherwise = -- Common case: x1 >= x2 >= y < = 0 !y' = y -# delta -- y <= y' <= x1; hence y' is representable -- Invariant: x >= y -- Note that: z >= y' => z + delta won't underflow -- so we are guaranteed not to underflow if/when we recurse go_dn x | isTrue# (x <# y') = [I# x] | otherwise = I# x : go_dn (x +# delta) in I# x1 : go_dn x2 -- Requires x2 <= x1 efdtIntDnFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r efdtIntDnFB c n x1 x2 y -- Be careful about underflow! | isTrue# (y ># x2) = if isTrue# (y ># x1) then n else I# x1 `c` n | otherwise = -- Common case: x1 >= x2 >= y < = 0 !y' = y -# delta -- y <= y' <= x1; hence y' is representable -- Invariant: x >= y -- Note that: z >= y' => z + delta won't underflow -- so we are guaranteed not to underflow if/when we recurse go_dn x | isTrue# (x <# y') = I# x `c` n | otherwise = I# x `c` go_dn (x +# delta) in I# x1 `c` go_dn x2 ------------------------------------------------------------------------ Word ------------------------------------------------------------------------ instance Bounded Word where minBound = 0 use unboxed literals for maxBound , because GHC does n't optimise ( fromInteger 0xffffffff : : Word ) . maxBound = W# (int2Word# 0xFFFFFFFFFFFFFFFF#) instance Enum Word where succ x | x /= maxBound = x + 1 | otherwise = succError "Word" pred x | x /= minBound = x - 1 | otherwise = predError "Word" toEnum i@(I# i#) | i >= 0 = W# (int2Word# i#) | otherwise = toEnumError "Word" i (minBound::Word, maxBound::Word) fromEnum x@(W# x#) | x <= maxIntWord = I# (word2Int# x#) | otherwise = fromEnumError "Word" x # INLINE enumFrom # enumFrom (W# x#) = eftWord x# maxWord# where !(W# maxWord#) = maxBound -- Blarg: technically I guess enumFrom isn't strict! # INLINE enumFromTo # enumFromTo (W# x) (W# y) = eftWord x y # INLINE enumFromThen # enumFromThen (W# x1) (W# x2) = efdWord x1 x2 {-# INLINE enumFromThenTo #-} enumFromThenTo (W# x1) (W# x2) (W# y) = efdtWord x1 x2 y maxIntWord :: Word -- The biggest word representable as an Int maxIntWord = W# (case maxInt of I# i -> int2Word# i) ----------------------------------------------------- -- eftWord and eftWordFB deal with [a..b], which is the -- most common form, so we take a lot of care -- In particular, we have rules for deforestation # RULES " eftWord " [ ~1 ] forall x y. eftWord x y = build ( \ c n - > eftWordFB c n x y ) " eftWordList " [ 1 ] eftWordFB ( :) [ ] = eftWord # "eftWord" [~1] forall x y. eftWord x y = build (\ c n -> eftWordFB c n x y) "eftWordList" [1] eftWordFB (:) [] = eftWord #-} The rules for Word work much the same way that they do for Int . See Note [ How the rules work ] . # NOINLINE [ 1 ] eftWord # eftWord :: Word# -> Word# -> [Word] -- [x1..x2] eftWord x0 y | isTrue# (x0 `gtWord#` y) = [] | otherwise = go x0 where go x = W# x : if isTrue# (x `eqWord#` y) then [] else go (x `plusWord#` 1##) {-# INLINE [0] eftWordFB #-} eftWordFB :: (Word -> r -> r) -> r -> Word# -> Word# -> r eftWordFB c n x0 y | isTrue# (x0 `gtWord#` y) = n | otherwise = go x0 where go x = W# x `c` if isTrue# (x `eqWord#` y) then n else go (x `plusWord#` 1##) Watch out for y = maxBound ; hence = = , not > Be very careful not to have more than one " c " -- so that when eftInfFB is inlined we can inline -- whatever is bound to "c" ----------------------------------------------------- -- efdWord and efdtWord deal with [a,b..] and [a,b..c]. -- The code is more complicated because of worries about Word overflow. See Note [ How the rules work ] # RULES " efdtWord " [ ~1 ] forall x1 x2 y. efdtWord x1 x2 y = build ( \ c n - > efdtWordFB c n x1 x2 y ) " efdtWordUpList " [ 1 ] efdtWordFB ( :) [ ] = efdtWord # "efdtWord" [~1] forall x1 x2 y. efdtWord x1 x2 y = build (\ c n -> efdtWordFB c n x1 x2 y) "efdtWordUpList" [1] efdtWordFB (:) [] = efdtWord #-} efdWord :: Word# -> Word# -> [Word] [ .. maxWord ] efdWord x1 x2 | isTrue# (x2 `geWord#` x1) = case maxBound of W# y -> efdtWordUp x1 x2 y | otherwise = case minBound of W# y -> efdtWordDn x1 x2 y # NOINLINE [ 1 ] efdtWord # efdtWord :: Word# -> Word# -> Word# -> [Word] [ .. y ] efdtWord x1 x2 y | isTrue# (x2 `geWord#` x1) = efdtWordUp x1 x2 y | otherwise = efdtWordDn x1 x2 y {-# INLINE [0] efdtWordFB #-} efdtWordFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r efdtWordFB c n x1 x2 y | isTrue# (x2 `geWord#` x1) = efdtWordUpFB c n x1 x2 y | otherwise = efdtWordDnFB c n x1 x2 y -- Requires x2 >= x1 efdtWordUp :: Word# -> Word# -> Word# -> [Word] efdtWordUp x1 x2 y -- Be careful about overflow! | isTrue# (y `ltWord#` x2) = if isTrue# (y `ltWord#` x1) then [] else [W# x1] | otherwise = -- Common case: x1 <= x2 <= y > = 0 !y' = y `minusWord#` delta -- x1 <= y' <= y; hence y' is representable -- Invariant: x <= y -- Note that: z <= y' => z + delta won't overflow -- so we are guaranteed not to overflow if/when we recurse go_up x | isTrue# (x `gtWord#` y') = [W# x] | otherwise = W# x : go_up (x `plusWord#` delta) in W# x1 : go_up x2 -- Requires x2 >= x1 efdtWordUpFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r efdtWordUpFB c n x1 x2 y -- Be careful about overflow! | isTrue# (y `ltWord#` x2) = if isTrue# (y `ltWord#` x1) then n else W# x1 `c` n | otherwise = -- Common case: x1 <= x2 <= y > = 0 !y' = y `minusWord#` delta -- x1 <= y' <= y; hence y' is representable -- Invariant: x <= y -- Note that: z <= y' => z + delta won't overflow -- so we are guaranteed not to overflow if/when we recurse go_up x | isTrue# (x `gtWord#` y') = W# x `c` n | otherwise = W# x `c` go_up (x `plusWord#` delta) in W# x1 `c` go_up x2 -- Requires x2 <= x1 efdtWordDn :: Word# -> Word# -> Word# -> [Word] efdtWordDn x1 x2 y -- Be careful about underflow! | isTrue# (y `gtWord#` x2) = if isTrue# (y `gtWord#` x1) then [] else [W# x1] | otherwise = -- Common case: x1 >= x2 >= y < = 0 !y' = y `minusWord#` delta -- y <= y' <= x1; hence y' is representable -- Invariant: x >= y -- Note that: z >= y' => z + delta won't underflow -- so we are guaranteed not to underflow if/when we recurse go_dn x | isTrue# (x `ltWord#` y') = [W# x] | otherwise = W# x : go_dn (x `plusWord#` delta) in W# x1 : go_dn x2 -- Requires x2 <= x1 efdtWordDnFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r efdtWordDnFB c n x1 x2 y -- Be careful about underflow! | isTrue# (y `gtWord#` x2) = if isTrue# (y `gtWord#` x1) then n else W# x1 `c` n | otherwise = -- Common case: x1 >= x2 >= y < = 0 !y' = y `minusWord#` delta -- y <= y' <= x1; hence y' is representable -- Invariant: x >= y -- Note that: z >= y' => z + delta won't underflow -- so we are guaranteed not to underflow if/when we recurse go_dn x | isTrue# (x `ltWord#` y') = W# x `c` n | otherwise = W# x `c` go_dn (x `plusWord#` delta) in W# x1 `c` go_dn x2 ------------------------------------------------------------------------ Integer ------------------------------------------------------------------------ instance Enum Integer where succ x = x + 1 pred x = x - 1 toEnum (I# n) = smallInteger n fromEnum n = I# (integerToInt n) # INLINE enumFrom # # INLINE enumFromThen # # INLINE enumFromTo # {-# INLINE enumFromThenTo #-} enumFrom x = enumDeltaInteger x 1 enumFromThen x y = enumDeltaInteger x (y-x) enumFromTo x lim = enumDeltaToInteger x 1 lim enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim See Note [ How the rules work ] # RULES " enumDeltaInteger " [ ~1 ] forall x y. enumDeltaInteger x y = build ( \c _ - > enumDeltaIntegerFB c x y ) " efdtInteger " [ ~1 ] forall x d l. enumDeltaToInteger x d l = build ( \c n - > enumDeltaToIntegerFB c n x d l ) " efdtInteger1 " [ ~1 ] forall 1 l = build ( \c n - > enumDeltaToInteger1FB c n x l ) " enumDeltaToInteger1FB " [ 1 ] forall c n x. enumDeltaToIntegerFB c n x 1 = enumDeltaToInteger1FB c n x " enumDeltaInteger " [ 1 ] enumDeltaIntegerFB ( :) = enumDeltaInteger " enumDeltaToInteger " [ 1 ] enumDeltaToIntegerFB ( :) [ ] = enumDeltaToInteger " enumDeltaToInteger1 " [ 1 ] enumDeltaToInteger1FB ( :) [ ] = enumDeltaToInteger1 # "enumDeltaInteger" [~1] forall x y. enumDeltaInteger x y = build (\c _ -> enumDeltaIntegerFB c x y) "efdtInteger" [~1] forall x d l. enumDeltaToInteger x d l = build (\c n -> enumDeltaToIntegerFB c n x d l) "efdtInteger1" [~1] forall x l. enumDeltaToInteger x 1 l = build (\c n -> enumDeltaToInteger1FB c n x l) "enumDeltaToInteger1FB" [1] forall c n x. enumDeltaToIntegerFB c n x 1 = enumDeltaToInteger1FB c n x "enumDeltaInteger" [1] enumDeltaIntegerFB (:) = enumDeltaInteger "enumDeltaToInteger" [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger "enumDeltaToInteger1" [1] enumDeltaToInteger1FB (:) [] = enumDeltaToInteger1 #-} Note [ rules for literal 1 ] The " 1 " rules above specialise for the common case where delta = 1 , so that we can avoid the delta>=0 test in enumDeltaToIntegerFB . Then enumDeltaToInteger1FB is nice and small and can be inlined , which would allow the constructor to be inlined and good things to happen . We match on the literal " 1 " both in phase 2 ( rule " efdtInteger1 " ) and phase 1 ( rule " enumDeltaToInteger1FB " ) , just for belt and braces We do not do it for Int this way because hand - tuned code already exists , and the special case varies more from the general case , due to the issue of overflows . The "1" rules above specialise for the common case where delta = 1, so that we can avoid the delta>=0 test in enumDeltaToIntegerFB. Then enumDeltaToInteger1FB is nice and small and can be inlined, which would allow the constructor to be inlined and good things to happen. We match on the literal "1" both in phase 2 (rule "efdtInteger1") and phase 1 (rule "enumDeltaToInteger1FB"), just for belt and braces We do not do it for Int this way because hand-tuned code already exists, and the special case varies more from the general case, due to the issue of overflows. -} {-# NOINLINE [0] enumDeltaIntegerFB #-} enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b enumDeltaIntegerFB c x0 d = go x0 where go x = x `seq` (x `c` go (x+d)) # NOINLINE [ 1 ] enumDeltaInteger # enumDeltaInteger :: Integer -> Integer -> [Integer] enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d) -- strict accumulator, so head ( drop 1000000 [ 1 .. ] -- works {-# NOINLINE [0] enumDeltaToIntegerFB #-} -- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire enumDeltaToIntegerFB :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a enumDeltaToIntegerFB c n x delta lim | delta >= 0 = up_fb c n x delta lim | otherwise = dn_fb c n x delta lim {-# NOINLINE [0] enumDeltaToInteger1FB #-} -- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire enumDeltaToInteger1FB :: (Integer -> a -> a) -> a -> Integer -> Integer -> a enumDeltaToInteger1FB c n x0 lim = go (x0 :: Integer) where go x | x > lim = n | otherwise = x `c` go (x+1) # NOINLINE [ 1 ] enumDeltaToInteger # enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer] enumDeltaToInteger x delta lim | delta >= 0 = up_list x delta lim | otherwise = dn_list x delta lim # NOINLINE [ 1 ] enumDeltaToInteger1 # enumDeltaToInteger1 :: Integer -> Integer -> [Integer] Special case for Delta = 1 enumDeltaToInteger1 x0 lim = go (x0 :: Integer) where go x | x > lim = [] | otherwise = x : go (x+1) up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a up_fb c n x0 delta lim = go (x0 :: Integer) where go x | x > lim = n | otherwise = x `c` go (x+delta) dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a dn_fb c n x0 delta lim = go (x0 :: Integer) where go x | x < lim = n | otherwise = x `c` go (x+delta) up_list :: Integer -> Integer -> Integer -> [Integer] up_list x0 delta lim = go (x0 :: Integer) where go x | x > lim = [] | otherwise = x : go (x+delta) dn_list :: Integer -> Integer -> Integer -> [Integer] dn_list x0 delta lim = go (x0 :: Integer) where go x | x < lim = [] | otherwise = x : go (x+delta)
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/builtins/base/GHC.Enum.hs
haskell
# LINE 1 "GHC.Enum.hs" # # OPTIONS_HADDOCK hide # --------------------------------------------------------------------------- | License : see libraries/base/LICENSE Maintainer : Stability : internal --------------------------------------------------------------------------- Double isn't available yet | The 'Bounded' class is used to name the upper and lower limits of a totally ordered may also have upper and lower bounds. 'Bounded' may also be derived for single-constructor datatypes whose constituent types are in 'Bounded'. arithmetic sequences. whose constructors have no fields). The nullary constructors are the following should hold: a runtime error. * 'fromEnum' and 'toEnum' should give a runtime error if the result value is not representable in the result type. * 'enumFrom' and 'enumFromThen' should be defined with an implicit bound, thus: > where | Convert from an 'Int'. | Convert to an 'Int'. It is implementation-dependent what 'fromEnum' returns when applied to a value that is too large to fit in an 'Int'. Default methods for bounded enumerations ---------------------------------------------------------------------- Helper functions ---------------------------------------------------------------------- # NOINLINE toEnumError # # NOINLINE fromEnumError # ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- Bool ---------------------------------------------------------------------- Use defaults for the rest ---------------------------------------------------------------------- Ordering ---------------------------------------------------------------------- Use defaults for the rest ---------------------------------------------------------------------- Char ---------------------------------------------------------------------- Blarg: technically I guess enumFrom isn't strict! # INLINE enumFromThenTo # # INLINE [0] eftCharFB # For enumFromThenTo we give up on inlining # NOINLINE [0] efdCharFB # # NOINLINE [0] efdtCharFB # # NOINLINE [1] efdtChar # ---------------------------------------------------------------------- Int ---------------------------------------------------------------------- Blarg: technically I guess enumFrom isn't strict! # INLINE enumFromThenTo # --------------------------------------------------- most common form, so we take a lot of care In particular, we have rules for deforestation - > build . eftIntFB > eftInt -> build . eftIntFB > eftInt [x1..x2] # INLINE [0] eftIntFB # so that when eftInfFB is inlined we can inline whatever is bound to "c" --------------------------------------------------- efdInt and efdtInt deal with [a,b..] and [a,b..c]. The code is more complicated because of worries about Int overflow. # INLINE [0] efdtIntFB # Requires x2 >= x1 Be careful about overflow! Common case: x1 <= x2 <= y x1 <= y' <= y; hence y' is representable Invariant: x <= y Note that: z <= y' => z + delta won't overflow so we are guaranteed not to overflow if/when we recurse Requires x2 >= x1 Be careful about overflow! Common case: x1 <= x2 <= y x1 <= y' <= y; hence y' is representable Invariant: x <= y Note that: z <= y' => z + delta won't overflow so we are guaranteed not to overflow if/when we recurse Requires x2 <= x1 Be careful about underflow! Common case: x1 >= x2 >= y y <= y' <= x1; hence y' is representable Invariant: x >= y Note that: z >= y' => z + delta won't underflow so we are guaranteed not to underflow if/when we recurse Requires x2 <= x1 Be careful about underflow! Common case: x1 >= x2 >= y y <= y' <= x1; hence y' is representable Invariant: x >= y Note that: z >= y' => z + delta won't underflow so we are guaranteed not to underflow if/when we recurse ---------------------------------------------------------------------- ---------------------------------------------------------------------- Blarg: technically I guess enumFrom isn't strict! # INLINE enumFromThenTo # The biggest word representable as an Int --------------------------------------------------- eftWord and eftWordFB deal with [a..b], which is the most common form, so we take a lot of care In particular, we have rules for deforestation [x1..x2] # INLINE [0] eftWordFB # so that when eftInfFB is inlined we can inline whatever is bound to "c" --------------------------------------------------- efdWord and efdtWord deal with [a,b..] and [a,b..c]. The code is more complicated because of worries about Word overflow. # INLINE [0] efdtWordFB # Requires x2 >= x1 Be careful about overflow! Common case: x1 <= x2 <= y x1 <= y' <= y; hence y' is representable Invariant: x <= y Note that: z <= y' => z + delta won't overflow so we are guaranteed not to overflow if/when we recurse Requires x2 >= x1 Be careful about overflow! Common case: x1 <= x2 <= y x1 <= y' <= y; hence y' is representable Invariant: x <= y Note that: z <= y' => z + delta won't overflow so we are guaranteed not to overflow if/when we recurse Requires x2 <= x1 Be careful about underflow! Common case: x1 >= x2 >= y y <= y' <= x1; hence y' is representable Invariant: x >= y Note that: z >= y' => z + delta won't underflow so we are guaranteed not to underflow if/when we recurse Requires x2 <= x1 Be careful about underflow! Common case: x1 >= x2 >= y y <= y' <= x1; hence y' is representable Invariant: x >= y Note that: z >= y' => z + delta won't underflow so we are guaranteed not to underflow if/when we recurse ---------------------------------------------------------------------- ---------------------------------------------------------------------- # INLINE enumFromThenTo # # NOINLINE [0] enumDeltaIntegerFB # strict accumulator, so works # NOINLINE [0] enumDeltaToIntegerFB # Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire # NOINLINE [0] enumDeltaToInteger1FB # Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire
# LANGUAGE Trustworthy # # LANGUAGE CPP , NoImplicitPrelude , BangPatterns , MagicHash # Module : Copyright : ( c ) The University of Glasgow , 1992 - 2002 Portability : non - portable ( GHC extensions ) The ' ' and ' Bounded ' classes . module GHC.Enum( Bounded(..), Enum(..), boundedEnumFrom, boundedEnumFromThen, toEnumError, fromEnumError, succError, predError, Instances for Bounded and : ( ) , , Int ) where import GHC.Base hiding ( many ) import GHC.Char import GHC.Integer import GHC.Num import GHC.Show type . ' ' is not a superclass of ' Bounded ' since types that are not The ' Bounded ' class may be derived for any enumeration type ; ' ' is the first constructor listed in the @data@ declaration and ' maxBound ' is the last . class Bounded a where minBound, maxBound :: a | Class ' ' defines operations on sequentially ordered types . The @enumFrom@ ... methods are used in 's translation of Instances of ' ' may be derived for any enumeration type ( types assumed to be numbered left - to - right by ' fromEnum ' from @0@ through @n-1@. See Chapter 10 of the /Haskell Report/ for more details . For any type that is an instance of class ' Bounded ' as well as ' ' , * The calls @'succ ' ' maxBound'@ and @'pred ' ' minBound'@ should result in For example , @'toEnum ' 7 : : ' Bool'@ is an error . > enumFrom x = enumFromTo x maxBound > enumFromThen x y = enumFromThenTo x y bound > bound | fromEnum y > = fromEnum x = maxBound > | otherwise = class Enum a where | the successor of a value . For numeric types , ' succ ' adds 1 . succ :: a -> a | the predecessor of a value . For numeric types , ' pred ' subtracts 1 . pred :: a -> a toEnum :: Int -> a fromEnum :: a -> Int | Used in Haskell 's translation of @[n .. ]@. enumFrom :: a -> [a] | Used in Haskell 's translation of @[n , n' .. ]@. enumFromThen :: a -> a -> [a] | Used in Haskell 's translation of @[n .. m]@. enumFromTo :: a -> a -> [a] | Used in Haskell 's translation of @[n , n' .. m]@. enumFromThenTo :: a -> a -> a -> [a] succ = toEnum . (+ 1) . fromEnum pred = toEnum . (subtract 1) . fromEnum enumFrom x = map toEnum [fromEnum x ..] enumFromThen x y = map toEnum [fromEnum x, fromEnum y ..] enumFromTo x y = map toEnum [fromEnum x .. fromEnum y] enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y] boundedEnumFrom :: (Enum a, Bounded a) => a -> [a] boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)] boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a] boundedEnumFromThen n1 n2 | i_n2 >= i_n1 = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)] | otherwise = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)] where i_n1 = fromEnum n1 i_n2 = fromEnum n2 toEnumError :: (Show a) => String -> Int -> (a,a) -> b toEnumError inst_ty i bnds = errorWithoutStackTrace $ "Enum.toEnum{" ++ inst_ty ++ "}: tag (" ++ show i ++ ") is outside of bounds " ++ show bnds fromEnumError :: (Show a) => String -> a -> b fromEnumError inst_ty x = errorWithoutStackTrace $ "Enum.fromEnum{" ++ inst_ty ++ "}: value (" ++ show x ++ ") is outside of Int's bounds " ++ show (minBound::Int, maxBound::Int) # NOINLINE succError # succError :: String -> a succError inst_ty = errorWithoutStackTrace $ "Enum.succ{" ++ inst_ty ++ "}: tried to take `succ' of maxBound" # NOINLINE predError # predError :: String -> a predError inst_ty = errorWithoutStackTrace $ "Enum.pred{" ++ inst_ty ++ "}: tried to take `pred' of minBound" Tuples instance Bounded () where minBound = () maxBound = () instance Enum () where succ _ = errorWithoutStackTrace "Prelude.Enum.().succ: bad argument" pred _ = errorWithoutStackTrace "Prelude.Enum.().pred: bad argument" toEnum x | x == 0 = () | otherwise = errorWithoutStackTrace "Prelude.Enum.().toEnum: bad argument" fromEnum () = 0 enumFrom () = [()] enumFromThen () () = let many = ():many in many enumFromTo () () = [()] enumFromThenTo () () () = let many = ():many in many Report requires instances up to 15 instance (Bounded a, Bounded b) => Bounded (a,b) where minBound = (minBound, minBound) maxBound = (maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where minBound = (minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where minBound = (minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a,b,c,d,e) where minBound = (minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f) => Bounded (a,b,c,d,e,f) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g) => Bounded (a,b,c,d,e,f,g) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h) => Bounded (a,b,c,d,e,f,g,h) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i) => Bounded (a,b,c,d,e,f,g,h,i) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j) => Bounded (a,b,c,d,e,f,g,h,i,j) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k) => Bounded (a,b,c,d,e,f,g,h,i,j,k) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g, Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n, Bounded o) => Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance Bounded Bool where minBound = False maxBound = True instance Enum Bool where succ False = True succ True = errorWithoutStackTrace "Prelude.Enum.Bool.succ: bad argument" pred True = False pred False = errorWithoutStackTrace "Prelude.Enum.Bool.pred: bad argument" toEnum n | n == 0 = False | n == 1 = True | otherwise = errorWithoutStackTrace "Prelude.Enum.Bool.toEnum: bad argument" fromEnum False = 0 fromEnum True = 1 enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Bounded Ordering where minBound = LT maxBound = GT instance Enum Ordering where succ LT = EQ succ EQ = GT succ GT = errorWithoutStackTrace "Prelude.Enum.Ordering.succ: bad argument" pred GT = EQ pred EQ = LT pred LT = errorWithoutStackTrace "Prelude.Enum.Ordering.pred: bad argument" toEnum n | n == 0 = LT | n == 1 = EQ | n == 2 = GT toEnum _ = errorWithoutStackTrace "Prelude.Enum.Ordering.toEnum: bad argument" fromEnum LT = 0 fromEnum EQ = 1 fromEnum GT = 2 enumFrom = boundedEnumFrom enumFromThen = boundedEnumFromThen instance Bounded Char where minBound = '\0' maxBound = '\x10FFFF' instance Enum Char where succ (C# c#) | isTrue# (ord# c# /=# 0x10FFFF#) = C# (chr# (ord# c# +# 1#)) | otherwise = errorWithoutStackTrace ("Prelude.Enum.Char.succ: bad argument") pred (C# c#) | isTrue# (ord# c# /=# 0#) = C# (chr# (ord# c# -# 1#)) | otherwise = errorWithoutStackTrace ("Prelude.Enum.Char.pred: bad argument") toEnum = chr fromEnum = ord # INLINE enumFrom # enumFrom (C# x) = eftChar (ord# x) 0x10FFFF# # INLINE enumFromTo # enumFromTo (C# x) (C# y) = eftChar (ord# x) (ord# y) # INLINE enumFromThen # enumFromThen (C# x1) (C# x2) = efdChar (ord# x1) (ord# x2) enumFromThenTo (C# x1) (C# x2) (C# y) = efdtChar (ord# x1) (ord# x2) (ord# y) See Note [ How the rules work ] # RULES " eftChar " [ ~1 ] forall x y. eftChar x y = build ( \c n - > eftCharFB c n x y ) " efdChar " [ ~1 ] forall x1 x2 . efdChar x1 x2 = build ( \ c n - > efdCharFB c n x1 x2 ) " efdtChar " [ ~1 ] forall x1 x2 l. efdtChar x1 x2 l = build ( \ c n - > efdtCharFB c n x1 x2 l ) " eftCharList " [ 1 ] eftCharFB ( :) [ ] = eftChar " efdCharList " [ 1 ] efdCharFB ( :) [ ] = efdChar " efdtCharList " [ 1 ] efdtCharFB ( :) [ ] = efdtChar # "eftChar" [~1] forall x y. eftChar x y = build (\c n -> eftCharFB c n x y) "efdChar" [~1] forall x1 x2. efdChar x1 x2 = build (\ c n -> efdCharFB c n x1 x2) "efdtChar" [~1] forall x1 x2 l. efdtChar x1 x2 l = build (\ c n -> efdtCharFB c n x1 x2 l) "eftCharList" [1] eftCharFB (:) [] = eftChar "efdCharList" [1] efdCharFB (:) [] = efdChar "efdtCharList" [1] efdtCharFB (:) [] = efdtChar #-} We can do better than for because we do n't have hassles about arithmetic overflow at maxBound eftCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a eftCharFB c n x0 y = go x0 where go x | isTrue# (x ># y) = n | otherwise = C# (chr# x) `c` go (x +# 1#) # NOINLINE [ 1 ] eftChar # eftChar :: Int# -> Int# -> String eftChar x y | isTrue# (x ># y ) = [] | otherwise = C# (chr# x) : eftChar (x +# 1#) y efdCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a efdCharFB c n x1 x2 | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta 0x10FFFF# | otherwise = go_dn_char_fb c n x1 delta 0# where !delta = x2 -# x1 # NOINLINE [ 1 ] efdChar # efdChar :: Int# -> Int# -> String efdChar x1 x2 | isTrue# (delta >=# 0#) = go_up_char_list x1 delta 0x10FFFF# | otherwise = go_dn_char_list x1 delta 0# where !delta = x2 -# x1 efdtCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a efdtCharFB c n x1 x2 lim | isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta lim | otherwise = go_dn_char_fb c n x1 delta lim where !delta = x2 -# x1 efdtChar :: Int# -> Int# -> Int# -> String efdtChar x1 x2 lim | isTrue# (delta >=# 0#) = go_up_char_list x1 delta lim | otherwise = go_dn_char_list x1 delta lim where !delta = x2 -# x1 go_up_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a go_up_char_fb c n x0 delta lim = go_up x0 where go_up x | isTrue# (x ># lim) = n | otherwise = C# (chr# x) `c` go_up (x +# delta) go_dn_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a go_dn_char_fb c n x0 delta lim = go_dn x0 where go_dn x | isTrue# (x <# lim) = n | otherwise = C# (chr# x) `c` go_dn (x +# delta) go_up_char_list :: Int# -> Int# -> Int# -> String go_up_char_list x0 delta lim = go_up x0 where go_up x | isTrue# (x ># lim) = [] | otherwise = C# (chr# x) : go_up (x +# delta) go_dn_char_list :: Int# -> Int# -> Int# -> String go_dn_char_list x0 delta lim = go_dn x0 where go_dn x | isTrue# (x <# lim) = [] | otherwise = C# (chr# x) : go_dn (x +# delta) Be careful about these instances . ( a ) remember that you have to count down as well as up e.g. [ 13,12 .. 0 ] ( b ) be careful of Int overflow ( c ) remember that is bounded , so [ 1 .. ] terminates at maxInt Be careful about these instances. (a) remember that you have to count down as well as up e.g. [13,12..0] (b) be careful of Int overflow (c) remember that Int is bounded, so [1..] terminates at maxInt -} instance Bounded Int where minBound = minInt maxBound = maxInt instance Enum Int where succ x | x == maxBound = errorWithoutStackTrace "Prelude.Enum.succ{Int}: tried to take `succ' of maxBound" | otherwise = x + 1 pred x | x == minBound = errorWithoutStackTrace "Prelude.Enum.pred{Int}: tried to take `pred' of minBound" | otherwise = x - 1 toEnum x = x fromEnum x = x # INLINE enumFrom # enumFrom (I# x) = eftInt x maxInt# where !(I# maxInt#) = maxInt # INLINE enumFromTo # enumFromTo (I# x) (I# y) = eftInt x y # INLINE enumFromThen # enumFromThen (I# x1) (I# x2) = efdInt x1 x2 enumFromThenTo (I# x1) (I# x2) (I# y) = efdtInt x1 x2 y eftInt and eftIntFB deal with [ a .. b ] , which is the # RULES " eftInt " [ ~1 ] forall x y. eftInt x y = build ( \ c n - > eftIntFB c n x y ) " eftIntList " [ 1 ] eftIntFB ( :) [ ] = eftInt # "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y) "eftIntList" [1] eftIntFB (:) [] = eftInt #-} Note [ How the rules work ] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Phase 0 : optionally inline eftInt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Phase 0: optionally inline eftInt -} # NOINLINE [ 1 ] eftInt # eftInt :: Int# -> Int# -> [Int] eftInt x0 y | isTrue# (x0 ># y) = [] | otherwise = go x0 where go x = I# x : if isTrue# (x ==# y) then [] else go (x +# 1#) eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r eftIntFB c n x0 y | isTrue# (x0 ># y) = n | otherwise = go x0 where go x = I# x `c` if isTrue# (x ==# y) then n else go (x +# 1#) Watch out for y = maxBound ; hence = = , not > Be very careful not to have more than one " c " See Note [ How the rules work ] # RULES " efdtInt " [ ~1 ] forall x1 x2 y. efdtInt x1 x2 y = build ( \ c n - > efdtIntFB c n x1 x2 y ) " efdtIntUpList " [ 1 ] efdtIntFB ( :) [ ] = efdtInt # "efdtInt" [~1] forall x1 x2 y. efdtInt x1 x2 y = build (\ c n -> efdtIntFB c n x1 x2 y) "efdtIntUpList" [1] efdtIntFB (:) [] = efdtInt #-} efdInt :: Int# -> Int# -> [Int] [ x1,x2 .. maxInt ] efdInt x1 x2 | isTrue# (x2 >=# x1) = case maxInt of I# y -> efdtIntUp x1 x2 y | otherwise = case minInt of I# y -> efdtIntDn x1 x2 y # NOINLINE [ 1 ] efdtInt # efdtInt :: Int# -> Int# -> Int# -> [Int] [ .. y ] efdtInt x1 x2 y | isTrue# (x2 >=# x1) = efdtIntUp x1 x2 y | otherwise = efdtIntDn x1 x2 y efdtIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r efdtIntFB c n x1 x2 y | isTrue# (x2 >=# x1) = efdtIntUpFB c n x1 x2 y | otherwise = efdtIntDnFB c n x1 x2 y efdtIntUp :: Int# -> Int# -> Int# -> [Int] | isTrue# (y <# x2) = if isTrue# (y <# x1) then [] else [I# x1] > = 0 go_up x | isTrue# (x ># y') = [I# x] | otherwise = I# x : go_up (x +# delta) in I# x1 : go_up x2 efdtIntUpFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r | isTrue# (y <# x2) = if isTrue# (y <# x1) then n else I# x1 `c` n > = 0 go_up x | isTrue# (x ># y') = I# x `c` n | otherwise = I# x `c` go_up (x +# delta) in I# x1 `c` go_up x2 efdtIntDn :: Int# -> Int# -> Int# -> [Int] | isTrue# (y ># x2) = if isTrue# (y ># x1) then [] else [I# x1] < = 0 go_dn x | isTrue# (x <# y') = [I# x] | otherwise = I# x : go_dn (x +# delta) in I# x1 : go_dn x2 efdtIntDnFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r | isTrue# (y ># x2) = if isTrue# (y ># x1) then n else I# x1 `c` n < = 0 go_dn x | isTrue# (x <# y') = I# x `c` n | otherwise = I# x `c` go_dn (x +# delta) in I# x1 `c` go_dn x2 Word instance Bounded Word where minBound = 0 use unboxed literals for maxBound , because GHC does n't optimise ( fromInteger 0xffffffff : : Word ) . maxBound = W# (int2Word# 0xFFFFFFFFFFFFFFFF#) instance Enum Word where succ x | x /= maxBound = x + 1 | otherwise = succError "Word" pred x | x /= minBound = x - 1 | otherwise = predError "Word" toEnum i@(I# i#) | i >= 0 = W# (int2Word# i#) | otherwise = toEnumError "Word" i (minBound::Word, maxBound::Word) fromEnum x@(W# x#) | x <= maxIntWord = I# (word2Int# x#) | otherwise = fromEnumError "Word" x # INLINE enumFrom # enumFrom (W# x#) = eftWord x# maxWord# where !(W# maxWord#) = maxBound # INLINE enumFromTo # enumFromTo (W# x) (W# y) = eftWord x y # INLINE enumFromThen # enumFromThen (W# x1) (W# x2) = efdWord x1 x2 enumFromThenTo (W# x1) (W# x2) (W# y) = efdtWord x1 x2 y maxIntWord :: Word maxIntWord = W# (case maxInt of I# i -> int2Word# i) # RULES " eftWord " [ ~1 ] forall x y. eftWord x y = build ( \ c n - > eftWordFB c n x y ) " eftWordList " [ 1 ] eftWordFB ( :) [ ] = eftWord # "eftWord" [~1] forall x y. eftWord x y = build (\ c n -> eftWordFB c n x y) "eftWordList" [1] eftWordFB (:) [] = eftWord #-} The rules for Word work much the same way that they do for Int . See Note [ How the rules work ] . # NOINLINE [ 1 ] eftWord # eftWord :: Word# -> Word# -> [Word] eftWord x0 y | isTrue# (x0 `gtWord#` y) = [] | otherwise = go x0 where go x = W# x : if isTrue# (x `eqWord#` y) then [] else go (x `plusWord#` 1##) eftWordFB :: (Word -> r -> r) -> r -> Word# -> Word# -> r eftWordFB c n x0 y | isTrue# (x0 `gtWord#` y) = n | otherwise = go x0 where go x = W# x `c` if isTrue# (x `eqWord#` y) then n else go (x `plusWord#` 1##) Watch out for y = maxBound ; hence = = , not > Be very careful not to have more than one " c " See Note [ How the rules work ] # RULES " efdtWord " [ ~1 ] forall x1 x2 y. efdtWord x1 x2 y = build ( \ c n - > efdtWordFB c n x1 x2 y ) " efdtWordUpList " [ 1 ] efdtWordFB ( :) [ ] = efdtWord # "efdtWord" [~1] forall x1 x2 y. efdtWord x1 x2 y = build (\ c n -> efdtWordFB c n x1 x2 y) "efdtWordUpList" [1] efdtWordFB (:) [] = efdtWord #-} efdWord :: Word# -> Word# -> [Word] [ .. maxWord ] efdWord x1 x2 | isTrue# (x2 `geWord#` x1) = case maxBound of W# y -> efdtWordUp x1 x2 y | otherwise = case minBound of W# y -> efdtWordDn x1 x2 y # NOINLINE [ 1 ] efdtWord # efdtWord :: Word# -> Word# -> Word# -> [Word] [ .. y ] efdtWord x1 x2 y | isTrue# (x2 `geWord#` x1) = efdtWordUp x1 x2 y | otherwise = efdtWordDn x1 x2 y efdtWordFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r efdtWordFB c n x1 x2 y | isTrue# (x2 `geWord#` x1) = efdtWordUpFB c n x1 x2 y | otherwise = efdtWordDnFB c n x1 x2 y efdtWordUp :: Word# -> Word# -> Word# -> [Word] | isTrue# (y `ltWord#` x2) = if isTrue# (y `ltWord#` x1) then [] else [W# x1] > = 0 go_up x | isTrue# (x `gtWord#` y') = [W# x] | otherwise = W# x : go_up (x `plusWord#` delta) in W# x1 : go_up x2 efdtWordUpFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r | isTrue# (y `ltWord#` x2) = if isTrue# (y `ltWord#` x1) then n else W# x1 `c` n > = 0 go_up x | isTrue# (x `gtWord#` y') = W# x `c` n | otherwise = W# x `c` go_up (x `plusWord#` delta) in W# x1 `c` go_up x2 efdtWordDn :: Word# -> Word# -> Word# -> [Word] | isTrue# (y `gtWord#` x2) = if isTrue# (y `gtWord#` x1) then [] else [W# x1] < = 0 go_dn x | isTrue# (x `ltWord#` y') = [W# x] | otherwise = W# x : go_dn (x `plusWord#` delta) in W# x1 : go_dn x2 efdtWordDnFB :: (Word -> r -> r) -> r -> Word# -> Word# -> Word# -> r | isTrue# (y `gtWord#` x2) = if isTrue# (y `gtWord#` x1) then n else W# x1 `c` n < = 0 go_dn x | isTrue# (x `ltWord#` y') = W# x `c` n | otherwise = W# x `c` go_dn (x `plusWord#` delta) in W# x1 `c` go_dn x2 Integer instance Enum Integer where succ x = x + 1 pred x = x - 1 toEnum (I# n) = smallInteger n fromEnum n = I# (integerToInt n) # INLINE enumFrom # # INLINE enumFromThen # # INLINE enumFromTo # enumFrom x = enumDeltaInteger x 1 enumFromThen x y = enumDeltaInteger x (y-x) enumFromTo x lim = enumDeltaToInteger x 1 lim enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim See Note [ How the rules work ] # RULES " enumDeltaInteger " [ ~1 ] forall x y. enumDeltaInteger x y = build ( \c _ - > enumDeltaIntegerFB c x y ) " efdtInteger " [ ~1 ] forall x d l. enumDeltaToInteger x d l = build ( \c n - > enumDeltaToIntegerFB c n x d l ) " efdtInteger1 " [ ~1 ] forall 1 l = build ( \c n - > enumDeltaToInteger1FB c n x l ) " enumDeltaToInteger1FB " [ 1 ] forall c n x. enumDeltaToIntegerFB c n x 1 = enumDeltaToInteger1FB c n x " enumDeltaInteger " [ 1 ] enumDeltaIntegerFB ( :) = enumDeltaInteger " enumDeltaToInteger " [ 1 ] enumDeltaToIntegerFB ( :) [ ] = enumDeltaToInteger " enumDeltaToInteger1 " [ 1 ] enumDeltaToInteger1FB ( :) [ ] = enumDeltaToInteger1 # "enumDeltaInteger" [~1] forall x y. enumDeltaInteger x y = build (\c _ -> enumDeltaIntegerFB c x y) "efdtInteger" [~1] forall x d l. enumDeltaToInteger x d l = build (\c n -> enumDeltaToIntegerFB c n x d l) "efdtInteger1" [~1] forall x l. enumDeltaToInteger x 1 l = build (\c n -> enumDeltaToInteger1FB c n x l) "enumDeltaToInteger1FB" [1] forall c n x. enumDeltaToIntegerFB c n x 1 = enumDeltaToInteger1FB c n x "enumDeltaInteger" [1] enumDeltaIntegerFB (:) = enumDeltaInteger "enumDeltaToInteger" [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger "enumDeltaToInteger1" [1] enumDeltaToInteger1FB (:) [] = enumDeltaToInteger1 #-} Note [ rules for literal 1 ] The " 1 " rules above specialise for the common case where delta = 1 , so that we can avoid the delta>=0 test in enumDeltaToIntegerFB . Then enumDeltaToInteger1FB is nice and small and can be inlined , which would allow the constructor to be inlined and good things to happen . We match on the literal " 1 " both in phase 2 ( rule " efdtInteger1 " ) and phase 1 ( rule " enumDeltaToInteger1FB " ) , just for belt and braces We do not do it for Int this way because hand - tuned code already exists , and the special case varies more from the general case , due to the issue of overflows . The "1" rules above specialise for the common case where delta = 1, so that we can avoid the delta>=0 test in enumDeltaToIntegerFB. Then enumDeltaToInteger1FB is nice and small and can be inlined, which would allow the constructor to be inlined and good things to happen. We match on the literal "1" both in phase 2 (rule "efdtInteger1") and phase 1 (rule "enumDeltaToInteger1FB"), just for belt and braces We do not do it for Int this way because hand-tuned code already exists, and the special case varies more from the general case, due to the issue of overflows. -} enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b enumDeltaIntegerFB c x0 d = go x0 where go x = x `seq` (x `c` go (x+d)) # NOINLINE [ 1 ] enumDeltaInteger # enumDeltaInteger :: Integer -> Integer -> [Integer] enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d) head ( drop 1000000 [ 1 .. ] enumDeltaToIntegerFB :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a enumDeltaToIntegerFB c n x delta lim | delta >= 0 = up_fb c n x delta lim | otherwise = dn_fb c n x delta lim enumDeltaToInteger1FB :: (Integer -> a -> a) -> a -> Integer -> Integer -> a enumDeltaToInteger1FB c n x0 lim = go (x0 :: Integer) where go x | x > lim = n | otherwise = x `c` go (x+1) # NOINLINE [ 1 ] enumDeltaToInteger # enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer] enumDeltaToInteger x delta lim | delta >= 0 = up_list x delta lim | otherwise = dn_list x delta lim # NOINLINE [ 1 ] enumDeltaToInteger1 # enumDeltaToInteger1 :: Integer -> Integer -> [Integer] Special case for Delta = 1 enumDeltaToInteger1 x0 lim = go (x0 :: Integer) where go x | x > lim = [] | otherwise = x : go (x+1) up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a up_fb c n x0 delta lim = go (x0 :: Integer) where go x | x > lim = n | otherwise = x `c` go (x+delta) dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a dn_fb c n x0 delta lim = go (x0 :: Integer) where go x | x < lim = n | otherwise = x `c` go (x+delta) up_list :: Integer -> Integer -> Integer -> [Integer] up_list x0 delta lim = go (x0 :: Integer) where go x | x > lim = [] | otherwise = x : go (x+delta) dn_list :: Integer -> Integer -> Integer -> [Integer] dn_list x0 delta lim = go (x0 :: Integer) where go x | x < lim = [] | otherwise = x : go (x+delta)
9556bf3c490eaa6cbbe8cf5276ed988ce2cd629aeab6b3d88ea20e3c9a17b358
97jaz/gregor
generics.rkt
#lang racket/base (require racket/dict racket/generic racket/match racket/math "core/structs.rkt" "core/math.rkt" "core/ymd.rkt" "core/hmsn.rkt" "difference.rkt" "date.rkt" "exn.rkt" "time.rkt" "datetime.rkt" "moment.rkt" "period.rkt" "offset-resolvers.rkt") (provide (all-defined-out)) (define (resolve/orig resolve orig) (λ (g/o dt tzid m) (resolve g/o dt tzid (or m (and (moment? orig) orig))))) (define-generics date-provider (->date date-provider) (->ymd date-provider) (->jdn date-provider) (->year date-provider) (->quarter date-provider) (->month date-provider) (->day date-provider) (->wday date-provider) (->yday date-provider) (->iso-week date-provider) (->iso-wyear date-provider) (->iso-wday date-provider) (sunday? date-provider) (monday? date-provider) (tuesday? date-provider) (wednesday? date-provider) (thursday? date-provider) (friday? date-provider) (saturday? date-provider) (with-ymd date-provider ymd #:resolve-offset [resolve-offset]) (with-jdn date-provider jdn #:resolve-offset [resolve-offset]) (at-time date-provider t #:resolve-offset [resolve-offset]) (at-midnight date-provider #:resolve-offset [resolve-offset]) (at-noon date-provider #:resolve-offset [resolve-offset]) #:defaults ([date? (define ->date (λ (x) x)) (define with-ymd (λ (d ymd #:resolve-offset [_ resolve-offset/raise]) (ymd->date ymd))) (define with-jdn (λ (d jdn #:resolve-offset [_ resolve-offset/raise]) (jdn->date jdn))) (define at-time (λ (d t #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime d (->time t))))] [datetime? (define ->date datetime->date) (define with-ymd (λ (dt ymd #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (ymd->date ymd) (datetime->time dt)))) (define with-jdn (λ (dt jdn #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (jdn->date jdn) (datetime->time dt)))) (define at-time (λ (dt t #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (datetime->date dt) (->time t))))] [moment? (define/generic /ymd with-ymd) (define/generic /jdn with-jdn) (define/generic @time at-time) (define ->date (compose1 datetime->date moment->datetime/local)) (define with-ymd (λ (m ymd #:resolve-offset [r resolve-offset/raise]) (define dt (/ymd (moment->datetime/local m) ymd)) (datetime+tz->moment dt (moment->timezone m) r))) (define with-jdn (λ (m jdn #:resolve-offset [r resolve-offset/raise]) (define dt (/jdn (moment->datetime/local m) jdn)) (datetime+tz->moment dt (moment->timezone m) r))) (define at-time (λ (m t #:resolve-offset [r resolve-offset/raise]) (define dt (@time (moment->datetime/local m) (->time t))) (datetime+tz->moment dt (moment->timezone m) r)))]) #:fallbacks [(define/generic as-date ->date) (define ->ymd (compose1 date->ymd as-date)) (define ->jdn (compose1 date->jdn as-date)) (define ->year (compose1 YMD-y ->ymd)) (define ->quarter (compose1 ymd->quarter ->ymd)) (define ->month (compose1 YMD-m ->ymd)) (define ->day (compose1 YMD-d ->ymd)) (define ->wday (compose1 jdn->wday ->jdn)) (define ->yday (compose1 ymd->yday ->ymd)) (define ->iso-week (compose1 date->iso-week as-date)) (define ->iso-wyear (compose1 date->iso-wyear as-date)) (define ->iso-wday (compose1 jdn->iso-wday ->jdn)) (define (dow? n) (λ (d) (= n (->wday d)))) (define sunday? (dow? 0)) (define monday? (dow? 1)) (define tuesday? (dow? 2)) (define wednesday? (dow? 3)) (define thursday? (dow? 4)) (define friday? (dow? 5)) (define saturday? (dow? 6)) (define/generic @time at-time) (define at-midnight (λ (d #:resolve-offset [_ resolve-offset/raise]) (@time d MIDNIGHT #:resolve-offset _))) (define at-noon (λ (d #:resolve-offset [_ resolve-offset/raise]) (@time d NOON #:resolve-offset _)))]) (define-generics date-arithmetic-provider (+years date-arithmetic-provider n #:resolve-offset [resolve-offset]) (+months date-arithmetic-provider n #:resolve-offset [resolve-offset]) (+weeks date-arithmetic-provider n #:resolve-offset [resolve-offset]) (+days date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-years date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-months date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-weeks date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-days date-arithmetic-provider n #:resolve-offset [resolve-offset]) (+date-period date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-date-period date-arithmetic-provider n #:resolve-offset [resolve-offset]) #:defaults ([date-provider? (define (d+ from as fn) (λ (d n #:resolve-offset [resolve resolve-offset/retain]) (from d (fn (as d) n) #:resolve-offset (resolve/orig resolve d)))) (define (ymd+ fn) (d+ with-ymd ->ymd fn)) (define (jdn+ fn) (d+ with-jdn ->jdn fn)) (define +years (ymd+ ymd-add-years)) (define +months (ymd+ ymd-add-months)) (define +days (jdn+ +)) (define (+date-period d p #:resolve-offset [resolve resolve-offset/retain]) (match-define (period [years ys] [months ms] [weeks ws] [days ds]) p) (+days (+months d (+ (* 12 ys) ms) #:resolve-offset resolve) (+ ds (* 7 ws)) #:resolve-offset resolve))] [period? (define (mk ctor sgn) (λ (p n #:resolve-offset [resolve resolve-offset/retain]) (period p (ctor (sgn n))))) (define +years (mk years +)) (define +months (mk months +)) (define +weeks (mk weeks +)) (define -weeks (mk weeks -)) (define +days (mk days +)) (define (+date-period p0 p1 #:resolve-offset [resolve resolve-offset/retain]) (period p0 p1))]) #:fallbacks [(define/generic +y +years) (define/generic +m +months) (define/generic +d +days) (define/generic +p +date-period) (define (sub fn [neg -]) (λ (d n #:resolve-offset [resolve resolve-offset/retain]) (fn d (neg n) #:resolve-offset resolve))) (define (+weeks d n #:resolve-offset [resolve resolve-offset/retain]) (+d d (* 7 n) #:resolve-offset resolve)) (define -years (sub +y)) (define -months (sub +m)) (define -weeks (sub +weeks)) (define -days (sub +d)) (define -date-period (sub +p negate-period))]) (define-generics time-provider (->time time-provider) (->hmsn time-provider) (->hours time-provider) (->minutes time-provider) (->seconds time-provider [fractional?]) (->milliseconds time-provider) (->microseconds time-provider) (->nanoseconds time-provider) (on-date time-provider d #:resolve-offset [resolve-offset]) #:defaults ([time? (define ->time (λ (x) x)) (define (on-date t d #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (->date d) t))] [datetime? (define ->time datetime->time) (define on-date (λ (dt d #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (->date d) (->time dt))))] [moment? (define/generic on-date/g on-date) (define ->time (compose1 datetime->time moment->datetime/local)) (define on-date (λ (m d #:resolve-offset [r resolve-offset/raise]) (define dt (on-date/g (moment->datetime/local m) d)) (datetime+tz->moment dt (moment->timezone m) r)))]) #:fallbacks [(define/generic as-time ->time) (define ->hmsn (compose1 time->hmsn as-time)) (define ->hours (compose1 HMSN-h ->hmsn)) (define ->minutes (compose1 HMSN-m ->hmsn)) (define ->seconds (λ (t [fractional? #f]) (match-define (HMSN _ _ s n) (->hmsn t)) (+ s (if fractional? (/ n NS/SECOND) 0)))) (define ->nanoseconds (compose1 HMSN-n ->hmsn)) (define ->milliseconds (λ (t) (exact-floor (/ (->nanoseconds t) 1000000)))) (define ->microseconds (λ (t) (exact-floor (/ (->nanoseconds t) 1000))))]) (define-generics time-arithmetic-provider (+hours time-arithmetic-provider n) (+minutes time-arithmetic-provider n) (+seconds time-arithmetic-provider n) (+milliseconds time-arithmetic-provider n) (+microseconds time-arithmetic-provider n) (+nanoseconds time-arithmetic-provider n) (-hours time-arithmetic-provider n) (-minutes time-arithmetic-provider n) (-seconds time-arithmetic-provider n) (-milliseconds time-arithmetic-provider n) (-microseconds time-arithmetic-provider n) (-nanoseconds time-arithmetic-provider n) (+time-period time-arithmetic-provider p) (-time-period time-arithmetic-provider p) #:defaults ([time? (define (+nanoseconds t n) (day-ns->time (mod (+ (time->ns t) n) NS/DAY)))] [datetime? (define +nanoseconds datetime-add-nanoseconds)] [moment? (define +nanoseconds moment-add-nanoseconds)] [period? (define-syntax-rule (mk ctor +t -t) (begin (define (+t p n) (period p (ctor n))) (define (-t p n) (period p (ctor (- n)))))) (mk hours +hours -hours) (mk minutes +minutes -minutes) (mk seconds +seconds -seconds) (mk milliseconds +milliseconds -milliseconds) (mk microseconds +microseconds -microseconds) (mk nanoseconds +nanoseconds -nanoseconds) (define (+time-period p0 p1) (period p0 p1))]) #:fallbacks [(define/generic ns+ +nanoseconds) (define (-nanoseconds t n) (ns+ t (- n))) (define (t+/- NS/UNIT i) (λ (t n) (ns+ t (* n NS/UNIT i)))) (define (t+ NS/UNIT) (t+/- NS/UNIT 1)) (define (t- NS/UNIT) (t+/- NS/UNIT -1)) (define +hours (t+ NS/HOUR)) (define +minutes (t+ NS/MINUTE)) (define +seconds (t+ NS/SECOND)) (define +milliseconds (t+ NS/MILLI)) (define +microseconds (t+ NS/MICRO)) (define -hours (t- NS/HOUR)) (define -minutes (t- NS/MINUTE)) (define -seconds (t- NS/SECOND)) (define -milliseconds (t- NS/MILLI)) (define -microseconds (t- NS/MICRO)) (define/generic +p +time-period) (define (+time-period t p) (match-define (period [hours hrs] [minutes min] [seconds sec] [milliseconds ms] [microseconds us] [nanoseconds ns]) p) (ns+ t (+ (* NS/HOUR hrs) (* NS/MINUTE min) (* NS/SECOND sec) (* NS/MILLI ms) (* NS/MICRO us) ns))) (define (-time-period t p) (+p t (negate-period p)))]) (define-generics datetime-provider (->datetime/local datetime-provider) (->datetime/utc datetime-provider) (->datetime/similar datetime-provider other) (->posix datetime-provider) (->jd datetime-provider) (years-between datetime-provider other) (months-between datetime-provider other) (weeks-between datetime-provider other) (days-between datetime-provider other) (hours-between datetime-provider other) (minutes-between datetime-provider other) (seconds-between datetime-provider other) (milliseconds-between datetime-provider other) (microseconds-between datetime-provider other) (nanoseconds-between datetime-provider other) (with-timezone datetime-provider tz #:resolve-offset [resolve-offset]) #:defaults ([date? (define ->datetime/local at-midnight) (define ->datetime/utc at-midnight)] [datetime? (define ->datetime/local (λ (x) x)) (define ->datetime/utc ->datetime/local)] [moment? (define/generic ->dt/l ->datetime/local) (define ->datetime/local moment->datetime/local) (define ->datetime/utc (compose1 moment->datetime/local moment-in-utc)) (define (->datetime/similar self other) (->dt/l (cond [(moment-provider? other) (timezone-adjust other (->timezone self))] [else other])))]) #:fallbacks [(define/generic ->dt ->datetime/utc) (define/generic ->dt/l ->datetime/local) (define/generic ->dt/s ->datetime/similar) (define (->datetime/similar _ dt) (->dt/l dt)) (define (->jd dt) (datetime->jd (->dt dt))) (define EPOCH (moment 1970 #:tz UTC)) (define (->posix dt) (/ (nanoseconds-between EPOCH dt) NS/SECOND)) (define (lift/date fn) (λ (d1 d2) (fn (->dt/l d1) (->dt/s d1 d2)))) (define (lift/time fn) (λ (d1 d2) (fn (->dt d1) (->dt d2)))) (define (quot fn n) (λ (d1 d2) (quotient (fn d1 d2) n))) (define months-between (lift/date datetime-months-between)) (define years-between (quot months-between 12)) (define days-between (lift/date datetime-days-between)) (define weeks-between (quot days-between 7)) (define nanoseconds-between (lift/time datetime-nanoseconds-between)) (define hours-between (quot nanoseconds-between NS/HOUR)) (define minutes-between (quot nanoseconds-between NS/MINUTE)) (define seconds-between (quot nanoseconds-between NS/SECOND)) (define milliseconds-between (quot nanoseconds-between NS/MILLI)) (define microseconds-between (quot nanoseconds-between NS/MICRO)) (define (with-timezone t tz #:resolve-offset [r resolve-offset/raise]) (datetime+tz->moment (->dt/l t) tz r))]) (define-generics datetime-arithmetic-provider (+period datetime-arithmetic-provider p #:resolve-offset [resolve-offset]) (-period datetime-arithmetic-provider p #:resolve-offset [resolve-offset]) #:defaults [(datetime?) (moment?) (period?)] #:fallbacks [(define (+period t p #:resolve-offset [r resolve-offset/retain]) (define t0 (+date-period t (period->date-period p) #:resolve-offset (resolve/orig r t))) (+time-period t0 (period->time-period p))) (define (-period t p #:resolve-offset [r resolve-offset/retain]) (+period t (negate-period p) #:resolve-offset r))]) (define-generics moment-provider (->moment moment-provider) (->utc-offset moment-provider) (->timezone moment-provider) (->tzid moment-provider) (adjust-timezone moment-provider tz) #:defaults ([moment? (define ->moment (λ (x) x)) (define ->utc-offset moment->utc-offset) (define ->timezone moment->timezone) (define ->tzid moment->tzid) (define adjust-timezone timezone-adjust)])) (define (tzid-provider? x) (and (moment-provider? x) (->tzid x)))
null
https://raw.githubusercontent.com/97jaz/gregor/91d71c6082fec4197aaf9ade57aceb148116c11c/gregor-lib/gregor/private/generics.rkt
racket
#lang racket/base (require racket/dict racket/generic racket/match racket/math "core/structs.rkt" "core/math.rkt" "core/ymd.rkt" "core/hmsn.rkt" "difference.rkt" "date.rkt" "exn.rkt" "time.rkt" "datetime.rkt" "moment.rkt" "period.rkt" "offset-resolvers.rkt") (provide (all-defined-out)) (define (resolve/orig resolve orig) (λ (g/o dt tzid m) (resolve g/o dt tzid (or m (and (moment? orig) orig))))) (define-generics date-provider (->date date-provider) (->ymd date-provider) (->jdn date-provider) (->year date-provider) (->quarter date-provider) (->month date-provider) (->day date-provider) (->wday date-provider) (->yday date-provider) (->iso-week date-provider) (->iso-wyear date-provider) (->iso-wday date-provider) (sunday? date-provider) (monday? date-provider) (tuesday? date-provider) (wednesday? date-provider) (thursday? date-provider) (friday? date-provider) (saturday? date-provider) (with-ymd date-provider ymd #:resolve-offset [resolve-offset]) (with-jdn date-provider jdn #:resolve-offset [resolve-offset]) (at-time date-provider t #:resolve-offset [resolve-offset]) (at-midnight date-provider #:resolve-offset [resolve-offset]) (at-noon date-provider #:resolve-offset [resolve-offset]) #:defaults ([date? (define ->date (λ (x) x)) (define with-ymd (λ (d ymd #:resolve-offset [_ resolve-offset/raise]) (ymd->date ymd))) (define with-jdn (λ (d jdn #:resolve-offset [_ resolve-offset/raise]) (jdn->date jdn))) (define at-time (λ (d t #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime d (->time t))))] [datetime? (define ->date datetime->date) (define with-ymd (λ (dt ymd #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (ymd->date ymd) (datetime->time dt)))) (define with-jdn (λ (dt jdn #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (jdn->date jdn) (datetime->time dt)))) (define at-time (λ (dt t #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (datetime->date dt) (->time t))))] [moment? (define/generic /ymd with-ymd) (define/generic /jdn with-jdn) (define/generic @time at-time) (define ->date (compose1 datetime->date moment->datetime/local)) (define with-ymd (λ (m ymd #:resolve-offset [r resolve-offset/raise]) (define dt (/ymd (moment->datetime/local m) ymd)) (datetime+tz->moment dt (moment->timezone m) r))) (define with-jdn (λ (m jdn #:resolve-offset [r resolve-offset/raise]) (define dt (/jdn (moment->datetime/local m) jdn)) (datetime+tz->moment dt (moment->timezone m) r))) (define at-time (λ (m t #:resolve-offset [r resolve-offset/raise]) (define dt (@time (moment->datetime/local m) (->time t))) (datetime+tz->moment dt (moment->timezone m) r)))]) #:fallbacks [(define/generic as-date ->date) (define ->ymd (compose1 date->ymd as-date)) (define ->jdn (compose1 date->jdn as-date)) (define ->year (compose1 YMD-y ->ymd)) (define ->quarter (compose1 ymd->quarter ->ymd)) (define ->month (compose1 YMD-m ->ymd)) (define ->day (compose1 YMD-d ->ymd)) (define ->wday (compose1 jdn->wday ->jdn)) (define ->yday (compose1 ymd->yday ->ymd)) (define ->iso-week (compose1 date->iso-week as-date)) (define ->iso-wyear (compose1 date->iso-wyear as-date)) (define ->iso-wday (compose1 jdn->iso-wday ->jdn)) (define (dow? n) (λ (d) (= n (->wday d)))) (define sunday? (dow? 0)) (define monday? (dow? 1)) (define tuesday? (dow? 2)) (define wednesday? (dow? 3)) (define thursday? (dow? 4)) (define friday? (dow? 5)) (define saturday? (dow? 6)) (define/generic @time at-time) (define at-midnight (λ (d #:resolve-offset [_ resolve-offset/raise]) (@time d MIDNIGHT #:resolve-offset _))) (define at-noon (λ (d #:resolve-offset [_ resolve-offset/raise]) (@time d NOON #:resolve-offset _)))]) (define-generics date-arithmetic-provider (+years date-arithmetic-provider n #:resolve-offset [resolve-offset]) (+months date-arithmetic-provider n #:resolve-offset [resolve-offset]) (+weeks date-arithmetic-provider n #:resolve-offset [resolve-offset]) (+days date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-years date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-months date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-weeks date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-days date-arithmetic-provider n #:resolve-offset [resolve-offset]) (+date-period date-arithmetic-provider n #:resolve-offset [resolve-offset]) (-date-period date-arithmetic-provider n #:resolve-offset [resolve-offset]) #:defaults ([date-provider? (define (d+ from as fn) (λ (d n #:resolve-offset [resolve resolve-offset/retain]) (from d (fn (as d) n) #:resolve-offset (resolve/orig resolve d)))) (define (ymd+ fn) (d+ with-ymd ->ymd fn)) (define (jdn+ fn) (d+ with-jdn ->jdn fn)) (define +years (ymd+ ymd-add-years)) (define +months (ymd+ ymd-add-months)) (define +days (jdn+ +)) (define (+date-period d p #:resolve-offset [resolve resolve-offset/retain]) (match-define (period [years ys] [months ms] [weeks ws] [days ds]) p) (+days (+months d (+ (* 12 ys) ms) #:resolve-offset resolve) (+ ds (* 7 ws)) #:resolve-offset resolve))] [period? (define (mk ctor sgn) (λ (p n #:resolve-offset [resolve resolve-offset/retain]) (period p (ctor (sgn n))))) (define +years (mk years +)) (define +months (mk months +)) (define +weeks (mk weeks +)) (define -weeks (mk weeks -)) (define +days (mk days +)) (define (+date-period p0 p1 #:resolve-offset [resolve resolve-offset/retain]) (period p0 p1))]) #:fallbacks [(define/generic +y +years) (define/generic +m +months) (define/generic +d +days) (define/generic +p +date-period) (define (sub fn [neg -]) (λ (d n #:resolve-offset [resolve resolve-offset/retain]) (fn d (neg n) #:resolve-offset resolve))) (define (+weeks d n #:resolve-offset [resolve resolve-offset/retain]) (+d d (* 7 n) #:resolve-offset resolve)) (define -years (sub +y)) (define -months (sub +m)) (define -weeks (sub +weeks)) (define -days (sub +d)) (define -date-period (sub +p negate-period))]) (define-generics time-provider (->time time-provider) (->hmsn time-provider) (->hours time-provider) (->minutes time-provider) (->seconds time-provider [fractional?]) (->milliseconds time-provider) (->microseconds time-provider) (->nanoseconds time-provider) (on-date time-provider d #:resolve-offset [resolve-offset]) #:defaults ([time? (define ->time (λ (x) x)) (define (on-date t d #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (->date d) t))] [datetime? (define ->time datetime->time) (define on-date (λ (dt d #:resolve-offset [_ resolve-offset/raise]) (date+time->datetime (->date d) (->time dt))))] [moment? (define/generic on-date/g on-date) (define ->time (compose1 datetime->time moment->datetime/local)) (define on-date (λ (m d #:resolve-offset [r resolve-offset/raise]) (define dt (on-date/g (moment->datetime/local m) d)) (datetime+tz->moment dt (moment->timezone m) r)))]) #:fallbacks [(define/generic as-time ->time) (define ->hmsn (compose1 time->hmsn as-time)) (define ->hours (compose1 HMSN-h ->hmsn)) (define ->minutes (compose1 HMSN-m ->hmsn)) (define ->seconds (λ (t [fractional? #f]) (match-define (HMSN _ _ s n) (->hmsn t)) (+ s (if fractional? (/ n NS/SECOND) 0)))) (define ->nanoseconds (compose1 HMSN-n ->hmsn)) (define ->milliseconds (λ (t) (exact-floor (/ (->nanoseconds t) 1000000)))) (define ->microseconds (λ (t) (exact-floor (/ (->nanoseconds t) 1000))))]) (define-generics time-arithmetic-provider (+hours time-arithmetic-provider n) (+minutes time-arithmetic-provider n) (+seconds time-arithmetic-provider n) (+milliseconds time-arithmetic-provider n) (+microseconds time-arithmetic-provider n) (+nanoseconds time-arithmetic-provider n) (-hours time-arithmetic-provider n) (-minutes time-arithmetic-provider n) (-seconds time-arithmetic-provider n) (-milliseconds time-arithmetic-provider n) (-microseconds time-arithmetic-provider n) (-nanoseconds time-arithmetic-provider n) (+time-period time-arithmetic-provider p) (-time-period time-arithmetic-provider p) #:defaults ([time? (define (+nanoseconds t n) (day-ns->time (mod (+ (time->ns t) n) NS/DAY)))] [datetime? (define +nanoseconds datetime-add-nanoseconds)] [moment? (define +nanoseconds moment-add-nanoseconds)] [period? (define-syntax-rule (mk ctor +t -t) (begin (define (+t p n) (period p (ctor n))) (define (-t p n) (period p (ctor (- n)))))) (mk hours +hours -hours) (mk minutes +minutes -minutes) (mk seconds +seconds -seconds) (mk milliseconds +milliseconds -milliseconds) (mk microseconds +microseconds -microseconds) (mk nanoseconds +nanoseconds -nanoseconds) (define (+time-period p0 p1) (period p0 p1))]) #:fallbacks [(define/generic ns+ +nanoseconds) (define (-nanoseconds t n) (ns+ t (- n))) (define (t+/- NS/UNIT i) (λ (t n) (ns+ t (* n NS/UNIT i)))) (define (t+ NS/UNIT) (t+/- NS/UNIT 1)) (define (t- NS/UNIT) (t+/- NS/UNIT -1)) (define +hours (t+ NS/HOUR)) (define +minutes (t+ NS/MINUTE)) (define +seconds (t+ NS/SECOND)) (define +milliseconds (t+ NS/MILLI)) (define +microseconds (t+ NS/MICRO)) (define -hours (t- NS/HOUR)) (define -minutes (t- NS/MINUTE)) (define -seconds (t- NS/SECOND)) (define -milliseconds (t- NS/MILLI)) (define -microseconds (t- NS/MICRO)) (define/generic +p +time-period) (define (+time-period t p) (match-define (period [hours hrs] [minutes min] [seconds sec] [milliseconds ms] [microseconds us] [nanoseconds ns]) p) (ns+ t (+ (* NS/HOUR hrs) (* NS/MINUTE min) (* NS/SECOND sec) (* NS/MILLI ms) (* NS/MICRO us) ns))) (define (-time-period t p) (+p t (negate-period p)))]) (define-generics datetime-provider (->datetime/local datetime-provider) (->datetime/utc datetime-provider) (->datetime/similar datetime-provider other) (->posix datetime-provider) (->jd datetime-provider) (years-between datetime-provider other) (months-between datetime-provider other) (weeks-between datetime-provider other) (days-between datetime-provider other) (hours-between datetime-provider other) (minutes-between datetime-provider other) (seconds-between datetime-provider other) (milliseconds-between datetime-provider other) (microseconds-between datetime-provider other) (nanoseconds-between datetime-provider other) (with-timezone datetime-provider tz #:resolve-offset [resolve-offset]) #:defaults ([date? (define ->datetime/local at-midnight) (define ->datetime/utc at-midnight)] [datetime? (define ->datetime/local (λ (x) x)) (define ->datetime/utc ->datetime/local)] [moment? (define/generic ->dt/l ->datetime/local) (define ->datetime/local moment->datetime/local) (define ->datetime/utc (compose1 moment->datetime/local moment-in-utc)) (define (->datetime/similar self other) (->dt/l (cond [(moment-provider? other) (timezone-adjust other (->timezone self))] [else other])))]) #:fallbacks [(define/generic ->dt ->datetime/utc) (define/generic ->dt/l ->datetime/local) (define/generic ->dt/s ->datetime/similar) (define (->datetime/similar _ dt) (->dt/l dt)) (define (->jd dt) (datetime->jd (->dt dt))) (define EPOCH (moment 1970 #:tz UTC)) (define (->posix dt) (/ (nanoseconds-between EPOCH dt) NS/SECOND)) (define (lift/date fn) (λ (d1 d2) (fn (->dt/l d1) (->dt/s d1 d2)))) (define (lift/time fn) (λ (d1 d2) (fn (->dt d1) (->dt d2)))) (define (quot fn n) (λ (d1 d2) (quotient (fn d1 d2) n))) (define months-between (lift/date datetime-months-between)) (define years-between (quot months-between 12)) (define days-between (lift/date datetime-days-between)) (define weeks-between (quot days-between 7)) (define nanoseconds-between (lift/time datetime-nanoseconds-between)) (define hours-between (quot nanoseconds-between NS/HOUR)) (define minutes-between (quot nanoseconds-between NS/MINUTE)) (define seconds-between (quot nanoseconds-between NS/SECOND)) (define milliseconds-between (quot nanoseconds-between NS/MILLI)) (define microseconds-between (quot nanoseconds-between NS/MICRO)) (define (with-timezone t tz #:resolve-offset [r resolve-offset/raise]) (datetime+tz->moment (->dt/l t) tz r))]) (define-generics datetime-arithmetic-provider (+period datetime-arithmetic-provider p #:resolve-offset [resolve-offset]) (-period datetime-arithmetic-provider p #:resolve-offset [resolve-offset]) #:defaults [(datetime?) (moment?) (period?)] #:fallbacks [(define (+period t p #:resolve-offset [r resolve-offset/retain]) (define t0 (+date-period t (period->date-period p) #:resolve-offset (resolve/orig r t))) (+time-period t0 (period->time-period p))) (define (-period t p #:resolve-offset [r resolve-offset/retain]) (+period t (negate-period p) #:resolve-offset r))]) (define-generics moment-provider (->moment moment-provider) (->utc-offset moment-provider) (->timezone moment-provider) (->tzid moment-provider) (adjust-timezone moment-provider tz) #:defaults ([moment? (define ->moment (λ (x) x)) (define ->utc-offset moment->utc-offset) (define ->timezone moment->timezone) (define ->tzid moment->tzid) (define adjust-timezone timezone-adjust)])) (define (tzid-provider? x) (and (moment-provider? x) (->tzid x)))
7f2454a6141c53ca14261568cb1f139630e93ccb4b9b8a4f35b333b4256822a3
josefs/Gradualizer
type_pattern.erl
%%% @doc Test cases for `add_type_pat/4' -module(type_pattern). -compile([export_all, nowarn_export_all]). -type mychar() :: char(). %% The user type `mychar()' inside a list is not normalized when %% `add_types_pats/4' is called, but postponed later within ` subtype(string ( ) , [ mychar ( ) ] , TEnv ) ' . There was a typo that specifically in case of a string pattern VEnv was passed instead of TEnv . -spec f([mychar()]) -> any(). f("foo") -> ok; f(_) -> also_ok. -type ok_tuple() :: {ok}. -spec g([ok_tuple()]) -> list(). g(List) -> [ok || {ok} <- List].
null
https://raw.githubusercontent.com/josefs/Gradualizer/bd92da1e47a0fdb8bd22009da10bd73f0422e066/test/should_pass/type_pattern.erl
erlang
@doc Test cases for `add_type_pat/4' The user type `mychar()' inside a list is not normalized when `add_types_pats/4' is called, but postponed later within
-module(type_pattern). -compile([export_all, nowarn_export_all]). -type mychar() :: char(). ` subtype(string ( ) , [ mychar ( ) ] , TEnv ) ' . There was a typo that specifically in case of a string pattern VEnv was passed instead of TEnv . -spec f([mychar()]) -> any(). f("foo") -> ok; f(_) -> also_ok. -type ok_tuple() :: {ok}. -spec g([ok_tuple()]) -> list(). g(List) -> [ok || {ok} <- List].
3c4fad6638c34a1f66f2177f125ac96b1ae873242a41f29e0169270235e0609c
Bogdanp/try-racket
all.rkt
#lang racket/base (define-syntax-rule (reprovide mod ...) (begin (require mod ...) (provide (all-from-out mod ...)))) (reprovide "common.rkt" "editor.rkt")
null
https://raw.githubusercontent.com/Bogdanp/try-racket/0b82259d60edb08a5158d60500e0104cf9dbaad6/try-racket/pages/all.rkt
racket
#lang racket/base (define-syntax-rule (reprovide mod ...) (begin (require mod ...) (provide (all-from-out mod ...)))) (reprovide "common.rkt" "editor.rkt")
c9ebe9c31fb75f14567bb1c1a5a3aa419e6610ece2dbc309b2e437488c3ad72c
zmyrgel/tursas
eval.clj
(ns tursas.state0x88.eval (:use (tursas state) (tursas.state0x88 common util))) (def pawn-value 10) (def bishop-value 30) (def knight-value 30) (def rook-value 50) (def queen-value 90) (def king-value 99999) ;; Score tables for each piece type ;; all tables are from white players point of view. (def pawn-scores [0 0 0 0 0 0 0 0 5 5 5 0 0 5 5 5 0 0 5 15 15 5 0 0 5 5 10 15 15 10 5 5 0 0 5 10 10 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]) (def rook-scores [5 0 5 0 0 5 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]) (def rook-end-scores [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]) (def knight-scores [-10 -5 -5 -5 -5 -5 -5 -10 -5 -5 0 5 5 0 -5 -5 -5 5 5 10 10 5 5 -5 -5 0 10 10 10 10 0 -5 -5 0 10 10 10 10 0 -5 -5 5 5 10 10 10 5 -5 -5 -5 0 5 5 0 -5 -5 -10 -5 -5 -5 -5 -5 -5 -10]) (def bishop-scores [-15 -10 -10 -10 -10 -10 -10 -15 -10 0 0 0 0 0 0 -10 -10 0 5 10 10 5 0 -10 -10 5 5 10 10 5 5 -10 -10 0 10 10 10 10 0 -10 -10 10 10 10 10 10 10 -10 -10 5 0 0 0 0 5 -10 -15 -10 -10 -10 -10 -10 -10 -15]) (def king-scores [ 0 -5 5 0 0 -5 5 0 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10]) (def king-end-scores [-15 -10 -10 -10 -10 -10 -10 -15 -10 -10 -5 0 0 -5 -10 -10 -10 -5 5 10 10 5 -5 -10 -10 -5 10 15 15 10 -5 -10 -10 -5 10 15 15 10 -5 -10 -10 -5 5 10 10 5 -5 -10 -10 -10 -5 0 0 -5 -10 -10 -15 -10 -10 -10 -10 -10 -10 -15]) (def white-pawn-table (make-table pawn-scores)) (def black-pawn-table (make-table (reverse pawn-scores))) (def white-knight-table (make-table knight-scores)) (def black-knight-table (make-table (reverse knight-scores))) (def white-bishop-table (make-table bishop-scores)) (def black-bishop-table (make-table (reverse bishop-scores))) (def white-rook-table (make-table rook-scores)) (def black-rook-table (make-table (reverse rook-scores))) (def white-king-table (make-table king-scores)) (def black-king-table (make-table (reverse king-scores))) (def white-king-table-end-game (make-table king-end-scores)) (def black-king-table-end-game (make-table (reverse king-end-scores))) (defn- material-value "Gives material value for given piece." [piece] (cond (== piece white-pawn) pawn-value (== piece white-knight) knight-value (== piece white-bishop) bishop-value (== piece white-rook) rook-value (== piece white-queen) queen-value (== piece white-king) king-value (== piece black-pawn) pawn-value (== piece black-knight) knight-value (== piece black-bishop) bishop-value (== piece black-rook) rook-value (== piece black-queen) queen-value (== piece black-king) king-value :else 0)) (defn- index-score "Checks piece-specific index score" [piece index game-situation] (cond (== piece white-pawn) (get white-pawn-table index) (== piece black-pawn) (get black-pawn-table index) (== piece white-knight) (get white-knight-table index) (== piece black-knight) (get black-knight-table index) (== piece white-bishop) (get white-bishop-table index) (== piece black-bishop) (get black-bishop-table index) (== piece white-rook) (get white-rook-table index) (== piece black-rook) (get black-rook-table index) (== piece white-king) (if (== game-situation end-game) (get white-king-table-end-game index) (get white-king-table index)) (== piece black-king) (if (== game-situation end-game) (get black-king-table-end-game index) (get black-king-table index)) :else 0)) (defn- pawn-shield-bonus "Returns pawn-shield bonus to score if king is castled and pawns protect it." [state] 0) (defn- bishop-pair-bonus "Grants small bonus if both bishops are present." [state] 0) (defn- bishop-mobility-bonus "When number of pawns is reduced, grant small bonus for each bishop. They get more useful once there's more room to move." [state] 0) (defn- knight-mobility-penalty "When number of pawns decreases, the effectiviness of knights is reduced. Reduce the value of knights at this point to reflect the fact." [state] 0) (defn- early-queen-penalty "Give small penalty when if queen is moved early in the game. It makes it vurnerable to enemy captures." [state] 0) (defn- mobility-bonus "Give small bonus to pieces if it can move more." [state] 0) (defn- threat-bonus "Give small bonus to each piece which is threatening enemy piece." [state] 0) (defn- protection-bonus "Give small bonus to pieces which protect some other piece." [state] 0) (defn- pawn-color-penalty "Give small penalty if there is a lot of pawns in same colored squares as the players bishop." [state] 0) (defn- pawn-advanced-bonus "Give bonus for advancing pawns so they will get promoted to other pieces." [state] 0) (defn- score "Calculates score for side." [pieces situation] (reduce (fn [score [index piece]] (+ score (material-value piece) (index-score piece index situation))) 0 (seq pieces))) (defn heuristic-value "Calculates heuristic value for given state." [player whites blacks situation] (let [pieces (if (== player white) (list whites blacks) (list blacks whites))] (+ (score (first pieces) situation) (- (score (second pieces) situation))))) (defn end-score [state] (if (mate? state) (- king-value) 0))
null
https://raw.githubusercontent.com/zmyrgel/tursas/362551a1861be0728f21b561d8907d0ca04333f7/src/tursas/state0x88/eval.clj
clojure
Score tables for each piece type all tables are from white players point of view.
(ns tursas.state0x88.eval (:use (tursas state) (tursas.state0x88 common util))) (def pawn-value 10) (def bishop-value 30) (def knight-value 30) (def rook-value 50) (def queen-value 90) (def king-value 99999) (def pawn-scores [0 0 0 0 0 0 0 0 5 5 5 0 0 5 5 5 0 0 5 15 15 5 0 0 5 5 10 15 15 10 5 5 0 0 5 10 10 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]) (def rook-scores [5 0 5 0 0 5 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]) (def rook-end-scores [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]) (def knight-scores [-10 -5 -5 -5 -5 -5 -5 -10 -5 -5 0 5 5 0 -5 -5 -5 5 5 10 10 5 5 -5 -5 0 10 10 10 10 0 -5 -5 0 10 10 10 10 0 -5 -5 5 5 10 10 10 5 -5 -5 -5 0 5 5 0 -5 -5 -10 -5 -5 -5 -5 -5 -5 -10]) (def bishop-scores [-15 -10 -10 -10 -10 -10 -10 -15 -10 0 0 0 0 0 0 -10 -10 0 5 10 10 5 0 -10 -10 5 5 10 10 5 5 -10 -10 0 10 10 10 10 0 -10 -10 10 10 10 10 10 10 -10 -10 5 0 0 0 0 5 -10 -15 -10 -10 -10 -10 -10 -10 -15]) (def king-scores [ 0 -5 5 0 0 -5 5 0 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10 -10]) (def king-end-scores [-15 -10 -10 -10 -10 -10 -10 -15 -10 -10 -5 0 0 -5 -10 -10 -10 -5 5 10 10 5 -5 -10 -10 -5 10 15 15 10 -5 -10 -10 -5 10 15 15 10 -5 -10 -10 -5 5 10 10 5 -5 -10 -10 -10 -5 0 0 -5 -10 -10 -15 -10 -10 -10 -10 -10 -10 -15]) (def white-pawn-table (make-table pawn-scores)) (def black-pawn-table (make-table (reverse pawn-scores))) (def white-knight-table (make-table knight-scores)) (def black-knight-table (make-table (reverse knight-scores))) (def white-bishop-table (make-table bishop-scores)) (def black-bishop-table (make-table (reverse bishop-scores))) (def white-rook-table (make-table rook-scores)) (def black-rook-table (make-table (reverse rook-scores))) (def white-king-table (make-table king-scores)) (def black-king-table (make-table (reverse king-scores))) (def white-king-table-end-game (make-table king-end-scores)) (def black-king-table-end-game (make-table (reverse king-end-scores))) (defn- material-value "Gives material value for given piece." [piece] (cond (== piece white-pawn) pawn-value (== piece white-knight) knight-value (== piece white-bishop) bishop-value (== piece white-rook) rook-value (== piece white-queen) queen-value (== piece white-king) king-value (== piece black-pawn) pawn-value (== piece black-knight) knight-value (== piece black-bishop) bishop-value (== piece black-rook) rook-value (== piece black-queen) queen-value (== piece black-king) king-value :else 0)) (defn- index-score "Checks piece-specific index score" [piece index game-situation] (cond (== piece white-pawn) (get white-pawn-table index) (== piece black-pawn) (get black-pawn-table index) (== piece white-knight) (get white-knight-table index) (== piece black-knight) (get black-knight-table index) (== piece white-bishop) (get white-bishop-table index) (== piece black-bishop) (get black-bishop-table index) (== piece white-rook) (get white-rook-table index) (== piece black-rook) (get black-rook-table index) (== piece white-king) (if (== game-situation end-game) (get white-king-table-end-game index) (get white-king-table index)) (== piece black-king) (if (== game-situation end-game) (get black-king-table-end-game index) (get black-king-table index)) :else 0)) (defn- pawn-shield-bonus "Returns pawn-shield bonus to score if king is castled and pawns protect it." [state] 0) (defn- bishop-pair-bonus "Grants small bonus if both bishops are present." [state] 0) (defn- bishop-mobility-bonus "When number of pawns is reduced, grant small bonus for each bishop. They get more useful once there's more room to move." [state] 0) (defn- knight-mobility-penalty "When number of pawns decreases, the effectiviness of knights is reduced. Reduce the value of knights at this point to reflect the fact." [state] 0) (defn- early-queen-penalty "Give small penalty when if queen is moved early in the game. It makes it vurnerable to enemy captures." [state] 0) (defn- mobility-bonus "Give small bonus to pieces if it can move more." [state] 0) (defn- threat-bonus "Give small bonus to each piece which is threatening enemy piece." [state] 0) (defn- protection-bonus "Give small bonus to pieces which protect some other piece." [state] 0) (defn- pawn-color-penalty "Give small penalty if there is a lot of pawns in same colored squares as the players bishop." [state] 0) (defn- pawn-advanced-bonus "Give bonus for advancing pawns so they will get promoted to other pieces." [state] 0) (defn- score "Calculates score for side." [pieces situation] (reduce (fn [score [index piece]] (+ score (material-value piece) (index-score piece index situation))) 0 (seq pieces))) (defn heuristic-value "Calculates heuristic value for given state." [player whites blacks situation] (let [pieces (if (== player white) (list whites blacks) (list blacks whites))] (+ (score (first pieces) situation) (- (score (second pieces) situation))))) (defn end-score [state] (if (mate? state) (- king-value) 0))
931f39103583e87e1ea430a1f38a862931b98ed8123ca0e2bb9fb602dac42ddf
ArulselvanMadhavan/haskell-first-principles
MonoidTestUtils.hs
module MonoidTestUtils where import Data.Monoid import Test.QuickCheck monoidAssoc :: (Eq m, Monoid m) => m -> m -> m -> Bool monoidAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c) monoidLeftIdentity :: (Eq m, Monoid m) => m -> Bool monoidLeftIdentity a = (mempty <> a) == a monoidRightIdentity :: (Eq m, Monoid m) => m -> Bool monoidRightIdentity a = (a <> mempty) == a testStringMonoidAssoc :: IO () testStringMonoidAssoc = quickCheck (monoidAssoc :: String -> String -> String -> Bool) testStringLeftIdentity :: IO () testStringLeftIdentity = quickCheck (monoidLeftIdentity :: String -> Bool) runTests :: IO () runTests = do testStringMonoidAssoc testStringLeftIdentity
null
https://raw.githubusercontent.com/ArulselvanMadhavan/haskell-first-principles/06e0c71c502848c8e75c8109dd49c0954d815bba/chapter15/test/MonoidTestUtils.hs
haskell
module MonoidTestUtils where import Data.Monoid import Test.QuickCheck monoidAssoc :: (Eq m, Monoid m) => m -> m -> m -> Bool monoidAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c) monoidLeftIdentity :: (Eq m, Monoid m) => m -> Bool monoidLeftIdentity a = (mempty <> a) == a monoidRightIdentity :: (Eq m, Monoid m) => m -> Bool monoidRightIdentity a = (a <> mempty) == a testStringMonoidAssoc :: IO () testStringMonoidAssoc = quickCheck (monoidAssoc :: String -> String -> String -> Bool) testStringLeftIdentity :: IO () testStringLeftIdentity = quickCheck (monoidLeftIdentity :: String -> Bool) runTests :: IO () runTests = do testStringMonoidAssoc testStringLeftIdentity
c715850ac6db25946d02eaf4be15e8a1925453db4846783560a473a8d6eb014b
alura-cursos/datomic-identidades-e-queries
db.clj
(ns ecommerce.db (:use clojure.pprint) (:require [datomic.api :as d])) (def db-uri "datomic:dev:4334/ecommerce") (defn abre-conexao! [] (d/create-database db-uri) (d/connect db-uri)) (defn apaga-banco! [] (d/delete-database db-uri)) ; Produtos ; id? nome String 1 = = > Computador Novo ; slug String 1 ==> /computador_novo preco ponto flutuante 1 = = > 3500.10 categoria_id integer = = > 3 ; id_entidade atributo valor 15 : produto / nome Computador Novo ID_TX operacao 15 : produto / slug /computador_novo ID_TX operacao 15 : produto / preco 3500.10 ID_TX operacao 15 : produto / categoria 37 17 : produto / nome Telefone Caro ID_TX operacao 17 : produto / slug /telefone ID_TX operacao 17 : produto / preco 8888.88 ID_TX operacao 36 : categoria / nome Eletronicos (def schema [ ; Produtos {:db/ident :produto/nome :db/valueType :db.type/string :db/cardinality :db.cardinality/one :db/doc "O nome de um produto"} {:db/ident :produto/slug :db/valueType :db.type/string :db/cardinality :db.cardinality/one :db/doc "O caminho para acessar esse produto via http"} {:db/ident :produto/preco :db/valueType :db.type/bigdec :db/cardinality :db.cardinality/one :db/doc "O preço de um produto com precisão monetária"} {:db/ident :produto/palavra-chave :db/valueType :db.type/string :db/cardinality :db.cardinality/many} {:db/ident :produto/id :db/valueType :db.type/uuid :db/cardinality :db.cardinality/one :db/unique :db.unique/identity} {:db/ident :produto/categoria :db/valueType :db.type/ref :db/cardinality :db.cardinality/one} Categorias {:db/ident :categoria/nome :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :categoria/id :db/valueType :db.type/uuid :db/cardinality :db.cardinality/one :db/unique :db.unique/identity} ]) (defn cria-schema! [conn] (d/transact conn schema)) ; pull explicito atributo a atributo ( [ db ] ( d / q ' [: find ( pull ? entidade [: produto / nome : produto / preco : produto / slug ] ) ; :where [?entidade :produto/nome]] db)) pull generico , vantagem preguica , desvantagem pode trazer mais do que eu queira (defn todos-os-produtos [db] (d/q '[:find (pull ?entidade [*]) :where [?entidade :produto/nome]] db)) no sql eh : ; String sql = "meu codigo sql"; ; conexao.query(sql) ; esse aqui eh similar ao String sql eh comum e voce pode em um def ou let porem ... -q é hungara ... indica o TIPO ... humm .. não parece ser legal ; em clojure vc vai encontrar esse padro em alguns exemplos e documentacao nao recomendamos notacao hungara , ainda menos ;) (def todos-os-produtos-por-slug-fixo-q '[:find ?entidade :where [?entidade :produto/slug "/computador-novo"]]) (defn todos-os-produtos-por-slug-fixo [db] (d/q todos-os-produtos-por-slug-fixo-q db)) ; não estou usando notacao hungara e extract ; eh comum no sql: String sql = "select * from where slug=::SLUG::" ; conexao.query(sql, {::SLUG:: "/computador-novo}) (defn todos-os-produtos-por-slug [db slug] (d/q '[:find ?entidade :in $ ?slug-procurado ; proposital diferente da variável de clojure para evitar erros :where [?entidade :produto/slug ?slug-procurado]] db slug)) ; ?entity => ?entidade => ?produto => ?p se ... _ (defn todos-os-slugs [db] (d/q '[:find ?slug :where [_ :produto/slug ?slug]] db)) estou sendo explicito 1 a 1 (defn todos-os-produtos-por-preco [db preco-minimo-requisitado] (d/q '[:find ?nome, ?preco :in $, ?preco-minimo :keys produto/nome, produto/preco :where [?produto :produto/preco ?preco] [(> ?preco ?preco-minimo)] [?produto :produto/nome ?nome]] db, preco-minimo-requisitado)) eu tenho 10mil ... se eu tenho 1000 produtos com preco > 5000 , so 10 produtos com quantidade < 10 passar por 10 mil [ ( > preco 5000 ) ] ; = > 5000 datom [ ( < quantidade 10 ) ] ; = > 10 ; passar por 10 mil [ ( < quantidade 10 ) ] ; = > 10 [ ( > preco 5000 ) ] ; = > 10 ; em geral as condicoes da mais restritiva pra menos restritiva ... pois o plano tomamos (defn todos-os-produtos-por-palavra-chave [db palavra-chave-buscada] (d/q '[:find (pull ?produto [*]) :in $ ?palavra-chave :where [?produto :produto/palavra-chave ?palavra-chave]] db palavra-chave-buscada)) (defn um-produto-por-dbid [db db-id] (d/pull db '[*] db-id)) (defn um-produto [db produto-id] (d/pull db '[*] [:produto/id produto-id])) (defn todas-as-categorias [db] (d/q '[:find (pull ?categoria [*]) :where [?categoria :categoria/id]] db)) (defn db-adds-de-atribuicao-de-categorias [produtos categoria] (reduce (fn [db-adds produto] (conj db-adds [:db/add [:produto/id (:produto/id produto)] :produto/categoria [:categoria/id (:categoria/id categoria)]])) [] produtos)) (defn atribui-categorias! [conn produtos categoria] (let [a-transacionar (db-adds-de-atribuicao-de-categorias produtos categoria)] (d/transact conn a-transacionar))) (defn adiciona-produtos! [conn produtos] (d/transact conn produtos)) como esses dois estão um só mas vamos schema fica mais fácil de trabalhar (defn adiciona-categorias! [conn categorias] (d/transact conn categorias)) (defn todos-os-nomes-de-produtos-e-categorias [db] (d/q '[:find ?nome-do-produto ?nome-da-categoria :keys produto categoria :where [?produto :produto/nome ?nome-do-produto] [?produto :produto/categoria ?categoria] [?categoria :categoria/nome ?nome-da-categoria]] db))
null
https://raw.githubusercontent.com/alura-cursos/datomic-identidades-e-queries/2c14e40f02ae3ac2ebd39d2a1d07fbdc87526052/aula4.1/ecommerce/src/ecommerce/db.clj
clojure
Produtos id? slug String 1 ==> /computador_novo id_entidade atributo valor Produtos pull explicito atributo a atributo :where [?entidade :produto/nome]] db)) String sql = "meu codigo sql"; conexao.query(sql) esse aqui eh similar ao String sql em clojure ) não estou usando notacao hungara e extract eh comum no sql: String sql = "select * from where slug=::SLUG::" conexao.query(sql, {::SLUG:: "/computador-novo}) proposital diferente da variável de clojure para evitar erros ?entity => ?entidade => ?produto => ?p = > 5000 datom = > 10 = > 10 = > 10
(ns ecommerce.db (:use clojure.pprint) (:require [datomic.api :as d])) (def db-uri "datomic:dev:4334/ecommerce") (defn abre-conexao! [] (d/create-database db-uri) (d/connect db-uri)) (defn apaga-banco! [] (d/delete-database db-uri)) nome String 1 = = > Computador Novo preco ponto flutuante 1 = = > 3500.10 categoria_id integer = = > 3 15 : produto / nome Computador Novo ID_TX operacao 15 : produto / slug /computador_novo ID_TX operacao 15 : produto / preco 3500.10 ID_TX operacao 15 : produto / categoria 37 17 : produto / nome Telefone Caro ID_TX operacao 17 : produto / slug /telefone ID_TX operacao 17 : produto / preco 8888.88 ID_TX operacao 36 : categoria / nome Eletronicos (def schema [ {:db/ident :produto/nome :db/valueType :db.type/string :db/cardinality :db.cardinality/one :db/doc "O nome de um produto"} {:db/ident :produto/slug :db/valueType :db.type/string :db/cardinality :db.cardinality/one :db/doc "O caminho para acessar esse produto via http"} {:db/ident :produto/preco :db/valueType :db.type/bigdec :db/cardinality :db.cardinality/one :db/doc "O preço de um produto com precisão monetária"} {:db/ident :produto/palavra-chave :db/valueType :db.type/string :db/cardinality :db.cardinality/many} {:db/ident :produto/id :db/valueType :db.type/uuid :db/cardinality :db.cardinality/one :db/unique :db.unique/identity} {:db/ident :produto/categoria :db/valueType :db.type/ref :db/cardinality :db.cardinality/one} Categorias {:db/ident :categoria/nome :db/valueType :db.type/string :db/cardinality :db.cardinality/one} {:db/ident :categoria/id :db/valueType :db.type/uuid :db/cardinality :db.cardinality/one :db/unique :db.unique/identity} ]) (defn cria-schema! [conn] (d/transact conn schema)) ( [ db ] ( d / q ' [: find ( pull ? entidade [: produto / nome : produto / preco : produto / slug ] ) pull generico , vantagem preguica , desvantagem pode trazer mais do que eu queira (defn todos-os-produtos [db] (d/q '[:find (pull ?entidade [*]) :where [?entidade :produto/nome]] db)) no sql eh : eh comum e voce pode em um def ou let porem ... -q é hungara ... indica o TIPO ... humm .. não parece ser legal vc vai encontrar esse padro em alguns exemplos e documentacao (def todos-os-produtos-por-slug-fixo-q '[:find ?entidade :where [?entidade :produto/slug "/computador-novo"]]) (defn todos-os-produtos-por-slug-fixo [db] (d/q todos-os-produtos-por-slug-fixo-q db)) (defn todos-os-produtos-por-slug [db slug] (d/q '[:find ?entidade :where [?entidade :produto/slug ?slug-procurado]] db slug)) se ... _ (defn todos-os-slugs [db] (d/q '[:find ?slug :where [_ :produto/slug ?slug]] db)) estou sendo explicito 1 a 1 (defn todos-os-produtos-por-preco [db preco-minimo-requisitado] (d/q '[:find ?nome, ?preco :in $, ?preco-minimo :keys produto/nome, produto/preco :where [?produto :produto/preco ?preco] [(> ?preco ?preco-minimo)] [?produto :produto/nome ?nome]] db, preco-minimo-requisitado)) eu tenho 10mil ... se eu tenho 1000 produtos com preco > 5000 , so 10 produtos com quantidade < 10 passar por 10 mil passar por 10 mil em geral as condicoes da mais restritiva pra menos restritiva ... pois o plano tomamos (defn todos-os-produtos-por-palavra-chave [db palavra-chave-buscada] (d/q '[:find (pull ?produto [*]) :in $ ?palavra-chave :where [?produto :produto/palavra-chave ?palavra-chave]] db palavra-chave-buscada)) (defn um-produto-por-dbid [db db-id] (d/pull db '[*] db-id)) (defn um-produto [db produto-id] (d/pull db '[*] [:produto/id produto-id])) (defn todas-as-categorias [db] (d/q '[:find (pull ?categoria [*]) :where [?categoria :categoria/id]] db)) (defn db-adds-de-atribuicao-de-categorias [produtos categoria] (reduce (fn [db-adds produto] (conj db-adds [:db/add [:produto/id (:produto/id produto)] :produto/categoria [:categoria/id (:categoria/id categoria)]])) [] produtos)) (defn atribui-categorias! [conn produtos categoria] (let [a-transacionar (db-adds-de-atribuicao-de-categorias produtos categoria)] (d/transact conn a-transacionar))) (defn adiciona-produtos! [conn produtos] (d/transact conn produtos)) como esses dois estão um só mas vamos schema fica mais fácil de trabalhar (defn adiciona-categorias! [conn categorias] (d/transact conn categorias)) (defn todos-os-nomes-de-produtos-e-categorias [db] (d/q '[:find ?nome-do-produto ?nome-da-categoria :keys produto categoria :where [?produto :produto/nome ?nome-do-produto] [?produto :produto/categoria ?categoria] [?categoria :categoria/nome ?nome-da-categoria]] db))
20de29d1cf7af1773a0b5f6ddcb1f11fe91cbfbb914525e90c563ed3b7ce5708
janestreet/memtrace_viewer_with_deps
test_config.ml
open! Core open! Import let%expect_test "default timing-wheel precision and level durations" = let module I = Incremental.Make () in let config = I.Clock.default_timing_wheel_config in let durations = Timing_wheel.Config.durations config in require [%here] (Time_ns.Span.( >= ) (List.last_exn durations) Time_ns.Span.day); print_s [%message "" ~alarm_precision:(Timing_wheel.Config.alarm_precision config : Time_ns.Span.t) (durations : Time_ns.Span.t list)]; [%expect {| ((alarm_precision 1.048576ms) (durations ( 17.179869184s 1d15h5m37.488355328s 52d2h59m59.627370496s 104d5h59m59.254740992s 208d11h59m58.509481984s 416d23h59m57.018963968s 833d23h59m54.037927936s 1667d23h59m48.075855872s 3335d23h59m36.151711744s 6671d23h59m12.303423488s 13343d23h58m24.606846976s 26687d23h56m49.213693952s 53375d23h53m38.427387903s))) |}] ;; let%expect_test "default timing wheel can handle the full range of times" = let module I = Incremental.Make () in let open I in let clock = Clock.create ~start:Time_ns.epoch () in let o = observe (Clock.at clock Time_ns.max_value_representable) in let show_o () = print_s [%sexp (o : Before_or_after.t Observer.t)] in stabilize (); show_o (); [%expect {| Before |}]; Clock.advance_clock clock ~to_:Time_ns.max_value_representable; stabilize (); show_o (); [%expect {| After |}] ;;
null
https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/incremental/test/test_config.ml
ocaml
open! Core open! Import let%expect_test "default timing-wheel precision and level durations" = let module I = Incremental.Make () in let config = I.Clock.default_timing_wheel_config in let durations = Timing_wheel.Config.durations config in require [%here] (Time_ns.Span.( >= ) (List.last_exn durations) Time_ns.Span.day); print_s [%message "" ~alarm_precision:(Timing_wheel.Config.alarm_precision config : Time_ns.Span.t) (durations : Time_ns.Span.t list)]; [%expect {| ((alarm_precision 1.048576ms) (durations ( 17.179869184s 1d15h5m37.488355328s 52d2h59m59.627370496s 104d5h59m59.254740992s 208d11h59m58.509481984s 416d23h59m57.018963968s 833d23h59m54.037927936s 1667d23h59m48.075855872s 3335d23h59m36.151711744s 6671d23h59m12.303423488s 13343d23h58m24.606846976s 26687d23h56m49.213693952s 53375d23h53m38.427387903s))) |}] ;; let%expect_test "default timing wheel can handle the full range of times" = let module I = Incremental.Make () in let open I in let clock = Clock.create ~start:Time_ns.epoch () in let o = observe (Clock.at clock Time_ns.max_value_representable) in let show_o () = print_s [%sexp (o : Before_or_after.t Observer.t)] in stabilize (); show_o (); [%expect {| Before |}]; Clock.advance_clock clock ~to_:Time_ns.max_value_representable; stabilize (); show_o (); [%expect {| After |}] ;;
402959388f61800378881042a643d1258a7c748166c7f3fd490c195d599aa0ed
evdubs/renegade-way
analysis.rkt
#lang racket/base (require gregor racket/class racket/gui/base racket/match "../condor-analysis.rkt" "../price-analysis.rkt" "condor-analysis-box.rkt" "price-analysis-box.rkt" "rank-analysis.rkt" "vol-analysis.rkt" "position-analysis.rkt") (provide analysis-tab-panel show-analysis) (define analysis-frame (new frame% [label "Analysis"] [width 1000] [height 1000])) (define analysis-input-pane (new horizontal-pane% [parent analysis-frame] [stretchable-height #f])) (define market-field (new text-field% [parent analysis-input-pane] [label "Market(s)"] [init-value "SPY,MDY,SLY"])) (define sector-field (new text-field% [parent analysis-input-pane] [label "Sector"] [init-value ""])) (define start-date-field (new text-field% [parent analysis-input-pane] [label "Start Date"] [init-value (date->iso8601 (-months (today) 5))])) (define end-date-field (new text-field% [parent analysis-input-pane] [label "End Date"] [init-value (date->iso8601 (today))])) (define filter-input-pane (new horizontal-pane% [parent analysis-frame] [stretchable-height #f])) (define hide-hold-check-box (new check-box% [parent filter-input-pane] [label "Hide Hold"] [callback (λ (b e) (price-analysis-filter #:hide-hold (send hide-hold-check-box get-value) #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)))])) (define hide-no-pattern-check-box (new check-box% [parent filter-input-pane] [label "Hide No Pattern"] [callback (λ (b e) (price-analysis-filter #:hide-hold (send hide-hold-check-box get-value) #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (condor-analysis-filter #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)))])) (define hide-spread-check-box (new check-box% [parent filter-input-pane] [label "Hide Large Spread"] [callback (λ (b e) (price-analysis-filter #:hide-hold (send hide-hold-check-box get-value) #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (rank-analysis-filter #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (vol-analysis-filter #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (condor-analysis-filter #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)))])) (define hide-non-weekly-check-box (new check-box% [parent filter-input-pane] [label "Hide Non-Weekly"] [callback (λ (b e) (price-analysis-filter #:hide-hold (send hide-hold-check-box get-value) #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (rank-analysis-filter #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (vol-analysis-filter #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (condor-analysis-filter #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)))])) (define analysis-tab-panel (new tab-panel% [choices (list "Price" "Rank" "Vol" "Condor" "Position")] [parent analysis-frame] [callback (λ (p e) (refresh-tab-panel))])) (define (refresh-tab-panel) (map (λ (c) (send analysis-tab-panel delete-child c)) (send analysis-tab-panel get-children)) (match (send analysis-tab-panel get-item-label (send analysis-tab-panel get-selection)) ["Price" (price-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))] ["Rank" (rank-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))] ["Vol" (vol-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))] ["Condor" (condor-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))] ["Position" (position-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))])) (define analyze-button (new button% [parent analysis-input-pane] [label "Analyze"] [callback (λ (b e) (send b enable #f) (match (send analysis-tab-panel get-item-label (send analysis-tab-panel get-selection)) ["Price" (refresh-tab-panel) (run-price-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value)) (update-price-analysis-box price-analysis-list price-analysis-hash)] ["Rank" (refresh-tab-panel) (run-rank-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value))] ["Vol" (refresh-tab-panel) (run-vol-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value))] ["Condor" (refresh-tab-panel) (run-condor-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value)) (update-condor-analysis-box condor-analysis-list condor-analysis-hash)] ["Position" (refresh-tab-panel) (run-position-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value))]) (send b enable #t))])) (define (show-analysis) ; init everything so we don't get errors when selecting elements to hide (price-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (rank-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (vol-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (condor-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (position-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (refresh-tab-panel) (send analysis-frame show #t))
null
https://raw.githubusercontent.com/evdubs/renegade-way/93b03d40e86c069d712ddd907fb932ebfad87457/gui/analysis.rkt
racket
init everything so we don't get errors when selecting elements to hide
#lang racket/base (require gregor racket/class racket/gui/base racket/match "../condor-analysis.rkt" "../price-analysis.rkt" "condor-analysis-box.rkt" "price-analysis-box.rkt" "rank-analysis.rkt" "vol-analysis.rkt" "position-analysis.rkt") (provide analysis-tab-panel show-analysis) (define analysis-frame (new frame% [label "Analysis"] [width 1000] [height 1000])) (define analysis-input-pane (new horizontal-pane% [parent analysis-frame] [stretchable-height #f])) (define market-field (new text-field% [parent analysis-input-pane] [label "Market(s)"] [init-value "SPY,MDY,SLY"])) (define sector-field (new text-field% [parent analysis-input-pane] [label "Sector"] [init-value ""])) (define start-date-field (new text-field% [parent analysis-input-pane] [label "Start Date"] [init-value (date->iso8601 (-months (today) 5))])) (define end-date-field (new text-field% [parent analysis-input-pane] [label "End Date"] [init-value (date->iso8601 (today))])) (define filter-input-pane (new horizontal-pane% [parent analysis-frame] [stretchable-height #f])) (define hide-hold-check-box (new check-box% [parent filter-input-pane] [label "Hide Hold"] [callback (λ (b e) (price-analysis-filter #:hide-hold (send hide-hold-check-box get-value) #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)))])) (define hide-no-pattern-check-box (new check-box% [parent filter-input-pane] [label "Hide No Pattern"] [callback (λ (b e) (price-analysis-filter #:hide-hold (send hide-hold-check-box get-value) #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (condor-analysis-filter #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)))])) (define hide-spread-check-box (new check-box% [parent filter-input-pane] [label "Hide Large Spread"] [callback (λ (b e) (price-analysis-filter #:hide-hold (send hide-hold-check-box get-value) #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (rank-analysis-filter #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (vol-analysis-filter #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (condor-analysis-filter #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)))])) (define hide-non-weekly-check-box (new check-box% [parent filter-input-pane] [label "Hide Non-Weekly"] [callback (λ (b e) (price-analysis-filter #:hide-hold (send hide-hold-check-box get-value) #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (rank-analysis-filter #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (vol-analysis-filter #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)) (condor-analysis-filter #:hide-no-pattern (send hide-no-pattern-check-box get-value) #:hide-large-spread (send hide-spread-check-box get-value) #:hide-non-weekly (send hide-non-weekly-check-box get-value)))])) (define analysis-tab-panel (new tab-panel% [choices (list "Price" "Rank" "Vol" "Condor" "Position")] [parent analysis-frame] [callback (λ (p e) (refresh-tab-panel))])) (define (refresh-tab-panel) (map (λ (c) (send analysis-tab-panel delete-child c)) (send analysis-tab-panel get-children)) (match (send analysis-tab-panel get-item-label (send analysis-tab-panel get-selection)) ["Price" (price-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))] ["Rank" (rank-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))] ["Vol" (vol-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))] ["Condor" (condor-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))] ["Position" (position-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value))])) (define analyze-button (new button% [parent analysis-input-pane] [label "Analyze"] [callback (λ (b e) (send b enable #f) (match (send analysis-tab-panel get-item-label (send analysis-tab-panel get-selection)) ["Price" (refresh-tab-panel) (run-price-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value)) (update-price-analysis-box price-analysis-list price-analysis-hash)] ["Rank" (refresh-tab-panel) (run-rank-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value))] ["Vol" (refresh-tab-panel) (run-vol-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value))] ["Condor" (refresh-tab-panel) (run-condor-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value)) (update-condor-analysis-box condor-analysis-list condor-analysis-hash)] ["Position" (refresh-tab-panel) (run-position-analysis (send market-field get-value) (send sector-field get-value) (send start-date-field get-value) (send end-date-field get-value))]) (send b enable #t))])) (define (show-analysis) (price-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (rank-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (vol-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (condor-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (position-analysis-box analysis-tab-panel (send start-date-field get-value) (send end-date-field get-value)) (refresh-tab-panel) (send analysis-frame show #t))
ab292e2b2dc03fd56087943f90ff03140f14f229654170f4709501d2e0c0c368
simonmar/haxl-icfp14-sample-code
Fetch.hs
# LANGUAGE ExistentialQuantification , GADTs , StandaloneDeriving # module Fetch where import Types import MockData import DataCache import Data.IORef import Control.Applicative import Data.Traversable import Data.Sequence as Seq import Data.Monoid import Data.Foldable (toList) import Control.Exception hiding (throw, catch) import Prelude hiding (catch) -- <<Result data Result a = Done a | Blocked (Seq BlockedRequest) (Fetch a) | Throw SomeException -- >> -- <<Fetch newtype Fetch a = Fetch { unFetch :: IORef DataCache -> IO (Result a) } -- >> < < BlockedRequest data BlockedRequest = forall a . BlockedRequest (Request a) (IORef (FetchStatus a)) -- >> < < dataFetch dataFetch :: Request a -> Fetch a dataFetch request = Fetch $ \ref -> do cache <- readIORef ref case DataCache.lookup request cache of Nothing -> do box <- newIORef NotFetched writeIORef ref (DataCache.insert request box cache) let br = BlockedRequest request box return (Blocked (singleton br) (cont box)) Just box -> do r <- readIORef box case r of FetchSuccess result -> return (Done result) FetchFailure e -> return (Throw e) NotFetched -> return (Blocked Seq.empty (cont box)) where cont box = Fetch $ \ref -> do r <- readIORef box case r of FetchSuccess a -> return (Done a) FetchFailure e -> return (Throw e) NotFetched -> error "dataFetch" -- >> instance Functor Fetch where fmap f h = do x <- h; return (f x) -- <<Monad instance Monad Fetch where return a = Fetch $ \ref -> return (Done a) Fetch m >>= k = Fetch $ \ref -> do r <- m ref case r of Done a -> unFetch (k a) ref Blocked br c -> return (Blocked br (c >>= k)) Throw e -> return (Throw e) -- >> -- <<Applicative instance Applicative Fetch where pure = return Fetch f <*> Fetch x = Fetch $ \ref -> do f' <- f ref x' <- x ref case (f',x') of (Done g, Done y ) -> return (Done (g y)) (Done g, Blocked br c ) -> return (Blocked br (g <$> c)) (Done g, Throw e ) -> return (Throw e) (Blocked br c, Done y ) -> return (Blocked br (c <*> return y)) (Blocked br1 c, Blocked br2 d) -> return (Blocked (br1 <> br2) (c <*> d)) (Blocked br c, Throw e ) -> return (Blocked br (c <*> throw e)) (Throw e, _ ) -> return (Throw e) -- >> -- <<throw throw :: Exception e => e -> Fetch a throw e = Fetch $ \_ -> return (Throw (toException e)) -- >> -- <<catch catch :: Exception e => Fetch a -> (e -> Fetch a) -> Fetch a catch (Fetch h) handler = Fetch $ \ref -> do r <- h ref case r of Done a -> return (Done a) Blocked br c -> return (Blocked br (catch c handler)) Throw e -> case fromException e of Just e' -> unFetch (handler e') ref Nothing -> return (Throw e) -- >> -- <<runFetch runFetch :: Fetch a -> IO a runFetch h = do ref <- newIORef DataCache.empty runFetch' ref h runFetch' :: IORef DataCache -> Fetch a -> IO a runFetch' ref (Fetch h) = do r <- h ref case r of Done a -> return a Blocked br cont -> do fetch (toList br) runFetch' ref cont -- >> fetch :: [BlockedRequest] -> IO () fetch bs = do putStrLn "==== fetch ====" mapM_ ppr bs where ppr (BlockedRequest r m) = do print r writeIORef m (FetchSuccess (requestVal r)) mapM :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b) mapM = traverse sequence :: (Applicative f, Traversable t) => t (f a) -> f (t a) sequence = Data.Traversable.sequenceA
null
https://raw.githubusercontent.com/simonmar/haxl-icfp14-sample-code/31859f50e0548f3e581acd26944ceb00953f2c42/haxl-exceptions/Fetch.hs
haskell
<<Result >> <<Fetch >> >> >> <<Monad >> <<Applicative >> <<throw >> <<catch >> <<runFetch >>
# LANGUAGE ExistentialQuantification , GADTs , StandaloneDeriving # module Fetch where import Types import MockData import DataCache import Data.IORef import Control.Applicative import Data.Traversable import Data.Sequence as Seq import Data.Monoid import Data.Foldable (toList) import Control.Exception hiding (throw, catch) import Prelude hiding (catch) data Result a = Done a | Blocked (Seq BlockedRequest) (Fetch a) | Throw SomeException newtype Fetch a = Fetch { unFetch :: IORef DataCache -> IO (Result a) } < < BlockedRequest data BlockedRequest = forall a . BlockedRequest (Request a) (IORef (FetchStatus a)) < < dataFetch dataFetch :: Request a -> Fetch a dataFetch request = Fetch $ \ref -> do cache <- readIORef ref case DataCache.lookup request cache of Nothing -> do box <- newIORef NotFetched writeIORef ref (DataCache.insert request box cache) let br = BlockedRequest request box return (Blocked (singleton br) (cont box)) Just box -> do r <- readIORef box case r of FetchSuccess result -> return (Done result) FetchFailure e -> return (Throw e) NotFetched -> return (Blocked Seq.empty (cont box)) where cont box = Fetch $ \ref -> do r <- readIORef box case r of FetchSuccess a -> return (Done a) FetchFailure e -> return (Throw e) NotFetched -> error "dataFetch" instance Functor Fetch where fmap f h = do x <- h; return (f x) instance Monad Fetch where return a = Fetch $ \ref -> return (Done a) Fetch m >>= k = Fetch $ \ref -> do r <- m ref case r of Done a -> unFetch (k a) ref Blocked br c -> return (Blocked br (c >>= k)) Throw e -> return (Throw e) instance Applicative Fetch where pure = return Fetch f <*> Fetch x = Fetch $ \ref -> do f' <- f ref x' <- x ref case (f',x') of (Done g, Done y ) -> return (Done (g y)) (Done g, Blocked br c ) -> return (Blocked br (g <$> c)) (Done g, Throw e ) -> return (Throw e) (Blocked br c, Done y ) -> return (Blocked br (c <*> return y)) (Blocked br1 c, Blocked br2 d) -> return (Blocked (br1 <> br2) (c <*> d)) (Blocked br c, Throw e ) -> return (Blocked br (c <*> throw e)) (Throw e, _ ) -> return (Throw e) throw :: Exception e => e -> Fetch a throw e = Fetch $ \_ -> return (Throw (toException e)) catch :: Exception e => Fetch a -> (e -> Fetch a) -> Fetch a catch (Fetch h) handler = Fetch $ \ref -> do r <- h ref case r of Done a -> return (Done a) Blocked br c -> return (Blocked br (catch c handler)) Throw e -> case fromException e of Just e' -> unFetch (handler e') ref Nothing -> return (Throw e) runFetch :: Fetch a -> IO a runFetch h = do ref <- newIORef DataCache.empty runFetch' ref h runFetch' :: IORef DataCache -> Fetch a -> IO a runFetch' ref (Fetch h) = do r <- h ref case r of Done a -> return a Blocked br cont -> do fetch (toList br) runFetch' ref cont fetch :: [BlockedRequest] -> IO () fetch bs = do putStrLn "==== fetch ====" mapM_ ppr bs where ppr (BlockedRequest r m) = do print r writeIORef m (FetchSuccess (requestVal r)) mapM :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b) mapM = traverse sequence :: (Applicative f, Traversable t) => t (f a) -> f (t a) sequence = Data.Traversable.sequenceA
9e3678d48e3893b1eb80c6174e8027f4d3b78102cccc58c293819085c7535024
poscat0x04/telegram-types
SetChatPhoto.hs
module Web.Telegram.Types.Internal.API.SetChatPhoto where import Common import Web.Telegram.Types.Internal.API.ChatId import Web.Telegram.Types.Internal.InputFile data SetChatPhoto = SetChatPhoto { chatId :: ChatId, photo :: InputFile 'Normal } deriving stock (Show, Eq, Generic) deriving (ToParts) via SnakeParts SetChatPhoto mkLabel ''SetChatPhoto makeMethod ''SetChatPhoto
null
https://raw.githubusercontent.com/poscat0x04/telegram-types/3de0710640f5303638a83e409001b0342299aeb8/src/Web/Telegram/Types/Internal/API/SetChatPhoto.hs
haskell
module Web.Telegram.Types.Internal.API.SetChatPhoto where import Common import Web.Telegram.Types.Internal.API.ChatId import Web.Telegram.Types.Internal.InputFile data SetChatPhoto = SetChatPhoto { chatId :: ChatId, photo :: InputFile 'Normal } deriving stock (Show, Eq, Generic) deriving (ToParts) via SnakeParts SetChatPhoto mkLabel ''SetChatPhoto makeMethod ''SetChatPhoto
55e3c45c38eaaf34ad259d2855c972d68b8593f22028664bc794f395654123d5
facebookarchive/pfff
lib_parsing_hs.ml
* * Copyright ( C ) 2010 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) 2010 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 (*****************************************************************************) (* Wrappers *) (*****************************************************************************) (*****************************************************************************) (* Filemames *) (*****************************************************************************) let find_hs_files_of_dir_or_files xs = Common.files_of_dir_or_files_no_vcs_nofilter xs +> List.filter (fun filename -> let ftype = File_type.file_type_of_file filename in match ftype with | File_type.PL (File_type.Haskell _) -> true | _ -> false ) +> Common.sort
null
https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/lang_haskell/parsing/lib_parsing_hs.ml
ocaml
*************************************************************************** Wrappers *************************************************************************** *************************************************************************** Filemames ***************************************************************************
* * Copyright ( C ) 2010 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) 2010 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 let find_hs_files_of_dir_or_files xs = Common.files_of_dir_or_files_no_vcs_nofilter xs +> List.filter (fun filename -> let ftype = File_type.file_type_of_file filename in match ftype with | File_type.PL (File_type.Haskell _) -> true | _ -> false ) +> Common.sort
21f5131c84c01c68f514fc206c8dcae1aa8461cf55ad8ab6718571e0b943afd4
clj-commons/useful
deftype.clj
(ns flatland.useful.deftype (:use [flatland.useful.experimental.delegate :only [parse-deftype-specs emit-deftype-specs]] [flatland.useful.map :only [merge-in]]) (:require [clojure.string :as s]) (:import (clojure.lang IObj MapEntry IPersistentVector IPersistentMap APersistentMap MapEquivalence) (java.util Map Map$Entry))) ;; to define a new map type, you still must provide: ;; - IPersistentMap: ;; - (.count this) ;; - (.valAt this k not-found) ;; - (.empty this) ;; - (.assoc this k v) ;; - (.without this k) ;; - (.seq this) ;; - recommended but not required: (.entryAt this k) ;; - IObj ;; - (.meta this) ;; - (.withMeta this m) (defmacro defmap [name fields & specs] `(deftype ~name ~fields ~@(emit-deftype-specs (->> (parse-deftype-specs specs) (merge-in (parse-deftype-specs `(java.util.Map (size [this#] (count this#)) (containsKey [this# k#] (contains? this# k#)) (isEmpty [this#] (empty? this#)) (keySet [this#] (set (keys this#))) (values [this#] (vals this#)) (get [this# k#] (get this# k#)) (containsValue [this# v#] (boolean (seq (filter #(= % v#) (vals this#))))) Object (toString [this#] (str "{" (s/join ", " (for [[k# v#] this#] (str k# " " v#))) "}")) (equals [this# other#] (= this# other#)) (hashCode [this#] (APersistentMap/mapHash this#)) clojure.lang.IFn (invoke [this# k#] (get this# k#)) (invoke [this# k# not-found#] (get this# k# not-found#)) MapEquivalence IPersistentMap (equiv [this# other#] (and (instance? Map other#) (or (instance? MapEquivalence other#) (not (instance? IPersistentMap other#))) (= (count this#) (count other#)) (every? (fn [e#] (let [k# (key e#) o# ^Map other#] (and (.containsKey o# k#) (= (.get o# k#) (val e#))))) (seq this#)))) (entryAt [this# k#] (let [not-found# (Object.) v# (get this# k# not-found#)] (when (not= v# not-found#) (MapEntry. k# v#)))) (valAt [this# k#] (get this# k# nil)) (cons [this# obj#] (condp instance? obj# Map$Entry (assoc this# (key obj#) (val obj#)) IPersistentVector (if (= 2 (count obj#)) (assoc this# (nth obj# 0) (nth obj# 1)) (throw (IllegalArgumentException. "Vector arg to map conj must be a pair"))) (reduce (fn [m# e#] (assoc m# (key e#) (val e#))) this# obj#))) (iterator [this#] (clojure.lang.SeqIterator. (seq this#)))))))))) (defmap AList [entries meta] IPersistentMap (count [this] (count entries)) (valAt [this k not-found] (if-let [e (find this k)] (val e) not-found)) (entryAt [this k] (first (filter #(= k (key %)) entries))) (empty [this] (AList. () meta)) (seq [this] (seq entries)) (assoc [this k v] (AList. (conj entries (MapEntry. k v)) meta)) (without [this k] (AList. (->> entries (remove #(= k (key %))) (apply list)) meta)) IObj (meta [this] meta) (withMeta [this meta] (AList. entries meta))) (defn alist "A map stored like a common-lisp alist, ie a seq of [key, value] pairs. A new entry can simply be consed onto the front, without having to do any additional work to update the rest of the entries." [& kvs] (AList. (apply list (map vec (partition 2 kvs))) nil))
null
https://raw.githubusercontent.com/clj-commons/useful/dc5cdebf8983a2e2ea24ec8951fbb4dfb037da45/src/flatland/useful/deftype.clj
clojure
to define a new map type, you still must provide: - IPersistentMap: - (.count this) - (.valAt this k not-found) - (.empty this) - (.assoc this k v) - (.without this k) - (.seq this) - recommended but not required: (.entryAt this k) - IObj - (.meta this) - (.withMeta this m)
(ns flatland.useful.deftype (:use [flatland.useful.experimental.delegate :only [parse-deftype-specs emit-deftype-specs]] [flatland.useful.map :only [merge-in]]) (:require [clojure.string :as s]) (:import (clojure.lang IObj MapEntry IPersistentVector IPersistentMap APersistentMap MapEquivalence) (java.util Map Map$Entry))) (defmacro defmap [name fields & specs] `(deftype ~name ~fields ~@(emit-deftype-specs (->> (parse-deftype-specs specs) (merge-in (parse-deftype-specs `(java.util.Map (size [this#] (count this#)) (containsKey [this# k#] (contains? this# k#)) (isEmpty [this#] (empty? this#)) (keySet [this#] (set (keys this#))) (values [this#] (vals this#)) (get [this# k#] (get this# k#)) (containsValue [this# v#] (boolean (seq (filter #(= % v#) (vals this#))))) Object (toString [this#] (str "{" (s/join ", " (for [[k# v#] this#] (str k# " " v#))) "}")) (equals [this# other#] (= this# other#)) (hashCode [this#] (APersistentMap/mapHash this#)) clojure.lang.IFn (invoke [this# k#] (get this# k#)) (invoke [this# k# not-found#] (get this# k# not-found#)) MapEquivalence IPersistentMap (equiv [this# other#] (and (instance? Map other#) (or (instance? MapEquivalence other#) (not (instance? IPersistentMap other#))) (= (count this#) (count other#)) (every? (fn [e#] (let [k# (key e#) o# ^Map other#] (and (.containsKey o# k#) (= (.get o# k#) (val e#))))) (seq this#)))) (entryAt [this# k#] (let [not-found# (Object.) v# (get this# k# not-found#)] (when (not= v# not-found#) (MapEntry. k# v#)))) (valAt [this# k#] (get this# k# nil)) (cons [this# obj#] (condp instance? obj# Map$Entry (assoc this# (key obj#) (val obj#)) IPersistentVector (if (= 2 (count obj#)) (assoc this# (nth obj# 0) (nth obj# 1)) (throw (IllegalArgumentException. "Vector arg to map conj must be a pair"))) (reduce (fn [m# e#] (assoc m# (key e#) (val e#))) this# obj#))) (iterator [this#] (clojure.lang.SeqIterator. (seq this#)))))))))) (defmap AList [entries meta] IPersistentMap (count [this] (count entries)) (valAt [this k not-found] (if-let [e (find this k)] (val e) not-found)) (entryAt [this k] (first (filter #(= k (key %)) entries))) (empty [this] (AList. () meta)) (seq [this] (seq entries)) (assoc [this k v] (AList. (conj entries (MapEntry. k v)) meta)) (without [this k] (AList. (->> entries (remove #(= k (key %))) (apply list)) meta)) IObj (meta [this] meta) (withMeta [this meta] (AList. entries meta))) (defn alist "A map stored like a common-lisp alist, ie a seq of [key, value] pairs. A new entry can simply be consed onto the front, without having to do any additional work to update the rest of the entries." [& kvs] (AList. (apply list (map vec (partition 2 kvs))) nil))
92653c0100328b8f4e7f530487e444428b5c83e4fe9b4e4edeaeae8e7aabec7a
input-output-hk/cardano-ledger
Gen.hs
module Test.Cardano.Chain.Update.Gen ( genCanonicalProtocolParameters, genApplicationName, genError, genProtocolVersion, genProtocolParameters, genProtocolParametersUpdate, genSoftforkRule, genSoftwareVersion, genSystemTag, genInstallerHash, genPayload, genProof, genProposal, genProposalBody, genUpId, genUpsData, genVote, ) where import Cardano.Chain.Slotting (SlotNumber (..)) import Cardano.Chain.Update ( ApplicationName (..), ApplicationNameError (..), InstallerHash (..), Payload, Proof, Proposal, ProposalBody (..), ProtocolParameters (..), ProtocolParametersUpdate (..), ProtocolVersion (..), SoftforkRule (..), SoftwareVersion (..), SoftwareVersionError (..), SystemTag (..), SystemTagError (..), UpId, Vote, applicationNameMaxLength, mkVote, payload, systemTagMaxLength, unsafeProposal, ) import qualified Cardano.Chain.Update.Validation.Endorsement as Endorsement import Cardano.Chain.Update.Validation.Interface (Error (..)) import qualified Cardano.Chain.Update.Validation.Registration as Registration import qualified Cardano.Chain.Update.Validation.Voting as Voting import Cardano.Crypto (ProtocolMagicId) import Cardano.Prelude import Hedgehog import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Test.Cardano.Chain.Common.Gen ( genCanonicalTxFeePolicy, genKeyHash, genLovelacePortion, genScriptVersion, genTxFeePolicy, ) import Test.Cardano.Chain.Slotting.Gen ( genEpochNumber, genSlotNumber, ) import Test.Cardano.Crypto.Gen ( genAbstractHash, genHashRaw, genSignature, genSigningKey, genVerificationKey, ) import Test.Cardano.Prelude genApplicationName :: Gen ApplicationName genApplicationName = ApplicationName <$> Gen.text (Range.constant 0 applicationNameMaxLength) Gen.alphaNum genCanonicalProtocolParameters :: Gen ProtocolParameters genCanonicalProtocolParameters = ProtocolParameters <$> genScriptVersion <*> genNatural <*> genNatural <*> genNatural <*> genNatural <*> genNatural <*> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion <*> genSlotNumber <*> genSoftforkRule <*> genCanonicalTxFeePolicy <*> genEpochNumber genProtocolVersion :: Gen ProtocolVersion genProtocolVersion = ProtocolVersion <$> Gen.word16 Range.constantBounded <*> Gen.word16 Range.constantBounded <*> Gen.word8 Range.constantBounded genProtocolParameters :: Gen ProtocolParameters genProtocolParameters = ProtocolParameters <$> genScriptVersion <*> genNatural <*> genNatural <*> genNatural <*> genNatural <*> genNatural <*> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion <*> genSlotNumber <*> genSoftforkRule <*> genTxFeePolicy <*> genEpochNumber genProtocolParametersUpdate :: Gen ProtocolParametersUpdate genProtocolParametersUpdate = ProtocolParametersUpdate <$> Gen.maybe genScriptVersion <*> Gen.maybe genNatural <*> Gen.maybe genNatural <*> Gen.maybe genNatural <*> Gen.maybe genNatural <*> Gen.maybe genNatural <*> Gen.maybe genLovelacePortion <*> Gen.maybe genLovelacePortion <*> Gen.maybe genLovelacePortion <*> Gen.maybe genLovelacePortion <*> Gen.maybe genSlotNumber <*> Gen.maybe genSoftforkRule <*> Gen.maybe genTxFeePolicy <*> Gen.maybe genEpochNumber genSoftforkRule :: Gen SoftforkRule genSoftforkRule = SoftforkRule <$> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion genSoftwareVersion :: Gen SoftwareVersion genSoftwareVersion = SoftwareVersion <$> genApplicationName <*> Gen.word32 Range.constantBounded genSystemTag :: Gen SystemTag genSystemTag = SystemTag <$> Gen.text (Range.constant 0 systemTagMaxLength) Gen.alphaNum genInstallerHash :: Gen InstallerHash genInstallerHash = InstallerHash <$> genHashRaw genPayload :: ProtocolMagicId -> Gen Payload genPayload pm = payload <$> Gen.maybe (genProposal pm) <*> Gen.list (Range.linear 0 10) (genVote pm) genProof :: ProtocolMagicId -> Gen Proof genProof pm = genAbstractHash (genPayload pm) genProposal :: ProtocolMagicId -> Gen Proposal genProposal pm = unsafeProposal <$> genProposalBody <*> genVerificationKey <*> genSignature pm genProposalBody genProposalBody :: Gen ProposalBody genProposalBody = ProposalBody <$> genProtocolVersion <*> genProtocolParametersUpdate <*> genSoftwareVersion <*> genUpsData genUpId :: ProtocolMagicId -> Gen UpId genUpId pm = genAbstractHash (genProposal pm) genUpsData :: Gen (Map SystemTag InstallerHash) genUpsData = Gen.map (Range.linear 0 20) ((,) <$> genSystemTag <*> genInstallerHash) genVote :: ProtocolMagicId -> Gen Vote genVote pm = mkVote pm <$> genSigningKey <*> genUpId pm <*> Gen.bool genError :: ProtocolMagicId -> Gen Error genError pm = Gen.choice [ Registration <$> genRegistrationError , Voting <$> genVotingError pm , Endorsement <$> genEndorsementError , NumberOfGenesisKeysTooLarge <$> genRegistrationTooLarge ] genRegistrationError :: Gen Registration.Error genRegistrationError = Gen.choice [ Registration.DuplicateProtocolVersion <$> genProtocolVersion , Registration.DuplicateSoftwareVersion <$> genSoftwareVersion , Registration.InvalidProposer <$> genKeyHash , Registration.InvalidProtocolVersion <$> genProtocolVersion <*> (Registration.Adopted <$> genProtocolVersion) , Registration.InvalidScriptVersion <$> genWord16 <*> genWord16 , pure Registration.InvalidSignature , Registration.InvalidSoftwareVersion <$> ( Gen.map (Range.linear 1 20) $ do name <- genApplicationName version <- genWord32 slotNo <- SlotNumber <$> Gen.word64 Range.constantBounded meta <- Gen.map (Range.linear 1 10) $ (,) <$> genSystemTag <*> genInstallerHash pure (name, (Registration.ApplicationVersion version slotNo meta)) ) <*> genSoftwareVersion , Registration.MaxBlockSizeTooLarge <$> (Registration.TooLarge <$> genNatural <*> genNatural) , Registration.MaxTxSizeTooLarge <$> (Registration.TooLarge <$> genNatural <*> genNatural) , pure Registration.ProposalAttributesUnknown , Registration.ProposalTooLarge <$> (Registration.TooLarge <$> genNatural <*> genNatural) , (Registration.SoftwareVersionError . SoftwareVersionApplicationNameError) <$> Gen.choice [ ApplicationNameTooLong <$> Gen.text (Range.linear 0 20) Gen.alphaNum , ApplicationNameNotAscii <$> Gen.text (Range.linear 0 20) Gen.alphaNum ] , Registration.SystemTagError <$> Gen.choice [ SystemTagNotAscii <$> Gen.text (Range.linear 0 20) Gen.alphaNum , SystemTagTooLong <$> Gen.text (Range.linear 0 20) Gen.alphaNum ] ] genVotingError :: ProtocolMagicId -> Gen Voting.Error genVotingError pm = Gen.choice [ pure Voting.VotingInvalidSignature , Voting.VotingProposalNotRegistered <$> genUpId pm , Voting.VotingVoterNotDelegate <$> genKeyHash ] genEndorsementError :: Gen Endorsement.Error genEndorsementError = Endorsement.MultipleProposalsForProtocolVersion <$> genProtocolVersion genRegistrationTooLarge :: Gen (Registration.TooLarge Int) genRegistrationTooLarge = Registration.TooLarge <$> Gen.int Range.constantBounded <*> Gen.int Range.constantBounded
null
https://raw.githubusercontent.com/input-output-hk/cardano-ledger/31c0bb1f5e78e40b83adfd1a916e69f47fdc9835/eras/byron/ledger/impl/test/Test/Cardano/Chain/Update/Gen.hs
haskell
module Test.Cardano.Chain.Update.Gen ( genCanonicalProtocolParameters, genApplicationName, genError, genProtocolVersion, genProtocolParameters, genProtocolParametersUpdate, genSoftforkRule, genSoftwareVersion, genSystemTag, genInstallerHash, genPayload, genProof, genProposal, genProposalBody, genUpId, genUpsData, genVote, ) where import Cardano.Chain.Slotting (SlotNumber (..)) import Cardano.Chain.Update ( ApplicationName (..), ApplicationNameError (..), InstallerHash (..), Payload, Proof, Proposal, ProposalBody (..), ProtocolParameters (..), ProtocolParametersUpdate (..), ProtocolVersion (..), SoftforkRule (..), SoftwareVersion (..), SoftwareVersionError (..), SystemTag (..), SystemTagError (..), UpId, Vote, applicationNameMaxLength, mkVote, payload, systemTagMaxLength, unsafeProposal, ) import qualified Cardano.Chain.Update.Validation.Endorsement as Endorsement import Cardano.Chain.Update.Validation.Interface (Error (..)) import qualified Cardano.Chain.Update.Validation.Registration as Registration import qualified Cardano.Chain.Update.Validation.Voting as Voting import Cardano.Crypto (ProtocolMagicId) import Cardano.Prelude import Hedgehog import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import Test.Cardano.Chain.Common.Gen ( genCanonicalTxFeePolicy, genKeyHash, genLovelacePortion, genScriptVersion, genTxFeePolicy, ) import Test.Cardano.Chain.Slotting.Gen ( genEpochNumber, genSlotNumber, ) import Test.Cardano.Crypto.Gen ( genAbstractHash, genHashRaw, genSignature, genSigningKey, genVerificationKey, ) import Test.Cardano.Prelude genApplicationName :: Gen ApplicationName genApplicationName = ApplicationName <$> Gen.text (Range.constant 0 applicationNameMaxLength) Gen.alphaNum genCanonicalProtocolParameters :: Gen ProtocolParameters genCanonicalProtocolParameters = ProtocolParameters <$> genScriptVersion <*> genNatural <*> genNatural <*> genNatural <*> genNatural <*> genNatural <*> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion <*> genSlotNumber <*> genSoftforkRule <*> genCanonicalTxFeePolicy <*> genEpochNumber genProtocolVersion :: Gen ProtocolVersion genProtocolVersion = ProtocolVersion <$> Gen.word16 Range.constantBounded <*> Gen.word16 Range.constantBounded <*> Gen.word8 Range.constantBounded genProtocolParameters :: Gen ProtocolParameters genProtocolParameters = ProtocolParameters <$> genScriptVersion <*> genNatural <*> genNatural <*> genNatural <*> genNatural <*> genNatural <*> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion <*> genSlotNumber <*> genSoftforkRule <*> genTxFeePolicy <*> genEpochNumber genProtocolParametersUpdate :: Gen ProtocolParametersUpdate genProtocolParametersUpdate = ProtocolParametersUpdate <$> Gen.maybe genScriptVersion <*> Gen.maybe genNatural <*> Gen.maybe genNatural <*> Gen.maybe genNatural <*> Gen.maybe genNatural <*> Gen.maybe genNatural <*> Gen.maybe genLovelacePortion <*> Gen.maybe genLovelacePortion <*> Gen.maybe genLovelacePortion <*> Gen.maybe genLovelacePortion <*> Gen.maybe genSlotNumber <*> Gen.maybe genSoftforkRule <*> Gen.maybe genTxFeePolicy <*> Gen.maybe genEpochNumber genSoftforkRule :: Gen SoftforkRule genSoftforkRule = SoftforkRule <$> genLovelacePortion <*> genLovelacePortion <*> genLovelacePortion genSoftwareVersion :: Gen SoftwareVersion genSoftwareVersion = SoftwareVersion <$> genApplicationName <*> Gen.word32 Range.constantBounded genSystemTag :: Gen SystemTag genSystemTag = SystemTag <$> Gen.text (Range.constant 0 systemTagMaxLength) Gen.alphaNum genInstallerHash :: Gen InstallerHash genInstallerHash = InstallerHash <$> genHashRaw genPayload :: ProtocolMagicId -> Gen Payload genPayload pm = payload <$> Gen.maybe (genProposal pm) <*> Gen.list (Range.linear 0 10) (genVote pm) genProof :: ProtocolMagicId -> Gen Proof genProof pm = genAbstractHash (genPayload pm) genProposal :: ProtocolMagicId -> Gen Proposal genProposal pm = unsafeProposal <$> genProposalBody <*> genVerificationKey <*> genSignature pm genProposalBody genProposalBody :: Gen ProposalBody genProposalBody = ProposalBody <$> genProtocolVersion <*> genProtocolParametersUpdate <*> genSoftwareVersion <*> genUpsData genUpId :: ProtocolMagicId -> Gen UpId genUpId pm = genAbstractHash (genProposal pm) genUpsData :: Gen (Map SystemTag InstallerHash) genUpsData = Gen.map (Range.linear 0 20) ((,) <$> genSystemTag <*> genInstallerHash) genVote :: ProtocolMagicId -> Gen Vote genVote pm = mkVote pm <$> genSigningKey <*> genUpId pm <*> Gen.bool genError :: ProtocolMagicId -> Gen Error genError pm = Gen.choice [ Registration <$> genRegistrationError , Voting <$> genVotingError pm , Endorsement <$> genEndorsementError , NumberOfGenesisKeysTooLarge <$> genRegistrationTooLarge ] genRegistrationError :: Gen Registration.Error genRegistrationError = Gen.choice [ Registration.DuplicateProtocolVersion <$> genProtocolVersion , Registration.DuplicateSoftwareVersion <$> genSoftwareVersion , Registration.InvalidProposer <$> genKeyHash , Registration.InvalidProtocolVersion <$> genProtocolVersion <*> (Registration.Adopted <$> genProtocolVersion) , Registration.InvalidScriptVersion <$> genWord16 <*> genWord16 , pure Registration.InvalidSignature , Registration.InvalidSoftwareVersion <$> ( Gen.map (Range.linear 1 20) $ do name <- genApplicationName version <- genWord32 slotNo <- SlotNumber <$> Gen.word64 Range.constantBounded meta <- Gen.map (Range.linear 1 10) $ (,) <$> genSystemTag <*> genInstallerHash pure (name, (Registration.ApplicationVersion version slotNo meta)) ) <*> genSoftwareVersion , Registration.MaxBlockSizeTooLarge <$> (Registration.TooLarge <$> genNatural <*> genNatural) , Registration.MaxTxSizeTooLarge <$> (Registration.TooLarge <$> genNatural <*> genNatural) , pure Registration.ProposalAttributesUnknown , Registration.ProposalTooLarge <$> (Registration.TooLarge <$> genNatural <*> genNatural) , (Registration.SoftwareVersionError . SoftwareVersionApplicationNameError) <$> Gen.choice [ ApplicationNameTooLong <$> Gen.text (Range.linear 0 20) Gen.alphaNum , ApplicationNameNotAscii <$> Gen.text (Range.linear 0 20) Gen.alphaNum ] , Registration.SystemTagError <$> Gen.choice [ SystemTagNotAscii <$> Gen.text (Range.linear 0 20) Gen.alphaNum , SystemTagTooLong <$> Gen.text (Range.linear 0 20) Gen.alphaNum ] ] genVotingError :: ProtocolMagicId -> Gen Voting.Error genVotingError pm = Gen.choice [ pure Voting.VotingInvalidSignature , Voting.VotingProposalNotRegistered <$> genUpId pm , Voting.VotingVoterNotDelegate <$> genKeyHash ] genEndorsementError :: Gen Endorsement.Error genEndorsementError = Endorsement.MultipleProposalsForProtocolVersion <$> genProtocolVersion genRegistrationTooLarge :: Gen (Registration.TooLarge Int) genRegistrationTooLarge = Registration.TooLarge <$> Gen.int Range.constantBounded <*> Gen.int Range.constantBounded
3383b102d4fa2ddcfc9a0c701e317299d97ac3e00c442feaa07320c58e7b191e
jeapostrophe/exp
csv2org.rkt
#lang racket (require (planet neil/csv)) (match-define (list-rest header games) (csv->list (current-input-port))) (define (extend-l l) (append l (build-list (- (length header) (length l)) (λ (i) "")))) (define (mprintf fmt arg) (unless (string=? "" arg) (printf fmt arg))) (printf "* Games\n") (for ([entry (in-list games)]) (match-define (list system year game/en game/jp can-play? last-price paid recv done? comments again? blog?) (extend-l entry)) (printf "** ~a\n" game/en) (printf " :PROPERTIES:\n") (mprintf " :System:\t~a\n" system) (mprintf " :Year:\t~a\n" year) (mprintf " :Completed:\t~a\n" done?) (mprintf " :PlayAgain:\t~a\n" again?) (mprintf " :Reviewed:\t~a\n" blog?) (printf " :END:\n") (mprintf "\n ~a\n\n" comments)) (printf #<<END * Settings #+COLUMNS: %25ITEM %System %Year %Completed %PlayAgain %Reviewed END )
null
https://raw.githubusercontent.com/jeapostrophe/exp/43615110fd0439d2ef940c42629fcdc054c370f9/csv2org.rkt
racket
#lang racket (require (planet neil/csv)) (match-define (list-rest header games) (csv->list (current-input-port))) (define (extend-l l) (append l (build-list (- (length header) (length l)) (λ (i) "")))) (define (mprintf fmt arg) (unless (string=? "" arg) (printf fmt arg))) (printf "* Games\n") (for ([entry (in-list games)]) (match-define (list system year game/en game/jp can-play? last-price paid recv done? comments again? blog?) (extend-l entry)) (printf "** ~a\n" game/en) (printf " :PROPERTIES:\n") (mprintf " :System:\t~a\n" system) (mprintf " :Year:\t~a\n" year) (mprintf " :Completed:\t~a\n" done?) (mprintf " :PlayAgain:\t~a\n" again?) (mprintf " :Reviewed:\t~a\n" blog?) (printf " :END:\n") (mprintf "\n ~a\n\n" comments)) (printf #<<END * Settings #+COLUMNS: %25ITEM %System %Year %Completed %PlayAgain %Reviewed END )
f641d9da3f668da6e8e8250d3315fae62d0995c928c04089ca75f9c6d297c962
CodyReichert/qi
tar.lisp
tar.lisp -- reading and writing tar files from Common Lisp ;;; Yes, perfectly good implementations of tar already exist. However, ;;; there are none for Common Lisp. :) Actually, the main motivation ;;; behind writing this was to eventually provide a TAR-OP or something ;;; similar for ASDF. This would make packaging up systems very easy. ;;; Furthermore, something like asdf-install could use this package as ;;; part of its installation routines. ;;; ;;; Implementation notes: ;;; ;;; Tar archives make ugly conflations between characters and bytes, as ;;; is typical of C programs. This implementation deals strictly with ;;; bytes internally and will only convert to actual strings when the ;;; user requests it. Hooks are provided for the user to customize the ;;; conversion of byte vectors to strings. Bind ;;; *BYTEVEC-TO-STRING-CONVERSION-FUNCTION* or ;;; *STRING-TO-BYTEVEC-CONVERSION-FUNCTION* to use your own custom ;;; conversion functions. The default functions will convert strings as ;;; ASCII (Latin-1, really), which may be good enough for you. ;;; ;;; Bugs almost certainly remain. Regular files are the only archivable ;;; entities at the moment; attempting to back up your /dev directory ;;; with the tools contained herein will be a futile exercise. ;;; The implementation only handles ustar archives ( POSIX circa 1988 or so ) and does not handle pax archives ( POSIX circa 2001 or so ) . This ;;; is a shortcoming that I would like to see fixed, but have not yet ;;; examined what would be necessary to do so. Archive buffer handling ;;; would likely need to be altered somewhat, as the current version is biased towards handling tar files ( fixed records of 512 bytes ) . (in-package :archive) ;;; constants and class definitions (defconstant +tar-n-block-bytes+ 512) ;;; GNU tar makes this configurable, actually. (defconstant +tar-n-record-blocks+ 20) (defconstant +tar-n-record-bytes+ (* +tar-n-block-bytes+ +tar-n-record-blocks+)) ;;; values for tar's `typeflag' field (defconstant +tar-regular-file+ #x30) ;;; backwards compatibility (defconstant +tar-regular-alternate-file+ #x00) (defconstant +tar-hard-link+ #x31) (defconstant +tar-symbolic-link+ #x32) (defconstant +tar-character-device+ #x33) (defconstant +tar-block-device+ #x34) (defconstant +tar-directory-file+ #x35) (defconstant +tar-fifo-device+ #x36) (defconstant +tar-implementation-specific-file+ #x37) (defconstant +posix-extended-header+ #x78) (defconstant +posix-global-header+ #x67) ;;; non-standard typeflags (defconstant +gnutar-long-link-name+ #x4b) (defconstant +gnutar-long-name+ #x4c) (defconstant +gnutar-sparse+ #x53) (defconstant +ascii-space+ #x20) (defconstant +ascii-zero+ #x30) (defconstant +ascii-nine+ #x39) (defconstant +ascii-a+ #x61) (defconstant +ascii-z+ #x7a) (defparameter *tar-magic-vector* (coerce `(,@(map 'list #'char-code "ustar") 0) '(vector (unsigned-byte 8)))) (defparameter *tar-version-vector* (coerce (map 'list #'char-code "00") '(vector (unsigned-byte 8)))) (defclass tar-archive (archive) ()) (defmethod initialize-instance :after ((instance tar-archive) &rest initargs) (declare (ignore initargs)) (initialize-entry-buffer instance +tar-header-length+)) ;;; Conditions (define-condition tar-error (archive-error) () (:documentation "All errors specific to tar archives are of this type.")) (define-condition invalid-tar-checksum-error (tar-error) ((provided :initarg :provided :reader provided) (computed :initarg :computed :reader computed)) (:report (lambda (condition stream) (format stream "Invalid tar header checksum ~D (wanted ~D)" (provided condition) (computed condition)))) (:documentation "Signaled when the checksum in a tar header is invalid.")) (define-condition unhandled-error (tar-error) ((typeflag :initarg :typeflag :reader typeflag)) (:documentation "Signaled when a tar entry that ARCHIVE doesn't understand is encountered.")) (define-condition unhandled-read-header-error (tar-error) () (:report (lambda (condition stream) (let ((flag (typeflag condition))) (cond ((= flag +posix-global-header+) (format stream "Don't understand POSIX extended header entry")) ((= flag +gnutar-sparse+) (format stream "Don't understand GNU tar sparse entry")) (t (format stream "Can't understand typeflag: ~A" flag)))))) (:documentation "Signaled when attempting to parse an unsupported tar entry.")) (define-condition unhandled-extract-entry-error (tar-error) () (:report (lambda (condition stream) (format stream "Don't know how to extract a type ~A tar entry yet" (typeflag condition)))) (:documentation "Signaled when attempting to extract an unsupported tar entry.")) (define-condition unhandled-write-entry-error (tar-error) () (:report (lambda (condition stream) (format stream "Don't know how to write a type ~A tar entry yet" (typeflag condition)))) (:documentation "Signaled when attempting to write an unsupported tar entry.")) ;;; Groveling through tar headers (defun read-number-from-buffer (buffer &key (start 0) end (radix 10)) (declare (type (simple-array (unsigned-byte 8) (*)) buffer)) (declare (type (integer 2 36) radix)) (let ((end (or (position-if #'(lambda (b) ;; For BSD tar, a number can end with ;; a space or a null byte. (or (= b +ascii-space+) (zerop b))) buffer :start start :end end) end (length buffer)))) ;; GNU tar permits storing numbers as binary; a binary number is indicated by starting the field with # x80 . (if (= (aref buffer start) #x80) (loop for i from (1- end) downto (1+ start) for base = 1 then (* base 256) sum (* (aref buffer i) base)) (loop for i from (1- end) downto start for base = 1 then (* base radix) sum (let ((byte (aref buffer i))) (cond ((<= +ascii-zero+ byte +ascii-nine+) (* base (- byte +ascii-zero+))) ((<= +ascii-a+ byte +ascii-z+) (* base (+ 10 (- byte +ascii-a+)))) (t (error "Invalid byte: ~A in ~A" byte (subseq buffer start end))))))))) (defun write-number-to-buffer (number buffer &key (start 0) end (radix 10) nullp) (declare (type (simple-array (unsigned-byte 8) (*)) buffer)) (declare (type (integer 2 36) radix)) (let ((end (let ((dend (or end (length buffer)))) (if nullp (1- dend) dend)))) (loop for i from (1- end) downto start do (multiple-value-bind (quo rem) (truncate number radix) (setf number quo) (setf (aref buffer i) (cond ((<= 0 rem 9) (+ rem +ascii-zero+)) ((<= 10 rem 36) (+ (- rem 10) +ascii-a+)) (t (error "Don't know how to encode ~A" rem)))))) (values))) (defun read-bytevec-from-buffer (buffer &key (start 0) end nullp) (let ((end (if nullp (position 0 buffer :start start :end end) end))) (subseq buffer start end))) ;;; translate from tar's awkward name/prefix fields into something sane (defmethod name ((entry tar-entry)) (let ((prefix (%prefix entry))) (if (or (zerop (length prefix)) (zerop (aref prefix 0))) ; no prefix given (bytevec-to-string (%name entry)) (bytevec-to-string (concatenate '(vector (unsigned-byte 8)) prefix (%name entry)))))) (defmethod (setf name) (value (entry tar-entry)) FIXME : need to handle ` PREFIX ' correctly too . (setf (%name entry) (string-to-bytevec value)) value) (defmethod print-object ((entry tar-entry) stream) (print-unreadable-object (entry stream) (format stream "Tar-Entry ~A" (cond ((slot-boundp entry 'pathname) (namestring (entry-pathname entry))) (t (name entry)))))) (defmethod print-object ((entry tar-longname-entry) stream) (print-unreadable-object (entry stream) (format stream "Tar-Longname-Entry ~A" (cond ((slot-boundp entry 'pathname) (namestring (entry-pathname entry))) (t (name entry)))))) (defmethod entry-regular-file-p ((entry tar-entry)) (eql (typeflag entry) +tar-regular-file+)) (defmethod entry-directory-p ((entry tar-entry)) (eql (typeflag entry) +tar-directory-file+)) (defmethod entry-symbolic-link-p ((entry tar-entry)) (eql (typeflag entry) +tar-symbolic-link+)) (defmethod entry-character-device-p ((entry tar-entry)) (eql (typeflag entry) +tar-character-device+)) (defmethod entry-block-device-p ((entry tar-entry)) (eql (typeflag entry) +tar-block-device+)) (defmethod entry-fifo-p ((entry tar-entry)) (eql (typeflag entry) +tar-fifo-device+)) ;;; archives ;;; internal functions of all kinds (defun round-up-to-tar-block (num) (* (ceiling num +tar-n-block-bytes+) +tar-n-block-bytes+)) (defun tar-checksum-guts (block start transform-fun) (declare (type (simple-array (unsigned-byte 8) (*)) block)) (let ((end (+ start +tar-n-block-bytes+)) (checksum-start (+ start +tar-header-checksum-offset+)) (checksum-end (+ start +tar-header-checksum-offset+ +tar-header-checksum-length+))) (loop for i from start below end sum (if (or (< i checksum-start) (<= checksum-end i)) (funcall transform-fun (aref block i)) +ascii-space+)))) (defun compute-checksum-for-tar-header (block start) (tar-checksum-guts block start #'identity)) (defun compute-old-checksum-for-tar-header (block start) (tar-checksum-guts block start #'(lambda (b) (if (< b 128) b (- b 256))))) (defun tar-block-checksum-matches-p (block checksum start) (let ((sum (compute-checksum-for-tar-header block start))) (if (= sum checksum) t ;; try the older, signed arithmetic way (let ((signed-sum (compute-old-checksum-for-tar-header block start))) (values (= signed-sum checksum) sum))))) (defun null-block-p (block start) (declare (type (simple-array (unsigned-byte 8) (*)) block)) (null (position-if-not #'zerop block :start start :end (+ start +tar-n-block-bytes+)))) (defparameter *modefuns-to-typeflags* (list (cons 'isreg +tar-regular-file+) (cons 'isdir +tar-directory-file+) (cons 'ischarfile +tar-character-device+) (cons 'isblockfile +tar-block-device+) (cons 'isfifo +tar-fifo-device+) (cons 'islink +tar-symbolic-link+))) (defun typeflag-for-mode (mode) (loop for (modefun . typeflag) in *modefuns-to-typeflags* when (funcall modefun mode) do (return-from typeflag-for-mode typeflag) finally (error "No typeflag found for mode ~A" mode))) (defmethod create-entry-from-pathname ((archive tar-archive) pathname) (let ((stat (stat pathname))) (make-instance 'tar-entry :pathname pathname :mode (logand +permissions-mask+ (stat-mode stat)) :typeflag (typeflag-for-mode (stat-mode stat)) :uid (stat-uid stat) :gid (stat-gid stat) :size (stat-size stat) :mtime (stat-mtime stat)))) (defmethod create-entry-from-pathname :around ((archive tar-archive) pathname) (let ((instance (call-next-method))) (when (fad:directory-pathname-p pathname) (change-class instance 'directory-tar-entry)) instance)) (defmethod write-entry-to-archive ((archive tar-archive) (entry tar-entry) &key (stream t)) (let ((namestring (namestring (entry-pathname entry)))) (when (and (>= (length namestring) +tar-header-%name-length+) (zerop (length (%name entry)))) (let ((link-entry (make-instance 'tar-longname-entry :pathname (entry-pathname entry) :%name (convert-string-to-bytevec "././@LongLink") :uname "root" :gname "root" :typeflag +gnutar-long-name+ :size (1+ (length namestring))))) (write-entry-to-archive archive link-entry :stream stream))) (call-next-method))) (defmethod write-entry-data ((archive tar-archive) (entry tar-longname-entry) stream) (declare (ignore stream)) ;; This way is slow and inefficient, but obviously correct. It is also easy to guarantee that we 're writing in 512 - byte blocks . (let* ((namestring (namestring (entry-pathname entry))) (bytename (string-to-bytevec namestring)) (entry-length (round-up-to-tar-block (1+ (length bytename)))) (entry-buffer (make-array entry-length :element-type '(unsigned-byte 8) :initial-element 0))) (replace entry-buffer bytename) (write-sequence entry-buffer (archive-stream archive)) (values))) (defmethod write-entry-to-buffer ((entry tar-entry) buffer &optional (start 0)) (declare (type (simple-array (unsigned-byte 8) (*)) buffer)) ;; ensure a clean slate (assert (<= (+ start +tar-n-block-bytes+) (length buffer))) (fill buffer 0 :start start :end (+ start +tar-n-block-bytes+)) (cond ((> (length (%name entry)) 0) (tar-header-write-%name-to-buffer buffer start (%name entry))) (t (let* ((namestring (namestring (entry-pathname entry))) (bytestring (string-to-bytevec namestring))) (tar-header-write-%name-to-buffer buffer start (subseq bytestring 0 (min (length bytestring) (1- +tar-header-%name-length+))))))) (tar-header-write-mode-to-buffer buffer start (mode entry)) (tar-header-write-uid-to-buffer buffer start (uid entry)) (tar-header-write-gid-to-buffer buffer start (gid entry)) (tar-header-write-magic-to-buffer buffer start *tar-magic-vector*) (tar-header-write-version-to-buffer buffer start *tar-version-vector*) (tar-header-write-size-to-buffer buffer start (size entry)) (tar-header-write-mtime-to-buffer buffer start (mtime entry)) (tar-header-write-typeflag-to-buffer buffer start (typeflag entry)) ;; the checksum is written in a peculiar fashion (let* ((checksum (compute-checksum-for-tar-header buffer start)) (checksum-offset (+ start +tar-header-checksum-offset+))) (write-number-to-buffer checksum buffer :start checksum-offset :end (+ checksum-offset +tar-header-checksum-length+ -2) :radix 8) ;; terminated with a NULL and then a space (!?) (setf (aref buffer (+ checksum-offset 6)) 0 (aref buffer (+ checksum-offset 7)) +ascii-space+))) (defun read-tar-entry-from-buffer (buffer &key (start 0)) (with-extracted-fields (tar-header buffer start %name mode mtime size checksum uid gid magic typeflag uname gname) (multiple-value-bind (validp computed) (tar-block-checksum-matches-p buffer checksum start) (unless validp (error 'invalid-tar-checksum-error :provided checksum :computed computed)) (make-instance 'tar-entry :%name %name :mode mode :mtime mtime :size size :checksum checksum :uid uid :gid gid :magic magic :typeflag typeflag :uname uname :gname gname)))) ;;; buffering data from the archive's stream ;;; ;;; we want to do a couple of different things with buffered data: ;;; ;;; * read entries from the buffered data--requires a specific amount ;;; of data at read time. the data required for this operation is ;;; discarded immediately after use. * read variable - sized data from the buffered data or stream-- ;;; requires a specific amount of data at read time. this data must ;;; persist after reading it from the buffer--displaced arrays could ;;; not be used for this purpose. ;;; * transfer data from the archive's stream/data to another stream ;;; (i.e. processing entry data). (defmethod read-entry-from-archive ((archive tar-archive)) (let ((entry-block (read-entry-block archive))) (if (null-block-p entry-block 0) nil (let ((entry (read-tar-entry-from-buffer entry-block :start 0))) (cond ((= (typeflag entry) +gnutar-long-name+) (let ((real-name (read-data-block archive (size entry) #'round-up-to-tar-block)) (entry (read-entry-from-archive archive))) (setf (%name entry) real-name) entry)) ((= (typeflag entry) +gnutar-long-link-name+) (let ((real-link-name (read-data-block archive (size entry) #'round-up-to-tar-block)) (entry (read-entry-from-archive archive))) (setf (linkname entry) real-link-name) entry)) ((or (= (typeflag entry) +tar-regular-file+) (= (typeflag entry) +tar-directory-file+)) entry) ((= (typeflag entry) +posix-global-header+) ;; FIXME: We should make the information from this ;; available to the user. At the moment, however, most ;; global headers seen in the wild are git stashing a ;; "comment=<sha1>". So just ignore them for now. (let ((global-header (read-data-block archive (size entry) #'round-up-to-tar-block))) (declare (ignore global-header)) (read-entry-from-archive archive))) (t (error 'unhandled-read-header-error :typeflag (typeflag entry)))))))) FIXME : must add permissions handling , , etc . maybe those should ;;; be specified by flags or somesuch? (defmethod extract-entry ((archive tar-archive) (entry tar-entry)) ;; FIXME: this is potentially bogus (let ((name (merge-pathnames (name entry) *default-pathname-defaults*))) (cond ((= (typeflag entry) +tar-directory-file+) (ensure-directories-exist name)) ((= (typeflag entry) +tar-regular-file+) (ensure-directories-exist name) (with-open-file (stream name :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)) (transfer-entry-data-to-stream archive entry stream))) (t (error 'unhandled-extract-entry-error :typeflag (typeflag entry)))))) (defmethod transfer-entry-data-to-stream ((archive tar-archive) (entry tar-entry) stream) (transfer-entry-data-to-stream* archive entry stream #'round-up-to-tar-block)) (defmethod discard-entry ((archive tar-archive) (entry tar-entry)) (discard-unused-entry-data archive entry #'round-up-to-tar-block)) (defun transfer-stream-to-archive (archive stream) (with-slots (file-buffer (archive-stream stream)) archive (do ((bytes-read (read-sequence file-buffer stream) (read-sequence file-buffer stream)) (total-bytes 0 (+ total-bytes bytes-read)) (length (length file-buffer))) ((< bytes-read length) (let* ((rounded-length (round-up-to-tar-block bytes-read)) (total-bytes (+ total-bytes bytes-read)) (rounded-bytes (round-up-to-tar-block total-bytes ))) (fill file-buffer 0 :start bytes-read :end rounded-length) (incf (bytes-output archive) (+ rounded-bytes +tar-header-length+)) (write-sequence file-buffer archive-stream :end rounded-length) (values))) (write-sequence file-buffer archive-stream)))) ;;; writing entries in various guises (defmethod write-entry-to-archive :before ((archive tar-archive) (entry tar-entry) &key stream) (declare (ignore stream)) (unless (member (typeflag entry) (list +tar-regular-file+ +tar-directory-file+ +gnutar-long-name+) :test #'=) (error 'unhandled-write-entry-error :typeflag (typeflag entry)))) (defmethod finalize-archive ((archive tar-archive)) (let ((null-block (make-array +tar-n-record-bytes+ :element-type '(unsigned-byte 8) :initial-element 0))) (declare (dynamic-extent null-block)) (write-sequence null-block (archive-stream archive) :end (* +tar-header-length+ 2)) (incf (bytes-output archive) 1024) (assert (zerop (mod (bytes-output archive) +tar-header-length+))) (multiple-value-bind (multiplier bytes-remaining) (ceiling (bytes-output archive) +tar-n-record-bytes+) (declare (ignore multiplier)) (write-sequence null-block (archive-stream archive) :end (- bytes-remaining)) (values)))) (defun create-tar-file (pathname filelist) (with-open-archive (archive pathname :direction :output :if-exists :supersede) (dolist (file filelist (finalize-archive archive)) (let ((entry (create-entry-from-pathname archive file))) (write-entry-to-archive archive entry)))))
null
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/archive-latest/tar.lisp
lisp
Yes, perfectly good implementations of tar already exist. However, there are none for Common Lisp. :) Actually, the main motivation behind writing this was to eventually provide a TAR-OP or something similar for ASDF. This would make packaging up systems very easy. Furthermore, something like asdf-install could use this package as part of its installation routines. Implementation notes: Tar archives make ugly conflations between characters and bytes, as is typical of C programs. This implementation deals strictly with bytes internally and will only convert to actual strings when the user requests it. Hooks are provided for the user to customize the conversion of byte vectors to strings. Bind *BYTEVEC-TO-STRING-CONVERSION-FUNCTION* or *STRING-TO-BYTEVEC-CONVERSION-FUNCTION* to use your own custom conversion functions. The default functions will convert strings as ASCII (Latin-1, really), which may be good enough for you. Bugs almost certainly remain. Regular files are the only archivable entities at the moment; attempting to back up your /dev directory with the tools contained herein will be a futile exercise. is a shortcoming that I would like to see fixed, but have not yet examined what would be necessary to do so. Archive buffer handling would likely need to be altered somewhat, as the current version is constants and class definitions GNU tar makes this configurable, actually. values for tar's `typeflag' field backwards compatibility non-standard typeflags Conditions Groveling through tar headers For BSD tar, a number can end with a space or a null byte. GNU tar permits storing numbers as binary; a binary number is translate from tar's awkward name/prefix fields into something sane no prefix given archives internal functions of all kinds try the older, signed arithmetic way This way is slow and inefficient, but obviously correct. It is ensure a clean slate the checksum is written in a peculiar fashion terminated with a NULL and then a space (!?) buffering data from the archive's stream we want to do a couple of different things with buffered data: * read entries from the buffered data--requires a specific amount of data at read time. the data required for this operation is discarded immediately after use. requires a specific amount of data at read time. this data must persist after reading it from the buffer--displaced arrays could not be used for this purpose. * transfer data from the archive's stream/data to another stream (i.e. processing entry data). FIXME: We should make the information from this available to the user. At the moment, however, most global headers seen in the wild are git stashing a "comment=<sha1>". So just ignore them for now. be specified by flags or somesuch? FIXME: this is potentially bogus writing entries in various guises
tar.lisp -- reading and writing tar files from Common Lisp The implementation only handles ustar archives ( POSIX circa 1988 or so ) and does not handle pax archives ( POSIX circa 2001 or so ) . This biased towards handling tar files ( fixed records of 512 bytes ) . (in-package :archive) (defconstant +tar-n-block-bytes+ 512) (defconstant +tar-n-record-blocks+ 20) (defconstant +tar-n-record-bytes+ (* +tar-n-block-bytes+ +tar-n-record-blocks+)) (defconstant +tar-regular-file+ #x30) (defconstant +tar-regular-alternate-file+ #x00) (defconstant +tar-hard-link+ #x31) (defconstant +tar-symbolic-link+ #x32) (defconstant +tar-character-device+ #x33) (defconstant +tar-block-device+ #x34) (defconstant +tar-directory-file+ #x35) (defconstant +tar-fifo-device+ #x36) (defconstant +tar-implementation-specific-file+ #x37) (defconstant +posix-extended-header+ #x78) (defconstant +posix-global-header+ #x67) (defconstant +gnutar-long-link-name+ #x4b) (defconstant +gnutar-long-name+ #x4c) (defconstant +gnutar-sparse+ #x53) (defconstant +ascii-space+ #x20) (defconstant +ascii-zero+ #x30) (defconstant +ascii-nine+ #x39) (defconstant +ascii-a+ #x61) (defconstant +ascii-z+ #x7a) (defparameter *tar-magic-vector* (coerce `(,@(map 'list #'char-code "ustar") 0) '(vector (unsigned-byte 8)))) (defparameter *tar-version-vector* (coerce (map 'list #'char-code "00") '(vector (unsigned-byte 8)))) (defclass tar-archive (archive) ()) (defmethod initialize-instance :after ((instance tar-archive) &rest initargs) (declare (ignore initargs)) (initialize-entry-buffer instance +tar-header-length+)) (define-condition tar-error (archive-error) () (:documentation "All errors specific to tar archives are of this type.")) (define-condition invalid-tar-checksum-error (tar-error) ((provided :initarg :provided :reader provided) (computed :initarg :computed :reader computed)) (:report (lambda (condition stream) (format stream "Invalid tar header checksum ~D (wanted ~D)" (provided condition) (computed condition)))) (:documentation "Signaled when the checksum in a tar header is invalid.")) (define-condition unhandled-error (tar-error) ((typeflag :initarg :typeflag :reader typeflag)) (:documentation "Signaled when a tar entry that ARCHIVE doesn't understand is encountered.")) (define-condition unhandled-read-header-error (tar-error) () (:report (lambda (condition stream) (let ((flag (typeflag condition))) (cond ((= flag +posix-global-header+) (format stream "Don't understand POSIX extended header entry")) ((= flag +gnutar-sparse+) (format stream "Don't understand GNU tar sparse entry")) (t (format stream "Can't understand typeflag: ~A" flag)))))) (:documentation "Signaled when attempting to parse an unsupported tar entry.")) (define-condition unhandled-extract-entry-error (tar-error) () (:report (lambda (condition stream) (format stream "Don't know how to extract a type ~A tar entry yet" (typeflag condition)))) (:documentation "Signaled when attempting to extract an unsupported tar entry.")) (define-condition unhandled-write-entry-error (tar-error) () (:report (lambda (condition stream) (format stream "Don't know how to write a type ~A tar entry yet" (typeflag condition)))) (:documentation "Signaled when attempting to write an unsupported tar entry.")) (defun read-number-from-buffer (buffer &key (start 0) end (radix 10)) (declare (type (simple-array (unsigned-byte 8) (*)) buffer)) (declare (type (integer 2 36) radix)) (let ((end (or (position-if #'(lambda (b) (or (= b +ascii-space+) (zerop b))) buffer :start start :end end) end (length buffer)))) indicated by starting the field with # x80 . (if (= (aref buffer start) #x80) (loop for i from (1- end) downto (1+ start) for base = 1 then (* base 256) sum (* (aref buffer i) base)) (loop for i from (1- end) downto start for base = 1 then (* base radix) sum (let ((byte (aref buffer i))) (cond ((<= +ascii-zero+ byte +ascii-nine+) (* base (- byte +ascii-zero+))) ((<= +ascii-a+ byte +ascii-z+) (* base (+ 10 (- byte +ascii-a+)))) (t (error "Invalid byte: ~A in ~A" byte (subseq buffer start end))))))))) (defun write-number-to-buffer (number buffer &key (start 0) end (radix 10) nullp) (declare (type (simple-array (unsigned-byte 8) (*)) buffer)) (declare (type (integer 2 36) radix)) (let ((end (let ((dend (or end (length buffer)))) (if nullp (1- dend) dend)))) (loop for i from (1- end) downto start do (multiple-value-bind (quo rem) (truncate number radix) (setf number quo) (setf (aref buffer i) (cond ((<= 0 rem 9) (+ rem +ascii-zero+)) ((<= 10 rem 36) (+ (- rem 10) +ascii-a+)) (t (error "Don't know how to encode ~A" rem)))))) (values))) (defun read-bytevec-from-buffer (buffer &key (start 0) end nullp) (let ((end (if nullp (position 0 buffer :start start :end end) end))) (subseq buffer start end))) (defmethod name ((entry tar-entry)) (let ((prefix (%prefix entry))) (if (or (zerop (length prefix)) (bytevec-to-string (%name entry)) (bytevec-to-string (concatenate '(vector (unsigned-byte 8)) prefix (%name entry)))))) (defmethod (setf name) (value (entry tar-entry)) FIXME : need to handle ` PREFIX ' correctly too . (setf (%name entry) (string-to-bytevec value)) value) (defmethod print-object ((entry tar-entry) stream) (print-unreadable-object (entry stream) (format stream "Tar-Entry ~A" (cond ((slot-boundp entry 'pathname) (namestring (entry-pathname entry))) (t (name entry)))))) (defmethod print-object ((entry tar-longname-entry) stream) (print-unreadable-object (entry stream) (format stream "Tar-Longname-Entry ~A" (cond ((slot-boundp entry 'pathname) (namestring (entry-pathname entry))) (t (name entry)))))) (defmethod entry-regular-file-p ((entry tar-entry)) (eql (typeflag entry) +tar-regular-file+)) (defmethod entry-directory-p ((entry tar-entry)) (eql (typeflag entry) +tar-directory-file+)) (defmethod entry-symbolic-link-p ((entry tar-entry)) (eql (typeflag entry) +tar-symbolic-link+)) (defmethod entry-character-device-p ((entry tar-entry)) (eql (typeflag entry) +tar-character-device+)) (defmethod entry-block-device-p ((entry tar-entry)) (eql (typeflag entry) +tar-block-device+)) (defmethod entry-fifo-p ((entry tar-entry)) (eql (typeflag entry) +tar-fifo-device+)) (defun round-up-to-tar-block (num) (* (ceiling num +tar-n-block-bytes+) +tar-n-block-bytes+)) (defun tar-checksum-guts (block start transform-fun) (declare (type (simple-array (unsigned-byte 8) (*)) block)) (let ((end (+ start +tar-n-block-bytes+)) (checksum-start (+ start +tar-header-checksum-offset+)) (checksum-end (+ start +tar-header-checksum-offset+ +tar-header-checksum-length+))) (loop for i from start below end sum (if (or (< i checksum-start) (<= checksum-end i)) (funcall transform-fun (aref block i)) +ascii-space+)))) (defun compute-checksum-for-tar-header (block start) (tar-checksum-guts block start #'identity)) (defun compute-old-checksum-for-tar-header (block start) (tar-checksum-guts block start #'(lambda (b) (if (< b 128) b (- b 256))))) (defun tar-block-checksum-matches-p (block checksum start) (let ((sum (compute-checksum-for-tar-header block start))) (if (= sum checksum) t (let ((signed-sum (compute-old-checksum-for-tar-header block start))) (values (= signed-sum checksum) sum))))) (defun null-block-p (block start) (declare (type (simple-array (unsigned-byte 8) (*)) block)) (null (position-if-not #'zerop block :start start :end (+ start +tar-n-block-bytes+)))) (defparameter *modefuns-to-typeflags* (list (cons 'isreg +tar-regular-file+) (cons 'isdir +tar-directory-file+) (cons 'ischarfile +tar-character-device+) (cons 'isblockfile +tar-block-device+) (cons 'isfifo +tar-fifo-device+) (cons 'islink +tar-symbolic-link+))) (defun typeflag-for-mode (mode) (loop for (modefun . typeflag) in *modefuns-to-typeflags* when (funcall modefun mode) do (return-from typeflag-for-mode typeflag) finally (error "No typeflag found for mode ~A" mode))) (defmethod create-entry-from-pathname ((archive tar-archive) pathname) (let ((stat (stat pathname))) (make-instance 'tar-entry :pathname pathname :mode (logand +permissions-mask+ (stat-mode stat)) :typeflag (typeflag-for-mode (stat-mode stat)) :uid (stat-uid stat) :gid (stat-gid stat) :size (stat-size stat) :mtime (stat-mtime stat)))) (defmethod create-entry-from-pathname :around ((archive tar-archive) pathname) (let ((instance (call-next-method))) (when (fad:directory-pathname-p pathname) (change-class instance 'directory-tar-entry)) instance)) (defmethod write-entry-to-archive ((archive tar-archive) (entry tar-entry) &key (stream t)) (let ((namestring (namestring (entry-pathname entry)))) (when (and (>= (length namestring) +tar-header-%name-length+) (zerop (length (%name entry)))) (let ((link-entry (make-instance 'tar-longname-entry :pathname (entry-pathname entry) :%name (convert-string-to-bytevec "././@LongLink") :uname "root" :gname "root" :typeflag +gnutar-long-name+ :size (1+ (length namestring))))) (write-entry-to-archive archive link-entry :stream stream))) (call-next-method))) (defmethod write-entry-data ((archive tar-archive) (entry tar-longname-entry) stream) (declare (ignore stream)) also easy to guarantee that we 're writing in 512 - byte blocks . (let* ((namestring (namestring (entry-pathname entry))) (bytename (string-to-bytevec namestring)) (entry-length (round-up-to-tar-block (1+ (length bytename)))) (entry-buffer (make-array entry-length :element-type '(unsigned-byte 8) :initial-element 0))) (replace entry-buffer bytename) (write-sequence entry-buffer (archive-stream archive)) (values))) (defmethod write-entry-to-buffer ((entry tar-entry) buffer &optional (start 0)) (declare (type (simple-array (unsigned-byte 8) (*)) buffer)) (assert (<= (+ start +tar-n-block-bytes+) (length buffer))) (fill buffer 0 :start start :end (+ start +tar-n-block-bytes+)) (cond ((> (length (%name entry)) 0) (tar-header-write-%name-to-buffer buffer start (%name entry))) (t (let* ((namestring (namestring (entry-pathname entry))) (bytestring (string-to-bytevec namestring))) (tar-header-write-%name-to-buffer buffer start (subseq bytestring 0 (min (length bytestring) (1- +tar-header-%name-length+))))))) (tar-header-write-mode-to-buffer buffer start (mode entry)) (tar-header-write-uid-to-buffer buffer start (uid entry)) (tar-header-write-gid-to-buffer buffer start (gid entry)) (tar-header-write-magic-to-buffer buffer start *tar-magic-vector*) (tar-header-write-version-to-buffer buffer start *tar-version-vector*) (tar-header-write-size-to-buffer buffer start (size entry)) (tar-header-write-mtime-to-buffer buffer start (mtime entry)) (tar-header-write-typeflag-to-buffer buffer start (typeflag entry)) (let* ((checksum (compute-checksum-for-tar-header buffer start)) (checksum-offset (+ start +tar-header-checksum-offset+))) (write-number-to-buffer checksum buffer :start checksum-offset :end (+ checksum-offset +tar-header-checksum-length+ -2) :radix 8) (setf (aref buffer (+ checksum-offset 6)) 0 (aref buffer (+ checksum-offset 7)) +ascii-space+))) (defun read-tar-entry-from-buffer (buffer &key (start 0)) (with-extracted-fields (tar-header buffer start %name mode mtime size checksum uid gid magic typeflag uname gname) (multiple-value-bind (validp computed) (tar-block-checksum-matches-p buffer checksum start) (unless validp (error 'invalid-tar-checksum-error :provided checksum :computed computed)) (make-instance 'tar-entry :%name %name :mode mode :mtime mtime :size size :checksum checksum :uid uid :gid gid :magic magic :typeflag typeflag :uname uname :gname gname)))) * read variable - sized data from the buffered data or stream-- (defmethod read-entry-from-archive ((archive tar-archive)) (let ((entry-block (read-entry-block archive))) (if (null-block-p entry-block 0) nil (let ((entry (read-tar-entry-from-buffer entry-block :start 0))) (cond ((= (typeflag entry) +gnutar-long-name+) (let ((real-name (read-data-block archive (size entry) #'round-up-to-tar-block)) (entry (read-entry-from-archive archive))) (setf (%name entry) real-name) entry)) ((= (typeflag entry) +gnutar-long-link-name+) (let ((real-link-name (read-data-block archive (size entry) #'round-up-to-tar-block)) (entry (read-entry-from-archive archive))) (setf (linkname entry) real-link-name) entry)) ((or (= (typeflag entry) +tar-regular-file+) (= (typeflag entry) +tar-directory-file+)) entry) ((= (typeflag entry) +posix-global-header+) (let ((global-header (read-data-block archive (size entry) #'round-up-to-tar-block))) (declare (ignore global-header)) (read-entry-from-archive archive))) (t (error 'unhandled-read-header-error :typeflag (typeflag entry)))))))) FIXME : must add permissions handling , , etc . maybe those should (defmethod extract-entry ((archive tar-archive) (entry tar-entry)) (let ((name (merge-pathnames (name entry) *default-pathname-defaults*))) (cond ((= (typeflag entry) +tar-directory-file+) (ensure-directories-exist name)) ((= (typeflag entry) +tar-regular-file+) (ensure-directories-exist name) (with-open-file (stream name :direction :output :if-exists :supersede :element-type '(unsigned-byte 8)) (transfer-entry-data-to-stream archive entry stream))) (t (error 'unhandled-extract-entry-error :typeflag (typeflag entry)))))) (defmethod transfer-entry-data-to-stream ((archive tar-archive) (entry tar-entry) stream) (transfer-entry-data-to-stream* archive entry stream #'round-up-to-tar-block)) (defmethod discard-entry ((archive tar-archive) (entry tar-entry)) (discard-unused-entry-data archive entry #'round-up-to-tar-block)) (defun transfer-stream-to-archive (archive stream) (with-slots (file-buffer (archive-stream stream)) archive (do ((bytes-read (read-sequence file-buffer stream) (read-sequence file-buffer stream)) (total-bytes 0 (+ total-bytes bytes-read)) (length (length file-buffer))) ((< bytes-read length) (let* ((rounded-length (round-up-to-tar-block bytes-read)) (total-bytes (+ total-bytes bytes-read)) (rounded-bytes (round-up-to-tar-block total-bytes ))) (fill file-buffer 0 :start bytes-read :end rounded-length) (incf (bytes-output archive) (+ rounded-bytes +tar-header-length+)) (write-sequence file-buffer archive-stream :end rounded-length) (values))) (write-sequence file-buffer archive-stream)))) (defmethod write-entry-to-archive :before ((archive tar-archive) (entry tar-entry) &key stream) (declare (ignore stream)) (unless (member (typeflag entry) (list +tar-regular-file+ +tar-directory-file+ +gnutar-long-name+) :test #'=) (error 'unhandled-write-entry-error :typeflag (typeflag entry)))) (defmethod finalize-archive ((archive tar-archive)) (let ((null-block (make-array +tar-n-record-bytes+ :element-type '(unsigned-byte 8) :initial-element 0))) (declare (dynamic-extent null-block)) (write-sequence null-block (archive-stream archive) :end (* +tar-header-length+ 2)) (incf (bytes-output archive) 1024) (assert (zerop (mod (bytes-output archive) +tar-header-length+))) (multiple-value-bind (multiplier bytes-remaining) (ceiling (bytes-output archive) +tar-n-record-bytes+) (declare (ignore multiplier)) (write-sequence null-block (archive-stream archive) :end (- bytes-remaining)) (values)))) (defun create-tar-file (pathname filelist) (with-open-archive (archive pathname :direction :output :if-exists :supersede) (dolist (file filelist (finalize-archive archive)) (let ((entry (create-entry-from-pathname archive file))) (write-entry-to-archive archive entry)))))
d0fd5c2238128441a6a2cf115eaa285c8aadf18821ea18707c4ee7062ec3025b
SimulaVR/godot-haskell
JavaScript.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.JavaScript (Godot.Core.JavaScript.eval) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Object() # NOINLINE bindJavaScript_eval # | Execute the string @code@ as JavaScript code within the browser window . This is a call to the actual global JavaScript function @eval()@. If @use_global_execution_context@ is @true@ , the code will be evaluated in the global execution context . Otherwise , it is evaluated in the execution context of a function within the engine 's runtime environment . bindJavaScript_eval :: MethodBind bindJavaScript_eval = unsafePerformIO $ withCString "JavaScript" $ \ clsNamePtr -> withCString "eval" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Execute the string @code@ as JavaScript code within the browser window . This is a call to the actual global JavaScript function @eval()@. If @use_global_execution_context@ is @true@ , the code will be evaluated in the global execution context . Otherwise , it is evaluated in the execution context of a function within the engine 's runtime environment . eval :: (JavaScript :< cls, Object :< cls) => cls -> GodotString -> Maybe Bool -> IO GodotVariant eval cls arg1 arg2 = withVariantArray [toVariant arg1, maybe (VariantBool False) toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindJavaScript_eval (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod JavaScript "eval" '[GodotString, Maybe Bool] (IO GodotVariant) where nodeMethod = Godot.Core.JavaScript.eval
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/JavaScript.hs
haskell
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.JavaScript (Godot.Core.JavaScript.eval) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Object() # NOINLINE bindJavaScript_eval # | Execute the string @code@ as JavaScript code within the browser window . This is a call to the actual global JavaScript function @eval()@. If @use_global_execution_context@ is @true@ , the code will be evaluated in the global execution context . Otherwise , it is evaluated in the execution context of a function within the engine 's runtime environment . bindJavaScript_eval :: MethodBind bindJavaScript_eval = unsafePerformIO $ withCString "JavaScript" $ \ clsNamePtr -> withCString "eval" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Execute the string @code@ as JavaScript code within the browser window . This is a call to the actual global JavaScript function @eval()@. If @use_global_execution_context@ is @true@ , the code will be evaluated in the global execution context . Otherwise , it is evaluated in the execution context of a function within the engine 's runtime environment . eval :: (JavaScript :< cls, Object :< cls) => cls -> GodotString -> Maybe Bool -> IO GodotVariant eval cls arg1 arg2 = withVariantArray [toVariant arg1, maybe (VariantBool False) toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindJavaScript_eval (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod JavaScript "eval" '[GodotString, Maybe Bool] (IO GodotVariant) where nodeMethod = Godot.Core.JavaScript.eval
72b530a2e7969c7a1a6585cf19e0d4180678acf05320dd8b3c6bbf80ab02c103
goblint/analyzer
observerAnalysis.ml
open Prelude.Ana open Analyses open MyCFG module type StepObserverAutomaton = ObserverAutomaton.S with type t = node * node (* TODO: instead of multiple observer analyses, use single list-domained observer analysis? *) let get_fresh_spec_id = let fresh_id = ref 0 in fun () -> let return_id = !fresh_id in fresh_id := return_id + 1; return_id (* TODO: relax q type *) module MakeSpec (Automaton: StepObserverAutomaton with type q = int) : Analyses.MCPSpec = struct include Analyses.DefaultSpec let id = get_fresh_spec_id () let name () = "observer" ^ string_of_int id module ChainParams = struct (* let n = List.length Arg.path *) let n () = -1 let names x = "state " ^ string_of_int x end module D = Lattice.Flat (Printable.Chain (ChainParams)) (Printable.DefaultNames) module C = D let should_join x y = D.equal x y (* fully path-sensitive *) let step d prev_node node = match d with | `Lifted q -> begin let q' = Automaton.next q (prev_node, node) in if Automaton.accepting q' then raise Deadcode else `Lifted q' end | _ -> d let step_ctx ctx = step ctx.local ctx.prev_node ctx.node (* transfer functions *) let assign ctx (lval:lval) (rval:exp) : D.t = step_ctx ctx let vdecl ctx (_:varinfo) : D.t = step_ctx ctx let branch ctx (exp:exp) (tv:bool) : D.t = step_ctx ctx let body ctx (f:fundec) : D.t = step_ctx ctx let return ctx (exp:exp option) (f:fundec) : D.t = step_ctx ctx let enter ctx (lval: lval option) (f:fundec) (args:exp list) : (D.t * D.t) list = (* ctx.local doesn't matter here? *) [ctx.local, step ctx.local ctx.prev_node (FunctionEntry f)] let combine ctx (lval:lval option) fexp (f:fundec) (args:exp list) fc (au:D.t) (f_ask: Queries.ask) : D.t = step au (Function f) ctx.node let special ctx (lval: lval option) (f:varinfo) (arglist:exp list) : D.t = step_ctx ctx let startstate v = `Lifted Automaton.initial let threadenter ctx lval f args = [D.top ()] let threadspawn ctx lval f args fctx = ctx.local let exitstate v = D.top () end module type PathArg = sig val path: (node * node) list end module MakePathSpec (Arg: PathArg) : Analyses.MCPSpec = struct module KMP = ObserverAutomaton.KMP ( struct type t = Node.t * Node.t [@@deriving eq] let pattern = Array.of_list Arg.path end ) include MakeSpec (KMP) let ( ) = Arg.path | > List.map ( fun ( p , n ) - > Printf.sprintf " ( % d , % d ) " p n ) | > String.concat " ; " | > Printf.printf " observer path : [ % s]\n " |> List.map (fun (p, n) -> Printf.sprintf "(%d, %d)" p n) |> String.concat "; " |> Printf.printf "observer path: [%s]\n" *) end let _ = let module Spec = MakeSpec ( struct ( * let path = [ ( 23 , 24 ) ; ( 24 , 25 ) ] let module Spec = MakeSpec ( struct (* let path = [(23, 24); (24, 25)] *) let path = [ ( 30 , 32 ) ; ( 32 , 34 ) ; ( 34 , 26 ) ; ( 26 , 29 ) ] junker , nofun , no - SV , observer 1 let path = [ ( 1 , 2 ) ; ( 2 , 6 ) ; ( 6 , 8) ; ( 8 , 10 ) ] junker , nofun , SV , observer 1 let path = [ ( 17 , 18 ) ; ( 18 , 22 ) ; ( 22 , 24 ) ; ( 24 , 26 ) ] junker , observer 3 let path = [ ( 14 , 16 ) ; ( 16 , 18 ) ; ( 18 , 10 ) ; ( 10 , 13 ) ] junker , SV , observer 3 let path = [ ( 30 , 32 ) ; ( 32 , 34 ) ; ( 34 , 26 ) ; ( 26 , 29 ) ] FSE15 , nofun , swapped a let path = [ ( 20 , 22 ) ; ( 22 , 24 ) ; ( 24 , 28 ) ; ( 28 , 29 ) ; ( 29 , 30 ) ; ( 30 , 32 ) ] (* path_nofun *) let path = [ ( 20 , 21 ) ; ( 21 , 25 ) ; ( 25 , 27 ) ] let path = [(23, 24); (24, 25); (25, 27)] end ) in MCP.register_analysis (module Spec) *)
null
https://raw.githubusercontent.com/goblint/analyzer/3fc209f2b3bdcc44c40e3c30053a2fa64368ff2e/src/witness/observerAnalysis.ml
ocaml
TODO: instead of multiple observer analyses, use single list-domained observer analysis? TODO: relax q type let n = List.length Arg.path fully path-sensitive transfer functions ctx.local doesn't matter here? let path = [(23, 24); (24, 25)] path_nofun
open Prelude.Ana open Analyses open MyCFG module type StepObserverAutomaton = ObserverAutomaton.S with type t = node * node let get_fresh_spec_id = let fresh_id = ref 0 in fun () -> let return_id = !fresh_id in fresh_id := return_id + 1; return_id module MakeSpec (Automaton: StepObserverAutomaton with type q = int) : Analyses.MCPSpec = struct include Analyses.DefaultSpec let id = get_fresh_spec_id () let name () = "observer" ^ string_of_int id module ChainParams = struct let n () = -1 let names x = "state " ^ string_of_int x end module D = Lattice.Flat (Printable.Chain (ChainParams)) (Printable.DefaultNames) module C = D let step d prev_node node = match d with | `Lifted q -> begin let q' = Automaton.next q (prev_node, node) in if Automaton.accepting q' then raise Deadcode else `Lifted q' end | _ -> d let step_ctx ctx = step ctx.local ctx.prev_node ctx.node let assign ctx (lval:lval) (rval:exp) : D.t = step_ctx ctx let vdecl ctx (_:varinfo) : D.t = step_ctx ctx let branch ctx (exp:exp) (tv:bool) : D.t = step_ctx ctx let body ctx (f:fundec) : D.t = step_ctx ctx let return ctx (exp:exp option) (f:fundec) : D.t = step_ctx ctx let enter ctx (lval: lval option) (f:fundec) (args:exp list) : (D.t * D.t) list = [ctx.local, step ctx.local ctx.prev_node (FunctionEntry f)] let combine ctx (lval:lval option) fexp (f:fundec) (args:exp list) fc (au:D.t) (f_ask: Queries.ask) : D.t = step au (Function f) ctx.node let special ctx (lval: lval option) (f:varinfo) (arglist:exp list) : D.t = step_ctx ctx let startstate v = `Lifted Automaton.initial let threadenter ctx lval f args = [D.top ()] let threadspawn ctx lval f args fctx = ctx.local let exitstate v = D.top () end module type PathArg = sig val path: (node * node) list end module MakePathSpec (Arg: PathArg) : Analyses.MCPSpec = struct module KMP = ObserverAutomaton.KMP ( struct type t = Node.t * Node.t [@@deriving eq] let pattern = Array.of_list Arg.path end ) include MakeSpec (KMP) let ( ) = Arg.path | > List.map ( fun ( p , n ) - > Printf.sprintf " ( % d , % d ) " p n ) | > String.concat " ; " | > Printf.printf " observer path : [ % s]\n " |> List.map (fun (p, n) -> Printf.sprintf "(%d, %d)" p n) |> String.concat "; " |> Printf.printf "observer path: [%s]\n" *) end let _ = let module Spec = MakeSpec ( struct ( * let path = [ ( 23 , 24 ) ; ( 24 , 25 ) ] let module Spec = MakeSpec ( struct let path = [ ( 30 , 32 ) ; ( 32 , 34 ) ; ( 34 , 26 ) ; ( 26 , 29 ) ] junker , nofun , no - SV , observer 1 let path = [ ( 1 , 2 ) ; ( 2 , 6 ) ; ( 6 , 8) ; ( 8 , 10 ) ] junker , nofun , SV , observer 1 let path = [ ( 17 , 18 ) ; ( 18 , 22 ) ; ( 22 , 24 ) ; ( 24 , 26 ) ] junker , observer 3 let path = [ ( 14 , 16 ) ; ( 16 , 18 ) ; ( 18 , 10 ) ; ( 10 , 13 ) ] junker , SV , observer 3 let path = [ ( 30 , 32 ) ; ( 32 , 34 ) ; ( 34 , 26 ) ; ( 26 , 29 ) ] FSE15 , nofun , swapped a let path = [ ( 20 , 22 ) ; ( 22 , 24 ) ; ( 24 , 28 ) ; ( 28 , 29 ) ; ( 29 , 30 ) ; ( 30 , 32 ) ] let path = [ ( 20 , 21 ) ; ( 21 , 25 ) ; ( 25 , 27 ) ] let path = [(23, 24); (24, 25); (25, 27)] end ) in MCP.register_analysis (module Spec) *)
31917ab2e6dc3ca8a5fe551532154ed313c73ca2fb0c15ff9371eaeb6cff19a7
qiao/sicp-solutions
3.72.scm
(define (weight pair) (+ (square (car pair)) (square (cadr pair)))) (define pairs (weighted-pairs integers integers weight)) (define numbers (stream-map weight pairs)) (define (filter-numbers s) (let* ((x (stream-car s)) (y (stream-car (stream-car s))) (z (stream-car (stream-car (stream-car s))))) (if (= x y z) (cons-stream x (filter-numbers (stream-cdr (stream-cdr (stream-cdr s))))) (filter-numbers (stream-cdr s))))) (define the-numbers (filter-numbers numbers))
null
https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter3/3.72.scm
scheme
(define (weight pair) (+ (square (car pair)) (square (cadr pair)))) (define pairs (weighted-pairs integers integers weight)) (define numbers (stream-map weight pairs)) (define (filter-numbers s) (let* ((x (stream-car s)) (y (stream-car (stream-car s))) (z (stream-car (stream-car (stream-car s))))) (if (= x y z) (cons-stream x (filter-numbers (stream-cdr (stream-cdr (stream-cdr s))))) (filter-numbers (stream-cdr s))))) (define the-numbers (filter-numbers numbers))
4f62227b3d3199b15c26390c8d3f2825b0686438764f7fc5d2de64043a27e642
lexi-lambda/freer-simple
Loop.hs
module Tests.Loop (tests) where import Control.Concurrent (forkIO, killThread) import Control.Concurrent.QSemN (newQSemN, signalQSemN, waitQSemN) import Control.Monad (forever) import Data.Function (fix) import Test.Tasty (TestTree, localOption, mkTimeout, testGroup) import Test.Tasty.HUnit (testCase) import Control.Monad.Freer (Eff, Member, runM, send) tests :: TestTree tests = localOption timeout $ testGroup "Loop tests" [ testCase "fix loop" $ testLoop fixLoop , testCase "tail loop" $ testLoop tailLoop , testCase "forever loop" $ testLoop foreverLoop ] where timeout = mkTimeout 1000000 testLoop :: (IO () -> Eff '[IO] ()) -> IO () testLoop loop = do s <- newQSemN 0 t <- forkIO . runM . loop $ signalQSemN s 1 waitQSemN s 5 killThread t fixLoop :: Member IO r => IO () -> Eff r () fixLoop action = fix $ \fxLoop -> do send action fxLoop tailLoop :: Member IO r => IO () -> Eff r () tailLoop action = let loop = send action *> loop in loop foreverLoop :: Member IO r => IO () -> Eff r () foreverLoop action = forever $ send action
null
https://raw.githubusercontent.com/lexi-lambda/freer-simple/e5ef0fec4a79585f99c0df8bc9e2e67cc0c0fb4a/tests/Tests/Loop.hs
haskell
module Tests.Loop (tests) where import Control.Concurrent (forkIO, killThread) import Control.Concurrent.QSemN (newQSemN, signalQSemN, waitQSemN) import Control.Monad (forever) import Data.Function (fix) import Test.Tasty (TestTree, localOption, mkTimeout, testGroup) import Test.Tasty.HUnit (testCase) import Control.Monad.Freer (Eff, Member, runM, send) tests :: TestTree tests = localOption timeout $ testGroup "Loop tests" [ testCase "fix loop" $ testLoop fixLoop , testCase "tail loop" $ testLoop tailLoop , testCase "forever loop" $ testLoop foreverLoop ] where timeout = mkTimeout 1000000 testLoop :: (IO () -> Eff '[IO] ()) -> IO () testLoop loop = do s <- newQSemN 0 t <- forkIO . runM . loop $ signalQSemN s 1 waitQSemN s 5 killThread t fixLoop :: Member IO r => IO () -> Eff r () fixLoop action = fix $ \fxLoop -> do send action fxLoop tailLoop :: Member IO r => IO () -> Eff r () tailLoop action = let loop = send action *> loop in loop foreverLoop :: Member IO r => IO () -> Eff r () foreverLoop action = forever $ send action
ae4d427add28ff033438bac7af2814101783939e3248cdfe311685ddc2aeca8a
herd/herdtools7
interpreter.ml
(****************************************************************************) (* the diy toolsuite *) (* *) , University College London , UK . , INRIA Paris - Rocquencourt , France . (* *) Copyright 2013 - present Institut National de Recherche en Informatique et (* en Automatique and the authors. All rights reserved. *) (* *) This software is governed by the CeCILL - B license under French law and (* abiding by the rules of distribution of free software. You can use, *) modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . (****************************************************************************) (** Interpreter for a user-specified model *) open Printf module type Config = sig val m : AST.t val bell : bool (* executing bell file *) name of bell file if present Restricted Model . Config val showsome : bool val debug : bool val debug_files : bool val verbose : int val skipchecks : StringSet.t val strictskip : bool val cycles : StringSet.t val compat : bool (* Show control *) val doshow : StringSet.t val showraw : StringSet.t val symetric : StringSet.t (* find files *) val libfind : string -> string (* check variant *) val variant : string -> bool end (* Simplified Sem module. In effect, the interpreter needs a restricted subset of Sem functionalities: set of events, relation on events and that is about all. A few utilities are passed as the next "U" argument to functor. *) module type SimplifiedSem = sig module E : sig type event val event_compare : event -> event -> int val pp_eiid : event -> string val pp_instance : event -> string val is_store : event -> bool val is_pt : event -> bool module EventSet : MySet.S with type elt = event module EventRel : InnerRel.S with type elt0 = event and module Elts = EventSet module EventMap : MyMap.S with type key = event end type test type concrete type event = E.event type event_set = E.EventSet.t type event_rel = E.EventRel.t type rel_pp = (string * event_rel) list type set_pp = event_set StringMap.t end module Make (O:Config) (S:SimplifiedSem) (U: sig val partition_events : S.event_set -> S.event_set list val loc2events : string -> S.event_set -> S.event_set val check_through : bool -> bool val pp_failure : S.test -> S.concrete -> string -> S.rel_pp -> unit val pp : S.test -> S.concrete -> string -> S.rel_pp -> unit val fromto : S.event_rel -> (* po *) S.event_set (* labelled fence(s) *) -> S.event_rel (* localised fence relation *) val same_value : S.event -> S.event -> bool val same_oa : S.event -> S.event -> bool val writable2 : S.event -> S.event -> bool end) : sig (* Some constants passed to the interpreter, made open for the convenience of building them from outside *) type ks = { id : S.event_rel Lazy.t; unv : S.event_rel Lazy.t; evts : S.event_set; conc : S.concrete; po:S.event_rel;} (* Initial environment, they differ from internal env, so as not to expose the polymorphic argument of the later *) type init_env val init_env_empty : init_env val add_rels : init_env -> S.event_rel Lazy.t Misc.Simple.bds -> init_env val add_sets : init_env -> S.event_set Lazy.t Misc.Simple.bds -> init_env val get_set : init_env -> string -> S.event_set Lazy.t option (* Subset of interpreter state used by the caller *) type st_out = { out_show : S.rel_pp Lazy.t ; out_sets : S.set_pp Lazy.t ; out_skipped : StringSet.t ; out_flags : Flag.Set.t ; out_bell_info : BellModel.info ; } (* Interpreter *) val interpret : S.test -> ('a -> 'a) -> ks -> init_env -> S.rel_pp Lazy.t -> (st_out -> 'a -> 'a) -> 'a -> 'a end = struct let _dbg = false let () = if _dbg then match O.bell_fname with | None -> eprintf "Interpret has no bell file\n" | Some fname -> eprintf "Interpret bell file is %s\n" fname let next_id = let id = ref 0 in fun () -> let r = !id in id := r+1 ; r (****************************) (* Convenient abbreviations *) (****************************) module E = S.E module W = Warn.Make(O) (* Add relations amongst event classes, notice that a class is an event set, regardless of class disjointness *) module ClassRel = InnerRel.Make(E.EventSet) (* Check utilities *) open AST let skip_this_check name = match name with | Some name -> StringSet.mem name O.skipchecks | None -> false let cycle_this_check name = match name with | Some name -> StringSet.mem name O.cycles | None -> false let check_through test_type ok = match test_type with | Check -> U.check_through ok | UndefinedUnless|Flagged|Assert -> ok (* Model interpret *) let (_,_,mprog) = O.m (* Debug printing *) let _debug_proc chan p = fprintf chan "%i" p let debug_event chan e = fprintf chan "%s" (E.pp_eiid e) let debug_set chan s = output_char chan '{' ; E.EventSet.pp chan "," debug_event s ; output_char chan '}' let debug_rel chan r = E.EventRel.pp chan "," (fun chan (e1,e2) -> fprintf chan "%a -> %a" debug_event e1 debug_event e2) r let debug_class_rel chan r = ClassRel.pp chan "," (fun chan (e1,e2) -> fprintf chan "%a -> %a" debug_set e1 debug_set e2) r type ks = { id : S.event_rel Lazy.t; unv : S.event_rel Lazy.t; evts : S.event_set; conc : S.concrete; po:S.event_rel; } (* Internal typing *) type typ = | TEmpty | TEvent | TEvents | TPair | TRel | TClassRel | TTag of string |TClo | TProc | TSet of typ | TTuple of typ list let rec eq_type t1 t2 = match t1,t2 with | (TEmpty,(TSet _ as t)) | ((TSet _ as t),TEmpty) -> Some t | (TEvents,TEvents) | (TEmpty,TEvents) | (TEvents,TEmpty) -> Some TEvents | (TRel,TRel) | (TEmpty,TRel) | (TRel,TEmpty) -> Some TRel | (TClassRel,TClassRel) | (TEmpty,TClassRel) | (TClassRel,TEmpty) -> Some TClassRel | TEvent,TEvent -> Some TEvent | TPair,TPair -> Some TPair | TTag s1,TTag s2 when s1 = s2 -> Some t1 | TSet t1,TSet t2 -> begin match eq_type t1 t2 with | None -> None | Some t -> Some (TSet t) end | TTuple ts1,TTuple ts2 -> Misc.app_opt (fun ts -> TTuple ts) (eq_types ts1 ts2) | TClo,TClo -> Some TClo | TProc,TProc -> Some TProc | _,_ -> None and eq_types ts1 ts2 = match ts1,ts2 with | [],[] -> Some [] | ([],_::_)|(_::_,[]) -> None | t1::ts1,t2::ts2 -> begin let ts = eq_types ts1 ts2 and t = eq_type t1 t2 in match t,ts with | Some t,Some ts -> Some (t::ts) | _,_ -> None end let type_equal t1 t2 = match eq_type t1 t2 with | None -> false | Some _ -> true exception CompError of string exception PrimError of string let rec pp_typ = function | TEmpty -> "{}" | TEvent -> "event" | TEvents -> "events" | TPair -> "pair" | TRel -> "rel" | TClassRel -> "classrel" | TTag ty -> ty | TClo -> "closure" | TProc -> "procedure" | TSet elt -> sprintf "%s set" (pp_typ elt) | TTuple ts -> sprintf "(%s)" (String.concat " * " (List.map pp_typ ts)) module rec V : sig type v = | Empty | Unv | Pair of (S.event * S.event) | Rel of S.event_rel | ClassRel of ClassRel.t | Event of S.event | Set of S.event_set | Clo of closure | Prim of string * int * (v -> v) | Proc of procedure | Tag of string * string (* type X name *) | ValSet of typ * ValSet.t (* elt type X set *) | Tuple of v list and env = { vals : v Lazy.t StringMap.t; enums : string list StringMap.t; tags : string StringMap.t; } and closure = { clo_args : AST.pat ; mutable clo_env : env ; clo_body : AST.exp; clo_name : string * int; } (* unique id (hack) *) and procedure = { proc_args : AST.pat ; mutable proc_env : env; proc_body : AST.ins list; } val type_val : v -> typ end = struct type v = | Empty | Unv | Pair of (S.event * S.event) | Rel of S.event_rel | ClassRel of ClassRel.t | Event of S.event | Set of S.event_set | Clo of closure | Prim of string * int * (v -> v) | Proc of procedure | Tag of string * string (* type X name *) | ValSet of typ * ValSet.t (* elt type X set *) | Tuple of v list and env = { vals : v Lazy.t StringMap.t; enums : string list StringMap.t; tags : string StringMap.t; } and closure = { clo_args : AST.pat ; mutable clo_env : env ; clo_body : AST.exp; clo_name : string * int; } (* unique id (hack) *) and procedure = { proc_args : AST.pat ; mutable proc_env : env; proc_body : AST.ins list; } let rec type_val = function | V.Empty -> TEmpty | Unv -> assert false (* Discarded before *) | Pair _ -> TPair | Rel _ -> TRel | ClassRel _ -> TClassRel | Event _ -> TEvent | Set _ -> TEvents | Clo _|Prim _ -> TClo | Proc _ -> TProc | Tag (t,_) -> TTag t | ValSet (t,_) -> TSet t | Tuple vs -> TTuple (List.map type_val vs) end and ValOrder : Set.OrderedType with type t = V.v = struct (* Note: cannot use Full in sets.. *) type t = V.v open V let error fmt = ksprintf (fun msg -> raise (CompError msg)) fmt let rec compare v1 v2 = match v1,v2 with | V.Empty,V.Empty -> 0 (* Expand all legitimate empty's *) | V.Empty,ValSet (_,s) -> ValSet.compare ValSet.empty s | ValSet (_,s),V.Empty -> ValSet.compare s ValSet.empty | V.Empty,Rel r -> E.EventRel.compare E.EventRel.empty r | Rel r,V.Empty -> E.EventRel.compare r E.EventRel.empty | V.Empty,Set s -> E.EventSet.compare E.EventSet.empty s | Set s,V.Empty -> E.EventSet.compare s E.EventSet.empty | V.Empty,ClassRel r -> ClassRel.compare ClassRel.empty r | ClassRel r,V.Empty -> ClassRel.compare r ClassRel.empty (* Legitimate cmp *) | Tag (_,s1), Tag (_,s2) -> String.compare s1 s2 | Event e1,Event e2 -> E.event_compare e1 e2 | ValSet (_,s1),ValSet (_,s2) -> ValSet.compare s1 s2 | Rel r1,Rel r2 -> E.EventRel.compare r1 r2 | ClassRel r1,ClassRel r2 -> ClassRel.compare r1 r2 | Set s1,Set s2 -> E.EventSet.compare s1 s2 | (Clo {clo_name = (_,i1);_},Clo {clo_name=(_,i2);_}) | (Prim (_,i1,_),Prim (_,i2,_)) -> Misc.int_compare i1 i2 | Clo _,Prim _ -> 1 | Prim _,Clo _ -> -1 | Tuple vs,Tuple ws -> compares vs ws (* Errors *) | (Unv,_)|(_,Unv) -> error "Universe in compare" | _,_ -> let t1 = V.type_val v1 and t2 = V.type_val v2 in if type_equal t1 t2 then error "Sets of %s are illegal" (pp_typ t1) else error "Heterogeneous set elements: types %s and %s " (pp_typ t1) (pp_typ t2) and compares vs ws = match vs,ws with | [],[] -> 0 | [],_::_ -> -1 | _::_,[] -> 1 | v::vs,w::ws -> begin match compare v w with | 0 -> compares vs ws | r -> r end end and ValSet : (MySet.S with type elt = V.v) = MySet.Make(ValOrder) type fix = CheckFailed of V.env | CheckOk of V.env let error silent loc fmt = ksprintf (fun msg -> if O.debug || not silent then eprintf "%a: %s\n" TxtLoc.pp loc msg ; raise Misc.Exit) (* Silent failure *) fmt let error_not_silent loc fmt = error false loc fmt let warn loc fmt = ksprintf (fun msg -> Warn.warn_always "%a: %s" TxtLoc.pp loc msg) fmt open V (* pretty *) let pp_type_val v = pp_typ (type_val v) let rec pp_val = function | Unv -> "<universe>" | V.Empty -> "{}" | Tag (_,s) -> sprintf "'%s" s | ValSet (_,s) -> sprintf "{%s}" (ValSet.pp_str "," pp_val s) | Clo {clo_name=(n,x);_} -> sprintf "%s_%i" n x | V.Tuple vs -> sprintf "(%s)" (String.concat "," (List.map pp_val vs)) | v -> sprintf "<%s>" (pp_type_val v) let rec debug_val_set chan s = output_char chan '{' ; ValSet.pp chan "," debug_val s ; output_char chan '}' and debug_val chan = function | ValSet (_,s) -> debug_val_set chan s | Set es -> debug_set chan es | Rel r -> debug_rel chan r | ClassRel r -> debug_class_rel chan r | v -> fprintf chan "%s" (pp_val v) (* lift a tag to a singleton set *) let tag2set v = match v with | V.Tag (t,_) -> ValSet (TTag t,ValSet.singleton v) | _ -> v (* extract lists from tuples *) let pat_as_vars = function | Pvar x -> [x] | Ptuple xs -> xs let v_as_vs = function | V.Tuple vs -> vs | Pair (ev1,ev2) -> [Event ev1;Event ev2;] | v -> [v] let pat2empty = function | Pvar _ -> V.Empty | Ptuple xs -> V.Tuple (List.map (fun _ -> V.Empty) xs) let bdvar = function | None -> StringSet.empty | Some x -> StringSet.singleton x let bdvars (_,pat,_) = match pat with | Pvar x -> bdvar x | Ptuple xs -> StringSet.unions (List.map bdvar xs) (* Add values to env *) let do_add_val k v env = { env with vals = StringMap.add k v env.vals; } let add_val k v env = match k with | None -> env | Some k -> do_add_val k v env let add_pat_val silent loc pat v env = match pat with | Pvar k -> add_val k v env | Ptuple ks -> let rec add_rec extract env = function | [] -> env | k::ks -> let vk = lazy begin match extract (Lazy.force v) with | v::_ -> v | [] -> error silent loc "%s" "binding mismatch" end in let env = add_val k vk env and extract v = match extract v with | _::vs -> vs | [] -> error silent loc "%s" "binding mismatch" in add_rec extract env ks in add_rec v_as_vs env ks let env_empty = {vals=StringMap.empty; enums=StringMap.empty; tags=StringMap.empty; } (* Initial env, a restriction of env *) type init_env = E.EventSet.t Lazy.t Misc.Simple.bds * E.EventRel.t Lazy.t Misc.Simple.bds let init_env_empty = [],[] let add_rels (sets,rels) bds = (sets,bds@rels) and add_sets (sets,rels) bds = (bds@sets,rels) let get_set (sets,_) key = let rec f_rec = function | [] -> None | (k,v)::sets -> if Misc.string_eq key k then Some v else f_rec sets in f_rec sets (* Go on *) let add_vals_once mk = List.fold_right (fun (k,v) m -> if StringMap.mem k m then Warn.warn_always "redefining key '%s' in cat interpreter initial environment" k ; StringMap.add k (mk v) m) let env_from_ienv (sets,rels) = let vals = add_vals_once (fun v -> lazy (Set (Lazy.force v))) sets StringMap.empty in let vals = add_vals_once (fun v -> lazy (Rel (Lazy.force v))) rels vals in { env_empty with vals; } (* Primitive added internally to actual env *) let add_prims env bds = let vals = env.vals in let vals = List.fold_left (fun vals (k,f) -> StringMap.add k (lazy (Prim (k,next_id (),f))) vals) vals bds in { env with vals; } type loc = (TxtLoc.t * string option) list module Shown = struct type t = Rel of S.event_rel | Set of S.event_set let apply_rel f (sr:t) = match sr with | Rel r -> Rel (f r) | Set _ -> sr end Internal status of interpreter type inter_st = { included : StringSet.t ; loc : loc ; } let inter_st_empty = { included = StringSet.empty; loc = []; } Complete status type st = { env : V.env ; show : Shown.t StringMap.t Lazy.t ; skipped : StringSet.t ; flags : Flag.Set.t ; ks : ks ; bell_info : BellModel.info ; st : inter_st ; } (* Interpretation result *) type st_out = { out_show : S.event_rel Misc.Simple.bds Lazy.t ; out_sets : S.event_set StringMap.t Lazy.t ; out_skipped : StringSet.t ; out_flags : Flag.Set.t ; out_bell_info : BellModel.info ; } (* Remove transitive edges, except if instructed not to *) let rt_loc lbl = if O.verbose <= 1 && not (StringSet.mem lbl O.symetric) && not (StringSet.mem lbl O.showraw) then E.EventRel.remove_transitive_edges else (fun x -> x) let show_to_vbpp st = StringMap.fold (fun tag v k -> match v with | Shown.Rel v -> (tag,v)::k | Shown.Set _ -> k) (Lazy.force st.show) [] let show_to_sets st = StringMap.fold (fun tag v k -> match v with | Shown.Rel _ -> k | Shown.Set v -> StringMap.add tag v k) (Lazy.force st.show) StringMap.empty let st2out st = {out_show = lazy (show_to_vbpp st) ; out_sets = lazy (show_to_sets st) ; out_skipped = st.skipped ; out_flags = st.flags ; out_bell_info = st.bell_info ; } let push_loc st loc = let ist = st.st in let loc = loc :: ist.loc in let ist = { ist with loc; } in { st with st=ist; } let pop_loc st = let ist = st.st in match ist.loc with | [] -> assert false | _::loc -> let ist = { ist with loc; } in { st with st=ist; } let show_loc (loc,name) = eprintf "%a: calling procedure%s\n" TxtLoc.pp loc (match name with | None -> "" | Some n -> " as " ^ n) let show_call_stack st = List.iter show_loc st let protect_call st f x = try f x with Misc.Exit -> let st = st.st in List.iter (fun loc -> if O.debug then show_loc loc) st.loc ; raise Misc.Exit (* Type of eval env *) module EV = struct type env = { env : V.env ; silent : bool; ks : ks; } end let from_st st = { EV.env=st.env; silent=false; ks=st.ks; } let set_op env loc t op s1 s2 = try V.ValSet (t,op s1 s2) with CompError msg -> error env.EV.silent loc "%s" msg let tags_universe {enums=env; _} t = let tags = try StringMap.find t env with Not_found -> assert false in let tags = ValSet.of_list (List.map (fun s -> V.Tag (t,s)) tags) in tags let find_env {vals=env; _} k = Lazy.force begin try StringMap.find k env with | Not_found -> Warn.user_error "unbound var: %s" k end let find_env_loc loc env k = try find_env env.EV.env k with Misc.UserError msg -> error env.EV.silent loc "%s" msg (* find without forcing lazy's *) let just_find_env fail loc env k = try StringMap.find k env.EV.env.vals with Not_found -> if fail then error env.EV.silent loc "unbound var: %s" k else raise Not_found let as_rel ks = function | Rel r -> r | Empty -> E.EventRel.empty | Unv -> Lazy.force ks.unv | v -> eprintf "this is not a relation: '%s'" (pp_val v) ; assert false let as_classrel = function | ClassRel r -> r | Empty -> ClassRel.empty | Unv -> Warn.fatal "No universal class relation" | v -> eprintf "this is not a relation: '%s'" (pp_val v) ; assert false let as_set ks = function | Set s -> s | Empty -> E.EventSet.empty | Unv -> ks.evts | _ -> assert false let as_valset = function | ValSet (_,v) -> v | _ -> assert false let as_tag = function | V.Tag (_,tag) -> tag | _ -> assert false let as_tags tags = let ss = ValSet.fold (fun v k -> as_tag v::k) tags [] in StringSet.of_list ss exception Stabilised of typ let stabilised ks env = let rec stabilised vs ws = match vs,ws with | [],[] -> true | v::vs,w::ws -> begin match v,w with | (_,V.Empty)|(Unv,_) -> stabilised vs ws (* Relation *) | (V.Empty,Rel w) -> E.EventRel.is_empty w && stabilised vs ws | (Rel v,Unv) -> E.EventRel.subset (Lazy.force ks.unv) v && stabilised vs ws | Rel v,Rel w -> E.EventRel.subset w v && stabilised vs ws (* Class relation *) | (V.Empty,ClassRel w) -> ClassRel.is_empty w && stabilised vs ws | ClassRel v,ClassRel w -> ClassRel.subset w v && stabilised vs ws (* Event Set *) | (V.Empty,Set w) -> E.EventSet.is_empty w && stabilised vs ws | (Set v,Unv) -> E.EventSet.subset ks.evts v && stabilised vs ws | Set v,Set w -> E.EventSet.subset w v && stabilised vs ws (* Value Set *) | (V.Empty,ValSet (_,w)) -> ValSet.is_empty w && stabilised vs ws | (ValSet (TTag t,v),Unv) -> ValSet.subset (tags_universe env t) v && stabilised vs ws | ValSet (_,v),ValSet (_,w) -> ValSet.subset w v && stabilised vs ws | _,_ -> eprintf "Problem %s vs. %s\n" (pp_val v) (pp_val w) ; raise (Stabilised (type_val w)) end | _,_ -> assert false in stabilised Syntactic function let is_fun = function | Fun _ -> true | _ -> false (* Get an expression location *) let get_loc = function | Konst (loc,_) | AST.Tag (loc,_) | Var (loc,_) | ExplicitSet (loc,_) | Op1 (loc,_,_) | Op (loc,_,_) | Bind (loc,_,_) | BindRec (loc,_,_) | App (loc,_,_) | Fun (loc,_,_,_,_) | Match (loc,_,_,_) | MatchSet (loc,_,_,_) | Try (loc,_,_) | If (loc,_,_,_) -> loc let empty_rel = Rel E.EventRel.empty let error_typ silent loc t0 t1 = error silent loc"type %s expected, %s found" (pp_typ t0) (pp_typ t1) let error_rel silent loc v = error_typ silent loc TRel (type_val v) let error_events silent loc v = error_typ silent loc TEvents (type_val v) (* Tests are polymorphic, acting on relations, class relations and sets *) let test2pred env t e v = match t,v with | Acyclic,Rel r -> E.EventRel.is_acyclic r | Irreflexive,Rel r -> E.EventRel.is_irreflexive r | Acyclic,ClassRel r -> ClassRel.is_acyclic r | Irreflexive,ClassRel r -> ClassRel.is_irreflexive r | TestEmpty,Rel r -> E.EventRel.is_empty r | TestEmpty,ClassRel r -> ClassRel.is_empty r | TestEmpty,Set s -> E.EventSet.is_empty s | (Acyclic|Irreflexive),Set _ -> error env.EV.silent (get_loc e) "relation expected" | _,_ -> assert false (* Called on Rel or Set *) let test2pred env t e v = match t with | Yes t -> test2pred env t e v | No t -> not (test2pred env t e v) (********************************) (* Helpers for n-ary operations *) (********************************) let type_list silent = function | [] -> assert false | (_,v)::vs -> let rec type_rec t0 = function | [] -> t0,[] | (loc,v)::vs -> let t1 = type_val v in (* eprintf "Value: %s, Type %s\n" (pp_val v) (pp_typ t1) ; *) match eq_type t0 t1 with | Some t0 -> let t0,vs = type_rec t0 vs in t0,v::vs | None -> error silent loc "type %s expected, %s found" (pp_typ t0) (pp_typ t1) in let t0,vs = type_rec (type_val v) vs in t0,v::vs (* Check explicit set arguments *) let set_args silent = let rec s_rec = function | [] -> [] | (loc,Unv)::_ -> error silent loc "universe in explicit set" | x::xs -> x::s_rec xs in s_rec (* Union is polymorphic *) let union_args = let rec u_rec = function | [] -> [] | (_,V.Empty)::xs -> u_rec xs | (_,Unv)::_ -> raise Exit | (loc,v)::xs -> (loc,tag2set v)::u_rec xs in u_rec (* Definition of primitives *) module type PrimArg = sig type base module Rel : InnerRel.S with type elt0=base val debug_set : out_channel -> Rel.Elts.t -> unit val debug_rel : out_channel -> Rel.t -> unit val mk_val : Rel.t -> V.v val typ : typ end module EventArg = struct type base = E.event module Rel = E.EventRel let debug_set = debug_set let debug_rel = debug_rel let mk_val r = Rel r let typ = TRel end module ClassArg = struct type base = E.EventSet.t module Rel = ClassRel let debug_set chan ss = fprintf chan "{%a}" (fun chan ss -> ClassRel.Elts.pp chan "," debug_set ss) ss let debug_rel = debug_class_rel let mk_val r = ClassRel r let typ = TClassRel end Debug ClassRel 's as instance relations module InstanceArg = struct type base = E.EventSet.t module let debug_set chan ss = chan " { % a } " ( fun chan ss - > ClassRel.Elts.pp chan " , " debug_set ss ) ss let debug_instance chan es = try chan " % s " ( E.pp_instance ( E.EventSet.choose es ) ) with Not_found - > assert false let = ClassRel.pp chan " , " ( fun chan ( e1,e2 ) - > chan " { % a - > % a } " debug_instance e1 debug_instance e2 ) r let debug_rel = debug_instance_rel let mk_val r = ClassRel r let typ = end module InstanceArg = struct type base = E.EventSet.t module Rel = ClassRel let debug_set chan ss = fprintf chan "{%a}" (fun chan ss -> ClassRel.Elts.pp chan "," debug_set ss) ss let debug_instance chan es = try fprintf chan "%s" (E.pp_instance (E.EventSet.choose es)) with Not_found -> assert false let debug_instance_rel chan r = ClassRel.pp chan "," (fun chan (e1,e2) -> fprintf chan "{%a -> %a}" debug_instance e1 debug_instance e2) r let debug_rel = debug_instance_rel let mk_val r = ClassRel r let typ = TClassRel end *) let arg_mismatch () = raise (PrimError "argument mismatch") let partition arg = match arg with | Set evts -> let r = U.partition_events evts in let vs = List.map (fun es -> Set es) r in ValSet (TEvents,ValSet.of_list vs) | _ -> arg_mismatch () and classes arg = match arg with | Rel r -> let r = E.EventRel.classes r in let vs = List.map (fun es -> Set es) r in ValSet (TEvents,ValSet.of_list vs) | _ -> arg_mismatch () (* Lift a relation from events to event classes *) and lift arg = match arg with | V.Tuple [ValSet (TEvents,cls);Rel r] -> let m = ValSet.fold (fun v m -> match v with | Set evts -> E.EventSet.fold (fun e m -> E.EventMap.add e evts m) evts m | _ -> assert false) cls E.EventMap.empty in let clsr = E.EventRel.fold (fun (e1,e2) k -> try let cl1 = E.EventMap.find e1 m and cl2 = E.EventMap.find e2 m in ClassRel.add (cl1,cl2) k with Not_found -> k) r ClassRel.empty in V.ClassRel clsr | _ -> arg_mismatch () (* Delift a relation from event classes to events *) and delift arg = match arg with | ClassRel clsr -> let r = ClassRel.fold (fun (cl1,cl2) k -> E.EventRel.cartesian cl1 cl2::k) clsr [] in Rel (E.EventRel.unions r) | _ -> arg_mismatch () (* Restrict delift by intersection (fulldeflift(clsr) & loc) *) and deliftinter arg = match arg with | V.Tuple[Rel m;ClassRel clsr] -> let make_rel_from_classpair (cl1,cl2) = E.EventRel.filter (fun (e1,e2) -> E.EventSet.mem e1 cl1 && E.EventSet.mem e2 cl2) m in let r = ClassRel.fold (fun clp k -> make_rel_from_classpair clp::k) clsr [] in Rel (E.EventRel.unions r) | _ -> arg_mismatch () and linearisations = let module Make = functor (In : PrimArg) -> struct let mem = In.Rel.Elts.mem let zyva es r = if O.debug && O.verbose > 1 then begin eprintf "Linearisations:\n" ; eprintf " %a\n" In.debug_set es ; eprintf " {%a}\n" In.debug_rel (In.Rel.filter (fun (e1,e2) -> mem e1 es && mem e2 es) r) end ; let nodes = es in if O.debug && O.verbose > 1 then begin let n = In.Rel.all_topos_kont_rel nodes r (fun _ -> 0) (fun _ k -> k+1) 0 in eprintf "number of orders: %i\n" n end ; let rs = In.Rel.all_topos_kont_rel nodes r (fun o -> let o = In.Rel.filter (fun (e1,e2) -> mem e1 es && mem e2 es) o in if O.debug then begin eprintf "Linearisation failed {%a}\n%!" In.debug_rel o ; ValSet.singleton (In.mk_val o) end else ValSet.empty) (fun o os -> if O.debug && O.verbose > 1 then eprintf " -> {%a}\n%!" In.debug_rel o ; ValSet.add (In.mk_val o) os) ValSet.empty in ValSet (In.typ,rs) end in fun ks arg -> match arg with | V.Tuple [Set es;Rel r;] -> let module L = Make(EventArg) in L.zyva es r | V.Tuple [ValSet (TEvents,es);ClassRel r;] -> let module L = Make(ClassArg) in let es = let sets = ValSet.fold (fun v k -> as_set ks v::k) es [] in ClassRel.Elts.of_list sets in L.zyva es r | _ -> arg_mismatch () and bisimulation = fun arg -> match arg with | V.Tuple [Rel t; Rel e; ] -> Rel (E.EventRel.bisimulation t e) | V.Tuple [ClassRel t; ClassRel e; ] -> ClassRel (ClassRel.bisimulation t e) | _ -> arg_mismatch () and tag2scope env arg = match arg with | V.Tag (_,tag) -> begin try let v = Lazy.force (StringMap.find tag env.vals) in match v with | V.Empty|V.Unv|V.Rel _ -> v | _ -> raise (PrimError (sprintf "value %s is not a relation, found %s" tag (pp_type_val v))) with Not_found -> raise (PrimError (sprintf "cannot find scope instance %s (the litmus test might be missing a scope tree declaration)" tag)) end | _ -> arg_mismatch () and tag2events env arg = match arg with | V.Tag (_,tag) -> let x = BellName.tag2instrs_var tag in begin try let v = Lazy.force (StringMap.find x env.vals) in match v with | V.Empty|V.Unv|V.Set _ -> v | _ -> raise (PrimError (sprintf "value %s is not a set of events, found %s" x (pp_type_val v))) with Not_found -> raise (PrimError (sprintf "cannot find event set %s" x)) end | _ -> arg_mismatch () and fromto ks arg = match arg with | V.Set es -> V.Rel (U.fromto ks.po es) | _ -> arg_mismatch () and tag2fenced env arg = match arg with | V.Tag (_,tag) -> let not_a_set_of_events x v = raise (PrimError (sprintf "value %s is not a set of events, found %s" x (pp_type_val v))) in let find_rel id = match Lazy.force (StringMap.find id env.vals) with | V.Rel rel -> rel | _ -> assert false in let po = find_rel "po" in let fromto = find_rel "fromto" in let x = BellName.tag2instrs_var tag in begin try let v = Lazy.force (StringMap.find x env.vals) in match v with | V.Empty -> V.Rel E.EventRel.empty | V.Unv -> assert false (* jade: we assert false when all the events in the execution bear the tag tag *) | V.Set bevts -> let filter (x, y) = E.EventSet.exists (fun b -> E.EventRel.mem (x,b) po && E.EventRel.mem (b,y) po) bevts in V.Rel (E.EventRel.filter filter fromto) | _ -> not_a_set_of_events x v with Not_found -> raise (PrimError (sprintf "cannot find event set %s" x)) end | _ -> arg_mismatch () and loc2events ks arg = match arg with | V.Tag (_,s) -> let evts = ks.evts in let r = U.loc2events s evts in Set r | _ -> arg_mismatch () and domain arg = match arg with | V.Empty -> V.Empty | V.Unv -> V.Unv | V.Rel r -> V.Set (E.EventRel.domain r) | _ -> arg_mismatch () and range arg = match arg with | V.Empty -> V.Empty | V.Unv -> V.Unv | V.Rel r -> V.Set (E.EventRel.codomain r) | _ -> arg_mismatch () and fail arg = let pp = pp_val arg in let msg = sprintf "fail on %s" pp in raise (PrimError msg) and different_values arg = match arg with | V.Rel r -> let r = E.EventRel.filter (fun (e1,e2) -> not (U.same_value e1 e2)) r in V.Rel r | _ -> arg_mismatch () and same_oaRel arg = match arg with | V.Rel r -> let r = E.EventRel.filter (fun (e1,e2) -> (U.same_oa e1 e2)) r in V.Rel r | _ -> arg_mismatch () and check_two pred arg = match arg with | V.Tuple [V.Set ws; V.Rel prec; ] -> let m = E.EventRel.M.to_map prec in let ws = E.EventSet.filter (fun w -> E.is_store w && E.is_pt w && begin match E.EventSet.as_singleton (E.EventRel.M.succs w m) with | Some p -> pred w p w does not qualify when zero of two or more prec - related events | None -> false end) ws in V.Set ws | _ -> arg_mismatch () let oa_changes = check_two (fun w p -> not (U.same_oa w p)) and at_least_one_writable = check_two U.writable2 let add_primitives ks m = add_prims m [ "at-least-one-writable",at_least_one_writable; "oa-changes",oa_changes; "same-oa",same_oaRel; "different-values",different_values; "fromto",fromto ks; "classes-loc",partition; "classes",classes; "lift",lift; "delift",delift; "deliftinter",deliftinter; "linearisations",linearisations ks; "bisimulation",bisimulation; "tag2scope",tag2scope m; "tag2level",tag2scope m; "tag2events",tag2events m; "tag2fenced",tag2fenced m; "loc2events",loc2events ks; "domain",domain; "range",range; "fail",fail; ] (***************) (* Interpreter *) (***************) type rel = | Rid of (E.event -> bool) | Revent of E.EventRel.t | Rclass of ClassRel.t let eval_variant loc v = try O.variant v with Not_found -> Warn.warn_always "%a: non-existent variant \"%s\", assumed unset" TxtLoc.pp loc v ; false let rec eval_variant_cond loc = function | Variant v -> eval_variant loc v | OpNot v -> not (eval_variant_cond loc v) | OpAnd (v1,v2) -> (eval_variant_cond loc v1) && (eval_variant_cond loc v2) | OpOr (v1,v2) -> (eval_variant_cond loc v1) || (eval_variant_cond loc v2) For all success call kont , accumulating results let interpret test kfail = let rec eval_loc env e = get_loc e,eval env e and check_id env e = match e with | Op1 (_,ToId,e) -> Some (eval_events_mem env e) | _ -> None and eval env = function | Konst (_,AST.Empty SET) -> V.Empty (* Polymorphic empty *) | Konst (_,AST.Empty RLN) -> empty_rel | Konst (_,Universe _) -> Unv | AST.Tag (loc,s) -> begin try V.Tag (StringMap.find s env.EV.env.tags,s) with Not_found -> error env.EV.silent loc "tag '%s is undefined" s end | Var (loc,k) -> find_env_loc loc env k | Fun (loc,xs,body,name,fvs) -> Clo (eval_fun false env loc xs body name fvs) Unary operators | Op1 (_,Plus,e) -> begin match eval env e with | V.Empty -> V.Empty | Unv -> Unv | Rel r -> Rel (E.EventRel.transitive_closure r) | v -> error_rel env.EV.silent (get_loc e) v end | Op1 (_,Star,e) -> begin match eval env e with | V.Empty -> Rel (Lazy.force env.EV.ks.id) | Unv -> Unv | Rel r -> Rel (E.EventRel.union (E.EventRel.transitive_closure r) (Lazy.force env.EV.ks.id)) | v -> error_rel env.EV.silent (get_loc e) v end | Op1 (_,Opt,e) -> begin match eval env e with | V.Empty -> Rel (Lazy.force env.EV.ks.id) | Unv -> Unv | Rel r -> Rel (E.EventRel.union r (Lazy.force env.EV.ks.id)) | v -> error_rel env.EV.silent (get_loc e) v end | Op1 (_,Comp,e) -> (* Back to polymorphism *) begin match eval env e with | V.Empty -> Unv | Unv -> V.Empty | Set s -> Set (E.EventSet.diff env.EV.ks.evts s) | Rel r -> Rel (E.EventRel.diff (Lazy.force env.EV.ks.unv) r) | ValSet (TTag ts as t,s) -> ValSet (t,ValSet.diff (tags_universe env.EV.env ts) s) | v -> error env.EV.silent (get_loc e) "set or relation expected, %s found" (pp_typ (type_val v)) end | Op1 (_,Inv,e) -> begin match eval env e with | V.Empty -> V.Empty | Unv -> Unv | Rel r -> Rel (E.EventRel.inverse r) | ClassRel r -> ClassRel (ClassRel.inverse r) | Pair (v1,v2) -> Pair (v2,v1) | v -> error_rel env.EV.silent (get_loc e) v end | Op1 (_,ToId,e) -> begin match eval env e with | V.Empty -> V.Empty | Unv -> Rel (Lazy.force env.EV.ks.id) | Set s -> Rel (E.EventRel.set_to_rln s) | v -> error_events env.EV.silent (get_loc e) v end One xplicit N - ary operator | ExplicitSet (loc,es) -> let vs = List.map (eval_loc env) es in let vs = set_args env.EV.silent vs in begin match vs with | [] -> V.Empty | _ -> let t,vs = type_list env.EV.silent vs in try match t with | TEvent -> let vs = List.rev_map (function Event e -> e | _ -> assert false) vs in Set (E.EventSet.of_list vs) | TPair -> let vs = List.rev_map (function Pair p -> p | _ -> assert false) vs in Rel (E.EventRel.of_list vs) | _ -> ValSet (t,ValSet.of_list vs) with CompError msg -> error env.EV.silent loc "%s" msg end (* Tuple is an actual N-ary operator *) | Op (_loc,AST.Tuple,es) -> V.Tuple (List.map (eval env) es) (* N-ary operators, those associative binary operators are optimized *) | Op (loc,Union,es) -> let vs = List.map (eval_loc env) es in begin try let vs = union_args vs in match vs with | [] -> V.Empty | _ -> let t,vs = type_list env.EV.silent vs in match t with | TClassRel -> ClassRel(ClassRel.unions (List.map as_classrel vs)) | TRel -> Rel (E.EventRel.unions (List.map (as_rel env.EV.ks) vs)) | TEvents -> Set (E.EventSet.unions (List.map (as_set env.EV.ks) vs)) | TSet telt -> ValSet (telt,ValSet.unions (List.map as_valset vs)) | ty -> error env.EV.silent loc "cannot perform union on type '%s'" (pp_typ ty) with Exit -> Unv end | Op (loc,Seq,es) -> begin try let vs = List.map (eval_rels env) es in let rec do_seq = function | [] -> assert false | [v] -> v | v::vs -> begin match v,do_seq vs with | Rid f,Rid fs -> Rid (fun e -> f e && fs e) | Rid f,Revent vs -> Revent (E.EventRel.filter (fun (e1,_) -> f e1) vs) | Revent v,Rid fs -> Revent (E.EventRel.filter (fun (_,e2) -> fs e2) v) | Revent v,Revent vs -> Revent (E.EventRel.sequence v vs) | Rclass v,Rclass vs -> Rclass (ClassRel.sequence v vs) | _,_ -> error env.EV.silent loc "mixing relations in sequence" end in match do_seq vs with | Rid f -> Rel (E.EventRel.set_to_rln (E.EventSet.filter f env.EV.ks.evts)) | Revent r -> Rel r | Rclass r -> ClassRel r with Exit -> V.Empty end begin try let f1,rs , f2 = eval_seq_args env es in let r = E.EventRel.sequence rs ( Lazy.force env.EV.ks.id ) in let r = match f1,f2 with | None , None - > r | Some f1,None - > E.EventRel.filter ( fun ( e1 , _ ) - > f1 e1 ) r | None , Some f2 - > E.EventRel.filter ( fun ( _ , e2 ) - > f2 e2 ) r | Some f1,Some f2 - > E.EventRel.filter ( fun ( e1,e2 ) - > f1 e1 & & f2 e2 ) r in Rel r with Exit - > empty_rel end begin try let f1,rs,f2 = eval_seq_args env es in let r = List.fold_right E.EventRel.sequence rs (Lazy.force env.EV.ks.id) in let r = match f1,f2 with | None,None -> r | Some f1,None -> E.EventRel.filter (fun (e1,_) -> f1 e1) r | None,Some f2 -> E.EventRel.filter (fun (_,e2) -> f2 e2) r | Some f1,Some f2 -> E.EventRel.filter (fun (e1,e2) -> f1 e1 && f2 e2) r in Rel r with Exit -> empty_rel end *) (* Binary operators *) | Op (_loc1,Inter,[e1;Op (_loc2,Cartesian,[e2;e3])]) | Op (_loc1,Inter,[Op (_loc2,Cartesian,[e2;e3]);e1]) -> let r = eval_rel env e1 and f1 = eval_events_mem env e2 and f2 = eval_events_mem env e3 in let r = E.EventRel.filter (fun (e1,e2) -> f1 e1 && f2 e2) r in Rel r | Op (loc,Inter,[e1;e2;]) -> (* Binary notation kept in parser *) let loc1,v1 = eval_loc env e1 and loc2,v2 = eval_loc env e2 in begin match tag2set v1,tag2set v2 with | (V.Tag _,_)|(_,V.Tag _) -> assert false | Rel r1,Rel r2 -> Rel (E.EventRel.inter r1 r2) | ClassRel r1,ClassRel r2 -> ClassRel (ClassRel.inter r1 r2) | Set s1,Set s2 -> Set (E.EventSet.inter s1 s2) | ValSet (t,s1),ValSet (_,s2) -> set_op env loc t ValSet.inter s1 s2 | (Unv,r)|(r,Unv) -> r | (V.Empty,_)|(_,V.Empty) -> V.Empty | (Event _|Pair _|Clo _|Prim _|Proc _|V.Tuple _),_ -> error env.EV.silent loc1 "intersection on %s" (pp_typ (type_val v1)) | _,(Event _|Pair _|Clo _|Prim _|Proc _|V.Tuple _) -> error env.EV.silent loc2 "intersection on %s" (pp_typ (type_val v2)) | ((Rel _|ClassRel _),(Set _|ValSet _)) | ((Set _|ValSet _),(Rel _|ClassRel _)) -> error env.EV.silent loc "mixing sets and relations in intersection" | (ValSet _,Set _) | (Set _,ValSet _) -> error env.EV.silent loc "mixing event sets and sets in intersection" | (ClassRel _,Rel _) | (Rel _,ClassRel _) -> error env.EV.silent loc "mixing event relation and class relation in intersection" end | Op (loc,Diff,[e1;e2;]) -> let loc1,v1 = eval_loc env e1 and loc2,v2 = eval_loc env e2 in begin match tag2set v1,tag2set v2 with | (V.Tag _,_)|(_,V.Tag _) -> assert false | Rel r1,Rel r2 -> Rel (E.EventRel.diff r1 r2) | ClassRel r1,ClassRel r2 -> ClassRel (ClassRel.diff r1 r2) | Set s1,Set s2 -> Set (E.EventSet.diff s1 s2) | ValSet (t,s1),ValSet (_,s2) -> set_op env loc t ValSet.diff s1 s2 | Unv,Rel r -> Rel (E.EventRel.diff (Lazy.force env.EV.ks.unv) r) | Unv,Set s -> Set (E.EventSet.diff env.EV.ks.evts s) | Unv,ValSet (TTag ts as t,s) -> ValSet (t,ValSet.diff (tags_universe env.EV.env ts) s) | Unv,ClassRel _ -> error env.EV.silent loc1 "cannot build universe for element type %s" (pp_typ TClassRel) | Unv,ValSet (t,_) -> error env.EV.silent loc1 "cannot build universe for element type %s" (pp_typ t) | Unv,V.Empty -> Unv | (Rel _|ClassRel _|Set _|V.Empty|Unv|ValSet _),Unv | V.Empty,(Rel _|ClassRel _|Set _|V.Empty|ValSet _) -> V.Empty | (Rel _|ClassRel _|Set _|ValSet _),V.Empty -> v1 | (Event _|Pair _|Clo _|Proc _|Prim _|V.Tuple _),_ -> error env.EV.silent loc1 "difference on %s" (pp_typ (type_val v1)) | _,(Event _|Pair _|Clo _|Proc _|Prim _|V.Tuple _) -> error env.EV.silent loc2 "difference on %s" (pp_typ (type_val v2)) | ((Set _|ValSet _),(ClassRel _|Rel _))|((ClassRel _|Rel _),(Set _|ValSet _)) -> error env.EV.silent loc "mixing set and relation in difference" | (Set _,ValSet _)|(ValSet _,Set _) -> error env.EV.silent loc "mixing event set and set in difference" | (Rel _,ClassRel _)|(ClassRel _,Rel _) -> error env.EV.silent loc "mixing event relation and class relation in difference" end | Op (_,Cartesian,[e1;e2;]) -> let s1 = eval_events env e1 and s2 = eval_events env e2 in Rel (E.EventRel.cartesian s1 s2) | Op (loc,Add,[e1;e2;]) -> let v1 = eval env e1 and v2 = eval env e2 in begin match v1,v2 with | V.Unv,_ -> error env.EV.silent loc "universe in set ++" | _,V.Unv -> V.Unv | Event e,V.Empty -> Set (E.EventSet.singleton e) | Pair p,V.Empty -> Rel (E.EventRel.singleton p) | _,V.Empty -> V.ValSet (type_val v1,ValSet.singleton v1) | V.Empty,V.ValSet (TSet e2 as t2,s2) -> let v1 = ValSet (e2,ValSet.empty) in set_op env loc t2 ValSet.add v1 s2 | _,V.ValSet (_,s2) -> set_op env loc (type_val v1) ValSet.add v1 s2 | Pair p,Rel r -> Rel (E.EventRel.add p r) | Tuple [Event ev1;Event ev2;],Rel r -> Rel (E.EventRel.add (ev1,ev2) r) | _,Rel _ -> error env.EV.silent (get_loc e1) "this expression of type '%s' should be a pair" (pp_typ (type_val v2)) | Event e,Set es -> Set (E.EventSet.add e es) | _,Set _ -> error env.EV.silent (get_loc e1) "this expression of type '%s' should be an event" (pp_typ (type_val v1)) | _, (Event _|Pair _|Clo _|Prim _ |Proc _|V.Tag (_, _)|V.Tuple _) -> error env.EV.silent (get_loc e2) "this expression of type '%s' should be a set" (pp_typ (type_val v2)) | _,ClassRel _ -> error env.EV.silent (get_loc e2) "this expression of type '%s' cannot occur here" (pp_typ (type_val v2)) end | Op (_,(Diff|Inter|Cartesian|Add),_) -> assert false (* By parsing *) (* Application/bindings *) | App (loc,f,e) -> eval_app loc env (eval env f) (eval env e) | Bind (_,bds,e) -> let m = eval_bds env bds in eval { env with EV.env = m;} e | BindRec (loc,bds,e) -> let m = match env_rec (fun _ -> true) env loc (fun pp -> pp) bds with | CheckOk env -> env | CheckFailed _ -> assert false (* No check in expr binding *) in eval { env with EV.env=m;} e | Match (loc,e,cls,d) -> let v = eval env e in begin match v with | V.Tag (_,s) -> let rec match_rec = function | [] -> begin match d with | Some e -> eval env e | None -> error env.EV.silent loc "pattern matching failed on value '%s'" s end | (ps,es)::cls -> if s = ps then eval env es else match_rec cls in match_rec cls | V.Empty -> error env.EV.silent (get_loc e) "matching on empty" | V.Unv -> error env.EV.silent (get_loc e) "matching on universe" | _ -> error env.EV.silent (get_loc e) "matching on non-tag value of type '%s'" (pp_typ (type_val v)) end | MatchSet (loc,e,ife,cl) -> let v = eval env e in begin match v with | V.Empty -> eval env ife | V.Unv -> error env.EV.silent loc "%s" "Cannot set-match on universe" | Set es -> if E.EventSet.is_empty es then eval env ife else begin match cl with | EltRem (x,xs,ex) -> let elt = lazy begin try E.EventSet.choose es with Not_found -> assert false end in let s = lazy begin Set (E.EventSet.remove (Lazy.force elt) es) end in let elt = lazy (Event (Lazy.force elt)) in let m = env.EV.env in let m = add_val x elt m in let m = add_val xs s m in eval { env with EV.env = m; } ex | PreEltPost (xs1,x,xs2,ex) -> let s1,elt,s2 = try E.EventSet.split3 es with Not_found -> assert false in let m = env.EV.env in let m = add_val x (lazy (Event elt)) m in let m = add_val xs1 (lazy (Set s1)) m in let m = add_val xs2 (lazy (Set s2)) m in eval { env with EV.env = m; } ex end | Rel r -> if E.EventRel.is_empty r then eval env ife else begin match cl with | EltRem (x,xs,ex) -> let p = lazy begin try E.EventRel.choose r with Not_found -> assert false end in let s = lazy begin Rel (E.EventRel.remove (Lazy.force p) r) end in let p = lazy (Pair (Lazy.force p)) in let m = env.EV.env in let m = add_val x p m in let m = add_val xs s m in eval { env with EV.env = m; } ex | PreEltPost (xs1,x,xs2,ex) -> let s1,elt,s2 = try E.EventRel.split3 r with Not_found -> assert false in let m = env.EV.env in let m = add_val x (lazy (Pair elt)) m in let m = add_val xs1 (lazy (Rel s1)) m in let m = add_val xs2 (lazy (Rel s2)) m in eval { env with EV.env = m; } ex end | ValSet (t,s) -> if ValSet.is_empty s then eval env ife else begin match cl with | EltRem (x,xs,ex) -> let elt = lazy begin try ValSet.choose s with Not_found -> assert false end in let s = lazy begin try ValSet (t,ValSet.remove (Lazy.force elt) s) with CompError msg -> error env.EV.silent (get_loc e) "%s" msg end in let m = env.EV.env in let m = add_val x elt m in let m = add_val xs s m in eval { env with EV.env = m; } ex | PreEltPost (xs1,x,xs2,ex) -> let s1,elt,s2 = try ValSet.split3 s with Not_found -> assert false in let m = env.EV.env in let m = add_val x (lazy elt) m in let m = add_val xs1 (lazy (ValSet (t,s1))) m in let m = add_val xs2 (lazy (ValSet (t,s2))) m in eval { env with EV.env = m; } ex end | _ -> error env.EV.silent (get_loc e) "set-matching on non-set value of type '%s'" (pp_typ (type_val v)) end | Try (loc,e1,e2) -> begin try eval { env with EV.silent = true; } e1 with Misc.Exit -> if O.debug then warn loc "caught failure" ; eval env e2 end | If (loc,cond,ifso,ifnot) -> if eval_cond loc env cond then eval env ifso else eval env ifnot and eval_cond loc env c = match c with | In (e1,e2) -> let loc1,v1 = eval_loc env e1 in begin match v1 with | Event e -> let v2 = eval_events env e2 in E.EventSet.mem e v2 | Pair p -> let v2 = eval_rel env e2 in E.EventRel.mem p v2 | Tuple [Event ev1;Event ev2;] -> let v2 = eval_rel env e2 in E.EventRel.mem (ev1,ev2) v2 | _ -> begin match eval_loc env e2 with | _,ValSet (t2,vs) -> let t1 = V.type_val v1 in if type_equal t1 t2 then ValSet.mem v1 vs else error_typ env.EV.silent loc1 t2 t1 | loc2,v2 -> error env.EV.silent loc2 "set expected, found %s" (pp_typ (type_val v2)) end end | Eq (e1,e2) -> let v1 = eval env e1 and v2 = eval env e2 in ValOrder.compare v1 v2 = 0 | Subset(e1,e2) -> (*ici*) let v1 = eval_loc env e1 and v2 = eval_loc env e2 in let t,_ = type_list env.EV.silent [v1;v2] in let a' = snd v1 and b' = snd v2 in begin match t with | TRel -> E.EventRel.subset (as_rel env.EV.ks a') (as_rel env.EV.ks b') | TEvents -> E.EventSet.subset (as_set env.EV.ks a') (as_set env.EV.ks b') | TSet _ -> ValSet.subset (as_valset a') (as_valset b') | ty -> error env.EV.silent loc "cannot perform subset on type '%s'" (pp_typ ty) end | VariantCond v -> eval_variant_cond loc v and eval_app loc env vf va = match vf with | Clo f -> let env = { env with EV.env=add_args loc f.clo_args va env f.clo_env;} in if O.debug then begin try eval env f.clo_body with | Misc.Exit -> error env.EV.silent loc "Calling" | e -> error env.EV.silent loc "Calling (%s)" (Printexc.to_string e) end else eval env f.clo_body | Prim (name,_,f) -> begin try f va with | PrimError msg -> error env.EV.silent loc "primitive %s: %s" name msg | Misc.Exit -> error env.EV.silent loc "Calling primitive %s" name end | _ -> error env.EV.silent loc "closure or primitive expected" and eval_fun is_rec env loc pat body name fvs = if O.debug && O.verbose > 1 then begin let sz = StringMap.fold (fun _ _ k -> k+1) env.EV.env.vals 0 in let fs = StringSet.pp_str "," (fun x -> x) fvs in warn loc "Closure %s, env=%i, free={%s}" name sz fs end ; let vals = StringSet.fold (fun x k -> try let v = just_find_env (not is_rec) loc env x in StringMap.add x v k with Not_found -> k) fvs StringMap.empty in let env = { env.EV.env with vals; } in {clo_args=pat; clo_env=env; clo_body=body; clo_name=(name,next_id ()); } and add_args loc pat v env_es env_clo = let xs = pat_as_vars pat in let vs = match xs with [_] -> [v] | _ -> v_as_vs v in let bds = try List.combine xs vs with _ -> error env_es.EV.silent loc "argument_mismatch" in let env_call = List.fold_right (fun (x,v) env -> add_val x (lazy v) env) bds env_clo in env_call and eval_rel env e = match eval env e with | Rel v -> v | Pair p -> E.EventRel.singleton p | V.Empty -> E.EventRel.empty | Unv -> Lazy.force env.EV.ks.unv | v -> error_rel env.EV.silent (get_loc e) v and eval_rels env e = match check_id env e with | Some es -> Rid es | None -> match eval env e with | Rel v -> Revent v | ClassRel v -> Rclass v | Pair p -> Revent (E.EventRel.singleton p) | V.Empty -> raise Exit | Unv -> Revent (Lazy.force env.EV.ks.unv) | v -> error_rel env.EV.silent (get_loc e) v and eval_events env e = match eval env e with | Set v -> v | Event e -> E.EventSet.singleton e | V.Empty -> E.EventSet.empty | Unv -> env.EV.ks.evts | v -> error_events env.EV.silent (get_loc e) v and eval_rel_set env e = match eval env e with | Rel _ | Set _ |ClassRel _ as v -> v | Event e -> Set (E.EventSet.singleton e) | Pair p -> Rel (E.EventRel.singleton p) | V.Empty -> Rel E.EventRel.empty | Unv -> Rel (Lazy.force env.EV.ks.unv) | _ -> error env.EV.silent (get_loc e) "relation or set expected" and eval_shown env e = match eval_rel_set env e with | Set v -> Shown.Set v | Rel v -> Shown.Rel v | ClassRel _ -> Shown.Rel E.EventRel.empty (* Show nothing *) | _ -> assert false and eval_events_mem env e = match eval env e with | Set s -> fun e -> E.EventSet.mem e s | Event e0 -> fun e -> E.event_compare e0 e = 0 | V.Empty -> fun _ -> false | Unv -> fun _ -> true | v -> error_events env.EV.silent (get_loc e) v and eval_proc loc env x = match find_env_loc loc env x with | Proc p -> p | _ -> Warn.user_error "procedure expected" (* For let *) and eval_bds env_bd = let rec do_rec bds = match bds with | [] -> env_bd.EV.env | (loc,p,e)::bds -> (* begin match v with | Rel r -> printf "Defining relation %s = {%a}.\n" k debug_rel r | Set s -> printf "Defining set %s = %a.\n" k debug_set s | Clo _ -> printf "Defining function %s.\n" k end; *) add_pat_val env_bd.EV.silent loc p (lazy (eval env_bd e)) (do_rec bds) in do_rec (* For let rec *) and env_rec check env loc pp bds = let fs,nfs = List.partition (fun (_,_,e) -> is_fun e) bds in let fs = List.map (fun (loc,p,e) -> match p with | Pvar x -> x,e | Ptuple _ -> error env.EV.silent loc "%s" "binding mismatch") fs in match nfs with | [] -> CheckOk (env_rec_funs env loc fs) | _ -> env_rec_vals check env loc pp fs nfs (* Recursive functions *) and env_rec_funs env_bd _loc bds = let env = env_bd.EV.env in let clos = List.map (function | f,Fun (loc,xs,body,name,fvs) -> f,eval_fun true env_bd loc xs body name fvs,fvs | _ -> assert false) bds in let add_funs pred env = List.fold_left (fun env (f,clo,_) -> if pred f then add_val f (lazy (Clo clo)) env else env) env clos in List.iter (fun (_,clo,fvs) -> clo.clo_env <- add_funs (fun x -> match x with | None -> false | Some x -> StringSet.mem x fvs) clo.clo_env) clos ; add_funs (fun _ -> true) env Compute fixpoint of relations and env_rec_vals check env_bd loc pp funs bds = (* Pretty print (relation) current values *) let vb_pp vs = List.fold_left2 (fun k (_loc,pat,_) v -> let pp_id x v k = try let v = match v with | V.Empty -> E.EventRel.empty | Unv -> Lazy.force env_bd.EV.ks.unv | Rel r -> r | _ -> raise Exit in let x = match x with | Some x -> x | None -> "_" in (x, rt_loc x v)::k with Exit -> k in let rec pp_ids xs vs k = match xs,vs with | ([],_)|(_,[]) -> k (* do not fail for pretty print *) | x::xs,v::vs -> pp_id x v (pp_ids xs vs k) in match pat with | Pvar x -> pp_id x v k | Ptuple xs -> pp_ids xs (v_as_vs v) k) [] bds vs in Fixpoint iteration let rec fix k env vs = if O.debug && O.verbose > 1 then begin let vb_pp = pp (vb_pp vs) in U.pp_failure test env_bd.EV.ks.conc (sprintf "Fix %i" k) vb_pp end ; let env,ws = fix_step env_bd env bds in let env = env_rec_funs { env_bd with EV.env=env;} loc funs in let check_ok = check { env_bd with EV.env=env; } in if not check_ok then begin if O.debug then warn loc "Fix point interrupted" ; CheckFailed env end else let over = begin try stabilised env_bd.EV.ks env vs ws with Stabilised t -> error env_bd.EV.silent loc "illegal recursion on type '%s'" (pp_typ t) end in if over then CheckOk env else fix (k+1) env ws in let env0 = List.fold_left (fun env (_,pat,_) -> match pat with | Pvar k -> add_val k (lazy V.Empty) env | Ptuple ks -> List.fold_left (fun env k -> add_val k (lazy V.Empty) env) env ks) env_bd.EV.env bds in let env0 = env_rec_funs { env_bd with EV.env=env0;} loc funs in let env = if O.bell then CheckOk env0 (* Do not compute fixpoint in bell *) else fix 0 env0 (List.map (fun (_,pat,_) -> pat2empty pat) bds) in if O.debug then warn loc "Fix point over" ; env and fix_step env_bd env bds = match bds with | [] -> env,[] | (loc,k,e)::bds -> let v = eval {env_bd with EV.env=env;} e in let env = add_pat_val env_bd.EV.silent loc k (lazy v) env in let env,vs = fix_step env_bd env bds in env,(v::vs) in (* Showing bound variables, (-doshow option) *) let find_show_shown ks env x = let loc_asrel v = match v with | Rel r -> Shown.Rel (rt_loc x r) | Set r -> if _dbg then eprintf "Found set %s: %a\n%!" x debug_set r; Shown.Set r | V.Empty -> Shown.Rel E.EventRel.empty | Unv -> Shown.Rel (rt_loc x (Lazy.force ks.unv)) | v -> Warn.warn_always "Warning show: %s is not a relation: '%s'" x (pp_val v) ; raise Not_found in try loc_asrel (Lazy.force (StringMap.find x env.vals)) with Not_found -> Shown.Rel E.EventRel.empty in let doshowone x st = if O.showsome && StringSet.mem x O.doshow then let show = lazy begin StringMap.add x (find_show_shown st.ks st.env x) (Lazy.force st.show) end in { st with show;} else st in let doshow bds st = if O.showsome then begin let to_show = StringSet.inter O.doshow (StringSet.unions (List.map bdvars bds)) in if StringSet.is_empty to_show then st else let show = lazy begin StringSet.fold (fun x show -> let r = find_show_shown st.ks st.env x in StringMap.add x r show) to_show (Lazy.force st.show) end in { st with show;} end else st in let check_bell_enum = if O.bell then fun loc st name tags -> try if name = BellName.scopes then let bell_info = BellModel.add_rel name tags st.bell_info in { st with bell_info;} else if name = BellName.regions then let bell_info = BellModel.add_regions tags st.bell_info in { st with bell_info;} else if name = BellName.levels then let bell_info = BellModel.add_rel name tags st.bell_info in let bell_info = BellModel.add_order name (StringRel.order_to_succ tags) bell_info in { st with bell_info } else st with BellModel.Defined -> error_not_silent loc "second definition of bell enum %s" name else fun _loc st _v _tags -> st in (* Check if order is being defined by a "narrower" function *) let check_bell_order = if O.bell then let fun_as_rel f_order loc st id_tags id_fun = (* This function evaluate all calls to id_fun on all tags in id_tags *) let env = from_st st in let cat_fun = try find_env_loc TxtLoc.none env id_fun with _ -> assert false in let cat_tags = let cat_tags = try StringMap.find id_tags env.EV.env.vals with Not_found -> error false loc "tag set %s must be defined while defining %s" id_tags id_fun in match Lazy.force cat_tags with | V.ValSet (TTag _,scs) -> scs | v -> error false loc "%s must be a tag set, found %s" id_tags (pp_typ (type_val v)) in let order = ValSet.fold (fun tag order -> let tgt = try eval_app loc { env with EV.silent=true;} cat_fun tag with Misc.Exit -> V.Empty in let tag = as_tag tag in let add tgt order = StringRel.add (tag,as_tag tgt) order in match tgt with | V.Empty -> order | V.Tag (_,_) -> add tgt order | V.ValSet (TTag _,vs) -> ValSet.fold add vs order | _ -> error false loc "implicit call %s('%s) must return a tag, found %s" id_fun tag (pp_typ (type_val tgt))) cat_tags StringRel.empty in let tags_set = as_tags cat_tags in let order = f_order order in if O.debug then begin warn loc "Defining hierarchy on %s from function %s" id_tags id_fun ; eprintf "%s: {%a}\n" id_tags (fun chan -> StringSet.pp chan "," output_string) tags_set ; eprintf "hierarchy: %a\n" (fun chan -> StringRel.pp chan " " (fun chan (a,b) -> fprintf chan "(%s,%s)" a b)) order end ; if not (StringRel.is_hierarchy tags_set order) then error false loc "%s defines the non-hierarchical relation %s" id_fun (BellModel.pp_order_dec order) ; try let bell_info = BellModel.add_order id_tags order st.bell_info in { st with bell_info;} with BellModel.Defined -> let old = try BellModel.get_order id_tags st.bell_info with Not_found -> assert false in if not (StringRel.equal old order) then error_not_silent loc "incompatible definition of order on %s by %s" id_tags id_fun ; st in fun bds st -> List.fold_left (fun st (_,pat,e) -> match pat with | Pvar (Some v) -> if v = BellName.wider then let loc = get_loc e in fun_as_rel Misc.identity loc st BellName.scopes v else if v = BellName.narrower then let loc = get_loc e in fun_as_rel StringRel.inverse loc st BellName.scopes v else st | Pvar None -> st | Ptuple _ -> st) st bds else fun _bds st -> st in (* Evaluate test -> bool *) let eval_test check env t e = check (test2pred env t e (eval_rel_set env e)) in let make_eval_test = function | None -> fun _env -> true | Some (_,_,t,e,name) -> if skip_this_check name then fun _env -> true else fun env -> eval_test (check_through Check) env t e in let pp_check_failure (st:st) (loc,pos,_,e,_) = warn loc "check failed" ; show_call_stack st.st.loc ; if O.debug && O.verbose > 0 then begin let pp = match pos with | Pos _ -> "???" | Txt txt -> txt in let v = eval_rel (from_st st) e in let cy = E.EventRel.get_cycle v in U.pp_failure test st.ks.conc (sprintf "Failure of '%s'" pp) (let k = show_to_vbpp st in ("CY",E.EventRel.cycle_option_to_rel cy)::k) end and show_cycle st (_loc,pos,tst,e,_) = let pp = match pos with | Pos _ -> "???" | Txt txt -> txt in let v = eval_rel (from_st st) e in let tst = match tst with Yes tst|No tst -> tst in let v = match tst with | Acyclic -> v | Irreflexive | TestEmpty -> E.EventRel.remove_transitive_edges v in let tag,cy = match tst with | Acyclic |Irreflexive -> let cy = E.EventRel.get_cycle v in if O.verbose > 0 then begin match cy with | Some xs -> eprintf "Cycle: %s\n" (String.concat " " (List.map E.pp_eiid xs)) | None -> () end ; "CY",E.EventRel.cycle_option_to_rel cy | TestEmpty -> "NE",v in U.pp test st.ks.conc (sprintf "%s for '%s'" (match tst with | Acyclic | Irreflexive -> "Cycle" | TestEmpty -> "Relation") pp) (let k = show_to_vbpp st in (tag,cy)::k) in Execute one instruction let eval_st st e = eval (from_st st) e in let rec exec : 'a. st -> ins -> ('a -> 'a) -> (st -> 'a -> 'a) -> 'a -> 'a = fun (type res) st i kfail kont (res:res) -> match i with | IfVariant (loc,v,ins_true,ins_false) -> let ins = if eval_variant_cond loc v then ins_true else ins_false in run st ins kfail kont res | Debug (_,e) -> if O.debug then begin let v = eval_st st e in eprintf "%a: value is %a\n%!" TxtLoc.pp (get_loc e) debug_val v end ; kont st res | Show (_,xs) when not O.bell -> if O.showsome then let xs = List.filter (fun x -> try ignore (StringMap.find x st.env.vals); true with Not_found -> false) xs in let show = lazy begin List.fold_left (fun show x -> StringMap.add x (find_show_shown st.ks st.env x) show) (Lazy.force st.show) xs end in kont { st with show;} res else kont st res | UnShow (_,xs) when not O.bell -> if O.showsome then let show = lazy begin List.fold_left (fun show x -> StringMap.remove x show) (Lazy.force st.show) (StringSet.(elements (diff (of_list xs) O.doshow))) end in kont { st with show;} res else kont st res | ShowAs (_,e,id) when not O.bell -> if O.showsome then let show = lazy begin try let v = Shown.apply_rel (rt_loc id) (eval_shown { (from_st st) with EV.silent=true } e) in StringMap.add id v (Lazy.force st.show) with Misc.Exit -> Lazy.force st.show end in kont { st with show; } res else kont st res | Test (tst,ty) when not O.bell -> exec_test st tst ty kfail kont res | Let (_loc,bds) -> let env = eval_bds (from_st st) bds in let st = { st with env; } in let st = doshow bds st in let st = check_bell_order bds st in kont st res | Rec (loc,bds,testo) -> let env = match env_rec (make_eval_test testo) (from_st st) loc (fun pp -> pp@show_to_vbpp st) bds with | CheckOk env -> Some env | CheckFailed env -> if O.debug then begin let st = { st with env; } in let st = doshow bds st in pp_check_failure st (Misc.as_some testo) end ; None in begin match env with | None -> kfail res | Some env -> let st = { st with env; } in let st = doshow bds st in Check again for strictskip let st = match testo with | None -> st | Some (_,_,t,e,name) -> if O.strictskip && skip_this_check name && not (eval_test Misc.identity (from_st st) t e) then begin { st with skipped = StringSet.add (Misc.as_some name) st.skipped;} end else st in (* Check bell definitions *) let st = check_bell_order bds st in kont st res end | InsMatch (loc,e,cls,d) -> let v = eval_st st e in begin match v with | V.Tag (_,s) -> let rec match_rec = function | [] -> begin match d with | Some dseq -> run st dseq kfail kont res | None -> error_not_silent loc "pattern matching failed on value '%s'" s end | (ps,pprog)::cls -> if s = ps then run st pprog kfail kont res else match_rec cls in match_rec cls | V.Empty -> error_not_silent (get_loc e) "matching on empty" | V.Unv -> error_not_silent (get_loc e) "matching on universe" | _ -> error_not_silent (get_loc e) "matching on non-tag value of type '%s'" (pp_typ (type_val v)) end | Include (loc,fname) -> let fname = match fname with | "lock.cat" when O.compat -> "cos-opt.cat" | _ -> fname in if StringSet.mem fname st.st.included && (O.verbose > 0 || O.debug_files) then begin Warn.warn_always "%a: including %s another time" TxtLoc.pp loc fname end ; do_include loc fname st kfail kont res | Procedure (_,name,args,body,is_rec) -> let p = { proc_args=args; proc_env=st.env; proc_body=body; } in let proc = Proc p in let env_plus_p = do_add_val name (lazy proc) st.env in begin match is_rec with | IsRec -> p.proc_env <- env_plus_p | IsNotRec -> () end ; kont { st with env = env_plus_p } res | Call (loc,name,es,tname) when not O.bell -> let skip = skip_this_check tname || skip_this_check (Some name) in if O.debug && skip then warn loc "skipping call: %s" (match tname with | Some n -> n | None -> name); if skip && not O.strictskip then (* won't call *) kont st res else (* will call *) let env0 = from_st st in let p = protect_call st (eval_proc loc env0) name in let env1 = protect_call st (fun penv -> add_args loc p.proc_args (eval env0 es) env0 penv) p.proc_env in if skip then (* call for boolean... *) let pname = match tname with | Some _ -> tname | None -> Some name in let tval = let benv = env1 in run { (push_loc st (loc,pname)) with env=benv; } p.proc_body (fun x -> x) (fun _ _ -> true) false in if tval then kont st res else kont { st with skipped = StringSet.add (Misc.as_some tname) st.skipped;} res else let pname = match tname with | Some _ -> tname | None -> Some name in let st = push_loc st (loc,pname) in run { st with env = env1; } p.proc_body kfail (fun st_call res -> let st_call = pop_loc st_call in kont { st_call with env = st.env ;} res) (* Note, show is preserved *) res | Enum (loc,name,xs) -> let env = st.env in let tags = List.fold_left (fun env x -> StringMap.add x name env) env.tags xs in let enums = StringMap.add name xs env.enums in (* add a set of all tags... *) let alltags = lazy begin let vs = List.fold_left (fun k x -> ValSet.add (V.Tag (name,x)) k) ValSet.empty xs in V.ValSet (TTag name,vs) end in let env = do_add_val name alltags env in if O.debug && O.verbose > 1 then warn loc "adding set of all tags for %s" name ; let env = { env with tags; enums; } in let st = { st with env;} in let st = check_bell_enum loc st name xs in kont st res | Forall (_loc,x,e,body) when not O.bell -> let st0 = st in let env0 = st0.env in let v = eval (from_st st0) e in begin match tag2set v with | V.Empty -> kont st res | ValSet (_,set) -> let rec run_set st vs res = if ValSet.is_empty vs then kont st res else let v = try ValSet.choose vs with Not_found -> assert false in let env = do_add_val x (lazy v) env0 in run { st with env;} body kfail (fun st res -> run_set { st with env=env0;} (ValSet.remove v vs) res) res in run_set st set res | _ -> error_not_silent (get_loc e) "forall instruction applied to non-set value" end | WithFrom (_loc,x,e) when not O.bell -> let st0 = st in let env0 = st0.env in let v = eval (from_st st0) e in begin match v with | V.Empty -> kfail res | ValSet (_,vs) -> ValSet.fold (fun v res -> let env = do_add_val x (lazy v) env0 in kont (doshowone x {st with env;}) res) vs res | _ -> error_not_silent (get_loc e) "set expected" end | Events (loc,x,es,def) when O.bell -> let x = BellName.tr_compat x in if not (StringSet.mem x BellName.all_sets) then error_not_silent loc "event type %s is not part of legal {%s}\n" x (StringSet.pp_str "," Misc.identity BellName.all_sets) ; let vs = List.map (eval_loc (from_st st)) es in let event_sets = List.map (fun (loc,v) -> match v with | ValSet(TTag _,elts) -> let tags = ValSet.fold (fun elt k -> let tag = as_tag elt in match tag with | "release" when O.compat -> "assign"::"release"::k | "acquire"when O.compat -> "deref"::"lderef"::"acquire"::k | _ -> tag::k) elts [] in StringSet.of_list tags | V.Tag (_,tag) -> StringSet.singleton tag | _ -> error false loc "event declaration expected a set of tags, found %s" (pp_val v)) vs in let bell_info = BellModel.add_events x event_sets st.bell_info in let bell_info = if def then let defarg = List.map2 (fun ss e -> match StringSet.as_singleton ss with | None -> error_not_silent (get_loc e) "ambiguous default declaration" | Some a -> a) event_sets es in try BellModel.add_default x defarg bell_info with BellModel.Defined -> error_not_silent loc "second definition of default for %s" x else bell_info in let st = { st with bell_info;} in kont st res | Events _ -> assert (not O.bell) ; kont st res (* Ignore bell constructs when executing model *) | Test _|UnShow _|Show _|ShowAs _ | Call _|Forall _ | WithFrom _ -> assert O.bell ; kont st res (* Ignore cat constructs when executing bell *) and exec_test : 'a.st -> app_test -> test_type -> ('a -> 'a) -> (st -> 'a -> 'a) -> 'a -> 'a = fun st (loc,_,t,e,name as tst) test_type kfail kont res -> let skip = skip_this_check name in let cycle = cycle_this_check name in if O.debug && skip then warn loc "skipping check: %s" (Misc.as_some name) ; if O.strictskip || not skip || cycle then let ok = eval_test (check_through test_type) (from_st st) t e in if cycle && begin match ok,t with | (false,Yes _) | (true,No _) -> true | (false,No _) | (true,Yes _) -> false end then show_cycle st tst ; if ok then match test_type with | Check|UndefinedUnless|Assert -> kont st res | Flagged -> begin match name with | None -> warn loc "this flagged test does not have a name" ; kont st res | Some name -> if O.debug then warn loc "flag %s recorded" name ; kont {st with flags= Flag.Set.add (Flag.Flag name) st.flags;} res end else begin if skip then begin assert O.strictskip ; kont { st with skipped = StringSet.add (Misc.as_some name) st.skipped;} res end else begin match test_type with | Check -> if O.debug then pp_check_failure st tst ; kfail res | UndefinedUnless -> kont {st with flags=Flag.Set.add Flag.Undef st.flags;} res | Flagged -> kont st res | Assert -> let a = match name with | None -> "(unknown)" | Some name -> name in Warn.user_error "%s assertion failed, check input test." a end end else begin W.warn "Skipping check %s" (Misc.as_some name) ; kont st res end and do_include : 'a . TxtLoc.t -> string ->st -> ('a -> 'a) -> (st -> 'a -> 'a) -> 'a -> 'a = fun loc fname st kfail kont res -> (* Run sub-model file *) if O.debug then warn loc "include \"%s\"" fname ; let module P = ParseModel.Make (struct include LexUtils.Default let libfind = O.libfind end) in let (_,_,iprog) = try P.parse fname with Misc.Fatal msg | Misc.UserError msg -> error_not_silent loc "%s" msg in let stst = st.st in let included = StringSet.add fname stst.included in let stst = { stst with included; } in let st = { st with st=stst; } in run st iprog kfail kont res and run : 'a.st -> ins list -> ('a -> 'a) -> (st -> 'a -> 'a) -> 'a -> 'a = fun st c kfail kont res -> match c with | [] -> kont st res | i::c -> exec st i kfail (fun st res -> run st c kfail kont res) res in fun ks m vb_pp kont res -> (* Primitives *) let m = add_primitives ks (env_from_ienv m) in (* Initial show's *) if _dbg then begin eprintf "showsome=%b, doshow={%s}\n" O.showsome (StringSet.pp_str ", " Misc.identity O.doshow) end ; let show = if O.showsome then lazy begin let show = List.fold_left (fun show (tag,v) -> StringMap.add tag (Shown.Rel v) show) StringMap.empty (Lazy.force vb_pp) in StringSet.fold (fun tag show -> StringMap.add tag (find_show_shown ks m tag) show) O.doshow show end else lazy StringMap.empty in let st = {env=m; show=show; skipped=StringSet.empty; flags=Flag.Set.empty; ks; bell_info=BellModel.empty_info; st=inter_st_empty; } in let kont st res = kont (st2out st) res in let just_run st res = run st mprog kfail kont res in do_include TxtLoc.none "stdlib.cat" st kfail (match O.bell_fname with | None -> just_run (* No bell file, just run *) | Some fname -> fun st res -> do_include TxtLoc.none fname st kfail just_run res) res end
null
https://raw.githubusercontent.com/herd/herdtools7/14b473b819601028afc0464f304a2cbed5ad26d9/lib/interpreter.ml
ocaml
************************************************************************** the diy toolsuite en Automatique and the authors. All rights reserved. abiding by the rules of distribution of free software. You can use, ************************************************************************** * Interpreter for a user-specified model executing bell file Show control find files check variant Simplified Sem module. In effect, the interpreter needs a restricted subset of Sem functionalities: set of events, relation on events and that is about all. A few utilities are passed as the next "U" argument to functor. po labelled fence(s) localised fence relation Some constants passed to the interpreter, made open for the convenience of building them from outside Initial environment, they differ from internal env, so as not to expose the polymorphic argument of the later Subset of interpreter state used by the caller Interpreter ************************** Convenient abbreviations ************************** Add relations amongst event classes, notice that a class is an event set, regardless of class disjointness Check utilities Model interpret Debug printing Internal typing type X name elt type X set unique id (hack) type X name elt type X set unique id (hack) Discarded before Note: cannot use Full in sets.. Expand all legitimate empty's Legitimate cmp Errors Silent failure pretty lift a tag to a singleton set extract lists from tuples Add values to env Initial env, a restriction of env Go on Primitive added internally to actual env Interpretation result Remove transitive edges, except if instructed not to Type of eval env find without forcing lazy's Relation Class relation Event Set Value Set Get an expression location Tests are polymorphic, acting on relations, class relations and sets Called on Rel or Set ****************************** Helpers for n-ary operations ****************************** eprintf "Value: %s, Type %s\n" (pp_val v) (pp_typ t1) ; Check explicit set arguments Union is polymorphic Definition of primitives Lift a relation from events to event classes Delift a relation from event classes to events Restrict delift by intersection (fulldeflift(clsr) & loc) jade: we assert false when all the events in the execution bear the tag tag ************* Interpreter ************* Polymorphic empty Back to polymorphism Tuple is an actual N-ary operator N-ary operators, those associative binary operators are optimized Binary operators Binary notation kept in parser By parsing Application/bindings No check in expr binding ici Show nothing For let begin match v with | Rel r -> printf "Defining relation %s = {%a}.\n" k debug_rel r | Set s -> printf "Defining set %s = %a.\n" k debug_set s | Clo _ -> printf "Defining function %s.\n" k end; For let rec Recursive functions Pretty print (relation) current values do not fail for pretty print Do not compute fixpoint in bell Showing bound variables, (-doshow option) Check if order is being defined by a "narrower" function This function evaluate all calls to id_fun on all tags in id_tags Evaluate test -> bool Check bell definitions won't call will call call for boolean... Note, show is preserved add a set of all tags... Ignore bell constructs when executing model Ignore cat constructs when executing bell Run sub-model file Primitives Initial show's No bell file, just run
, University College London , UK . , INRIA Paris - Rocquencourt , France . Copyright 2013 - present Institut National de Recherche en Informatique et This software is governed by the CeCILL - B license under French law and modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . open Printf module type Config = sig val m : AST.t name of bell file if present Restricted Model . Config val showsome : bool val debug : bool val debug_files : bool val verbose : int val skipchecks : StringSet.t val strictskip : bool val cycles : StringSet.t val compat : bool val doshow : StringSet.t val showraw : StringSet.t val symetric : StringSet.t val libfind : string -> string val variant : string -> bool end module type SimplifiedSem = sig module E : sig type event val event_compare : event -> event -> int val pp_eiid : event -> string val pp_instance : event -> string val is_store : event -> bool val is_pt : event -> bool module EventSet : MySet.S with type elt = event module EventRel : InnerRel.S with type elt0 = event and module Elts = EventSet module EventMap : MyMap.S with type key = event end type test type concrete type event = E.event type event_set = E.EventSet.t type event_rel = E.EventRel.t type rel_pp = (string * event_rel) list type set_pp = event_set StringMap.t end module Make (O:Config) (S:SimplifiedSem) (U: sig val partition_events : S.event_set -> S.event_set list val loc2events : string -> S.event_set -> S.event_set val check_through : bool -> bool val pp_failure : S.test -> S.concrete -> string -> S.rel_pp -> unit val pp : S.test -> S.concrete -> string -> S.rel_pp -> unit val fromto : val same_value : S.event -> S.event -> bool val same_oa : S.event -> S.event -> bool val writable2 : S.event -> S.event -> bool end) : sig type ks = { id : S.event_rel Lazy.t; unv : S.event_rel Lazy.t; evts : S.event_set; conc : S.concrete; po:S.event_rel;} type init_env val init_env_empty : init_env val add_rels : init_env -> S.event_rel Lazy.t Misc.Simple.bds -> init_env val add_sets : init_env -> S.event_set Lazy.t Misc.Simple.bds -> init_env val get_set : init_env -> string -> S.event_set Lazy.t option type st_out = { out_show : S.rel_pp Lazy.t ; out_sets : S.set_pp Lazy.t ; out_skipped : StringSet.t ; out_flags : Flag.Set.t ; out_bell_info : BellModel.info ; } val interpret : S.test -> ('a -> 'a) -> ks -> init_env -> S.rel_pp Lazy.t -> (st_out -> 'a -> 'a) -> 'a -> 'a end = struct let _dbg = false let () = if _dbg then match O.bell_fname with | None -> eprintf "Interpret has no bell file\n" | Some fname -> eprintf "Interpret bell file is %s\n" fname let next_id = let id = ref 0 in fun () -> let r = !id in id := r+1 ; r module E = S.E module W = Warn.Make(O) module ClassRel = InnerRel.Make(E.EventSet) open AST let skip_this_check name = match name with | Some name -> StringSet.mem name O.skipchecks | None -> false let cycle_this_check name = match name with | Some name -> StringSet.mem name O.cycles | None -> false let check_through test_type ok = match test_type with | Check -> U.check_through ok | UndefinedUnless|Flagged|Assert -> ok let (_,_,mprog) = O.m let _debug_proc chan p = fprintf chan "%i" p let debug_event chan e = fprintf chan "%s" (E.pp_eiid e) let debug_set chan s = output_char chan '{' ; E.EventSet.pp chan "," debug_event s ; output_char chan '}' let debug_rel chan r = E.EventRel.pp chan "," (fun chan (e1,e2) -> fprintf chan "%a -> %a" debug_event e1 debug_event e2) r let debug_class_rel chan r = ClassRel.pp chan "," (fun chan (e1,e2) -> fprintf chan "%a -> %a" debug_set e1 debug_set e2) r type ks = { id : S.event_rel Lazy.t; unv : S.event_rel Lazy.t; evts : S.event_set; conc : S.concrete; po:S.event_rel; } type typ = | TEmpty | TEvent | TEvents | TPair | TRel | TClassRel | TTag of string |TClo | TProc | TSet of typ | TTuple of typ list let rec eq_type t1 t2 = match t1,t2 with | (TEmpty,(TSet _ as t)) | ((TSet _ as t),TEmpty) -> Some t | (TEvents,TEvents) | (TEmpty,TEvents) | (TEvents,TEmpty) -> Some TEvents | (TRel,TRel) | (TEmpty,TRel) | (TRel,TEmpty) -> Some TRel | (TClassRel,TClassRel) | (TEmpty,TClassRel) | (TClassRel,TEmpty) -> Some TClassRel | TEvent,TEvent -> Some TEvent | TPair,TPair -> Some TPair | TTag s1,TTag s2 when s1 = s2 -> Some t1 | TSet t1,TSet t2 -> begin match eq_type t1 t2 with | None -> None | Some t -> Some (TSet t) end | TTuple ts1,TTuple ts2 -> Misc.app_opt (fun ts -> TTuple ts) (eq_types ts1 ts2) | TClo,TClo -> Some TClo | TProc,TProc -> Some TProc | _,_ -> None and eq_types ts1 ts2 = match ts1,ts2 with | [],[] -> Some [] | ([],_::_)|(_::_,[]) -> None | t1::ts1,t2::ts2 -> begin let ts = eq_types ts1 ts2 and t = eq_type t1 t2 in match t,ts with | Some t,Some ts -> Some (t::ts) | _,_ -> None end let type_equal t1 t2 = match eq_type t1 t2 with | None -> false | Some _ -> true exception CompError of string exception PrimError of string let rec pp_typ = function | TEmpty -> "{}" | TEvent -> "event" | TEvents -> "events" | TPair -> "pair" | TRel -> "rel" | TClassRel -> "classrel" | TTag ty -> ty | TClo -> "closure" | TProc -> "procedure" | TSet elt -> sprintf "%s set" (pp_typ elt) | TTuple ts -> sprintf "(%s)" (String.concat " * " (List.map pp_typ ts)) module rec V : sig type v = | Empty | Unv | Pair of (S.event * S.event) | Rel of S.event_rel | ClassRel of ClassRel.t | Event of S.event | Set of S.event_set | Clo of closure | Prim of string * int * (v -> v) | Proc of procedure | Tuple of v list and env = { vals : v Lazy.t StringMap.t; enums : string list StringMap.t; tags : string StringMap.t; } and closure = { clo_args : AST.pat ; mutable clo_env : env ; clo_body : AST.exp; and procedure = { proc_args : AST.pat ; mutable proc_env : env; proc_body : AST.ins list; } val type_val : v -> typ end = struct type v = | Empty | Unv | Pair of (S.event * S.event) | Rel of S.event_rel | ClassRel of ClassRel.t | Event of S.event | Set of S.event_set | Clo of closure | Prim of string * int * (v -> v) | Proc of procedure | Tuple of v list and env = { vals : v Lazy.t StringMap.t; enums : string list StringMap.t; tags : string StringMap.t; } and closure = { clo_args : AST.pat ; mutable clo_env : env ; clo_body : AST.exp; and procedure = { proc_args : AST.pat ; mutable proc_env : env; proc_body : AST.ins list; } let rec type_val = function | V.Empty -> TEmpty | Pair _ -> TPair | Rel _ -> TRel | ClassRel _ -> TClassRel | Event _ -> TEvent | Set _ -> TEvents | Clo _|Prim _ -> TClo | Proc _ -> TProc | Tag (t,_) -> TTag t | ValSet (t,_) -> TSet t | Tuple vs -> TTuple (List.map type_val vs) end and ValOrder : Set.OrderedType with type t = V.v = struct type t = V.v open V let error fmt = ksprintf (fun msg -> raise (CompError msg)) fmt let rec compare v1 v2 = match v1,v2 with | V.Empty,V.Empty -> 0 | V.Empty,ValSet (_,s) -> ValSet.compare ValSet.empty s | ValSet (_,s),V.Empty -> ValSet.compare s ValSet.empty | V.Empty,Rel r -> E.EventRel.compare E.EventRel.empty r | Rel r,V.Empty -> E.EventRel.compare r E.EventRel.empty | V.Empty,Set s -> E.EventSet.compare E.EventSet.empty s | Set s,V.Empty -> E.EventSet.compare s E.EventSet.empty | V.Empty,ClassRel r -> ClassRel.compare ClassRel.empty r | ClassRel r,V.Empty -> ClassRel.compare r ClassRel.empty | Tag (_,s1), Tag (_,s2) -> String.compare s1 s2 | Event e1,Event e2 -> E.event_compare e1 e2 | ValSet (_,s1),ValSet (_,s2) -> ValSet.compare s1 s2 | Rel r1,Rel r2 -> E.EventRel.compare r1 r2 | ClassRel r1,ClassRel r2 -> ClassRel.compare r1 r2 | Set s1,Set s2 -> E.EventSet.compare s1 s2 | (Clo {clo_name = (_,i1);_},Clo {clo_name=(_,i2);_}) | (Prim (_,i1,_),Prim (_,i2,_)) -> Misc.int_compare i1 i2 | Clo _,Prim _ -> 1 | Prim _,Clo _ -> -1 | Tuple vs,Tuple ws -> compares vs ws | (Unv,_)|(_,Unv) -> error "Universe in compare" | _,_ -> let t1 = V.type_val v1 and t2 = V.type_val v2 in if type_equal t1 t2 then error "Sets of %s are illegal" (pp_typ t1) else error "Heterogeneous set elements: types %s and %s " (pp_typ t1) (pp_typ t2) and compares vs ws = match vs,ws with | [],[] -> 0 | [],_::_ -> -1 | _::_,[] -> 1 | v::vs,w::ws -> begin match compare v w with | 0 -> compares vs ws | r -> r end end and ValSet : (MySet.S with type elt = V.v) = MySet.Make(ValOrder) type fix = CheckFailed of V.env | CheckOk of V.env let error silent loc fmt = ksprintf (fun msg -> if O.debug || not silent then eprintf "%a: %s\n" TxtLoc.pp loc msg ; fmt let error_not_silent loc fmt = error false loc fmt let warn loc fmt = ksprintf (fun msg -> Warn.warn_always "%a: %s" TxtLoc.pp loc msg) fmt open V let pp_type_val v = pp_typ (type_val v) let rec pp_val = function | Unv -> "<universe>" | V.Empty -> "{}" | Tag (_,s) -> sprintf "'%s" s | ValSet (_,s) -> sprintf "{%s}" (ValSet.pp_str "," pp_val s) | Clo {clo_name=(n,x);_} -> sprintf "%s_%i" n x | V.Tuple vs -> sprintf "(%s)" (String.concat "," (List.map pp_val vs)) | v -> sprintf "<%s>" (pp_type_val v) let rec debug_val_set chan s = output_char chan '{' ; ValSet.pp chan "," debug_val s ; output_char chan '}' and debug_val chan = function | ValSet (_,s) -> debug_val_set chan s | Set es -> debug_set chan es | Rel r -> debug_rel chan r | ClassRel r -> debug_class_rel chan r | v -> fprintf chan "%s" (pp_val v) let tag2set v = match v with | V.Tag (t,_) -> ValSet (TTag t,ValSet.singleton v) | _ -> v let pat_as_vars = function | Pvar x -> [x] | Ptuple xs -> xs let v_as_vs = function | V.Tuple vs -> vs | Pair (ev1,ev2) -> [Event ev1;Event ev2;] | v -> [v] let pat2empty = function | Pvar _ -> V.Empty | Ptuple xs -> V.Tuple (List.map (fun _ -> V.Empty) xs) let bdvar = function | None -> StringSet.empty | Some x -> StringSet.singleton x let bdvars (_,pat,_) = match pat with | Pvar x -> bdvar x | Ptuple xs -> StringSet.unions (List.map bdvar xs) let do_add_val k v env = { env with vals = StringMap.add k v env.vals; } let add_val k v env = match k with | None -> env | Some k -> do_add_val k v env let add_pat_val silent loc pat v env = match pat with | Pvar k -> add_val k v env | Ptuple ks -> let rec add_rec extract env = function | [] -> env | k::ks -> let vk = lazy begin match extract (Lazy.force v) with | v::_ -> v | [] -> error silent loc "%s" "binding mismatch" end in let env = add_val k vk env and extract v = match extract v with | _::vs -> vs | [] -> error silent loc "%s" "binding mismatch" in add_rec extract env ks in add_rec v_as_vs env ks let env_empty = {vals=StringMap.empty; enums=StringMap.empty; tags=StringMap.empty; } type init_env = E.EventSet.t Lazy.t Misc.Simple.bds * E.EventRel.t Lazy.t Misc.Simple.bds let init_env_empty = [],[] let add_rels (sets,rels) bds = (sets,bds@rels) and add_sets (sets,rels) bds = (bds@sets,rels) let get_set (sets,_) key = let rec f_rec = function | [] -> None | (k,v)::sets -> if Misc.string_eq key k then Some v else f_rec sets in f_rec sets let add_vals_once mk = List.fold_right (fun (k,v) m -> if StringMap.mem k m then Warn.warn_always "redefining key '%s' in cat interpreter initial environment" k ; StringMap.add k (mk v) m) let env_from_ienv (sets,rels) = let vals = add_vals_once (fun v -> lazy (Set (Lazy.force v))) sets StringMap.empty in let vals = add_vals_once (fun v -> lazy (Rel (Lazy.force v))) rels vals in { env_empty with vals; } let add_prims env bds = let vals = env.vals in let vals = List.fold_left (fun vals (k,f) -> StringMap.add k (lazy (Prim (k,next_id (),f))) vals) vals bds in { env with vals; } type loc = (TxtLoc.t * string option) list module Shown = struct type t = Rel of S.event_rel | Set of S.event_set let apply_rel f (sr:t) = match sr with | Rel r -> Rel (f r) | Set _ -> sr end Internal status of interpreter type inter_st = { included : StringSet.t ; loc : loc ; } let inter_st_empty = { included = StringSet.empty; loc = []; } Complete status type st = { env : V.env ; show : Shown.t StringMap.t Lazy.t ; skipped : StringSet.t ; flags : Flag.Set.t ; ks : ks ; bell_info : BellModel.info ; st : inter_st ; } type st_out = { out_show : S.event_rel Misc.Simple.bds Lazy.t ; out_sets : S.event_set StringMap.t Lazy.t ; out_skipped : StringSet.t ; out_flags : Flag.Set.t ; out_bell_info : BellModel.info ; } let rt_loc lbl = if O.verbose <= 1 && not (StringSet.mem lbl O.symetric) && not (StringSet.mem lbl O.showraw) then E.EventRel.remove_transitive_edges else (fun x -> x) let show_to_vbpp st = StringMap.fold (fun tag v k -> match v with | Shown.Rel v -> (tag,v)::k | Shown.Set _ -> k) (Lazy.force st.show) [] let show_to_sets st = StringMap.fold (fun tag v k -> match v with | Shown.Rel _ -> k | Shown.Set v -> StringMap.add tag v k) (Lazy.force st.show) StringMap.empty let st2out st = {out_show = lazy (show_to_vbpp st) ; out_sets = lazy (show_to_sets st) ; out_skipped = st.skipped ; out_flags = st.flags ; out_bell_info = st.bell_info ; } let push_loc st loc = let ist = st.st in let loc = loc :: ist.loc in let ist = { ist with loc; } in { st with st=ist; } let pop_loc st = let ist = st.st in match ist.loc with | [] -> assert false | _::loc -> let ist = { ist with loc; } in { st with st=ist; } let show_loc (loc,name) = eprintf "%a: calling procedure%s\n" TxtLoc.pp loc (match name with | None -> "" | Some n -> " as " ^ n) let show_call_stack st = List.iter show_loc st let protect_call st f x = try f x with Misc.Exit -> let st = st.st in List.iter (fun loc -> if O.debug then show_loc loc) st.loc ; raise Misc.Exit module EV = struct type env = { env : V.env ; silent : bool; ks : ks; } end let from_st st = { EV.env=st.env; silent=false; ks=st.ks; } let set_op env loc t op s1 s2 = try V.ValSet (t,op s1 s2) with CompError msg -> error env.EV.silent loc "%s" msg let tags_universe {enums=env; _} t = let tags = try StringMap.find t env with Not_found -> assert false in let tags = ValSet.of_list (List.map (fun s -> V.Tag (t,s)) tags) in tags let find_env {vals=env; _} k = Lazy.force begin try StringMap.find k env with | Not_found -> Warn.user_error "unbound var: %s" k end let find_env_loc loc env k = try find_env env.EV.env k with Misc.UserError msg -> error env.EV.silent loc "%s" msg let just_find_env fail loc env k = try StringMap.find k env.EV.env.vals with Not_found -> if fail then error env.EV.silent loc "unbound var: %s" k else raise Not_found let as_rel ks = function | Rel r -> r | Empty -> E.EventRel.empty | Unv -> Lazy.force ks.unv | v -> eprintf "this is not a relation: '%s'" (pp_val v) ; assert false let as_classrel = function | ClassRel r -> r | Empty -> ClassRel.empty | Unv -> Warn.fatal "No universal class relation" | v -> eprintf "this is not a relation: '%s'" (pp_val v) ; assert false let as_set ks = function | Set s -> s | Empty -> E.EventSet.empty | Unv -> ks.evts | _ -> assert false let as_valset = function | ValSet (_,v) -> v | _ -> assert false let as_tag = function | V.Tag (_,tag) -> tag | _ -> assert false let as_tags tags = let ss = ValSet.fold (fun v k -> as_tag v::k) tags [] in StringSet.of_list ss exception Stabilised of typ let stabilised ks env = let rec stabilised vs ws = match vs,ws with | [],[] -> true | v::vs,w::ws -> begin match v,w with | (_,V.Empty)|(Unv,_) -> stabilised vs ws | (V.Empty,Rel w) -> E.EventRel.is_empty w && stabilised vs ws | (Rel v,Unv) -> E.EventRel.subset (Lazy.force ks.unv) v && stabilised vs ws | Rel v,Rel w -> E.EventRel.subset w v && stabilised vs ws | (V.Empty,ClassRel w) -> ClassRel.is_empty w && stabilised vs ws | ClassRel v,ClassRel w -> ClassRel.subset w v && stabilised vs ws | (V.Empty,Set w) -> E.EventSet.is_empty w && stabilised vs ws | (Set v,Unv) -> E.EventSet.subset ks.evts v && stabilised vs ws | Set v,Set w -> E.EventSet.subset w v && stabilised vs ws | (V.Empty,ValSet (_,w)) -> ValSet.is_empty w && stabilised vs ws | (ValSet (TTag t,v),Unv) -> ValSet.subset (tags_universe env t) v && stabilised vs ws | ValSet (_,v),ValSet (_,w) -> ValSet.subset w v && stabilised vs ws | _,_ -> eprintf "Problem %s vs. %s\n" (pp_val v) (pp_val w) ; raise (Stabilised (type_val w)) end | _,_ -> assert false in stabilised Syntactic function let is_fun = function | Fun _ -> true | _ -> false let get_loc = function | Konst (loc,_) | AST.Tag (loc,_) | Var (loc,_) | ExplicitSet (loc,_) | Op1 (loc,_,_) | Op (loc,_,_) | Bind (loc,_,_) | BindRec (loc,_,_) | App (loc,_,_) | Fun (loc,_,_,_,_) | Match (loc,_,_,_) | MatchSet (loc,_,_,_) | Try (loc,_,_) | If (loc,_,_,_) -> loc let empty_rel = Rel E.EventRel.empty let error_typ silent loc t0 t1 = error silent loc"type %s expected, %s found" (pp_typ t0) (pp_typ t1) let error_rel silent loc v = error_typ silent loc TRel (type_val v) let error_events silent loc v = error_typ silent loc TEvents (type_val v) let test2pred env t e v = match t,v with | Acyclic,Rel r -> E.EventRel.is_acyclic r | Irreflexive,Rel r -> E.EventRel.is_irreflexive r | Acyclic,ClassRel r -> ClassRel.is_acyclic r | Irreflexive,ClassRel r -> ClassRel.is_irreflexive r | TestEmpty,Rel r -> E.EventRel.is_empty r | TestEmpty,ClassRel r -> ClassRel.is_empty r | TestEmpty,Set s -> E.EventSet.is_empty s | (Acyclic|Irreflexive),Set _ -> error env.EV.silent (get_loc e) "relation expected" let test2pred env t e v = match t with | Yes t -> test2pred env t e v | No t -> not (test2pred env t e v) let type_list silent = function | [] -> assert false | (_,v)::vs -> let rec type_rec t0 = function | [] -> t0,[] | (loc,v)::vs -> let t1 = type_val v in match eq_type t0 t1 with | Some t0 -> let t0,vs = type_rec t0 vs in t0,v::vs | None -> error silent loc "type %s expected, %s found" (pp_typ t0) (pp_typ t1) in let t0,vs = type_rec (type_val v) vs in t0,v::vs let set_args silent = let rec s_rec = function | [] -> [] | (loc,Unv)::_ -> error silent loc "universe in explicit set" | x::xs -> x::s_rec xs in s_rec let union_args = let rec u_rec = function | [] -> [] | (_,V.Empty)::xs -> u_rec xs | (_,Unv)::_ -> raise Exit | (loc,v)::xs -> (loc,tag2set v)::u_rec xs in u_rec module type PrimArg = sig type base module Rel : InnerRel.S with type elt0=base val debug_set : out_channel -> Rel.Elts.t -> unit val debug_rel : out_channel -> Rel.t -> unit val mk_val : Rel.t -> V.v val typ : typ end module EventArg = struct type base = E.event module Rel = E.EventRel let debug_set = debug_set let debug_rel = debug_rel let mk_val r = Rel r let typ = TRel end module ClassArg = struct type base = E.EventSet.t module Rel = ClassRel let debug_set chan ss = fprintf chan "{%a}" (fun chan ss -> ClassRel.Elts.pp chan "," debug_set ss) ss let debug_rel = debug_class_rel let mk_val r = ClassRel r let typ = TClassRel end Debug ClassRel 's as instance relations module InstanceArg = struct type base = E.EventSet.t module let debug_set chan ss = chan " { % a } " ( fun chan ss - > ClassRel.Elts.pp chan " , " debug_set ss ) ss let debug_instance chan es = try chan " % s " ( E.pp_instance ( E.EventSet.choose es ) ) with Not_found - > assert false let = ClassRel.pp chan " , " ( fun chan ( e1,e2 ) - > chan " { % a - > % a } " debug_instance e1 debug_instance e2 ) r let debug_rel = debug_instance_rel let mk_val r = ClassRel r let typ = end module InstanceArg = struct type base = E.EventSet.t module Rel = ClassRel let debug_set chan ss = fprintf chan "{%a}" (fun chan ss -> ClassRel.Elts.pp chan "," debug_set ss) ss let debug_instance chan es = try fprintf chan "%s" (E.pp_instance (E.EventSet.choose es)) with Not_found -> assert false let debug_instance_rel chan r = ClassRel.pp chan "," (fun chan (e1,e2) -> fprintf chan "{%a -> %a}" debug_instance e1 debug_instance e2) r let debug_rel = debug_instance_rel let mk_val r = ClassRel r let typ = TClassRel end *) let arg_mismatch () = raise (PrimError "argument mismatch") let partition arg = match arg with | Set evts -> let r = U.partition_events evts in let vs = List.map (fun es -> Set es) r in ValSet (TEvents,ValSet.of_list vs) | _ -> arg_mismatch () and classes arg = match arg with | Rel r -> let r = E.EventRel.classes r in let vs = List.map (fun es -> Set es) r in ValSet (TEvents,ValSet.of_list vs) | _ -> arg_mismatch () and lift arg = match arg with | V.Tuple [ValSet (TEvents,cls);Rel r] -> let m = ValSet.fold (fun v m -> match v with | Set evts -> E.EventSet.fold (fun e m -> E.EventMap.add e evts m) evts m | _ -> assert false) cls E.EventMap.empty in let clsr = E.EventRel.fold (fun (e1,e2) k -> try let cl1 = E.EventMap.find e1 m and cl2 = E.EventMap.find e2 m in ClassRel.add (cl1,cl2) k with Not_found -> k) r ClassRel.empty in V.ClassRel clsr | _ -> arg_mismatch () and delift arg = match arg with | ClassRel clsr -> let r = ClassRel.fold (fun (cl1,cl2) k -> E.EventRel.cartesian cl1 cl2::k) clsr [] in Rel (E.EventRel.unions r) | _ -> arg_mismatch () and deliftinter arg = match arg with | V.Tuple[Rel m;ClassRel clsr] -> let make_rel_from_classpair (cl1,cl2) = E.EventRel.filter (fun (e1,e2) -> E.EventSet.mem e1 cl1 && E.EventSet.mem e2 cl2) m in let r = ClassRel.fold (fun clp k -> make_rel_from_classpair clp::k) clsr [] in Rel (E.EventRel.unions r) | _ -> arg_mismatch () and linearisations = let module Make = functor (In : PrimArg) -> struct let mem = In.Rel.Elts.mem let zyva es r = if O.debug && O.verbose > 1 then begin eprintf "Linearisations:\n" ; eprintf " %a\n" In.debug_set es ; eprintf " {%a}\n" In.debug_rel (In.Rel.filter (fun (e1,e2) -> mem e1 es && mem e2 es) r) end ; let nodes = es in if O.debug && O.verbose > 1 then begin let n = In.Rel.all_topos_kont_rel nodes r (fun _ -> 0) (fun _ k -> k+1) 0 in eprintf "number of orders: %i\n" n end ; let rs = In.Rel.all_topos_kont_rel nodes r (fun o -> let o = In.Rel.filter (fun (e1,e2) -> mem e1 es && mem e2 es) o in if O.debug then begin eprintf "Linearisation failed {%a}\n%!" In.debug_rel o ; ValSet.singleton (In.mk_val o) end else ValSet.empty) (fun o os -> if O.debug && O.verbose > 1 then eprintf " -> {%a}\n%!" In.debug_rel o ; ValSet.add (In.mk_val o) os) ValSet.empty in ValSet (In.typ,rs) end in fun ks arg -> match arg with | V.Tuple [Set es;Rel r;] -> let module L = Make(EventArg) in L.zyva es r | V.Tuple [ValSet (TEvents,es);ClassRel r;] -> let module L = Make(ClassArg) in let es = let sets = ValSet.fold (fun v k -> as_set ks v::k) es [] in ClassRel.Elts.of_list sets in L.zyva es r | _ -> arg_mismatch () and bisimulation = fun arg -> match arg with | V.Tuple [Rel t; Rel e; ] -> Rel (E.EventRel.bisimulation t e) | V.Tuple [ClassRel t; ClassRel e; ] -> ClassRel (ClassRel.bisimulation t e) | _ -> arg_mismatch () and tag2scope env arg = match arg with | V.Tag (_,tag) -> begin try let v = Lazy.force (StringMap.find tag env.vals) in match v with | V.Empty|V.Unv|V.Rel _ -> v | _ -> raise (PrimError (sprintf "value %s is not a relation, found %s" tag (pp_type_val v))) with Not_found -> raise (PrimError (sprintf "cannot find scope instance %s (the litmus test might be missing a scope tree declaration)" tag)) end | _ -> arg_mismatch () and tag2events env arg = match arg with | V.Tag (_,tag) -> let x = BellName.tag2instrs_var tag in begin try let v = Lazy.force (StringMap.find x env.vals) in match v with | V.Empty|V.Unv|V.Set _ -> v | _ -> raise (PrimError (sprintf "value %s is not a set of events, found %s" x (pp_type_val v))) with Not_found -> raise (PrimError (sprintf "cannot find event set %s" x)) end | _ -> arg_mismatch () and fromto ks arg = match arg with | V.Set es -> V.Rel (U.fromto ks.po es) | _ -> arg_mismatch () and tag2fenced env arg = match arg with | V.Tag (_,tag) -> let not_a_set_of_events x v = raise (PrimError (sprintf "value %s is not a set of events, found %s" x (pp_type_val v))) in let find_rel id = match Lazy.force (StringMap.find id env.vals) with | V.Rel rel -> rel | _ -> assert false in let po = find_rel "po" in let fromto = find_rel "fromto" in let x = BellName.tag2instrs_var tag in begin try let v = Lazy.force (StringMap.find x env.vals) in match v with | V.Empty -> V.Rel E.EventRel.empty | V.Set bevts -> let filter (x, y) = E.EventSet.exists (fun b -> E.EventRel.mem (x,b) po && E.EventRel.mem (b,y) po) bevts in V.Rel (E.EventRel.filter filter fromto) | _ -> not_a_set_of_events x v with Not_found -> raise (PrimError (sprintf "cannot find event set %s" x)) end | _ -> arg_mismatch () and loc2events ks arg = match arg with | V.Tag (_,s) -> let evts = ks.evts in let r = U.loc2events s evts in Set r | _ -> arg_mismatch () and domain arg = match arg with | V.Empty -> V.Empty | V.Unv -> V.Unv | V.Rel r -> V.Set (E.EventRel.domain r) | _ -> arg_mismatch () and range arg = match arg with | V.Empty -> V.Empty | V.Unv -> V.Unv | V.Rel r -> V.Set (E.EventRel.codomain r) | _ -> arg_mismatch () and fail arg = let pp = pp_val arg in let msg = sprintf "fail on %s" pp in raise (PrimError msg) and different_values arg = match arg with | V.Rel r -> let r = E.EventRel.filter (fun (e1,e2) -> not (U.same_value e1 e2)) r in V.Rel r | _ -> arg_mismatch () and same_oaRel arg = match arg with | V.Rel r -> let r = E.EventRel.filter (fun (e1,e2) -> (U.same_oa e1 e2)) r in V.Rel r | _ -> arg_mismatch () and check_two pred arg = match arg with | V.Tuple [V.Set ws; V.Rel prec; ] -> let m = E.EventRel.M.to_map prec in let ws = E.EventSet.filter (fun w -> E.is_store w && E.is_pt w && begin match E.EventSet.as_singleton (E.EventRel.M.succs w m) with | Some p -> pred w p w does not qualify when zero of two or more prec - related events | None -> false end) ws in V.Set ws | _ -> arg_mismatch () let oa_changes = check_two (fun w p -> not (U.same_oa w p)) and at_least_one_writable = check_two U.writable2 let add_primitives ks m = add_prims m [ "at-least-one-writable",at_least_one_writable; "oa-changes",oa_changes; "same-oa",same_oaRel; "different-values",different_values; "fromto",fromto ks; "classes-loc",partition; "classes",classes; "lift",lift; "delift",delift; "deliftinter",deliftinter; "linearisations",linearisations ks; "bisimulation",bisimulation; "tag2scope",tag2scope m; "tag2level",tag2scope m; "tag2events",tag2events m; "tag2fenced",tag2fenced m; "loc2events",loc2events ks; "domain",domain; "range",range; "fail",fail; ] type rel = | Rid of (E.event -> bool) | Revent of E.EventRel.t | Rclass of ClassRel.t let eval_variant loc v = try O.variant v with Not_found -> Warn.warn_always "%a: non-existent variant \"%s\", assumed unset" TxtLoc.pp loc v ; false let rec eval_variant_cond loc = function | Variant v -> eval_variant loc v | OpNot v -> not (eval_variant_cond loc v) | OpAnd (v1,v2) -> (eval_variant_cond loc v1) && (eval_variant_cond loc v2) | OpOr (v1,v2) -> (eval_variant_cond loc v1) || (eval_variant_cond loc v2) For all success call kont , accumulating results let interpret test kfail = let rec eval_loc env e = get_loc e,eval env e and check_id env e = match e with | Op1 (_,ToId,e) -> Some (eval_events_mem env e) | _ -> None and eval env = function | Konst (_,AST.Empty RLN) -> empty_rel | Konst (_,Universe _) -> Unv | AST.Tag (loc,s) -> begin try V.Tag (StringMap.find s env.EV.env.tags,s) with Not_found -> error env.EV.silent loc "tag '%s is undefined" s end | Var (loc,k) -> find_env_loc loc env k | Fun (loc,xs,body,name,fvs) -> Clo (eval_fun false env loc xs body name fvs) Unary operators | Op1 (_,Plus,e) -> begin match eval env e with | V.Empty -> V.Empty | Unv -> Unv | Rel r -> Rel (E.EventRel.transitive_closure r) | v -> error_rel env.EV.silent (get_loc e) v end | Op1 (_,Star,e) -> begin match eval env e with | V.Empty -> Rel (Lazy.force env.EV.ks.id) | Unv -> Unv | Rel r -> Rel (E.EventRel.union (E.EventRel.transitive_closure r) (Lazy.force env.EV.ks.id)) | v -> error_rel env.EV.silent (get_loc e) v end | Op1 (_,Opt,e) -> begin match eval env e with | V.Empty -> Rel (Lazy.force env.EV.ks.id) | Unv -> Unv | Rel r -> Rel (E.EventRel.union r (Lazy.force env.EV.ks.id)) | v -> error_rel env.EV.silent (get_loc e) v end begin match eval env e with | V.Empty -> Unv | Unv -> V.Empty | Set s -> Set (E.EventSet.diff env.EV.ks.evts s) | Rel r -> Rel (E.EventRel.diff (Lazy.force env.EV.ks.unv) r) | ValSet (TTag ts as t,s) -> ValSet (t,ValSet.diff (tags_universe env.EV.env ts) s) | v -> error env.EV.silent (get_loc e) "set or relation expected, %s found" (pp_typ (type_val v)) end | Op1 (_,Inv,e) -> begin match eval env e with | V.Empty -> V.Empty | Unv -> Unv | Rel r -> Rel (E.EventRel.inverse r) | ClassRel r -> ClassRel (ClassRel.inverse r) | Pair (v1,v2) -> Pair (v2,v1) | v -> error_rel env.EV.silent (get_loc e) v end | Op1 (_,ToId,e) -> begin match eval env e with | V.Empty -> V.Empty | Unv -> Rel (Lazy.force env.EV.ks.id) | Set s -> Rel (E.EventRel.set_to_rln s) | v -> error_events env.EV.silent (get_loc e) v end One xplicit N - ary operator | ExplicitSet (loc,es) -> let vs = List.map (eval_loc env) es in let vs = set_args env.EV.silent vs in begin match vs with | [] -> V.Empty | _ -> let t,vs = type_list env.EV.silent vs in try match t with | TEvent -> let vs = List.rev_map (function Event e -> e | _ -> assert false) vs in Set (E.EventSet.of_list vs) | TPair -> let vs = List.rev_map (function Pair p -> p | _ -> assert false) vs in Rel (E.EventRel.of_list vs) | _ -> ValSet (t,ValSet.of_list vs) with CompError msg -> error env.EV.silent loc "%s" msg end | Op (_loc,AST.Tuple,es) -> V.Tuple (List.map (eval env) es) | Op (loc,Union,es) -> let vs = List.map (eval_loc env) es in begin try let vs = union_args vs in match vs with | [] -> V.Empty | _ -> let t,vs = type_list env.EV.silent vs in match t with | TClassRel -> ClassRel(ClassRel.unions (List.map as_classrel vs)) | TRel -> Rel (E.EventRel.unions (List.map (as_rel env.EV.ks) vs)) | TEvents -> Set (E.EventSet.unions (List.map (as_set env.EV.ks) vs)) | TSet telt -> ValSet (telt,ValSet.unions (List.map as_valset vs)) | ty -> error env.EV.silent loc "cannot perform union on type '%s'" (pp_typ ty) with Exit -> Unv end | Op (loc,Seq,es) -> begin try let vs = List.map (eval_rels env) es in let rec do_seq = function | [] -> assert false | [v] -> v | v::vs -> begin match v,do_seq vs with | Rid f,Rid fs -> Rid (fun e -> f e && fs e) | Rid f,Revent vs -> Revent (E.EventRel.filter (fun (e1,_) -> f e1) vs) | Revent v,Rid fs -> Revent (E.EventRel.filter (fun (_,e2) -> fs e2) v) | Revent v,Revent vs -> Revent (E.EventRel.sequence v vs) | Rclass v,Rclass vs -> Rclass (ClassRel.sequence v vs) | _,_ -> error env.EV.silent loc "mixing relations in sequence" end in match do_seq vs with | Rid f -> Rel (E.EventRel.set_to_rln (E.EventSet.filter f env.EV.ks.evts)) | Revent r -> Rel r | Rclass r -> ClassRel r with Exit -> V.Empty end begin try let f1,rs , f2 = eval_seq_args env es in let r = E.EventRel.sequence rs ( Lazy.force env.EV.ks.id ) in let r = match f1,f2 with | None , None - > r | Some f1,None - > E.EventRel.filter ( fun ( e1 , _ ) - > f1 e1 ) r | None , Some f2 - > E.EventRel.filter ( fun ( _ , e2 ) - > f2 e2 ) r | Some f1,Some f2 - > E.EventRel.filter ( fun ( e1,e2 ) - > f1 e1 & & f2 e2 ) r in Rel r with Exit - > empty_rel end begin try let f1,rs,f2 = eval_seq_args env es in let r = List.fold_right E.EventRel.sequence rs (Lazy.force env.EV.ks.id) in let r = match f1,f2 with | None,None -> r | Some f1,None -> E.EventRel.filter (fun (e1,_) -> f1 e1) r | None,Some f2 -> E.EventRel.filter (fun (_,e2) -> f2 e2) r | Some f1,Some f2 -> E.EventRel.filter (fun (e1,e2) -> f1 e1 && f2 e2) r in Rel r with Exit -> empty_rel end *) | Op (_loc1,Inter,[e1;Op (_loc2,Cartesian,[e2;e3])]) | Op (_loc1,Inter,[Op (_loc2,Cartesian,[e2;e3]);e1]) -> let r = eval_rel env e1 and f1 = eval_events_mem env e2 and f2 = eval_events_mem env e3 in let r = E.EventRel.filter (fun (e1,e2) -> f1 e1 && f2 e2) r in Rel r let loc1,v1 = eval_loc env e1 and loc2,v2 = eval_loc env e2 in begin match tag2set v1,tag2set v2 with | (V.Tag _,_)|(_,V.Tag _) -> assert false | Rel r1,Rel r2 -> Rel (E.EventRel.inter r1 r2) | ClassRel r1,ClassRel r2 -> ClassRel (ClassRel.inter r1 r2) | Set s1,Set s2 -> Set (E.EventSet.inter s1 s2) | ValSet (t,s1),ValSet (_,s2) -> set_op env loc t ValSet.inter s1 s2 | (Unv,r)|(r,Unv) -> r | (V.Empty,_)|(_,V.Empty) -> V.Empty | (Event _|Pair _|Clo _|Prim _|Proc _|V.Tuple _),_ -> error env.EV.silent loc1 "intersection on %s" (pp_typ (type_val v1)) | _,(Event _|Pair _|Clo _|Prim _|Proc _|V.Tuple _) -> error env.EV.silent loc2 "intersection on %s" (pp_typ (type_val v2)) | ((Rel _|ClassRel _),(Set _|ValSet _)) | ((Set _|ValSet _),(Rel _|ClassRel _)) -> error env.EV.silent loc "mixing sets and relations in intersection" | (ValSet _,Set _) | (Set _,ValSet _) -> error env.EV.silent loc "mixing event sets and sets in intersection" | (ClassRel _,Rel _) | (Rel _,ClassRel _) -> error env.EV.silent loc "mixing event relation and class relation in intersection" end | Op (loc,Diff,[e1;e2;]) -> let loc1,v1 = eval_loc env e1 and loc2,v2 = eval_loc env e2 in begin match tag2set v1,tag2set v2 with | (V.Tag _,_)|(_,V.Tag _) -> assert false | Rel r1,Rel r2 -> Rel (E.EventRel.diff r1 r2) | ClassRel r1,ClassRel r2 -> ClassRel (ClassRel.diff r1 r2) | Set s1,Set s2 -> Set (E.EventSet.diff s1 s2) | ValSet (t,s1),ValSet (_,s2) -> set_op env loc t ValSet.diff s1 s2 | Unv,Rel r -> Rel (E.EventRel.diff (Lazy.force env.EV.ks.unv) r) | Unv,Set s -> Set (E.EventSet.diff env.EV.ks.evts s) | Unv,ValSet (TTag ts as t,s) -> ValSet (t,ValSet.diff (tags_universe env.EV.env ts) s) | Unv,ClassRel _ -> error env.EV.silent loc1 "cannot build universe for element type %s" (pp_typ TClassRel) | Unv,ValSet (t,_) -> error env.EV.silent loc1 "cannot build universe for element type %s" (pp_typ t) | Unv,V.Empty -> Unv | (Rel _|ClassRel _|Set _|V.Empty|Unv|ValSet _),Unv | V.Empty,(Rel _|ClassRel _|Set _|V.Empty|ValSet _) -> V.Empty | (Rel _|ClassRel _|Set _|ValSet _),V.Empty -> v1 | (Event _|Pair _|Clo _|Proc _|Prim _|V.Tuple _),_ -> error env.EV.silent loc1 "difference on %s" (pp_typ (type_val v1)) | _,(Event _|Pair _|Clo _|Proc _|Prim _|V.Tuple _) -> error env.EV.silent loc2 "difference on %s" (pp_typ (type_val v2)) | ((Set _|ValSet _),(ClassRel _|Rel _))|((ClassRel _|Rel _),(Set _|ValSet _)) -> error env.EV.silent loc "mixing set and relation in difference" | (Set _,ValSet _)|(ValSet _,Set _) -> error env.EV.silent loc "mixing event set and set in difference" | (Rel _,ClassRel _)|(ClassRel _,Rel _) -> error env.EV.silent loc "mixing event relation and class relation in difference" end | Op (_,Cartesian,[e1;e2;]) -> let s1 = eval_events env e1 and s2 = eval_events env e2 in Rel (E.EventRel.cartesian s1 s2) | Op (loc,Add,[e1;e2;]) -> let v1 = eval env e1 and v2 = eval env e2 in begin match v1,v2 with | V.Unv,_ -> error env.EV.silent loc "universe in set ++" | _,V.Unv -> V.Unv | Event e,V.Empty -> Set (E.EventSet.singleton e) | Pair p,V.Empty -> Rel (E.EventRel.singleton p) | _,V.Empty -> V.ValSet (type_val v1,ValSet.singleton v1) | V.Empty,V.ValSet (TSet e2 as t2,s2) -> let v1 = ValSet (e2,ValSet.empty) in set_op env loc t2 ValSet.add v1 s2 | _,V.ValSet (_,s2) -> set_op env loc (type_val v1) ValSet.add v1 s2 | Pair p,Rel r -> Rel (E.EventRel.add p r) | Tuple [Event ev1;Event ev2;],Rel r -> Rel (E.EventRel.add (ev1,ev2) r) | _,Rel _ -> error env.EV.silent (get_loc e1) "this expression of type '%s' should be a pair" (pp_typ (type_val v2)) | Event e,Set es -> Set (E.EventSet.add e es) | _,Set _ -> error env.EV.silent (get_loc e1) "this expression of type '%s' should be an event" (pp_typ (type_val v1)) | _, (Event _|Pair _|Clo _|Prim _ |Proc _|V.Tag (_, _)|V.Tuple _) -> error env.EV.silent (get_loc e2) "this expression of type '%s' should be a set" (pp_typ (type_val v2)) | _,ClassRel _ -> error env.EV.silent (get_loc e2) "this expression of type '%s' cannot occur here" (pp_typ (type_val v2)) end | App (loc,f,e) -> eval_app loc env (eval env f) (eval env e) | Bind (_,bds,e) -> let m = eval_bds env bds in eval { env with EV.env = m;} e | BindRec (loc,bds,e) -> let m = match env_rec (fun _ -> true) env loc (fun pp -> pp) bds with | CheckOk env -> env eval { env with EV.env=m;} e | Match (loc,e,cls,d) -> let v = eval env e in begin match v with | V.Tag (_,s) -> let rec match_rec = function | [] -> begin match d with | Some e -> eval env e | None -> error env.EV.silent loc "pattern matching failed on value '%s'" s end | (ps,es)::cls -> if s = ps then eval env es else match_rec cls in match_rec cls | V.Empty -> error env.EV.silent (get_loc e) "matching on empty" | V.Unv -> error env.EV.silent (get_loc e) "matching on universe" | _ -> error env.EV.silent (get_loc e) "matching on non-tag value of type '%s'" (pp_typ (type_val v)) end | MatchSet (loc,e,ife,cl) -> let v = eval env e in begin match v with | V.Empty -> eval env ife | V.Unv -> error env.EV.silent loc "%s" "Cannot set-match on universe" | Set es -> if E.EventSet.is_empty es then eval env ife else begin match cl with | EltRem (x,xs,ex) -> let elt = lazy begin try E.EventSet.choose es with Not_found -> assert false end in let s = lazy begin Set (E.EventSet.remove (Lazy.force elt) es) end in let elt = lazy (Event (Lazy.force elt)) in let m = env.EV.env in let m = add_val x elt m in let m = add_val xs s m in eval { env with EV.env = m; } ex | PreEltPost (xs1,x,xs2,ex) -> let s1,elt,s2 = try E.EventSet.split3 es with Not_found -> assert false in let m = env.EV.env in let m = add_val x (lazy (Event elt)) m in let m = add_val xs1 (lazy (Set s1)) m in let m = add_val xs2 (lazy (Set s2)) m in eval { env with EV.env = m; } ex end | Rel r -> if E.EventRel.is_empty r then eval env ife else begin match cl with | EltRem (x,xs,ex) -> let p = lazy begin try E.EventRel.choose r with Not_found -> assert false end in let s = lazy begin Rel (E.EventRel.remove (Lazy.force p) r) end in let p = lazy (Pair (Lazy.force p)) in let m = env.EV.env in let m = add_val x p m in let m = add_val xs s m in eval { env with EV.env = m; } ex | PreEltPost (xs1,x,xs2,ex) -> let s1,elt,s2 = try E.EventRel.split3 r with Not_found -> assert false in let m = env.EV.env in let m = add_val x (lazy (Pair elt)) m in let m = add_val xs1 (lazy (Rel s1)) m in let m = add_val xs2 (lazy (Rel s2)) m in eval { env with EV.env = m; } ex end | ValSet (t,s) -> if ValSet.is_empty s then eval env ife else begin match cl with | EltRem (x,xs,ex) -> let elt = lazy begin try ValSet.choose s with Not_found -> assert false end in let s = lazy begin try ValSet (t,ValSet.remove (Lazy.force elt) s) with CompError msg -> error env.EV.silent (get_loc e) "%s" msg end in let m = env.EV.env in let m = add_val x elt m in let m = add_val xs s m in eval { env with EV.env = m; } ex | PreEltPost (xs1,x,xs2,ex) -> let s1,elt,s2 = try ValSet.split3 s with Not_found -> assert false in let m = env.EV.env in let m = add_val x (lazy elt) m in let m = add_val xs1 (lazy (ValSet (t,s1))) m in let m = add_val xs2 (lazy (ValSet (t,s2))) m in eval { env with EV.env = m; } ex end | _ -> error env.EV.silent (get_loc e) "set-matching on non-set value of type '%s'" (pp_typ (type_val v)) end | Try (loc,e1,e2) -> begin try eval { env with EV.silent = true; } e1 with Misc.Exit -> if O.debug then warn loc "caught failure" ; eval env e2 end | If (loc,cond,ifso,ifnot) -> if eval_cond loc env cond then eval env ifso else eval env ifnot and eval_cond loc env c = match c with | In (e1,e2) -> let loc1,v1 = eval_loc env e1 in begin match v1 with | Event e -> let v2 = eval_events env e2 in E.EventSet.mem e v2 | Pair p -> let v2 = eval_rel env e2 in E.EventRel.mem p v2 | Tuple [Event ev1;Event ev2;] -> let v2 = eval_rel env e2 in E.EventRel.mem (ev1,ev2) v2 | _ -> begin match eval_loc env e2 with | _,ValSet (t2,vs) -> let t1 = V.type_val v1 in if type_equal t1 t2 then ValSet.mem v1 vs else error_typ env.EV.silent loc1 t2 t1 | loc2,v2 -> error env.EV.silent loc2 "set expected, found %s" (pp_typ (type_val v2)) end end | Eq (e1,e2) -> let v1 = eval env e1 and v2 = eval env e2 in ValOrder.compare v1 v2 = 0 let v1 = eval_loc env e1 and v2 = eval_loc env e2 in let t,_ = type_list env.EV.silent [v1;v2] in let a' = snd v1 and b' = snd v2 in begin match t with | TRel -> E.EventRel.subset (as_rel env.EV.ks a') (as_rel env.EV.ks b') | TEvents -> E.EventSet.subset (as_set env.EV.ks a') (as_set env.EV.ks b') | TSet _ -> ValSet.subset (as_valset a') (as_valset b') | ty -> error env.EV.silent loc "cannot perform subset on type '%s'" (pp_typ ty) end | VariantCond v -> eval_variant_cond loc v and eval_app loc env vf va = match vf with | Clo f -> let env = { env with EV.env=add_args loc f.clo_args va env f.clo_env;} in if O.debug then begin try eval env f.clo_body with | Misc.Exit -> error env.EV.silent loc "Calling" | e -> error env.EV.silent loc "Calling (%s)" (Printexc.to_string e) end else eval env f.clo_body | Prim (name,_,f) -> begin try f va with | PrimError msg -> error env.EV.silent loc "primitive %s: %s" name msg | Misc.Exit -> error env.EV.silent loc "Calling primitive %s" name end | _ -> error env.EV.silent loc "closure or primitive expected" and eval_fun is_rec env loc pat body name fvs = if O.debug && O.verbose > 1 then begin let sz = StringMap.fold (fun _ _ k -> k+1) env.EV.env.vals 0 in let fs = StringSet.pp_str "," (fun x -> x) fvs in warn loc "Closure %s, env=%i, free={%s}" name sz fs end ; let vals = StringSet.fold (fun x k -> try let v = just_find_env (not is_rec) loc env x in StringMap.add x v k with Not_found -> k) fvs StringMap.empty in let env = { env.EV.env with vals; } in {clo_args=pat; clo_env=env; clo_body=body; clo_name=(name,next_id ()); } and add_args loc pat v env_es env_clo = let xs = pat_as_vars pat in let vs = match xs with [_] -> [v] | _ -> v_as_vs v in let bds = try List.combine xs vs with _ -> error env_es.EV.silent loc "argument_mismatch" in let env_call = List.fold_right (fun (x,v) env -> add_val x (lazy v) env) bds env_clo in env_call and eval_rel env e = match eval env e with | Rel v -> v | Pair p -> E.EventRel.singleton p | V.Empty -> E.EventRel.empty | Unv -> Lazy.force env.EV.ks.unv | v -> error_rel env.EV.silent (get_loc e) v and eval_rels env e = match check_id env e with | Some es -> Rid es | None -> match eval env e with | Rel v -> Revent v | ClassRel v -> Rclass v | Pair p -> Revent (E.EventRel.singleton p) | V.Empty -> raise Exit | Unv -> Revent (Lazy.force env.EV.ks.unv) | v -> error_rel env.EV.silent (get_loc e) v and eval_events env e = match eval env e with | Set v -> v | Event e -> E.EventSet.singleton e | V.Empty -> E.EventSet.empty | Unv -> env.EV.ks.evts | v -> error_events env.EV.silent (get_loc e) v and eval_rel_set env e = match eval env e with | Rel _ | Set _ |ClassRel _ as v -> v | Event e -> Set (E.EventSet.singleton e) | Pair p -> Rel (E.EventRel.singleton p) | V.Empty -> Rel E.EventRel.empty | Unv -> Rel (Lazy.force env.EV.ks.unv) | _ -> error env.EV.silent (get_loc e) "relation or set expected" and eval_shown env e = match eval_rel_set env e with | Set v -> Shown.Set v | Rel v -> Shown.Rel v | _ -> assert false and eval_events_mem env e = match eval env e with | Set s -> fun e -> E.EventSet.mem e s | Event e0 -> fun e -> E.event_compare e0 e = 0 | V.Empty -> fun _ -> false | Unv -> fun _ -> true | v -> error_events env.EV.silent (get_loc e) v and eval_proc loc env x = match find_env_loc loc env x with | Proc p -> p | _ -> Warn.user_error "procedure expected" and eval_bds env_bd = let rec do_rec bds = match bds with | [] -> env_bd.EV.env | (loc,p,e)::bds -> add_pat_val env_bd.EV.silent loc p (lazy (eval env_bd e)) (do_rec bds) in do_rec and env_rec check env loc pp bds = let fs,nfs = List.partition (fun (_,_,e) -> is_fun e) bds in let fs = List.map (fun (loc,p,e) -> match p with | Pvar x -> x,e | Ptuple _ -> error env.EV.silent loc "%s" "binding mismatch") fs in match nfs with | [] -> CheckOk (env_rec_funs env loc fs) | _ -> env_rec_vals check env loc pp fs nfs and env_rec_funs env_bd _loc bds = let env = env_bd.EV.env in let clos = List.map (function | f,Fun (loc,xs,body,name,fvs) -> f,eval_fun true env_bd loc xs body name fvs,fvs | _ -> assert false) bds in let add_funs pred env = List.fold_left (fun env (f,clo,_) -> if pred f then add_val f (lazy (Clo clo)) env else env) env clos in List.iter (fun (_,clo,fvs) -> clo.clo_env <- add_funs (fun x -> match x with | None -> false | Some x -> StringSet.mem x fvs) clo.clo_env) clos ; add_funs (fun _ -> true) env Compute fixpoint of relations and env_rec_vals check env_bd loc pp funs bds = let vb_pp vs = List.fold_left2 (fun k (_loc,pat,_) v -> let pp_id x v k = try let v = match v with | V.Empty -> E.EventRel.empty | Unv -> Lazy.force env_bd.EV.ks.unv | Rel r -> r | _ -> raise Exit in let x = match x with | Some x -> x | None -> "_" in (x, rt_loc x v)::k with Exit -> k in let rec pp_ids xs vs k = match xs,vs with | x::xs,v::vs -> pp_id x v (pp_ids xs vs k) in match pat with | Pvar x -> pp_id x v k | Ptuple xs -> pp_ids xs (v_as_vs v) k) [] bds vs in Fixpoint iteration let rec fix k env vs = if O.debug && O.verbose > 1 then begin let vb_pp = pp (vb_pp vs) in U.pp_failure test env_bd.EV.ks.conc (sprintf "Fix %i" k) vb_pp end ; let env,ws = fix_step env_bd env bds in let env = env_rec_funs { env_bd with EV.env=env;} loc funs in let check_ok = check { env_bd with EV.env=env; } in if not check_ok then begin if O.debug then warn loc "Fix point interrupted" ; CheckFailed env end else let over = begin try stabilised env_bd.EV.ks env vs ws with Stabilised t -> error env_bd.EV.silent loc "illegal recursion on type '%s'" (pp_typ t) end in if over then CheckOk env else fix (k+1) env ws in let env0 = List.fold_left (fun env (_,pat,_) -> match pat with | Pvar k -> add_val k (lazy V.Empty) env | Ptuple ks -> List.fold_left (fun env k -> add_val k (lazy V.Empty) env) env ks) env_bd.EV.env bds in let env0 = env_rec_funs { env_bd with EV.env=env0;} loc funs in let env = else fix 0 env0 (List.map (fun (_,pat,_) -> pat2empty pat) bds) in if O.debug then warn loc "Fix point over" ; env and fix_step env_bd env bds = match bds with | [] -> env,[] | (loc,k,e)::bds -> let v = eval {env_bd with EV.env=env;} e in let env = add_pat_val env_bd.EV.silent loc k (lazy v) env in let env,vs = fix_step env_bd env bds in env,(v::vs) in let find_show_shown ks env x = let loc_asrel v = match v with | Rel r -> Shown.Rel (rt_loc x r) | Set r -> if _dbg then eprintf "Found set %s: %a\n%!" x debug_set r; Shown.Set r | V.Empty -> Shown.Rel E.EventRel.empty | Unv -> Shown.Rel (rt_loc x (Lazy.force ks.unv)) | v -> Warn.warn_always "Warning show: %s is not a relation: '%s'" x (pp_val v) ; raise Not_found in try loc_asrel (Lazy.force (StringMap.find x env.vals)) with Not_found -> Shown.Rel E.EventRel.empty in let doshowone x st = if O.showsome && StringSet.mem x O.doshow then let show = lazy begin StringMap.add x (find_show_shown st.ks st.env x) (Lazy.force st.show) end in { st with show;} else st in let doshow bds st = if O.showsome then begin let to_show = StringSet.inter O.doshow (StringSet.unions (List.map bdvars bds)) in if StringSet.is_empty to_show then st else let show = lazy begin StringSet.fold (fun x show -> let r = find_show_shown st.ks st.env x in StringMap.add x r show) to_show (Lazy.force st.show) end in { st with show;} end else st in let check_bell_enum = if O.bell then fun loc st name tags -> try if name = BellName.scopes then let bell_info = BellModel.add_rel name tags st.bell_info in { st with bell_info;} else if name = BellName.regions then let bell_info = BellModel.add_regions tags st.bell_info in { st with bell_info;} else if name = BellName.levels then let bell_info = BellModel.add_rel name tags st.bell_info in let bell_info = BellModel.add_order name (StringRel.order_to_succ tags) bell_info in { st with bell_info } else st with BellModel.Defined -> error_not_silent loc "second definition of bell enum %s" name else fun _loc st _v _tags -> st in let check_bell_order = if O.bell then let fun_as_rel f_order loc st id_tags id_fun = let env = from_st st in let cat_fun = try find_env_loc TxtLoc.none env id_fun with _ -> assert false in let cat_tags = let cat_tags = try StringMap.find id_tags env.EV.env.vals with Not_found -> error false loc "tag set %s must be defined while defining %s" id_tags id_fun in match Lazy.force cat_tags with | V.ValSet (TTag _,scs) -> scs | v -> error false loc "%s must be a tag set, found %s" id_tags (pp_typ (type_val v)) in let order = ValSet.fold (fun tag order -> let tgt = try eval_app loc { env with EV.silent=true;} cat_fun tag with Misc.Exit -> V.Empty in let tag = as_tag tag in let add tgt order = StringRel.add (tag,as_tag tgt) order in match tgt with | V.Empty -> order | V.Tag (_,_) -> add tgt order | V.ValSet (TTag _,vs) -> ValSet.fold add vs order | _ -> error false loc "implicit call %s('%s) must return a tag, found %s" id_fun tag (pp_typ (type_val tgt))) cat_tags StringRel.empty in let tags_set = as_tags cat_tags in let order = f_order order in if O.debug then begin warn loc "Defining hierarchy on %s from function %s" id_tags id_fun ; eprintf "%s: {%a}\n" id_tags (fun chan -> StringSet.pp chan "," output_string) tags_set ; eprintf "hierarchy: %a\n" (fun chan -> StringRel.pp chan " " (fun chan (a,b) -> fprintf chan "(%s,%s)" a b)) order end ; if not (StringRel.is_hierarchy tags_set order) then error false loc "%s defines the non-hierarchical relation %s" id_fun (BellModel.pp_order_dec order) ; try let bell_info = BellModel.add_order id_tags order st.bell_info in { st with bell_info;} with BellModel.Defined -> let old = try BellModel.get_order id_tags st.bell_info with Not_found -> assert false in if not (StringRel.equal old order) then error_not_silent loc "incompatible definition of order on %s by %s" id_tags id_fun ; st in fun bds st -> List.fold_left (fun st (_,pat,e) -> match pat with | Pvar (Some v) -> if v = BellName.wider then let loc = get_loc e in fun_as_rel Misc.identity loc st BellName.scopes v else if v = BellName.narrower then let loc = get_loc e in fun_as_rel StringRel.inverse loc st BellName.scopes v else st | Pvar None -> st | Ptuple _ -> st) st bds else fun _bds st -> st in let eval_test check env t e = check (test2pred env t e (eval_rel_set env e)) in let make_eval_test = function | None -> fun _env -> true | Some (_,_,t,e,name) -> if skip_this_check name then fun _env -> true else fun env -> eval_test (check_through Check) env t e in let pp_check_failure (st:st) (loc,pos,_,e,_) = warn loc "check failed" ; show_call_stack st.st.loc ; if O.debug && O.verbose > 0 then begin let pp = match pos with | Pos _ -> "???" | Txt txt -> txt in let v = eval_rel (from_st st) e in let cy = E.EventRel.get_cycle v in U.pp_failure test st.ks.conc (sprintf "Failure of '%s'" pp) (let k = show_to_vbpp st in ("CY",E.EventRel.cycle_option_to_rel cy)::k) end and show_cycle st (_loc,pos,tst,e,_) = let pp = match pos with | Pos _ -> "???" | Txt txt -> txt in let v = eval_rel (from_st st) e in let tst = match tst with Yes tst|No tst -> tst in let v = match tst with | Acyclic -> v | Irreflexive | TestEmpty -> E.EventRel.remove_transitive_edges v in let tag,cy = match tst with | Acyclic |Irreflexive -> let cy = E.EventRel.get_cycle v in if O.verbose > 0 then begin match cy with | Some xs -> eprintf "Cycle: %s\n" (String.concat " " (List.map E.pp_eiid xs)) | None -> () end ; "CY",E.EventRel.cycle_option_to_rel cy | TestEmpty -> "NE",v in U.pp test st.ks.conc (sprintf "%s for '%s'" (match tst with | Acyclic | Irreflexive -> "Cycle" | TestEmpty -> "Relation") pp) (let k = show_to_vbpp st in (tag,cy)::k) in Execute one instruction let eval_st st e = eval (from_st st) e in let rec exec : 'a. st -> ins -> ('a -> 'a) -> (st -> 'a -> 'a) -> 'a -> 'a = fun (type res) st i kfail kont (res:res) -> match i with | IfVariant (loc,v,ins_true,ins_false) -> let ins = if eval_variant_cond loc v then ins_true else ins_false in run st ins kfail kont res | Debug (_,e) -> if O.debug then begin let v = eval_st st e in eprintf "%a: value is %a\n%!" TxtLoc.pp (get_loc e) debug_val v end ; kont st res | Show (_,xs) when not O.bell -> if O.showsome then let xs = List.filter (fun x -> try ignore (StringMap.find x st.env.vals); true with Not_found -> false) xs in let show = lazy begin List.fold_left (fun show x -> StringMap.add x (find_show_shown st.ks st.env x) show) (Lazy.force st.show) xs end in kont { st with show;} res else kont st res | UnShow (_,xs) when not O.bell -> if O.showsome then let show = lazy begin List.fold_left (fun show x -> StringMap.remove x show) (Lazy.force st.show) (StringSet.(elements (diff (of_list xs) O.doshow))) end in kont { st with show;} res else kont st res | ShowAs (_,e,id) when not O.bell -> if O.showsome then let show = lazy begin try let v = Shown.apply_rel (rt_loc id) (eval_shown { (from_st st) with EV.silent=true } e) in StringMap.add id v (Lazy.force st.show) with Misc.Exit -> Lazy.force st.show end in kont { st with show; } res else kont st res | Test (tst,ty) when not O.bell -> exec_test st tst ty kfail kont res | Let (_loc,bds) -> let env = eval_bds (from_st st) bds in let st = { st with env; } in let st = doshow bds st in let st = check_bell_order bds st in kont st res | Rec (loc,bds,testo) -> let env = match env_rec (make_eval_test testo) (from_st st) loc (fun pp -> pp@show_to_vbpp st) bds with | CheckOk env -> Some env | CheckFailed env -> if O.debug then begin let st = { st with env; } in let st = doshow bds st in pp_check_failure st (Misc.as_some testo) end ; None in begin match env with | None -> kfail res | Some env -> let st = { st with env; } in let st = doshow bds st in Check again for strictskip let st = match testo with | None -> st | Some (_,_,t,e,name) -> if O.strictskip && skip_this_check name && not (eval_test Misc.identity (from_st st) t e) then begin { st with skipped = StringSet.add (Misc.as_some name) st.skipped;} end else st in let st = check_bell_order bds st in kont st res end | InsMatch (loc,e,cls,d) -> let v = eval_st st e in begin match v with | V.Tag (_,s) -> let rec match_rec = function | [] -> begin match d with | Some dseq -> run st dseq kfail kont res | None -> error_not_silent loc "pattern matching failed on value '%s'" s end | (ps,pprog)::cls -> if s = ps then run st pprog kfail kont res else match_rec cls in match_rec cls | V.Empty -> error_not_silent (get_loc e) "matching on empty" | V.Unv -> error_not_silent (get_loc e) "matching on universe" | _ -> error_not_silent (get_loc e) "matching on non-tag value of type '%s'" (pp_typ (type_val v)) end | Include (loc,fname) -> let fname = match fname with | "lock.cat" when O.compat -> "cos-opt.cat" | _ -> fname in if StringSet.mem fname st.st.included && (O.verbose > 0 || O.debug_files) then begin Warn.warn_always "%a: including %s another time" TxtLoc.pp loc fname end ; do_include loc fname st kfail kont res | Procedure (_,name,args,body,is_rec) -> let p = { proc_args=args; proc_env=st.env; proc_body=body; } in let proc = Proc p in let env_plus_p = do_add_val name (lazy proc) st.env in begin match is_rec with | IsRec -> p.proc_env <- env_plus_p | IsNotRec -> () end ; kont { st with env = env_plus_p } res | Call (loc,name,es,tname) when not O.bell -> let skip = skip_this_check tname || skip_this_check (Some name) in if O.debug && skip then warn loc "skipping call: %s" (match tname with | Some n -> n | None -> name); kont st res let env0 = from_st st in let p = protect_call st (eval_proc loc env0) name in let env1 = protect_call st (fun penv -> add_args loc p.proc_args (eval env0 es) env0 penv) p.proc_env in let pname = match tname with | Some _ -> tname | None -> Some name in let tval = let benv = env1 in run { (push_loc st (loc,pname)) with env=benv; } p.proc_body (fun x -> x) (fun _ _ -> true) false in if tval then kont st res else kont { st with skipped = StringSet.add (Misc.as_some tname) st.skipped;} res else let pname = match tname with | Some _ -> tname | None -> Some name in let st = push_loc st (loc,pname) in run { st with env = env1; } p.proc_body kfail (fun st_call res -> let st_call = pop_loc st_call in res | Enum (loc,name,xs) -> let env = st.env in let tags = List.fold_left (fun env x -> StringMap.add x name env) env.tags xs in let enums = StringMap.add name xs env.enums in let alltags = lazy begin let vs = List.fold_left (fun k x -> ValSet.add (V.Tag (name,x)) k) ValSet.empty xs in V.ValSet (TTag name,vs) end in let env = do_add_val name alltags env in if O.debug && O.verbose > 1 then warn loc "adding set of all tags for %s" name ; let env = { env with tags; enums; } in let st = { st with env;} in let st = check_bell_enum loc st name xs in kont st res | Forall (_loc,x,e,body) when not O.bell -> let st0 = st in let env0 = st0.env in let v = eval (from_st st0) e in begin match tag2set v with | V.Empty -> kont st res | ValSet (_,set) -> let rec run_set st vs res = if ValSet.is_empty vs then kont st res else let v = try ValSet.choose vs with Not_found -> assert false in let env = do_add_val x (lazy v) env0 in run { st with env;} body kfail (fun st res -> run_set { st with env=env0;} (ValSet.remove v vs) res) res in run_set st set res | _ -> error_not_silent (get_loc e) "forall instruction applied to non-set value" end | WithFrom (_loc,x,e) when not O.bell -> let st0 = st in let env0 = st0.env in let v = eval (from_st st0) e in begin match v with | V.Empty -> kfail res | ValSet (_,vs) -> ValSet.fold (fun v res -> let env = do_add_val x (lazy v) env0 in kont (doshowone x {st with env;}) res) vs res | _ -> error_not_silent (get_loc e) "set expected" end | Events (loc,x,es,def) when O.bell -> let x = BellName.tr_compat x in if not (StringSet.mem x BellName.all_sets) then error_not_silent loc "event type %s is not part of legal {%s}\n" x (StringSet.pp_str "," Misc.identity BellName.all_sets) ; let vs = List.map (eval_loc (from_st st)) es in let event_sets = List.map (fun (loc,v) -> match v with | ValSet(TTag _,elts) -> let tags = ValSet.fold (fun elt k -> let tag = as_tag elt in match tag with | "release" when O.compat -> "assign"::"release"::k | "acquire"when O.compat -> "deref"::"lderef"::"acquire"::k | _ -> tag::k) elts [] in StringSet.of_list tags | V.Tag (_,tag) -> StringSet.singleton tag | _ -> error false loc "event declaration expected a set of tags, found %s" (pp_val v)) vs in let bell_info = BellModel.add_events x event_sets st.bell_info in let bell_info = if def then let defarg = List.map2 (fun ss e -> match StringSet.as_singleton ss with | None -> error_not_silent (get_loc e) "ambiguous default declaration" | Some a -> a) event_sets es in try BellModel.add_default x defarg bell_info with BellModel.Defined -> error_not_silent loc "second definition of default for %s" x else bell_info in let st = { st with bell_info;} in kont st res | Events _ -> assert (not O.bell) ; | Test _|UnShow _|Show _|ShowAs _ | Call _|Forall _ | WithFrom _ -> assert O.bell ; and exec_test : 'a.st -> app_test -> test_type -> ('a -> 'a) -> (st -> 'a -> 'a) -> 'a -> 'a = fun st (loc,_,t,e,name as tst) test_type kfail kont res -> let skip = skip_this_check name in let cycle = cycle_this_check name in if O.debug && skip then warn loc "skipping check: %s" (Misc.as_some name) ; if O.strictskip || not skip || cycle then let ok = eval_test (check_through test_type) (from_st st) t e in if cycle && begin match ok,t with | (false,Yes _) | (true,No _) -> true | (false,No _) | (true,Yes _) -> false end then show_cycle st tst ; if ok then match test_type with | Check|UndefinedUnless|Assert -> kont st res | Flagged -> begin match name with | None -> warn loc "this flagged test does not have a name" ; kont st res | Some name -> if O.debug then warn loc "flag %s recorded" name ; kont {st with flags= Flag.Set.add (Flag.Flag name) st.flags;} res end else begin if skip then begin assert O.strictskip ; kont { st with skipped = StringSet.add (Misc.as_some name) st.skipped;} res end else begin match test_type with | Check -> if O.debug then pp_check_failure st tst ; kfail res | UndefinedUnless -> kont {st with flags=Flag.Set.add Flag.Undef st.flags;} res | Flagged -> kont st res | Assert -> let a = match name with | None -> "(unknown)" | Some name -> name in Warn.user_error "%s assertion failed, check input test." a end end else begin W.warn "Skipping check %s" (Misc.as_some name) ; kont st res end and do_include : 'a . TxtLoc.t -> string ->st -> ('a -> 'a) -> (st -> 'a -> 'a) -> 'a -> 'a = fun loc fname st kfail kont res -> if O.debug then warn loc "include \"%s\"" fname ; let module P = ParseModel.Make (struct include LexUtils.Default let libfind = O.libfind end) in let (_,_,iprog) = try P.parse fname with Misc.Fatal msg | Misc.UserError msg -> error_not_silent loc "%s" msg in let stst = st.st in let included = StringSet.add fname stst.included in let stst = { stst with included; } in let st = { st with st=stst; } in run st iprog kfail kont res and run : 'a.st -> ins list -> ('a -> 'a) -> (st -> 'a -> 'a) -> 'a -> 'a = fun st c kfail kont res -> match c with | [] -> kont st res | i::c -> exec st i kfail (fun st res -> run st c kfail kont res) res in fun ks m vb_pp kont res -> let m = add_primitives ks (env_from_ienv m) in if _dbg then begin eprintf "showsome=%b, doshow={%s}\n" O.showsome (StringSet.pp_str ", " Misc.identity O.doshow) end ; let show = if O.showsome then lazy begin let show = List.fold_left (fun show (tag,v) -> StringMap.add tag (Shown.Rel v) show) StringMap.empty (Lazy.force vb_pp) in StringSet.fold (fun tag show -> StringMap.add tag (find_show_shown ks m tag) show) O.doshow show end else lazy StringMap.empty in let st = {env=m; show=show; skipped=StringSet.empty; flags=Flag.Set.empty; ks; bell_info=BellModel.empty_info; st=inter_st_empty; } in let kont st res = kont (st2out st) res in let just_run st res = run st mprog kfail kont res in do_include TxtLoc.none "stdlib.cat" st kfail (match O.bell_fname with | Some fname -> fun st res -> do_include TxtLoc.none fname st kfail just_run res) res end
f20ce96f7209b8531757d44a555c916474c79c49785d98eb3a4e8f5981b0561b
hopbit/sonic-pi-snippets
bg_sofll.sps
# key: bg sofll # point_line: 4 # point_index: 0 # -- live_loop :background do # stop # use_bpm: 96 # sync :melody use_synth :piano background.size.times do |n| play background[n][0], sustain: background[n][1] sleep background[n][2] end end
null
https://raw.githubusercontent.com/hopbit/sonic-pi-snippets/2232854ac9587fc2f9f684ba04d7476e2dbaa288/backgrounds/bg_sofll.sps
scheme
# key: bg sofll # point_line: 4 # point_index: 0 # -- live_loop :background do # stop # use_bpm: 96 # sync :melody use_synth :piano background.size.times do |n| play background[n][0], sustain: background[n][1] sleep background[n][2] end end
1dc3142ec3108048b1da056bef63965f7dc9440a0e9067ccfcbeb30693225ffb
umutisik/mathvas
Settings.hs
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. In addition , you can configure a number of different aspects of Yesod by overriding methods in the Yesod typeclass . That instance is declared in the Foundation.hs file . module Settings where import ClassyPrelude.Yesod import Control.Exception (throw) import Data.Aeson (Result (..), fromJSON, withObject, (.!=), (.:?)) import Data.FileEmbed (embedFile) import Data.Yaml (decodeEither') import Database.Persist.Postgresql (PostgresConf) import Language.Haskell.TH.Syntax (Exp, Name, Q) import Network.Wai.Handler.Warp (HostPreference) import Yesod.Default.Config2 (applyEnvValue, configSettingsYml) import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload, widgetFileReload) -- | Runtime settings to configure this application. These settings can be -- loaded from various sources: defaults, environment variables, config files, -- theoretically even a database. data AppSettings = AppSettings { appStaticDir :: String -- ^ Directory from which to serve static files. , appDatabaseConf :: PostgresConf -- ^ Configuration settings for accessing the database. , appRoot :: Text -- ^ Base for all generated URLs. , appHost :: HostPreference -- ^ Host/interface the server should bind to. , appPort :: Int -- ^ Port to listen on , appIpFromHeader :: Bool -- ^ Get the IP address from the header when logging. Useful when sitting -- behind a reverse proxy. , appDetailedRequestLogging :: Bool -- ^ Use detailed request logging system , appShouldLogAll :: Bool -- ^ Should all log messages be displayed? , appReloadTemplates :: Bool -- ^ Use the reload version of templates , appMutableStatic :: Bool -- ^ Assume that files in the static dir may change after compilation , appSkipCombining :: Bool -- ^ Perform no stylesheet/script combining -- Example app-specific configuration values. , appCopyright :: Text -- ^ Copyright text to appear in the footer of the page , appAnalytics :: Maybe Text ^ Google Analytics code } instance FromJSON AppSettings where parseJSON = withObject "AppSettings" $ \o -> do let defaultDev = #if DEVELOPMENT True #else False #endif appStaticDir <- o .: "static-dir" appDatabaseConf <- o .: "database" appRoot <- o .: "approot" appHost <- fromString <$> o .: "host" appPort <- o .: "port" appIpFromHeader <- o .: "ip-from-header" appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev appShouldLogAll <- o .:? "should-log-all" .!= defaultDev appReloadTemplates <- o .:? "reload-templates" .!= defaultDev appMutableStatic <- o .:? "mutable-static" .!= defaultDev appSkipCombining <- o .:? "skip-combining" .!= defaultDev appCopyright <- o .: "copyright" appAnalytics <- o .:? "analytics" return AppSettings {..} -- | Settings for 'widgetFile', such as which template languages to support and default Hamlet settings . -- -- For more information on modifying behavior, see: -- -- -widgetFile widgetFileSettings :: WidgetFileSettings widgetFileSettings = def -- | How static files should be combined. combineSettings :: CombineSettings combineSettings = def -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if appReloadTemplates compileTimeAppSettings then widgetFileReload else widgetFileNoReload) widgetFileSettings -- | Raw bytes at compile time of @config/settings.yml@ configSettingsYmlBS :: ByteString configSettingsYmlBS = $(embedFile configSettingsYml) | @config / settings.yml@ , parsed to a @Value@. configSettingsYmlValue :: Value configSettingsYmlValue = either Control.Exception.throw id $ decodeEither' configSettingsYmlBS | A version of parsed at compile time from @config / settings.yml@. compileTimeAppSettings :: AppSettings compileTimeAppSettings = case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of Error e -> error e Success settings -> settings The following two functions can be used to combine multiple CSS or JS files -- at compile time to decrease the number of http requests. -- Sample usage (inside a Widget): -- > $ ( combineStylesheets ' StaticR [ style1_css , style2_css ] ) combineStylesheets :: Name -> [Route Static] -> Q Exp combineStylesheets = combineStylesheets' (appSkipCombining compileTimeAppSettings) combineSettings combineScripts :: Name -> [Route Static] -> Q Exp combineScripts = combineScripts' (appSkipCombining compileTimeAppSettings) combineSettings
null
https://raw.githubusercontent.com/umutisik/mathvas/9f764cd4d54370262c70c7ec3eadae076a1eb489/Settings.hs
haskell
| Settings are centralized, as much as possible, into this file. This includes database connection settings, static file locations, etc. | Runtime settings to configure this application. These settings can be loaded from various sources: defaults, environment variables, config files, theoretically even a database. ^ Directory from which to serve static files. ^ Configuration settings for accessing the database. ^ Base for all generated URLs. ^ Host/interface the server should bind to. ^ Port to listen on ^ Get the IP address from the header when logging. Useful when sitting behind a reverse proxy. ^ Use detailed request logging system ^ Should all log messages be displayed? ^ Use the reload version of templates ^ Assume that files in the static dir may change after compilation ^ Perform no stylesheet/script combining Example app-specific configuration values. ^ Copyright text to appear in the footer of the page | Settings for 'widgetFile', such as which template languages to support and For more information on modifying behavior, see: -widgetFile | How static files should be combined. The rest of this file contains settings which rarely need changing by a user. | Raw bytes at compile time of @config/settings.yml@ at compile time to decrease the number of http requests. Sample usage (inside a Widget):
In addition , you can configure a number of different aspects of Yesod by overriding methods in the Yesod typeclass . That instance is declared in the Foundation.hs file . module Settings where import ClassyPrelude.Yesod import Control.Exception (throw) import Data.Aeson (Result (..), fromJSON, withObject, (.!=), (.:?)) import Data.FileEmbed (embedFile) import Data.Yaml (decodeEither') import Database.Persist.Postgresql (PostgresConf) import Language.Haskell.TH.Syntax (Exp, Name, Q) import Network.Wai.Handler.Warp (HostPreference) import Yesod.Default.Config2 (applyEnvValue, configSettingsYml) import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload, widgetFileReload) data AppSettings = AppSettings { appStaticDir :: String , appDatabaseConf :: PostgresConf , appRoot :: Text , appHost :: HostPreference , appPort :: Int , appIpFromHeader :: Bool , appDetailedRequestLogging :: Bool , appShouldLogAll :: Bool , appReloadTemplates :: Bool , appMutableStatic :: Bool , appSkipCombining :: Bool , appCopyright :: Text , appAnalytics :: Maybe Text ^ Google Analytics code } instance FromJSON AppSettings where parseJSON = withObject "AppSettings" $ \o -> do let defaultDev = #if DEVELOPMENT True #else False #endif appStaticDir <- o .: "static-dir" appDatabaseConf <- o .: "database" appRoot <- o .: "approot" appHost <- fromString <$> o .: "host" appPort <- o .: "port" appIpFromHeader <- o .: "ip-from-header" appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev appShouldLogAll <- o .:? "should-log-all" .!= defaultDev appReloadTemplates <- o .:? "reload-templates" .!= defaultDev appMutableStatic <- o .:? "mutable-static" .!= defaultDev appSkipCombining <- o .:? "skip-combining" .!= defaultDev appCopyright <- o .: "copyright" appAnalytics <- o .:? "analytics" return AppSettings {..} default Hamlet settings . widgetFileSettings :: WidgetFileSettings widgetFileSettings = def combineSettings :: CombineSettings combineSettings = def widgetFile :: String -> Q Exp widgetFile = (if appReloadTemplates compileTimeAppSettings then widgetFileReload else widgetFileNoReload) widgetFileSettings configSettingsYmlBS :: ByteString configSettingsYmlBS = $(embedFile configSettingsYml) | @config / settings.yml@ , parsed to a @Value@. configSettingsYmlValue :: Value configSettingsYmlValue = either Control.Exception.throw id $ decodeEither' configSettingsYmlBS | A version of parsed at compile time from @config / settings.yml@. compileTimeAppSettings :: AppSettings compileTimeAppSettings = case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of Error e -> error e Success settings -> settings The following two functions can be used to combine multiple CSS or JS files > $ ( combineStylesheets ' StaticR [ style1_css , style2_css ] ) combineStylesheets :: Name -> [Route Static] -> Q Exp combineStylesheets = combineStylesheets' (appSkipCombining compileTimeAppSettings) combineSettings combineScripts :: Name -> [Route Static] -> Q Exp combineScripts = combineScripts' (appSkipCombining compileTimeAppSettings) combineSettings
3767b560ca878561d96f3cc8122f8b3f9bdc8bd39a13bfeec59537bc1259626d
rroohhh/guix_packages
unrar.scm
(define-module (vup unrar)) (use-modules (guix packages)) (use-modules (guix build-system gnu)) (use-modules (guix download)) (use-modules ((guix licenses) #:prefix license:)) (define-public unrar (package (name "unrar") (version "6.0.3") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "185cqhw5frkia22gb8hi2779n7zlkhrw3sm698q9x7w75lwm7vqx")))) (build-system gnu-build-system) (arguments '(#:make-flags (list "CC=gcc" (string-append "DESTDIR=" %output)) #:phases (alist-delete 'configure (alist-delete 'check %standard-phases)))) (inputs `()) (home-page "/") (synopsis "unrar") (description "unrar, non free.") (license license:x11)))
null
https://raw.githubusercontent.com/rroohhh/guix_packages/8226e4500d2687d119ede3ebf620488f072c430c/vup/unrar.scm
scheme
(define-module (vup unrar)) (use-modules (guix packages)) (use-modules (guix build-system gnu)) (use-modules (guix download)) (use-modules ((guix licenses) #:prefix license:)) (define-public unrar (package (name "unrar") (version "6.0.3") (source (origin (method url-fetch) (uri (string-append "-" version ".tar.gz")) (sha256 (base32 "185cqhw5frkia22gb8hi2779n7zlkhrw3sm698q9x7w75lwm7vqx")))) (build-system gnu-build-system) (arguments '(#:make-flags (list "CC=gcc" (string-append "DESTDIR=" %output)) #:phases (alist-delete 'configure (alist-delete 'check %standard-phases)))) (inputs `()) (home-page "/") (synopsis "unrar") (description "unrar, non free.") (license license:x11)))
5d4dbbe5d907d982a7232116f0610bfe314465566e6a359bc26fd750907f05db
kendroe/CoqRewriter
mylist.mli
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REWRITELIB * * mylist.mli * * This file contains signatures for some useful list processing functions * * ( C ) 2017 , * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * will be provided when the work is complete . * * For a commercial license , contact Roe Mobile Development , LLC at * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REWRITELIB * * mylist.mli * * This file contains signatures for some useful list processing functions * * (C) 2017, Kenneth Roe * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. * will be provided when the work is complete. * * For a commercial license, contact Roe Mobile Development, LLC at * * ******************************************************************************) val member: 'a -> 'a list -> bool val select: ('a -> bool) -> 'a list -> 'a list val remove_dups: 'a list -> 'a list val difference: 'a list -> 'a list -> 'a list val delete: 'a -> 'a list -> 'a list val delete_one: 'a -> 'a list -> 'a list val intersect: 'a list -> 'a list -> 'a list val append: 'a list -> 'a list -> 'a list val is_subset: 'a list -> 'a list -> bool val replace_nth: ('a list) -> int -> 'a -> ('a list) val delete_nth: 'a list -> int -> ('a list) val ( *| ) : ('a -> 'b list) -> ('b -> 'c list) -> ('a -> 'c list) val x: ('a -> 'b) -> ('a -> 'b list) val ( <| ) : ('a list) -> ('a -> 'b list) -> 'b list val ( <> ) : ('a list) -> ('a -> 'b) -> 'b list val ( |> ) : ('a list) -> ('a -> bool) -> 'a list val ( >< ) : ('a list) -> ('b list) -> (('a * 'b) list) val cross_list : ('a list list) -> ('a list list) val pair_lists : ('a list) -> ('b list) -> (('a * 'b) list) val parent : ('a list) -> ('a list) val is_prefix_list : ('a list) -> ('a list) -> bool val tail : ('a list) -> int -> ('a list)
null
https://raw.githubusercontent.com/kendroe/CoqRewriter/ddf5dc2ea51105d5a2dc87c99f0d364cf2b8ebf5/plugin/src/mylist.mli
ocaml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REWRITELIB * * mylist.mli * * This file contains signatures for some useful list processing functions * * ( C ) 2017 , * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program . If not , see < / > . * will be provided when the work is complete . * * For a commercial license , contact Roe Mobile Development , LLC at * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * REWRITELIB * * mylist.mli * * This file contains signatures for some useful list processing functions * * (C) 2017, Kenneth Roe * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see </>. * will be provided when the work is complete. * * For a commercial license, contact Roe Mobile Development, LLC at * * ******************************************************************************) val member: 'a -> 'a list -> bool val select: ('a -> bool) -> 'a list -> 'a list val remove_dups: 'a list -> 'a list val difference: 'a list -> 'a list -> 'a list val delete: 'a -> 'a list -> 'a list val delete_one: 'a -> 'a list -> 'a list val intersect: 'a list -> 'a list -> 'a list val append: 'a list -> 'a list -> 'a list val is_subset: 'a list -> 'a list -> bool val replace_nth: ('a list) -> int -> 'a -> ('a list) val delete_nth: 'a list -> int -> ('a list) val ( *| ) : ('a -> 'b list) -> ('b -> 'c list) -> ('a -> 'c list) val x: ('a -> 'b) -> ('a -> 'b list) val ( <| ) : ('a list) -> ('a -> 'b list) -> 'b list val ( <> ) : ('a list) -> ('a -> 'b) -> 'b list val ( |> ) : ('a list) -> ('a -> bool) -> 'a list val ( >< ) : ('a list) -> ('b list) -> (('a * 'b) list) val cross_list : ('a list list) -> ('a list list) val pair_lists : ('a list) -> ('b list) -> (('a * 'b) list) val parent : ('a list) -> ('a list) val is_prefix_list : ('a list) -> ('a list) -> bool val tail : ('a list) -> int -> ('a list)
35bbb1217378ca7496c3665abf3aa69f1f5ebc0aaaafb8211da843a57b0e7120
soegaard/super
test-object-notation.rkt
#lang super racket (define point% (class* object% (printable<%>) (super-new) (init-field [x 0] [y 0]) (define/public (custom-print port qq-depth) (do-print this print port)) (define/public (custom-display port) (do-print this display port)) (define/public (custom-write port) (do-print this write port)) (define (do-print object out port) (display (~a "(object:point% x=" x " y=" y ")") port)) (define/public (move-x dx) (new this% [x (+ x dx)] [y y])) (define/public (move-y dy) (new this% [y (+ y dy)] [x x])) (define/public (get-x) x))) (define circle% (class object% (super-new) (init-field [center (new point%)] [radius 1]))) 1 . o.f field access (define p (new point% [x 11] [y 22])) p p.x 2 . o.f1.f2 repeated field access (define c (new circle% [center p] [radius 33])) c.radius c.center.x c.center.y 3 . ( o .m a ... ) invoke method m on object o wth arguments a ... (define p2 (p .move-x 1)) p2.x 4 . ( o .m1 a1 ... .m2 a2 ... ) same as ( ( o .m1 a1 ... ) .m2 a2 ... ) (p .move-x 1 .move-y 2 .get-x) 5 . ( o.m a ... ) invoke method m on object o wth arguments a ... (p.move-x 20) (p.move-x 20 .move-y 4) ; same as (p .move-x 20 .move-y 4)
null
https://raw.githubusercontent.com/soegaard/super/2451bf46cce1eb0dfef8b7f0da5dec7a9c265fbd/test-object-notation.rkt
racket
same as
#lang super racket (define point% (class* object% (printable<%>) (super-new) (init-field [x 0] [y 0]) (define/public (custom-print port qq-depth) (do-print this print port)) (define/public (custom-display port) (do-print this display port)) (define/public (custom-write port) (do-print this write port)) (define (do-print object out port) (display (~a "(object:point% x=" x " y=" y ")") port)) (define/public (move-x dx) (new this% [x (+ x dx)] [y y])) (define/public (move-y dy) (new this% [y (+ y dy)] [x x])) (define/public (get-x) x))) (define circle% (class object% (super-new) (init-field [center (new point%)] [radius 1]))) 1 . o.f field access (define p (new point% [x 11] [y 22])) p p.x 2 . o.f1.f2 repeated field access (define c (new circle% [center p] [radius 33])) c.radius c.center.x c.center.y 3 . ( o .m a ... ) invoke method m on object o wth arguments a ... (define p2 (p .move-x 1)) p2.x 4 . ( o .m1 a1 ... .m2 a2 ... ) same as ( ( o .m1 a1 ... ) .m2 a2 ... ) (p .move-x 1 .move-y 2 .get-x) 5 . ( o.m a ... ) invoke method m on object o wth arguments a ... (p.move-x 20) (p.move-x 20 .move-y 4) (p .move-x 20 .move-y 4)
da050abec72197d0413f1a27d74254756ce915853e9e2bfcb4b5ae0f45327069
nikodemus/SBCL
packages.impure.lisp
;;;; miscellaneous tests of package-related stuff This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; While most of SBCL is derived from the CMU CL system , the test ;;;; files (like this one) were written from scratch after the fork from CMU CL . ;;;; ;;;; This software is in the public domain and is provided with ;;;; absolutely no warranty. See the COPYING and CREDITS files for ;;;; more information. (make-package "FOO") (defvar *foo* (find-package (coerce "FOO" 'base-string))) (rename-package "FOO" (make-array 0 :element-type nil)) (assert (eq *foo* (find-package ""))) (assert (delete-package "")) (make-package "BAR") (defvar *baz* (rename-package "BAR" "BAZ")) (assert (eq *baz* (find-package "BAZ"))) (assert (delete-package *baz*)) (handler-case (export :foo) (package-error (c) (princ c)) (:no-error (&rest args) (error "(EXPORT :FOO) returned ~S" args))) (make-package "FOO") (assert (shadow #\a :foo)) (defpackage :PACKAGE-DESIGNATOR-1 (:use #.(find-package :cl))) (defpackage :PACKAGE-DESIGNATOR-2 (:import-from #.(find-package :cl) "+")) (defpackage "EXAMPLE-INDIRECT" (:import-from "CL" "+")) (defpackage "EXAMPLE-PACKAGE" (:shadow "CAR") (:shadowing-import-from "CL" "CAAR") (:use) (:import-from "CL" "CDR") (:import-from "EXAMPLE-INDIRECT" "+") (:export "CAR" "CDR" "EXAMPLE")) (flet ((check-symbol (name expected-status expected-home-name) (multiple-value-bind (symbol status) (find-symbol name "EXAMPLE-PACKAGE") (let ((home (symbol-package symbol)) (expected-home (find-package expected-home-name))) (assert (eql home expected-home)) (assert (eql status expected-status)))))) (check-symbol "CAR" :external "EXAMPLE-PACKAGE") (check-symbol "CDR" :external "CL") (check-symbol "EXAMPLE" :external "EXAMPLE-PACKAGE") (check-symbol "CAAR" :internal "CL") (check-symbol "+" :internal "CL") (check-symbol "CDDR" nil "CL")) (defpackage "TEST-ORIGINAL" (:nicknames "A-NICKNAME")) (assert (raises-error? (defpackage "A-NICKNAME"))) (assert (eql (find-package "A-NICKNAME") (find-package "TEST-ORIGINAL"))) Utilities (defun sym (package name) (let ((package (or (find-package package) package))) (multiple-value-bind (symbol status) (find-symbol name package) (assert status (package name symbol status) "No symbol with name ~A in ~S." name package symbol status) (values symbol status)))) (defmacro with-name-conflict-resolution ((symbol &key restarted) form &body body) "Resolves potential name conflict condition arising from FORM. The conflict is resolved in favour of SYMBOL, a form which must evaluate to a symbol. If RESTARTED is a symbol, it is bound for the BODY forms and set to T if a restart was invoked." (check-type restarted symbol "a binding name") (let ((%symbol (copy-symbol 'symbol))) `(let (,@(when restarted `((,restarted))) (,%symbol ,symbol)) (handler-bind ((sb-ext:name-conflict (lambda (condition) ,@(when restarted `((setf ,restarted t))) (assert (member ,%symbol (sb-ext:name-conflict-symbols condition))) (invoke-restart 'sb-ext:resolve-conflict ,%symbol)))) ,form) ,@body))) (defmacro with-packages (specs &body forms) (let ((names (mapcar #'car specs))) `(unwind-protect (progn (delete-packages ',names) ,@(mapcar (lambda (spec) `(defpackage ,@spec)) specs) ,@forms) (delete-packages ',names)))) (defun delete-packages (names) (dolist (p names) (ignore-errors (delete-package p)))) ;;;; Tests ;;; USE-PACKAGE (with-test (:name use-package.1) (with-packages (("FOO" (:export "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use))) (with-name-conflict-resolution ((sym "BAR" "SYM") :restarted restartedp) (use-package '("FOO" "BAR") "BAZ") (is restartedp) (is (eq (sym "BAR" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name use-package.2) (with-packages (("FOO" (:export "SYM")) ("BAZ" (:use) (:intern "SYM"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (use-package "FOO" "BAZ") (is restartedp) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name use-package.2a) (with-packages (("FOO" (:export "SYM")) ("BAZ" (:use) (:intern "SYM"))) (with-name-conflict-resolution ((sym "BAZ" "SYM") :restarted restartedp) (use-package "FOO" "BAZ") (is restartedp) (is (equal (list (sym "BAZ" "SYM") :internal) (multiple-value-list (sym "BAZ" "SYM"))))))) (with-test (:name use-package-conflict-set :fails-on :sbcl) (with-packages (("FOO" (:export "SYM")) ("QUX" (:export "SYM")) ("BAR" (:intern "SYM")) ("BAZ" (:use) (:import-from "BAR" "SYM"))) (let ((conflict-set)) (block nil (handler-bind ((sb-ext:name-conflict (lambda (condition) (setf conflict-set (copy-list (sb-ext:name-conflict-symbols condition))) (return)))) (use-package '("FOO" "QUX") "BAZ"))) (setf conflict-set (sort conflict-set #'string< :key (lambda (symbol) (package-name (symbol-package symbol))))) (is (equal (list (sym "BAR" "SYM") (sym "FOO" "SYM") (sym "QUX" "SYM")) conflict-set))))) ;;; EXPORT (with-test (:name export.1) (with-packages (("FOO" (:intern "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use "FOO" "BAR"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name export.1a) (with-packages (("FOO" (:intern "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use "FOO" "BAR"))) (with-name-conflict-resolution ((sym "BAR" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (eq (sym "BAR" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name export.ensure-exported) (with-packages (("FOO" (:intern "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use "FOO" "BAR") (:IMPORT-FROM "BAR" "SYM"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (equal (list (sym "FOO" "SYM") :external) (multiple-value-list (sym "FOO" "SYM")))) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name export.3.intern) (with-packages (("FOO" (:intern "SYM")) ("BAZ" (:use "FOO") (:intern "SYM"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name export.3a.intern) (with-packages (("FOO" (:intern "SYM")) ("BAZ" (:use "FOO") (:intern "SYM"))) (with-name-conflict-resolution ((sym "BAZ" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (equal (list (sym "BAZ" "SYM") :internal) (multiple-value-list (sym "BAZ" "SYM"))))))) ;;; IMPORT (with-test (:name import-nil.1) (with-packages (("FOO" (:use) (:intern "NIL")) ("BAZ" (:use) (:intern "NIL"))) (with-name-conflict-resolution ((sym "FOO" "NIL") :restarted restartedp) (import (list (sym "FOO" "NIL")) "BAZ") (is restartedp) (is (eq (sym "FOO" "NIL") (sym "BAZ" "NIL")))))) (with-test (:name import-nil.2) (with-packages (("BAZ" (:use) (:intern "NIL"))) (with-name-conflict-resolution ('CL:NIL :restarted restartedp) (import '(CL:NIL) "BAZ") (is restartedp) (is (eq 'CL:NIL (sym "BAZ" "NIL")))))) (with-test (:name import-single-conflict :fails-on :sbcl) (with-packages (("FOO" (:export "NIL")) ("BAR" (:export "NIL")) ("BAZ" (:use))) (let ((conflict-sets '())) (handler-bind ((sb-ext:name-conflict (lambda (condition) (push (copy-list (sb-ext:name-conflict-symbols condition)) conflict-sets) (invoke-restart 'sb-ext:resolve-conflict 'CL:NIL)))) (import (list 'CL:NIL (sym "FOO" "NIL") (sym "BAR" "NIL")) "BAZ")) (is (eql 1 (length conflict-sets))) (is (eql 3 (length (first conflict-sets))))))) ;;; Make sure that resolving a name-conflict in IMPORT doesn't leave ;;; multiple symbols of the same name in the package (this particular ;;; scenario found in 1.0.38.9, but clearly a longstanding issue). (with-test (:name import-conflict-resolution) (with-packages (("FOO" (:export "NIL")) ("BAR" (:use))) (with-name-conflict-resolution ((sym "FOO" "NIL")) (import (list 'CL:NIL (sym "FOO" "NIL")) "BAR")) (do-symbols (sym "BAR") (assert (eq sym (sym "FOO" "NIL")))))) UNINTERN (with-test (:name unintern.1) (with-packages (("FOO" (:export "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use "FOO" "BAR") (:shadow "SYM"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (unintern (sym "BAZ" "SYM") "BAZ") (is restartedp) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name unintern.2) (with-packages (("FOO" (:intern "SYM"))) (unintern :sym "FOO") (assert (find-symbol "SYM" "FOO")))) ;;; WITH-PACKAGE-ITERATOR error signalling had problems (with-test (:name with-package-itarator.error) (assert (eq :good (handler-case (progn (eval '(with-package-iterator (sym :cl-user :foo) (sym))) :bad) ((and simple-condition program-error) (c) (assert (equal (list :foo) (simple-condition-format-arguments c))) :good))))) ;;; MAKE-PACKAGE error in another thread blocking FIND-PACKAGE & FIND-SYMBOL (with-test (:name :bug-511072 :skipped-on '(not :sb-thread)) (let* ((p (make-package :bug-511072)) (sem1 (sb-thread:make-semaphore)) (sem2 (sb-thread:make-semaphore)) (t2 (make-join-thread (lambda () (handler-bind ((error (lambda (c) (sb-thread:signal-semaphore sem1) (sb-thread:wait-on-semaphore sem2) (abort c)))) (make-package :bug-511072)))))) (sb-thread:wait-on-semaphore sem1) (with-timeout 10 (assert (eq 'cons (read-from-string "CL:CONS")))) (sb-thread:signal-semaphore sem2))) (with-test (:name :package-local-nicknames) ;; Clear slate (without-package-locks (delete-package :package-local-nicknames-test-1) (delete-package :package-local-nicknames-test-2)) (eval `(defpackage :package-local-nicknames-test-1 (:local-nicknames (:l :cl) (:sb :sb-ext)))) (eval `(defpackage :package-local-nicknames-test-2 (:export "CONS"))) ;; Introspection (let ((alist (package-local-nicknames :package-local-nicknames-test-1))) (assert (equal '("L" . "CL") (assoc "L" alist :test 'string=))) (assert (equal '("SB" . "SB-EXT") (assoc "SB" alist :test 'string=))) (assert (eql 2 (length alist)))) ;; Usage (let ((*package* (find-package :package-local-nicknames-test-1))) (let ((cons0 (read-from-string "L:CONS")) (exit0 (read-from-string "SB:EXIT")) (cons1 (find-symbol "CONS" :l)) (exit1 (find-symbol "EXIT" :sb)) (cl (find-package :l)) (sb (find-package :sb))) (assert (eq 'cons cons0)) (assert (eq 'cons cons1)) (assert (equal "L:CONS" (prin1-to-string cons0))) (assert (eq 'sb-ext:exit exit0)) (assert (eq 'sb-ext:exit exit1)) (assert (equal "SB:EXIT" (prin1-to-string exit0))) (assert (eq cl (find-package :common-lisp))) (assert (eq sb (find-package :sb-ext))))) ;; Can't add same name twice for different global names. (assert (eq :oopsie (handler-case (add-package-local-nickname :l :package-local-nicknames-test-2 :package-local-nicknames-test-1) (error () :oopsie)))) ;; But same name twice is OK. (add-package-local-nickname :l :cl :package-local-nicknames-test-1) ;; Removal. (assert (remove-package-local-nickname :l :package-local-nicknames-test-1)) (let ((*package* (find-package :package-local-nicknames-test-1))) (let ((exit0 (read-from-string "SB:EXIT")) (exit1 (find-symbol "EXIT" :sb)) (sb (find-package :sb))) (assert (eq 'sb-ext:exit exit0)) (assert (eq 'sb-ext:exit exit1)) (assert (equal "SB:EXIT" (prin1-to-string exit0))) (assert (eq sb (find-package :sb-ext))) (assert (not (find-package :l))))) ;; Adding back as another package. (assert (eq (find-package :package-local-nicknames-test-1) (add-package-local-nickname :l :package-local-nicknames-test-2 :package-local-nicknames-test-1))) (let ((*package* (find-package :package-local-nicknames-test-1))) (let ((cons0 (read-from-string "L:CONS")) (exit0 (read-from-string "SB:EXIT")) (cons1 (find-symbol "CONS" :l)) (exit1 (find-symbol "EXIT" :sb)) (cl (find-package :l)) (sb (find-package :sb))) (assert (eq cons0 cons1)) (assert (not (eq 'cons cons0))) (assert (eq (find-symbol "CONS" :package-local-nicknames-test-2) cons0)) (assert (equal "L:CONS" (prin1-to-string cons0))) (assert (eq 'sb-ext:exit exit0)) (assert (eq 'sb-ext:exit exit1)) (assert (equal "SB:EXIT" (prin1-to-string exit0))) (assert (eq cl (find-package :package-local-nicknames-test-2))) (assert (eq sb (find-package :sb-ext))))) ;; Interaction with package locks. (lock-package :package-local-nicknames-test-1) (assert (eq :package-oopsie (handler-case (add-package-local-nickname :c :sb-c :package-local-nicknames-test-1) (package-lock-violation () :package-oopsie)))) (assert (eq :package-oopsie (handler-case (remove-package-local-nickname :l :package-local-nicknames-test-1) (package-lock-violation () :package-oopsie)))) (unlock-package :package-local-nicknames-test-1) (add-package-local-nickname :c :sb-c :package-local-nicknames-test-1) (remove-package-local-nickname :l :package-local-nicknames-test-1))
null
https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/tests/packages.impure.lisp
lisp
miscellaneous tests of package-related stuff more information. files (like this one) were written from scratch after the fork This software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. Tests USE-PACKAGE EXPORT IMPORT Make sure that resolving a name-conflict in IMPORT doesn't leave multiple symbols of the same name in the package (this particular scenario found in 1.0.38.9, but clearly a longstanding issue). WITH-PACKAGE-ITERATOR error signalling had problems MAKE-PACKAGE error in another thread blocking FIND-PACKAGE & FIND-SYMBOL Clear slate Introspection Usage Can't add same name twice for different global names. But same name twice is OK. Removal. Adding back as another package. Interaction with package locks.
This software is part of the SBCL system . See the README file for While most of SBCL is derived from the CMU CL system , the test from CMU CL . (make-package "FOO") (defvar *foo* (find-package (coerce "FOO" 'base-string))) (rename-package "FOO" (make-array 0 :element-type nil)) (assert (eq *foo* (find-package ""))) (assert (delete-package "")) (make-package "BAR") (defvar *baz* (rename-package "BAR" "BAZ")) (assert (eq *baz* (find-package "BAZ"))) (assert (delete-package *baz*)) (handler-case (export :foo) (package-error (c) (princ c)) (:no-error (&rest args) (error "(EXPORT :FOO) returned ~S" args))) (make-package "FOO") (assert (shadow #\a :foo)) (defpackage :PACKAGE-DESIGNATOR-1 (:use #.(find-package :cl))) (defpackage :PACKAGE-DESIGNATOR-2 (:import-from #.(find-package :cl) "+")) (defpackage "EXAMPLE-INDIRECT" (:import-from "CL" "+")) (defpackage "EXAMPLE-PACKAGE" (:shadow "CAR") (:shadowing-import-from "CL" "CAAR") (:use) (:import-from "CL" "CDR") (:import-from "EXAMPLE-INDIRECT" "+") (:export "CAR" "CDR" "EXAMPLE")) (flet ((check-symbol (name expected-status expected-home-name) (multiple-value-bind (symbol status) (find-symbol name "EXAMPLE-PACKAGE") (let ((home (symbol-package symbol)) (expected-home (find-package expected-home-name))) (assert (eql home expected-home)) (assert (eql status expected-status)))))) (check-symbol "CAR" :external "EXAMPLE-PACKAGE") (check-symbol "CDR" :external "CL") (check-symbol "EXAMPLE" :external "EXAMPLE-PACKAGE") (check-symbol "CAAR" :internal "CL") (check-symbol "+" :internal "CL") (check-symbol "CDDR" nil "CL")) (defpackage "TEST-ORIGINAL" (:nicknames "A-NICKNAME")) (assert (raises-error? (defpackage "A-NICKNAME"))) (assert (eql (find-package "A-NICKNAME") (find-package "TEST-ORIGINAL"))) Utilities (defun sym (package name) (let ((package (or (find-package package) package))) (multiple-value-bind (symbol status) (find-symbol name package) (assert status (package name symbol status) "No symbol with name ~A in ~S." name package symbol status) (values symbol status)))) (defmacro with-name-conflict-resolution ((symbol &key restarted) form &body body) "Resolves potential name conflict condition arising from FORM. The conflict is resolved in favour of SYMBOL, a form which must evaluate to a symbol. If RESTARTED is a symbol, it is bound for the BODY forms and set to T if a restart was invoked." (check-type restarted symbol "a binding name") (let ((%symbol (copy-symbol 'symbol))) `(let (,@(when restarted `((,restarted))) (,%symbol ,symbol)) (handler-bind ((sb-ext:name-conflict (lambda (condition) ,@(when restarted `((setf ,restarted t))) (assert (member ,%symbol (sb-ext:name-conflict-symbols condition))) (invoke-restart 'sb-ext:resolve-conflict ,%symbol)))) ,form) ,@body))) (defmacro with-packages (specs &body forms) (let ((names (mapcar #'car specs))) `(unwind-protect (progn (delete-packages ',names) ,@(mapcar (lambda (spec) `(defpackage ,@spec)) specs) ,@forms) (delete-packages ',names)))) (defun delete-packages (names) (dolist (p names) (ignore-errors (delete-package p)))) (with-test (:name use-package.1) (with-packages (("FOO" (:export "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use))) (with-name-conflict-resolution ((sym "BAR" "SYM") :restarted restartedp) (use-package '("FOO" "BAR") "BAZ") (is restartedp) (is (eq (sym "BAR" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name use-package.2) (with-packages (("FOO" (:export "SYM")) ("BAZ" (:use) (:intern "SYM"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (use-package "FOO" "BAZ") (is restartedp) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name use-package.2a) (with-packages (("FOO" (:export "SYM")) ("BAZ" (:use) (:intern "SYM"))) (with-name-conflict-resolution ((sym "BAZ" "SYM") :restarted restartedp) (use-package "FOO" "BAZ") (is restartedp) (is (equal (list (sym "BAZ" "SYM") :internal) (multiple-value-list (sym "BAZ" "SYM"))))))) (with-test (:name use-package-conflict-set :fails-on :sbcl) (with-packages (("FOO" (:export "SYM")) ("QUX" (:export "SYM")) ("BAR" (:intern "SYM")) ("BAZ" (:use) (:import-from "BAR" "SYM"))) (let ((conflict-set)) (block nil (handler-bind ((sb-ext:name-conflict (lambda (condition) (setf conflict-set (copy-list (sb-ext:name-conflict-symbols condition))) (return)))) (use-package '("FOO" "QUX") "BAZ"))) (setf conflict-set (sort conflict-set #'string< :key (lambda (symbol) (package-name (symbol-package symbol))))) (is (equal (list (sym "BAR" "SYM") (sym "FOO" "SYM") (sym "QUX" "SYM")) conflict-set))))) (with-test (:name export.1) (with-packages (("FOO" (:intern "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use "FOO" "BAR"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name export.1a) (with-packages (("FOO" (:intern "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use "FOO" "BAR"))) (with-name-conflict-resolution ((sym "BAR" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (eq (sym "BAR" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name export.ensure-exported) (with-packages (("FOO" (:intern "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use "FOO" "BAR") (:IMPORT-FROM "BAR" "SYM"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (equal (list (sym "FOO" "SYM") :external) (multiple-value-list (sym "FOO" "SYM")))) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name export.3.intern) (with-packages (("FOO" (:intern "SYM")) ("BAZ" (:use "FOO") (:intern "SYM"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name export.3a.intern) (with-packages (("FOO" (:intern "SYM")) ("BAZ" (:use "FOO") (:intern "SYM"))) (with-name-conflict-resolution ((sym "BAZ" "SYM") :restarted restartedp) (export (sym "FOO" "SYM") "FOO") (is restartedp) (is (equal (list (sym "BAZ" "SYM") :internal) (multiple-value-list (sym "BAZ" "SYM"))))))) (with-test (:name import-nil.1) (with-packages (("FOO" (:use) (:intern "NIL")) ("BAZ" (:use) (:intern "NIL"))) (with-name-conflict-resolution ((sym "FOO" "NIL") :restarted restartedp) (import (list (sym "FOO" "NIL")) "BAZ") (is restartedp) (is (eq (sym "FOO" "NIL") (sym "BAZ" "NIL")))))) (with-test (:name import-nil.2) (with-packages (("BAZ" (:use) (:intern "NIL"))) (with-name-conflict-resolution ('CL:NIL :restarted restartedp) (import '(CL:NIL) "BAZ") (is restartedp) (is (eq 'CL:NIL (sym "BAZ" "NIL")))))) (with-test (:name import-single-conflict :fails-on :sbcl) (with-packages (("FOO" (:export "NIL")) ("BAR" (:export "NIL")) ("BAZ" (:use))) (let ((conflict-sets '())) (handler-bind ((sb-ext:name-conflict (lambda (condition) (push (copy-list (sb-ext:name-conflict-symbols condition)) conflict-sets) (invoke-restart 'sb-ext:resolve-conflict 'CL:NIL)))) (import (list 'CL:NIL (sym "FOO" "NIL") (sym "BAR" "NIL")) "BAZ")) (is (eql 1 (length conflict-sets))) (is (eql 3 (length (first conflict-sets))))))) (with-test (:name import-conflict-resolution) (with-packages (("FOO" (:export "NIL")) ("BAR" (:use))) (with-name-conflict-resolution ((sym "FOO" "NIL")) (import (list 'CL:NIL (sym "FOO" "NIL")) "BAR")) (do-symbols (sym "BAR") (assert (eq sym (sym "FOO" "NIL")))))) UNINTERN (with-test (:name unintern.1) (with-packages (("FOO" (:export "SYM")) ("BAR" (:export "SYM")) ("BAZ" (:use "FOO" "BAR") (:shadow "SYM"))) (with-name-conflict-resolution ((sym "FOO" "SYM") :restarted restartedp) (unintern (sym "BAZ" "SYM") "BAZ") (is restartedp) (is (eq (sym "FOO" "SYM") (sym "BAZ" "SYM")))))) (with-test (:name unintern.2) (with-packages (("FOO" (:intern "SYM"))) (unintern :sym "FOO") (assert (find-symbol "SYM" "FOO")))) (with-test (:name with-package-itarator.error) (assert (eq :good (handler-case (progn (eval '(with-package-iterator (sym :cl-user :foo) (sym))) :bad) ((and simple-condition program-error) (c) (assert (equal (list :foo) (simple-condition-format-arguments c))) :good))))) (with-test (:name :bug-511072 :skipped-on '(not :sb-thread)) (let* ((p (make-package :bug-511072)) (sem1 (sb-thread:make-semaphore)) (sem2 (sb-thread:make-semaphore)) (t2 (make-join-thread (lambda () (handler-bind ((error (lambda (c) (sb-thread:signal-semaphore sem1) (sb-thread:wait-on-semaphore sem2) (abort c)))) (make-package :bug-511072)))))) (sb-thread:wait-on-semaphore sem1) (with-timeout 10 (assert (eq 'cons (read-from-string "CL:CONS")))) (sb-thread:signal-semaphore sem2))) (with-test (:name :package-local-nicknames) (without-package-locks (delete-package :package-local-nicknames-test-1) (delete-package :package-local-nicknames-test-2)) (eval `(defpackage :package-local-nicknames-test-1 (:local-nicknames (:l :cl) (:sb :sb-ext)))) (eval `(defpackage :package-local-nicknames-test-2 (:export "CONS"))) (let ((alist (package-local-nicknames :package-local-nicknames-test-1))) (assert (equal '("L" . "CL") (assoc "L" alist :test 'string=))) (assert (equal '("SB" . "SB-EXT") (assoc "SB" alist :test 'string=))) (assert (eql 2 (length alist)))) (let ((*package* (find-package :package-local-nicknames-test-1))) (let ((cons0 (read-from-string "L:CONS")) (exit0 (read-from-string "SB:EXIT")) (cons1 (find-symbol "CONS" :l)) (exit1 (find-symbol "EXIT" :sb)) (cl (find-package :l)) (sb (find-package :sb))) (assert (eq 'cons cons0)) (assert (eq 'cons cons1)) (assert (equal "L:CONS" (prin1-to-string cons0))) (assert (eq 'sb-ext:exit exit0)) (assert (eq 'sb-ext:exit exit1)) (assert (equal "SB:EXIT" (prin1-to-string exit0))) (assert (eq cl (find-package :common-lisp))) (assert (eq sb (find-package :sb-ext))))) (assert (eq :oopsie (handler-case (add-package-local-nickname :l :package-local-nicknames-test-2 :package-local-nicknames-test-1) (error () :oopsie)))) (add-package-local-nickname :l :cl :package-local-nicknames-test-1) (assert (remove-package-local-nickname :l :package-local-nicknames-test-1)) (let ((*package* (find-package :package-local-nicknames-test-1))) (let ((exit0 (read-from-string "SB:EXIT")) (exit1 (find-symbol "EXIT" :sb)) (sb (find-package :sb))) (assert (eq 'sb-ext:exit exit0)) (assert (eq 'sb-ext:exit exit1)) (assert (equal "SB:EXIT" (prin1-to-string exit0))) (assert (eq sb (find-package :sb-ext))) (assert (not (find-package :l))))) (assert (eq (find-package :package-local-nicknames-test-1) (add-package-local-nickname :l :package-local-nicknames-test-2 :package-local-nicknames-test-1))) (let ((*package* (find-package :package-local-nicknames-test-1))) (let ((cons0 (read-from-string "L:CONS")) (exit0 (read-from-string "SB:EXIT")) (cons1 (find-symbol "CONS" :l)) (exit1 (find-symbol "EXIT" :sb)) (cl (find-package :l)) (sb (find-package :sb))) (assert (eq cons0 cons1)) (assert (not (eq 'cons cons0))) (assert (eq (find-symbol "CONS" :package-local-nicknames-test-2) cons0)) (assert (equal "L:CONS" (prin1-to-string cons0))) (assert (eq 'sb-ext:exit exit0)) (assert (eq 'sb-ext:exit exit1)) (assert (equal "SB:EXIT" (prin1-to-string exit0))) (assert (eq cl (find-package :package-local-nicknames-test-2))) (assert (eq sb (find-package :sb-ext))))) (lock-package :package-local-nicknames-test-1) (assert (eq :package-oopsie (handler-case (add-package-local-nickname :c :sb-c :package-local-nicknames-test-1) (package-lock-violation () :package-oopsie)))) (assert (eq :package-oopsie (handler-case (remove-package-local-nickname :l :package-local-nicknames-test-1) (package-lock-violation () :package-oopsie)))) (unlock-package :package-local-nicknames-test-1) (add-package-local-nickname :c :sb-c :package-local-nicknames-test-1) (remove-package-local-nickname :l :package-local-nicknames-test-1))
b9419e4d08544cc6e709d01278809db519ca3daed00131e3d785e16e38345127
shortishly/haystack
haystack_config.erl
Copyright ( c ) 2012 - 2016 < > %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(haystack_config). -export([acceptors/1]). -export([debug/1]). -export([docker/1]). -export([enabled/1]). -export([origin/0]). -export([origin/1]). -export([port/1]). -export([tsig_rr_fudge/0]). %% We are not using envy for the following docker environment variable %% lookups because we don't want to prefix the environment variable %% with the haystack application name. docker(host) -> haystack:get_env(docker_host, [os_env]); docker(cert_path) -> haystack:get_env(docker_cert_path, [os_env]); docker(cert) -> haystack:get_env(docker_cert, [os_env]); docker(key) -> haystack:get_env(docker_key, [os_env]). port(udp) -> envy(to_integer, udp_port, 53); port(http) -> envy(to_integer, http_port, 80); port(http_alt) -> envy(to_integer, http_alt_port, 8080). enabled(debug) -> envy(to_boolean, debug, false). debug(applications) -> envy(to_list, debug_applications, "haystack"). acceptors(http) -> envy(to_integer, http_acceptors, 100); acceptors(http_alt) -> envy(to_integer, http_alt_acceptors, 100). tsig_rr_fudge() -> envy(to_integer, tsig_rr_fudge, 300). origin() -> envy(to_binary, origin, <<"haystack">>). origin(ns) -> <<"ns.", (origin())/binary>>; origin(services) -> <<"services.", (origin())/binary>>; origin(dockers) -> <<"dockers.", (origin())/binary>>; origin(containers) -> <<"containers.", (origin())/binary>>. envy(To, Name, Default) -> envy:To(haystack, Name, default(Default)). default(Default) -> [os_env, app_env, {default, Default}].
null
https://raw.githubusercontent.com/shortishly/haystack/7ff0d737dcd90adf60c861b2cf755aee1355e555/src/haystack_config.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. We are not using envy for the following docker environment variable lookups because we don't want to prefix the environment variable with the haystack application name.
Copyright ( c ) 2012 - 2016 < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(haystack_config). -export([acceptors/1]). -export([debug/1]). -export([docker/1]). -export([enabled/1]). -export([origin/0]). -export([origin/1]). -export([port/1]). -export([tsig_rr_fudge/0]). docker(host) -> haystack:get_env(docker_host, [os_env]); docker(cert_path) -> haystack:get_env(docker_cert_path, [os_env]); docker(cert) -> haystack:get_env(docker_cert, [os_env]); docker(key) -> haystack:get_env(docker_key, [os_env]). port(udp) -> envy(to_integer, udp_port, 53); port(http) -> envy(to_integer, http_port, 80); port(http_alt) -> envy(to_integer, http_alt_port, 8080). enabled(debug) -> envy(to_boolean, debug, false). debug(applications) -> envy(to_list, debug_applications, "haystack"). acceptors(http) -> envy(to_integer, http_acceptors, 100); acceptors(http_alt) -> envy(to_integer, http_alt_acceptors, 100). tsig_rr_fudge() -> envy(to_integer, tsig_rr_fudge, 300). origin() -> envy(to_binary, origin, <<"haystack">>). origin(ns) -> <<"ns.", (origin())/binary>>; origin(services) -> <<"services.", (origin())/binary>>; origin(dockers) -> <<"dockers.", (origin())/binary>>; origin(containers) -> <<"containers.", (origin())/binary>>. envy(To, Name, Default) -> envy:To(haystack, Name, default(Default)). default(Default) -> [os_env, app_env, {default, Default}].
2911dec9cf33400a9a36a6ba26af7c0b4ef1393f2803cfe350c27932fad68d82
HunterYIboHu/htdp2-solution
ex205-examples.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 ex205-examples) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/itunes) ;; data difinitions ( define - struct date [ year month day hour minute second ] ) ; A Date is a structure: ( make - date N N N N N N ) interpretation An instance records six pieces of information : the date 's year , month ( 1 ~ 12 ) , day ( 1 ~ 31 ) , hour ( 0 ~ 23 ) , minute ( 0 ~ 59 ) , andsecond ( 0 ~ 59 ) (define 1-add (create-date 2016 8 12 14 20 50)) (define 1-play (create-date 2016 8 12 14 30 24)) (define 2-add (create-date 2016 7 29 22 15 45)) (define 2-play (create-date 2016 8 9 12 20 30)) (define 3-add (create-date 2016 7 14 20 13 45)) (define 3-play (create-date 2016 8 5 19 7 3)) ;;;; data difinition functions ;;;; ; String -> List ; consume a n as the name of track (define (create-name n) (list "name" n)) ; String -> List ; consume a n as the name of artists (define (create-artist n) (list "artist" n)) ; String -> List ; consume a t as the title of album (define (create-album t) (list "album" t)) ; N -> List ; consume a N as the lasting time of music, by milesecond. (define (create-time lt) (list "time" lt)) ; N -> List ; consume a N as its postion with the album (define (create-track# pos) (list "track#" pos)) ; Date -> List ; the date represent when the track is added (define (create-added d) (list "added" d)) ; N -> List ; the number repersent how often it has been played (define (create-play# pt) (list "play#" pt)) ; Date -> List ; the date represent when the track is played recently (define (create-played d) (list "played" d)) ;;;; end difinition functions ;;;; An Association is a list of two items : ( cons String ( cons BSDN ' ( ) ) ) (define 1-name (create-name "Ascendance")) (define 2-name (create-name "Master of Tides")) (define 3-name (create-name "Animals")) (define 1-artist (create-artist "Lindsey Stirling")) (define 2-artist (create-artist "Maroon5")) (define 1-album (create-album "Shatter Me")) (define 2-album (create-album "Animals")) (define 1-time (create-time 266000)) (define 2-time (create-time 261000)) (define 3-time (create-time 231000)) (define 1-track# (create-track# 8)) (define 2-track# (create-track# 11)) (define 3-track# (create-track# 1)) (define 1-added (create-added 1-add)) (define 2-added (create-added 2-add)) (define 3-added (create-added 3-add)) (define 1-play# (create-play# 45)) (define 2-play# (create-play# 60)) (define 3-play# (create-play# 100)) (define 1-played (create-played 1-play)) (define 2-played (create-played 2-play)) (define 3-played (create-played 3-play)) A BSDN is one of : ; - Boolean ; - Number ; - String ; - Date ; An LAssoc is one of: ; - '() - ( cons Association LAssoc ) (define 1-music (list 1-name 1-artist 1-album 1-time 1-track# 1-added 1-play# 1-played)) (define 2-music (list 2-name 1-artist 1-album 2-time 2-track# 2-added 2-play# 2-played)) (define 3-music (list 3-name 2-artist 2-album 3-time 3-track# 3-added 3-play# 3-played)) An LLists is one of : ; - '() - ( cons LAssoc LLists ) (define 1-Track (list 1-music 2-music 3-music)) (define 2-Track (list 2-music 1-music)) (define one-Track (make-list 10 1-music)) (define two-Track (list 2-music 2-music 3-music 2-music 3-music))
null
https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter2/Section13-project-list/ex205-examples.rkt
racket
about the language level of this file in a form that our tools can easily process. data difinitions A Date is a structure: data difinition functions ;;;; String -> List consume a n as the name of track String -> List consume a n as the name of artists String -> List consume a t as the title of album N -> List consume a N as the lasting time of music, by milesecond. N -> List consume a N as its postion with the album Date -> List the date represent when the track is added N -> List the number repersent how often it has been played Date -> List the date represent when the track is played recently end difinition functions ;;;; - Boolean - Number - String - Date An LAssoc is one of: - '() - '()
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex205-examples) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/itunes) ( define - struct date [ year month day hour minute second ] ) ( make - date N N N N N N ) interpretation An instance records six pieces of information : the date 's year , month ( 1 ~ 12 ) , day ( 1 ~ 31 ) , hour ( 0 ~ 23 ) , minute ( 0 ~ 59 ) , andsecond ( 0 ~ 59 ) (define 1-add (create-date 2016 8 12 14 20 50)) (define 1-play (create-date 2016 8 12 14 30 24)) (define 2-add (create-date 2016 7 29 22 15 45)) (define 2-play (create-date 2016 8 9 12 20 30)) (define 3-add (create-date 2016 7 14 20 13 45)) (define 3-play (create-date 2016 8 5 19 7 3)) (define (create-name n) (list "name" n)) (define (create-artist n) (list "artist" n)) (define (create-album t) (list "album" t)) (define (create-time lt) (list "time" lt)) (define (create-track# pos) (list "track#" pos)) (define (create-added d) (list "added" d)) (define (create-play# pt) (list "play#" pt)) (define (create-played d) (list "played" d)) An Association is a list of two items : ( cons String ( cons BSDN ' ( ) ) ) (define 1-name (create-name "Ascendance")) (define 2-name (create-name "Master of Tides")) (define 3-name (create-name "Animals")) (define 1-artist (create-artist "Lindsey Stirling")) (define 2-artist (create-artist "Maroon5")) (define 1-album (create-album "Shatter Me")) (define 2-album (create-album "Animals")) (define 1-time (create-time 266000)) (define 2-time (create-time 261000)) (define 3-time (create-time 231000)) (define 1-track# (create-track# 8)) (define 2-track# (create-track# 11)) (define 3-track# (create-track# 1)) (define 1-added (create-added 1-add)) (define 2-added (create-added 2-add)) (define 3-added (create-added 3-add)) (define 1-play# (create-play# 45)) (define 2-play# (create-play# 60)) (define 3-play# (create-play# 100)) (define 1-played (create-played 1-play)) (define 2-played (create-played 2-play)) (define 3-played (create-played 3-play)) A BSDN is one of : - ( cons Association LAssoc ) (define 1-music (list 1-name 1-artist 1-album 1-time 1-track# 1-added 1-play# 1-played)) (define 2-music (list 2-name 1-artist 1-album 2-time 2-track# 2-added 2-play# 2-played)) (define 3-music (list 3-name 2-artist 2-album 3-time 3-track# 3-added 3-play# 3-played)) An LLists is one of : - ( cons LAssoc LLists ) (define 1-Track (list 1-music 2-music 3-music)) (define 2-Track (list 2-music 1-music)) (define one-Track (make-list 10 1-music)) (define two-Track (list 2-music 2-music 3-music 2-music 3-music))
88e455f258e7ad31c2c8084fff7aa347151418459a27e0bec8d87dc3e03654b2
spechub/Hets
GraphQL.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} module PGIP.GraphQL (isGraphQL, processGraphQL) where import PGIP.GraphQL.Resolver import PGIP.Shared import Driver.Options import Data.Aeson as Aeson import qualified Data.ByteString.Lazy as LBS import qualified Data.Text.Lazy.Encoding as LEncoding import Data.Maybe import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Text.Lazy as LText import Data.Text as Text import Network.Wai import GHC.Generics import qualified Control.Monad.Fail as Fail isGraphQL :: String -> [String] -> Bool isGraphQL httpVerb pathComponents = httpVerb == "POST" && pathComponents == ["graphql"] processGraphQL :: HetcatsOpts -> Cache -> Request -> IO String processGraphQL opts sessionReference request = do body <- receivedRequestBody request let bodyQueryE = Aeson.eitherDecode $ LBS.fromStrict body :: Either String QueryBodyAux queryBody <- case bodyQueryE of Left message -> Fail.fail ("bad request body: " ++ message) Right b -> return $ toGraphQLQueryBody b resolve opts sessionReference (graphQLQuery queryBody) (graphQLVariables queryBody) -- This structure contains the data that is passed to the GraphQL API data QueryBody = QueryBody { graphQLQuery :: Text , graphQLVariables :: Map Text Text } deriving (Show, Generic) -- This is an auxiliary strucutre that helps to parse the request body. -- It is then converted to QueryBody. data QueryBodyAux = QueryBodyAux { query :: Text , variables :: Maybe (Map Text Aeson.Value) } deriving (Show, Generic) instance FromJSON QueryBodyAux -- For an unknown reason, GraphQL-API requires the query to be enclosed in {} toGraphQLQueryBody :: QueryBodyAux -> QueryBody toGraphQLQueryBody QueryBodyAux { query = q, variables = aesonVariables } = QueryBody { graphQLQuery = q , graphQLVariables = Map.map convert $ fromMaybe Map.empty aesonVariables } where convert = LText.toStrict . LEncoding.decodeUtf8 . Aeson.encode
null
https://raw.githubusercontent.com/spechub/Hets/f582640a174df08d4c965d7c0a1ab24d1a31000d/PGIP/GraphQL.hs
haskell
# LANGUAGE OverloadedStrings # This structure contains the data that is passed to the GraphQL API This is an auxiliary strucutre that helps to parse the request body. It is then converted to QueryBody. For an unknown reason, GraphQL-API requires the query to be enclosed in {}
# LANGUAGE DeriveGeneric # module PGIP.GraphQL (isGraphQL, processGraphQL) where import PGIP.GraphQL.Resolver import PGIP.Shared import Driver.Options import Data.Aeson as Aeson import qualified Data.ByteString.Lazy as LBS import qualified Data.Text.Lazy.Encoding as LEncoding import Data.Maybe import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Text.Lazy as LText import Data.Text as Text import Network.Wai import GHC.Generics import qualified Control.Monad.Fail as Fail isGraphQL :: String -> [String] -> Bool isGraphQL httpVerb pathComponents = httpVerb == "POST" && pathComponents == ["graphql"] processGraphQL :: HetcatsOpts -> Cache -> Request -> IO String processGraphQL opts sessionReference request = do body <- receivedRequestBody request let bodyQueryE = Aeson.eitherDecode $ LBS.fromStrict body :: Either String QueryBodyAux queryBody <- case bodyQueryE of Left message -> Fail.fail ("bad request body: " ++ message) Right b -> return $ toGraphQLQueryBody b resolve opts sessionReference (graphQLQuery queryBody) (graphQLVariables queryBody) data QueryBody = QueryBody { graphQLQuery :: Text , graphQLVariables :: Map Text Text } deriving (Show, Generic) data QueryBodyAux = QueryBodyAux { query :: Text , variables :: Maybe (Map Text Aeson.Value) } deriving (Show, Generic) instance FromJSON QueryBodyAux toGraphQLQueryBody :: QueryBodyAux -> QueryBody toGraphQLQueryBody QueryBodyAux { query = q, variables = aesonVariables } = QueryBody { graphQLQuery = q , graphQLVariables = Map.map convert $ fromMaybe Map.empty aesonVariables } where convert = LText.toStrict . LEncoding.decodeUtf8 . Aeson.encode
143029d8e5abec0e34ecd7d1cb9c369f5af2bf2a7b2151c9d1c5d7f9b7c04a28
jacekschae/shadow-firebase
core.cljs
(ns app.core (:require [reagent.core :as reagent :refer [atom]] [app.views :as views] [app.fb.init :refer [firebase-init]] [app.fb.db :as fb-db])) (defn ^:export main [] (reagent/render-component [views/app] (.getElementById js/document "app")) (firebase-init) (fb-db/db-subscribe ["counter"]))
null
https://raw.githubusercontent.com/jacekschae/shadow-firebase/1471c02231805b8717a0b121522104465ffc1803/src/app/core.cljs
clojure
(ns app.core (:require [reagent.core :as reagent :refer [atom]] [app.views :as views] [app.fb.init :refer [firebase-init]] [app.fb.db :as fb-db])) (defn ^:export main [] (reagent/render-component [views/app] (.getElementById js/document "app")) (firebase-init) (fb-db/db-subscribe ["counter"]))
32acb9d7190063f0653e297d3a2f1ba7845c3d1a85ba8321c735d0be0c43ecba
ivanjovanovic/sicp
e-3.6.scm
Exercise 3.6 . ; ; It is useful to be able to reset a random-number generator to ; produce a sequence starting from a given value. Design a new rand procedure ; that is called with an argument that is either the symbol generate or the ; symbol reset and behaves as follows: (rand 'generate) produces a new random ; number; ((rand 'reset) <new-value>) resets the internal state variable to the ; designated <new-value>. Thus, by resetting the state, one can generate ; repeatable sequences. These are very handy to have when testing and debugging ; programs that use random numbers. ; ------------------------------------------------------------ ; This is not that difficult ot do when we know the technique of message passing. Rand is not object that contains local state and two actions ' generate and ' reset (load "../helpers.scm") ; practically we have to define our random number generator. ; first initializer (define random-init (inexact->exact (current-milliseconds))) ; and how we update random number every time randomization is called. ; @see ; I will use with some predefined constants ; just for sake of the simplicity ; m = 19 ( primary number ) a = 3 c = 5 ; Probably incorrect but for simplicity just to explain what it means to build random sequence generator ; this should be sufficient. For more information read a bit more on the topic of random/pseudo ; random number generation ; maximum number this generator can produce is m ( which we have to define significantly high for big seqs ) (define random-update (let ((m 19) (a 3) (c 5)) (lambda (x) (modulo (+ (* a x) c) m)))) ; and randomization procedure to expose ; message handler action (define rand (let ((x random-init)) (lambda (m) (cond ((eq? m 'generate) (begin (set! x (random-update x)) x)) ((eq? m 'reset) (lambda (value) (set! x value))))))) ; this is initialized by random-init ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; here we set the seed on our own ; (output "reseting") ( ( rand ' reset ) 10 ) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; here we reset the sequence ; (output "reseting") ( ( rand ' reset ) 10 ) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate)) ; (output (rand 'generate))
null
https://raw.githubusercontent.com/ivanjovanovic/sicp/a3bfbae0a0bda414b042e16bbb39bf39cd3c38f8/3.1/e-3.6.scm
scheme
It is useful to be able to reset a random-number generator to produce a sequence starting from a given value. Design a new rand procedure that is called with an argument that is either the symbol generate or the symbol reset and behaves as follows: (rand 'generate) produces a new random number; ((rand 'reset) <new-value>) resets the internal state variable to the designated <new-value>. Thus, by resetting the state, one can generate repeatable sequences. These are very handy to have when testing and debugging programs that use random numbers. ------------------------------------------------------------ This is not that difficult ot do when we know the technique of message passing. practically we have to define our random number generator. first initializer and how we update random number every time randomization is called. @see just for sake of the simplicity Probably incorrect but for simplicity just to explain what it means to build random sequence generator this should be sufficient. For more information read a bit more on the topic of random/pseudo random number generation and randomization procedure to expose message handler action this is initialized by random-init (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) here we set the seed on our own (output "reseting") (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) here we reset the sequence (output "reseting") (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate)) (output (rand 'generate))
Exercise 3.6 . Rand is not object that contains local state and two actions ' generate and ' reset (load "../helpers.scm") (define random-init (inexact->exact (current-milliseconds))) I will use with some predefined constants m = 19 ( primary number ) a = 3 c = 5 maximum number this generator can produce is m ( which we have to define significantly high for big seqs ) (define random-update (let ((m 19) (a 3) (c 5)) (lambda (x) (modulo (+ (* a x) c) m)))) (define rand (let ((x random-init)) (lambda (m) (cond ((eq? m 'generate) (begin (set! x (random-update x)) x)) ((eq? m 'reset) (lambda (value) (set! x value))))))) ( ( rand ' reset ) 10 ) ( ( rand ' reset ) 10 )
45077055fcfe085f26b658397c73f79e5827cdb17faa493d21cc29217ffb6293
IGJoshua/farolero
signal.cljc
(ns farolero.signal (:require [clojure.spec.alpha :as s] [farolero.protocols :refer [Jump]]) #?(:clj (:import (farolero.signal Signal)))) #?(:cljs (defrecord Signal [target args])) (defn make-signal [target args] (#?(:clj Signal. :cljs ->Signal) target args)) (s/fdef make-signal :args (s/cat :target (s/or :keyword keyword? :internal-integer integer?) :args (s/coll-of any?))) (extend-protocol Jump Signal (args [signal] (.-args signal)) (is-target? [signal v] (= (.-target signal) v)))
null
https://raw.githubusercontent.com/IGJoshua/farolero/db3baff4a1468a0167be74f263e2415e613c5fa8/src/cljc/farolero/signal.cljc
clojure
(ns farolero.signal (:require [clojure.spec.alpha :as s] [farolero.protocols :refer [Jump]]) #?(:clj (:import (farolero.signal Signal)))) #?(:cljs (defrecord Signal [target args])) (defn make-signal [target args] (#?(:clj Signal. :cljs ->Signal) target args)) (s/fdef make-signal :args (s/cat :target (s/or :keyword keyword? :internal-integer integer?) :args (s/coll-of any?))) (extend-protocol Jump Signal (args [signal] (.-args signal)) (is-target? [signal v] (= (.-target signal) v)))
0c53ac1b35157ffdd50f9bdad58ced854dac57aad1aa2d4349c4c1b63ab5e210
inhabitedtype/ocaml-aws
copyDBParameterGroup.mli
open Types type input = CopyDBParameterGroupMessage.t type output = CopyDBParameterGroupResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/rds/lib/copyDBParameterGroup.mli
ocaml
open Types type input = CopyDBParameterGroupMessage.t type output = CopyDBParameterGroupResult.t type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
7016cccfa115f1f28ff2f10b6b366a9614a205188a408429717245f9138251f2
aristidb/aws
Select.hs
module Aws.SimpleDb.Commands.Select where import Aws.Core import Aws.SimpleDb.Core import Control.Applicative import Control.Monad import Data.Maybe import Prelude import Text.XML.Cursor (($//), (&|)) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Text.XML.Cursor as Cu data Select = Select { sSelectExpression :: T.Text , sConsistentRead :: Bool , sNextToken :: Maybe T.Text } deriving (Show) data SelectResponse = SelectResponse { srItems :: [Item [Attribute T.Text]] , srNextToken :: Maybe T.Text } deriving (Show) select :: T.Text -> Select select expr = Select { sSelectExpression = expr, sConsistentRead = False, sNextToken = Nothing } -- | ServiceConfiguration: 'SdbConfiguration' instance SignQuery Select where type ServiceConfiguration Select = SdbConfiguration signQuery Select{..} = sdbSignQuery . catMaybes $ [ Just ("Action", "Select") , Just ("SelectExpression", T.encodeUtf8 sSelectExpression) , ("ConsistentRead", awsTrue) <$ guard sConsistentRead , (("NextToken",) . T.encodeUtf8) <$> sNextToken ] instance ResponseConsumer r SelectResponse where type ResponseMetadata SelectResponse = SdbMetadata responseConsumer _ _ = sdbResponseConsumer parse where parse cursor = do sdbCheckResponseType () "SelectResponse" cursor items <- sequence $ cursor $// Cu.laxElement "Item" &| readItem let nextToken = listToMaybe $ cursor $// elContent "NextToken" return $ SelectResponse items nextToken instance Transaction Select SelectResponse instance AsMemoryResponse SelectResponse where type MemoryResponse SelectResponse = SelectResponse loadToMemory = return instance ListResponse SelectResponse (Item [Attribute T.Text]) where listResponse = srItems instance IteratedTransaction Select SelectResponse where nextIteratedRequest req SelectResponse{srNextToken=nt} = req{sNextToken=nt} <$ nt ( SelectResponse s1 _ ) ( SelectResponse s2 nt2 ) = SelectResponse ( s1 + + s2 ) nt2
null
https://raw.githubusercontent.com/aristidb/aws/a99113ed7768f9758346052c0d8939b66c6efa87/Aws/SimpleDb/Commands/Select.hs
haskell
| ServiceConfiguration: 'SdbConfiguration'
module Aws.SimpleDb.Commands.Select where import Aws.Core import Aws.SimpleDb.Core import Control.Applicative import Control.Monad import Data.Maybe import Prelude import Text.XML.Cursor (($//), (&|)) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Text.XML.Cursor as Cu data Select = Select { sSelectExpression :: T.Text , sConsistentRead :: Bool , sNextToken :: Maybe T.Text } deriving (Show) data SelectResponse = SelectResponse { srItems :: [Item [Attribute T.Text]] , srNextToken :: Maybe T.Text } deriving (Show) select :: T.Text -> Select select expr = Select { sSelectExpression = expr, sConsistentRead = False, sNextToken = Nothing } instance SignQuery Select where type ServiceConfiguration Select = SdbConfiguration signQuery Select{..} = sdbSignQuery . catMaybes $ [ Just ("Action", "Select") , Just ("SelectExpression", T.encodeUtf8 sSelectExpression) , ("ConsistentRead", awsTrue) <$ guard sConsistentRead , (("NextToken",) . T.encodeUtf8) <$> sNextToken ] instance ResponseConsumer r SelectResponse where type ResponseMetadata SelectResponse = SdbMetadata responseConsumer _ _ = sdbResponseConsumer parse where parse cursor = do sdbCheckResponseType () "SelectResponse" cursor items <- sequence $ cursor $// Cu.laxElement "Item" &| readItem let nextToken = listToMaybe $ cursor $// elContent "NextToken" return $ SelectResponse items nextToken instance Transaction Select SelectResponse instance AsMemoryResponse SelectResponse where type MemoryResponse SelectResponse = SelectResponse loadToMemory = return instance ListResponse SelectResponse (Item [Attribute T.Text]) where listResponse = srItems instance IteratedTransaction Select SelectResponse where nextIteratedRequest req SelectResponse{srNextToken=nt} = req{sNextToken=nt} <$ nt ( SelectResponse s1 _ ) ( SelectResponse s2 nt2 ) = SelectResponse ( s1 + + s2 ) nt2
360d8bcc36ccb8f2c32f3cfcf81d320c01a6de796e7bbcc80ec199459480e145
NovoLabs/gregor
consumer.clj
(ns gregor.details.consumer (:require [gregor.details.protocols.consumer :refer [ConsumerProtocol] :as consumer] [gregor.details.transform :as xform] [gregor.details.deserializer :refer [->deserializer]]) (:import org.apache.kafka.clients.consumer.KafkaConsumer java.util.concurrent.TimeUnit org.apache.kafka.common.errors.WakeupException java.util.Collection java.util.regex.Pattern)) (defn reify-consumer-protocol "Create a reified implementation of a consumer, which includes ConsumerProtocol and SharedProtocol functions" [^KafkaConsumer consumer] (reify ConsumerProtocol (close! [_ timeout] (if-not (int? timeout) (.close consumer) (.close consumer (long timeout) TimeUnit/MILLISECONDS))) ;; Hopefully we can remove this try ... catch in the future. There is currently a synchronization bug that arises if the user spams control events that for functions that can throw WakeupException . Since the WakeupException is used to exit ` poll ! ` to handle control events (partitions-for [_ topic] (mapv xform/partition-info->data (.partitionsFor consumer topic))) (poll! [_ timeout] (xform/consumer-records->data (.poll consumer timeout))) (subscribe! [_ topics] (let [t (xform/data->topics topics)] (if (vector? t) (.subscribe ^KafkaConsumer consumer ^Collection t) (.subscribe ^KafkaConsumer consumer ^Pattern t)))) (unsubscribe! [_] (.unsubscribe consumer)) (subscription [_] (.subscription consumer)) (commit! [_] #(.commitSync consumer)) (wakeup! [_] (.wakeup consumer)))) (defn make-consumer "Create a consumer from a configuration" [{:keys [key-deserializer value-deserializer kafka-configuration topics] :or {key-deserializer :edn value-deserializer :edn}}] (let [driver (reify-consumer-protocol (KafkaConsumer. (xform/opts->props kafka-configuration) (->deserializer key-deserializer) (->deserializer value-deserializer)))] (consumer/subscribe! driver topics) driver))
null
https://raw.githubusercontent.com/NovoLabs/gregor/017488d88abe23df1f0389080629d6f26ba2a84e/src/gregor/details/consumer.clj
clojure
Hopefully we can remove this try ... catch in the future. There is currently a synchronization bug
(ns gregor.details.consumer (:require [gregor.details.protocols.consumer :refer [ConsumerProtocol] :as consumer] [gregor.details.transform :as xform] [gregor.details.deserializer :refer [->deserializer]]) (:import org.apache.kafka.clients.consumer.KafkaConsumer java.util.concurrent.TimeUnit org.apache.kafka.common.errors.WakeupException java.util.Collection java.util.regex.Pattern)) (defn reify-consumer-protocol "Create a reified implementation of a consumer, which includes ConsumerProtocol and SharedProtocol functions" [^KafkaConsumer consumer] (reify ConsumerProtocol (close! [_ timeout] (if-not (int? timeout) (.close consumer) (.close consumer (long timeout) TimeUnit/MILLISECONDS))) that arises if the user spams control events that for functions that can throw WakeupException . Since the WakeupException is used to exit ` poll ! ` to handle control events (partitions-for [_ topic] (mapv xform/partition-info->data (.partitionsFor consumer topic))) (poll! [_ timeout] (xform/consumer-records->data (.poll consumer timeout))) (subscribe! [_ topics] (let [t (xform/data->topics topics)] (if (vector? t) (.subscribe ^KafkaConsumer consumer ^Collection t) (.subscribe ^KafkaConsumer consumer ^Pattern t)))) (unsubscribe! [_] (.unsubscribe consumer)) (subscription [_] (.subscription consumer)) (commit! [_] #(.commitSync consumer)) (wakeup! [_] (.wakeup consumer)))) (defn make-consumer "Create a consumer from a configuration" [{:keys [key-deserializer value-deserializer kafka-configuration topics] :or {key-deserializer :edn value-deserializer :edn}}] (let [driver (reify-consumer-protocol (KafkaConsumer. (xform/opts->props kafka-configuration) (->deserializer key-deserializer) (->deserializer value-deserializer)))] (consumer/subscribe! driver topics) driver))
3c79e5aa431bbe8521da22142f1655ea34646b40c2d27727a79e0f540c111566
thomescai/erlang-ftpserver
config.erl
%% config-module. %% functions related to the server-configuration. %% for now, this is also the place to change the config-settings. -module(config). -include("bifrost.hrl"). -export([get_opt/2,get_opt/3]). get_opt(Key, Opts, Default) -> case proplists:get_value(Key, Opts) of undefined -> case application:get_env(ftpserver,Key) of {ok, Value} -> Value; undefined -> Default end; Value -> Value end. get_opt(Key, Opts) -> case proplists:get_value(Key, Opts) of undefined -> case application:get_env(ftpserver,Key) of {ok, Value} -> Value; undefined -> undefined end; Value -> Value end.
null
https://raw.githubusercontent.com/thomescai/erlang-ftpserver/061a8a3c2b13533542302bc9e19d29eba21d0998/src/config.erl
erlang
config-module. functions related to the server-configuration. for now, this is also the place to change the config-settings.
-module(config). -include("bifrost.hrl"). -export([get_opt/2,get_opt/3]). get_opt(Key, Opts, Default) -> case proplists:get_value(Key, Opts) of undefined -> case application:get_env(ftpserver,Key) of {ok, Value} -> Value; undefined -> Default end; Value -> Value end. get_opt(Key, Opts) -> case proplists:get_value(Key, Opts) of undefined -> case application:get_env(ftpserver,Key) of {ok, Value} -> Value; undefined -> undefined end; Value -> Value end.
a72ac903f19c56ad143d04bf1fb42ee0c0543485968a5d8ee3f4ab47d29895ae
Helium4Haskell/helium
BgExplicitTypedBinding.hs
module BgExplicitTypedBinding where f :: Bool f 1 = 1
null
https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeerrors/Examples/BgExplicitTypedBinding.hs
haskell
module BgExplicitTypedBinding where f :: Bool f 1 = 1
55f074681b51d7b325a5e34309ce35db481981ead4bf090be31a14464f864674
lambdacube3d/lambdacube-workshop
Asteroids06.hs
# LANGUAGE LambdaCase , OverloadedStrings , RecordWildCards # import Control.Monad import System.IO import System.Directory import Data.Vect import Codec.Picture as Juicy import Graphics.UI.GLFW as GLFW import LambdaCube.Compiler as LambdaCube -- compiler import LambdaCube.GL as LambdaCubeGL -- renderer import qualified LambdaCube.OBJ as OBJ import Logic -- for mesh construction import LambdaCube.GL.Mesh as LambdaCubeGL import qualified Data.Map as Map import qualified Data.Vector as V asteroidsModificationTime = getModificationTime "Asteroids.lc" main :: IO () main = do hSetBuffering stdout NoBuffering win <- initWindow "LambdaCube Asteroids" 640 640 -- setup render data let inputSchema = makeSchema $ do defObjectArray "objects" Triangles $ do "position" @: Attribute_V4F "normal" @: Attribute_V3F "uvw" @: Attribute_V3F defObjectArray "debugObjects" Triangles $ do "position" @: Attribute_V3F defObjectArray "quad" Triangles $ do "position" @: Attribute_V2F "uv" @: Attribute_V2F defUniforms $ do "time" @: Float "diffuseTexture" @: FTexture2D "diffuseColor" @: V4F "position" @: V3F "angle" @: Float "radius" @: Float storage <- LambdaCubeGL.allocStorage inputSchema -- load OBJ geometry and material descriptions let loadObj fname = OBJ.loadOBJToGPU fname >>= \case Left err -> fail err Right a -> return a (asteroidMesh,asteroidMtl) <- loadObj "data/asteroid.obj" (spaceshipMesh,spaceshipMtl) <- loadObj "data/spaceship.obj" (bulletMesh,bulletMtl) <- loadObj "data/missile.obj" let objRadius obj = maximum [boundingSphereRadius $ meshData mesh | (mesh, _) <- obj] spaceshipRadius = objRadius spaceshipMesh asteroidRadius = objRadius asteroidMesh bulletRadius = objRadius bulletMesh putStrLn $ "spaceship radius: " ++ show spaceshipRadius putStrLn $ "asteroid radius: " ++ show asteroidRadius putStrLn $ "bullet radius: " ++ show bulletRadius -- load materials textures gpuMtlLib <- OBJ.uploadMtlLib $ mconcat [spaceshipMtl, asteroidMtl, bulletMtl] spaceshipObj <- OBJ.addOBJToObjectArray storage "objects" ["position", "angle", "radius"] spaceshipMesh gpuMtlLib asteroidPool <- replicateM 1000 $ OBJ.addOBJToObjectArray storage "objects" ["position", "angle", "radius"] asteroidMesh gpuMtlLib bulletPool <- replicateM 1000 $ OBJ.addOBJToObjectArray storage "objects" ["position", "angle", "radius"] bulletMesh gpuMtlLib -- debug sphere sphereMesh <- LambdaCubeGL.uploadMeshToGPU $ sphere 1 8 spherePool <- replicateM 1000 $ do sphereObj <- LambdaCubeGL.addMeshToObjectArray storage "debugObjects" ["diffuseColor", "position", "radius", "angle"] sphereMesh return [sphereObj] -- background quadMesh <- LambdaCubeGL.uploadMeshToGPU quad backgroundObj <- LambdaCubeGL.addMeshToObjectArray storage "quad" ["diffuseTexture"] quadMesh -- load image and upload texture Right img <- Juicy.readImage "data/background.jpg" textureData <- LambdaCubeGL.uploadTexture2DToGPU img LambdaCubeGL.updateObjectUniforms backgroundObj $ do "diffuseTexture" @= return textureData allocate GL pipeline let loadRenderer = do LambdaCube.compileMain ["."] OpenGL33 "Asteroids.lc" >>= \case Left err -> do putStrLn $ "compile error:\n" ++ ppShow err return Nothing Right pipelineDesc -> do renderer <- LambdaCubeGL.allocRenderer pipelineDesc LambdaCubeGL.setStorage renderer storage >>= \case -- check schema compatibility Just err -> do putStrLn $ "setStorage error: " ++ err LambdaCubeGL.disposeRenderer renderer return Nothing Nothing -> do putStrLn $ "setStorage ok" return $ Just renderer disableObjects :: [LambdaCubeGL.Object] -> IO () disableObjects objs = mapM_ (\obj -> LambdaCubeGL.enableObject obj False) objs addToScene :: Vec2 -> Float -> Float -> V4 Float -> [[LambdaCubeGL.Object]] -> IO [[LambdaCubeGL.Object]] addToScene position angle radius color (objs:pool) = do forM_ objs $ \obj -> do LambdaCubeGL.enableObject obj True LambdaCubeGL.updateObjectUniforms obj $ do "angle" @= return angle "radius" @= return radius "diffuseColor" @= return color "position" @= let Vec2 x y = position in do return (V3 x y 0) return pool white = V4 1 1 1 1 :: V4 Float floatTime :: IO Float floatTime = do Just t <- GLFW.getTime return $ realToFrac t loop renderer world@World{..} t0 lcTime0 = do -- update graphics input GLFW.getWindowSize win >>= \(w,h) -> LambdaCubeGL.setScreenSize storage (fromIntegral w) (fromIntegral h) t <- floatTime LambdaCubeGL.updateUniforms storage $ do "time" @= return t -- collision visuals spherePool1 <- case spaceship of Just spaceship -> addToScene (sPosition spaceship) (sAngle spaceship) (sRadius spaceship) (V4 1 0 0 1) spherePool _ -> return spherePool spherePool2 <- foldM (\pool asteroid -> addToScene (aPosition asteroid) 0 (aRadius asteroid) (V4 0 1 0 1) pool) spherePool1 asteroids spherePool3 <- foldM (\pool bullet -> addToScene (bPosition bullet) 0 (bRadius bullet) (V4 0 1 1 1) pool) spherePool2 bullets disableObjects $ concat spherePool3 -- spaceship case spaceship of Nothing -> disableObjects spaceshipObj Just spaceship -> void $ addToScene (sPosition spaceship) (sAngle spaceship) (sRadius spaceship / spaceshipRadius) white [spaceshipObj] -- asteroids asteroidPool1 <- foldM (\pool asteroid -> addToScene (aPosition asteroid) 0 (aRadius asteroid / asteroidRadius) white pool) asteroidPool asteroids disableObjects $ concat asteroidPool1 -- bullets bulletPool1 <- foldM (\pool Bullet{..} -> addToScene bPosition bAngle (bRadius / bulletRadius) white pool) bulletPool bullets disableObjects $ concat bulletPool1 -- render LambdaCubeGL.renderFrame renderer GLFW.swapBuffers win GLFW.pollEvents let keyIsPressed k = fmap (==KeyState'Pressed) $ GLFW.getKey win k userInput <- UserInput <$> keyIsPressed Key'Left <*> keyIsPressed Key'Right <*> keyIsPressed Key'Up <*> keyIsPressed Key'Down <*> keyIsPressed Key'Space <*> keyIsPressed Key'Enter let deltaTime = t - t0 Hint : IO is instance of MonadRandom lcTime <- asteroidsModificationTime let reload = lcTime /= lcTime0 renderer' <- if not reload then return renderer else do loadRenderer >>= \case Nothing -> return renderer Just newRenderer -> do putStrLn "Reload renderer" LambdaCubeGL.disposeRenderer renderer return newRenderer t <- if reload then floatTime else return t escape <- keyIsPressed Key'Escape if escape then return () else loop renderer' world' t lcTime Just renderer <- loadRenderer t0 <- floatTime lcTime <- asteroidsModificationTime loop renderer world0 t0 lcTime LambdaCubeGL.disposeRenderer renderer LambdaCubeGL.disposeStorage storage GLFW.destroyWindow win GLFW.terminate initWindow :: String -> Int -> Int -> IO Window initWindow title width height = do GLFW.init GLFW.defaultWindowHints mapM_ GLFW.windowHint [ WindowHint'ContextVersionMajor 3 , WindowHint'ContextVersionMinor 3 , WindowHint'OpenGLProfile OpenGLProfile'Core , WindowHint'OpenGLForwardCompat True ] Just win <- GLFW.createWindow width height title Nothing Nothing GLFW.makeContextCurrent $ Just win return win -- utils sphere :: Float -> Int -> LambdaCubeGL.Mesh sphere radius n = Mesh { mAttributes = Map.fromList [("position", A_V3F vertices), ("normal", A_V3F normals)] , mPrimitive = P_TrianglesI indices } where m = pi / fromIntegral n vertices = V.map (\(V3 x y z) -> V3 (radius * x) (radius * y) (radius * z)) normals normals = V.fromList [V3 (sin a * cos b) (cos a) (sin a * sin b) | i <- [0..n], j <- [0..2 * n - 1], let a = fromIntegral i * m, let b = fromIntegral j * m] indices = V.fromList $ concat [[ix i j, ix i' j, ix i' j', ix i' j', ix i j', ix i j] | i <- [0..n - 1], j <- [0..2 * n - 1], let i' = i + 1, let j' = (j + 1) `mod` (2 * n)] ix i j = fromIntegral (i * 2 * n + j) v4ToVec3 :: V4 Float -> Vec3 v4ToVec3 (V4 x y z _) = Vec3 x y z boundingSphereRadius :: LambdaCubeGL.Mesh -> Float boundingSphereRadius Mesh{..} = case Map.lookup "position" mAttributes of Just (A_V4F vertices) -> maximum $ fmap (len . v4ToVec3) vertices _ -> 0 quad :: LambdaCubeGL.Mesh quad = Mesh { mAttributes = Map.fromList [ ("position", A_V2F $ V.fromList [V2 1 1, V2 1 (-1), V2 (-1) (-1) ,V2 1 1, V2 (-1) (-1), V2 (-1) 1]) , ("uv", A_V2F $ V.fromList [V2 1 1, V2 1 0, V2 0 0 ,V2 1 1, V2 0 0, V2 0 1]) ] , mPrimitive = P_Triangles }
null
https://raw.githubusercontent.com/lambdacube3d/lambdacube-workshop/3d40c91811d0aaf9fa57c3b8eb4a3f1bde0e3173/asteroids/stages/Asteroids06.hs
haskell
compiler renderer for mesh construction setup render data load OBJ geometry and material descriptions load materials textures debug sphere background load image and upload texture check schema compatibility update graphics input collision visuals spaceship asteroids bullets render utils
# LANGUAGE LambdaCase , OverloadedStrings , RecordWildCards # import Control.Monad import System.IO import System.Directory import Data.Vect import Codec.Picture as Juicy import Graphics.UI.GLFW as GLFW import qualified LambdaCube.OBJ as OBJ import Logic import LambdaCube.GL.Mesh as LambdaCubeGL import qualified Data.Map as Map import qualified Data.Vector as V asteroidsModificationTime = getModificationTime "Asteroids.lc" main :: IO () main = do hSetBuffering stdout NoBuffering win <- initWindow "LambdaCube Asteroids" 640 640 let inputSchema = makeSchema $ do defObjectArray "objects" Triangles $ do "position" @: Attribute_V4F "normal" @: Attribute_V3F "uvw" @: Attribute_V3F defObjectArray "debugObjects" Triangles $ do "position" @: Attribute_V3F defObjectArray "quad" Triangles $ do "position" @: Attribute_V2F "uv" @: Attribute_V2F defUniforms $ do "time" @: Float "diffuseTexture" @: FTexture2D "diffuseColor" @: V4F "position" @: V3F "angle" @: Float "radius" @: Float storage <- LambdaCubeGL.allocStorage inputSchema let loadObj fname = OBJ.loadOBJToGPU fname >>= \case Left err -> fail err Right a -> return a (asteroidMesh,asteroidMtl) <- loadObj "data/asteroid.obj" (spaceshipMesh,spaceshipMtl) <- loadObj "data/spaceship.obj" (bulletMesh,bulletMtl) <- loadObj "data/missile.obj" let objRadius obj = maximum [boundingSphereRadius $ meshData mesh | (mesh, _) <- obj] spaceshipRadius = objRadius spaceshipMesh asteroidRadius = objRadius asteroidMesh bulletRadius = objRadius bulletMesh putStrLn $ "spaceship radius: " ++ show spaceshipRadius putStrLn $ "asteroid radius: " ++ show asteroidRadius putStrLn $ "bullet radius: " ++ show bulletRadius gpuMtlLib <- OBJ.uploadMtlLib $ mconcat [spaceshipMtl, asteroidMtl, bulletMtl] spaceshipObj <- OBJ.addOBJToObjectArray storage "objects" ["position", "angle", "radius"] spaceshipMesh gpuMtlLib asteroidPool <- replicateM 1000 $ OBJ.addOBJToObjectArray storage "objects" ["position", "angle", "radius"] asteroidMesh gpuMtlLib bulletPool <- replicateM 1000 $ OBJ.addOBJToObjectArray storage "objects" ["position", "angle", "radius"] bulletMesh gpuMtlLib sphereMesh <- LambdaCubeGL.uploadMeshToGPU $ sphere 1 8 spherePool <- replicateM 1000 $ do sphereObj <- LambdaCubeGL.addMeshToObjectArray storage "debugObjects" ["diffuseColor", "position", "radius", "angle"] sphereMesh return [sphereObj] quadMesh <- LambdaCubeGL.uploadMeshToGPU quad backgroundObj <- LambdaCubeGL.addMeshToObjectArray storage "quad" ["diffuseTexture"] quadMesh Right img <- Juicy.readImage "data/background.jpg" textureData <- LambdaCubeGL.uploadTexture2DToGPU img LambdaCubeGL.updateObjectUniforms backgroundObj $ do "diffuseTexture" @= return textureData allocate GL pipeline let loadRenderer = do LambdaCube.compileMain ["."] OpenGL33 "Asteroids.lc" >>= \case Left err -> do putStrLn $ "compile error:\n" ++ ppShow err return Nothing Right pipelineDesc -> do renderer <- LambdaCubeGL.allocRenderer pipelineDesc Just err -> do putStrLn $ "setStorage error: " ++ err LambdaCubeGL.disposeRenderer renderer return Nothing Nothing -> do putStrLn $ "setStorage ok" return $ Just renderer disableObjects :: [LambdaCubeGL.Object] -> IO () disableObjects objs = mapM_ (\obj -> LambdaCubeGL.enableObject obj False) objs addToScene :: Vec2 -> Float -> Float -> V4 Float -> [[LambdaCubeGL.Object]] -> IO [[LambdaCubeGL.Object]] addToScene position angle radius color (objs:pool) = do forM_ objs $ \obj -> do LambdaCubeGL.enableObject obj True LambdaCubeGL.updateObjectUniforms obj $ do "angle" @= return angle "radius" @= return radius "diffuseColor" @= return color "position" @= let Vec2 x y = position in do return (V3 x y 0) return pool white = V4 1 1 1 1 :: V4 Float floatTime :: IO Float floatTime = do Just t <- GLFW.getTime return $ realToFrac t loop renderer world@World{..} t0 lcTime0 = do GLFW.getWindowSize win >>= \(w,h) -> LambdaCubeGL.setScreenSize storage (fromIntegral w) (fromIntegral h) t <- floatTime LambdaCubeGL.updateUniforms storage $ do "time" @= return t spherePool1 <- case spaceship of Just spaceship -> addToScene (sPosition spaceship) (sAngle spaceship) (sRadius spaceship) (V4 1 0 0 1) spherePool _ -> return spherePool spherePool2 <- foldM (\pool asteroid -> addToScene (aPosition asteroid) 0 (aRadius asteroid) (V4 0 1 0 1) pool) spherePool1 asteroids spherePool3 <- foldM (\pool bullet -> addToScene (bPosition bullet) 0 (bRadius bullet) (V4 0 1 1 1) pool) spherePool2 bullets disableObjects $ concat spherePool3 case spaceship of Nothing -> disableObjects spaceshipObj Just spaceship -> void $ addToScene (sPosition spaceship) (sAngle spaceship) (sRadius spaceship / spaceshipRadius) white [spaceshipObj] asteroidPool1 <- foldM (\pool asteroid -> addToScene (aPosition asteroid) 0 (aRadius asteroid / asteroidRadius) white pool) asteroidPool asteroids disableObjects $ concat asteroidPool1 bulletPool1 <- foldM (\pool Bullet{..} -> addToScene bPosition bAngle (bRadius / bulletRadius) white pool) bulletPool bullets disableObjects $ concat bulletPool1 LambdaCubeGL.renderFrame renderer GLFW.swapBuffers win GLFW.pollEvents let keyIsPressed k = fmap (==KeyState'Pressed) $ GLFW.getKey win k userInput <- UserInput <$> keyIsPressed Key'Left <*> keyIsPressed Key'Right <*> keyIsPressed Key'Up <*> keyIsPressed Key'Down <*> keyIsPressed Key'Space <*> keyIsPressed Key'Enter let deltaTime = t - t0 Hint : IO is instance of MonadRandom lcTime <- asteroidsModificationTime let reload = lcTime /= lcTime0 renderer' <- if not reload then return renderer else do loadRenderer >>= \case Nothing -> return renderer Just newRenderer -> do putStrLn "Reload renderer" LambdaCubeGL.disposeRenderer renderer return newRenderer t <- if reload then floatTime else return t escape <- keyIsPressed Key'Escape if escape then return () else loop renderer' world' t lcTime Just renderer <- loadRenderer t0 <- floatTime lcTime <- asteroidsModificationTime loop renderer world0 t0 lcTime LambdaCubeGL.disposeRenderer renderer LambdaCubeGL.disposeStorage storage GLFW.destroyWindow win GLFW.terminate initWindow :: String -> Int -> Int -> IO Window initWindow title width height = do GLFW.init GLFW.defaultWindowHints mapM_ GLFW.windowHint [ WindowHint'ContextVersionMajor 3 , WindowHint'ContextVersionMinor 3 , WindowHint'OpenGLProfile OpenGLProfile'Core , WindowHint'OpenGLForwardCompat True ] Just win <- GLFW.createWindow width height title Nothing Nothing GLFW.makeContextCurrent $ Just win return win sphere :: Float -> Int -> LambdaCubeGL.Mesh sphere radius n = Mesh { mAttributes = Map.fromList [("position", A_V3F vertices), ("normal", A_V3F normals)] , mPrimitive = P_TrianglesI indices } where m = pi / fromIntegral n vertices = V.map (\(V3 x y z) -> V3 (radius * x) (radius * y) (radius * z)) normals normals = V.fromList [V3 (sin a * cos b) (cos a) (sin a * sin b) | i <- [0..n], j <- [0..2 * n - 1], let a = fromIntegral i * m, let b = fromIntegral j * m] indices = V.fromList $ concat [[ix i j, ix i' j, ix i' j', ix i' j', ix i j', ix i j] | i <- [0..n - 1], j <- [0..2 * n - 1], let i' = i + 1, let j' = (j + 1) `mod` (2 * n)] ix i j = fromIntegral (i * 2 * n + j) v4ToVec3 :: V4 Float -> Vec3 v4ToVec3 (V4 x y z _) = Vec3 x y z boundingSphereRadius :: LambdaCubeGL.Mesh -> Float boundingSphereRadius Mesh{..} = case Map.lookup "position" mAttributes of Just (A_V4F vertices) -> maximum $ fmap (len . v4ToVec3) vertices _ -> 0 quad :: LambdaCubeGL.Mesh quad = Mesh { mAttributes = Map.fromList [ ("position", A_V2F $ V.fromList [V2 1 1, V2 1 (-1), V2 (-1) (-1) ,V2 1 1, V2 (-1) (-1), V2 (-1) 1]) , ("uv", A_V2F $ V.fromList [V2 1 1, V2 1 0, V2 0 0 ,V2 1 1, V2 0 0, V2 0 1]) ] , mPrimitive = P_Triangles }
1786ae7ed6d8ec2893743eb71b8e9eb9e1c83a4de3009025edde427ab59155a4
xvw/preface
equivalence.ml
module Invariant_suite = Preface.Qcheck.Invariant.Suite_contravariant (Req.Equivalence) (Preface.Equivalence.Invariant) (Sample.Int) (Sample.String) (Sample.Float) module Contravariant_suite = Preface.Qcheck.Contravariant.Suite (Req.Equivalence) (Preface.Equivalence.Contravariant) (Sample.Int) (Sample.String) (Sample.Float) module Divisible_suite = Preface.Qcheck.Divisible.Suite (Req.Equivalence) (Preface.Equivalence.Divisible) (Sample.Int) (Sample.String) (Sample.Float) module Decidable_suite = Preface.Qcheck.Decidable.Suite (Req.Equivalence) (Preface.Equivalence.Decidable) (Sample.Int) (Sample.String) (Sample.Float) let cases ~count = Util.with_alcotest ~count [ ("Equivalence Invariant", Invariant_suite.tests) ; ("Equivalence Contravariant", Contravariant_suite.tests) ; ("Equivalence Divisible", Divisible_suite.tests) ; ("Equivalence Decidable", Decidable_suite.tests) ] ;;
null
https://raw.githubusercontent.com/xvw/preface/84a297e1ee2967ad4341dca875da8d2dc6d7638c/test/preface_laws_test/equivalence.ml
ocaml
module Invariant_suite = Preface.Qcheck.Invariant.Suite_contravariant (Req.Equivalence) (Preface.Equivalence.Invariant) (Sample.Int) (Sample.String) (Sample.Float) module Contravariant_suite = Preface.Qcheck.Contravariant.Suite (Req.Equivalence) (Preface.Equivalence.Contravariant) (Sample.Int) (Sample.String) (Sample.Float) module Divisible_suite = Preface.Qcheck.Divisible.Suite (Req.Equivalence) (Preface.Equivalence.Divisible) (Sample.Int) (Sample.String) (Sample.Float) module Decidable_suite = Preface.Qcheck.Decidable.Suite (Req.Equivalence) (Preface.Equivalence.Decidable) (Sample.Int) (Sample.String) (Sample.Float) let cases ~count = Util.with_alcotest ~count [ ("Equivalence Invariant", Invariant_suite.tests) ; ("Equivalence Contravariant", Contravariant_suite.tests) ; ("Equivalence Divisible", Divisible_suite.tests) ; ("Equivalence Decidable", Decidable_suite.tests) ] ;;
61dee5bae4b4d3d2dac683b400de011fdb53d5ea231fda68805cf10c1aaa5b19
kronkltd/jiksnu
logger.clj
(ns jiksnu.logger (:require [ciste.config :refer [config config* describe-config]] [clojure.data.json :as json] [clojure.string :as string] [jiksnu.sentry :as sentry] jiksnu.serializers [puget.printer :as puget] [taoensso.timbre :as timbre] [taoensso.timbre.appenders.core :refer [println-appender spit-appender]])) (describe-config [:jiksnu :logger :appenders] :string "Comma-separated list of logging appenders to be enabled" :default (string/join "," ["jiksnu.logger/json-appender" "jiksnu.logger/stdout-appender" "jiksnu.sentry/raven-appender"])) (describe-config [:jiksnu :logger :blacklist] :string "Comma-separated list of namespaces to blacklist" :default "") (defn get-appenders [] (->> (string/split (config :jiksnu :logger :appenders) #",") (map (fn [f] (let [[ns-part var-part] (string/split f #"/") ns-ref (the-ns (symbol ns-part)) fn-ref (symbol var-part)] [f (var-get (ns-resolve ns-ref fn-ref))]))) (into {}))) (defn json-formatter ([data] (json-formatter nil data)) ([opts data] (let [{:keys [instant level ?err_ varargs_ output-fn config appender]} data out-data {:level level :file (:?file data) :instant instant :message (force (:msg_ data)) :varargs (:varargs_ data) ;; :err (force ?err_) ;; :keys (keys data) :line (:?line data) :ns (:?ns-str data) :context (:context data) :hostname (force (:hostname_ data))}] (->> out-data (map (fn [[k v]] (when v [k v]))) (into {}) json/write-str)))) (def json-appender (assoc (spit-appender {:fname "logs/timbre-spit.log"}) :output-fn json-formatter)) (def json-stdout-appender (assoc (println-appender {:stream :auto}) :output-fn json-formatter)) (def pretty-stdout-appender (assoc (println-appender {:stream :auto}) :output-fn (comp puget/cprint-str #(dissoc % :config)))) (def stdout-appender (println-appender {:stream :auto})) (defn set-logger [] (let [appenders (get-appenders) ns-blacklist (string/split (config :jiksnu :logger :blacklist) #",") opts {:level :debug :ns-whitelist [] :ns-blacklist ns-blacklist :middleware [] :timestamp-opts timbre/default-timestamp-opts :appenders appenders}] (timbre/set-config! opts)))
null
https://raw.githubusercontent.com/kronkltd/jiksnu/8c91e9b1fddcc0224b028e573f7c3ca2f227e516/src/jiksnu/logger.clj
clojure
:err (force ?err_) :keys (keys data)
(ns jiksnu.logger (:require [ciste.config :refer [config config* describe-config]] [clojure.data.json :as json] [clojure.string :as string] [jiksnu.sentry :as sentry] jiksnu.serializers [puget.printer :as puget] [taoensso.timbre :as timbre] [taoensso.timbre.appenders.core :refer [println-appender spit-appender]])) (describe-config [:jiksnu :logger :appenders] :string "Comma-separated list of logging appenders to be enabled" :default (string/join "," ["jiksnu.logger/json-appender" "jiksnu.logger/stdout-appender" "jiksnu.sentry/raven-appender"])) (describe-config [:jiksnu :logger :blacklist] :string "Comma-separated list of namespaces to blacklist" :default "") (defn get-appenders [] (->> (string/split (config :jiksnu :logger :appenders) #",") (map (fn [f] (let [[ns-part var-part] (string/split f #"/") ns-ref (the-ns (symbol ns-part)) fn-ref (symbol var-part)] [f (var-get (ns-resolve ns-ref fn-ref))]))) (into {}))) (defn json-formatter ([data] (json-formatter nil data)) ([opts data] (let [{:keys [instant level ?err_ varargs_ output-fn config appender]} data out-data {:level level :file (:?file data) :instant instant :message (force (:msg_ data)) :varargs (:varargs_ data) :line (:?line data) :ns (:?ns-str data) :context (:context data) :hostname (force (:hostname_ data))}] (->> out-data (map (fn [[k v]] (when v [k v]))) (into {}) json/write-str)))) (def json-appender (assoc (spit-appender {:fname "logs/timbre-spit.log"}) :output-fn json-formatter)) (def json-stdout-appender (assoc (println-appender {:stream :auto}) :output-fn json-formatter)) (def pretty-stdout-appender (assoc (println-appender {:stream :auto}) :output-fn (comp puget/cprint-str #(dissoc % :config)))) (def stdout-appender (println-appender {:stream :auto})) (defn set-logger [] (let [appenders (get-appenders) ns-blacklist (string/split (config :jiksnu :logger :blacklist) #",") opts {:level :debug :ns-whitelist [] :ns-blacklist ns-blacklist :middleware [] :timestamp-opts timbre/default-timestamp-opts :appenders appenders}] (timbre/set-config! opts)))
fc8c76e8bf8af0a7ea743bef9806e8e4b69d06e7c0031df9eb55fe33b32087cc
mlabs-haskell/plutip
ClusterStartup.hs
module Spec.ClusterStartup (test) where import Cardano.Api (UTxO (unUTxO)) import Cardano.Api qualified as Capi import Control.Arrow (right) import Control.Monad (zipWithM) import Data.Default (Default (def)) import Data.Map qualified as Map import Data.Set qualified as Set import Plutip.CardanoApi (currentBlock, utxosAtAddress) import Plutip.Cluster (withCluster, withFundedCluster) import Plutip.Keys (cardanoMainnetAddress) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (assertFailure, testCase) test :: TestTree test = testGroup "Cluster startup" [ test1 , test2 ] test1 :: TestTree test1 = testCase "Cluster starts up" $ do withCluster def $ \cenv -> do res <- currentBlock cenv case res of Left _ -> assertFailure "Failed to query the cluster node for block number." Right _ -> pure () test2 :: TestTree test2 = testCase "Funded cluster starts up funded" $ do withFundedCluster def distr $ \cenv keys -> do res <- zipWithM (\ds1 addr -> right (eqDistr ds1) <$> utxosAtAddress cenv addr) distr (cardanoMainnetAddress <$> keys) case sequence res of Left err -> assertFailure $ "Failed to query the cluster node for utxos: " <> show err Right checks -> if and checks then pure () else assertFailure "Queried utxo distribution is incorrect." where distr :: [[Capi.Lovelace]] distr = [[ada 2], [ada 2, ada 22], [ada 3, ada 33, ada 333]] eqDistr ds1 queried = let ds2 = map (\case Capi.TxOut _ value _ _ -> Capi.txOutValueToLovelace value) $ Map.elems $ unUTxO queried in Set.fromList ds1 == Set.fromList ds2 && length ds1 == length ds2 ada = (*) 1_000_000
null
https://raw.githubusercontent.com/mlabs-haskell/plutip/89cf822c213f6a4278a88c8a8bb982696c649e76/test/Spec/ClusterStartup.hs
haskell
module Spec.ClusterStartup (test) where import Cardano.Api (UTxO (unUTxO)) import Cardano.Api qualified as Capi import Control.Arrow (right) import Control.Monad (zipWithM) import Data.Default (Default (def)) import Data.Map qualified as Map import Data.Set qualified as Set import Plutip.CardanoApi (currentBlock, utxosAtAddress) import Plutip.Cluster (withCluster, withFundedCluster) import Plutip.Keys (cardanoMainnetAddress) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (assertFailure, testCase) test :: TestTree test = testGroup "Cluster startup" [ test1 , test2 ] test1 :: TestTree test1 = testCase "Cluster starts up" $ do withCluster def $ \cenv -> do res <- currentBlock cenv case res of Left _ -> assertFailure "Failed to query the cluster node for block number." Right _ -> pure () test2 :: TestTree test2 = testCase "Funded cluster starts up funded" $ do withFundedCluster def distr $ \cenv keys -> do res <- zipWithM (\ds1 addr -> right (eqDistr ds1) <$> utxosAtAddress cenv addr) distr (cardanoMainnetAddress <$> keys) case sequence res of Left err -> assertFailure $ "Failed to query the cluster node for utxos: " <> show err Right checks -> if and checks then pure () else assertFailure "Queried utxo distribution is incorrect." where distr :: [[Capi.Lovelace]] distr = [[ada 2], [ada 2, ada 22], [ada 3, ada 33, ada 333]] eqDistr ds1 queried = let ds2 = map (\case Capi.TxOut _ value _ _ -> Capi.txOutValueToLovelace value) $ Map.elems $ unUTxO queried in Set.fromList ds1 == Set.fromList ds2 && length ds1 == length ds2 ada = (*) 1_000_000
430799e6e2fa53a8bd9d334a1ac38ecae5c2ea951e75a930d3f6b5f62d5ffaf9
areina/elfeed-cljsrn
events_test.cljs
(ns elfeed-cljsrn.events-test (:require [cljs.test :refer [deftest is testing]] [elfeed-cljsrn.events :as events])) (deftest search-execute-handler-test (testing "when the search term is empty" (let [term "" expected-default-term "@15-days-old +unread" db {:search {:default-term expected-default-term}} expected-search-params {:term "" :default-term expected-default-term :searching? false} expected-db {:search expected-search-params}] (is (= (events/search-execute-handler {:db db} [:search/execute {:term term}]) {:dispatch [:fetch-entries expected-search-params] :db expected-db})))) (testing "when the search term is not empty" (let [term "@95-days-old" expected-default-term "@15-days-old +unread" db {:search {:default-term expected-default-term}} expected-search-params {:term term :default-term expected-default-term :searching? false} expected-db {:search expected-search-params}] (is (= (events/search-execute-handler {:db db} [:search/execute {:term term}]) {:dispatch [:fetch-entries expected-search-params] :db expected-db}))))) (deftest fetch-entries-handler-test (testing "when term in search-params is empty" (let [term "" expected-default-term "@15-days-old +unread" db {} search-params {:term term :default-term expected-default-term :feed-title nil} subject (events/fetch-entries {:db db} [:fetch/entries search-params])] (is (= (:params (:http-xhrio subject)) {:q (js/encodeURIComponent expected-default-term)})) (is (= (:on-success (:http-xhrio subject)) [:success-fetch-entries search-params])) (is (= (:db subject) {:fetching-feeds? true :fetching-entries? true})))) (testing "when there is feed-title in search-params" (let [search-params {:term "@15-days-old +unread" :feed-title "Foo"} term-without-feed-title (:term search-params) db {} subject (events/fetch-entries {:db db} [:fetch/entries search-params])] (is (= (:params (:http-xhrio subject)) {:q (js/encodeURIComponent term-without-feed-title)})) (is (= (:on-success (:http-xhrio subject)) [:success-fetch-entries search-params])) (is (= (:db subject) {:fetching-feeds? true :fetching-entries? true}))))) (deftest success-fetch-entries-handler-test (let [event-id :success-fetch-entries db {} response ""] (testing "when there is feed title" (let [search-params {:term "@15-days-old +unread" :feed-title "Foo"} term-with-feed-title (str (:term search-params) " " (:feed-title search-params)) subject (events/success-fetch-entries {:db db} [event-id search-params response])] (is (= (:params (:http-xhrio subject)) {:q (js/encodeURIComponent term-with-feed-title)})) (is (= (:on-success (:http-xhrio subject)) [:process-entries])) (is (= (:dispatch-n subject) (list [:process-feeds response] [:process-total-entries response]))))) (testing "when there isn't feed title" (let [search-params {} subject (events/success-fetch-entries {:db db} [event-id search-params response])] (is (= subject {:dispatch-n (list [:process-feeds response] [:process-entries response] [:process-total-entries response])}))))))
null
https://raw.githubusercontent.com/areina/elfeed-cljsrn/4dea27f785d24a16da05c0ab2ac0c6a6f23360f1/test/elfeed_cljsrn/events_test.cljs
clojure
(ns elfeed-cljsrn.events-test (:require [cljs.test :refer [deftest is testing]] [elfeed-cljsrn.events :as events])) (deftest search-execute-handler-test (testing "when the search term is empty" (let [term "" expected-default-term "@15-days-old +unread" db {:search {:default-term expected-default-term}} expected-search-params {:term "" :default-term expected-default-term :searching? false} expected-db {:search expected-search-params}] (is (= (events/search-execute-handler {:db db} [:search/execute {:term term}]) {:dispatch [:fetch-entries expected-search-params] :db expected-db})))) (testing "when the search term is not empty" (let [term "@95-days-old" expected-default-term "@15-days-old +unread" db {:search {:default-term expected-default-term}} expected-search-params {:term term :default-term expected-default-term :searching? false} expected-db {:search expected-search-params}] (is (= (events/search-execute-handler {:db db} [:search/execute {:term term}]) {:dispatch [:fetch-entries expected-search-params] :db expected-db}))))) (deftest fetch-entries-handler-test (testing "when term in search-params is empty" (let [term "" expected-default-term "@15-days-old +unread" db {} search-params {:term term :default-term expected-default-term :feed-title nil} subject (events/fetch-entries {:db db} [:fetch/entries search-params])] (is (= (:params (:http-xhrio subject)) {:q (js/encodeURIComponent expected-default-term)})) (is (= (:on-success (:http-xhrio subject)) [:success-fetch-entries search-params])) (is (= (:db subject) {:fetching-feeds? true :fetching-entries? true})))) (testing "when there is feed-title in search-params" (let [search-params {:term "@15-days-old +unread" :feed-title "Foo"} term-without-feed-title (:term search-params) db {} subject (events/fetch-entries {:db db} [:fetch/entries search-params])] (is (= (:params (:http-xhrio subject)) {:q (js/encodeURIComponent term-without-feed-title)})) (is (= (:on-success (:http-xhrio subject)) [:success-fetch-entries search-params])) (is (= (:db subject) {:fetching-feeds? true :fetching-entries? true}))))) (deftest success-fetch-entries-handler-test (let [event-id :success-fetch-entries db {} response ""] (testing "when there is feed title" (let [search-params {:term "@15-days-old +unread" :feed-title "Foo"} term-with-feed-title (str (:term search-params) " " (:feed-title search-params)) subject (events/success-fetch-entries {:db db} [event-id search-params response])] (is (= (:params (:http-xhrio subject)) {:q (js/encodeURIComponent term-with-feed-title)})) (is (= (:on-success (:http-xhrio subject)) [:process-entries])) (is (= (:dispatch-n subject) (list [:process-feeds response] [:process-total-entries response]))))) (testing "when there isn't feed title" (let [search-params {} subject (events/success-fetch-entries {:db db} [event-id search-params response])] (is (= subject {:dispatch-n (list [:process-feeds response] [:process-entries response] [:process-total-entries response])}))))))
f6e7cab916b97dbc50a507504d959d4a0dea7b2784faa1cfc16cc1ab7fe91068
mikewin/cspbox-trading
open_range_breakout.clj
(ns cspbox.trading.ind.open-range-breakout (:require [cspbox.trading.ind.spec :refer [average-true-range]] [cspbox.runtime.store.buf.roll :refer [make-lookback-buffer]] [cspbox.trading.order.market :refer [market-closed-p]] [cspbox.runtime.sys.utils.macro :refer [to-map]] [taoensso.timbre :as log])) (defn opening-range-breakout "" [{:keys [volatility-limit N]}] (let [volatility (average-true-range N nil :percent) counter-fn (make-lookback-buffer 1) 3/2 K2 3] (fn[price timestamp] (let [prev-volatility (:value (volatility)) market-on-close (market-closed-p timestamp) counter (or (counter-fn) 0) counter (if market-on-close 0 (inc counter)) value (:value (volatility price))] (counter-fn counter) (when (and (not market-on-close) (< prev-volatility volatility-limit) (>= value volatility-limit)) (let [R1 (* price (inc (* value K1))) R2 (* price (inc (* value K2))) S1 (/ price (inc (* value K1))) S2 (/ price (inc (* value K2)))] (to-map R1 R2 S1 S2 market-on-close N counter)))))))
null
https://raw.githubusercontent.com/mikewin/cspbox-trading/76f9cfb780d5f36e5fbd6d8cec7c978a0e51cb94/src/cspbox/trading/ind/open_range_breakout.clj
clojure
(ns cspbox.trading.ind.open-range-breakout (:require [cspbox.trading.ind.spec :refer [average-true-range]] [cspbox.runtime.store.buf.roll :refer [make-lookback-buffer]] [cspbox.trading.order.market :refer [market-closed-p]] [cspbox.runtime.sys.utils.macro :refer [to-map]] [taoensso.timbre :as log])) (defn opening-range-breakout "" [{:keys [volatility-limit N]}] (let [volatility (average-true-range N nil :percent) counter-fn (make-lookback-buffer 1) 3/2 K2 3] (fn[price timestamp] (let [prev-volatility (:value (volatility)) market-on-close (market-closed-p timestamp) counter (or (counter-fn) 0) counter (if market-on-close 0 (inc counter)) value (:value (volatility price))] (counter-fn counter) (when (and (not market-on-close) (< prev-volatility volatility-limit) (>= value volatility-limit)) (let [R1 (* price (inc (* value K1))) R2 (* price (inc (* value K2))) S1 (/ price (inc (* value K1))) S2 (/ price (inc (* value K2)))] (to-map R1 R2 S1 S2 market-on-close N counter)))))))
c90c17a271d7425fcbd6a64fed02d393083db36fa281f697a650bb7c7551ace6
namin/staged-miniKanren
tests-append.scm
(load "staged-load.scm") (display "in mk") (newline) (define (appendo xs ys zs) (conde ((== xs '()) (== ys zs)) ((fresh (xa xd zd) (== xs (cons xa xd)) (== zs (cons xa zd)) (appendo xd ys zd))))) (time (length (run* (x y) (appendo x y (make-list 500 'a))))) (display "unstaged") (newline) (time (length (run* (x y) (evalo-unstaged `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (append ',x ',y)) (make-list 500 'a))))) (display "unstaged env-passing") (newline) (time (length (run* (xs ys) (u-eval-expo `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (append xs ys)) `((xs . (val . ,xs)) (ys . (val . ,ys)) . ,initial-env) (make-list 500 'a))))) (display "staged") (newline) (define-staged-relation (appendo2 xs ys zs) (evalo-staged `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (append ',xs ',ys)) zs)) (time (length (run* (x y) (appendo2 x y (make-list 500 'a))))) (display "staged env-passing") (newline) (define-staged-relation (appendo3 xs ys zs) (eval-expo #t `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (append xs ys)) `((xs . (val . ,xs)) (ys . (val . ,ys)) . ,initial-env) zs)) (time (length (run* (x y) (appendo3 x y (make-list 500 'a))))) (define-staged-relation (context-appendo e xs ys res) (eval-expo #t `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) ,e) `((xs . (val . ,xs)) (ys . (val . ,ys)) . ,initial-env) res)) (time (length (run* (xs ys) (context-appendo `(append xs ys) xs ys (make-list 500 'a)))))
null
https://raw.githubusercontent.com/namin/staged-miniKanren/8816527be93db1dece235d4dd1491b0b9ece1910/tests-append.scm
scheme
(load "staged-load.scm") (display "in mk") (newline) (define (appendo xs ys zs) (conde ((== xs '()) (== ys zs)) ((fresh (xa xd zd) (== xs (cons xa xd)) (== zs (cons xa zd)) (appendo xd ys zd))))) (time (length (run* (x y) (appendo x y (make-list 500 'a))))) (display "unstaged") (newline) (time (length (run* (x y) (evalo-unstaged `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (append ',x ',y)) (make-list 500 'a))))) (display "unstaged env-passing") (newline) (time (length (run* (xs ys) (u-eval-expo `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (append xs ys)) `((xs . (val . ,xs)) (ys . (val . ,ys)) . ,initial-env) (make-list 500 'a))))) (display "staged") (newline) (define-staged-relation (appendo2 xs ys zs) (evalo-staged `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (append ',xs ',ys)) zs)) (time (length (run* (x y) (appendo2 x y (make-list 500 'a))))) (display "staged env-passing") (newline) (define-staged-relation (appendo3 xs ys zs) (eval-expo #t `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) (append xs ys)) `((xs . (val . ,xs)) (ys . (val . ,ys)) . ,initial-env) zs)) (time (length (run* (x y) (appendo3 x y (make-list 500 'a))))) (define-staged-relation (context-appendo e xs ys res) (eval-expo #t `(letrec ((append (lambda (xs ys) (if (null? xs) ys (cons (car xs) (append (cdr xs) ys)))))) ,e) `((xs . (val . ,xs)) (ys . (val . ,ys)) . ,initial-env) res)) (time (length (run* (xs ys) (context-appendo `(append xs ys) xs ys (make-list 500 'a)))))
f0cffb8ebc34704ed97a5e8e856067a519572cdf14ee9e520dc61b73445190fa
con-kitty/categorifier
Base.hs
# LANGUAGE TupleSections # | The ` Categorifier . . can support most of categorification ( ` arr ` is a -- very powerful operation), but it doesn't provide all of the appropriate functions and some of them are too complicated to encode directly in GHC Core . This module bridges the gap to make the Core definitions more tractable . module Categorifier.Core.Base ( distlB, fixB, ifThenElseB, lassocB, rassocB, strengthB, uncurryB, ) where import Control.Arrow (Arrow (arr, first), ArrowLoop (..)) import Control.Category (Category (..)) import Data.Bifunctor (Bifunctor (bimap)) import Prelude hiding ((.)) distlB :: Bifunctor f => (a, f b c) -> f (a, b) (a, c) distlB (a, fbc) = bimap (a,) (a,) fbc fixB :: ArrowLoop k => k (a, x) x -> k a x fixB f = loop (arr (\x -> (x, x)) . f) ifThenElseB :: (Bool, (a, a)) -> a ifThenElseB (t, (c, a)) = if t then c else a lassocB :: (a, (b, c)) -> ((a, b), c) lassocB (a, (b, c)) = ((a, b), c) rassocB :: ((a, b), c) -> (a, (b, c)) rassocB ((a, b), c) = (a, (b, c)) strengthB :: Functor f => (a, f b) -> f (a, b) strengthB (a, fb) = (a,) <$> fb uncurryB :: Arrow k => k a (b -> c) -> k (a, b) c uncurryB f = arr (uncurry ($)) . first f
null
https://raw.githubusercontent.com/con-kitty/categorifier/df7e88e08535c646b97841c323326404b4a46664/plugin/Categorifier/Core/Base.hs
haskell
very powerful operation), but it doesn't provide all of the appropriate functions and some of
# LANGUAGE TupleSections # | The ` Categorifier . . can support most of categorification ( ` arr ` is a them are too complicated to encode directly in GHC Core . This module bridges the gap to make the Core definitions more tractable . module Categorifier.Core.Base ( distlB, fixB, ifThenElseB, lassocB, rassocB, strengthB, uncurryB, ) where import Control.Arrow (Arrow (arr, first), ArrowLoop (..)) import Control.Category (Category (..)) import Data.Bifunctor (Bifunctor (bimap)) import Prelude hiding ((.)) distlB :: Bifunctor f => (a, f b c) -> f (a, b) (a, c) distlB (a, fbc) = bimap (a,) (a,) fbc fixB :: ArrowLoop k => k (a, x) x -> k a x fixB f = loop (arr (\x -> (x, x)) . f) ifThenElseB :: (Bool, (a, a)) -> a ifThenElseB (t, (c, a)) = if t then c else a lassocB :: (a, (b, c)) -> ((a, b), c) lassocB (a, (b, c)) = ((a, b), c) rassocB :: ((a, b), c) -> (a, (b, c)) rassocB ((a, b), c) = (a, (b, c)) strengthB :: Functor f => (a, f b) -> f (a, b) strengthB (a, fb) = (a,) <$> fb uncurryB :: Arrow k => k a (b -> c) -> k (a, b) c uncurryB f = arr (uncurry ($)) . first f
39fe7c80280554c7eaa3818a2dd6adef0b1c82d42fe146bdad4ab5cced054a45
chicken-mobile/chicken-sdl2-android-builder
define-enum-mask-accessor.scm
;; chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2 ;; Copyright © 2013 , 2015 - 2016 . ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; - Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; ;; - Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in ;; the documentation and/or other materials provided with the ;; distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS ;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , ;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED ;; OF THE POSSIBILITY OF SUCH DAMAGE. Macro : define - enum - mask - accessor ;;; ;;; Defines a getter and (optionally) setter that automatically ;;; convert enums from integer to list of symbols when getting, and ;;; from list of symbols to integer when setting. This macro is ;;; usually used for struct fields that hold an enum bitfield. ;;; ;;; This macro works by wrapping an existing "raw" getter and setter ;;; that work with integer values. The integer values are converted ;;; to/from lists of symbols using enum mask packer/unpacker ;;; procedures. ;;; ;;; Usage (getter and setter): ;;; ;;; (define-enum-mask-accessor getter : ( GETTER ;;; raw: GETTER-RAW unpack : UNPACKER exact : DEFAULT - EXACT ? ) ;;; setter: (SETTER ;;; raw: SETTER-RAW ;;; pack: PACKER)) ;;; ;;; Usage (getter only): ;;; ;;; (define-enum-mask-accessor getter : ( GETTER ;;; raw: GETTER-RAW unpack : UNPACKER exact : DEFAULT - EXACT ? ) ) ;;; GETTER is the name for a getter procedure that returns the field value as a list of symbols . The getter procedure accepts one required argument , an object that will be passed to GETTER - RAW , and one optional argument , which controls whether bitmasks must ;;; match exactly (see define-enum-mask-unpacker). The getter ;;; procedure will be defined by this macro. If a setter is also ;;; specified, the getter procedure will be enhanced to work with " generalized set ! " ( SRFI 17 ) . ;;; GETTER - RAW is the name of an existing struct field getter that ;;; returns an integer value. ;;; UNPACKER is the name of an existing procedure that unpacks an ;;; integer value to a list of symbols. It is used to convert the value returned by GETTER - RAW . Usually UNPACKER is a procedure ;;; defined with define-enum-mask-unpacker. ;;; ;;; DEFAULT-EXACT? must be #t or #f, and determines the default value ;;; for the optional argument to the getter procedure, which controls ;;; whether bitmasks much match exactly or not. ;;; SETTER is the name for a setter procedure that accepts an object ;;; and a list of enum symbols. The setter procedure will also accept an integer , which is assumed to be an already - packed bitfield ;;; value. The setter will throw an error if given a list containing ;;; an unrecognized symbol, or invalid type. The setter procedure will ;;; be defined by this macro. ;;; ;;; SETTER-RAW is the name of an existing procedure which sets a ;;; struct field to an integer value. ;;; ;;; PACKER is the name of an existing procedure that packs a list of ;;; enum symbols to an integer value. It is used to convert a list of ;;; symbols before passing it to SETTER-RAW. Usually PACKER is a ;;; procedure defined with define-enum-mask-packer. ;;; ;;; Example: ;;; ;;; (define-enum-mask-accessor ;;; getter: (keysym-mod ;;; raw: keysym-mod-raw ;;; unpack: unpack-keymods ;;; exact: #f) ;;; setter: (keysym-mod-set! ;;; raw: keysym-mod-raw-set! ;;; pack: pack-keymods)) ;;; (define-syntax define-enum-mask-accessor (syntax-rules (getter: raw: unpack: exact: setter: pack:) ;; Getter and setter ((define-enum-mask-accessor getter: (getter-name raw: getter-raw unpack: unpacker exact: default-exact?) setter: (setter-name raw: setter-raw pack: packer)) (begin (define (setter-name record new) (setter-raw record (cond ((integer? new) new) ((list? new) (packer new (lambda (x) (error 'setter-name "unrecognized enum value" x)))) (else (error 'setter-name "invalid type (expected list of symbols, or integer)" new))))) (define (getter-name record #!optional (exact? default-exact?)) (unpacker (getter-raw record) exact?)) (set! (setter getter-name) setter-name))) ;; Only getter ((define-enum-mask-accessor getter: (getter-name raw: getter-raw unpack: unpacker exact: default-exact?)) (define (getter-name record #!optional (exact? default-exact?)) (unpacker (getter-raw record) exact?)))))
null
https://raw.githubusercontent.com/chicken-mobile/chicken-sdl2-android-builder/90ef1f0ff667737736f1932e204d29ae615a00c4/eggs/sdl2/lib/sdl2-internals/helpers/define-enum-mask-accessor.scm
scheme
All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Defines a getter and (optionally) setter that automatically convert enums from integer to list of symbols when getting, and from list of symbols to integer when setting. This macro is usually used for struct fields that hold an enum bitfield. This macro works by wrapping an existing "raw" getter and setter that work with integer values. The integer values are converted to/from lists of symbols using enum mask packer/unpacker procedures. Usage (getter and setter): (define-enum-mask-accessor raw: GETTER-RAW setter: (SETTER raw: SETTER-RAW pack: PACKER)) Usage (getter only): (define-enum-mask-accessor raw: GETTER-RAW match exactly (see define-enum-mask-unpacker). The getter procedure will be defined by this macro. If a setter is also specified, the getter procedure will be enhanced to work with returns an integer value. integer value to a list of symbols. It is used to convert the defined with define-enum-mask-unpacker. DEFAULT-EXACT? must be #t or #f, and determines the default value for the optional argument to the getter procedure, which controls whether bitmasks much match exactly or not. and a list of enum symbols. The setter procedure will also accept value. The setter will throw an error if given a list containing an unrecognized symbol, or invalid type. The setter procedure will be defined by this macro. SETTER-RAW is the name of an existing procedure which sets a struct field to an integer value. PACKER is the name of an existing procedure that packs a list of enum symbols to an integer value. It is used to convert a list of symbols before passing it to SETTER-RAW. Usually PACKER is a procedure defined with define-enum-mask-packer. Example: (define-enum-mask-accessor getter: (keysym-mod raw: keysym-mod-raw unpack: unpack-keymods exact: #f) setter: (keysym-mod-set! raw: keysym-mod-raw-set! pack: pack-keymods)) Getter and setter Only getter
chicken - sdl2 : CHICKEN Scheme bindings to Simple DirectMedia Layer 2 Copyright © 2013 , 2015 - 2016 . " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , Macro : define - enum - mask - accessor getter : ( GETTER unpack : UNPACKER exact : DEFAULT - EXACT ? ) getter : ( GETTER unpack : UNPACKER exact : DEFAULT - EXACT ? ) ) GETTER is the name for a getter procedure that returns the field value as a list of symbols . The getter procedure accepts one required argument , an object that will be passed to GETTER - RAW , and one optional argument , which controls whether bitmasks must " generalized set ! " ( SRFI 17 ) . GETTER - RAW is the name of an existing struct field getter that UNPACKER is the name of an existing procedure that unpacks an value returned by GETTER - RAW . Usually UNPACKER is a procedure SETTER is the name for a setter procedure that accepts an object an integer , which is assumed to be an already - packed bitfield (define-syntax define-enum-mask-accessor (syntax-rules (getter: raw: unpack: exact: setter: pack:) ((define-enum-mask-accessor getter: (getter-name raw: getter-raw unpack: unpacker exact: default-exact?) setter: (setter-name raw: setter-raw pack: packer)) (begin (define (setter-name record new) (setter-raw record (cond ((integer? new) new) ((list? new) (packer new (lambda (x) (error 'setter-name "unrecognized enum value" x)))) (else (error 'setter-name "invalid type (expected list of symbols, or integer)" new))))) (define (getter-name record #!optional (exact? default-exact?)) (unpacker (getter-raw record) exact?)) (set! (setter getter-name) setter-name))) ((define-enum-mask-accessor getter: (getter-name raw: getter-raw unpack: unpacker exact: default-exact?)) (define (getter-name record #!optional (exact? default-exact?)) (unpacker (getter-raw record) exact?)))))
51f18d10ff84660923eda35101387dad5d813b26384179908ab272e42b4a85d2
elastic/eui-cljs
icon_logo_sketch.cljs
(ns eui.icon-logo-sketch (:require ["@elastic/eui/lib/components/icon/assets/logo_sketch.js" :as eui])) (def logoSketch eui/icon)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/icon_logo_sketch.cljs
clojure
(ns eui.icon-logo-sketch (:require ["@elastic/eui/lib/components/icon/assets/logo_sketch.js" :as eui])) (def logoSketch eui/icon)
65b963159bb3b846f350e903530f8a0babc27732b2aff590e11e5cae4d4e20e6
input-output-hk/cardano-sl
Web.hs
-- | Web API parts of cardano-explorer module Pos.Explorer.Web ( module Web ) where import Pos.Explorer.Web.Server as Web import Pos.Explorer.Web.Transform as Web
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/explorer/src/Pos/Explorer/Web.hs
haskell
| Web API parts of cardano-explorer
module Pos.Explorer.Web ( module Web ) where import Pos.Explorer.Web.Server as Web import Pos.Explorer.Web.Transform as Web
71b778dd73428d7336f1cd4808fe7fbc88674d9cc54769a501b436f73df143fc
Javran/advent-of-code
Day13.hs
module Javran.AdventOfCode.Y2016.Day13 ( ) where import Control.Monad import Data.Bits import Data.Function import qualified Data.Map.Strict as M import qualified Data.PSQueue as PQ import Data.Semigroup import qualified Data.Sequence as Seq import qualified Data.Set as S import Javran.AdventOfCode.Prelude import Javran.AdventOfCode.TestExtra data Day13 deriving (Generic) type Coord = (Int, Int) -- X then Y data Cell = Open | Wall deriving (Ord, Eq) mkMapInfo :: Int -> Coord -> Cell mkMapInfo seed (x, y) = if even (popCount v) then Open else Wall where -- same polynomial, re-arranged to slightly reduce the amount of operations. v = x * (x + 3 + 2 * y) + y + y * y + seed adjacents :: (Coord -> Cell) -> Coord -> [Coord] adjacents mi coord = do coord'@(x', y') <- udlrOfCoord coord guard $ x' >= 0 && y' >= 0 && mi coord' == Open pure coord' aStar :: (Coord -> Cell) -> Coord -> PQ.PSQ Coord (Arg Int Int) -> M.Map Coord Int -> Int aStar mi goal = fix \search q0 dists -> case PQ.minView q0 of Nothing -> error "queue exhausted" Just (u PQ.:-> (Arg _fScore distU), q1) -> if u == goal then distU else let nexts = do v <- adjacents mi u let mDistV = dists M.!? v distV' = distU + 1 fScore' = distV' + manhattan v goal guard $ maybe True (distV' <) mDistV pure (v, distV', Arg fScore' distV') q2 = foldr upd q1 nexts where upd (v, _, prio') = PQ.insert v prio' dists' = foldr upd dists nexts where upd (v, distV', _) = M.insert v distV' in search q2 dists' bfs :: (Coord -> Cell) -> S.Set Coord -> (Seq.Seq (Coord, Int) -> Int) bfs mi discovered = \case Seq.Empty -> S.size discovered (u, dist) Seq.:<| q1 -> let nexts = do guard $ dist < 50 v <- adjacents mi u guard $ S.notMember v discovered pure (v, dist + 1) discovered' = foldr (\(v, _) -> S.insert v) discovered nexts q2 = q1 <> Seq.fromList nexts in bfs mi discovered' q2 instance Solution Day13 where solutionRun _ SolutionContext {getInputS, answerShow} = do (ex, rawInput) <- consumeExtra getInputS let seed = read @Int . head . lines $ rawInput mapInfo = mkMapInfo seed start = (1, 1) target = singleLineExtra (31, 39) ex answerShow $ aStar mapInfo target (PQ.singleton start (Arg (manhattan start target) 0)) (M.singleton start 0) answerShow $ bfs mapInfo (S.singleton start) (Seq.singleton (start, 0))
null
https://raw.githubusercontent.com/Javran/advent-of-code/676ef13c2f9d341cf7de0f383335a1cf577bd73d/src/Javran/AdventOfCode/Y2016/Day13.hs
haskell
X then Y same polynomial, re-arranged to slightly reduce the amount of operations.
module Javran.AdventOfCode.Y2016.Day13 ( ) where import Control.Monad import Data.Bits import Data.Function import qualified Data.Map.Strict as M import qualified Data.PSQueue as PQ import Data.Semigroup import qualified Data.Sequence as Seq import qualified Data.Set as S import Javran.AdventOfCode.Prelude import Javran.AdventOfCode.TestExtra data Day13 deriving (Generic) data Cell = Open | Wall deriving (Ord, Eq) mkMapInfo :: Int -> Coord -> Cell mkMapInfo seed (x, y) = if even (popCount v) then Open else Wall where v = x * (x + 3 + 2 * y) + y + y * y + seed adjacents :: (Coord -> Cell) -> Coord -> [Coord] adjacents mi coord = do coord'@(x', y') <- udlrOfCoord coord guard $ x' >= 0 && y' >= 0 && mi coord' == Open pure coord' aStar :: (Coord -> Cell) -> Coord -> PQ.PSQ Coord (Arg Int Int) -> M.Map Coord Int -> Int aStar mi goal = fix \search q0 dists -> case PQ.minView q0 of Nothing -> error "queue exhausted" Just (u PQ.:-> (Arg _fScore distU), q1) -> if u == goal then distU else let nexts = do v <- adjacents mi u let mDistV = dists M.!? v distV' = distU + 1 fScore' = distV' + manhattan v goal guard $ maybe True (distV' <) mDistV pure (v, distV', Arg fScore' distV') q2 = foldr upd q1 nexts where upd (v, _, prio') = PQ.insert v prio' dists' = foldr upd dists nexts where upd (v, distV', _) = M.insert v distV' in search q2 dists' bfs :: (Coord -> Cell) -> S.Set Coord -> (Seq.Seq (Coord, Int) -> Int) bfs mi discovered = \case Seq.Empty -> S.size discovered (u, dist) Seq.:<| q1 -> let nexts = do guard $ dist < 50 v <- adjacents mi u guard $ S.notMember v discovered pure (v, dist + 1) discovered' = foldr (\(v, _) -> S.insert v) discovered nexts q2 = q1 <> Seq.fromList nexts in bfs mi discovered' q2 instance Solution Day13 where solutionRun _ SolutionContext {getInputS, answerShow} = do (ex, rawInput) <- consumeExtra getInputS let seed = read @Int . head . lines $ rawInput mapInfo = mkMapInfo seed start = (1, 1) target = singleLineExtra (31, 39) ex answerShow $ aStar mapInfo target (PQ.singleton start (Arg (manhattan start target) 0)) (M.singleton start 0) answerShow $ bfs mapInfo (S.singleton start) (Seq.singleton (start, 0))
d2e6201bc90988c346a022654f1b1055b5150cd6752463292d60d304f6d856d3
francescoc/scalabilitywitherlangotp
bsc.erl
-module(bsc). -behaviour(application). %% Application callbacks -export([start/2, start_phase/3, stop/1]). start(_StartType, _StartArgs) -> bsc_sup:start_link(). start_phase(StartPhase, StartType, Args) -> io:format("bsc:start_phase(~p,~p,~p).~n", [StartPhase, StartType, Args]). stop(_Data) -> ok.
null
https://raw.githubusercontent.com/francescoc/scalabilitywitherlangotp/961de968f034e55eba22eea9a368fe9f47c608cc/ch9/start_phases/bsc.erl
erlang
Application callbacks
-module(bsc). -behaviour(application). -export([start/2, start_phase/3, stop/1]). start(_StartType, _StartArgs) -> bsc_sup:start_link(). start_phase(StartPhase, StartType, Args) -> io:format("bsc:start_phase(~p,~p,~p).~n", [StartPhase, StartType, Args]). stop(_Data) -> ok.
981ef84fed93d20cbe27caa01a7789831349812faa8823a9a8fa3869e0fdd85b
kowainik/containers-backpack
Int.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE TypeFamilies #-} module Map.Int ( Map , Key , empty , singleton , fromList , null , size , member , lookup , lookupDefault , toList , keys , elems , insert , insertWith , adjust , update , delete , alter ) where import Control.DeepSeq (NFData (..)) import Data.Coerce (coerce) import Prelude hiding (lookup, null) import qualified Data.IntMap.Strict as M newtype Map k v = IM (M.IntMap v) deriving newtype (Show, Eq, NFData) type Key = (~) Int empty :: forall k v. Map k v empty = coerce @(M.IntMap v) M.empty {-# INLINE empty #-} singleton :: forall k v. Key k => k -> v -> Map k v singleton = coerce @(k -> v -> M.IntMap v) M.singleton # INLINE singleton # fromList :: forall k v. Key k => [(k, v)] -> Map k v fromList = coerce @([(k, v)] -> M.IntMap v) M.fromList # INLINE fromList # null :: forall k v. Map k v -> Bool null = coerce @(M.IntMap v -> Bool) M.null # INLINE null # size :: forall k v. Map k v -> Int size = coerce @(M.IntMap v -> Int) M.size # INLINE size # member :: forall k v. Key k => k -> Map k v -> Bool member = coerce @(k -> M.IntMap v -> Bool) M.member {-# INLINE member #-} lookup :: forall k v. Key k => k -> Map k v -> Maybe v lookup = coerce @(k -> M.IntMap v -> Maybe v) M.lookup {-# INLINE lookup #-} lookupDefault :: forall k v. Key k => v -> k -> Map k v -> v lookupDefault = coerce @(v -> k -> M.IntMap v -> v) M.findWithDefault # INLINE lookupDefault # toList :: forall k v. Key k => Map k v -> [(k, v)] toList = coerce @(M.IntMap v -> [(k, v)]) M.toList # INLINE toList # keys :: forall k v. Key k => Map k v -> [k] keys = coerce @(M.IntMap v -> [k]) M.keys # INLINE keys # elems :: forall k v. Map k v -> [v] elems = coerce @(M.IntMap v -> [v]) M.elems # INLINE elems # insert :: forall k v. Key k => k -> v -> Map k v -> Map k v insert = coerce @(k -> v -> M.IntMap v -> M.IntMap v) M.insert # INLINE insert # insertWith :: forall k v. Key k => (v -> v -> v) -> k -> v -> Map k v -> Map k v insertWith = coerce @((v -> v -> v) -> k -> v -> M.IntMap v -> M.IntMap v) M.insertWith # INLINE insertWith # adjust :: forall k v. Key k => (v -> v) -> k -> Map k v -> Map k v adjust = coerce @((v -> v) -> k -> M.IntMap v -> M.IntMap v) M.adjust # INLINE adjust # update :: forall k v. Key k => (v -> Maybe v) -> k -> Map k v -> Map k v update = coerce @((v -> Maybe v) -> k -> M.IntMap v -> M.IntMap v) M.update # INLINE update # delete :: forall k v. Key k => k -> Map k v -> Map k v delete = coerce @(k -> M.IntMap v -> M.IntMap v) M.delete {-# INLINE delete #-} alter :: forall k v. Key k => (Maybe v -> Maybe v) -> k -> Map k v -> Map k v alter = coerce @((Maybe v -> Maybe v) -> k -> M.IntMap v -> M.IntMap v) M.alter # INLINE alter #
null
https://raw.githubusercontent.com/kowainik/containers-backpack/d74fbb592dd1994c62cfd3a900d1c7429fd859d6/src/int-strict/Map/Int.hs
haskell
# LANGUAGE TypeFamilies # # INLINE empty # # INLINE member # # INLINE lookup # # INLINE delete #
# LANGUAGE FlexibleInstances # module Map.Int ( Map , Key , empty , singleton , fromList , null , size , member , lookup , lookupDefault , toList , keys , elems , insert , insertWith , adjust , update , delete , alter ) where import Control.DeepSeq (NFData (..)) import Data.Coerce (coerce) import Prelude hiding (lookup, null) import qualified Data.IntMap.Strict as M newtype Map k v = IM (M.IntMap v) deriving newtype (Show, Eq, NFData) type Key = (~) Int empty :: forall k v. Map k v empty = coerce @(M.IntMap v) M.empty singleton :: forall k v. Key k => k -> v -> Map k v singleton = coerce @(k -> v -> M.IntMap v) M.singleton # INLINE singleton # fromList :: forall k v. Key k => [(k, v)] -> Map k v fromList = coerce @([(k, v)] -> M.IntMap v) M.fromList # INLINE fromList # null :: forall k v. Map k v -> Bool null = coerce @(M.IntMap v -> Bool) M.null # INLINE null # size :: forall k v. Map k v -> Int size = coerce @(M.IntMap v -> Int) M.size # INLINE size # member :: forall k v. Key k => k -> Map k v -> Bool member = coerce @(k -> M.IntMap v -> Bool) M.member lookup :: forall k v. Key k => k -> Map k v -> Maybe v lookup = coerce @(k -> M.IntMap v -> Maybe v) M.lookup lookupDefault :: forall k v. Key k => v -> k -> Map k v -> v lookupDefault = coerce @(v -> k -> M.IntMap v -> v) M.findWithDefault # INLINE lookupDefault # toList :: forall k v. Key k => Map k v -> [(k, v)] toList = coerce @(M.IntMap v -> [(k, v)]) M.toList # INLINE toList # keys :: forall k v. Key k => Map k v -> [k] keys = coerce @(M.IntMap v -> [k]) M.keys # INLINE keys # elems :: forall k v. Map k v -> [v] elems = coerce @(M.IntMap v -> [v]) M.elems # INLINE elems # insert :: forall k v. Key k => k -> v -> Map k v -> Map k v insert = coerce @(k -> v -> M.IntMap v -> M.IntMap v) M.insert # INLINE insert # insertWith :: forall k v. Key k => (v -> v -> v) -> k -> v -> Map k v -> Map k v insertWith = coerce @((v -> v -> v) -> k -> v -> M.IntMap v -> M.IntMap v) M.insertWith # INLINE insertWith # adjust :: forall k v. Key k => (v -> v) -> k -> Map k v -> Map k v adjust = coerce @((v -> v) -> k -> M.IntMap v -> M.IntMap v) M.adjust # INLINE adjust # update :: forall k v. Key k => (v -> Maybe v) -> k -> Map k v -> Map k v update = coerce @((v -> Maybe v) -> k -> M.IntMap v -> M.IntMap v) M.update # INLINE update # delete :: forall k v. Key k => k -> Map k v -> Map k v delete = coerce @(k -> M.IntMap v -> M.IntMap v) M.delete alter :: forall k v. Key k => (Maybe v -> Maybe v) -> k -> Map k v -> Map k v alter = coerce @((Maybe v -> Maybe v) -> k -> M.IntMap v -> M.IntMap v) M.alter # INLINE alter #
12f3bd7dfe5c40d7a3b7c6f0e871004809e5c24ef850c3bedbd8f5ac9527f615
MaskRay/OJHaskell
TLE_CIRUT.hs
import Data.Array.Base import Data.Array.IO import Data.Function import Data.List import Data.Monoid import Text.Printf import System.IO.Unsafe tau = pi*2 data Circle = Circle { x::Double, y::Double, r::Double } distance a b = sqrt $ (x b-x a)^2+(y b-y a)^2 contain a b = r a >= r b + distance a b intersects a b = r a+r b > d && d > abs (r a-r b) where d = distance a b intersection a b = if r a+r b > d && d > abs (r a-r b) then if end > tau then [(bgn,1),(tau,-1),(0.0,1),(end-tau,-1)] else [(bgn,1),(end,-1)] else [] where alpha = atan2 (y b-y a) (x b-x a) theta = acos $ (r a^2+d*d-r b^2) / (2*r a*d) d = distance a b (t1, t2) = (alpha-theta, alpha+theta) (bgn, end) = if t1 < 0 then (t1+tau, t2+tau) else (t1, t2) solve ([], _) res = return () solve (c:cs, cs2) res = do go 0.0 (succ . length $ filter (\d -> contain d c) cs2) (events ++ [(tau, 0)]) solve (cs, c:cs2) res where events = sort $ concatMap (intersection c) $ cs2++cs arch c bgn end = (/2) $ r c^2*(end-bgn-sin (end-bgn)) + (fst pbgn*snd pend-snd pbgn*fst pend) where pbgn = (x c+r c*cos bgn, y c+r c*sin bgn) pend = (x c+r c*cos end, y c+r c*sin end) go _ _ [] = return () go l st (e:es) = do old <- unsafeRead res st unsafeWrite res st (old + arch c l (fst e)) go (fst e) (st + snd e) es main = do _ <- getLine lines <- fmap lines getContents let a = map ((\ [xx,yy,rr] -> Circle {x=xx,y=yy,r=rr}) . map read . words) lines a' = reverse $ sortBy (compare `on` r) a n = length a' res <- newArray (0,n+1) 0 :: IO (IOArray Int Double) solve (a', []) res mapM_ (\i -> do x <- unsafeRead res i y <- unsafeRead res (i+1) printf "[%d] = %.3f\n" i (x-y)) [1..n]
null
https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/SPOJ/TLE_CIRUT.hs
haskell
import Data.Array.Base import Data.Array.IO import Data.Function import Data.List import Data.Monoid import Text.Printf import System.IO.Unsafe tau = pi*2 data Circle = Circle { x::Double, y::Double, r::Double } distance a b = sqrt $ (x b-x a)^2+(y b-y a)^2 contain a b = r a >= r b + distance a b intersects a b = r a+r b > d && d > abs (r a-r b) where d = distance a b intersection a b = if r a+r b > d && d > abs (r a-r b) then if end > tau then [(bgn,1),(tau,-1),(0.0,1),(end-tau,-1)] else [(bgn,1),(end,-1)] else [] where alpha = atan2 (y b-y a) (x b-x a) theta = acos $ (r a^2+d*d-r b^2) / (2*r a*d) d = distance a b (t1, t2) = (alpha-theta, alpha+theta) (bgn, end) = if t1 < 0 then (t1+tau, t2+tau) else (t1, t2) solve ([], _) res = return () solve (c:cs, cs2) res = do go 0.0 (succ . length $ filter (\d -> contain d c) cs2) (events ++ [(tau, 0)]) solve (cs, c:cs2) res where events = sort $ concatMap (intersection c) $ cs2++cs arch c bgn end = (/2) $ r c^2*(end-bgn-sin (end-bgn)) + (fst pbgn*snd pend-snd pbgn*fst pend) where pbgn = (x c+r c*cos bgn, y c+r c*sin bgn) pend = (x c+r c*cos end, y c+r c*sin end) go _ _ [] = return () go l st (e:es) = do old <- unsafeRead res st unsafeWrite res st (old + arch c l (fst e)) go (fst e) (st + snd e) es main = do _ <- getLine lines <- fmap lines getContents let a = map ((\ [xx,yy,rr] -> Circle {x=xx,y=yy,r=rr}) . map read . words) lines a' = reverse $ sortBy (compare `on` r) a n = length a' res <- newArray (0,n+1) 0 :: IO (IOArray Int Double) solve (a', []) res mapM_ (\i -> do x <- unsafeRead res i y <- unsafeRead res (i+1) printf "[%d] = %.3f\n" i (x-y)) [1..n]
05511829cf7ea3517c1b4d2c8c69eda631beb01fa86bb26af15c0d8ec47b4646
austral/austral
TypeParameter.mli
Part of the Austral project , under the Apache License v2.0 with LLVM Exceptions . See LICENSE file for details . SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception Part of the Austral project, under the Apache License v2.0 with LLVM Exceptions. See LICENSE file for details. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *) (** This module defines the type_parameter type. *) open Identifier open Type (** Represents type parameters. *) type type_parameter [@@deriving (show, sexp)] (** Construct a type parameter. *) val make_typaram : identifier * universe * qident * sident list -> type_parameter (** The type parameter's name. *) val typaram_name : type_parameter -> identifier (** The type parameter's universe. *) val typaram_universe : type_parameter -> universe (** The name of the declaration this type parameter belongs to. *) val typaram_source : type_parameter -> qident * The type parameter 's constraints , i.e. , a list of the names of typeclasses arguments to this type must implement . arguments to this type must implement. *) val typaram_constraints : type_parameter -> sident list (** Transform a type parameter into an equivalent type variable. *) val typaram_to_tyvar : type_parameter -> type_var (** Transform a type variable into an equivalent type parameter. *) val tyvar_to_typaram : type_var -> type_parameter
null
https://raw.githubusercontent.com/austral/austral/69b6f7de36cc9576483acd1ac4a31bf52074dbd1/lib/TypeParameter.mli
ocaml
* This module defines the type_parameter type. * Represents type parameters. * Construct a type parameter. * The type parameter's name. * The type parameter's universe. * The name of the declaration this type parameter belongs to. * Transform a type parameter into an equivalent type variable. * Transform a type variable into an equivalent type parameter.
Part of the Austral project , under the Apache License v2.0 with LLVM Exceptions . See LICENSE file for details . SPDX - License - Identifier : Apache-2.0 WITH LLVM - exception Part of the Austral project, under the Apache License v2.0 with LLVM Exceptions. See LICENSE file for details. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *) open Identifier open Type type type_parameter [@@deriving (show, sexp)] val make_typaram : identifier * universe * qident * sident list -> type_parameter val typaram_name : type_parameter -> identifier val typaram_universe : type_parameter -> universe val typaram_source : type_parameter -> qident * The type parameter 's constraints , i.e. , a list of the names of typeclasses arguments to this type must implement . arguments to this type must implement. *) val typaram_constraints : type_parameter -> sident list val typaram_to_tyvar : type_parameter -> type_var val tyvar_to_typaram : type_var -> type_parameter
1a264425cdc85df99c16b286dd55fa31eeb0c61c6249358798888cc210f3808b
lojic/LearningRacket
day01-benknoble.rkt
#lang racket version showing it 's not necessary to compute the sum ;; of the sliding windows :) Here's why: ;; ;; Given a list of '(a b c d ...) the sums of the sliding-3 windows are: ;; a + b + c ;; b + c + d an increase implies d > a ;; c + d + e an increase implies e > b ;; ... etc. (require "../../advent/advent.rkt") (define input (file->list "day01.txt")) (define ((partn n) scans) (count < (drop-right scans n) (drop scans n))) (define (part1) ((partn 1) input)) (define (part2) ((partn 3) input))
null
https://raw.githubusercontent.com/lojic/LearningRacket/00951818e2d160989e1b56cf00dfa38b55b6f4a9/advent-of-code-2021/solutions/day01/day01-benknoble.rkt
racket
of the sliding windows :) Here's why: Given a list of '(a b c d ...) the sums of the sliding-3 windows are: a + b + c b + c + d an increase implies d > a c + d + e an increase implies e > b ... etc.
#lang racket version showing it 's not necessary to compute the sum (require "../../advent/advent.rkt") (define input (file->list "day01.txt")) (define ((partn n) scans) (count < (drop-right scans n) (drop scans n))) (define (part1) ((partn 1) input)) (define (part2) ((partn 3) input))
2dccf0dc4329a0a09e73c6662e514c514a8c3f1bc43ef15003ef37ad782d72ae
coccinelle/coccinelle
lazy.mli
type 'a t = 'a CamlinternalLazy.t exception Undefined external force : 'a t -> 'a = "%lazy_force" val map : ('a -> 'b) -> 'a t -> 'b t val is_val : 'a t -> bool val from_val : 'a -> 'a t val map_val : ('a -> 'b) -> 'a t -> 'b t val from_fun : (unit -> 'a) -> 'a t val force_val : 'a t -> 'a val lazy_from_fun : (unit -> 'a) -> 'a t val lazy_from_val : 'a -> 'a t val lazy_is_val : 'a t -> bool
null
https://raw.githubusercontent.com/coccinelle/coccinelle/5448bb2bd03491ffec356bf7bd6ddcdbf4d36bc9/bundles/stdcompat/stdcompat-current/interfaces/4.14/lazy.mli
ocaml
type 'a t = 'a CamlinternalLazy.t exception Undefined external force : 'a t -> 'a = "%lazy_force" val map : ('a -> 'b) -> 'a t -> 'b t val is_val : 'a t -> bool val from_val : 'a -> 'a t val map_val : ('a -> 'b) -> 'a t -> 'b t val from_fun : (unit -> 'a) -> 'a t val force_val : 'a t -> 'a val lazy_from_fun : (unit -> 'a) -> 'a t val lazy_from_val : 'a -> 'a t val lazy_is_val : 'a t -> bool
6d28287e5bf908744ee6d0013beb6995380d2089353e1e687d932f619076ae9d
unclebob/AdventOfCode2021
project.clj
(defproject day20 "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :main day20.core :dependencies [[org.clojure/clojure "1.8.0"]] :profiles {:dev {:dependencies [[speclj "3.3.2"]]}} :plugins [[speclj "3.3.2"]] :test-paths ["spec"])
null
https://raw.githubusercontent.com/unclebob/AdventOfCode2021/897b078146a80cc477a8a22b0af722a878f2aef3/day20/project.clj
clojure
(defproject day20 "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :main day20.core :dependencies [[org.clojure/clojure "1.8.0"]] :profiles {:dev {:dependencies [[speclj "3.3.2"]]}} :plugins [[speclj "3.3.2"]] :test-paths ["spec"])
25464aae189cfed02f9786206c69ca9908f77ec972fabee5e9e536ed6450135d
eschulte/software-evolution
cil.lisp
;;; cil.lisp --- cil software representation Copyright ( C ) 2012 ;;; License: ;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 , or ( at your option ) ;; any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License along with GNU Emacs ; see the file COPYING . If not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , , USA . ;;; Code: (in-package :software-evolution) ;;; cil software objects (defclass cil (ast) ((compiler :initarg :compiler :accessor compiler :initform "gcc"))) (defmethod apply-mutation ((cil cil) op) (with-temp-file-of (src (ext cil)) (genome cil) (multiple-value-bind (stdout stderr exit) (shell "cil-mutate ~a ~a ~a" (ecase (car op) (:cut "-cut") (:insert "-insert") (:swap "-swap") (:ids "-ids") (:trace "-trace")) (if (eq (car op) :trace) (if (second op) (format nil "-trace-file ~a" (second op)) "") (mapconcat (lambda (pair) (format nil "-stmt~d ~d" (car pair) (cdr pair))) (loop :for id :in (cdr op) :as i :from 1 :collect (cons i id)) " ")) src) (unless (zerop exit) (error 'mutate :text (format nil "cil-mutate:~a" stderr) :obj cil)) stdout))) (defmethod phenome ((cil cil) &key bin) (with-temp-file-of (src (ext cil)) (genome cil) (let ((bin (or bin (temp-file-name)))) (multiple-value-bind (stdout stderr exit) (shell "~a ~a -o ~a ~{~a~^ ~}" (compiler cil) src bin (flags cil)) (declare (ignorable stdout)) (values (if (zerop exit) bin stderr) exit))))) (defmethod lines ((cil cil)) (split-sequence #\Newline (genome cil))) (defmethod (setf lines) (new (cil cil)) (setf (genome cil) (format nil "~{~a~^~%~}" new))) (defun instrument (cil &optional trace-file) "Instrument CIL for traced execution. Optionally specify the name of the file in which to save trace data." (setf (genome cil) (apply-mutation cil (list :trace trace-file))) cil)
null
https://raw.githubusercontent.com/eschulte/software-evolution/dbf5900d1eef834b93eeb00eca34eb7c80e701b6/software/cil.lisp
lisp
cil.lisp --- cil software representation License: This program is free software; you can redistribute it and/or modify either version 3 , or ( at your option ) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. see the file COPYING . If not , write to the Code: cil software objects
Copyright ( C ) 2012 it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , , USA . (in-package :software-evolution) (defclass cil (ast) ((compiler :initarg :compiler :accessor compiler :initform "gcc"))) (defmethod apply-mutation ((cil cil) op) (with-temp-file-of (src (ext cil)) (genome cil) (multiple-value-bind (stdout stderr exit) (shell "cil-mutate ~a ~a ~a" (ecase (car op) (:cut "-cut") (:insert "-insert") (:swap "-swap") (:ids "-ids") (:trace "-trace")) (if (eq (car op) :trace) (if (second op) (format nil "-trace-file ~a" (second op)) "") (mapconcat (lambda (pair) (format nil "-stmt~d ~d" (car pair) (cdr pair))) (loop :for id :in (cdr op) :as i :from 1 :collect (cons i id)) " ")) src) (unless (zerop exit) (error 'mutate :text (format nil "cil-mutate:~a" stderr) :obj cil)) stdout))) (defmethod phenome ((cil cil) &key bin) (with-temp-file-of (src (ext cil)) (genome cil) (let ((bin (or bin (temp-file-name)))) (multiple-value-bind (stdout stderr exit) (shell "~a ~a -o ~a ~{~a~^ ~}" (compiler cil) src bin (flags cil)) (declare (ignorable stdout)) (values (if (zerop exit) bin stderr) exit))))) (defmethod lines ((cil cil)) (split-sequence #\Newline (genome cil))) (defmethod (setf lines) (new (cil cil)) (setf (genome cil) (format nil "~{~a~^~%~}" new))) (defun instrument (cil &optional trace-file) "Instrument CIL for traced execution. Optionally specify the name of the file in which to save trace data." (setf (genome cil) (apply-mutation cil (list :trace trace-file))) cil)
10f9b8f113b7178823b1ef21d0bbbc078f738271e3a181def0546b84d394fcc9
spurious/chibi-scheme-mirror
pathname.scm
Copyright ( c ) 2009 - 2013 . All rights reserved . ;; BSD-style license: ;;> A general, non-filesystem-specific pathname library. ;; POSIX basename ;; (define (path-strip-directory path) ;; (if (string=? path "") ;; path ( let ( ( end ( string - skip - right path # \/ ) ) ) ( if ( zero ? end ) ;; "/" ( let ( ( start ( string - find - right path # \/ 0 end ) ) ) ;; (substring-cursor path start end)))))) ;;> Returns just the basename of \var{path}, with any directory ;;> removed. If \var{path} does not contain a directory separator, ;;> return the whole \var{path}. If \var{path} ends in a directory ;;> separator (i.e. path is a directory), or is empty, return the ;;> empty string. ;; GNU basename (define (path-strip-directory path) (substring-cursor path (string-find-right path #\/))) ;;> Returns just the directory of \var{path}. ;;> If \var{path} is relative (or empty), return \scheme{"."}. (define (path-directory path) (if (string=? path "") "." (let ((end (string-skip-right path #\/))) (if (zero? end) "/" (let ((start (string-find-right path #\/ 0 end))) (if (zero? start) "." (let ((start2 (string-skip-right path #\/ 0 start))) (if (zero? start2) "/" (substring-cursor path 0 start2))))))))) (define (path-extension-pos path) (let ((end (string-cursor-end path))) (let lp ((i end) (dot #f)) (if (<= i 0) #f (let* ((i2 (string-cursor-prev path i)) (ch (string-cursor-ref path i2))) (cond ((eqv? #\. ch) (and (< i end) (lp i2 (or dot i)))) ((eqv? #\/ ch) #f) (dot) (else (lp i2 #f)))))))) ;;> Returns the rightmost extension of \var{path}, not including the ;;> \scheme{"."}. If there is no extension, returns \scheme{#f}. The > extension will always be non - empty and contain no . "}s . (define (path-extension path) (let ((i (path-extension-pos path))) (and i (substring-cursor path i)))) ;;> Returns \var{path} with the extension, if any, removed, ;;> along with the \scheme{"."}. (define (path-strip-extension path) (let ((i (path-extension-pos path))) (if i (substring-cursor path 0 (string-cursor-prev path i)) path))) ;;> Returns \var{path} with the extension, if any, replaced ;;> with \var{ext}. (define (path-replace-extension path ext) (string-append (path-strip-extension path) "." ext)) ;;> Returns \var{path} with any leading ../ removed. (define (path-strip-leading-parents path) (if (string-prefix? "../" path) (path-strip-leading-parents (substring path 3)) (if (equal? path "..") "" path))) ;;> Returns \scheme{#t} iff \var{path} is an absolute path, ;;> i.e. begins with "/". (define (path-absolute? path) (and (not (string=? "" path)) (eqv? #\/ (string-ref path 0)))) ;;> Returns \scheme{#t} iff \var{path} is a relative path. (define (path-relative? path) (not (path-absolute? path))) ;;> Returns the suffix of \var{path} relative to the directory ;;> \var{dir}, or \scheme{#f} if \var{path} is not contained in > \var{dir } . If the two are the same ( modulo a trailing ;;> \scheme{"/"}), then \scheme{"."} is returned. (define (path-relative-to path dir) (let* ((path (path-normalize path)) (path-end (string-cursor-end path)) (dir (path-normalize dir)) (dir-end (string-cursor-end dir)) (i (string-mismatch dir path))) (cond ((not (<= 1 dir-end i path-end)) (let ((i2 (string-cursor-next path i))) (and (= i path-end) (= i2 dir-end) (eqv? #\/ (string-cursor-ref dir i)) "."))) ((= i path-end) ".") ((eqv? #\/ (string-cursor-ref path i)) (let ((i2 (string-cursor-next path i))) (if (= i2 path-end) "." (substring-cursor path i2)))) ((eqv? #\/ (string-cursor-ref path (string-cursor-prev path i))) (substring-cursor path i)) (else #f)))) ;;> Resolve \var{path} relative to the given directory. Returns ;;> \var{path} unchanged if already absolute. (define (path-resolve path dir) (if (path-absolute? path) path (make-path dir path))) ;; This looks big and hairy, but it's mutation-free and guarantees: ( string= ? s ( path - normalize s ) ) < = > ( eq ? s ( path - normalize s ) ) ;; i.e. fast and simple for already normalized paths. ;;> Returns a normalized version of path, with duplicate directory ;;> separators removed and "/./" and "x/../" references removed. ;;> Does not take symbolic links into account - this is meant to ;;> be abstract and applicable to paths on remote systems and in ;;> URIs. Returns \var{path} itself if \var{path} is already ;;> normalized. (define (path-normalize path) (let* ((len (string-length path)) (len-1 (- len 1))) (define (collect i j res) (if (>= i j) res (cons (substring path i j) res))) (define (finish i res) (if (zero? i) path (string-join (reverse (collect i len res))))) ;; loop invariants: ;; - res is a list such that (string-concatenate-reverse res) ;; is always the normalized string up to j ;; - the tail of the string from j onward can be concatenated to ;; the above value to get a partially normalized path referring ;; to the same location as the original path (define (inside i j res) (if (>= j len) (finish i res) (if (eqv? #\/ (string-ref path j)) (boundary i (+ j 1) res) (inside i (+ j 1) res)))) (define (boundary i j res) (if (>= j len) (finish i res) (case (string-ref path j) ((#\.) (cond ((or (= j len-1) (eqv? #\/ (string-ref path (+ j 1)))) (if (= i j) (boundary (+ j 2) (+ j 2) res) (let ((s (substring path i j))) (boundary (+ j 2) (+ j 2) (cons s res))))) ((eqv? #\. (string-ref path (+ j 1))) (if (or (>= j (- len 2)) (eqv? #\/ (string-ref path (+ j 2)))) (if (>= i (- j 1)) (if (null? res) (backup j "" '()) (backup j (car res) (cdr res))) (backup j (substring path i j) res)) (inside i (+ j 2) res))) (else (inside i (+ j 1) res)))) ((#\/) (boundary (+ j 1) (+ j 1) (collect i j res))) (else (inside i (+ j 1) res))))) (define (backup j s res) (let ((pos (+ j 3))) (cond case 1 : we 're reduced to accumulating parents of the cwd ((or (string=? s "/..") (string=? s "..")) (boundary pos pos (cons "/.." (cons s res)))) case 2 : the string is n't a component itself , skip it ((or (string=? s "") (string=? s ".") (string=? s "/")) (if (pair? res) (backup j (car res) (cdr res)) (boundary pos pos (if (string=? s "/") '("/") '(".."))))) case3 : just take the directory of the string (else (let ((d (path-directory s))) (cond ((string=? d "/") (boundary pos pos (if (null? res) '("/") res))) ((string=? d ".") (boundary pos pos res)) (else (boundary pos pos (cons "/" (cons d res)))))))))) ;; start with boundary if abs path, otherwise inside (if (zero? len) path ((if (eqv? #\/ (string-ref path 0)) boundary inside) 0 1 '())))) ;;> Return a new string representing the path where each of \var{args} ;;> is a path component, separated with the directory separator. ;;> \var{args} may include symbols and integers, in addition to ;;> strings. (define (make-path . args) (define (x->string x) (cond ((string? x) x) ((symbol? x) (symbol->string x)) ((number? x) (number->string x)) (else (error "not a valid path component" x)))) (define (trim-trailing-slash s) (substring-cursor s 0 (string-skip-right s #\/))) (if (null? args) "" (let* ((args0 (x->string (car args))) (start (trim-trailing-slash args0))) (let lp ((ls (cdr args)) (res (if (string=? "" start) '() (list start)))) (cond ((null? ls) (if (and (null? res) (not (string=? "" args0))) "/" (string-join (reverse res)))) ((pair? (car ls)) (lp (append (car ls) (cdr ls)) res)) (else (let ((x (trim-trailing-slash (x->string (car ls))))) (cond ((string=? x "") (lp (cdr ls) res)) ((eqv? #\/ (string-ref x 0)) (lp (cdr ls) (cons x res))) (else (lp (cdr ls) (cons x (cons "/" res))))))))))))
null
https://raw.githubusercontent.com/spurious/chibi-scheme-mirror/49168ab073f64a95c834b5f584a9aaea3469594d/lib/chibi/pathname.scm
scheme
BSD-style license: > A general, non-filesystem-specific pathname library. POSIX basename (define (path-strip-directory path) (if (string=? path "") path "/" (substring-cursor path start end)))))) > Returns just the basename of \var{path}, with any directory > removed. If \var{path} does not contain a directory separator, > return the whole \var{path}. If \var{path} ends in a directory > separator (i.e. path is a directory), or is empty, return the > empty string. GNU basename > Returns just the directory of \var{path}. > If \var{path} is relative (or empty), return \scheme{"."}. > Returns the rightmost extension of \var{path}, not including the > \scheme{"."}. If there is no extension, returns \scheme{#f}. The > Returns \var{path} with the extension, if any, removed, > along with the \scheme{"."}. > Returns \var{path} with the extension, if any, replaced > with \var{ext}. > Returns \var{path} with any leading ../ removed. > Returns \scheme{#t} iff \var{path} is an absolute path, > i.e. begins with "/". > Returns \scheme{#t} iff \var{path} is a relative path. > Returns the suffix of \var{path} relative to the directory > \var{dir}, or \scheme{#f} if \var{path} is not contained in > \scheme{"/"}), then \scheme{"."} is returned. > Resolve \var{path} relative to the given directory. Returns > \var{path} unchanged if already absolute. This looks big and hairy, but it's mutation-free and guarantees: i.e. fast and simple for already normalized paths. > Returns a normalized version of path, with duplicate directory > separators removed and "/./" and "x/../" references removed. > Does not take symbolic links into account - this is meant to > be abstract and applicable to paths on remote systems and in > URIs. Returns \var{path} itself if \var{path} is already > normalized. loop invariants: - res is a list such that (string-concatenate-reverse res) is always the normalized string up to j - the tail of the string from j onward can be concatenated to the above value to get a partially normalized path referring to the same location as the original path start with boundary if abs path, otherwise inside > Return a new string representing the path where each of \var{args} > is a path component, separated with the directory separator. > \var{args} may include symbols and integers, in addition to > strings.
Copyright ( c ) 2009 - 2013 . All rights reserved . ( let ( ( end ( string - skip - right path # \/ ) ) ) ( if ( zero ? end ) ( let ( ( start ( string - find - right path # \/ 0 end ) ) ) (define (path-strip-directory path) (substring-cursor path (string-find-right path #\/))) (define (path-directory path) (if (string=? path "") "." (let ((end (string-skip-right path #\/))) (if (zero? end) "/" (let ((start (string-find-right path #\/ 0 end))) (if (zero? start) "." (let ((start2 (string-skip-right path #\/ 0 start))) (if (zero? start2) "/" (substring-cursor path 0 start2))))))))) (define (path-extension-pos path) (let ((end (string-cursor-end path))) (let lp ((i end) (dot #f)) (if (<= i 0) #f (let* ((i2 (string-cursor-prev path i)) (ch (string-cursor-ref path i2))) (cond ((eqv? #\. ch) (and (< i end) (lp i2 (or dot i)))) ((eqv? #\/ ch) #f) (dot) (else (lp i2 #f)))))))) > extension will always be non - empty and contain no . "}s . (define (path-extension path) (let ((i (path-extension-pos path))) (and i (substring-cursor path i)))) (define (path-strip-extension path) (let ((i (path-extension-pos path))) (if i (substring-cursor path 0 (string-cursor-prev path i)) path))) (define (path-replace-extension path ext) (string-append (path-strip-extension path) "." ext)) (define (path-strip-leading-parents path) (if (string-prefix? "../" path) (path-strip-leading-parents (substring path 3)) (if (equal? path "..") "" path))) (define (path-absolute? path) (and (not (string=? "" path)) (eqv? #\/ (string-ref path 0)))) (define (path-relative? path) (not (path-absolute? path))) > \var{dir } . If the two are the same ( modulo a trailing (define (path-relative-to path dir) (let* ((path (path-normalize path)) (path-end (string-cursor-end path)) (dir (path-normalize dir)) (dir-end (string-cursor-end dir)) (i (string-mismatch dir path))) (cond ((not (<= 1 dir-end i path-end)) (let ((i2 (string-cursor-next path i))) (and (= i path-end) (= i2 dir-end) (eqv? #\/ (string-cursor-ref dir i)) "."))) ((= i path-end) ".") ((eqv? #\/ (string-cursor-ref path i)) (let ((i2 (string-cursor-next path i))) (if (= i2 path-end) "." (substring-cursor path i2)))) ((eqv? #\/ (string-cursor-ref path (string-cursor-prev path i))) (substring-cursor path i)) (else #f)))) (define (path-resolve path dir) (if (path-absolute? path) path (make-path dir path))) ( string= ? s ( path - normalize s ) ) < = > ( eq ? s ( path - normalize s ) ) (define (path-normalize path) (let* ((len (string-length path)) (len-1 (- len 1))) (define (collect i j res) (if (>= i j) res (cons (substring path i j) res))) (define (finish i res) (if (zero? i) path (string-join (reverse (collect i len res))))) (define (inside i j res) (if (>= j len) (finish i res) (if (eqv? #\/ (string-ref path j)) (boundary i (+ j 1) res) (inside i (+ j 1) res)))) (define (boundary i j res) (if (>= j len) (finish i res) (case (string-ref path j) ((#\.) (cond ((or (= j len-1) (eqv? #\/ (string-ref path (+ j 1)))) (if (= i j) (boundary (+ j 2) (+ j 2) res) (let ((s (substring path i j))) (boundary (+ j 2) (+ j 2) (cons s res))))) ((eqv? #\. (string-ref path (+ j 1))) (if (or (>= j (- len 2)) (eqv? #\/ (string-ref path (+ j 2)))) (if (>= i (- j 1)) (if (null? res) (backup j "" '()) (backup j (car res) (cdr res))) (backup j (substring path i j) res)) (inside i (+ j 2) res))) (else (inside i (+ j 1) res)))) ((#\/) (boundary (+ j 1) (+ j 1) (collect i j res))) (else (inside i (+ j 1) res))))) (define (backup j s res) (let ((pos (+ j 3))) (cond case 1 : we 're reduced to accumulating parents of the cwd ((or (string=? s "/..") (string=? s "..")) (boundary pos pos (cons "/.." (cons s res)))) case 2 : the string is n't a component itself , skip it ((or (string=? s "") (string=? s ".") (string=? s "/")) (if (pair? res) (backup j (car res) (cdr res)) (boundary pos pos (if (string=? s "/") '("/") '(".."))))) case3 : just take the directory of the string (else (let ((d (path-directory s))) (cond ((string=? d "/") (boundary pos pos (if (null? res) '("/") res))) ((string=? d ".") (boundary pos pos res)) (else (boundary pos pos (cons "/" (cons d res)))))))))) (if (zero? len) path ((if (eqv? #\/ (string-ref path 0)) boundary inside) 0 1 '())))) (define (make-path . args) (define (x->string x) (cond ((string? x) x) ((symbol? x) (symbol->string x)) ((number? x) (number->string x)) (else (error "not a valid path component" x)))) (define (trim-trailing-slash s) (substring-cursor s 0 (string-skip-right s #\/))) (if (null? args) "" (let* ((args0 (x->string (car args))) (start (trim-trailing-slash args0))) (let lp ((ls (cdr args)) (res (if (string=? "" start) '() (list start)))) (cond ((null? ls) (if (and (null? res) (not (string=? "" args0))) "/" (string-join (reverse res)))) ((pair? (car ls)) (lp (append (car ls) (cdr ls)) res)) (else (let ((x (trim-trailing-slash (x->string (car ls))))) (cond ((string=? x "") (lp (cdr ls) res)) ((eqv? #\/ (string-ref x 0)) (lp (cdr ls) (cons x res))) (else (lp (cdr ls) (cons x (cons "/" res))))))))))))
9d8b173a2ca82d4fa21e60fd2a716135c909b8264a721ed755c4a3f72b02b2d2
fragnix/fragnix
Utils.hs
# LANGUAGE OverloadedStrings , module Utils ( IDType(..) , WithDeps(..) , sliceRequest , envRequest , archiveRequest , extract ) where import Fragnix.Slice (Slice) import Network.HTTP.Req import Language.Haskell.Names (Symbol) import Data.Text (Text, index, pack) import Data.ByteString.Lazy (ByteString) import qualified Codec.Archive.Tar as Tar import qualified Codec.Compression.GZip as GZip data IDType = EnvID Text | SliceID Text data WithDeps = WithDeps | WithoutDeps url :: Url 'Https url = https "raw.github.com" /: "fragnix" /: "fragnix-store" /: "main" sliceRequest :: Text -> IO (JsonResponse Slice) sliceRequest sliceId = runReq defaultHttpConfig $ do req GET (url /: "slices" /: pack [index sliceId 0] /: pack [index sliceId 1] /: sliceId) NoReqBody jsonResponse mempty envRequest :: Text -> IO (JsonResponse [Symbol]) envRequest envId = runReq defaultHttpConfig $ do req GET (url /: "environments" /: envId) NoReqBody jsonResponse mempty archiveRequest :: Text -> IO LbsResponse archiveRequest archive = runReq defaultHttpConfig $ do req GET (url /: "fragnix" /: archive) NoReqBody lbsResponse mempty extract :: FilePath -> ByteString -> IO () extract path = Tar.unpack path . Tar.read . GZip.decompress
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/app/Utils.hs
haskell
# LANGUAGE OverloadedStrings , module Utils ( IDType(..) , WithDeps(..) , sliceRequest , envRequest , archiveRequest , extract ) where import Fragnix.Slice (Slice) import Network.HTTP.Req import Language.Haskell.Names (Symbol) import Data.Text (Text, index, pack) import Data.ByteString.Lazy (ByteString) import qualified Codec.Archive.Tar as Tar import qualified Codec.Compression.GZip as GZip data IDType = EnvID Text | SliceID Text data WithDeps = WithDeps | WithoutDeps url :: Url 'Https url = https "raw.github.com" /: "fragnix" /: "fragnix-store" /: "main" sliceRequest :: Text -> IO (JsonResponse Slice) sliceRequest sliceId = runReq defaultHttpConfig $ do req GET (url /: "slices" /: pack [index sliceId 0] /: pack [index sliceId 1] /: sliceId) NoReqBody jsonResponse mempty envRequest :: Text -> IO (JsonResponse [Symbol]) envRequest envId = runReq defaultHttpConfig $ do req GET (url /: "environments" /: envId) NoReqBody jsonResponse mempty archiveRequest :: Text -> IO LbsResponse archiveRequest archive = runReq defaultHttpConfig $ do req GET (url /: "fragnix" /: archive) NoReqBody lbsResponse mempty extract :: FilePath -> ByteString -> IO () extract path = Tar.unpack path . Tar.read . GZip.decompress
a3bf0989295c5c418b68803d7b512a3bcecb9ae3ac8ea86303c03fbfb99afc57
racket/macro-debugger
prefs.rkt
#lang racket/base (require racket/class racket/contract/base framework/preferences "interfaces.rkt" "../syntax-browser/prefs.rkt" framework/notify) (provide pref:macro-step-limit pref:close-on-reset-console? macro-stepper-config-base% macro-stepper-config/prefs% macro-stepper-config/prefs/readonly%) (preferences:set-default 'MacroStepper:Frame:Width 700 number?) (preferences:set-default 'MacroStepper:Frame:Height 600 number?) (preferences:set-default 'MacroStepper:PropertiesShown? #f boolean?) (preferences:set-default 'MacroStepper:PropertiesPanelPercentage 1/3 number?) (preferences:set-default 'MacroStepper:DrawArrows? #t boolean?) (preferences:set-default 'MacroStepper:DisplayTaintIcons 'char (or/c 'char 'snip #f)) (preferences:set-default 'MacroStepper:MacroHidingMode "Disable" string?) (preferences:set-default 'MacroStepper:ShowHidingPanel? #t boolean?) (preferences:set-default 'MacroStepper:IdentifierComparison "bound-identifier=?" string?) (preferences:set-default 'MacroStepper:IdentifierPartition "By macro scopes" string?) (preferences:set-default 'MacroStepper:HighlightFoci? #t boolean?) (preferences:set-default 'MacroStepper:HighlightFrontier? #t boolean?) (preferences:set-default 'MacroStepper:ShowRenameSteps? #f boolean?) (preferences:set-default 'MacroStepper:SuppressWarnings? #f boolean?) (preferences:set-default 'MacroStepper:OneByOne? #f boolean?) (preferences:set-default 'MacroStepper:ExtraNavigation? #f boolean?) (preferences:set-default 'MacroStepper:DebugCatchErrors? #t boolean?) (preferences:set-default 'MacroStepper:SplitContext? #f boolean?) (preferences:set-default 'MacroStepper:MacroStepLimit 40000 (lambda (x) (or (eq? x #f) (exact-positive-integer? x)))) (preferences:set-default 'MacroStepper:RefreshOnResize? #t boolean?) (preferences:set-default 'MacroStepper:CloseOnResetConsole? #t boolean?) (define pref:width (preferences:get/set 'MacroStepper:Frame:Width)) (define pref:height (preferences:get/set 'MacroStepper:Frame:Height)) (define pref:props-shown? (preferences:get/set 'MacroStepper:PropertiesShown?)) (define pref:props-percentage (preferences:get/set 'MacroStepper:PropertiesPanelPercentage)) (define pref:draw-arrows? (preferences:get/set 'MacroStepper:DrawArrows?)) (define pref:taint-icons (preferences:get/set 'MacroStepper:DisplayTaintIcons)) (define pref:macro-hiding-mode (preferences:get/set 'MacroStepper:MacroHidingMode)) (define pref:show-hiding-panel? (preferences:get/set 'MacroStepper:ShowHidingPanel?)) (define pref:identifier=? (preferences:get/set 'MacroStepper:IdentifierComparison)) (define pref:primary-partition (preferences:get/set 'MacroStepper:IdentifierPartition)) (define pref:highlight-foci? (preferences:get/set 'MacroStepper:HighlightFoci?)) (define pref:highlight-frontier? (preferences:get/set 'MacroStepper:HighlightFrontier?)) (define pref:show-rename-steps? (preferences:get/set 'MacroStepper:ShowRenameSteps?)) (define pref:suppress-warnings? (preferences:get/set 'MacroStepper:SuppressWarnings?)) (define pref:one-by-one? (preferences:get/set 'MacroStepper:OneByOne?)) (define pref:extra-navigation? (preferences:get/set 'MacroStepper:ExtraNavigation?)) (define pref:debug-catch-errors? (preferences:get/set 'MacroStepper:DebugCatchErrors?)) (define pref:split-context? (preferences:get/set 'MacroStepper:SplitContext?)) (define pref:macro-step-limit (preferences:get/set 'MacroStepper:MacroStepLimit)) (define pref:refresh-on-resize? (preferences:get/set 'MacroStepper:RefreshOnResize?)) (define pref:close-on-reset-console? (preferences:get/set 'MacroStepper:CloseOnResetConsole?)) (define macro-stepper-config-base% (class* prefs-base% (config<%>) (init-field readonly?) (define-syntax-rule (define-pref-notify* (name pref) ...) (begin (notify:define-notify name (notify:notify-box/pref pref #:readonly? readonly?)) ...)) (define-pref-notify* (width pref:width) (height pref:height) (props-percentage pref:props-percentage) (props-shown? pref:props-shown?) (draw-arrows? pref:draw-arrows?) (taint-icons pref:taint-icons) (macro-hiding-mode pref:macro-hiding-mode) (show-hiding-panel? pref:show-hiding-panel?) (identifier=? pref:identifier=?) (primary-partition pref:primary-partition) (highlight-foci? pref:highlight-foci?) (highlight-frontier? pref:highlight-frontier?) (show-rename-steps? pref:show-rename-steps?) (suppress-warnings? pref:suppress-warnings?) (one-by-one? pref:one-by-one?) (extra-navigation? pref:extra-navigation?) (debug-catch-errors? pref:debug-catch-errors?) (split-context? pref:split-context?) (refresh-on-resize? pref:refresh-on-resize?) (close-on-reset-console? pref:close-on-reset-console?)) (super-new))) (define macro-stepper-config/prefs% (class macro-stepper-config-base% (super-new (readonly? #f)))) (define macro-stepper-config/prefs/readonly% (class macro-stepper-config-base% (super-new (readonly? #t))))
null
https://raw.githubusercontent.com/racket/macro-debugger/d4e2325e6d8eced81badf315048ff54f515110d5/macro-debugger/macro-debugger/view/prefs.rkt
racket
#lang racket/base (require racket/class racket/contract/base framework/preferences "interfaces.rkt" "../syntax-browser/prefs.rkt" framework/notify) (provide pref:macro-step-limit pref:close-on-reset-console? macro-stepper-config-base% macro-stepper-config/prefs% macro-stepper-config/prefs/readonly%) (preferences:set-default 'MacroStepper:Frame:Width 700 number?) (preferences:set-default 'MacroStepper:Frame:Height 600 number?) (preferences:set-default 'MacroStepper:PropertiesShown? #f boolean?) (preferences:set-default 'MacroStepper:PropertiesPanelPercentage 1/3 number?) (preferences:set-default 'MacroStepper:DrawArrows? #t boolean?) (preferences:set-default 'MacroStepper:DisplayTaintIcons 'char (or/c 'char 'snip #f)) (preferences:set-default 'MacroStepper:MacroHidingMode "Disable" string?) (preferences:set-default 'MacroStepper:ShowHidingPanel? #t boolean?) (preferences:set-default 'MacroStepper:IdentifierComparison "bound-identifier=?" string?) (preferences:set-default 'MacroStepper:IdentifierPartition "By macro scopes" string?) (preferences:set-default 'MacroStepper:HighlightFoci? #t boolean?) (preferences:set-default 'MacroStepper:HighlightFrontier? #t boolean?) (preferences:set-default 'MacroStepper:ShowRenameSteps? #f boolean?) (preferences:set-default 'MacroStepper:SuppressWarnings? #f boolean?) (preferences:set-default 'MacroStepper:OneByOne? #f boolean?) (preferences:set-default 'MacroStepper:ExtraNavigation? #f boolean?) (preferences:set-default 'MacroStepper:DebugCatchErrors? #t boolean?) (preferences:set-default 'MacroStepper:SplitContext? #f boolean?) (preferences:set-default 'MacroStepper:MacroStepLimit 40000 (lambda (x) (or (eq? x #f) (exact-positive-integer? x)))) (preferences:set-default 'MacroStepper:RefreshOnResize? #t boolean?) (preferences:set-default 'MacroStepper:CloseOnResetConsole? #t boolean?) (define pref:width (preferences:get/set 'MacroStepper:Frame:Width)) (define pref:height (preferences:get/set 'MacroStepper:Frame:Height)) (define pref:props-shown? (preferences:get/set 'MacroStepper:PropertiesShown?)) (define pref:props-percentage (preferences:get/set 'MacroStepper:PropertiesPanelPercentage)) (define pref:draw-arrows? (preferences:get/set 'MacroStepper:DrawArrows?)) (define pref:taint-icons (preferences:get/set 'MacroStepper:DisplayTaintIcons)) (define pref:macro-hiding-mode (preferences:get/set 'MacroStepper:MacroHidingMode)) (define pref:show-hiding-panel? (preferences:get/set 'MacroStepper:ShowHidingPanel?)) (define pref:identifier=? (preferences:get/set 'MacroStepper:IdentifierComparison)) (define pref:primary-partition (preferences:get/set 'MacroStepper:IdentifierPartition)) (define pref:highlight-foci? (preferences:get/set 'MacroStepper:HighlightFoci?)) (define pref:highlight-frontier? (preferences:get/set 'MacroStepper:HighlightFrontier?)) (define pref:show-rename-steps? (preferences:get/set 'MacroStepper:ShowRenameSteps?)) (define pref:suppress-warnings? (preferences:get/set 'MacroStepper:SuppressWarnings?)) (define pref:one-by-one? (preferences:get/set 'MacroStepper:OneByOne?)) (define pref:extra-navigation? (preferences:get/set 'MacroStepper:ExtraNavigation?)) (define pref:debug-catch-errors? (preferences:get/set 'MacroStepper:DebugCatchErrors?)) (define pref:split-context? (preferences:get/set 'MacroStepper:SplitContext?)) (define pref:macro-step-limit (preferences:get/set 'MacroStepper:MacroStepLimit)) (define pref:refresh-on-resize? (preferences:get/set 'MacroStepper:RefreshOnResize?)) (define pref:close-on-reset-console? (preferences:get/set 'MacroStepper:CloseOnResetConsole?)) (define macro-stepper-config-base% (class* prefs-base% (config<%>) (init-field readonly?) (define-syntax-rule (define-pref-notify* (name pref) ...) (begin (notify:define-notify name (notify:notify-box/pref pref #:readonly? readonly?)) ...)) (define-pref-notify* (width pref:width) (height pref:height) (props-percentage pref:props-percentage) (props-shown? pref:props-shown?) (draw-arrows? pref:draw-arrows?) (taint-icons pref:taint-icons) (macro-hiding-mode pref:macro-hiding-mode) (show-hiding-panel? pref:show-hiding-panel?) (identifier=? pref:identifier=?) (primary-partition pref:primary-partition) (highlight-foci? pref:highlight-foci?) (highlight-frontier? pref:highlight-frontier?) (show-rename-steps? pref:show-rename-steps?) (suppress-warnings? pref:suppress-warnings?) (one-by-one? pref:one-by-one?) (extra-navigation? pref:extra-navigation?) (debug-catch-errors? pref:debug-catch-errors?) (split-context? pref:split-context?) (refresh-on-resize? pref:refresh-on-resize?) (close-on-reset-console? pref:close-on-reset-console?)) (super-new))) (define macro-stepper-config/prefs% (class macro-stepper-config-base% (super-new (readonly? #f)))) (define macro-stepper-config/prefs/readonly% (class macro-stepper-config-base% (super-new (readonly? #t))))
1e6c90380ca863065d5576217d6c81bbc8d9b52e6299f43d9aaba170458830b3
fgalassi/cs61a-sp11
majority-strategy.scm
(load "higher-order") NB : bool - num and 1 are used because apparently you ca n't have a sentence of ; booleans so i am tricking it into a sequence of binary digits (define (majority-strategy first-strategy second-strategy third-strategy) (lambda (hand dealer-card) (majority-of? 1 (sentence (bool-num (first-strategy hand dealer-card)) (bool-num (second-strategy hand dealer-card)) (bool-num (third-strategy hand dealer-card)))))) (define (bool-num bool) (if bool 1 0)) (define (count-equal-to elem sent) (reduce 0 (lambda (total current-elem) (if (equal? elem current-elem) (+ 1 total) total)) sent)) (define (majority-of? elem sent) (> (count-equal-to elem sent) (/ (count sent) 2)))
null
https://raw.githubusercontent.com/fgalassi/cs61a-sp11/66df3b54b03ee27f368c716ae314fd7ed85c4dba/projects/blackjack/normal/majority-strategy.scm
scheme
booleans so i am tricking it into a sequence of binary digits
(load "higher-order") NB : bool - num and 1 are used because apparently you ca n't have a sentence of (define (majority-strategy first-strategy second-strategy third-strategy) (lambda (hand dealer-card) (majority-of? 1 (sentence (bool-num (first-strategy hand dealer-card)) (bool-num (second-strategy hand dealer-card)) (bool-num (third-strategy hand dealer-card)))))) (define (bool-num bool) (if bool 1 0)) (define (count-equal-to elem sent) (reduce 0 (lambda (total current-elem) (if (equal? elem current-elem) (+ 1 total) total)) sent)) (define (majority-of? elem sent) (> (count-equal-to elem sent) (/ (count sent) 2)))
16d2a28d588d2c19d8dc218236f46753100a948f483ad1d61f8a1c2056943cbe
dvingo/malli-code-gen
eql_pull.cljc
(ns space.matterandvoid.malli-gen.eql-pull "Generate EQL pull vectors from schemas Like space.matterandvoid.malli-gen.eql but uses options from schema properties EQL reference -query-language/eql#eql-for-selections" (:require [malli.core :as m] [space.matterandvoid.malli-gen.util :as u]) #?(:clj (:import [clojure.lang ExceptionInfo]))) (comment "Main members are:" space.matterandvoid.malli-gen-eql-pull/map->eql-pull-vector "EQL reference") [ 1 ] -query-language/eql#eql-for-selections [ 2 ] Crux pull #pull (defn ->schema "Huh?" [s] (cond-> s (not (m/schema? s)) m/deref)) (defn schema-type [s] (try (m/type (m/deref s)) (catch #?(:clj ExceptionInfo :cljs :error) e (if (= ::m/invalid-schema (:type (ex-data e))) nil (throw e))))) (def composite-schema-types #{:vector :map :sequential :set ::m/schema :and}) (defn is-vec-of-refs? [s] (let [s (m/deref s)] (and (= :vector (m/type s)) (= (count (m/children s)) 1) (u/ref-schema? (first (m/children s)))))) (defn atomic-prop? [prop-name schema] (not (and (composite-schema-types (m/type (m/deref schema))) (is-vec-of-refs? schema)))) (defn get-map-schema-from-seq "Given a seq of schemas, asserts there is only one :map schema and returns that." [s] (let [map-schemas (filter #(= (m/type %) :map) s)] (assert (= (count map-schemas) 1)) (first map-schemas))) (defn get-map-schema [s] (let [s (m/deref s) ; maybe a double deref right away? s-type (m/type s)] (cond (= :map s-type) s (#{:or :and} s-type) (get-map-schema-from-seq (m/children s))))) (def supported-schema-types #{:map}) need a helper function that takes two schemas which are map schemas , but may be refs - so you deref both first ;; they are equal if they have all the same keys (defn map-schemas-equal? "Treats two map schemas as being equivalent if they have all the same keys in the top level. 'm1' and 'm2' can be literal map schemas or RefSchemas to map schemas, or mix of both." [m1 m2] (let [children1 (map first (m/children (m/deref m1))) children2 (map first (m/children (m/deref m2)))] (= children1 children2))) (defn map->eql-pull-vector "Given a malli schema returns a query vector Does not handle arbitrary schema, your root schema (the one you pass to this function) must be a ':map' schema or an ':and' schema of a ':map'. all [:ref ::other-schema] become EQL joins. Crux pull #pull" [orig-schema] ;(prn ::pull-vector orig-schema) ( println ( apply str ( repeat 80 " - " ) ) ) (let [schema (m/deref orig-schema) {:space.matterandvoid.malli-gen.eql-pull/keys [pull-depth] :or {pull-depth 3}} (m/properties schema) _ (assert (supported-schema-types (m/type schema)) (str "Invalid schema. Supports: " (pr-str supported-schema-types))) ;_ (println "schema type: " (pr-str (m/type schema))) entry->pull-item (fn ->pull [entry] (let [[prop-name options child-schema] entry] ;(println "child schema: " child-schema) ;(println "options: " options) (if (atomic-prop? prop-name child-schema) prop-name (let [ref-schema (u/ref-coll->reffed child-schema) _ ( println " REF schema : " ( pr - str ref - schema ) ) _ ( println " REF schema get map : " ( pr - str ( get - map - schema ref - schema ) ) ) ;_ (println "orig schema: " (pr-str orig-schema)) recursive? (or (map-schemas-equal? ref-schema orig-schema) (map-schemas-equal? (get-map-schema ref-schema) (get-map-schema orig-schema))) #_#__ (println "orig schema get-map: " (pr-str (get-map-schema orig-schema)))] (if recursive? {prop-name pull-depth} (do ;(println "not recursve: type " (pr-str child-schema) (schema-type child-schema)) (cond (= :vector (schema-type child-schema)) (do ;(def x ref-schema) {prop-name (map->eql-pull-vector ref-schema)}) :else prop-name)))))))] (let [map-schema (get-map-schema schema)] ;(prn "chidren of schema: " (m/children map-schema)) (mapv entry->pull-item (m/children map-schema)))))
null
https://raw.githubusercontent.com/dvingo/malli-code-gen/8400a2d1f8e21b9de19d33329b225e8bb813c132/src/main/space/matterandvoid/malli_gen/eql_pull.cljc
clojure
maybe a double deref right away? they are equal if they have all the same keys (prn ::pull-vector orig-schema) _ (println "schema type: " (pr-str (m/type schema))) (println "child schema: " child-schema) (println "options: " options) _ (println "orig schema: " (pr-str orig-schema)) (println "not recursve: type " (pr-str child-schema) (schema-type child-schema)) (def x ref-schema) (prn "chidren of schema: " (m/children map-schema))
(ns space.matterandvoid.malli-gen.eql-pull "Generate EQL pull vectors from schemas Like space.matterandvoid.malli-gen.eql but uses options from schema properties EQL reference -query-language/eql#eql-for-selections" (:require [malli.core :as m] [space.matterandvoid.malli-gen.util :as u]) #?(:clj (:import [clojure.lang ExceptionInfo]))) (comment "Main members are:" space.matterandvoid.malli-gen-eql-pull/map->eql-pull-vector "EQL reference") [ 1 ] -query-language/eql#eql-for-selections [ 2 ] Crux pull #pull (defn ->schema "Huh?" [s] (cond-> s (not (m/schema? s)) m/deref)) (defn schema-type [s] (try (m/type (m/deref s)) (catch #?(:clj ExceptionInfo :cljs :error) e (if (= ::m/invalid-schema (:type (ex-data e))) nil (throw e))))) (def composite-schema-types #{:vector :map :sequential :set ::m/schema :and}) (defn is-vec-of-refs? [s] (let [s (m/deref s)] (and (= :vector (m/type s)) (= (count (m/children s)) 1) (u/ref-schema? (first (m/children s)))))) (defn atomic-prop? [prop-name schema] (not (and (composite-schema-types (m/type (m/deref schema))) (is-vec-of-refs? schema)))) (defn get-map-schema-from-seq "Given a seq of schemas, asserts there is only one :map schema and returns that." [s] (let [map-schemas (filter #(= (m/type %) :map) s)] (assert (= (count map-schemas) 1)) (first map-schemas))) (defn get-map-schema [s] s-type (m/type s)] (cond (= :map s-type) s (#{:or :and} s-type) (get-map-schema-from-seq (m/children s))))) (def supported-schema-types #{:map}) need a helper function that takes two schemas which are map schemas , but may be refs - so you deref both first (defn map-schemas-equal? "Treats two map schemas as being equivalent if they have all the same keys in the top level. 'm1' and 'm2' can be literal map schemas or RefSchemas to map schemas, or mix of both." [m1 m2] (let [children1 (map first (m/children (m/deref m1))) children2 (map first (m/children (m/deref m2)))] (= children1 children2))) (defn map->eql-pull-vector "Given a malli schema returns a query vector Does not handle arbitrary schema, your root schema (the one you pass to this function) must be a ':map' schema or an ':and' schema of a ':map'. all [:ref ::other-schema] become EQL joins. Crux pull #pull" [orig-schema] ( println ( apply str ( repeat 80 " - " ) ) ) (let [schema (m/deref orig-schema) {:space.matterandvoid.malli-gen.eql-pull/keys [pull-depth] :or {pull-depth 3}} (m/properties schema) _ (assert (supported-schema-types (m/type schema)) (str "Invalid schema. Supports: " (pr-str supported-schema-types))) entry->pull-item (fn ->pull [entry] (let [[prop-name options child-schema] entry] (if (atomic-prop? prop-name child-schema) prop-name (let [ref-schema (u/ref-coll->reffed child-schema) _ ( println " REF schema : " ( pr - str ref - schema ) ) _ ( println " REF schema get map : " ( pr - str ( get - map - schema ref - schema ) ) ) recursive? (or (map-schemas-equal? ref-schema orig-schema) (map-schemas-equal? (get-map-schema ref-schema) (get-map-schema orig-schema))) #_#__ (println "orig schema get-map: " (pr-str (get-map-schema orig-schema)))] (if recursive? {prop-name pull-depth} (do (cond (= :vector (schema-type child-schema)) (do {prop-name (map->eql-pull-vector ref-schema)}) :else prop-name)))))))] (let [map-schema (get-map-schema schema)] (mapv entry->pull-item (m/children map-schema)))))
bd93c01d3e0f25851fc6612389cf71043ee75da7e84ab2353f11923cd17502b1
fpco/ide-backend
Exception.hs
module Distribution.Compat.Exception ( catchIO, catchExit, tryIO, ) where import System.Exit import qualified Control.Exception as Exception tryIO :: IO a -> IO (Either Exception.IOException a) tryIO = Exception.try catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch catchExit :: IO a -> (ExitCode -> IO a) -> IO a catchExit = Exception.catch
null
https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/TestSuite/inputs/Cabal-1.22.0.0/Distribution/Compat/Exception.hs
haskell
module Distribution.Compat.Exception ( catchIO, catchExit, tryIO, ) where import System.Exit import qualified Control.Exception as Exception tryIO :: IO a -> IO (Either Exception.IOException a) tryIO = Exception.try catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch catchExit :: IO a -> (ExitCode -> IO a) -> IO a catchExit = Exception.catch
ace44772f6599bcdb21838311812870ff3ea1b3724389b6c8bd92ae8fb5d897c
dawidovsky/IIUWr
Wykład.rkt
#lang racket ;; arithmetic expressions (define (const? t) (number? t)) (define (binop? t) (and (list? t) (= (length t) 3) (member (car t) '(+ - * /)))) (define (binop-op e) (car e)) (define (binop-left e) (cadr e)) (define (binop-right e) (caddr e)) (define (binop-cons op l r) (list op l r)) (define (arith-expr? t) (or (const? t) (and (binop? t) (arith-expr? (binop-left t)) (arith-expr? (binop-right t))))) ;; calculator (define (op->proc op) (cond [(eq? op '+) +] [(eq? op '*) *] [(eq? op '-) -] [(eq? op '/) /])) (define (eval-arith e) (cond [(const? e) e] [(binop? e) ((op->proc (binop-op e)) (eval-arith (binop-left e)) (eval-arith (binop-right e)))])) ;; let expressions (define (let-def? t) (and (list? t) (= (length t) 2) (symbol? (car t)))) (define (let-def-var e) (car e)) (define (let-def-expr e) (cadr e)) (define (let-def-cons x e) (list x e)) (define (let? t) (and (list? t) (= (length t) 3) (eq? (car t) 'let) (let-def? (cadr t)))) (define (let-def e) (cadr e)) (define (let-expr e) (caddr e)) (define (let-cons def e) (list 'let def e)) (define (var? t) (symbol? t)) (define (var-var e) e) (define (var-cons x) x) (define (arith/let-expr? t) (or (const? t) (and (binop? t) (arith/let-expr? (binop-left t)) (arith/let-expr? (binop-right t))) (and (let? t) (arith/let-expr? (let-expr t)) (arith/let-expr? (let-def (let-def-expr t)))) (var? t))) ;; evalation via substitution (define (subst e x f) (cond [(const? e) e] [(binop? e) (binop-cons (binop-op e) (subst (binop-left e) x f) (subst (binop-right e) x f))] [(let? e) (let-cons (let-def-cons (let-def-var (let-def e)) (subst (let-def-expr (let-def e)) x f)) (if (eq? x (let-def-var (let-def e))) (let-expr e) (subst (let-expr e) x f)))] [(var? e) (if (eq? x (var-var e)) f (var-var e))])) (define (eval-subst e) (cond [(const? e) e] [(binop? e) ((op->proc (binop-op e)) (eval-subst (binop-left e)) (eval-subst (binop-right e)))] [(let? e) (eval-subst (subst (let-expr e) (let-def-var (let-def e)) (eval-subst (let-def-expr (let-def e)))))] [(var? e) (error "undefined variable" (var-var e))])) ;; evaluation via environments (define empty-env null) (define (add-to-env x v env) (cons (list x v) env)) (define (find-in-env x env) (cond [(null? env) (error "undefined variable" x)] [(eq? x (caar env)) (cadar env)] [else (find-in-env x (cdr env))])) (define (eval-env e env) (cond [(const? e) e] [(binop? e) ((op->proc (binop-op e)) (eval-env (binop-left e) env) (eval-env (binop-right e) env))] [(let? e) (eval-env (let-expr e) (env-for-let (let-def e) env))] [(var? e) (find-in-env (var-var e) env)])) (define (env-for-let def env) (add-to-env (let-def-var def) (eval-env (let-def-expr def) env) env)) (define (eval e) (eval-env e empty-env))
null
https://raw.githubusercontent.com/dawidovsky/IIUWr/73f0f65fb141f82a05dac2573f39f6fa48a81409/MP/Pracownia6/Wyk%C5%82ad.rkt
racket
arithmetic expressions calculator let expressions evalation via substitution evaluation via environments
#lang racket (define (const? t) (number? t)) (define (binop? t) (and (list? t) (= (length t) 3) (member (car t) '(+ - * /)))) (define (binop-op e) (car e)) (define (binop-left e) (cadr e)) (define (binop-right e) (caddr e)) (define (binop-cons op l r) (list op l r)) (define (arith-expr? t) (or (const? t) (and (binop? t) (arith-expr? (binop-left t)) (arith-expr? (binop-right t))))) (define (op->proc op) (cond [(eq? op '+) +] [(eq? op '*) *] [(eq? op '-) -] [(eq? op '/) /])) (define (eval-arith e) (cond [(const? e) e] [(binop? e) ((op->proc (binop-op e)) (eval-arith (binop-left e)) (eval-arith (binop-right e)))])) (define (let-def? t) (and (list? t) (= (length t) 2) (symbol? (car t)))) (define (let-def-var e) (car e)) (define (let-def-expr e) (cadr e)) (define (let-def-cons x e) (list x e)) (define (let? t) (and (list? t) (= (length t) 3) (eq? (car t) 'let) (let-def? (cadr t)))) (define (let-def e) (cadr e)) (define (let-expr e) (caddr e)) (define (let-cons def e) (list 'let def e)) (define (var? t) (symbol? t)) (define (var-var e) e) (define (var-cons x) x) (define (arith/let-expr? t) (or (const? t) (and (binop? t) (arith/let-expr? (binop-left t)) (arith/let-expr? (binop-right t))) (and (let? t) (arith/let-expr? (let-expr t)) (arith/let-expr? (let-def (let-def-expr t)))) (var? t))) (define (subst e x f) (cond [(const? e) e] [(binop? e) (binop-cons (binop-op e) (subst (binop-left e) x f) (subst (binop-right e) x f))] [(let? e) (let-cons (let-def-cons (let-def-var (let-def e)) (subst (let-def-expr (let-def e)) x f)) (if (eq? x (let-def-var (let-def e))) (let-expr e) (subst (let-expr e) x f)))] [(var? e) (if (eq? x (var-var e)) f (var-var e))])) (define (eval-subst e) (cond [(const? e) e] [(binop? e) ((op->proc (binop-op e)) (eval-subst (binop-left e)) (eval-subst (binop-right e)))] [(let? e) (eval-subst (subst (let-expr e) (let-def-var (let-def e)) (eval-subst (let-def-expr (let-def e)))))] [(var? e) (error "undefined variable" (var-var e))])) (define empty-env null) (define (add-to-env x v env) (cons (list x v) env)) (define (find-in-env x env) (cond [(null? env) (error "undefined variable" x)] [(eq? x (caar env)) (cadar env)] [else (find-in-env x (cdr env))])) (define (eval-env e env) (cond [(const? e) e] [(binop? e) ((op->proc (binop-op e)) (eval-env (binop-left e) env) (eval-env (binop-right e) env))] [(let? e) (eval-env (let-expr e) (env-for-let (let-def e) env))] [(var? e) (find-in-env (var-var e) env)])) (define (env-for-let def env) (add-to-env (let-def-var def) (eval-env (let-def-expr def) env) env)) (define (eval e) (eval-env e empty-env))
c81f07937d70efe6eafc8285527c7ebb17dcdbc7202f7f67ac19400cfc254b34
fortytools/holumbus
UserInterface.hs
-- ---------------------------------------------------------------------------- | Module : Holumbus . MapReduce . UserInterface Copyright : Copyright ( C ) 2008 License : MIT Maintainer : ( ) Stability : experimental Portability : portable Version : 0.1 Module : Holumbus.MapReduce.UserInterface Copyright : Copyright (C) 2008 Stefan Schmidt License : MIT Maintainer : Stefan Schmidt () Stability : experimental Portability: portable Version : 0.1 -} -- ---------------------------------------------------------------------------- module Holumbus.MapReduce.UserInterface ( -- * operations runUI ) where import Data.Maybe import Holumbus.Common.Utils ( handleAll ) import Holumbus.Common.FileHandling import qualified Holumbus.Common.Debug as DEBUG import qualified Holumbus.Console.Console as Console import qualified Holumbus.MapReduce.MapReduce as MR import qualified Holumbus.MapReduce.Types as T -- ---------------------------------------------------------------------------- Operations -- ---------------------------------------------------------------------------- -- | runs the user interface... just add an fileSystem an a fancy version-number runUI :: (MR.MapReduce mr) => mr -> String -> IO () runUI mr version = do -- starts the console with the specified commands Console.handleUserInput (createConsole version) mr -- ---------------------------------------------------------------------------- -- private functions -- ---------------------------------------------------------------------------- createConsole :: (MR.MapReduce mr) => String -> Console.ConsoleData mr createConsole version = Console.addConsoleCommand "site" getMySiteId "" $ Console.addConsoleCommand "mrtype" getMapReduceType "" $ Console.addConsoleCommand "startC" startControlling "" $ Console.addConsoleCommand "stopC" stopControlling "" $ Console.addConsoleCommand "isC" isControlling "" $ Console.addConsoleCommand "step" doSingleStep "" $ Console.addConsoleCommand "mrJob" doMapReduceJob "" $ Console.addConsoleCommand "parse" parseJob "" $ Console.addConsoleCommand "debug" printDebug "" $ Console.addConsoleCommand "version" (printVersion version) "prints the version" $ Console.initializeConsole getMySiteId :: (MR.MapReduce mr) => mr -> [String] -> IO () getMySiteId mr _ = handleAll (\e -> putStrLn $ show e) $ do s <- MR.getMySiteId mr putStrLn $ show s getMapReduceType :: (MR.MapReduce mr) => mr -> [String] -> IO () getMapReduceType mr _ = handleAll (\e -> putStrLn $ show e) $ do t <- MR.getMapReduceType mr putStrLn $ show t startControlling :: (MR.MapReduce mr) => mr -> [String] -> IO () startControlling mr _ = handleAll (\e -> putStrLn $ show e) $ do MR.startControlling mr stopControlling :: (MR.MapReduce mr) => mr -> [String] -> IO () stopControlling mr _ = handleAll (\e -> putStrLn $ show e) $ do MR.stopControlling mr isControlling :: (MR.MapReduce mr) => mr -> [String] -> IO () isControlling mr _ = handleAll (\e -> putStrLn $ show e) $ do b <- MR.isControlling mr putStrLn $ show b doSingleStep :: (MR.MapReduce mr) => mr -> [String] -> IO () doSingleStep mr _ = handleAll (\e -> putStrLn $ show e) $ do MR.doSingleStep mr doMapReduceJob :: (MR.MapReduce mr) => mr -> [String] -> IO () doMapReduceJob mr opts = do handleAll (\e -> putStrLn $ show e) $ do (mbName,_) <- Console.nextOption opts jobInfo <- (loadFromXmlFile (fromJust mbName))::IO T.JobInfo r <- MR.doMapReduceJob jobInfo mr putStrLn "RESULT:" putStrLn $ show r return () parseJob :: (MR.MapReduce mr) => mr -> [String] -> IO () parseJob _ opts = do handleAll (\e -> putStrLn $ show e) $ do (mbName,_) <- Console.nextOption opts jobInfo <- (loadFromXmlFile (fromJust mbName))::IO T.JobInfo putStrLn $ show jobInfo return () printDebug :: (MR.MapReduce mr) => mr -> [String] -> IO () printDebug mr _ = do handleAll (\e -> putStrLn $ show e) $ do DEBUG.printDebug mr printVersion :: (MR.MapReduce mr) => String -> mr -> [String] -> IO () printVersion version _ _ = do putStrLn version
null
https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/mapreduce/source/Holumbus/MapReduce/UserInterface.hs
haskell
---------------------------------------------------------------------------- ---------------------------------------------------------------------------- * operations ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- | runs the user interface... just add an fileSystem an a fancy version-number starts the console with the specified commands ---------------------------------------------------------------------------- private functions ----------------------------------------------------------------------------
| Module : Holumbus . MapReduce . UserInterface Copyright : Copyright ( C ) 2008 License : MIT Maintainer : ( ) Stability : experimental Portability : portable Version : 0.1 Module : Holumbus.MapReduce.UserInterface Copyright : Copyright (C) 2008 Stefan Schmidt License : MIT Maintainer : Stefan Schmidt () Stability : experimental Portability: portable Version : 0.1 -} module Holumbus.MapReduce.UserInterface ( runUI ) where import Data.Maybe import Holumbus.Common.Utils ( handleAll ) import Holumbus.Common.FileHandling import qualified Holumbus.Common.Debug as DEBUG import qualified Holumbus.Console.Console as Console import qualified Holumbus.MapReduce.MapReduce as MR import qualified Holumbus.MapReduce.Types as T Operations runUI :: (MR.MapReduce mr) => mr -> String -> IO () runUI mr version = do Console.handleUserInput (createConsole version) mr createConsole :: (MR.MapReduce mr) => String -> Console.ConsoleData mr createConsole version = Console.addConsoleCommand "site" getMySiteId "" $ Console.addConsoleCommand "mrtype" getMapReduceType "" $ Console.addConsoleCommand "startC" startControlling "" $ Console.addConsoleCommand "stopC" stopControlling "" $ Console.addConsoleCommand "isC" isControlling "" $ Console.addConsoleCommand "step" doSingleStep "" $ Console.addConsoleCommand "mrJob" doMapReduceJob "" $ Console.addConsoleCommand "parse" parseJob "" $ Console.addConsoleCommand "debug" printDebug "" $ Console.addConsoleCommand "version" (printVersion version) "prints the version" $ Console.initializeConsole getMySiteId :: (MR.MapReduce mr) => mr -> [String] -> IO () getMySiteId mr _ = handleAll (\e -> putStrLn $ show e) $ do s <- MR.getMySiteId mr putStrLn $ show s getMapReduceType :: (MR.MapReduce mr) => mr -> [String] -> IO () getMapReduceType mr _ = handleAll (\e -> putStrLn $ show e) $ do t <- MR.getMapReduceType mr putStrLn $ show t startControlling :: (MR.MapReduce mr) => mr -> [String] -> IO () startControlling mr _ = handleAll (\e -> putStrLn $ show e) $ do MR.startControlling mr stopControlling :: (MR.MapReduce mr) => mr -> [String] -> IO () stopControlling mr _ = handleAll (\e -> putStrLn $ show e) $ do MR.stopControlling mr isControlling :: (MR.MapReduce mr) => mr -> [String] -> IO () isControlling mr _ = handleAll (\e -> putStrLn $ show e) $ do b <- MR.isControlling mr putStrLn $ show b doSingleStep :: (MR.MapReduce mr) => mr -> [String] -> IO () doSingleStep mr _ = handleAll (\e -> putStrLn $ show e) $ do MR.doSingleStep mr doMapReduceJob :: (MR.MapReduce mr) => mr -> [String] -> IO () doMapReduceJob mr opts = do handleAll (\e -> putStrLn $ show e) $ do (mbName,_) <- Console.nextOption opts jobInfo <- (loadFromXmlFile (fromJust mbName))::IO T.JobInfo r <- MR.doMapReduceJob jobInfo mr putStrLn "RESULT:" putStrLn $ show r return () parseJob :: (MR.MapReduce mr) => mr -> [String] -> IO () parseJob _ opts = do handleAll (\e -> putStrLn $ show e) $ do (mbName,_) <- Console.nextOption opts jobInfo <- (loadFromXmlFile (fromJust mbName))::IO T.JobInfo putStrLn $ show jobInfo return () printDebug :: (MR.MapReduce mr) => mr -> [String] -> IO () printDebug mr _ = do handleAll (\e -> putStrLn $ show e) $ do DEBUG.printDebug mr printVersion :: (MR.MapReduce mr) => String -> mr -> [String] -> IO () printVersion version _ _ = do putStrLn version
98f1ab07556ffd8be6dbb9bde9a343bda8f79fd44914ef344460db4b8d4de4cc
mpieva/biohazard-tools
PriorityQueue.hs
module PriorityQueue ( Sized(..), PQ_Conf(..), PQ, makePQ, closePQ, enqueuePQ, viewMinPQ, sizePQ, listToPQ, pqToList, ByQName(..), byQName, ByMatePos(..), BySelfPos(..), br_qname, br_mate_pos, br_self_pos, br_copy ) where import Bio.Prelude import Bio.Bam hiding ( Stream ) import Data.Binary ( Binary, get, put ) import Data.Binary.Get ( runGetOrFail ) import Data.Binary.Put ( execPut ) import Foreign.C.Error ( throwErrnoIfMinus1 ) import Foreign.C.String ( withCAString ) import Foreign.C.Types ( CChar(..), CInt(..), CSize(..) ) import System.IO ( SeekMode(RelativeSeek) ) import qualified Data.ByteString as S import qualified Data.ByteString.Builder.Internal as B import qualified Data.ByteString.Internal as S ( createAndTrim ) import qualified Data.ByteString.Unsafe as S ( unsafeUseAsCStringLen ) import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as L ( ByteString(..) ) -- | A Priority Queue that can fall back to external storage. -- -- Note that such a Priority Queue automatically gives rise to an -- external sorting algorithm: enqueue everything, dequeue until empty. -- -- Whatever is to be stored in this queue needs to be in 'Binary', -- because it may need to be moved to external storage on demand. We -- also need a way to estimate the memory consumption of an enqueued object . When constructing the queue , the maximum amount of RAM to -- consume is set. Note that open input streams use memory for -- buffering, too, this should be taken into account, at least -- approximately. -- -- Enqueued objects are kept in an in-memory heap until the memory -- consumption becomes too high. At that point, the whole heap is -- sorted and dumped to external storage. If necessary, the file to do -- so is created and kept open. The newly created stream is added to a -- heap so that dequeueing objects amounts to performing a merge sort on -- multiple external streams. If too many streams are open, we do exactly that : merge - sort all streams in one generation into a single -- stream in the next generation. The discrete generations ensure that -- merging handles streams of roughly equal length. To conserve on file -- descriptors, we concatenate multiple streams into a single file, then use pread(2 ) on that as appropriate . This way , we need only one file -- descriptor per generation. -- -- A generic way to decide when too many streams are open or how much memory we can afford to use would be nice . That first condition is -- reached when seeking takes about as much time as reading (which -- depends on buffer size and system characteristics), so that an additional merge pass becomes economical . The second condition not -- only depends on how much memory we have, but also on how much we will -- use for the merging logic. Right now, both are just a parameter. data PQ_Conf = PQ_Conf { max_mb :: Int, -- ^ memory limit max_merge :: Int, -- ^ fan-in limit temp_path :: FilePath, -- ^ path to temporary files croak :: String -> IO () } data PQ a = PQ { heap :: !(SkewHeap a) -- generation 0 (in RAM) approx . size of gen 0 , sizePQ :: !Int -- number of items in total , spills :: [( Fd, SkewHeap (Stream a) )] } deriving Show -- | Things that have a (conservative) size estimate. Doesn't need to -- be accurate, it's used to decide when to spill to external memory. class Binary a => Sized a where usedBytes :: a -> Int -- For testing purposes. instance Sized Int where usedBytes _ = 8 -- | Creates a priority queue. Note that the priority queue creates -- files, which will only be cleaned up if deletePQ is called. makePQ :: (Ord a, Sized a) => PQ a makePQ = PQ Empty 0 0 [] | Closes open file descriptors . There is only one way file descriptors become detectably unused , which is when we migrate one generation of temporary streams to the next . In this case , the ' Fd ' is closed . Therefore , when we are done with a PQ , we have to close these file handles manually . ( Naturally , the ' PQ ' can no longer be -- used after calling this.) closePQ :: PQ a -> IO () closePQ = mapM_ (closeFd . fst) . spills -- | Enqueues an element. -- This operation may result in the creation of a file or in an enormous -- merge of already created files. enqueuePQ :: (Ord a, Sized a) => PQ_Conf -> a -> PQ a -> IO (PQ a) enqueuePQ cfg a (PQ p s c ss) = do let !msz = 1000000 * max_mb cfg !s' = s + usedBytes a !pq' = PQ (insertH a p) s' (succ c) ss if s' >= msz then flushPQ cfg pq' else return pq' listToPQ :: (Ord a, Sized a) => PQ_Conf -> [a] -> IO (PQ a) listToPQ cfg = foldM (flip (enqueuePQ cfg)) makePQ | Takes 99 % of the in - memory portion of the PQ and flushes it to -- generation one in external storage. flushPQ :: (Ord a, Sized a) => PQ_Conf -> PQ a -> IO (PQ a) flushPQ cfg PQ{..} = do croak cfg "Spilling memory to gen 0." let msz = 10000 * max_mb cfg (sheap, ssize, lheap) = splitH msz Empty 0 heap spills' <- spillTo cfg 0 (heapToList lheap) spills return $! PQ sheap ssize sizePQ spills' where We take up to 1 % of the maximum size off generation 0 and make that the -- new generation 0. The remainder is flushed. The idea is that the next -- items may be extracted soon, so it wouldn't pay to flush them. splitH msz sh ssz h = case viewMin h of Just (b,h') | usedBytes b + ssz < msz -> splitH msz (insertH b sh) (usedBytes b + ssz) h' _ -> (sh, ssz, h) -- Spill a list of thingies to external storage. A list of generations of external spills is supplied . We always spill to the first -- generation by appending to the 'Fd' and creating a new stream that is -- added to the 'SkewHeap'. If the list is empty, we have to create the first generation spill . -- After spilling , we check if the first generation overflowed . If -- so, we merge by spilling it to the tail of the list and recreating a new , empty first generation . spillTo :: (Ord a, Sized a) => PQ_Conf -> Int -> [a] -> [( Fd, SkewHeap (Stream a) )] -> IO [( Fd, SkewHeap (Stream a) )] spillTo cfg g as [ ] = mkEmptySpill cfg >>= spillTo cfg g as . (:[]) spillTo cfg g as (( fd, streams ) : spills ) = do str <- externalize fd . foldMap (execPut . put) $ as let streams' = insertH (decodeStream str) streams pos <- fdSeek fd RelativeSeek 0 croak cfg $ "Gen " ++ shows g " has " ++ shows (sizeH streams') " streams (fd " ++ shows fd ", " ++ shows (pos `shiftR` 20) "MB)." if sizeH streams' == max_merge cfg then do croak cfg $ "Spilling gen " ++ shows g " to gen " ++ shows (succ g) "." (:) <$> mkEmptySpill cfg <*> spillTo cfg (succ g) (unfoldr viewMinS streams') spills <* closeFd fd else return (( fd, streams' ) : spills ) mkEmptySpill :: PQ_Conf -> IO ( Fd, SkewHeap (Stream a) ) mkEmptySpill cfg = do pn <- getProgName fd <- withCAString (temp_path cfg ++ "/" ++ pn ++ "-XXXXXX") $ \p -> throwErrnoIfMinus1 "mkstemp" (mkstemp p) <* unlink p return ( fd, Empty ) -- | Creates a disk backed stream from a heap. The heap is unravelled -- in ascending order and written to a new segment in a temporary file. -- That segment is then converted back to a lazy bytestring, which is -- returned. (Yes, evil lazy IO.) externalize :: Fd -> B.Builder -> IO L.ByteString externalize fd s = do pos0 <- fdSeek fd RelativeSeek 0 fdPutLazy fd $ lz4 $ B.toLazyByteStringWith (B.untrimmedStrategy lz4_bsize lz4_bsize) L.empty s pos1 <- fdSeek fd RelativeSeek 0 unLz4 <$> fdGetLazy fd pos0 pos1 fdGetLazy :: Fd -> FileOffset -> FileOffset -> IO L.ByteString fdGetLazy fd p0 p1 | p0 == p1 = return L.empty | otherwise = do let len = (p1-p0) `min` (1024*1024) str <- S.createAndTrim (fromIntegral len) $ \p -> fmap fromIntegral $ throwErrnoIfMinus1 "pread" $ pread fd p (fromIntegral len) p0 L.Chunk str <$> unsafeInterleaveIO (fdGetLazy fd (p0 + fromIntegral (S.length str)) p1) foreign import ccall unsafe "stdlib.h mkstemp" mkstemp :: Ptr CChar -> IO Fd foreign import ccall unsafe "unistd.h unlink" unlink :: Ptr CChar -> IO CInt foreign import ccall unsafe "unistd.h pread" pread :: Fd -> Ptr a -> CSize -> FileOffset -> IO CSsize testList :: Ord a => [a] -> [a] testList (a:b:cs) | a <= b = a : testList (b:cs) | otherwise = error "sorting violated?!" testList [a] = [a] testList [ ] = [ ] decodeStream :: Binary a => L.ByteString -> Stream a decodeStream = go where go s | L.null s = Nil go s = case runGetOrFail get s of Left ( _rest, _consumed, err ) -> error err Right ( rest, _consumed, !a ) -> Cons a (decodeStream rest) viewMinPQ :: (Ord a, Sized a) => PQ a -> Maybe (a, PQ a) viewMinPQ PQ{..} = case viewMinL spills of Just (a, ss') -> case viewMin heap of Just (b, h') | b <= a -> Just (b, PQ h' (heap_size - usedBytes b) (pred sizePQ) spills) _ -> Just (a, PQ heap heap_size (pred sizePQ) ss') Nothing -> case viewMin heap of Just (b ,h') -> Just (b, PQ h' (heap_size - usedBytes b) (pred sizePQ) spills) Nothing -> Nothing viewMinL :: Ord a => [( Fd, SkewHeap (Stream a) )] -> Maybe (a, [( Fd, SkewHeap (Stream a) )]) viewMinL = minimumM . each where each [ ] = [ ] each ( (fd,hp) : xs ) = case viewMinS hp of Nothing -> k Just (a, hp') -> (a, (fd, hp') : xs) : k where k = [ (a, (fd,hp):xs') | (a,xs') <- each xs ] minimumM [] = Nothing minimumM xs = Just $ minimumBy (comparing fst) xs pqToList :: (Ord a, Sized a, Show a) => PQ a -> [a] pqToList = testList . unfoldr viewMinPQ -- We need an in-memory priority queue. Here's a skew heap. data SkewHeap a = Empty | Node a (SkewHeap a) (SkewHeap a) deriving Show singleton :: a -> SkewHeap a singleton x = Node x Empty Empty unionH :: Ord a => SkewHeap a -> SkewHeap a -> SkewHeap a Empty `unionH` t2 = t2 t1 `unionH` Empty = t1 t1@(Node x1 l1 r1) `unionH` t2@(Node x2 l2 r2) | x1 <= x2 = Node x1 (t2 `unionH` r1) l1 | otherwise = Node x2 (t1 `unionH` r2) l2 insertH :: Ord a => a -> SkewHeap a -> SkewHeap a insertH x heap = singleton x `unionH` heap viewMin :: Ord a => SkewHeap a -> Maybe (a, SkewHeap a) viewMin Empty = Nothing viewMin (Node x l r) = Just (x, unionH l r) viewMinS :: Ord a => SkewHeap (Stream a) -> Maybe (a, SkewHeap (Stream a)) viewMinS h = case viewMin h of Nothing -> Nothing Just (Nil , _) -> error "WTF?!" Just (Cons a Nil, h') -> Just (a, h') Just (Cons a s, h') -> Just (a, insertH s h') sizeH :: SkewHeap a -> Int sizeH Empty = 0 sizeH (Node _ l r) = sizeH l + sizeH r + 1 heapToList :: (Binary a, Ord a) => SkewHeap a -> [a] heapToList = unfoldr viewMin data Stream a = Nil | Cons !a (Stream a) deriving Show Streams are ordered by looking at just the first item . instance Eq a => Eq (Stream a) where Cons a _ == Cons b _ = a == b Nil == Nil = True _ == _ = False instance Ord a => Ord (Stream a) where Nil `compare` Nil = EQ Nil `compare` Cons _ _ = LT Cons _ _ `compare` Nil = GT Cons a _ `compare` Cons b _ = compare a b lz4_bsize, lz4_csize :: Int lz4_bsize = 16*1024*1024 - 128 lz4_csize = 16*1000*1000 -- We just compress and frame each 'Chunk' individually. -- 'toLazyByteStringWith' should give us 'Chunk's of reasonable size; -- but we enforce a maximum size to make decompression easier. lz4 :: L.ByteString -> L.ByteString lz4 = L.foldrChunks go L.empty where go s | S.null s = id | S.length s > lz4_csize = go (S.take lz4_csize s) . go (S.drop lz4_csize s) | otherwise = L.Chunk . unsafePerformIO $ S.createAndTrim lz4_bsize $ \pdest -> S.unsafeUseAsCStringLen s $ \(psrc,srcLen) -> do dLen <- c_lz4 psrc (plusPtr pdest 4) (fromIntegral srcLen) (fromIntegral lz4_bsize) -- place compressed size at beginning (slow and portable) pokeByteOff pdest 0 (fromIntegral (dLen `shiftR` 0) :: Word8) pokeByteOff pdest 1 (fromIntegral (dLen `shiftR` 8) :: Word8) pokeByteOff pdest 2 (fromIntegral (dLen `shiftR` 16) :: Word8) pokeByteOff pdest 3 (fromIntegral (dLen `shiftR` 24) :: Word8) return $ fromIntegral dLen + 4 foreign import ccall unsafe "lz4.h LZ4_compress_default" c_lz4 :: Ptr CChar -- source -> Ptr CChar -- dest -> CInt -- sourceSize -> CInt -- maxDestSize -> IO CInt -- number of bytes written unLz4 :: L.ByteString -> L.ByteString unLz4 s | L.null s = L.empty | otherwise = L.Chunk ck' . unLz4 $ L.drop (l+4) s where -- size (slow and portable) l = fromIntegral (L.index s 0) `shiftL` 0 .|. fromIntegral (L.index s 1) `shiftL` 8 .|. fromIntegral (L.index s 2) `shiftL` 16 .|. fromIntegral (L.index s 3) `shiftL` 24 ck = L.toStrict $ L.take (l+4) s ck' = unsafePerformIO $ S.createAndTrim lz4_bsize $ \pdst -> S.unsafeUseAsCStringLen ck $ \(psrc,srcLen) -> fromIntegral <$> c_unlz4 (plusPtr psrc 4) pdst (fromIntegral srcLen - 4) (fromIntegral lz4_bsize) foreign import ccall unsafe "lz4.h LZ4_decompress_safe" c_unlz4 :: Ptr CChar -- source -> Ptr Word8 -- dest -> CInt -- sourceSize -> CInt -- maxDestSize -> IO CInt -- number of bytes written data ByQName = ByQName { _bq_hash :: !Int , _bq_alnid :: !Int , _bq_rec :: !BamRaw } Note on XI : this is * not * the index read ( MPI EVAN convention ) , but -- the number of the alignment (Segemehl convention, I believe). -- Fortunately, the index is never numeric, so this is reasonably safe. byQName :: BamRaw -> ByQName byQName b = ByQName (hash $ br_qname b) (extAsInt 0 "XI" $ unpackBam b) b instance Eq ByQName where ByQName ah ai a == ByQName bh bi b = (ah, ai, br_qname a) == (bh, bi, br_qname b) instance Ord ByQName where ByQName ah ai a `compare` ByQName bh bi b = (ah, ai, b_qname (unpackBam a)) `compare` (bh, bi, b_qname (unpackBam b)) newtype ByMatePos = ByMatePos BamRaw instance Eq ByMatePos where ByMatePos a == ByMatePos b = br_mate_pos a == br_mate_pos b instance Ord ByMatePos where ByMatePos a `compare` ByMatePos b = br_mate_pos a `compare` br_mate_pos b newtype BySelfPos = BySelfPos BamRaw instance Eq BySelfPos where BySelfPos a == BySelfPos b = br_self_pos a == br_self_pos b instance Ord BySelfPos where BySelfPos a `compare` BySelfPos b = br_self_pos a `compare` br_self_pos b instance Binary ByQName where put (ByQName _ _ r) = put (raw_data r) ; get = byQName . bamRaw 0 <$> get instance Binary ByMatePos where put (ByMatePos r) = put (raw_data r) ; get = ByMatePos . bamRaw 0 <$> get instance Binary BySelfPos where put (BySelfPos r) = put (raw_data r) ; get = BySelfPos . bamRaw 0 <$> get instance Sized ByQName where usedBytes (ByQName _ _ r) = S.length (raw_data r) + 80 instance Sized ByMatePos where usedBytes (ByMatePos r) = S.length (raw_data r) + 64 instance Sized BySelfPos where usedBytes (BySelfPos r) = S.length (raw_data r) + 64 br_qname :: BamRaw -> Seqid br_qname = b_qname . unpackBam br_mate_pos :: BamRaw -> (Refseq, Int) br_mate_pos = (b_mrnm &&& b_mpos) . unpackBam br_self_pos :: BamRaw -> (Refseq, Int) br_self_pos = (b_rname &&& b_pos) . unpackBam br_copy :: BamRaw -> BamRaw br_copy br = bamRaw (virt_offset br) $! S.copy (raw_data br)
null
https://raw.githubusercontent.com/mpieva/biohazard-tools/93959b6ad0dde2a760559fe82853ab78497f0452/src/PriorityQueue.hs
haskell
| A Priority Queue that can fall back to external storage. Note that such a Priority Queue automatically gives rise to an external sorting algorithm: enqueue everything, dequeue until empty. Whatever is to be stored in this queue needs to be in 'Binary', because it may need to be moved to external storage on demand. We also need a way to estimate the memory consumption of an enqueued consume is set. Note that open input streams use memory for buffering, too, this should be taken into account, at least approximately. Enqueued objects are kept in an in-memory heap until the memory consumption becomes too high. At that point, the whole heap is sorted and dumped to external storage. If necessary, the file to do so is created and kept open. The newly created stream is added to a heap so that dequeueing objects amounts to performing a merge sort on multiple external streams. If too many streams are open, we do stream in the next generation. The discrete generations ensure that merging handles streams of roughly equal length. To conserve on file descriptors, we concatenate multiple streams into a single file, then descriptor per generation. A generic way to decide when too many streams are open or how much reached when seeking takes about as much time as reading (which depends on buffer size and system characteristics), so that an only depends on how much memory we have, but also on how much we will use for the merging logic. Right now, both are just a parameter. ^ memory limit ^ fan-in limit ^ path to temporary files generation 0 (in RAM) number of items in total | Things that have a (conservative) size estimate. Doesn't need to be accurate, it's used to decide when to spill to external memory. For testing purposes. | Creates a priority queue. Note that the priority queue creates files, which will only be cleaned up if deletePQ is called. used after calling this.) | Enqueues an element. This operation may result in the creation of a file or in an enormous merge of already created files. generation one in external storage. new generation 0. The remainder is flushed. The idea is that the next items may be extracted soon, so it wouldn't pay to flush them. Spill a list of thingies to external storage. A list of generations generation by appending to the 'Fd' and creating a new stream that is added to the 'SkewHeap'. If the list is empty, we have to create the so, we merge by spilling it to the tail of the list and recreating a | Creates a disk backed stream from a heap. The heap is unravelled in ascending order and written to a new segment in a temporary file. That segment is then converted back to a lazy bytestring, which is returned. (Yes, evil lazy IO.) We need an in-memory priority queue. Here's a skew heap. We just compress and frame each 'Chunk' individually. 'toLazyByteStringWith' should give us 'Chunk's of reasonable size; but we enforce a maximum size to make decompression easier. place compressed size at beginning (slow and portable) source dest sourceSize maxDestSize number of bytes written size (slow and portable) source dest sourceSize maxDestSize number of bytes written the number of the alignment (Segemehl convention, I believe). Fortunately, the index is never numeric, so this is reasonably safe.
module PriorityQueue ( Sized(..), PQ_Conf(..), PQ, makePQ, closePQ, enqueuePQ, viewMinPQ, sizePQ, listToPQ, pqToList, ByQName(..), byQName, ByMatePos(..), BySelfPos(..), br_qname, br_mate_pos, br_self_pos, br_copy ) where import Bio.Prelude import Bio.Bam hiding ( Stream ) import Data.Binary ( Binary, get, put ) import Data.Binary.Get ( runGetOrFail ) import Data.Binary.Put ( execPut ) import Foreign.C.Error ( throwErrnoIfMinus1 ) import Foreign.C.String ( withCAString ) import Foreign.C.Types ( CChar(..), CInt(..), CSize(..) ) import System.IO ( SeekMode(RelativeSeek) ) import qualified Data.ByteString as S import qualified Data.ByteString.Builder.Internal as B import qualified Data.ByteString.Internal as S ( createAndTrim ) import qualified Data.ByteString.Unsafe as S ( unsafeUseAsCStringLen ) import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Internal as L ( ByteString(..) ) object . When constructing the queue , the maximum amount of RAM to exactly that : merge - sort all streams in one generation into a single use pread(2 ) on that as appropriate . This way , we need only one file memory we can afford to use would be nice . That first condition is additional merge pass becomes economical . The second condition not data PQ_Conf = PQ_Conf { croak :: String -> IO () } approx . size of gen 0 , spills :: [( Fd, SkewHeap (Stream a) )] } deriving Show class Binary a => Sized a where usedBytes :: a -> Int instance Sized Int where usedBytes _ = 8 makePQ :: (Ord a, Sized a) => PQ a makePQ = PQ Empty 0 0 [] | Closes open file descriptors . There is only one way file descriptors become detectably unused , which is when we migrate one generation of temporary streams to the next . In this case , the ' Fd ' is closed . Therefore , when we are done with a PQ , we have to close these file handles manually . ( Naturally , the ' PQ ' can no longer be closePQ :: PQ a -> IO () closePQ = mapM_ (closeFd . fst) . spills enqueuePQ :: (Ord a, Sized a) => PQ_Conf -> a -> PQ a -> IO (PQ a) enqueuePQ cfg a (PQ p s c ss) = do let !msz = 1000000 * max_mb cfg !s' = s + usedBytes a !pq' = PQ (insertH a p) s' (succ c) ss if s' >= msz then flushPQ cfg pq' else return pq' listToPQ :: (Ord a, Sized a) => PQ_Conf -> [a] -> IO (PQ a) listToPQ cfg = foldM (flip (enqueuePQ cfg)) makePQ | Takes 99 % of the in - memory portion of the PQ and flushes it to flushPQ :: (Ord a, Sized a) => PQ_Conf -> PQ a -> IO (PQ a) flushPQ cfg PQ{..} = do croak cfg "Spilling memory to gen 0." let msz = 10000 * max_mb cfg (sheap, ssize, lheap) = splitH msz Empty 0 heap spills' <- spillTo cfg 0 (heapToList lheap) spills return $! PQ sheap ssize sizePQ spills' where We take up to 1 % of the maximum size off generation 0 and make that the splitH msz sh ssz h = case viewMin h of Just (b,h') | usedBytes b + ssz < msz -> splitH msz (insertH b sh) (usedBytes b + ssz) h' _ -> (sh, ssz, h) of external spills is supplied . We always spill to the first first generation spill . After spilling , we check if the first generation overflowed . If new , empty first generation . spillTo :: (Ord a, Sized a) => PQ_Conf -> Int -> [a] -> [( Fd, SkewHeap (Stream a) )] -> IO [( Fd, SkewHeap (Stream a) )] spillTo cfg g as [ ] = mkEmptySpill cfg >>= spillTo cfg g as . (:[]) spillTo cfg g as (( fd, streams ) : spills ) = do str <- externalize fd . foldMap (execPut . put) $ as let streams' = insertH (decodeStream str) streams pos <- fdSeek fd RelativeSeek 0 croak cfg $ "Gen " ++ shows g " has " ++ shows (sizeH streams') " streams (fd " ++ shows fd ", " ++ shows (pos `shiftR` 20) "MB)." if sizeH streams' == max_merge cfg then do croak cfg $ "Spilling gen " ++ shows g " to gen " ++ shows (succ g) "." (:) <$> mkEmptySpill cfg <*> spillTo cfg (succ g) (unfoldr viewMinS streams') spills <* closeFd fd else return (( fd, streams' ) : spills ) mkEmptySpill :: PQ_Conf -> IO ( Fd, SkewHeap (Stream a) ) mkEmptySpill cfg = do pn <- getProgName fd <- withCAString (temp_path cfg ++ "/" ++ pn ++ "-XXXXXX") $ \p -> throwErrnoIfMinus1 "mkstemp" (mkstemp p) <* unlink p return ( fd, Empty ) externalize :: Fd -> B.Builder -> IO L.ByteString externalize fd s = do pos0 <- fdSeek fd RelativeSeek 0 fdPutLazy fd $ lz4 $ B.toLazyByteStringWith (B.untrimmedStrategy lz4_bsize lz4_bsize) L.empty s pos1 <- fdSeek fd RelativeSeek 0 unLz4 <$> fdGetLazy fd pos0 pos1 fdGetLazy :: Fd -> FileOffset -> FileOffset -> IO L.ByteString fdGetLazy fd p0 p1 | p0 == p1 = return L.empty | otherwise = do let len = (p1-p0) `min` (1024*1024) str <- S.createAndTrim (fromIntegral len) $ \p -> fmap fromIntegral $ throwErrnoIfMinus1 "pread" $ pread fd p (fromIntegral len) p0 L.Chunk str <$> unsafeInterleaveIO (fdGetLazy fd (p0 + fromIntegral (S.length str)) p1) foreign import ccall unsafe "stdlib.h mkstemp" mkstemp :: Ptr CChar -> IO Fd foreign import ccall unsafe "unistd.h unlink" unlink :: Ptr CChar -> IO CInt foreign import ccall unsafe "unistd.h pread" pread :: Fd -> Ptr a -> CSize -> FileOffset -> IO CSsize testList :: Ord a => [a] -> [a] testList (a:b:cs) | a <= b = a : testList (b:cs) | otherwise = error "sorting violated?!" testList [a] = [a] testList [ ] = [ ] decodeStream :: Binary a => L.ByteString -> Stream a decodeStream = go where go s | L.null s = Nil go s = case runGetOrFail get s of Left ( _rest, _consumed, err ) -> error err Right ( rest, _consumed, !a ) -> Cons a (decodeStream rest) viewMinPQ :: (Ord a, Sized a) => PQ a -> Maybe (a, PQ a) viewMinPQ PQ{..} = case viewMinL spills of Just (a, ss') -> case viewMin heap of Just (b, h') | b <= a -> Just (b, PQ h' (heap_size - usedBytes b) (pred sizePQ) spills) _ -> Just (a, PQ heap heap_size (pred sizePQ) ss') Nothing -> case viewMin heap of Just (b ,h') -> Just (b, PQ h' (heap_size - usedBytes b) (pred sizePQ) spills) Nothing -> Nothing viewMinL :: Ord a => [( Fd, SkewHeap (Stream a) )] -> Maybe (a, [( Fd, SkewHeap (Stream a) )]) viewMinL = minimumM . each where each [ ] = [ ] each ( (fd,hp) : xs ) = case viewMinS hp of Nothing -> k Just (a, hp') -> (a, (fd, hp') : xs) : k where k = [ (a, (fd,hp):xs') | (a,xs') <- each xs ] minimumM [] = Nothing minimumM xs = Just $ minimumBy (comparing fst) xs pqToList :: (Ord a, Sized a, Show a) => PQ a -> [a] pqToList = testList . unfoldr viewMinPQ data SkewHeap a = Empty | Node a (SkewHeap a) (SkewHeap a) deriving Show singleton :: a -> SkewHeap a singleton x = Node x Empty Empty unionH :: Ord a => SkewHeap a -> SkewHeap a -> SkewHeap a Empty `unionH` t2 = t2 t1 `unionH` Empty = t1 t1@(Node x1 l1 r1) `unionH` t2@(Node x2 l2 r2) | x1 <= x2 = Node x1 (t2 `unionH` r1) l1 | otherwise = Node x2 (t1 `unionH` r2) l2 insertH :: Ord a => a -> SkewHeap a -> SkewHeap a insertH x heap = singleton x `unionH` heap viewMin :: Ord a => SkewHeap a -> Maybe (a, SkewHeap a) viewMin Empty = Nothing viewMin (Node x l r) = Just (x, unionH l r) viewMinS :: Ord a => SkewHeap (Stream a) -> Maybe (a, SkewHeap (Stream a)) viewMinS h = case viewMin h of Nothing -> Nothing Just (Nil , _) -> error "WTF?!" Just (Cons a Nil, h') -> Just (a, h') Just (Cons a s, h') -> Just (a, insertH s h') sizeH :: SkewHeap a -> Int sizeH Empty = 0 sizeH (Node _ l r) = sizeH l + sizeH r + 1 heapToList :: (Binary a, Ord a) => SkewHeap a -> [a] heapToList = unfoldr viewMin data Stream a = Nil | Cons !a (Stream a) deriving Show Streams are ordered by looking at just the first item . instance Eq a => Eq (Stream a) where Cons a _ == Cons b _ = a == b Nil == Nil = True _ == _ = False instance Ord a => Ord (Stream a) where Nil `compare` Nil = EQ Nil `compare` Cons _ _ = LT Cons _ _ `compare` Nil = GT Cons a _ `compare` Cons b _ = compare a b lz4_bsize, lz4_csize :: Int lz4_bsize = 16*1024*1024 - 128 lz4_csize = 16*1000*1000 lz4 :: L.ByteString -> L.ByteString lz4 = L.foldrChunks go L.empty where go s | S.null s = id | S.length s > lz4_csize = go (S.take lz4_csize s) . go (S.drop lz4_csize s) | otherwise = L.Chunk . unsafePerformIO $ S.createAndTrim lz4_bsize $ \pdest -> S.unsafeUseAsCStringLen s $ \(psrc,srcLen) -> do dLen <- c_lz4 psrc (plusPtr pdest 4) (fromIntegral srcLen) (fromIntegral lz4_bsize) pokeByteOff pdest 0 (fromIntegral (dLen `shiftR` 0) :: Word8) pokeByteOff pdest 1 (fromIntegral (dLen `shiftR` 8) :: Word8) pokeByteOff pdest 2 (fromIntegral (dLen `shiftR` 16) :: Word8) pokeByteOff pdest 3 (fromIntegral (dLen `shiftR` 24) :: Word8) return $ fromIntegral dLen + 4 foreign import ccall unsafe "lz4.h LZ4_compress_default" unLz4 :: L.ByteString -> L.ByteString unLz4 s | L.null s = L.empty | otherwise = L.Chunk ck' . unLz4 $ L.drop (l+4) s where l = fromIntegral (L.index s 0) `shiftL` 0 .|. fromIntegral (L.index s 1) `shiftL` 8 .|. fromIntegral (L.index s 2) `shiftL` 16 .|. fromIntegral (L.index s 3) `shiftL` 24 ck = L.toStrict $ L.take (l+4) s ck' = unsafePerformIO $ S.createAndTrim lz4_bsize $ \pdst -> S.unsafeUseAsCStringLen ck $ \(psrc,srcLen) -> fromIntegral <$> c_unlz4 (plusPtr psrc 4) pdst (fromIntegral srcLen - 4) (fromIntegral lz4_bsize) foreign import ccall unsafe "lz4.h LZ4_decompress_safe" data ByQName = ByQName { _bq_hash :: !Int , _bq_alnid :: !Int , _bq_rec :: !BamRaw } Note on XI : this is * not * the index read ( MPI EVAN convention ) , but byQName :: BamRaw -> ByQName byQName b = ByQName (hash $ br_qname b) (extAsInt 0 "XI" $ unpackBam b) b instance Eq ByQName where ByQName ah ai a == ByQName bh bi b = (ah, ai, br_qname a) == (bh, bi, br_qname b) instance Ord ByQName where ByQName ah ai a `compare` ByQName bh bi b = (ah, ai, b_qname (unpackBam a)) `compare` (bh, bi, b_qname (unpackBam b)) newtype ByMatePos = ByMatePos BamRaw instance Eq ByMatePos where ByMatePos a == ByMatePos b = br_mate_pos a == br_mate_pos b instance Ord ByMatePos where ByMatePos a `compare` ByMatePos b = br_mate_pos a `compare` br_mate_pos b newtype BySelfPos = BySelfPos BamRaw instance Eq BySelfPos where BySelfPos a == BySelfPos b = br_self_pos a == br_self_pos b instance Ord BySelfPos where BySelfPos a `compare` BySelfPos b = br_self_pos a `compare` br_self_pos b instance Binary ByQName where put (ByQName _ _ r) = put (raw_data r) ; get = byQName . bamRaw 0 <$> get instance Binary ByMatePos where put (ByMatePos r) = put (raw_data r) ; get = ByMatePos . bamRaw 0 <$> get instance Binary BySelfPos where put (BySelfPos r) = put (raw_data r) ; get = BySelfPos . bamRaw 0 <$> get instance Sized ByQName where usedBytes (ByQName _ _ r) = S.length (raw_data r) + 80 instance Sized ByMatePos where usedBytes (ByMatePos r) = S.length (raw_data r) + 64 instance Sized BySelfPos where usedBytes (BySelfPos r) = S.length (raw_data r) + 64 br_qname :: BamRaw -> Seqid br_qname = b_qname . unpackBam br_mate_pos :: BamRaw -> (Refseq, Int) br_mate_pos = (b_mrnm &&& b_mpos) . unpackBam br_self_pos :: BamRaw -> (Refseq, Int) br_self_pos = (b_rname &&& b_pos) . unpackBam br_copy :: BamRaw -> BamRaw br_copy br = bamRaw (virt_offset br) $! S.copy (raw_data br)
6ca2938dcb262ac111c7fc294af8ab7c99a2b32b92fce932026f38173b20f191
BenjaminVanRyseghem/great-things-done
integration.cljs
Copyright ( c ) 2015 , . All rights reserved . ; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns gtd.integration (:use-macros [macro.core :only (for-os)])) (def ^:private osx-mail-applescript "tell application \"Mail\" set _sel to get selection set _links to {} repeat with _msg in _sel set _messageURL to \"message\" & _msg's message id & \"%3e\" set end of _links to _messageURL end repeat set AppleScript's text item delimiters to return end tell return _links") (def ^:private osx-finder-applescript "tell application \"Finder\" set acc to {} set sel to the selection repeat with each in sel set end of acc to URL of each end repeat end tell return acc") (defn- run-applescript [code callback] (let [applescript (js/require "applescript")] (.execString applescript code (fn [err res] (when err (throw (js/Error. (str "Error when performing" code)))) (callback res))))) (defmulti retrieve-current-app-data-osx #(:id %1)) (defmethod retrieve-current-app-data-osx "com.apple.mail" [info callback] (run-applescript osx-mail-applescript callback)) (defmethod retrieve-current-app-data-osx "com.apple.finder" [info callback] (run-applescript osx-finder-applescript callback)) (defn- get-current-app-info-osx "Return info about the current frontmost application on OSX" [] (let [remote (js/require "remote") nodobjc (js/require "nodobjc")] (.framework nodobjc "AppKit") (let [workspace (.NSWorkspace nodobjc "sharedWorkspace") app (workspace "frontmostApplication") app-name (str (app "localizedName")) app-id (str (app "bundleIdentifier"))] {:name app-name :id app-id}))) (defn get-current-app-info [] (for-os "Mac OS X" (get-current-app-info-osx))) (defn ^:export js-get-current-app-info [] (clj->js (get-current-app-info))) (defn get-current-app-data [fun] (let [info (get-current-app-info)] (for-os "Mac OS X" (retrieve-current-app-data-osx info fun)))) (defn ^:export js-get-current-app-data [fun] (clj->js (get-current-app-data fun)))
null
https://raw.githubusercontent.com/BenjaminVanRyseghem/great-things-done/1db9adc871556a347426df842a4f5ea6b3a1b7e0/src/front/gtd/integration.cljs
clojure
The use and distribution terms for this software are covered by the which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) 2015 , . All rights reserved . Eclipse Public License 1.0 ( -1.0.php ) (ns gtd.integration (:use-macros [macro.core :only (for-os)])) (def ^:private osx-mail-applescript "tell application \"Mail\" set _sel to get selection set _links to {} repeat with _msg in _sel set _messageURL to \"message\" & _msg's message id & \"%3e\" set end of _links to _messageURL end repeat set AppleScript's text item delimiters to return end tell return _links") (def ^:private osx-finder-applescript "tell application \"Finder\" set acc to {} set sel to the selection repeat with each in sel set end of acc to URL of each end repeat end tell return acc") (defn- run-applescript [code callback] (let [applescript (js/require "applescript")] (.execString applescript code (fn [err res] (when err (throw (js/Error. (str "Error when performing" code)))) (callback res))))) (defmulti retrieve-current-app-data-osx #(:id %1)) (defmethod retrieve-current-app-data-osx "com.apple.mail" [info callback] (run-applescript osx-mail-applescript callback)) (defmethod retrieve-current-app-data-osx "com.apple.finder" [info callback] (run-applescript osx-finder-applescript callback)) (defn- get-current-app-info-osx "Return info about the current frontmost application on OSX" [] (let [remote (js/require "remote") nodobjc (js/require "nodobjc")] (.framework nodobjc "AppKit") (let [workspace (.NSWorkspace nodobjc "sharedWorkspace") app (workspace "frontmostApplication") app-name (str (app "localizedName")) app-id (str (app "bundleIdentifier"))] {:name app-name :id app-id}))) (defn get-current-app-info [] (for-os "Mac OS X" (get-current-app-info-osx))) (defn ^:export js-get-current-app-info [] (clj->js (get-current-app-info))) (defn get-current-app-data [fun] (let [info (get-current-app-info)] (for-os "Mac OS X" (retrieve-current-app-data-osx info fun)))) (defn ^:export js-get-current-app-data [fun] (clj->js (get-current-app-data fun)))
17c65b569f7f496dc24af9bb916653bca1f90d0d683494b516844392998cae90
clojure/spec-alpha2
spec.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "The spec library specifies the structure of data or functions and provides operations to validate, conform, explain, describe, and generate data based on the specs. Rationale: Guide: "} clojure.alpha.spec (:refer-clojure :exclude [+ * and assert or cat def keys merge comp]) (:require [clojure.alpha.spec.protocols :as protocols :refer [conform* unform* explain* gen* with-gen* describe*]] [clojure.walk :as walk] [clojure.alpha.spec.gen :as gen]) (:import [clojure.alpha.spec.protocols Spec Schema])) (alias 'c 'clojure.core) (alias 'sa 'clojure.spec.alpha) (def ^:dynamic *recursion-limit* "A soft limit on how many times a branching spec (or/alt/*/opt-keys/multi-spec) can be recursed through during generation. After this a non-recursive branch will be chosen." 4) (def ^:dynamic *fspec-iterations* "The number of times an anonymous fn specified by fspec will be (generatively) tested during conform" 21) (def ^:dynamic *coll-check-limit* "The number of elements validated in a collection spec'ed with 'every'" 101) (def ^:dynamic *coll-error-limit* "The number of errors reported by explain in a collection spec'ed with 'every'" 20) (defonce ^:private registry-ref (atom {})) (defn registry "Returns the registry map, prefer 'get-spec' to lookup a spec by name" [] @registry-ref) (defn spec? "returns x if x is a spec object, else logical false" [x] (when (c/or (instance? Spec x) (-> x meta (contains? `conform*))) x)) (defn schema? "Returns x if x is a schema object, else logical false" [x] (instance? Schema x)) (defn get-spec "Returns spec registered for keyword/symbol/var k, or nil." [k] (get (registry) (if (keyword? k) k (symbol k)))) (defn- deep-resolve [reg k] (loop [spec k] (if (ident? spec) (recur (get reg spec)) spec))) (defn- reg-resolve "returns the spec/regex at end of alias chain starting with k, nil if not found, k if k not ident" [k] (if (ident? k) (let [reg @registry-ref spec (get reg k)] (if-not (ident? spec) spec (deep-resolve reg spec))) k)) (defn- reg-resolve! "returns the spec/regex at end of alias chain starting with k, throws if not found, k if k not ident" [k] (if (ident? k) (c/or (reg-resolve k) (throw (Exception. (str "Unable to resolve spec: " k)))) k)) (defn regex? "returns x if x is a (clojure.spec) regex op, else logical false" [x] (c/and (::op x) x)) (defn- with-name [spec name] (cond (ident? spec) spec (regex? spec) (assoc spec ::name name) (instance? clojure.lang.IObj spec) (with-meta spec (assoc (meta spec) ::name name)))) (defn- spec-name [spec] (cond (ident? spec) spec (regex? spec) (::name spec) (instance? clojure.lang.IObj spec) (-> (meta spec) ::name))) (defn invalid? "tests the validity of a conform return value" [ret] (identical? ::invalid ret)) (defn- unfn [expr] (if (c/and (seq? expr) (symbol? (first expr)) (= "fn*" (name (first expr)))) (let [[[s] & form] (rest expr)] (conj (walk/postwalk-replace {s '%} form) '[%] 'fn)) expr)) (defn- res [form] (walk/postwalk #(cond (keyword? %) % (symbol? %) (c/or (some-> % resolve symbol) %) (sequential? %) (unfn %) :else %) form)) (defmulti expand-spec "Create a symbolic spec map from an explicated spec form. This is an extension point for adding new spec ops. Generally, consumers should instead call `resolve-spec`. For anything other than symbolic spec maps, return the same object unchanged." (fn [qform] (when (c/or (list? qform) (seq? qform)) (first qform)))) (defmethod expand-spec :default [o] o) (defmulti create-spec "Create a spec object from an explicated spec map. This is an extension point for adding new spec ops. Generally, consumers should instead call `resolve-spec`." (fn [smap] (when (map? smap) (:clojure.spec/op smap)))) (defmethod create-spec :default [o] o) (defn- pred-impl ([sym] (pred-impl sym nil)) ([sym gfn] (let [pred (deref (find-var sym))] (reify protocols/Spec (conform* [_ x settings-key settings] (let [ret (pred x)] (if ret x ::invalid))) (unform* [_ x] x) (explain* [_ path via in x settings-key settings] (when (not (pred x)) [{:path path :pred sym :val x :via via :in in}])) (gen* [_ _ _ _] (if gfn (gfn) (gen/gen-for-pred pred))) (with-gen* [_ gfn] (pred-impl sym gfn)) (describe* [_] sym))))) (defn- constant-val? [x] (c/or (nil? x) (boolean? x) (number? x) (string? x) (ident? x) (char? x) (c/and (coll? x) (empty? x)) (c/and (c/or (vector? x) (set? x) (map? x)) (every? constant-val? x)))) (defn- set-impl ([set-vals] (set-impl set-vals nil)) ([set-vals gfn] (c/assert (every? constant-val? set-vals) "set specs must contain constant values") (let [pred #(contains? set-vals %)] (reify protocols/Spec (conform* [_ x settings-key settings] (let [ret (pred x)] (if ret x ::invalid))) (unform* [_ x] x) (explain* [_ path via in x settings-key settings] (when (not (pred x)) [{:path path :pred set-vals :val x :via via :in in}])) (gen* [_ _ _ _] (if gfn (gfn) (gen/gen-for-pred set-vals))) (with-gen* [_ gfn] (set-impl set-vals gfn)) (describe* [_] set-vals))))) (declare gensub) (defn resolve-fn "Resolves a symbolic function to a function object (predicate)." [fn-form] (eval fn-form)) (defn resolve-spec "Returns a spec object given a fully-qualified spec op form, symbol, set, or registry identifier. If needed, use 'explicate' to qualify forms." [qform] (cond (keyword? qform) (reg-resolve! qform) (qualified-symbol? qform) (pred-impl (res qform)) (c/or (list? qform) (seq? qform)) (-> qform expand-spec create-spec) (map? qform) (create-spec qform) (set? qform) (set-impl qform) (nil? qform) nil (simple-symbol? qform) (throw (IllegalArgumentException. (str "Symbolic spec must be fully-qualified: " qform))) :else (throw (IllegalArgumentException. (str "Unknown spec op of type: " (class qform)))))) (defn- specize [x] (if (keyword? x) (reg-resolve! x) x)) (defn schema* "Returns a schema object given a fully-qualified schema definition. If needed use 'explicate' to qualify forms." [sform] (cond (keyword? sform) (reg-resolve! sform) (vector? sform) (create-spec `{:clojure.spec/op schema, :schema ~sform}) (map? sform) (create-spec `{:clojure.spec/op schema, :schema [~sform]}) (c/or (list? sform) (seq? sform)) (-> sform expand-spec create-spec) (nil? sform) nil :else (throw (IllegalArgumentException. (str "Unknown schema op of type: " (class sform)))))) (defn conform "Given a spec and a value, returns :clojure.alpha.spec/invalid if value does not match spec, else the (possibly destructured) value." ([spec x] (conform spec x nil)) ([spec x settings] (if (keyword? spec) (conform* (reg-resolve! spec) x spec settings) (conform* spec x nil settings)))) (defn unform "Given a spec and a value created by or compliant with a call to 'conform' with the same spec, returns a value with all conform destructuring undone." [spec x] (unform* (specize spec) x)) (defn form "returns the spec as data" [spec] ;;TODO - incorporate gens (describe* (specize spec))) (defn- abbrev [form] (cond (seq? form) (walk/postwalk (fn [form] (cond (c/and (symbol? form) (namespace form)) (-> form name symbol) (c/and (seq? form) (= 'fn (first form)) (= '[%] (second form))) (last form) :else form)) form) (c/and (symbol? form) (namespace form)) (-> form name symbol) :else form)) (defn describe "returns an abbreviated description of the spec as data" [spec] (abbrev (form spec))) (defn explain-data* [spec path via in x settings-key settings] (let [probs (explain* (specize spec) path via in x settings-key settings)] (when-not (empty? probs) {::sa/problems probs ::sa/spec spec ::sa/value x}))) (defn explain-data "Given a spec and a value x which ought to conform, returns nil if x conforms, else a map with at least the key ::problems whose value is a collection of problem-maps, where problem-map has at least :path :pred and :val keys describing the predicate and the value that failed at that path." ([spec x] (explain-data spec x nil)) ([spec x settings] (let [settings-key (when (keyword? spec) spec)] (explain-data* spec [] (if-let [name (spec-name spec)] [name] []) [] x settings-key settings)))) (defn explain-printer "Default printer for explain-data. nil indicates a successful validation." [ed] (if ed (let [problems (->> (::sa/problems ed) (sort-by #(- (count (:in %)))) (sort-by #(- (count (:path %)))))] ;;(prn {:ed ed}) (doseq [{:keys [path pred val reason via in] :as prob} problems] (pr val) (print " - failed: ") (if reason (print reason) (pr (abbrev pred))) (when-not (empty? in) (print (str " in: " (pr-str in)))) (when-not (empty? path) (print (str " at: " (pr-str path)))) (when-not (empty? via) (print (str " spec: " (pr-str (last via))))) (doseq [[k v] prob] (when-not (#{:path :pred :val :reason :via :in} k) (print "\n\t" (pr-str k) " ") (pr v))) (newline))) (println "Success!"))) (def ^:dynamic *explain-out* explain-printer) (defn explain-out "Prints explanation data (per 'explain-data') to *out* using the printer in *explain-out*, by default explain-printer." [ed] (*explain-out* ed)) (defn explain "Given a spec and a value that fails to conform, prints an explanation to *out*." ([spec x] (explain spec x nil)) ([spec x settings] (explain-out (explain-data spec x settings)))) (defn explain-str "Given a spec and a value that fails to conform, returns an explanation as a string." (^String [spec x] (explain-str spec x nil)) (^String [spec x settings] (with-out-str (explain spec x settings)))) (defn valid? "Helper function that returns true when x is valid for spec." ([spec x] (valid? spec x nil)) ([spec x settings] (if (keyword? spec) (let [spec' (reg-resolve! spec)] (not (invalid? (conform* spec' x spec settings)))) (not (invalid? (conform* spec x nil settings)))))) (defn- gensub [spec overrides path rmap form] ;;(prn {:spec spec :over overrides :path path :form form}) (let [spec (specize spec)] (if-let [g (c/or (when-let [gfn (c/or (get overrides (c/or (spec-name spec) spec)) (get overrides path))] (gfn)) (gen* spec overrides path rmap))] (gen/such-that #(valid? spec %) g 100) (let [abbr (abbrev form)] (throw (ex-info (str "Unable to construct gen at: " path " for: " abbr) {::sa/path path ::sa/form form ::sa/failure :no-gen})))))) (defn gen "Given a spec, returns the generator for it, or throws if none can be constructed. Optionally an overrides map can be provided which should map spec names or paths (vectors of keywords) to no-arg generator-creating fns. These will be used instead of the generators at those names/paths. Note that parent generator (in the spec or overrides map) will supersede those of any subtrees. A generator for a regex op must always return a sequential collection (i.e. a generator for s/? should return either an empty sequence/vector or a sequence/vector with one item in it)" ([spec] (gen spec nil)) ([spec overrides] (gensub spec overrides [] {::recursion-limit *recursion-limit*} spec))) (defn- explicate-1 [a-ns form] (walk/postwalk #(cond (keyword? %) % (symbol? %) (if-let [rs (some->> % (ns-resolve a-ns))] (if (var? rs) (symbol rs) %) %) :else %) form)) (defn explicate "Return a fully-qualified form given a namespace name context and a form" [ns-name form] (let [a-ns (find-ns ns-name)] (if (sequential? form) (map (partial explicate-1 a-ns) form) (explicate-1 a-ns form)))) (defn- ns-qualify "Qualify symbol s by resolving it or using the current *ns*." [s] (if-let [ns-sym (some-> s namespace symbol)] (c/or (some-> (get (ns-aliases *ns*) ns-sym) str (symbol (name s))) s) (symbol (str (.name *ns*)) (str s)))) (defmacro schema "Given a literal vector or map schema, expand to a proper explicated spec form, which when evaluated yields a schema object." [& coll] `(resolve-spec '~(explicate (ns-name *ns*) `(schema ~@coll)))) (defmacro union "Takes schemas and unions them, returning a schema object" [& schemas] `(resolve-spec '~(explicate (ns-name *ns*) `(union ~@schemas)))) (defmacro spec "Given a function symbol, set of constants, or anonymous function, returns a spec object." [s] `(resolve-spec '~(explicate (ns-name *ns*) s))) (defn register "Given a namespace-qualified keyword or resolvable symbol k, and a spec-name or spec object, makes an entry in the registry mapping k to the spec. Use nil to remove an entry in the registry for k." [k s] (c/assert (c/and (ident? k) (namespace k)) "k must be namespaced keyword or resolvable symbol") (if (nil? s) (swap! registry-ref dissoc k) (swap! registry-ref assoc k (with-name s k))) k) (defmacro def "Given a namespace-qualified keyword or resolvable symbol k, and a spec-name or symbolic spec, makes an entry in the registry mapping k to the spec. Use nil to remove an entry in the registry for k." [k spec-form] (let [k (if (symbol? k) (ns-qualify k) k) spec-def (cond (keyword? spec-form) spec-form (symbol? spec-form) `(spec ~spec-form) (set? spec-form) `(spec ~spec-form) (nil? spec-form) nil ;; remove mapping (c/or (list? spec-form) (seq? spec-form)) (let [explicated-form (explicate (ns-name *ns*) spec-form) op (first explicated-form)] (cond (#{'fn 'fn* `c/fn} op) `(spec ~explicated-form) (contains? (-> #'create-spec deref methods c/keys set) op) explicated-form :else (throw (ex-info (str "Unable to def " k ", unknown spec op: " op) {:k k :form explicated-form})))) :else (throw (ex-info (str "Unable to def " k ", invalid spec definition: " (pr-str spec-form)) {:k k :form spec-form})))] `(register '~k ~spec-def))) (defmacro with-gen "Takes a spec and a no-arg, generator-returning fn and returns a version of that spec that uses that generator" [spec gen-fn] `(resolve-spec '~(explicate (ns-name *ns*) `(with-gen ~spec ~gen-fn)))) (defmacro merge "Takes map-validating specs (e.g. 'keys' specs) and returns a spec that returns a conformed map satisfying all of the specs. Unlike 'and', merge can generate maps satisfying the union of the predicates." [& pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(merge ~@pred-forms)))) (defmacro every "takes a pred and validates collection elements against that pred. Note that 'every' does not do exhaustive checking, rather it samples *coll-check-limit* elements. Nor (as a result) does it do any conforming of elements. 'explain' will report at most *coll-error-limit* problems. Thus 'every' should be suitable for potentially large collections. Takes several kwargs options that further constrain the collection: :kind - a pred that the collection type must satisfy, e.g. vector? (default nil) Note that if :kind is specified and :into is not, this pred must generate in order for every to generate. :count - specifies coll has exactly this count (default nil) :min-count, :max-count - coll has count (<= min-count count max-count) (defaults nil) :distinct - all the elements are distinct (default nil) And additional args that control gen :gen-max - the maximum coll size to generate (default 20) :into - one of [], (), {}, #{} - the default collection to generate into (default: empty coll as generated by :kind pred if supplied, else []) Optionally takes :gen generator-fn, which must be a fn of no args that returns a test.check generator See also - coll-of, every-kv" [pred & {:keys [::describe] :as opts}] (let [nopts (dissoc opts ::describe) d (c/or describe `(every ~pred ~@(mapcat identity opts)))] `(resolve-spec '~(explicate (ns-name *ns*) `(every ~pred ::describe ~d ~@(mapcat identity nopts)))))) (defmacro every-kv "like 'every' but takes separate key and val preds and works on associative collections. Same options as 'every', :into defaults to {} See also - map-of" [kpred vpred & opts] `(resolve-spec '~(explicate (ns-name *ns*) `(every-kv ~kpred ~vpred ~@opts)))) (defmacro coll-of "Returns a spec for a collection of items satisfying pred. Unlike 'every', coll-of will exhaustively conform every value. Same options as 'every'. conform will produce a collection corresponding to :into if supplied, else will match the input collection, avoiding rebuilding when possible. See also - every, map-of" [pred & opts] `(resolve-spec '~(explicate (ns-name *ns*) `(coll-of ~pred ~@opts)))) (defmacro map-of "Returns a spec for a map whose keys satisfy kpred and vals satisfy vpred. Unlike 'every-kv', map-of will exhaustively conform every value. Same options as 'every', :kind defaults to map?, with the addition of: :conform-keys - conform keys as well as values (default false) See also - every-kv" [kpred vpred & opts] `(resolve-spec '~(explicate (ns-name *ns*) `(map-of ~kpred ~vpred ~@opts)))) (defmacro * "Returns a regex op that matches zero or more values matching pred. Produces a vector of matches iff there is at least one match" [pred-form] `(resolve-spec '~(explicate (ns-name *ns*) `(* ~pred-form)))) (defmacro + "Returns a regex op that matches one or more values matching pred. Produces a vector of matches" [pred-form] `(resolve-spec '~(explicate (ns-name *ns*) `(+ ~pred-form)))) (defmacro ? "Returns a regex op that matches zero or one value matching pred. Produces a single value (not a collection) if matched." [pred-form] `(resolve-spec '~(explicate (ns-name *ns*) `(? ~pred-form)))) (defmacro alt "Takes key+pred pairs, e.g. (s/alt :even even? :small #(< % 42)) Returns a regex op that returns a map entry containing the key of the first matching pred and the corresponding value. Thus the 'key' and 'val' functions can be used to refer generically to the components of the tagged return" [& key-pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(alt ~@key-pred-forms)))) (defmacro cat "Takes key+pred pairs, e.g. (s/cat :e even? :o odd?) Returns a regex op that matches (all) values in sequence, returning a map containing the keys of each pred and the corresponding value." [& key-pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(cat ~@key-pred-forms)))) (defmacro & "takes a regex op re, and predicates. Returns a regex-op that consumes input as per re but subjects the resulting value to the conjunction of the predicates, and any conforming they might perform." [re & preds] `(resolve-spec '~(explicate (ns-name *ns*) `(clojure.alpha.spec/& ~re ~@preds)))) (defmacro nest "takes a regex op and returns a non-regex op that describes a nested sequential collection." [re] `(resolve-spec '~(explicate (ns-name *ns*) `(nest ~re)))) (defmacro conformer "takes a predicate function with the semantics of conform i.e. it should return either a (possibly converted) value or :clojure.alpha.spec/invalid, and returns a spec that uses it as a predicate/conformer. Optionally takes a second fn that does unform of result of first" ([f] `(resolve-spec '~(explicate (ns-name *ns*) `(conformer ~f)))) ([f unf] `(resolve-spec '~(explicate (ns-name *ns*) `(conformer ~f ~unf))))) (defmacro fspec "takes :args :ret and (optional) :fn kwargs whose values are preds and returns a spec whose conform/explain take a fn and validates it using generative testing. The conformed value is always the fn itself. See 'fdef' for a single operation that creates an fspec and registers it, as well as a full description of :args, :ret and :fn fspecs can generate functions that validate the arguments and fabricate a return value compliant with the :ret spec, ignoring the :fn spec if present. Optionally takes :gen generator-fn, which must be a fn of no args that returns a test.check generator." [& opts] `(resolve-spec '~(explicate (ns-name *ns*) `(fspec ~@opts)))) (defn- macroexpand-check [v args] (let [fn-spec (get-spec v)] (when-let [arg-spec (:args fn-spec)] (when (invalid? (conform arg-spec args)) (let [ed (assoc (explain-data* arg-spec [] (if-let [name (spec-name arg-spec)] [name] []) [] args nil nil) ::sa/args args)] (throw (ex-info (str "Call to " (symbol v) " did not conform to spec.") ed))))))) (defmacro fdef "Takes a symbol naming a function, and one or more of the following: :args A regex spec for the function arguments as they were a list to be passed to apply - in this way, a single spec can handle functions with multiple arities :ret A spec for the function's return value :fn A spec of the relationship between args and ret - the value passed is {:args conformed-args :ret conformed-ret} and is expected to contain predicates that relate those values Qualifies fn-sym with resolve, or using *ns* if no resolution found. Registers an fspec in the global registry, where it can be retrieved by calling get-spec with the var or fully-qualified symbol. Once registered, function specs are included in doc, checked by instrument, tested by the runner clojure.alpha.spec.test/check, and (if a macro) used to explain errors during macroexpansion. Note that :fn specs require the presence of :args and :ret specs to conform values, and so :fn specs will be ignored if :args or :ret are missing. Returns the qualified fn-sym. For example, to register function specs for the symbol function: (s/fdef clojure.core/symbol :args (s/alt :separate (s/cat :ns string? :n string?) :str string? :sym symbol?) :ret symbol?)" [fn-sym & specs] `(clojure.alpha.spec/def ~fn-sym (clojure.alpha.spec/fspec ~@specs))) (defmacro keys "Creates and returns a map validating spec. :req and :opt are both vectors of namespaced-qualified keywords. The validator will ensure the :req keys are present. The :opt keys serve as documentation and may be used by the generator. The :req key vector supports 'and' and 'or' for key groups: (s/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z]) There are also -un versions of :req and :opt. These allow you to connect unqualified keys to specs. In each case, fully qualified keywords are passed, which name the specs, but unqualified keys (with the same name component) are expected and checked at conform-time, and generated during gen: (s/keys :req-un [:my.ns/x :my.ns/y]) The above says keys :x and :y are required, and will be validated and generated by specs (if they exist) named :my.ns/x :my.ns/y respectively. In addition, the values of *all* namespace-qualified keys will be validated (and possibly destructured) by any registered specs. Note: there is no support for inline value specification, by design. Optionally takes :gen generator-fn, which must be a fn of no args that returns a test.check generator." [& ks] `(resolve-spec '~(explicate (ns-name *ns*) `(keys ~@ks)))) (defmacro select "Takes a keyset and a selection pattern and returns a spec that validates a map. The keyset specifies what keys may be in the map and the specs to use if the keys are unqualified. The selection pattern indicates what keys must be in the map, and any nested maps." [keyset selection] `(resolve-spec '~(explicate (ns-name *ns*) `(select ~keyset ~selection)))) (defmacro multi-spec "Takes the name of a spec/predicate-returning multimethod and a tag-restoring keyword or fn (retag). Returns a spec that when conforming or explaining data will pass it to the multimethod to get an appropriate spec. You can e.g. use multi-spec to dynamically and extensibly associate specs with 'tagged' data (i.e. data where one of the fields indicates the shape of the rest of the structure). (defmulti mspec :tag) The methods should ignore their argument and return a predicate/spec: (defmethod mspec :int [_] (s/keys :req-un [::tag ::i])) retag is used during generation to retag generated values with matching tags. retag can either be a keyword, at which key the dispatch-tag will be assoc'ed, or a fn of generated value and dispatch-tag that should return an appropriately retagged value. Note that because the tags themselves comprise an open set, the tag key spec cannot enumerate the values, but can e.g. test for keyword?. Note also that the dispatch values of the multimethod will be included in the path, i.e. in reporting and gen overrides, even though those values are not evident in the spec. " [mm retag] `(resolve-spec '~(explicate (ns-name *ns*) `(multi-spec ~mm ~retag)))) (defmacro tuple "takes one or more preds and returns a spec for a tuple, a vector where each element conforms to the corresponding pred. Each element will be referred to in paths using its ordinal." [& preds] (c/assert (not (empty? preds))) `(resolve-spec '~(explicate (ns-name *ns*) `(tuple ~@preds)))) (defmacro or "Takes key+pred pairs, e.g. (s/or :even even? :small #(< % 42)) Returns a destructuring spec that returns a map entry containing the key of the first matching pred and the corresponding value. Thus the 'key' and 'val' functions can be used to refer generically to the components of the tagged return." [& key-pred-forms] (c/assert (c/and (even? (count key-pred-forms)) (->> key-pred-forms (partition 2) (map first) (every? keyword?))) "spec/or expects k1 p1 k2 p2..., where ks are keywords") `(resolve-spec '~(explicate (ns-name *ns*) `(or ~@key-pred-forms)))) (defmacro and "Takes predicate/spec-forms, e.g. (s/and int? even? #(< % 42)) Returns a spec that returns the conformed value. Successive conformed values propagate through rest of predicates." [& pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(and ~@pred-forms)))) (defmacro and- "Takes predicate/spec-forms, e.g. (s/and- (s/cat :i int?) #(pos? (first %))) Returns a spec that validates all preds on and returns the conformed value of the first pred. Conformed values are NOT propagated through rest of predicates." [& pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(and- ~@pred-forms)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; non-primitives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro keys* "takes the same arguments as spec/keys and returns a regex op that matches sequences of key/values, converts them into a map, and conforms that map with a corresponding spec/keys call: user=> (s/conform (s/keys :req-un [::a ::c]) {:a 1 :c 2}) {:a 1, :c 2} user=> (s/conform (s/keys* :req-un [::a ::c]) [:a 1 :c 2]) {:a 1, :c 2} the resulting regex op can be composed into a larger regex: user=> (s/conform (s/cat :i1 integer? :m (s/keys* :req-un [::a ::c]) :i2 integer?) [42 :a 1 :c 2 :d 4 99]) {:i1 42, :m {:a 1, :c 2, :d 4}, :i2 99}" [& kspecs] `(resolve-spec '~(explicate (ns-name *ns*) `(keys* ~@kspecs)))) (defmacro nonconforming "takes a spec and returns a spec that has the same properties except 'conform' returns the original (not the conformed) value." [spec] `(resolve-spec '~(explicate (ns-name *ns*) `(nonconforming ~spec)))) (defmacro nilable "returns a spec that accepts nil and values satisfying pred" [pred] `(resolve-spec '~(explicate (ns-name *ns*) `(nilable ~pred)))) (defn exercise "generates a number (default 10) of values compatible with spec and maps conform over them, returning a sequence of [val conformed-val] tuples. Optionally takes a generator overrides map as per gen" ([spec] (exercise spec 10)) ([spec n] (exercise spec n nil)) ([spec n overrides] (map #(vector % (conform spec %)) (gen/sample (gen spec overrides) n)))) (defn exercise-fn "exercises the fn named by sym (a symbol) by applying it to n (default 10) generated samples of its args spec. When fspec is supplied its arg spec is used, and sym-or-f can be a fn. Returns a sequence of tuples of [args ret]. " ([sym] (exercise-fn sym 10)) ([sym n] (exercise-fn sym n (get-spec sym))) ([sym-or-f n fspec] (let [f (if (symbol? sym-or-f) (resolve sym-or-f) sym-or-f)] (if-let [arg-spec (c/and fspec (:args fspec))] (for [args (gen/sample (gen arg-spec) n)] [args (apply f args)]) (throw (Exception. "No :args spec found, can't generate")))))) (defn inst-in-range? "Return true if inst at or after start and before end" [start end inst] (c/and (inst? inst) (let [t (inst-ms inst)] (c/and (<= (inst-ms start) t) (< t (inst-ms end)))))) (defn int-in-range? "Return true if start <= val, val < end and val is a fixed precision integer." [start end val] (c/and (int? val) (<= start val) (< val end))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; assert ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defonce ^{:dynamic true :doc "If true, compiler will enable spec asserts, which are then subject to runtime control via check-asserts? If false, compiler will eliminate all spec assert overhead. See 'assert'. Initially set to boolean value of clojure.spec.compile-asserts system property. Defaults to true."} *compile-asserts* (not= "false" (System/getProperty "clojure.spec.compile-asserts"))) (defn check-asserts? "Returns the value set by check-asserts." [] clojure.lang.RT/checkSpecAsserts) (defn check-asserts "Enable or disable spec asserts that have been compiled with '*compile-asserts*' true. See 'assert'. Initially set to boolean value of clojure.spec.check-asserts system property. Defaults to false." [flag] (set! (. clojure.lang.RT checkSpecAsserts) flag)) (defn assert* "Do not call this directly, use 'assert'." [spec x] (if (valid? spec x) x (let [ed (c/merge (assoc (explain-data* spec [] [] [] x nil nil) ::sa/failure :assertion-failed))] (throw (ex-info (str "Spec assertion failed\n" (with-out-str (explain-out ed))) ed))))) (defmacro assert "spec-checking assert expression. Returns x if x is valid? according to spec, else throws an ex-info with explain-data plus ::failure of :assertion-failed. Can be disabled at either compile time or runtime: If *compile-asserts* is false at compile time, compiles to x. Defaults to value of 'clojure.spec.compile-asserts' system property, or true if not set. If (check-asserts?) is false at runtime, always returns x. Defaults to value of 'clojure.spec.check-asserts' system property, or false if not set. You can toggle check-asserts? with (check-asserts bool)." [spec x] (if *compile-asserts* `(if clojure.lang.RT/checkSpecAsserts (assert* ~spec ~x) ~x) x)) (defn ^:skip-wiki sig-map "Do not call directly." [sig vals] (let [locals (->> sig (tree-seq coll? identity) (filter #(c/and (symbol? %) (not= '& %))) distinct vec)] (zipmap locals (eval `(let [~sig ~(vec vals)] ~locals))))) (defn ^:skip-wiki op-spec "Do not call directly, use `defop`" [sp form gfn] (reify protocols/Spec (conform* [_ x settings-key settings] (protocols/conform* @sp x settings-key settings)) (unform* [_ x] (unform @sp x)) (explain* [_ path via in x settings-key settings] (protocols/explain* @sp path via in x settings-key settings)) (gen* [_ _ _ _] (if gfn (gfn) (gen @sp))) (with-gen* [_ gfn] (op-spec sp form gfn)) (describe* [_] form))) (defmacro defop "Defines a new spec op with op-name defined by the form. Defines a macro for op-name with docstring that expands to a call to resolve-spec with the explicated form. args are replaced in the form. Creates a create-spec method implementation for op-name that creates a spec whose body is form. Opts allowed: :gen - takes a no-arg function returning a generator to use" {:arglists '([op-name doc-string? opts? [params*] form])} [op-name & op-tail] (let [form (last op-tail) opts (butlast op-tail) [doc args opts] (if (string? (first opts)) [(first opts) (second opts) (nthrest opts 2)] [nil (first opts) (rest opts)]) _ (c/assert (even? (count opts)) "defop options should be keyword/value pairs") {:keys [gen]} opts ns-name (ns-name *ns*) op (symbol (name ns-name) (name op-name))] `(do (defmethod expand-spec '~op [[~'_ ~'& ~'sargs]] (let [os# '~op] {:clojure.spec/op os# :args ~'sargs})) (defmethod create-spec '~op [~'mform] (let [a# (:args ~'mform) m# (sig-map '~args a#) ;; map of arg name to arg value sp# (delay (resolve-spec (explicate '~ns-name (walk/postwalk (fn [x#] (get m# x# x#)) '~form))))] (op-spec sp# (cons '~op a#) (resolve-fn (walk/postwalk (fn [x#] (get m# x# x#)) '~gen))))) (defmacro ~op-name ~@(if doc [doc] []) ;; docstring {:arglists (list '~args)} ;; metadata with arglists [~'& ~'sargs] (list `resolve-spec (list `explicate (list `quote '~ns-name) (list `quote (cons '~op ~'sargs)))))))) ;; Load the spec op implementations (load "/clojure/alpha/spec/impl") ;; Derived ops (defop inst-in "Returns a spec that validates insts in the range from start (inclusive) to end (exclusive)." [start end] :gen #(clojure.alpha.spec.gen/fmap (fn [^long d] (java.util.Date. d)) (clojure.alpha.spec.gen/large-integer* {:min (inst-ms start) :max (inst-ms end)})) (and inst? #(inst-in-range? start end %))) (defop int-in "Returns a spec that validates fixed precision integers in the range from start (inclusive) to end (exclusive)." [start end] :gen #(clojure.alpha.spec.gen/large-integer* {:min start :max (dec end)}) (and int? #(int-in-range? start end %))) (defop double-in "Specs a 64-bit floating point number. Options: :infinite? - whether +/- infinity allowed (default true) :NaN? - whether NaN allowed (default true) :min - minimum value (inclusive, default none) :max - maximum value (inclusive, default none)" [& {:keys [infinite? NaN? min max :as m]}] :gen #(clojure.alpha.spec.gen/double* m) (and double? #(if-not infinite? (not (Double/isInfinite %))) #(if-not NaN? (not (Double/isNaN %))) #(if min (<= min %) true) #(if max (<= % max) true))) (defmacro defcompop "Defines a new composite spec with op-name and args same as spec-op. The new spec takes the same args as spec-op, and also ensures the preds are satisfied." {:arglists '([op-name doc-string? spec-op preds+])} [op-name & tail] (let [[doc spec-op & preds] (if (string? (first tail)) tail (cons nil tail)) ns-name (ns-name *ns*) op (symbol (name ns-name) (name op-name))] (c/assert (pos? (count preds)) "defcompop should have at least one pred") `(do (defmethod expand-spec '~op [[~'_ ~'& ~'sargs]] (let [os# '~op] {:clojure.spec/op os# :primary '~(explicate ns-name spec-op) :preds '~(explicate ns-name preds) :args ~'sargs})) (defmethod create-spec '~op [~'mform] (let [primary# (:primary ~'mform) preds# (:preds ~'mform) a# (:args ~'mform) comp-spec# (concat (list 'clojure.alpha.spec/and- (cons '~(explicate ns-name spec-op) a#)) preds#)] (resolve-spec comp-spec#))) (defmacro ~op-name ~@(if doc [doc] []) {:arglists '~(:arglists (meta (find-var (explicate ns-name spec-op))))} [~'& ~'sargs] (list `resolve-spec (list `explicate (list `quote '~ns-name) (list `quote (cons '~op ~'sargs)))))))) (defcompop catv "Like s/cat, but constrain to only vectors" cat vector?) (defcompop cats "Like s/cat, but constrain to only seqs" cat seq?)
null
https://raw.githubusercontent.com/clojure/spec-alpha2/3d32b5e571b98e2930a7b2ed1dd9551bb269375a/src/main/clojure/clojure/alpha/spec.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. TODO - incorporate gens (prn {:ed ed}) (prn {:spec spec :over overrides :path path :form form}) remove mapping non-primitives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; assert ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; map of arg name to arg value docstring metadata with arglists Load the spec op implementations Derived ops
Copyright ( c ) . All rights reserved . (ns ^{:doc "The spec library specifies the structure of data or functions and provides operations to validate, conform, explain, describe, and generate data based on the specs. Rationale: Guide: "} clojure.alpha.spec (:refer-clojure :exclude [+ * and assert or cat def keys merge comp]) (:require [clojure.alpha.spec.protocols :as protocols :refer [conform* unform* explain* gen* with-gen* describe*]] [clojure.walk :as walk] [clojure.alpha.spec.gen :as gen]) (:import [clojure.alpha.spec.protocols Spec Schema])) (alias 'c 'clojure.core) (alias 'sa 'clojure.spec.alpha) (def ^:dynamic *recursion-limit* "A soft limit on how many times a branching spec (or/alt/*/opt-keys/multi-spec) can be recursed through during generation. After this a non-recursive branch will be chosen." 4) (def ^:dynamic *fspec-iterations* "The number of times an anonymous fn specified by fspec will be (generatively) tested during conform" 21) (def ^:dynamic *coll-check-limit* "The number of elements validated in a collection spec'ed with 'every'" 101) (def ^:dynamic *coll-error-limit* "The number of errors reported by explain in a collection spec'ed with 'every'" 20) (defonce ^:private registry-ref (atom {})) (defn registry "Returns the registry map, prefer 'get-spec' to lookup a spec by name" [] @registry-ref) (defn spec? "returns x if x is a spec object, else logical false" [x] (when (c/or (instance? Spec x) (-> x meta (contains? `conform*))) x)) (defn schema? "Returns x if x is a schema object, else logical false" [x] (instance? Schema x)) (defn get-spec "Returns spec registered for keyword/symbol/var k, or nil." [k] (get (registry) (if (keyword? k) k (symbol k)))) (defn- deep-resolve [reg k] (loop [spec k] (if (ident? spec) (recur (get reg spec)) spec))) (defn- reg-resolve "returns the spec/regex at end of alias chain starting with k, nil if not found, k if k not ident" [k] (if (ident? k) (let [reg @registry-ref spec (get reg k)] (if-not (ident? spec) spec (deep-resolve reg spec))) k)) (defn- reg-resolve! "returns the spec/regex at end of alias chain starting with k, throws if not found, k if k not ident" [k] (if (ident? k) (c/or (reg-resolve k) (throw (Exception. (str "Unable to resolve spec: " k)))) k)) (defn regex? "returns x if x is a (clojure.spec) regex op, else logical false" [x] (c/and (::op x) x)) (defn- with-name [spec name] (cond (ident? spec) spec (regex? spec) (assoc spec ::name name) (instance? clojure.lang.IObj spec) (with-meta spec (assoc (meta spec) ::name name)))) (defn- spec-name [spec] (cond (ident? spec) spec (regex? spec) (::name spec) (instance? clojure.lang.IObj spec) (-> (meta spec) ::name))) (defn invalid? "tests the validity of a conform return value" [ret] (identical? ::invalid ret)) (defn- unfn [expr] (if (c/and (seq? expr) (symbol? (first expr)) (= "fn*" (name (first expr)))) (let [[[s] & form] (rest expr)] (conj (walk/postwalk-replace {s '%} form) '[%] 'fn)) expr)) (defn- res [form] (walk/postwalk #(cond (keyword? %) % (symbol? %) (c/or (some-> % resolve symbol) %) (sequential? %) (unfn %) :else %) form)) (defmulti expand-spec "Create a symbolic spec map from an explicated spec form. This is an extension point for adding new spec ops. Generally, consumers should instead call `resolve-spec`. For anything other than symbolic spec maps, return the same object unchanged." (fn [qform] (when (c/or (list? qform) (seq? qform)) (first qform)))) (defmethod expand-spec :default [o] o) (defmulti create-spec "Create a spec object from an explicated spec map. This is an extension point for adding new spec ops. Generally, consumers should instead call `resolve-spec`." (fn [smap] (when (map? smap) (:clojure.spec/op smap)))) (defmethod create-spec :default [o] o) (defn- pred-impl ([sym] (pred-impl sym nil)) ([sym gfn] (let [pred (deref (find-var sym))] (reify protocols/Spec (conform* [_ x settings-key settings] (let [ret (pred x)] (if ret x ::invalid))) (unform* [_ x] x) (explain* [_ path via in x settings-key settings] (when (not (pred x)) [{:path path :pred sym :val x :via via :in in}])) (gen* [_ _ _ _] (if gfn (gfn) (gen/gen-for-pred pred))) (with-gen* [_ gfn] (pred-impl sym gfn)) (describe* [_] sym))))) (defn- constant-val? [x] (c/or (nil? x) (boolean? x) (number? x) (string? x) (ident? x) (char? x) (c/and (coll? x) (empty? x)) (c/and (c/or (vector? x) (set? x) (map? x)) (every? constant-val? x)))) (defn- set-impl ([set-vals] (set-impl set-vals nil)) ([set-vals gfn] (c/assert (every? constant-val? set-vals) "set specs must contain constant values") (let [pred #(contains? set-vals %)] (reify protocols/Spec (conform* [_ x settings-key settings] (let [ret (pred x)] (if ret x ::invalid))) (unform* [_ x] x) (explain* [_ path via in x settings-key settings] (when (not (pred x)) [{:path path :pred set-vals :val x :via via :in in}])) (gen* [_ _ _ _] (if gfn (gfn) (gen/gen-for-pred set-vals))) (with-gen* [_ gfn] (set-impl set-vals gfn)) (describe* [_] set-vals))))) (declare gensub) (defn resolve-fn "Resolves a symbolic function to a function object (predicate)." [fn-form] (eval fn-form)) (defn resolve-spec "Returns a spec object given a fully-qualified spec op form, symbol, set, or registry identifier. If needed, use 'explicate' to qualify forms." [qform] (cond (keyword? qform) (reg-resolve! qform) (qualified-symbol? qform) (pred-impl (res qform)) (c/or (list? qform) (seq? qform)) (-> qform expand-spec create-spec) (map? qform) (create-spec qform) (set? qform) (set-impl qform) (nil? qform) nil (simple-symbol? qform) (throw (IllegalArgumentException. (str "Symbolic spec must be fully-qualified: " qform))) :else (throw (IllegalArgumentException. (str "Unknown spec op of type: " (class qform)))))) (defn- specize [x] (if (keyword? x) (reg-resolve! x) x)) (defn schema* "Returns a schema object given a fully-qualified schema definition. If needed use 'explicate' to qualify forms." [sform] (cond (keyword? sform) (reg-resolve! sform) (vector? sform) (create-spec `{:clojure.spec/op schema, :schema ~sform}) (map? sform) (create-spec `{:clojure.spec/op schema, :schema [~sform]}) (c/or (list? sform) (seq? sform)) (-> sform expand-spec create-spec) (nil? sform) nil :else (throw (IllegalArgumentException. (str "Unknown schema op of type: " (class sform)))))) (defn conform "Given a spec and a value, returns :clojure.alpha.spec/invalid if value does not match spec, else the (possibly destructured) value." ([spec x] (conform spec x nil)) ([spec x settings] (if (keyword? spec) (conform* (reg-resolve! spec) x spec settings) (conform* spec x nil settings)))) (defn unform "Given a spec and a value created by or compliant with a call to 'conform' with the same spec, returns a value with all conform destructuring undone." [spec x] (unform* (specize spec) x)) (defn form "returns the spec as data" [spec] (describe* (specize spec))) (defn- abbrev [form] (cond (seq? form) (walk/postwalk (fn [form] (cond (c/and (symbol? form) (namespace form)) (-> form name symbol) (c/and (seq? form) (= 'fn (first form)) (= '[%] (second form))) (last form) :else form)) form) (c/and (symbol? form) (namespace form)) (-> form name symbol) :else form)) (defn describe "returns an abbreviated description of the spec as data" [spec] (abbrev (form spec))) (defn explain-data* [spec path via in x settings-key settings] (let [probs (explain* (specize spec) path via in x settings-key settings)] (when-not (empty? probs) {::sa/problems probs ::sa/spec spec ::sa/value x}))) (defn explain-data "Given a spec and a value x which ought to conform, returns nil if x conforms, else a map with at least the key ::problems whose value is a collection of problem-maps, where problem-map has at least :path :pred and :val keys describing the predicate and the value that failed at that path." ([spec x] (explain-data spec x nil)) ([spec x settings] (let [settings-key (when (keyword? spec) spec)] (explain-data* spec [] (if-let [name (spec-name spec)] [name] []) [] x settings-key settings)))) (defn explain-printer "Default printer for explain-data. nil indicates a successful validation." [ed] (if ed (let [problems (->> (::sa/problems ed) (sort-by #(- (count (:in %)))) (sort-by #(- (count (:path %)))))] (doseq [{:keys [path pred val reason via in] :as prob} problems] (pr val) (print " - failed: ") (if reason (print reason) (pr (abbrev pred))) (when-not (empty? in) (print (str " in: " (pr-str in)))) (when-not (empty? path) (print (str " at: " (pr-str path)))) (when-not (empty? via) (print (str " spec: " (pr-str (last via))))) (doseq [[k v] prob] (when-not (#{:path :pred :val :reason :via :in} k) (print "\n\t" (pr-str k) " ") (pr v))) (newline))) (println "Success!"))) (def ^:dynamic *explain-out* explain-printer) (defn explain-out "Prints explanation data (per 'explain-data') to *out* using the printer in *explain-out*, by default explain-printer." [ed] (*explain-out* ed)) (defn explain "Given a spec and a value that fails to conform, prints an explanation to *out*." ([spec x] (explain spec x nil)) ([spec x settings] (explain-out (explain-data spec x settings)))) (defn explain-str "Given a spec and a value that fails to conform, returns an explanation as a string." (^String [spec x] (explain-str spec x nil)) (^String [spec x settings] (with-out-str (explain spec x settings)))) (defn valid? "Helper function that returns true when x is valid for spec." ([spec x] (valid? spec x nil)) ([spec x settings] (if (keyword? spec) (let [spec' (reg-resolve! spec)] (not (invalid? (conform* spec' x spec settings)))) (not (invalid? (conform* spec x nil settings)))))) (defn- gensub [spec overrides path rmap form] (let [spec (specize spec)] (if-let [g (c/or (when-let [gfn (c/or (get overrides (c/or (spec-name spec) spec)) (get overrides path))] (gfn)) (gen* spec overrides path rmap))] (gen/such-that #(valid? spec %) g 100) (let [abbr (abbrev form)] (throw (ex-info (str "Unable to construct gen at: " path " for: " abbr) {::sa/path path ::sa/form form ::sa/failure :no-gen})))))) (defn gen "Given a spec, returns the generator for it, or throws if none can be constructed. Optionally an overrides map can be provided which should map spec names or paths (vectors of keywords) to no-arg generator-creating fns. These will be used instead of the generators at those names/paths. Note that parent generator (in the spec or overrides map) will supersede those of any subtrees. A generator for a regex op must always return a sequential collection (i.e. a generator for s/? should return either an empty sequence/vector or a sequence/vector with one item in it)" ([spec] (gen spec nil)) ([spec overrides] (gensub spec overrides [] {::recursion-limit *recursion-limit*} spec))) (defn- explicate-1 [a-ns form] (walk/postwalk #(cond (keyword? %) % (symbol? %) (if-let [rs (some->> % (ns-resolve a-ns))] (if (var? rs) (symbol rs) %) %) :else %) form)) (defn explicate "Return a fully-qualified form given a namespace name context and a form" [ns-name form] (let [a-ns (find-ns ns-name)] (if (sequential? form) (map (partial explicate-1 a-ns) form) (explicate-1 a-ns form)))) (defn- ns-qualify "Qualify symbol s by resolving it or using the current *ns*." [s] (if-let [ns-sym (some-> s namespace symbol)] (c/or (some-> (get (ns-aliases *ns*) ns-sym) str (symbol (name s))) s) (symbol (str (.name *ns*)) (str s)))) (defmacro schema "Given a literal vector or map schema, expand to a proper explicated spec form, which when evaluated yields a schema object." [& coll] `(resolve-spec '~(explicate (ns-name *ns*) `(schema ~@coll)))) (defmacro union "Takes schemas and unions them, returning a schema object" [& schemas] `(resolve-spec '~(explicate (ns-name *ns*) `(union ~@schemas)))) (defmacro spec "Given a function symbol, set of constants, or anonymous function, returns a spec object." [s] `(resolve-spec '~(explicate (ns-name *ns*) s))) (defn register "Given a namespace-qualified keyword or resolvable symbol k, and a spec-name or spec object, makes an entry in the registry mapping k to the spec. Use nil to remove an entry in the registry for k." [k s] (c/assert (c/and (ident? k) (namespace k)) "k must be namespaced keyword or resolvable symbol") (if (nil? s) (swap! registry-ref dissoc k) (swap! registry-ref assoc k (with-name s k))) k) (defmacro def "Given a namespace-qualified keyword or resolvable symbol k, and a spec-name or symbolic spec, makes an entry in the registry mapping k to the spec. Use nil to remove an entry in the registry for k." [k spec-form] (let [k (if (symbol? k) (ns-qualify k) k) spec-def (cond (keyword? spec-form) spec-form (symbol? spec-form) `(spec ~spec-form) (set? spec-form) `(spec ~spec-form) (c/or (list? spec-form) (seq? spec-form)) (let [explicated-form (explicate (ns-name *ns*) spec-form) op (first explicated-form)] (cond (#{'fn 'fn* `c/fn} op) `(spec ~explicated-form) (contains? (-> #'create-spec deref methods c/keys set) op) explicated-form :else (throw (ex-info (str "Unable to def " k ", unknown spec op: " op) {:k k :form explicated-form})))) :else (throw (ex-info (str "Unable to def " k ", invalid spec definition: " (pr-str spec-form)) {:k k :form spec-form})))] `(register '~k ~spec-def))) (defmacro with-gen "Takes a spec and a no-arg, generator-returning fn and returns a version of that spec that uses that generator" [spec gen-fn] `(resolve-spec '~(explicate (ns-name *ns*) `(with-gen ~spec ~gen-fn)))) (defmacro merge "Takes map-validating specs (e.g. 'keys' specs) and returns a spec that returns a conformed map satisfying all of the specs. Unlike 'and', merge can generate maps satisfying the union of the predicates." [& pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(merge ~@pred-forms)))) (defmacro every "takes a pred and validates collection elements against that pred. Note that 'every' does not do exhaustive checking, rather it samples *coll-check-limit* elements. Nor (as a result) does it do any conforming of elements. 'explain' will report at most *coll-error-limit* problems. Thus 'every' should be suitable for potentially large collections. Takes several kwargs options that further constrain the collection: :kind - a pred that the collection type must satisfy, e.g. vector? (default nil) Note that if :kind is specified and :into is not, this pred must generate in order for every to generate. :count - specifies coll has exactly this count (default nil) :min-count, :max-count - coll has count (<= min-count count max-count) (defaults nil) :distinct - all the elements are distinct (default nil) And additional args that control gen :gen-max - the maximum coll size to generate (default 20) :into - one of [], (), {}, #{} - the default collection to generate into (default: empty coll as generated by :kind pred if supplied, else []) Optionally takes :gen generator-fn, which must be a fn of no args that returns a test.check generator See also - coll-of, every-kv" [pred & {:keys [::describe] :as opts}] (let [nopts (dissoc opts ::describe) d (c/or describe `(every ~pred ~@(mapcat identity opts)))] `(resolve-spec '~(explicate (ns-name *ns*) `(every ~pred ::describe ~d ~@(mapcat identity nopts)))))) (defmacro every-kv "like 'every' but takes separate key and val preds and works on associative collections. Same options as 'every', :into defaults to {} See also - map-of" [kpred vpred & opts] `(resolve-spec '~(explicate (ns-name *ns*) `(every-kv ~kpred ~vpred ~@opts)))) (defmacro coll-of "Returns a spec for a collection of items satisfying pred. Unlike 'every', coll-of will exhaustively conform every value. Same options as 'every'. conform will produce a collection corresponding to :into if supplied, else will match the input collection, avoiding rebuilding when possible. See also - every, map-of" [pred & opts] `(resolve-spec '~(explicate (ns-name *ns*) `(coll-of ~pred ~@opts)))) (defmacro map-of "Returns a spec for a map whose keys satisfy kpred and vals satisfy vpred. Unlike 'every-kv', map-of will exhaustively conform every value. Same options as 'every', :kind defaults to map?, with the addition of: :conform-keys - conform keys as well as values (default false) See also - every-kv" [kpred vpred & opts] `(resolve-spec '~(explicate (ns-name *ns*) `(map-of ~kpred ~vpred ~@opts)))) (defmacro * "Returns a regex op that matches zero or more values matching pred. Produces a vector of matches iff there is at least one match" [pred-form] `(resolve-spec '~(explicate (ns-name *ns*) `(* ~pred-form)))) (defmacro + "Returns a regex op that matches one or more values matching pred. Produces a vector of matches" [pred-form] `(resolve-spec '~(explicate (ns-name *ns*) `(+ ~pred-form)))) (defmacro ? "Returns a regex op that matches zero or one value matching pred. Produces a single value (not a collection) if matched." [pred-form] `(resolve-spec '~(explicate (ns-name *ns*) `(? ~pred-form)))) (defmacro alt "Takes key+pred pairs, e.g. (s/alt :even even? :small #(< % 42)) Returns a regex op that returns a map entry containing the key of the first matching pred and the corresponding value. Thus the 'key' and 'val' functions can be used to refer generically to the components of the tagged return" [& key-pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(alt ~@key-pred-forms)))) (defmacro cat "Takes key+pred pairs, e.g. (s/cat :e even? :o odd?) Returns a regex op that matches (all) values in sequence, returning a map containing the keys of each pred and the corresponding value." [& key-pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(cat ~@key-pred-forms)))) (defmacro & "takes a regex op re, and predicates. Returns a regex-op that consumes input as per re but subjects the resulting value to the conjunction of the predicates, and any conforming they might perform." [re & preds] `(resolve-spec '~(explicate (ns-name *ns*) `(clojure.alpha.spec/& ~re ~@preds)))) (defmacro nest "takes a regex op and returns a non-regex op that describes a nested sequential collection." [re] `(resolve-spec '~(explicate (ns-name *ns*) `(nest ~re)))) (defmacro conformer "takes a predicate function with the semantics of conform i.e. it should return either a (possibly converted) value or :clojure.alpha.spec/invalid, and returns a spec that uses it as a predicate/conformer. Optionally takes a second fn that does unform of result of first" ([f] `(resolve-spec '~(explicate (ns-name *ns*) `(conformer ~f)))) ([f unf] `(resolve-spec '~(explicate (ns-name *ns*) `(conformer ~f ~unf))))) (defmacro fspec "takes :args :ret and (optional) :fn kwargs whose values are preds and returns a spec whose conform/explain take a fn and validates it using generative testing. The conformed value is always the fn itself. See 'fdef' for a single operation that creates an fspec and registers it, as well as a full description of :args, :ret and :fn fspecs can generate functions that validate the arguments and fabricate a return value compliant with the :ret spec, ignoring the :fn spec if present. Optionally takes :gen generator-fn, which must be a fn of no args that returns a test.check generator." [& opts] `(resolve-spec '~(explicate (ns-name *ns*) `(fspec ~@opts)))) (defn- macroexpand-check [v args] (let [fn-spec (get-spec v)] (when-let [arg-spec (:args fn-spec)] (when (invalid? (conform arg-spec args)) (let [ed (assoc (explain-data* arg-spec [] (if-let [name (spec-name arg-spec)] [name] []) [] args nil nil) ::sa/args args)] (throw (ex-info (str "Call to " (symbol v) " did not conform to spec.") ed))))))) (defmacro fdef "Takes a symbol naming a function, and one or more of the following: :args A regex spec for the function arguments as they were a list to be passed to apply - in this way, a single spec can handle functions with multiple arities :ret A spec for the function's return value :fn A spec of the relationship between args and ret - the value passed is {:args conformed-args :ret conformed-ret} and is expected to contain predicates that relate those values Qualifies fn-sym with resolve, or using *ns* if no resolution found. Registers an fspec in the global registry, where it can be retrieved by calling get-spec with the var or fully-qualified symbol. Once registered, function specs are included in doc, checked by instrument, tested by the runner clojure.alpha.spec.test/check, and (if a macro) used to explain errors during macroexpansion. Note that :fn specs require the presence of :args and :ret specs to conform values, and so :fn specs will be ignored if :args or :ret are missing. Returns the qualified fn-sym. For example, to register function specs for the symbol function: (s/fdef clojure.core/symbol :args (s/alt :separate (s/cat :ns string? :n string?) :str string? :sym symbol?) :ret symbol?)" [fn-sym & specs] `(clojure.alpha.spec/def ~fn-sym (clojure.alpha.spec/fspec ~@specs))) (defmacro keys "Creates and returns a map validating spec. :req and :opt are both vectors of namespaced-qualified keywords. The validator will ensure the :req keys are present. The :opt keys serve as documentation and may be used by the generator. The :req key vector supports 'and' and 'or' for key groups: (s/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z]) There are also -un versions of :req and :opt. These allow you to connect unqualified keys to specs. In each case, fully qualified keywords are passed, which name the specs, but unqualified keys (with the same name component) are expected and checked at conform-time, and generated during gen: (s/keys :req-un [:my.ns/x :my.ns/y]) The above says keys :x and :y are required, and will be validated and generated by specs (if they exist) named :my.ns/x :my.ns/y respectively. In addition, the values of *all* namespace-qualified keys will be validated (and possibly destructured) by any registered specs. Note: there is no support for inline value specification, by design. Optionally takes :gen generator-fn, which must be a fn of no args that returns a test.check generator." [& ks] `(resolve-spec '~(explicate (ns-name *ns*) `(keys ~@ks)))) (defmacro select "Takes a keyset and a selection pattern and returns a spec that validates a map. The keyset specifies what keys may be in the map and the specs to use if the keys are unqualified. The selection pattern indicates what keys must be in the map, and any nested maps." [keyset selection] `(resolve-spec '~(explicate (ns-name *ns*) `(select ~keyset ~selection)))) (defmacro multi-spec "Takes the name of a spec/predicate-returning multimethod and a tag-restoring keyword or fn (retag). Returns a spec that when conforming or explaining data will pass it to the multimethod to get an appropriate spec. You can e.g. use multi-spec to dynamically and extensibly associate specs with 'tagged' data (i.e. data where one of the fields indicates the shape of the rest of the structure). (defmulti mspec :tag) The methods should ignore their argument and return a predicate/spec: (defmethod mspec :int [_] (s/keys :req-un [::tag ::i])) retag is used during generation to retag generated values with matching tags. retag can either be a keyword, at which key the dispatch-tag will be assoc'ed, or a fn of generated value and dispatch-tag that should return an appropriately retagged value. Note that because the tags themselves comprise an open set, the tag key spec cannot enumerate the values, but can e.g. test for keyword?. Note also that the dispatch values of the multimethod will be included in the path, i.e. in reporting and gen overrides, even though those values are not evident in the spec. " [mm retag] `(resolve-spec '~(explicate (ns-name *ns*) `(multi-spec ~mm ~retag)))) (defmacro tuple "takes one or more preds and returns a spec for a tuple, a vector where each element conforms to the corresponding pred. Each element will be referred to in paths using its ordinal." [& preds] (c/assert (not (empty? preds))) `(resolve-spec '~(explicate (ns-name *ns*) `(tuple ~@preds)))) (defmacro or "Takes key+pred pairs, e.g. (s/or :even even? :small #(< % 42)) Returns a destructuring spec that returns a map entry containing the key of the first matching pred and the corresponding value. Thus the 'key' and 'val' functions can be used to refer generically to the components of the tagged return." [& key-pred-forms] (c/assert (c/and (even? (count key-pred-forms)) (->> key-pred-forms (partition 2) (map first) (every? keyword?))) "spec/or expects k1 p1 k2 p2..., where ks are keywords") `(resolve-spec '~(explicate (ns-name *ns*) `(or ~@key-pred-forms)))) (defmacro and "Takes predicate/spec-forms, e.g. (s/and int? even? #(< % 42)) Returns a spec that returns the conformed value. Successive conformed values propagate through rest of predicates." [& pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(and ~@pred-forms)))) (defmacro and- "Takes predicate/spec-forms, e.g. (s/and- (s/cat :i int?) #(pos? (first %))) Returns a spec that validates all preds on and returns the conformed value of the first pred. Conformed values are NOT propagated through rest of predicates." [& pred-forms] `(resolve-spec '~(explicate (ns-name *ns*) `(and- ~@pred-forms)))) (defmacro keys* "takes the same arguments as spec/keys and returns a regex op that matches sequences of key/values, converts them into a map, and conforms that map with a corresponding spec/keys call: user=> (s/conform (s/keys :req-un [::a ::c]) {:a 1 :c 2}) {:a 1, :c 2} user=> (s/conform (s/keys* :req-un [::a ::c]) [:a 1 :c 2]) {:a 1, :c 2} the resulting regex op can be composed into a larger regex: user=> (s/conform (s/cat :i1 integer? :m (s/keys* :req-un [::a ::c]) :i2 integer?) [42 :a 1 :c 2 :d 4 99]) {:i1 42, :m {:a 1, :c 2, :d 4}, :i2 99}" [& kspecs] `(resolve-spec '~(explicate (ns-name *ns*) `(keys* ~@kspecs)))) (defmacro nonconforming "takes a spec and returns a spec that has the same properties except 'conform' returns the original (not the conformed) value." [spec] `(resolve-spec '~(explicate (ns-name *ns*) `(nonconforming ~spec)))) (defmacro nilable "returns a spec that accepts nil and values satisfying pred" [pred] `(resolve-spec '~(explicate (ns-name *ns*) `(nilable ~pred)))) (defn exercise "generates a number (default 10) of values compatible with spec and maps conform over them, returning a sequence of [val conformed-val] tuples. Optionally takes a generator overrides map as per gen" ([spec] (exercise spec 10)) ([spec n] (exercise spec n nil)) ([spec n overrides] (map #(vector % (conform spec %)) (gen/sample (gen spec overrides) n)))) (defn exercise-fn "exercises the fn named by sym (a symbol) by applying it to n (default 10) generated samples of its args spec. When fspec is supplied its arg spec is used, and sym-or-f can be a fn. Returns a sequence of tuples of [args ret]. " ([sym] (exercise-fn sym 10)) ([sym n] (exercise-fn sym n (get-spec sym))) ([sym-or-f n fspec] (let [f (if (symbol? sym-or-f) (resolve sym-or-f) sym-or-f)] (if-let [arg-spec (c/and fspec (:args fspec))] (for [args (gen/sample (gen arg-spec) n)] [args (apply f args)]) (throw (Exception. "No :args spec found, can't generate")))))) (defn inst-in-range? "Return true if inst at or after start and before end" [start end inst] (c/and (inst? inst) (let [t (inst-ms inst)] (c/and (<= (inst-ms start) t) (< t (inst-ms end)))))) (defn int-in-range? "Return true if start <= val, val < end and val is a fixed precision integer." [start end val] (c/and (int? val) (<= start val) (< val end))) (defonce ^{:dynamic true :doc "If true, compiler will enable spec asserts, which are then subject to runtime control via check-asserts? If false, compiler will eliminate all spec assert overhead. See 'assert'. Initially set to boolean value of clojure.spec.compile-asserts system property. Defaults to true."} *compile-asserts* (not= "false" (System/getProperty "clojure.spec.compile-asserts"))) (defn check-asserts? "Returns the value set by check-asserts." [] clojure.lang.RT/checkSpecAsserts) (defn check-asserts "Enable or disable spec asserts that have been compiled with '*compile-asserts*' true. See 'assert'. Initially set to boolean value of clojure.spec.check-asserts system property. Defaults to false." [flag] (set! (. clojure.lang.RT checkSpecAsserts) flag)) (defn assert* "Do not call this directly, use 'assert'." [spec x] (if (valid? spec x) x (let [ed (c/merge (assoc (explain-data* spec [] [] [] x nil nil) ::sa/failure :assertion-failed))] (throw (ex-info (str "Spec assertion failed\n" (with-out-str (explain-out ed))) ed))))) (defmacro assert "spec-checking assert expression. Returns x if x is valid? according to spec, else throws an ex-info with explain-data plus ::failure of :assertion-failed. Can be disabled at either compile time or runtime: If *compile-asserts* is false at compile time, compiles to x. Defaults to value of 'clojure.spec.compile-asserts' system property, or true if not set. If (check-asserts?) is false at runtime, always returns x. Defaults to value of 'clojure.spec.check-asserts' system property, or false if not set. You can toggle check-asserts? with (check-asserts bool)." [spec x] (if *compile-asserts* `(if clojure.lang.RT/checkSpecAsserts (assert* ~spec ~x) ~x) x)) (defn ^:skip-wiki sig-map "Do not call directly." [sig vals] (let [locals (->> sig (tree-seq coll? identity) (filter #(c/and (symbol? %) (not= '& %))) distinct vec)] (zipmap locals (eval `(let [~sig ~(vec vals)] ~locals))))) (defn ^:skip-wiki op-spec "Do not call directly, use `defop`" [sp form gfn] (reify protocols/Spec (conform* [_ x settings-key settings] (protocols/conform* @sp x settings-key settings)) (unform* [_ x] (unform @sp x)) (explain* [_ path via in x settings-key settings] (protocols/explain* @sp path via in x settings-key settings)) (gen* [_ _ _ _] (if gfn (gfn) (gen @sp))) (with-gen* [_ gfn] (op-spec sp form gfn)) (describe* [_] form))) (defmacro defop "Defines a new spec op with op-name defined by the form. Defines a macro for op-name with docstring that expands to a call to resolve-spec with the explicated form. args are replaced in the form. Creates a create-spec method implementation for op-name that creates a spec whose body is form. Opts allowed: :gen - takes a no-arg function returning a generator to use" {:arglists '([op-name doc-string? opts? [params*] form])} [op-name & op-tail] (let [form (last op-tail) opts (butlast op-tail) [doc args opts] (if (string? (first opts)) [(first opts) (second opts) (nthrest opts 2)] [nil (first opts) (rest opts)]) _ (c/assert (even? (count opts)) "defop options should be keyword/value pairs") {:keys [gen]} opts ns-name (ns-name *ns*) op (symbol (name ns-name) (name op-name))] `(do (defmethod expand-spec '~op [[~'_ ~'& ~'sargs]] (let [os# '~op] {:clojure.spec/op os# :args ~'sargs})) (defmethod create-spec '~op [~'mform] (let [a# (:args ~'mform) sp# (delay (resolve-spec (explicate '~ns-name (walk/postwalk (fn [x#] (get m# x# x#)) '~form))))] (op-spec sp# (cons '~op a#) (resolve-fn (walk/postwalk (fn [x#] (get m# x# x#)) '~gen))))) (defmacro ~op-name [~'& ~'sargs] (list `resolve-spec (list `explicate (list `quote '~ns-name) (list `quote (cons '~op ~'sargs)))))))) (load "/clojure/alpha/spec/impl") (defop inst-in "Returns a spec that validates insts in the range from start (inclusive) to end (exclusive)." [start end] :gen #(clojure.alpha.spec.gen/fmap (fn [^long d] (java.util.Date. d)) (clojure.alpha.spec.gen/large-integer* {:min (inst-ms start) :max (inst-ms end)})) (and inst? #(inst-in-range? start end %))) (defop int-in "Returns a spec that validates fixed precision integers in the range from start (inclusive) to end (exclusive)." [start end] :gen #(clojure.alpha.spec.gen/large-integer* {:min start :max (dec end)}) (and int? #(int-in-range? start end %))) (defop double-in "Specs a 64-bit floating point number. Options: :infinite? - whether +/- infinity allowed (default true) :NaN? - whether NaN allowed (default true) :min - minimum value (inclusive, default none) :max - maximum value (inclusive, default none)" [& {:keys [infinite? NaN? min max :as m]}] :gen #(clojure.alpha.spec.gen/double* m) (and double? #(if-not infinite? (not (Double/isInfinite %))) #(if-not NaN? (not (Double/isNaN %))) #(if min (<= min %) true) #(if max (<= % max) true))) (defmacro defcompop "Defines a new composite spec with op-name and args same as spec-op. The new spec takes the same args as spec-op, and also ensures the preds are satisfied." {:arglists '([op-name doc-string? spec-op preds+])} [op-name & tail] (let [[doc spec-op & preds] (if (string? (first tail)) tail (cons nil tail)) ns-name (ns-name *ns*) op (symbol (name ns-name) (name op-name))] (c/assert (pos? (count preds)) "defcompop should have at least one pred") `(do (defmethod expand-spec '~op [[~'_ ~'& ~'sargs]] (let [os# '~op] {:clojure.spec/op os# :primary '~(explicate ns-name spec-op) :preds '~(explicate ns-name preds) :args ~'sargs})) (defmethod create-spec '~op [~'mform] (let [primary# (:primary ~'mform) preds# (:preds ~'mform) a# (:args ~'mform) comp-spec# (concat (list 'clojure.alpha.spec/and- (cons '~(explicate ns-name spec-op) a#)) preds#)] (resolve-spec comp-spec#))) (defmacro ~op-name ~@(if doc [doc] []) {:arglists '~(:arglists (meta (find-var (explicate ns-name spec-op))))} [~'& ~'sargs] (list `resolve-spec (list `explicate (list `quote '~ns-name) (list `quote (cons '~op ~'sargs)))))))) (defcompop catv "Like s/cat, but constrain to only vectors" cat vector?) (defcompop cats "Like s/cat, but constrain to only seqs" cat seq?)
a5c9e7e0b3360129a70e2f3c9df9a3e99908b3f8e0ffeb29c524424b0dd581d1
synduce/Synduce
minmax_sim.ml
let xi_0 a = (a, a) let xi_2 b c x = (max (max b c) x, min (min b c) x) let rec target = function Leaf(a) -> xi_0 a | Node(a, l, r) -> xi_2 a (amin l) (amax r) and amin = function Leaf(a) -> a | Node(a, l, r) -> min a (min (amin l) (amin r)) and amax = function Leaf(a) -> a | Node(a, l, r) -> max a (max (amax l) (amax r))
null
https://raw.githubusercontent.com/synduce/Synduce/289888afb1c312adfd631ce8d90df2134de827b8/extras/solutions/constraints/bst/minmax_sim.ml
ocaml
let xi_0 a = (a, a) let xi_2 b c x = (max (max b c) x, min (min b c) x) let rec target = function Leaf(a) -> xi_0 a | Node(a, l, r) -> xi_2 a (amin l) (amax r) and amin = function Leaf(a) -> a | Node(a, l, r) -> min a (min (amin l) (amin r)) and amax = function Leaf(a) -> a | Node(a, l, r) -> max a (max (amax l) (amax r))
da22e4cee375a90500dccdbbe682170091782152969a51e20e6bb82ad69e5f93
code-iai/ros_emacs_utils
swank-package-fu.lisp
(in-package :swank) (defslimefun package= (string1 string2) (let* ((pkg1 (guess-package string1)) (pkg2 (guess-package string2))) (and pkg1 pkg2 (eq pkg1 pkg2)))) (defslimefun export-symbol-for-emacs (symbol-str package-str) (let ((package (guess-package package-str))) (when package (let ((*buffer-package* package)) (export `(,(from-string symbol-str)) package))))) (defslimefun unexport-symbol-for-emacs (symbol-str package-str) (let ((package (guess-package package-str))) (when package (let ((*buffer-package* package)) (unexport `(,(from-string symbol-str)) package))))) #+sbcl (defun list-structure-symbols (name) (let ((dd (sb-kernel:find-defstruct-description name ))) (list* name (sb-kernel:dd-default-constructor dd) (sb-kernel:dd-predicate-name dd) (sb-kernel::dd-copier-name dd) (mapcar #'sb-kernel:dsd-accessor-name (sb-kernel:dd-slots dd))))) #+ccl (defun list-structure-symbols (name) (let ((definition (gethash name ccl::%defstructs%))) (list* name (ccl::sd-constructor definition) (ccl::sd-refnames definition)))) (defun list-class-symbols (name) (let* ((class (find-class name)) (slots (swank-mop:class-direct-slots class))) (labels ((extract-symbol (name) (if (and (consp name) (eql (car name) 'setf)) (cadr name) name)) (slot-accessors (slot) (nintersection (copy-list (swank-mop:slot-definition-readers slot)) (copy-list (swank-mop:slot-definition-readers slot)) :key #'extract-symbol))) (list* (class-name class) (mapcan #'slot-accessors slots))))) (defslimefun export-structure (name package) (let ((*package* (guess-package package))) (when *package* (let* ((name (from-string name)) (symbols (cond #+(or sbcl ccl) ((or (not (find-class name nil)) (subtypep name 'structure-object)) (list-structure-symbols name)) (t (list-class-symbols name))))) (export symbols) symbols)))) (provide :swank-package-fu)
null
https://raw.githubusercontent.com/code-iai/ros_emacs_utils/67aafa699ff0d8c6476ec577a8587bac3d498028/slime_wrapper/slime/contrib/swank-package-fu.lisp
lisp
(in-package :swank) (defslimefun package= (string1 string2) (let* ((pkg1 (guess-package string1)) (pkg2 (guess-package string2))) (and pkg1 pkg2 (eq pkg1 pkg2)))) (defslimefun export-symbol-for-emacs (symbol-str package-str) (let ((package (guess-package package-str))) (when package (let ((*buffer-package* package)) (export `(,(from-string symbol-str)) package))))) (defslimefun unexport-symbol-for-emacs (symbol-str package-str) (let ((package (guess-package package-str))) (when package (let ((*buffer-package* package)) (unexport `(,(from-string symbol-str)) package))))) #+sbcl (defun list-structure-symbols (name) (let ((dd (sb-kernel:find-defstruct-description name ))) (list* name (sb-kernel:dd-default-constructor dd) (sb-kernel:dd-predicate-name dd) (sb-kernel::dd-copier-name dd) (mapcar #'sb-kernel:dsd-accessor-name (sb-kernel:dd-slots dd))))) #+ccl (defun list-structure-symbols (name) (let ((definition (gethash name ccl::%defstructs%))) (list* name (ccl::sd-constructor definition) (ccl::sd-refnames definition)))) (defun list-class-symbols (name) (let* ((class (find-class name)) (slots (swank-mop:class-direct-slots class))) (labels ((extract-symbol (name) (if (and (consp name) (eql (car name) 'setf)) (cadr name) name)) (slot-accessors (slot) (nintersection (copy-list (swank-mop:slot-definition-readers slot)) (copy-list (swank-mop:slot-definition-readers slot)) :key #'extract-symbol))) (list* (class-name class) (mapcan #'slot-accessors slots))))) (defslimefun export-structure (name package) (let ((*package* (guess-package package))) (when *package* (let* ((name (from-string name)) (symbols (cond #+(or sbcl ccl) ((or (not (find-class name nil)) (subtypep name 'structure-object)) (list-structure-symbols name)) (t (list-class-symbols name))))) (export symbols) symbols)))) (provide :swank-package-fu)
46c0aadf1bc40b79c053f5bdf1476ea48f7e043b1af5be1b050b4afa7019dd98
jasonkuhrt-archive/hpfp-answers
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad (replicateM, (<=<)) import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Char8 as BC import Data.Text.Encoding (decodeUtf8, encodeUtf8) import qualified Data.Text.Lazy as TL import qualified Database.Redis as Redis import Database.Redis (Redis) import Network.URI (URI, parseURI) import qualified System.Random as SR import Web.Scotty import Data.Monoid ((<>)) import qualified Control.Monad.Reader as Reader import Control.Monad.Reader (ReaderT, ask, runReaderT) -- We need to generate our shortened URIs that refer to the links people post to this service. In order to rename, we need a character pool to select from: charPool :: String charPool = ['A'..'Z'] <> ['0'..'9'] -- Now we need to pick random elements from the pool. We will need to be impure to achieve randomness: randomElement :: String -> IO Char randomElement xs = fmap (xs !!) randomIndex where randomIndex = SR.randomRIO indexRange indexRange :: (Int, Int) indexRange = (0, length xs - 1) Next we apply randomElement to our char pool . By repeating this seven times we can make strings of seven random characters . genShortLink :: IO String genShortLink = replicateM 7 (randomElement charPool) Next we need to persistently store shortLinks and the URIs they point to . We can model this by treating shortLinks as keys and the URI they point to as the key 's value . Other data at play will be a connection to Redis , and a result of storing a shortLink ( which lets us know if there was an error , otherwise the status after finishing the command ) . saveURI :: BC.ByteString -> BC.ByteString -> ReaderT Redis.Connection IO (Either Redis.Reply Bool) saveURI shortLink uri = do conn <- ask let Redis setnx semantics are that if the key already exists its value is not overwritten . We want these semantics because users should not be overwritting their own or others ' shortLinks . A conflict is modelled here via False which states that while there was no unexpected error in trying to execute the command the key did exist and so no value was written . When this happens we should just try again . One conflict is already astronomically unlikely to happen , an loop / infinite loop of conflicts is infinitely more so , so this is a safe strategy I think ! And we avoid doubling the cost of every request with a Redis ` exists ` check . go = ensureSaved <=< redisRun (Redis.setnx shortLink uri) -- TODO ...we need to generate a new shortLink! ensureSaved (Right False) = go conn ensureSaved value = return value Reader.ReaderT go Next we need a way to get at a URI via its shortLink . getURI :: BC.ByteString -> ReaderT Redis.Connection IO (Either Redis.Reply (Maybe BC.ByteString)) getURI = Reader.ReaderT . redisRun . Redis.get -- Next are the web-service parts. app :: Redis.Connection -> ScottyM () app conn = do get "/" $ do uri <- param "uri" let parsedURI :: Maybe URI parsedURI = parseURI (TL.unpack uri) case parsedURI of Nothing -> text (uri <> " is an invalid URI.") Just _ -> do shortLink <- liftIO genShortLink let shortLink' = BC.pack shortLink uri' = encodeUtf8 (TL.toStrict uri) response <- liftIO (Reader.runReaderT (saveURI shortLink' uri') conn) text . TL.pack $ shortLink get "/:shortLink" $ do shortLink <- param "shortLink" uri <- liftIO (Reader.runReaderT (getURI shortLink) conn) case uri of Left reply -> text . TL.pack . show $ reply Right maybeURI -> case maybeURI of Nothing -> text "URI not found" Just byteString -> text . TL.fromStrict . decodeUtf8 $ byteString -- Next we need an entry point into this application. This is happens upon launch. main :: IO () main = do conn <- Redis.connect Redis.defaultConnectInfo scotty 3000 (app conn) -- Helpers redisRun :: Redis a -> Redis.Connection -> IO a redisRun = flip Redis.runRedis
null
https://raw.githubusercontent.com/jasonkuhrt-archive/hpfp-answers/c03ae936f208cfa3ca1eb0e720a5527cebe4c034/chapter-19-structure-applied/shrinkr/app/Main.hs
haskell
# LANGUAGE OverloadedStrings # We need to generate our shortened URIs that refer to the links people post to this service. In order to rename, we need a character pool to select from: Now we need to pick random elements from the pool. We will need to be impure to achieve randomness: TODO ...we need to generate a new shortLink! Next are the web-service parts. Next we need an entry point into this application. This is happens upon launch. Helpers
module Main where import Control.Monad (replicateM, (<=<)) import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Char8 as BC import Data.Text.Encoding (decodeUtf8, encodeUtf8) import qualified Data.Text.Lazy as TL import qualified Database.Redis as Redis import Database.Redis (Redis) import Network.URI (URI, parseURI) import qualified System.Random as SR import Web.Scotty import Data.Monoid ((<>)) import qualified Control.Monad.Reader as Reader import Control.Monad.Reader (ReaderT, ask, runReaderT) charPool :: String charPool = ['A'..'Z'] <> ['0'..'9'] randomElement :: String -> IO Char randomElement xs = fmap (xs !!) randomIndex where randomIndex = SR.randomRIO indexRange indexRange :: (Int, Int) indexRange = (0, length xs - 1) Next we apply randomElement to our char pool . By repeating this seven times we can make strings of seven random characters . genShortLink :: IO String genShortLink = replicateM 7 (randomElement charPool) Next we need to persistently store shortLinks and the URIs they point to . We can model this by treating shortLinks as keys and the URI they point to as the key 's value . Other data at play will be a connection to Redis , and a result of storing a shortLink ( which lets us know if there was an error , otherwise the status after finishing the command ) . saveURI :: BC.ByteString -> BC.ByteString -> ReaderT Redis.Connection IO (Either Redis.Reply Bool) saveURI shortLink uri = do conn <- ask let Redis setnx semantics are that if the key already exists its value is not overwritten . We want these semantics because users should not be overwritting their own or others ' shortLinks . A conflict is modelled here via False which states that while there was no unexpected error in trying to execute the command the key did exist and so no value was written . When this happens we should just try again . One conflict is already astronomically unlikely to happen , an loop / infinite loop of conflicts is infinitely more so , so this is a safe strategy I think ! And we avoid doubling the cost of every request with a Redis ` exists ` check . go = ensureSaved <=< redisRun (Redis.setnx shortLink uri) ensureSaved (Right False) = go conn ensureSaved value = return value Reader.ReaderT go Next we need a way to get at a URI via its shortLink . getURI :: BC.ByteString -> ReaderT Redis.Connection IO (Either Redis.Reply (Maybe BC.ByteString)) getURI = Reader.ReaderT . redisRun . Redis.get app :: Redis.Connection -> ScottyM () app conn = do get "/" $ do uri <- param "uri" let parsedURI :: Maybe URI parsedURI = parseURI (TL.unpack uri) case parsedURI of Nothing -> text (uri <> " is an invalid URI.") Just _ -> do shortLink <- liftIO genShortLink let shortLink' = BC.pack shortLink uri' = encodeUtf8 (TL.toStrict uri) response <- liftIO (Reader.runReaderT (saveURI shortLink' uri') conn) text . TL.pack $ shortLink get "/:shortLink" $ do shortLink <- param "shortLink" uri <- liftIO (Reader.runReaderT (getURI shortLink) conn) case uri of Left reply -> text . TL.pack . show $ reply Right maybeURI -> case maybeURI of Nothing -> text "URI not found" Just byteString -> text . TL.fromStrict . decodeUtf8 $ byteString main :: IO () main = do conn <- Redis.connect Redis.defaultConnectInfo scotty 3000 (app conn) redisRun :: Redis a -> Redis.Connection -> IO a redisRun = flip Redis.runRedis
7c6241c403c1eb3cc9b5922cb48c3de5e3340ef15c84c5a84c3147d5925e9962
metabase/metabase
tables.clj
(ns metabase.sync.sync-metadata.tables "Logic for updating Metabase Table models from metadata fetched from a physical DB." (:require [clojure.data :as data] [clojure.string :as str] [metabase.models.database :refer [Database]] [metabase.models.humanization :as humanization] [metabase.models.interface :as mi] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as perms-group] [metabase.models.table :refer [Table]] [metabase.sync.fetch-metadata :as fetch-metadata] [metabase.sync.interface :as i] [metabase.sync.sync-metadata.metabase-metadata :as metabase-metadata] [metabase.sync.util :as sync-util] [metabase.util :as u] [metabase.util.i18n :refer [trs]] [metabase.util.log :as log] [schema.core :as s] [toucan.db :as db])) ------------------------------------------------ " Crufty " Tables ------------------------------------------------- Crufty tables are ones we know are from frameworks like Rails or Django and thus automatically mark as ` : cruft ` (def ^:private crufty-table-patterns "Regular expressions that match Tables that should automatically given the `visibility-type` of `:cruft`. This means they are automatically hidden to users (but can be unhidden in the admin panel). These `Tables` are known to not contain useful data, such as migration or web framework internal tables." #{;; Django #"^auth_group$" #"^auth_group_permissions$" #"^auth_permission$" #"^django_admin_log$" #"^django_content_type$" #"^django_migrations$" #"^django_session$" #"^django_site$" #"^south_migrationhistory$" #"^user_groups$" #"^user_user_permissions$" ;; Drupal #".*_cache$" #".*_revision$" #"^advagg_.*" #"^apachesolr_.*" #"^authmap$" #"^autoload_registry.*" #"^batch$" #"^blocked_ips$" #"^cache.*" #"^captcha_.*" #"^config$" #"^field_revision_.*" #"^flood$" #"^node_revision.*" #"^queue$" #"^rate_bot_.*" #"^registry.*" #"^router.*" #"^semaphore$" #"^sequences$" #"^sessions$" #"^watchdog$" Rails / Active Record #"^schema_migrations$" #"^ar_internal_metadata$" ;; PostGIS #"^spatial_ref_sys$" ;; nginx #"^nginx_access_log$" Liquibase #"^databasechangelog$" #"^databasechangeloglock$" Lobos #"^lobos_migrations$" MSSQL #"^syncobj_0x.*"}) (s/defn ^:private is-crufty-table? :- s/Bool "Should we give newly created TABLE a `visibility_type` of `:cruft`?" [table :- i/DatabaseMetadataTable] (boolean (some #(re-find % (u/lower-case-en (:name table))) crufty-table-patterns))) ;;; ---------------------------------------------------- Syncing ----------------------------------------------------- (s/defn ^:private update-database-metadata! "If there is a version in the db-metadata update the DB to have that in the DB model" [database :- i/DatabaseInstance db-metadata :- i/DatabaseMetadata] (log/info (trs "Found new version for DB: {0}" (:version db-metadata))) (db/update! Database (u/the-id database) :details (assoc (:details database) :version (:version db-metadata)))) (defn create-or-reactivate-table! "Create a single new table in the database, or mark it as active if it already exists." [database {schema :schema, table-name :name, :as table}] (if-let [existing-id (db/select-one-id Table :db_id (u/the-id database) :schema schema :name table-name :active false)] ;; if the table already exists but is marked *inactive*, mark it as *active* (db/update! Table existing-id :active true) ;; otherwise create a new Table (let [is-crufty? (is-crufty-table? table)] (db/insert! Table :db_id (u/the-id database) :schema schema :name table-name :display_name (humanization/name->human-readable-name table-name) :active true :visibility_type (when is-crufty? :cruft) ;; if this is a crufty table, mark initial sync as complete since we'll skip the subsequent sync steps :initial_sync_status (if is-crufty? "complete" "incomplete"))))) ;; TODO - should we make this logic case-insensitive like it is for fields? (s/defn ^:private create-or-reactivate-tables! "Create NEW-TABLES for database, or if they already exist, mark them as active." [database :- i/DatabaseInstance, new-tables :- #{i/DatabaseMetadataTable}] (log/info (trs "Found new tables:") (for [table new-tables] (sync-util/name-for-logging (mi/instance Table table)))) (doseq [table new-tables] (create-or-reactivate-table! database table))) (s/defn ^:private retire-tables! "Mark any `old-tables` belonging to `database` as inactive." [database :- i/DatabaseInstance, old-tables :- #{i/DatabaseMetadataTable}] (log/info (trs "Marking tables as inactive:") (for [table old-tables] (sync-util/name-for-logging (mi/instance Table table)))) (doseq [{schema :schema, table-name :name, :as _table} old-tables] (db/update-where! Table {:db_id (u/the-id database) :schema schema :name table-name :active true} :active false))) (s/defn ^:private update-table-description! "Update description for any `changed-tables` belonging to `database`." [database :- i/DatabaseInstance, changed-tables :- #{i/DatabaseMetadataTable}] (log/info (trs "Updating description for tables:") (for [table changed-tables] (sync-util/name-for-logging (mi/instance Table table)))) (doseq [{schema :schema, table-name :name, description :description} changed-tables] (when-not (str/blank? description) (db/update-where! Table {:db_id (u/the-id database) :schema schema :name table-name :description nil} :description description)))) (s/defn ^:private table-set :- #{i/DatabaseMetadataTable} "So there exist tables for the user and metabase metadata tables for internal usage by metabase. Get set of user tables only, excluding metabase metadata tables." [db-metadata :- i/DatabaseMetadata] (set (for [table (:tables db-metadata) :when (not (metabase-metadata/is-metabase-metadata-table? table))] table))) (s/defn ^:private our-metadata :- #{i/DatabaseMetadataTable} "Return information about what Tables we have for this DB in the Metabase application DB." [database :- i/DatabaseInstance] (set (map (partial into {}) (db/select [Table :name :schema :description] :db_id (u/the-id database) :active true)))) (s/defn sync-tables-and-database! "Sync the Tables recorded in the Metabase application database with the ones obtained by calling `database`'s driver's implementation of `describe-database`. Also syncs the database metadata taken from describe-database if there is any" ([database :- i/DatabaseInstance] (sync-tables-and-database! database (fetch-metadata/db-metadata database))) ([database :- i/DatabaseInstance db-metadata] ;; determine what's changed between what info we have and what's in the DB (let [db-tables (table-set db-metadata) our-metadata (our-metadata database) strip-desc (fn [metadata] (set (map #(dissoc % :description) metadata))) [new-tables old-tables] (data/diff (strip-desc db-tables) (strip-desc our-metadata)) [changed-tables] (data/diff db-tables our-metadata)] ;; update database metadata from database (when (some? (:version db-metadata)) (sync-util/with-error-handling (format "Error creating/reactivating tables for %s" (sync-util/name-for-logging database)) (update-database-metadata! database db-metadata))) ;; create new tables as needed or mark them as active again (when (seq new-tables) (sync-util/with-error-handling (format "Error creating/reactivating tables for %s" (sync-util/name-for-logging database)) (create-or-reactivate-tables! database new-tables))) ;; mark old tables as inactive (when (seq old-tables) (sync-util/with-error-handling (format "Error retiring tables for %s" (sync-util/name-for-logging database)) (retire-tables! database old-tables))) ;; update description for changed tables (when (seq changed-tables) (sync-util/with-error-handling (format "Error updating table description for %s" (sync-util/name-for-logging database)) (update-table-description! database changed-tables))) ;; update native download perms for all groups if any tables were added or removed (when (or (seq new-tables) (seq old-tables)) (sync-util/with-error-handling (format "Error updating native download perms for %s" (sync-util/name-for-logging database)) (doseq [{id :id} (perms-group/non-admin-groups)] (perms/update-native-download-permissions! id (u/the-id database))))) {:updated-tables (+ (count new-tables) (count old-tables)) :total-tables (count our-metadata)})))
null
https://raw.githubusercontent.com/metabase/metabase/dad3d414e5bec482c15d826dcc97772412c98652/src/metabase/sync/sync_metadata/tables.clj
clojure
Django Drupal PostGIS nginx ---------------------------------------------------- Syncing ----------------------------------------------------- if the table already exists but is marked *inactive*, mark it as *active* otherwise create a new Table if this is a crufty table, mark initial sync as complete since we'll skip the subsequent sync steps TODO - should we make this logic case-insensitive like it is for fields? determine what's changed between what info we have and what's in the DB update database metadata from database create new tables as needed or mark them as active again mark old tables as inactive update description for changed tables update native download perms for all groups if any tables were added or removed
(ns metabase.sync.sync-metadata.tables "Logic for updating Metabase Table models from metadata fetched from a physical DB." (:require [clojure.data :as data] [clojure.string :as str] [metabase.models.database :refer [Database]] [metabase.models.humanization :as humanization] [metabase.models.interface :as mi] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as perms-group] [metabase.models.table :refer [Table]] [metabase.sync.fetch-metadata :as fetch-metadata] [metabase.sync.interface :as i] [metabase.sync.sync-metadata.metabase-metadata :as metabase-metadata] [metabase.sync.util :as sync-util] [metabase.util :as u] [metabase.util.i18n :refer [trs]] [metabase.util.log :as log] [schema.core :as s] [toucan.db :as db])) ------------------------------------------------ " Crufty " Tables ------------------------------------------------- Crufty tables are ones we know are from frameworks like Rails or Django and thus automatically mark as ` : cruft ` (def ^:private crufty-table-patterns "Regular expressions that match Tables that should automatically given the `visibility-type` of `:cruft`. This means they are automatically hidden to users (but can be unhidden in the admin panel). These `Tables` are known to not contain useful data, such as migration or web framework internal tables." #"^auth_group$" #"^auth_group_permissions$" #"^auth_permission$" #"^django_admin_log$" #"^django_content_type$" #"^django_migrations$" #"^django_session$" #"^django_site$" #"^south_migrationhistory$" #"^user_groups$" #"^user_user_permissions$" #".*_cache$" #".*_revision$" #"^advagg_.*" #"^apachesolr_.*" #"^authmap$" #"^autoload_registry.*" #"^batch$" #"^blocked_ips$" #"^cache.*" #"^captcha_.*" #"^config$" #"^field_revision_.*" #"^flood$" #"^node_revision.*" #"^queue$" #"^rate_bot_.*" #"^registry.*" #"^router.*" #"^semaphore$" #"^sequences$" #"^sessions$" #"^watchdog$" Rails / Active Record #"^schema_migrations$" #"^ar_internal_metadata$" #"^spatial_ref_sys$" #"^nginx_access_log$" Liquibase #"^databasechangelog$" #"^databasechangeloglock$" Lobos #"^lobos_migrations$" MSSQL #"^syncobj_0x.*"}) (s/defn ^:private is-crufty-table? :- s/Bool "Should we give newly created TABLE a `visibility_type` of `:cruft`?" [table :- i/DatabaseMetadataTable] (boolean (some #(re-find % (u/lower-case-en (:name table))) crufty-table-patterns))) (s/defn ^:private update-database-metadata! "If there is a version in the db-metadata update the DB to have that in the DB model" [database :- i/DatabaseInstance db-metadata :- i/DatabaseMetadata] (log/info (trs "Found new version for DB: {0}" (:version db-metadata))) (db/update! Database (u/the-id database) :details (assoc (:details database) :version (:version db-metadata)))) (defn create-or-reactivate-table! "Create a single new table in the database, or mark it as active if it already exists." [database {schema :schema, table-name :name, :as table}] (if-let [existing-id (db/select-one-id Table :db_id (u/the-id database) :schema schema :name table-name :active false)] (db/update! Table existing-id :active true) (let [is-crufty? (is-crufty-table? table)] (db/insert! Table :db_id (u/the-id database) :schema schema :name table-name :display_name (humanization/name->human-readable-name table-name) :active true :visibility_type (when is-crufty? :cruft) :initial_sync_status (if is-crufty? "complete" "incomplete"))))) (s/defn ^:private create-or-reactivate-tables! "Create NEW-TABLES for database, or if they already exist, mark them as active." [database :- i/DatabaseInstance, new-tables :- #{i/DatabaseMetadataTable}] (log/info (trs "Found new tables:") (for [table new-tables] (sync-util/name-for-logging (mi/instance Table table)))) (doseq [table new-tables] (create-or-reactivate-table! database table))) (s/defn ^:private retire-tables! "Mark any `old-tables` belonging to `database` as inactive." [database :- i/DatabaseInstance, old-tables :- #{i/DatabaseMetadataTable}] (log/info (trs "Marking tables as inactive:") (for [table old-tables] (sync-util/name-for-logging (mi/instance Table table)))) (doseq [{schema :schema, table-name :name, :as _table} old-tables] (db/update-where! Table {:db_id (u/the-id database) :schema schema :name table-name :active true} :active false))) (s/defn ^:private update-table-description! "Update description for any `changed-tables` belonging to `database`." [database :- i/DatabaseInstance, changed-tables :- #{i/DatabaseMetadataTable}] (log/info (trs "Updating description for tables:") (for [table changed-tables] (sync-util/name-for-logging (mi/instance Table table)))) (doseq [{schema :schema, table-name :name, description :description} changed-tables] (when-not (str/blank? description) (db/update-where! Table {:db_id (u/the-id database) :schema schema :name table-name :description nil} :description description)))) (s/defn ^:private table-set :- #{i/DatabaseMetadataTable} "So there exist tables for the user and metabase metadata tables for internal usage by metabase. Get set of user tables only, excluding metabase metadata tables." [db-metadata :- i/DatabaseMetadata] (set (for [table (:tables db-metadata) :when (not (metabase-metadata/is-metabase-metadata-table? table))] table))) (s/defn ^:private our-metadata :- #{i/DatabaseMetadataTable} "Return information about what Tables we have for this DB in the Metabase application DB." [database :- i/DatabaseInstance] (set (map (partial into {}) (db/select [Table :name :schema :description] :db_id (u/the-id database) :active true)))) (s/defn sync-tables-and-database! "Sync the Tables recorded in the Metabase application database with the ones obtained by calling `database`'s driver's implementation of `describe-database`. Also syncs the database metadata taken from describe-database if there is any" ([database :- i/DatabaseInstance] (sync-tables-and-database! database (fetch-metadata/db-metadata database))) ([database :- i/DatabaseInstance db-metadata] (let [db-tables (table-set db-metadata) our-metadata (our-metadata database) strip-desc (fn [metadata] (set (map #(dissoc % :description) metadata))) [new-tables old-tables] (data/diff (strip-desc db-tables) (strip-desc our-metadata)) [changed-tables] (data/diff db-tables our-metadata)] (when (some? (:version db-metadata)) (sync-util/with-error-handling (format "Error creating/reactivating tables for %s" (sync-util/name-for-logging database)) (update-database-metadata! database db-metadata))) (when (seq new-tables) (sync-util/with-error-handling (format "Error creating/reactivating tables for %s" (sync-util/name-for-logging database)) (create-or-reactivate-tables! database new-tables))) (when (seq old-tables) (sync-util/with-error-handling (format "Error retiring tables for %s" (sync-util/name-for-logging database)) (retire-tables! database old-tables))) (when (seq changed-tables) (sync-util/with-error-handling (format "Error updating table description for %s" (sync-util/name-for-logging database)) (update-table-description! database changed-tables))) (when (or (seq new-tables) (seq old-tables)) (sync-util/with-error-handling (format "Error updating native download perms for %s" (sync-util/name-for-logging database)) (doseq [{id :id} (perms-group/non-admin-groups)] (perms/update-native-download-permissions! id (u/the-id database))))) {:updated-tables (+ (count new-tables) (count old-tables)) :total-tables (count our-metadata)})))
698a37f4b1bca00996598105af79eafe342c3447e4968ca0c9b0b993eda60e4b
wireapp/wire-server
IntersperseSpec.hs
# LANGUAGE NumDecimals # # OPTIONS_GHC -fplugin = Polysemy . Plugin # module Test.IntersperseSpec where import qualified Data.Set as S import Imports hiding (intersperse) import Polysemy import Polysemy.Output (output) import Polysemy.State (evalState, get, modify) import Polysemy.Testing import Polysemy.Trace import Test.Hspec import UnliftIO (async) # ANN spec ( " HLint : ignore Redundant pure " : : String ) # spec :: Spec spec = do -- This test spins up an async thread that communicates with the main polysemy monad via an ' MVar ' . We then use ' intersperse ' to inject polling logic between each bind in order to read from the ' MVar ' . it "should poll from async-written channel" $ do result <- liftIO test let desired = S.fromList $ mconcat [ fmap ("loaded: " <>) ["hello", "world", "last"], fmap (show @Int) [1 .. 4], ["finished"] ] result `shouldBe` desired -- Example showing how intersperse lays out actions it "should stick code before every action" $ do let result = fst $ run $ runTraceList $ outputToTrace show $ evalState @Int 0 $ intersperse ((output =<< get) <* modify (+ 1)) $ do 0 trace "start" pure () 1 trace "middle" 2 _ <- get 3 trace "end" result `shouldBe` ["0", "start", "1", "middle", "2", "3", "end"] pull :: (Member (Embed IO) r, Member Trace r) => MVar String -> Sem r () pull chan = do embed (tryTakeMVar chan) >>= \case Nothing -> pure () Just s -> do trace $ "loaded: " <> s pull chan push :: MVar String -> IO () push chan = do putMVar chan "hello" putMVar chan "world" putMVar chan "last" test :: IO (Set String) test = fmap S.fromList $ do chan <- newEmptyMVar @_ @String _ <- async $ push chan fmap fst $ runM $ runTraceList $ intersperse (pull chan) $ do for_ [1 .. 4] $ \i -> do trace $ show @Int i liftIO $ threadDelay 1e5 trace "finished"
null
https://raw.githubusercontent.com/wireapp/wire-server/91b1be585940f6169131440090c29aa61516ac65/libs/polysemy-wire-zoo/test/Test/IntersperseSpec.hs
haskell
This test spins up an async thread that communicates with the main Example showing how intersperse lays out actions
# LANGUAGE NumDecimals # # OPTIONS_GHC -fplugin = Polysemy . Plugin # module Test.IntersperseSpec where import qualified Data.Set as S import Imports hiding (intersperse) import Polysemy import Polysemy.Output (output) import Polysemy.State (evalState, get, modify) import Polysemy.Testing import Polysemy.Trace import Test.Hspec import UnliftIO (async) # ANN spec ( " HLint : ignore Redundant pure " : : String ) # spec :: Spec spec = do polysemy monad via an ' MVar ' . We then use ' intersperse ' to inject polling logic between each bind in order to read from the ' MVar ' . it "should poll from async-written channel" $ do result <- liftIO test let desired = S.fromList $ mconcat [ fmap ("loaded: " <>) ["hello", "world", "last"], fmap (show @Int) [1 .. 4], ["finished"] ] result `shouldBe` desired it "should stick code before every action" $ do let result = fst $ run $ runTraceList $ outputToTrace show $ evalState @Int 0 $ intersperse ((output =<< get) <* modify (+ 1)) $ do 0 trace "start" pure () 1 trace "middle" 2 _ <- get 3 trace "end" result `shouldBe` ["0", "start", "1", "middle", "2", "3", "end"] pull :: (Member (Embed IO) r, Member Trace r) => MVar String -> Sem r () pull chan = do embed (tryTakeMVar chan) >>= \case Nothing -> pure () Just s -> do trace $ "loaded: " <> s pull chan push :: MVar String -> IO () push chan = do putMVar chan "hello" putMVar chan "world" putMVar chan "last" test :: IO (Set String) test = fmap S.fromList $ do chan <- newEmptyMVar @_ @String _ <- async $ push chan fmap fst $ runM $ runTraceList $ intersperse (pull chan) $ do for_ [1 .. 4] $ \i -> do trace $ show @Int i liftIO $ threadDelay 1e5 trace "finished"
c8107eb12ea9468cc7fd36351bbcad20f4a712cae4018a0d5f3c4cb66df3bb21
collbox/http-cron
cli.clj
(ns collbox.http-cron.cli (:require [clojure.string :as str] [clojure.tools.cli :as cli] [collbox.http-cron.conversion :as conv] [collbox.http-cron.core :as core] [com.stuartsierra.component :as component] [clojure.java.io :as io])) (defn- env-var [var] (when-let [v (System/getenv var)] (when-not (str/blank? v) v))) (defn- cli-options [] [["-f" "--file FILE" "File name for cron.yaml-style job specification" :default (or (env-var "HTTP_CRON_JOB_FILE") "cron.yaml")] ["-h" "--help" "Display usage instructions"] ["-b" "--base-uri BASE_URI" "Base URL to POST to" :default (or (env-var "HTTP_CRON_BASE_URL") (str "http://" (or (env-var "HTTP_CRON_HOST") "localhost") ":" (or (env-var "HTTP_CRON_PORT") "8080")))]]) (defn- error-msg [errors] (->> (concat ["Error parsing options:" ""] errors) (str/join \newline))) (defn- usage-msg [options-summary] (->> ["Usage: bin/run [options]" "" "Options:" options-summary] (str/join \newline))) (defn- validate-args [args] (let [{:keys [options errors summary]} (cli/parse-opts args (cli-options))] (cond (:help options) {:exit-message (usage-msg summary), :ok? true} errors {:exit-message (error-msg errors)} :else {:options options}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Public (defn -main [& args] (let [{:keys [options exit-message ok?]} (validate-args args) {:keys [file base-uri]} options] (cond exit-message (do (println exit-message) (System/exit (if ok? 0 1))) (not (.exists (io/file file))) (do (println (format "File '%s' does not exist" file)) (System/exit 1)) :else (let [job-specs (conv/parse-cron-yaml file) _ (println (format "Loaded %d job(s) from '%s', will POST to '%s'" (count job-specs) file base-uri)) hc (-> {:base-uri base-uri :job-specs job-specs} core/make-http-cron component/start)] (. (Runtime/getRuntime) (addShutdownHook (Thread. #(do (println "Interrupt received, stopping system.") (component/stop hc) (shutdown-agents))))) @(promise)))))
null
https://raw.githubusercontent.com/collbox/http-cron/5d5de11b92d359e7fbc36afe08ea9819e1908022/src/collbox/http_cron/cli.clj
clojure
Public
(ns collbox.http-cron.cli (:require [clojure.string :as str] [clojure.tools.cli :as cli] [collbox.http-cron.conversion :as conv] [collbox.http-cron.core :as core] [com.stuartsierra.component :as component] [clojure.java.io :as io])) (defn- env-var [var] (when-let [v (System/getenv var)] (when-not (str/blank? v) v))) (defn- cli-options [] [["-f" "--file FILE" "File name for cron.yaml-style job specification" :default (or (env-var "HTTP_CRON_JOB_FILE") "cron.yaml")] ["-h" "--help" "Display usage instructions"] ["-b" "--base-uri BASE_URI" "Base URL to POST to" :default (or (env-var "HTTP_CRON_BASE_URL") (str "http://" (or (env-var "HTTP_CRON_HOST") "localhost") ":" (or (env-var "HTTP_CRON_PORT") "8080")))]]) (defn- error-msg [errors] (->> (concat ["Error parsing options:" ""] errors) (str/join \newline))) (defn- usage-msg [options-summary] (->> ["Usage: bin/run [options]" "" "Options:" options-summary] (str/join \newline))) (defn- validate-args [args] (let [{:keys [options errors summary]} (cli/parse-opts args (cli-options))] (cond (:help options) {:exit-message (usage-msg summary), :ok? true} errors {:exit-message (error-msg errors)} :else {:options options}))) (defn -main [& args] (let [{:keys [options exit-message ok?]} (validate-args args) {:keys [file base-uri]} options] (cond exit-message (do (println exit-message) (System/exit (if ok? 0 1))) (not (.exists (io/file file))) (do (println (format "File '%s' does not exist" file)) (System/exit 1)) :else (let [job-specs (conv/parse-cron-yaml file) _ (println (format "Loaded %d job(s) from '%s', will POST to '%s'" (count job-specs) file base-uri)) hc (-> {:base-uri base-uri :job-specs job-specs} core/make-http-cron component/start)] (. (Runtime/getRuntime) (addShutdownHook (Thread. #(do (println "Interrupt received, stopping system.") (component/stop hc) (shutdown-agents))))) @(promise)))))
cef09ea3473ea0edeb9c5a16f354efda0b2dbfbc35d21751ba27eb083e249c4d
fabianbergmark/ECMA-262
String.hs
module Language.JavaScript.String where import Control.Applicative ((<*), (<$>)) import Control.Monad (void) import Text.Parsec import Text.ParserCombinators.Parsec.Char import Language.JavaScript.Lexer stringNumericLiteral :: CharParser st Double stringNumericLiteral = do mb <- optional strWhiteSpace do { n <- strNumericLiteral; optional strWhiteSpace; return n } <|> do { return 0 } strWhiteSpace :: CharParser st () strWhiteSpace = do { strWhiteSpaceChar; void $ optionMaybe strWhiteSpace } strWhiteSpaceChar :: CharParser st () strWhiteSpaceChar = void $ whiteSpace <|> lineTerminator strNumericLiteral :: CharParser st Double strNumericLiteral = (fromIntegral <$> hexIntegerLiteral) <|> strDecimalLiteral strDecimalLiteral :: CharParser st Double strDecimalLiteral = strUnsignedDecimalLiteral <|> do { void $ char '+'; strUnsignedDecimalLiteral } <|> do { void $ char '-'; mv <- strUnsignedDecimalLiteral; if mv == 0 then return 0 else return (-mv) } strUnsignedDecimalLiteral :: CharParser st Double strUnsignedDecimalLiteral = do { void $ string "Infinity"; return 0 } <|> do { (mv, _) <- try $ do { decimalDigits <* char '.' }; mdv <- optionMaybe decimalDigits; mev <- optionMaybe exponentPart; case (mdv, mev) of (Nothing, Nothing) -> return (fromIntegral mv) (Just (dv, n), Nothing) -> return $ (fromIntegral mv) + (fromIntegral dv) * 10 ^^ (-n) (Nothing, Just ev) -> return $ (fromIntegral mv) * 10 ^^ ev (Just (dv, n), Just ev) -> return $ ((fromIntegral mv) + (fromIntegral dv) * 10 ^^ (-n)) * 10 ^^ ev} <|> do { void $ char '.'; (dv, n) <- decimalDigits; mev <- optionMaybe exponentPart; case mev of Nothing -> return $ (fromIntegral dv) * 10 ^^ (-n) Just ev -> return $ (fromIntegral dv) * 10 ^^ (ev - n) } <|> do { (dv, _) <- decimalDigits; mev <- optionMaybe exponentPart; case mev of Nothing -> return (fromIntegral dv) Just ev -> return $ (fromIntegral dv) * 10 ^^ ev } parseString :: String -> Maybe Double parseString s = case runParser stringNumericLiteral () "" s of Right l -> Just l Left _ -> Nothing
null
https://raw.githubusercontent.com/fabianbergmark/ECMA-262/ff1d8c347514625595f34b48e95a594c35b052ea/src/Language/JavaScript/String.hs
haskell
module Language.JavaScript.String where import Control.Applicative ((<*), (<$>)) import Control.Monad (void) import Text.Parsec import Text.ParserCombinators.Parsec.Char import Language.JavaScript.Lexer stringNumericLiteral :: CharParser st Double stringNumericLiteral = do mb <- optional strWhiteSpace do { n <- strNumericLiteral; optional strWhiteSpace; return n } <|> do { return 0 } strWhiteSpace :: CharParser st () strWhiteSpace = do { strWhiteSpaceChar; void $ optionMaybe strWhiteSpace } strWhiteSpaceChar :: CharParser st () strWhiteSpaceChar = void $ whiteSpace <|> lineTerminator strNumericLiteral :: CharParser st Double strNumericLiteral = (fromIntegral <$> hexIntegerLiteral) <|> strDecimalLiteral strDecimalLiteral :: CharParser st Double strDecimalLiteral = strUnsignedDecimalLiteral <|> do { void $ char '+'; strUnsignedDecimalLiteral } <|> do { void $ char '-'; mv <- strUnsignedDecimalLiteral; if mv == 0 then return 0 else return (-mv) } strUnsignedDecimalLiteral :: CharParser st Double strUnsignedDecimalLiteral = do { void $ string "Infinity"; return 0 } <|> do { (mv, _) <- try $ do { decimalDigits <* char '.' }; mdv <- optionMaybe decimalDigits; mev <- optionMaybe exponentPart; case (mdv, mev) of (Nothing, Nothing) -> return (fromIntegral mv) (Just (dv, n), Nothing) -> return $ (fromIntegral mv) + (fromIntegral dv) * 10 ^^ (-n) (Nothing, Just ev) -> return $ (fromIntegral mv) * 10 ^^ ev (Just (dv, n), Just ev) -> return $ ((fromIntegral mv) + (fromIntegral dv) * 10 ^^ (-n)) * 10 ^^ ev} <|> do { void $ char '.'; (dv, n) <- decimalDigits; mev <- optionMaybe exponentPart; case mev of Nothing -> return $ (fromIntegral dv) * 10 ^^ (-n) Just ev -> return $ (fromIntegral dv) * 10 ^^ (ev - n) } <|> do { (dv, _) <- decimalDigits; mev <- optionMaybe exponentPart; case mev of Nothing -> return (fromIntegral dv) Just ev -> return $ (fromIntegral dv) * 10 ^^ ev } parseString :: String -> Maybe Double parseString s = case runParser stringNumericLiteral () "" s of Right l -> Just l Left _ -> Nothing
33702920ca31e3bf7dff364b13cfece711c6eb6f3e4096b566c4576728ab48f6
albertoruiz/easyVision
domain.hs
import Vision.GUI import Image.Processing import Image.Capture import Image.ROI import Util.Homogeneous import Numeric.LinearAlgebra basis = imageBasis vga copyROI b x = copy b [(x,topLeft (roi x))] vga = Size 480 640 k v = constantImage v vga :: Image Float u = k 0.2 up = modifyROI (roiArray 3 3 2 2) (u |*| xIb basis) -- u x = k 0 -- `copyROI` up y = k 0 `copyROI` up t a = domainTrans32f (k 0.5) (x,y) a main = do base <- toFloat . rgbToGray . resize vga <$> loadRGB "../../data/images/transi/dscn2070.jpg" runIt $ browser "domain transformation" [t base, base] (const Draw)
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/examples/domain.hs
haskell
u `copyROI` up
import Vision.GUI import Image.Processing import Image.Capture import Image.ROI import Util.Homogeneous import Numeric.LinearAlgebra basis = imageBasis vga copyROI b x = copy b [(x,topLeft (roi x))] vga = Size 480 640 k v = constantImage v vga :: Image Float u = k 0.2 y = k 0 `copyROI` up t a = domainTrans32f (k 0.5) (x,y) a main = do base <- toFloat . rgbToGray . resize vga <$> loadRGB "../../data/images/transi/dscn2070.jpg" runIt $ browser "domain transformation" [t base, base] (const Draw)
fc8582e0bd135d39057e4fb8827229753503ee1e6a6f7f9fc62adfd3bd837df1
spechub/Hets
Formula.hs
| Module : ./ConstraintCASL / Formula.hs Copyright : ( c ) , Uni Bremen 2006 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : portable parse terms and formulae Module : ./ConstraintCASL/Formula.hs Copyright : (c) Florian Mossakowski, Uni Bremen 2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : portable parse terms and formulae -} module ConstraintCASL.Formula where import Common.AnnoState import Common.Id import Common.Lexer import Common.Token import ConstraintCASL.AS_ConstraintCASL import Text.ParserCombinators.Parsec import CASL.AS_Basic_CASL {- ------------------------------------------------------------------------ formula ------------------------------------------------------------------------ -} cformula :: [String] -> AParser st ConstraintFORMULA cformula k = try ( do c1 <- conjunction k impliesT c2 <- conjunction k return (Implication_ConstraintFormula c1 c2)) <|> try ( do c1 <- conjunction k equivalentT c2 <- conjunction k return (Equivalence_ConstraintFormula c1 c2)) <|> do impliesT c <- conjunction k return (Axiom_ConstraintFormula c) conjunction :: [String] -> AParser st ATOMCONJUNCTION conjunction k = do (atoms, _) <- atom k `separatedBy` anComma return (Atom_Conjunction atoms) atom :: [String] -> AParser st ATOM atom k = try (do r <- relation k oParenT (terms, _) <- constraintterm k `separatedBy` anComma cParenT `notFollowedWith` relation k return (Prefix_Atom r terms)) <|> do t1 <- constraintterm k r <- relation k t2 <- constraintterm k return (Infix_Atom t1 r t2) simplerelation :: [String] -> AParser st RELATION simplerelation k = do emptyRelationT return Empty_Relation <|> do equalityRelationT return Equal_Relation <|> do oParenT r <- relation k cParenT return r <|> do ide <- parseId k return (Id_Relation ide) <|> do inverseT r <- relation k return (Inverse_Relation r) relation :: [String] -> AParser st RELATION relation k = try ( do (rels, _) <- simplerelation k `separatedBy` anComma return (Relation_Disjunction rels)) <|> simplerelation k constraintterm :: [String] -> AParser st ConstraintTERM constraintterm k = try (do ide <- parseId k return (Atomar_Term ide)) <|> do ide <- parseId k oParenT (terms, _) <- constraintterm k `separatedBy` anComma cParenT return (Composite_Term ide terms) formula :: [String] -> AParser st ConstraintCASLFORMULA formula k = do x <- cformula k return (ExtFORMULA x) emptyRelation :: String emptyRelation = "{}" emptyRelationT :: GenParser Char st Token emptyRelationT = pToken $ toKey emptyRelation equalityRelation :: String equalityRelation = "=" equalityRelationT :: GenParser Char st Token equalityRelationT = pToken $ toKey equalityRelation inverse :: String inverse = "~" inverseT :: GenParser Char st Token inverseT = pToken $ toKey inverse implies :: String implies = "|-" impliesT :: GenParser Char st Token impliesT = pToken $ toKey implies equivalent :: String equivalent = "-||-" equivalentT :: GenParser Char st Token equivalentT = pToken $ toKey equivalent constraintKeywords :: [String] constraintKeywords = [equivalent, implies] instance TermParser ConstraintFORMULA where termParser = aToTermParser $ cformula []
null
https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/ConstraintCASL/Formula.hs
haskell
------------------------------------------------------------------------ formula ------------------------------------------------------------------------
| Module : ./ConstraintCASL / Formula.hs Copyright : ( c ) , Uni Bremen 2006 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : portable parse terms and formulae Module : ./ConstraintCASL/Formula.hs Copyright : (c) Florian Mossakowski, Uni Bremen 2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : portable parse terms and formulae -} module ConstraintCASL.Formula where import Common.AnnoState import Common.Id import Common.Lexer import Common.Token import ConstraintCASL.AS_ConstraintCASL import Text.ParserCombinators.Parsec import CASL.AS_Basic_CASL cformula :: [String] -> AParser st ConstraintFORMULA cformula k = try ( do c1 <- conjunction k impliesT c2 <- conjunction k return (Implication_ConstraintFormula c1 c2)) <|> try ( do c1 <- conjunction k equivalentT c2 <- conjunction k return (Equivalence_ConstraintFormula c1 c2)) <|> do impliesT c <- conjunction k return (Axiom_ConstraintFormula c) conjunction :: [String] -> AParser st ATOMCONJUNCTION conjunction k = do (atoms, _) <- atom k `separatedBy` anComma return (Atom_Conjunction atoms) atom :: [String] -> AParser st ATOM atom k = try (do r <- relation k oParenT (terms, _) <- constraintterm k `separatedBy` anComma cParenT `notFollowedWith` relation k return (Prefix_Atom r terms)) <|> do t1 <- constraintterm k r <- relation k t2 <- constraintterm k return (Infix_Atom t1 r t2) simplerelation :: [String] -> AParser st RELATION simplerelation k = do emptyRelationT return Empty_Relation <|> do equalityRelationT return Equal_Relation <|> do oParenT r <- relation k cParenT return r <|> do ide <- parseId k return (Id_Relation ide) <|> do inverseT r <- relation k return (Inverse_Relation r) relation :: [String] -> AParser st RELATION relation k = try ( do (rels, _) <- simplerelation k `separatedBy` anComma return (Relation_Disjunction rels)) <|> simplerelation k constraintterm :: [String] -> AParser st ConstraintTERM constraintterm k = try (do ide <- parseId k return (Atomar_Term ide)) <|> do ide <- parseId k oParenT (terms, _) <- constraintterm k `separatedBy` anComma cParenT return (Composite_Term ide terms) formula :: [String] -> AParser st ConstraintCASLFORMULA formula k = do x <- cformula k return (ExtFORMULA x) emptyRelation :: String emptyRelation = "{}" emptyRelationT :: GenParser Char st Token emptyRelationT = pToken $ toKey emptyRelation equalityRelation :: String equalityRelation = "=" equalityRelationT :: GenParser Char st Token equalityRelationT = pToken $ toKey equalityRelation inverse :: String inverse = "~" inverseT :: GenParser Char st Token inverseT = pToken $ toKey inverse implies :: String implies = "|-" impliesT :: GenParser Char st Token impliesT = pToken $ toKey implies equivalent :: String equivalent = "-||-" equivalentT :: GenParser Char st Token equivalentT = pToken $ toKey equivalent constraintKeywords :: [String] constraintKeywords = [equivalent, implies] instance TermParser ConstraintFORMULA where termParser = aToTermParser $ cformula []
941460f8925db11c1e869715210567305950510d53ced3ec2ca8f4cfa948d9f5
clojure-interop/aws-api
AWSSecretsManagerAsyncClient.clj
(ns com.amazonaws.services.secretsmanager.AWSSecretsManagerAsyncClient "Client for accessing AWS Secrets Manager asynchronously. Each asynchronous method will return a Java Future object overloads which accept an AsyncHandler can be used to receive notification when an asynchronous operation completes. AWS Secrets Manager API Reference AWS Secrets Manager is a web service that enables you to store, manage, and retrieve, secrets. This guide provides descriptions of the Secrets Manager API. For more information about using this service, see the AWS Secrets Manager User Guide. API Version This version of the Secrets Manager API Reference documents the Secrets Manager API version 2017-10-17. As an alternative to using the API directly, you can use one of the AWS SDKs, which consist of libraries and sample code for various programming languages and platforms (such as Java, Ruby, .NET, iOS, and Android). The SDKs provide a convenient way to create programmatic access to AWS Secrets Manager. For example, the SDKs take care of cryptographically signing requests, managing errors, and retrying requests automatically. For more information about the AWS SDKs, including how to download and install them, see Tools for Amazon Web Services. We recommend that you use the AWS SDKs to make programmatic API calls to Secrets Manager. However, you also can use the Secrets Manager HTTP Query API to make direct calls to the Secrets Manager web service. To learn more about the Secrets Manager HTTP Query API, see Making Query Requests in the AWS Secrets Manager User Guide. Secrets Manager supports GET and POST requests for all actions. That is, the API doesn't require you to use GET for some actions and POST for others. However, GET requests are subject to the limitation size of a URL. Therefore, for operations that require larger sizes, use a POST request. Support and Feedback for AWS Secrets Manager We welcome your feedback. Send your comments to , or post your feedback and questions in the AWS Secrets Manager Discussion Forum. For more information about the AWS Discussion Forums, see Forums Help. How examples are presented The JSON that AWS Secrets Manager expects as your request parameters and that the service returns as a response to HTTP query requests are single, long strings without line breaks or white space formatting. The JSON shown in the examples is formatted with both line breaks and white space to improve readability. When example input parameters would also result in long strings that extend beyond the screen, we insert line breaks to enhance readability. You should always submit the input as a single JSON text string. Logging API Requests AWS Secrets Manager supports AWS CloudTrail, a service that records AWS API calls for your AWS account and delivers log files to an Amazon S3 bucket. By using information that's collected by AWS CloudTrail, you can determine which requests were successfully made to Secrets Manager, who made the request, when it was made, and so on. For more about AWS Secrets Manager and its support for AWS CloudTrail, see Logging AWS Secrets Manager Events with AWS CloudTrail in the AWS Secrets Manager User Guide. To learn more about CloudTrail, including how to turn it on and find your log files, see the AWS CloudTrail User Guide." (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.services.secretsmanager AWSSecretsManagerAsyncClient])) (defn *async-builder "returns: `com.amazonaws.services.secretsmanager.AWSSecretsManagerAsyncClientBuilder`" (^com.amazonaws.services.secretsmanager.AWSSecretsManagerAsyncClientBuilder [] (AWSSecretsManagerAsyncClient/asyncBuilder ))) (defn untag-resource-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.UntagResourceRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the UntagResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.UntagResourceResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UntagResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.untagResourceAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UntagResourceRequest request] (-> this (.untagResourceAsync request)))) (defn rotate-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.RotateSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the RotateSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.RotateSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.RotateSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.rotateSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.RotateSecretRequest request] (-> this (.rotateSecretAsync request)))) (defn list-secrets-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.ListSecretsRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the ListSecrets operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.ListSecretsResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.ListSecretsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.listSecretsAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.ListSecretsRequest request] (-> this (.listSecretsAsync request)))) (defn cancel-rotate-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.CancelRotateSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the CancelRotateSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.CancelRotateSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.CancelRotateSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.cancelRotateSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.CancelRotateSecretRequest request] (-> this (.cancelRotateSecretAsync request)))) (defn get-executor-service "Returns the executor service used by this client to execute async requests. returns: The executor service used by this client to execute async requests. - `java.util.concurrent.ExecutorService`" (^java.util.concurrent.ExecutorService [^AWSSecretsManagerAsyncClient this] (-> this (.getExecutorService)))) (defn update-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.UpdateSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the UpdateSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.UpdateSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UpdateSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.updateSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UpdateSecretRequest request] (-> this (.updateSecretAsync request)))) (defn describe-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.DescribeSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the DescribeSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.DescribeSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DescribeSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.describeSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DescribeSecretRequest request] (-> this (.describeSecretAsync request)))) (defn update-secret-version-stage-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.UpdateSecretVersionStageRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the UpdateSecretVersionStage operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.UpdateSecretVersionStageResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UpdateSecretVersionStageRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.updateSecretVersionStageAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UpdateSecretVersionStageRequest request] (-> this (.updateSecretVersionStageAsync request)))) (defn get-secret-value-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.GetSecretValueRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the GetSecretValue operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.GetSecretValueResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetSecretValueRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.getSecretValueAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetSecretValueRequest request] (-> this (.getSecretValueAsync request)))) (defn create-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.CreateSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the CreateSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.CreateSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.CreateSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.createSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.CreateSecretRequest request] (-> this (.createSecretAsync request)))) (defn put-secret-value-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.PutSecretValueRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the PutSecretValue operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.PutSecretValueResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.PutSecretValueRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.putSecretValueAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.PutSecretValueRequest request] (-> this (.putSecretValueAsync request)))) (defn shutdown "Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should call getExecutorService().shutdown() followed by getExecutorService().awaitTermination() prior to calling this method." ([^AWSSecretsManagerAsyncClient this] (-> this (.shutdown)))) (defn get-random-password-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.GetRandomPasswordRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the GetRandomPassword operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.GetRandomPasswordResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetRandomPasswordRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.getRandomPasswordAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetRandomPasswordRequest request] (-> this (.getRandomPasswordAsync request)))) (defn delete-resource-policy-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.DeleteResourcePolicyRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the DeleteResourcePolicy operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.DeleteResourcePolicyResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DeleteResourcePolicyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.deleteResourcePolicyAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DeleteResourcePolicyRequest request] (-> this (.deleteResourcePolicyAsync request)))) (defn list-secret-version-ids-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.ListSecretVersionIdsRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the ListSecretVersionIds operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.ListSecretVersionIdsResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.ListSecretVersionIdsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.listSecretVersionIdsAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.ListSecretVersionIdsRequest request] (-> this (.listSecretVersionIdsAsync request)))) (defn restore-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.RestoreSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the RestoreSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.RestoreSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.RestoreSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.restoreSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.RestoreSecretRequest request] (-> this (.restoreSecretAsync request)))) (defn put-resource-policy-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.PutResourcePolicyRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the PutResourcePolicy operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.PutResourcePolicyResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.PutResourcePolicyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.putResourcePolicyAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.PutResourcePolicyRequest request] (-> this (.putResourcePolicyAsync request)))) (defn get-resource-policy-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.GetResourcePolicyRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the GetResourcePolicy operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.GetResourcePolicyResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetResourcePolicyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.getResourcePolicyAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetResourcePolicyRequest request] (-> this (.getResourcePolicyAsync request)))) (defn tag-resource-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.TagResourceRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the TagResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.TagResourceResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.TagResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.tagResourceAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.TagResourceRequest request] (-> this (.tagResourceAsync request)))) (defn delete-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.DeleteSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the DeleteSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.DeleteSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DeleteSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.deleteSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DeleteSecretRequest request] (-> this (.deleteSecretAsync request))))
null
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.secretsmanager/src/com/amazonaws/services/secretsmanager/AWSSecretsManagerAsyncClient.clj
clojure
(ns com.amazonaws.services.secretsmanager.AWSSecretsManagerAsyncClient "Client for accessing AWS Secrets Manager asynchronously. Each asynchronous method will return a Java Future object overloads which accept an AsyncHandler can be used to receive notification when an asynchronous operation completes. AWS Secrets Manager API Reference AWS Secrets Manager is a web service that enables you to store, manage, and retrieve, secrets. This guide provides descriptions of the Secrets Manager API. For more information about using this service, see the AWS Secrets Manager User Guide. API Version This version of the Secrets Manager API Reference documents the Secrets Manager API version 2017-10-17. As an alternative to using the API directly, you can use one of the AWS SDKs, which consist of libraries and sample code for various programming languages and platforms (such as Java, Ruby, .NET, iOS, and Android). The SDKs provide a convenient way to create programmatic access to AWS Secrets Manager. For example, the SDKs take care of cryptographically signing requests, managing errors, and retrying requests automatically. For more information about the AWS SDKs, including how to download and install them, see Tools for Amazon Web Services. We recommend that you use the AWS SDKs to make programmatic API calls to Secrets Manager. However, you also can use the Secrets Manager HTTP Query API to make direct calls to the Secrets Manager web service. To learn more about the Secrets Manager HTTP Query API, see Making Query Requests in the AWS Secrets Manager User Guide. Secrets Manager supports GET and POST requests for all actions. That is, the API doesn't require you to use GET for some actions and POST for others. However, GET requests are subject to the limitation size of a URL. Therefore, for operations that require larger sizes, use a POST request. Support and Feedback for AWS Secrets Manager We welcome your feedback. Send your comments to , or post your feedback and questions in the AWS Secrets Manager Discussion Forum. For more information about the AWS Discussion Forums, see Forums Help. How examples are presented The JSON that AWS Secrets Manager expects as your request parameters and that the service returns as a response to HTTP query requests are single, long strings without line breaks or white space formatting. The JSON shown in the examples is formatted with both line breaks and white space to improve readability. When example input parameters would also result in long strings that extend beyond the screen, we insert line breaks to enhance readability. You should always submit the input as a single JSON text string. Logging API Requests AWS Secrets Manager supports AWS CloudTrail, a service that records AWS API calls for your AWS account and delivers log files to an Amazon S3 bucket. By using information that's collected by AWS CloudTrail, you can determine which requests were successfully made to Secrets Manager, who made the request, when it was made, and so on. For more about AWS Secrets Manager and its support for AWS CloudTrail, see Logging AWS Secrets Manager Events with AWS CloudTrail in the AWS Secrets Manager User Guide. To learn more about CloudTrail, including how to turn it on and find your log files, see the AWS CloudTrail User Guide." (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.services.secretsmanager AWSSecretsManagerAsyncClient])) (defn *async-builder "returns: `com.amazonaws.services.secretsmanager.AWSSecretsManagerAsyncClientBuilder`" (^com.amazonaws.services.secretsmanager.AWSSecretsManagerAsyncClientBuilder [] (AWSSecretsManagerAsyncClient/asyncBuilder ))) (defn untag-resource-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.UntagResourceRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the UntagResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.UntagResourceResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UntagResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.untagResourceAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UntagResourceRequest request] (-> this (.untagResourceAsync request)))) (defn rotate-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.RotateSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the RotateSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.RotateSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.RotateSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.rotateSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.RotateSecretRequest request] (-> this (.rotateSecretAsync request)))) (defn list-secrets-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.ListSecretsRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the ListSecrets operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.ListSecretsResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.ListSecretsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.listSecretsAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.ListSecretsRequest request] (-> this (.listSecretsAsync request)))) (defn cancel-rotate-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.CancelRotateSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the CancelRotateSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.CancelRotateSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.CancelRotateSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.cancelRotateSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.CancelRotateSecretRequest request] (-> this (.cancelRotateSecretAsync request)))) (defn get-executor-service "Returns the executor service used by this client to execute async requests. returns: The executor service used by this client to execute async requests. - `java.util.concurrent.ExecutorService`" (^java.util.concurrent.ExecutorService [^AWSSecretsManagerAsyncClient this] (-> this (.getExecutorService)))) (defn update-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.UpdateSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the UpdateSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.UpdateSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UpdateSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.updateSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UpdateSecretRequest request] (-> this (.updateSecretAsync request)))) (defn describe-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.DescribeSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the DescribeSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.DescribeSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DescribeSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.describeSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DescribeSecretRequest request] (-> this (.describeSecretAsync request)))) (defn update-secret-version-stage-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.UpdateSecretVersionStageRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the UpdateSecretVersionStage operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.UpdateSecretVersionStageResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UpdateSecretVersionStageRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.updateSecretVersionStageAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.UpdateSecretVersionStageRequest request] (-> this (.updateSecretVersionStageAsync request)))) (defn get-secret-value-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.GetSecretValueRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the GetSecretValue operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.GetSecretValueResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetSecretValueRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.getSecretValueAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetSecretValueRequest request] (-> this (.getSecretValueAsync request)))) (defn create-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.CreateSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the CreateSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.CreateSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.CreateSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.createSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.CreateSecretRequest request] (-> this (.createSecretAsync request)))) (defn put-secret-value-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.PutSecretValueRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the PutSecretValue operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.PutSecretValueResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.PutSecretValueRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.putSecretValueAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.PutSecretValueRequest request] (-> this (.putSecretValueAsync request)))) (defn shutdown "Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should call getExecutorService().shutdown() followed by getExecutorService().awaitTermination() prior to calling this method." ([^AWSSecretsManagerAsyncClient this] (-> this (.shutdown)))) (defn get-random-password-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.GetRandomPasswordRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the GetRandomPassword operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.GetRandomPasswordResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetRandomPasswordRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.getRandomPasswordAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetRandomPasswordRequest request] (-> this (.getRandomPasswordAsync request)))) (defn delete-resource-policy-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.DeleteResourcePolicyRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the DeleteResourcePolicy operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.DeleteResourcePolicyResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DeleteResourcePolicyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.deleteResourcePolicyAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DeleteResourcePolicyRequest request] (-> this (.deleteResourcePolicyAsync request)))) (defn list-secret-version-ids-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.ListSecretVersionIdsRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the ListSecretVersionIds operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.ListSecretVersionIdsResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.ListSecretVersionIdsRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.listSecretVersionIdsAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.ListSecretVersionIdsRequest request] (-> this (.listSecretVersionIdsAsync request)))) (defn restore-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.RestoreSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the RestoreSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.RestoreSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.RestoreSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.restoreSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.RestoreSecretRequest request] (-> this (.restoreSecretAsync request)))) (defn put-resource-policy-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.PutResourcePolicyRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the PutResourcePolicy operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.PutResourcePolicyResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.PutResourcePolicyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.putResourcePolicyAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.PutResourcePolicyRequest request] (-> this (.putResourcePolicyAsync request)))) (defn get-resource-policy-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.GetResourcePolicyRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the GetResourcePolicy operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.GetResourcePolicyResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetResourcePolicyRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.getResourcePolicyAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.GetResourcePolicyRequest request] (-> this (.getResourcePolicyAsync request)))) (defn tag-resource-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.TagResourceRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the TagResource operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.TagResourceResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.TagResourceRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.tagResourceAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.TagResourceRequest request] (-> this (.tagResourceAsync request)))) (defn delete-secret-async "Description copied from interface: AWSSecretsManagerAsync request - `com.amazonaws.services.secretsmanager.model.DeleteSecretRequest` async-handler - `com.amazonaws.handlers.AsyncHandler` returns: A Java Future containing the result of the DeleteSecret operation returned by the service. - `java.util.concurrent.Future<com.amazonaws.services.secretsmanager.model.DeleteSecretResult>`" (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DeleteSecretRequest request ^com.amazonaws.handlers.AsyncHandler async-handler] (-> this (.deleteSecretAsync request async-handler))) (^java.util.concurrent.Future [^AWSSecretsManagerAsyncClient this ^com.amazonaws.services.secretsmanager.model.DeleteSecretRequest request] (-> this (.deleteSecretAsync request))))
03e9b5d015ae0b475f60c2356cb9f67ad75981e2aa72411e6de3bb02360c9c0f
fakedata-haskell/fakedata
VolleyballSpec.hs
# LANGUAGE ScopedTypeVariables # {-# LANGUAGE OverloadedStrings #-} module VolleyballSpec where import qualified Data.Map as M import Data.Text hiding (all, map) import qualified Data.Text as T import qualified Data.Vector as V import Faker hiding (defaultFakerSettings) import Faker.Sport.Volleyball import Test.Hspec import TestImport import Faker.Internal isText :: Text -> Bool isText x = T.length x >= 1 fakerSettings :: FakerSettings fakerSettings = defaultFakerSettings verifyFakes :: [Fake Text] -> IO [Bool] verifyFakes funs = do let fs :: [IO Text] = map (generateWithSettings fakerSettings) funs gs :: [IO Bool] = map (\f -> isText <$> f) fs sequence gs spec :: Spec spec = do describe "Volleyball" $ do it "sanity checking" $ do let functions :: [Fake Text] = [ team, player, coach, position, formation ] bools <- verifyFakes functions (and bools) `shouldBe` True
null
https://raw.githubusercontent.com/fakedata-haskell/fakedata/ea938c38845b274e28abe7f4e8e342f491e83c89/test/VolleyballSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables # module VolleyballSpec where import qualified Data.Map as M import Data.Text hiding (all, map) import qualified Data.Text as T import qualified Data.Vector as V import Faker hiding (defaultFakerSettings) import Faker.Sport.Volleyball import Test.Hspec import TestImport import Faker.Internal isText :: Text -> Bool isText x = T.length x >= 1 fakerSettings :: FakerSettings fakerSettings = defaultFakerSettings verifyFakes :: [Fake Text] -> IO [Bool] verifyFakes funs = do let fs :: [IO Text] = map (generateWithSettings fakerSettings) funs gs :: [IO Bool] = map (\f -> isText <$> f) fs sequence gs spec :: Spec spec = do describe "Volleyball" $ do it "sanity checking" $ do let functions :: [Fake Text] = [ team, player, coach, position, formation ] bools <- verifyFakes functions (and bools) `shouldBe` True
402565a832323d46c8d1fd9b7570e34a2baa127ce4252efd1db8c7fbbd46cc18
xldenis/ill
Expression.hs
{-# LANGUAGE OverloadedStrings #-} module Thrill.Parser.Expression where import Thrill.Prelude import Thrill.Parser.Lexer import Thrill.Parser.Pattern import Thrill.Parser.Literal import Thrill.Syntax import Text.Megaparsec hiding (some, many) import Text.Megaparsec.Expr import Control.Comonad.Cofree import Control.Monad (when) import Control.Lens.Extras import Control.Lens ((^?)) import Data.Text (Text, unpack) expression :: Parser (Expr' Name SourceSpan) expression = body <|> nonBodyExpr nonBodyExpr :: Parser (Expr' Name SourceSpan) nonBodyExpr = assign <|> fullExpr fullExpr :: Parser (Expr' Name SourceSpan) fullExpr = makeExprParser (call <|> parens fullExpr <|> primExpr) opTable where primExpr = simpleExpr <|> consExpr consExpr :: Parser (Expr' Name SourceSpan) consExpr = caseE <|> lambda <|> ifE simpleExpr :: Parser (Expr' Name SourceSpan) simpleExpr = literalE <|> var <|> constructor body :: Parser (Expr' Name SourceSpan) -- need backtracking? body = label "body expression" . withLoc $ do bodyExps <- nonBodyExpr `sepEndBy1` sep when (isJust $ (last bodyExps) ^? _unwrap . _Assign) (fail "blocks must be terminated by non-assignment expression") return $ Body bodyExps assign :: Parser (Expr' Name SourceSpan) assign = label "assignment" . withLoc $ do names <- try $ do list identifier <* (symbol "=" <* notFollowedBy (char '=')) values <- list fullExpr when (length names /= length values) $ fail "Invalid assignment: length mismatch." return $ Assign names values call :: Parser (Expr' Name SourceSpan) call = label "functional invocation" . try $ do start <- getPosition func <- var <|> constructor <|> parens consExpr args <- some $ (,) <$> (parens $ list fullExpr) <*> getPosition return $ foldl (f start) func args where f startpos func (args, pos) = (SourceSpan startpos pos) :< Apply func args caseE :: Parser (Expr' Name SourceSpan) caseE = label "case expression" . withLoc $ do symbol "case" expr <- fullExpr symbol "of" scn matchers <- some $ do symbol "when" pat <- pattern symbol ":" expr <- body scn return (pat, expr) symbol "end" return $ Case expr matchers -- matchers lambda :: Parser (Expr' Name SourceSpan) lambda = label "lambda expression" . withLoc $ do symbol "fn" args <- lexeme $ parens . list $ pattern symbol "=" <* scn body <- body symbol "end" return $ Lambda args body ifE :: Parser (Expr' Name SourceSpan) ifE = label "if expression" . withLoc $ do symbol "if" cond <- label "condition" fullExpr label "then" $ symbol "then" <* scn left <- expression label "else-branch" $ symbol "else" <* scn right <- expression symbol "end" return $ If cond left right literalE = label "literal" $ withLoc (Literal <$> literal) var :: Parser (Expr' Name SourceSpan) var = label "variable" . try $ withLoc (Var <$> identifier) constructor :: Parser (Expr' Name SourceSpan) constructor = label "constructor" $ withLoc (Constructor <$> lexeme capitalized) opTable :: [[Operator Parser (Expr' Name SourceSpan)]] opTable = [ [ binary $ symbol "*" , binary $ symbol "/" , binary $ symbol "&&" ] , [ binary $ symbol "+" , binary $ symbol "-" , binary $ symbol "||" ] , [ binary $ try . lexeme $ string ">" <* notFollowedBy (char '=') , binary $ try . lexeme $ string "<" <* notFollowedBy (char '=') , binary $ symbol ">=" , binary $ symbol "<=" , binary $ symbol "==" ] ] binary :: Parser Text -> Operator Parser (Expr' Name SourceSpan) binary op = InfixL $ do op <- withLoc $ Var . unpack <$> op return $ \a b -> SourceSpan (begin $ extract a) (end $ extract b) :< (BinOp op a b)
null
https://raw.githubusercontent.com/xldenis/ill/46bb41bf5c82cd6fc4ad6d0d8d33cda9e87a671c/src/Thrill/Parser/Expression.hs
haskell
# LANGUAGE OverloadedStrings # need backtracking? matchers
module Thrill.Parser.Expression where import Thrill.Prelude import Thrill.Parser.Lexer import Thrill.Parser.Pattern import Thrill.Parser.Literal import Thrill.Syntax import Text.Megaparsec hiding (some, many) import Text.Megaparsec.Expr import Control.Comonad.Cofree import Control.Monad (when) import Control.Lens.Extras import Control.Lens ((^?)) import Data.Text (Text, unpack) expression :: Parser (Expr' Name SourceSpan) expression = body <|> nonBodyExpr nonBodyExpr :: Parser (Expr' Name SourceSpan) nonBodyExpr = assign <|> fullExpr fullExpr :: Parser (Expr' Name SourceSpan) fullExpr = makeExprParser (call <|> parens fullExpr <|> primExpr) opTable where primExpr = simpleExpr <|> consExpr consExpr :: Parser (Expr' Name SourceSpan) consExpr = caseE <|> lambda <|> ifE simpleExpr :: Parser (Expr' Name SourceSpan) simpleExpr = literalE <|> var <|> constructor body = label "body expression" . withLoc $ do bodyExps <- nonBodyExpr `sepEndBy1` sep when (isJust $ (last bodyExps) ^? _unwrap . _Assign) (fail "blocks must be terminated by non-assignment expression") return $ Body bodyExps assign :: Parser (Expr' Name SourceSpan) assign = label "assignment" . withLoc $ do names <- try $ do list identifier <* (symbol "=" <* notFollowedBy (char '=')) values <- list fullExpr when (length names /= length values) $ fail "Invalid assignment: length mismatch." return $ Assign names values call :: Parser (Expr' Name SourceSpan) call = label "functional invocation" . try $ do start <- getPosition func <- var <|> constructor <|> parens consExpr args <- some $ (,) <$> (parens $ list fullExpr) <*> getPosition return $ foldl (f start) func args where f startpos func (args, pos) = (SourceSpan startpos pos) :< Apply func args caseE :: Parser (Expr' Name SourceSpan) caseE = label "case expression" . withLoc $ do symbol "case" expr <- fullExpr symbol "of" scn matchers <- some $ do symbol "when" pat <- pattern symbol ":" expr <- body scn return (pat, expr) symbol "end" lambda :: Parser (Expr' Name SourceSpan) lambda = label "lambda expression" . withLoc $ do symbol "fn" args <- lexeme $ parens . list $ pattern symbol "=" <* scn body <- body symbol "end" return $ Lambda args body ifE :: Parser (Expr' Name SourceSpan) ifE = label "if expression" . withLoc $ do symbol "if" cond <- label "condition" fullExpr label "then" $ symbol "then" <* scn left <- expression label "else-branch" $ symbol "else" <* scn right <- expression symbol "end" return $ If cond left right literalE = label "literal" $ withLoc (Literal <$> literal) var :: Parser (Expr' Name SourceSpan) var = label "variable" . try $ withLoc (Var <$> identifier) constructor :: Parser (Expr' Name SourceSpan) constructor = label "constructor" $ withLoc (Constructor <$> lexeme capitalized) opTable :: [[Operator Parser (Expr' Name SourceSpan)]] opTable = [ [ binary $ symbol "*" , binary $ symbol "/" , binary $ symbol "&&" ] , [ binary $ symbol "+" , binary $ symbol "-" , binary $ symbol "||" ] , [ binary $ try . lexeme $ string ">" <* notFollowedBy (char '=') , binary $ try . lexeme $ string "<" <* notFollowedBy (char '=') , binary $ symbol ">=" , binary $ symbol "<=" , binary $ symbol "==" ] ] binary :: Parser Text -> Operator Parser (Expr' Name SourceSpan) binary op = InfixL $ do op <- withLoc $ Var . unpack <$> op return $ \a b -> SourceSpan (begin $ extract a) (end $ extract b) :< (BinOp op a b)
a18d23a6ee9601b4a95d4a55101eff4d60944bf530c6dd5f705096bfbadcb613
scrintal/heroicons-reagent
document_chart_bar.cljs
(ns com.scrintal.heroicons.mini.document-chart-bar) (defn render [] [:svg {:xmlns "" :viewBox "0 0 20 20" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M3 3.5A1.5 1.5 0 014.5 2h6.879a1.5 1.5 0 011.06.44l4.122 4.12A1.5 1.5 0 0117 7.622V16.5a1.5 1.5 0 01-1.5 1.5h-11A1.5 1.5 0 013 16.5v-13zM13.25 9a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5a.75.75 0 01.75-.75zm-6.5 4a.75.75 0 01.75.75v.5a.75.75 0 01-1.5 0v-.5a.75.75 0 01.75-.75zm4-1.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z" :clipRule "evenodd"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/mini/document_chart_bar.cljs
clojure
(ns com.scrintal.heroicons.mini.document-chart-bar) (defn render [] [:svg {:xmlns "" :viewBox "0 0 20 20" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M3 3.5A1.5 1.5 0 014.5 2h6.879a1.5 1.5 0 011.06.44l4.122 4.12A1.5 1.5 0 0117 7.622V16.5a1.5 1.5 0 01-1.5 1.5h-11A1.5 1.5 0 013 16.5v-13zM13.25 9a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5a.75.75 0 01.75-.75zm-6.5 4a.75.75 0 01.75.75v.5a.75.75 0 01-1.5 0v-.5a.75.75 0 01.75-.75zm4-1.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z" :clipRule "evenodd"}]])
24a00ebbcb94db730dec63907acbf7c66d0492e0360e574b87800592e1605174
bluelisp/hemlock
wire.lisp
;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; ;;; ********************************************************************** ;;; ;;; This file contains an interface to internet domain sockets. ;;; Written by . ;;; (in-package :hemlock.wire) ;;; Stuff that needs to be ported: (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +buffer-size+ 2048) (defconstant +initial-cache-size+ 16) (defconstant +funcall0-op+ 0) (defconstant +funcall1-op+ 1) (defconstant +funcall2-op+ 2) (defconstant +funcall3-op+ 3) (defconstant +funcall4-op+ 4) (defconstant +funcall5-op+ 5) (defconstant +funcall-op+ 6) (defconstant +number-op+ 7) (defconstant +string-op+ 8) (defconstant +symbol-op+ 9) (defconstant +save-op+ 10) (defconstant +lookup-op+ 11) (defconstant +remote-op+ 12) (defconstant +cons-op+ 13) (defconstant +bignum-op+ 14)) (defvar *current-wire* nil "The wire the form we are currently evaluating came across.") (defvar *this-host* nil "Unique identifier for this host.") (defvar *this-pid* nil "Unique identifier for this process.") (defvar *object-to-id* (make-hash-table :test 'eq) "Hash table mapping local objects to the corresponding remote id.") (defvar *id-to-object* (make-hash-table :test 'eql) "Hash table mapping remote id's to the curresponding local object.") (defvar *next-id* 0 "Next available id for remote objects.") (defstruct device (wire nil)) (defstruct (stream-device (:include device) (:conc-name device-) (:constructor make-stream-device (stream))) (stream (error "missing argument") :type stream)) (defmethod print-object ((object stream-device) stream) (print-unreadable-object (object stream) (format stream "~A" (device-stream object)))) (defstruct (wire (:constructor %make-wire (device)) (:print-function (lambda (wire stream depth) (declare (ignore depth)) (print-unreadable-object (wire stream) (format stream "~A" (wire-device wire)))))) (device (error "missing argument") :type device) (ibuf (make-array +buffer-size+ :element-type '(unsigned-byte 8))) (ibuf-offset 0) (ibuf-end 0) (obuf (make-array +buffer-size+ :element-type '(unsigned-byte 8))) (obuf-end 0) (object-cache (make-array +initial-cache-size+)) (cache-index 0) (object-hash (make-hash-table :test 'eq)) (encoding :utf-8)) (defun make-wire (device) (let ((wire (%make-wire device))) (setf (device-wire device) wire) wire)) (defstruct (remote-object (:constructor %make-remote-object (host pid id)) (:print-function (lambda (obj stream depth) (declare (ignore depth)) (format stream "#<Remote Object: [~x:~a] ~s>" (remote-object-host obj) (remote-object-pid obj) (remote-object-id obj))))) host pid id) (define-condition wire-error (error) ((wire :reader wire-error-wire :initarg :wire)) (:report (lambda (condition stream) (format stream "There is a problem with ~A." (wire-error-wire condition))))) (define-condition wire-eof (wire-error) () (:report (lambda (condition stream) (format stream "Recieved EOF on ~A." (wire-error-wire condition))))) (define-condition wire-io-error (wire-error) ((when :reader wire-io-error-when :initarg :when :initform "using") (msg :reader wire-io-error-msg :initarg :msg :initform "Failed.")) (:report (lambda (condition stream) (format stream "Error ~A ~A: ~A." (wire-io-error-when condition) (wire-error-wire condition) (wire-io-error-msg condition))))) (defclass serializable-object () ()) (defgeneric serialize (serializable-object)) (defgeneric deserialize-with-type (type data)) ;;; Remote Object Randomness ;;; REMOTE-OBJECT-LOCAL-P -- public ;;; First , make sure the * this - host * and * this - pid * are set . Then test to ;;; see if the remote object's host and pid fields are *this-host* and ;;; *this-pid* (defun remote-object-local-p (remote) "Returns T iff the given remote object is defined locally." (declare (type remote-object remote)) (unless *this-host* (setf *this-host* (unix-gethostid)) (setf *this-pid* (unix-getpid))) (and (eql (remote-object-host remote) *this-host*) (eql (remote-object-pid remote) *this-pid*))) ;;; REMOTE-OBJECT-EQ -- public ;;; Remote objects are considered EQ if they refer to the same object , ie ;;; Their host, pid, and id fields are the same (eql, cause they are all ;;; numbers). (defun remote-object-eq (remote1 remote2) "Returns T iff the two objects refer to the same (eq) object in the same process." (declare (type remote-object remote1 remote2)) (and (eql (remote-object-host remote1) (remote-object-host remote2)) (eql (remote-object-pid remote1) (remote-object-pid remote2)) (eql (remote-object-id remote1) (remote-object-id remote2)))) ;;; REMOTE-OBJECT-VALUE --- public ;;; First assure that the remote object is defined locally . If so , look up ;;; the id in *id-to-objects*. ;;; table. This will only happen if FORGET-REMOTE-TRANSLATION has been called ;;; on the local object. (defun remote-object-value (remote) "Return the associated value for the given remote object. It is an error if the remote object was not created in this process or if FORGET-REMOTE-TRANSLATION has been called on this remote object." (declare (type remote-object remote)) (unless (remote-object-local-p remote) (error "~S is defined is a different process." remote)) (multiple-value-bind (value found) (gethash (remote-object-id remote) *id-to-object*) (unless found (cerror "Use the value of NIL" "No value for ~S -- FORGET-REMOTE-TRANSLATION was called to early." remote)) value)) ;;; MAKE-REMOTE-OBJECT --- public ;;; ;;; Convert the given local object to a remote object. If the local object is ;;; alread entered in the *object-to-id* hash table, just use the old id. Otherwise , grab the next i d and put add both mappings to the two hash ;;; tables. (defun make-remote-object (local) "Convert the given local object to a remote object." (unless *this-host* (setf *this-host* (unix-gethostid)) (setf *this-pid* (unix-getpid))) (let ((id (gethash local *object-to-id*))) (unless id (setf id *next-id*) (setf (gethash local *object-to-id*) id) (setf (gethash id *id-to-object*) local) (incf *next-id*)) (%make-remote-object *this-host* *this-pid* id))) ;;; FORGET-REMOTE-TRANSLATION -- public ;;; ;;; Remove any translation information about the given object. If there is ;;; currenlt no translation for the object, don't bother doing anything. ;;; Otherwise remove it from the *object-to-id* hashtable, and remove the id ;;; from the *id-to-object* hashtable. (defun forget-remote-translation (local) "Forget the translation from the given local to the corresponding remote object. Passing that remote object to remote-object-value will new return NIL." (let ((id (gethash local *object-to-id*))) (when id (remhash local *object-to-id*) (remhash id *id-to-object*))) (values)) Wire input . WIRE - LISTEN -- public ;;; ;;; If nothing is in the current input buffer, select on the file descriptor. (defgeneric device-listen (device)) (defun wire-listen (wire) "Return T iff anything is in the input buffer or available on the socket." (or (< (wire-ibuf-offset wire) (wire-ibuf-end wire)) #+(or) (progn (dispatch-events-no-hang) (< (wire-ibuf-offset wire) (wire-ibuf-end wire))) (device-listen (wire-device wire)))) (defmethod device-listen ((device stream-device)) (listen (device-stream device))) ;;; WIRE-GET-BYTE -- public ;;; ;;; Return the next byte. (defun wire-get-byte (wire) "Return the next byte from the wire." (when (<= (wire-ibuf-end wire) (wire-ibuf-offset wire)) (fill-input-buffer wire)) (prog1 (elt (wire-ibuf wire) (wire-ibuf-offset wire)) (incf (wire-ibuf-offset wire)))) ;;; FILL-INPUT-BUFFER -- Internal ;;; ;;; Fill the input buffer from the socket. If we get an error reading, signal a wire - io - error . If we get an EOF , signal a wire - eof error . If we get any ;;; data, set the ibuf-end index. (defun fill-input-buffer (wire) "Read data off the socket, filling the input buffer. The buffer is cleared first. If fill-input-buffer returns, it is guarenteed that there will be at least one byte in the input buffer. If EOF was reached, as wire-eof error is signaled." (setf (wire-ibuf-offset wire) 0 (wire-ibuf-end wire) 0) (incf (wire-ibuf-end wire) (device-read (wire-device wire) (or (wire-ibuf wire) (error 'wire-eof :wire wire)))) (when (zerop (wire-ibuf-end wire)) (error 'wire-eof :wire wire)) (values)) (defmethod device-read ((device stream-device) buffer) (read-sequence (device-stream device) buffer)) ;;; APPEND-TO-INPUT-BUFFER -- Internal ;;; ;;; Add new data to the input buffer. Used asynchonous devices, where ;;; fill-input-buffer itself it just there to re-enter the event loop. (defun append-to-input-buffer (wire bytes) (let* ((oldpos (wire-ibuf-end wire)) (newpos (+ oldpos (length bytes)))) (setf (wire-ibuf-end wire) newpos) (when (> newpos (length (wire-ibuf wire))) (let ((old (wire-ibuf wire))) (setf (wire-ibuf wire) (make-array newpos :element-type '(unsigned-byte 8))) (replace (wire-ibuf wire) old))) (replace (wire-ibuf wire) bytes :start1 oldpos))) ;;; APPEND-TO-INPUT-BUFFER -- External. ;;; ;;; The externally-visible interface of the above function for device ;;; classes. (defun device-append-to-input-buffer (device bytes) (append-to-input-buffer (device-wire device) bytes)) ;;; WIRE-GET-NUMBER -- public ;;; Just read four bytes and pack them together with normal math ops . (defun wire-get-number (wire &optional (signed t)) "Read a number off the wire. Numbers are 4 bytes in network order. The optional argument controls weather or not the number should be considered signed (defaults to T)." (let* ((b1 (wire-get-byte wire)) (b2 (wire-get-byte wire)) (b3 (wire-get-byte wire)) (b4 (wire-get-byte wire)) (unsigned (+ b4 (* 256 (+ b3 (* 256 (+ b2 (* 256 b1)))))))) (if (and signed (> b1 127)) (logior (ash -1 32) unsigned) unsigned))) ;;; WIRE-GET-BIGNUM -- public ;;; ;;; Extracts a number, which might be a bignum. ;;; (defun wire-get-bignum (wire) "Reads an arbitrary integer sent by WIRE-OUTPUT-BIGNUM from the wire and return it." (let ((count-and-sign (wire-get-number wire))) (do ((count (abs count-and-sign) (1- count)) (result 0 (+ (ash result 32) (wire-get-number wire nil)))) ((not (plusp count)) (if (minusp count-and-sign) (- result) result))))) ;;; WIRE-GET-STRING -- public ;;; ;;; Use WIRE-GET-NUMBER to read the length, then keep pulling stuff out of the input buffer and re - filling it with FILL - INPUT - BUFFER until we 've read ;;; the entire string. (defun wire-get-string (wire) "Reads a string from the wire. The first four bytes spec the size in bytes." (let* ((nbytes (wire-get-number wire)) (bytes (make-array nbytes :element-type '(unsigned-byte 8))) (offset 0)) (declare (integer nbytes offset)) (loop (let ((avail (- (wire-ibuf-end wire) (wire-ibuf-offset wire))) (ibuf (wire-ibuf wire))) (declare (integer avail)) (cond ((<= nbytes avail) (replace bytes ibuf :start1 offset :start2 (wire-ibuf-offset wire)) (incf (wire-ibuf-offset wire) nbytes) (return nil)) ((zerop avail) (fill-input-buffer wire)) (t (replace bytes ibuf :start1 offset :start2 (wire-ibuf-offset wire) :end2 (wire-ibuf-end wire)) (incf offset avail) (decf nbytes avail) (incf (wire-ibuf-offset wire) avail))))) (babel:octets-to-string bytes :encoding (wire-encoding wire)))) ;;; WIRE-GET-OBJECT -- public ;;; First , read a byte to determine the type of the object to read . Then , ;;; depending on the type, call WIRE-GET-NUMBER, WIRE-GET-STRING, or whatever ;;; to read the necessary data. Note, funcall objects are funcalled. (defun wire-get-object (wire) "Reads the next object from the wire and returns it." (let ((identifier (wire-get-byte wire)) (*current-wire* wire)) (declare (fixnum identifier)) (cond ((eql identifier +lookup-op+) (let ((index (wire-get-number wire)) (cache (wire-object-cache wire))) (declare (integer index)) (declare (simple-vector cache)) (when (< index (length cache)) (svref cache index)))) ((eql identifier +number-op+) (wire-get-number wire)) ((eql identifier +bignum-op+) (wire-get-bignum wire)) ((eql identifier +string-op+) (wire-get-string wire)) ((eql identifier +symbol-op+) (let* ((symbol-name (wire-get-string wire)) (package-name (wire-get-string wire)) (package (find-package package-name))) (unless package (error "Attempt to read symbol, ~A, of wire into non-existent ~ package, ~A." symbol-name package-name)) (intern symbol-name package))) ((eql identifier +cons-op+) (cons (wire-get-object wire) (wire-get-object wire))) ((eql identifier +remote-op+) (let ((host (wire-get-number wire nil)) (pid (wire-get-number wire)) (id (wire-get-number wire))) (%make-remote-object host pid id))) ((eql identifier +save-op+) (let ((index (wire-get-number wire)) (cache (wire-object-cache wire))) (declare (integer index)) (declare (simple-vector cache)) (when (>= index (length cache)) (do ((newsize (* (length cache) 2) (* newsize 2))) ((< index newsize) (let ((newcache (make-array newsize))) (declare (simple-vector newcache)) (replace newcache cache) (setf cache newcache) (setf (wire-object-cache wire) cache))))) (setf (svref cache index) (wire-get-object wire)))) ((eql identifier +funcall0-op+) (funcall (wire-get-object wire))) ((eql identifier +funcall1-op+) (funcall (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall2-op+) (funcall (wire-get-object wire) (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall3-op+) (funcall (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall4-op+) (funcall (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall5-op+) (funcall (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall-op+) (let ((arg-count (wire-get-byte wire)) (function (wire-get-object wire)) (args '()) (last-cons nil) (this-cons nil)) (loop (when (zerop arg-count) (return nil)) (setf this-cons (cons (wire-get-object wire) nil)) (if (null last-cons) (setf args this-cons) (setf (cdr last-cons) this-cons)) (setf last-cons this-cons) (decf arg-count)) (apply function args)))))) ;;; Wire output routines. ;;; WIRE-FORCE-OUTPUT -- internal ;;; ;;; Output any stuff remaining in the output buffer. (defun wire-force-output (wire) "Send any info still in the output buffer down the wire and clear it. Nothing harmfull will happen if called when the output buffer is empty." (unless (zerop (wire-obuf-end wire)) (device-write (wire-device wire) (wire-obuf wire) (wire-obuf-end wire)) (setf (wire-obuf-end wire) 0)) (values)) (defmethod device-write ((device stream-device) buffer &optional (end (length buffer))) (write-sequence (device-stream device) buffer :end end)) WIRE - OUTPUT - BYTE -- public ;;; Stick the byte in the output buffer . If there is no space , flush the ;;; buffer using WIRE-FORCE-OUTPUT. (defun wire-output-byte (wire byte) "Output the given (8-bit) byte on the wire." (declare (integer byte)) (let ((fill-pointer (wire-obuf-end wire)) (obuf (wire-obuf wire))) (when (>= fill-pointer (length obuf)) (wire-force-output wire) (setf fill-pointer 0)) (setf (elt obuf fill-pointer) byte) (setf (wire-obuf-end wire) (1+ fill-pointer))) (values)) WIRE - OUTPUT - NUMBER -- public ;;; ;;; Output the number. Note, we don't care if the number is signed or not, because we just crank out the low 32 bits . ;;; (defun wire-output-number (wire number) "Output the given (32-bit) number on the wire." (declare (integer number)) (wire-output-byte wire (+ 0 (ldb (byte 8 24) number))) (wire-output-byte wire (ldb (byte 8 16) number)) (wire-output-byte wire (ldb (byte 8 8) number)) (wire-output-byte wire (ldb (byte 8 0) number)) (values)) WIRE - OUTPUT - BIGNUM -- public ;;; ;;; Output an arbitrary integer. ;;; (defun wire-output-bignum (wire number) "Outputs an arbitrary integer, but less effeciently than WIRE-OUTPUT-NUMBER." (do ((digits 0 (1+ digits)) (remaining (abs number) (ash remaining -32)) (words nil (cons (ldb (byte 32 0) remaining) words))) ((zerop remaining) (wire-output-number wire (if (minusp number) (- digits) digits)) (dolist (word words) (wire-output-number wire word))))) WIRE - OUTPUT - STRING -- public ;;; ;;; Output the string. Strings are represented by the length as a number, ;;; followed by the bytes of the string. ;;; (defun wire-output-string (wire string) "Output the given string. First output the length using WIRE-OUTPUT-NUMBER, then output the bytes." (declare (simple-string string)) (let* ((bytes (babel:string-to-octets string :encoding (wire-encoding wire))) (nbytes (length bytes))) (wire-output-number wire nbytes) (let* ((obuf (wire-obuf wire)) (obuf-end (wire-obuf-end wire)) (available (- (length obuf) obuf-end))) (declare (integer available)) (cond ((>= available nbytes) (replace obuf bytes :start1 obuf-end) (incf (wire-obuf-end wire) nbytes)) ((> nbytes (length obuf)) (wire-force-output wire) (device-write (wire-device wire) bytes)) (t (wire-force-output wire) (replace obuf bytes) (setf (wire-obuf-end wire) nbytes))))) (values)) WIRE - OUTPUT - FUNCALL -- public ;;; ;;; Send the funcall down the wire. Arguments are evaluated locally in the lexical environment of the WIRE - OUTPUT - FUNCALL . (defmacro wire-output-funcall (wire-form function &rest args) "Send the function and args down the wire as a funcall." (let ((num-args (length args)) (wire (gensym))) `(let ((,wire ,wire-form)) ,@(if (> num-args 5) `((wire-output-byte ,wire +funcall-op+) (wire-output-byte ,wire ,num-args)) `((wire-output-byte ,wire ,(+ +funcall0-op+ num-args)))) (wire-output-object ,wire ,function) ,@(mapcar #'(lambda (arg) `(wire-output-object ,wire ,arg)) args) (values)))) WIRE - OUTPUT - OBJECT -- public ;;; ;;; Output the given object. If the optional argument is non-nil, cache ;;; the object to enhance the performance of sending it multiple times. ;;; Caching defaults to yes for symbols, and nil for everything else. (defun wire-output-object (wire object &optional (cache-it (symbolp object))) "Output the given object on the given wire. If cache-it is T, enter this object in the cache for future reference." (let ((cache-index (gethash object (wire-object-hash wire)))) (cond (cache-index (wire-output-byte wire +lookup-op+) (wire-output-number wire cache-index)) (t (when cache-it (wire-output-byte wire +save-op+) (let ((index (wire-cache-index wire))) (wire-output-number wire index) (setf (gethash object (wire-object-hash wire)) index) (setf (wire-cache-index wire) (1+ index)))) (typecase object (integer (cond ((typep object '(signed-byte 32)) (wire-output-byte wire +number-op+) (wire-output-number wire object)) (t (wire-output-byte wire +bignum-op+) (wire-output-bignum wire object)))) (simple-string (wire-output-byte wire +string-op+) (wire-output-string wire object)) (symbol (wire-output-byte wire +symbol-op+) (wire-output-string wire (symbol-name object)) (wire-output-string wire (package-name (symbol-package object)))) (cons (wire-output-byte wire +cons-op+) (wire-output-object wire (car object)) (wire-output-object wire (cdr object))) (remote-object (wire-output-byte wire +remote-op+) (wire-output-number wire (remote-object-host object)) (wire-output-number wire (remote-object-pid object)) (wire-output-number wire (remote-object-id object))) (serializable-object (multiple-value-bind (type data) (serialize object) (wire-output-funcall wire 'deserialize-with-type type data))) (t (error "Error: Cannot output objects of type ~s across a wire." (type-of object))))))) (values))
null
https://raw.githubusercontent.com/bluelisp/hemlock/47e16ba731a0cf4ffd7fb2110e17c764ae757170/src/wire.lisp
lisp
-*- Mode: Lisp; indent-tabs-mode: nil -*- ********************************************************************** ********************************************************************** This file contains an interface to internet domain sockets. Stuff that needs to be ported: Remote Object Randomness REMOTE-OBJECT-LOCAL-P -- public see if the remote object's host and pid fields are *this-host* and *this-pid* REMOTE-OBJECT-EQ -- public Their host, pid, and id fields are the same (eql, cause they are all numbers). REMOTE-OBJECT-VALUE --- public the id in *id-to-objects*. table. This will only happen if FORGET-REMOTE-TRANSLATION has been called on the local object. MAKE-REMOTE-OBJECT --- public Convert the given local object to a remote object. If the local object is alread entered in the *object-to-id* hash table, just use the old id. tables. FORGET-REMOTE-TRANSLATION -- public Remove any translation information about the given object. If there is currenlt no translation for the object, don't bother doing anything. Otherwise remove it from the *object-to-id* hashtable, and remove the id from the *id-to-object* hashtable. If nothing is in the current input buffer, select on the file descriptor. WIRE-GET-BYTE -- public Return the next byte. FILL-INPUT-BUFFER -- Internal Fill the input buffer from the socket. If we get an error reading, signal data, set the ibuf-end index. APPEND-TO-INPUT-BUFFER -- Internal Add new data to the input buffer. Used asynchonous devices, where fill-input-buffer itself it just there to re-enter the event loop. APPEND-TO-INPUT-BUFFER -- External. The externally-visible interface of the above function for device classes. WIRE-GET-NUMBER -- public WIRE-GET-BIGNUM -- public Extracts a number, which might be a bignum. WIRE-GET-STRING -- public Use WIRE-GET-NUMBER to read the length, then keep pulling stuff out of the entire string. WIRE-GET-OBJECT -- public depending on the type, call WIRE-GET-NUMBER, WIRE-GET-STRING, or whatever to read the necessary data. Note, funcall objects are funcalled. Wire output routines. WIRE-FORCE-OUTPUT -- internal Output any stuff remaining in the output buffer. buffer using WIRE-FORCE-OUTPUT. Output the number. Note, we don't care if the number is signed or not, Output an arbitrary integer. Output the string. Strings are represented by the length as a number, followed by the bytes of the string. Send the funcall down the wire. Arguments are evaluated locally in the Output the given object. If the optional argument is non-nil, cache the object to enhance the performance of sending it multiple times. Caching defaults to yes for symbols, and nil for everything else.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . Written by . (in-package :hemlock.wire) (eval-when (:compile-toplevel :load-toplevel :execute) (defconstant +buffer-size+ 2048) (defconstant +initial-cache-size+ 16) (defconstant +funcall0-op+ 0) (defconstant +funcall1-op+ 1) (defconstant +funcall2-op+ 2) (defconstant +funcall3-op+ 3) (defconstant +funcall4-op+ 4) (defconstant +funcall5-op+ 5) (defconstant +funcall-op+ 6) (defconstant +number-op+ 7) (defconstant +string-op+ 8) (defconstant +symbol-op+ 9) (defconstant +save-op+ 10) (defconstant +lookup-op+ 11) (defconstant +remote-op+ 12) (defconstant +cons-op+ 13) (defconstant +bignum-op+ 14)) (defvar *current-wire* nil "The wire the form we are currently evaluating came across.") (defvar *this-host* nil "Unique identifier for this host.") (defvar *this-pid* nil "Unique identifier for this process.") (defvar *object-to-id* (make-hash-table :test 'eq) "Hash table mapping local objects to the corresponding remote id.") (defvar *id-to-object* (make-hash-table :test 'eql) "Hash table mapping remote id's to the curresponding local object.") (defvar *next-id* 0 "Next available id for remote objects.") (defstruct device (wire nil)) (defstruct (stream-device (:include device) (:conc-name device-) (:constructor make-stream-device (stream))) (stream (error "missing argument") :type stream)) (defmethod print-object ((object stream-device) stream) (print-unreadable-object (object stream) (format stream "~A" (device-stream object)))) (defstruct (wire (:constructor %make-wire (device)) (:print-function (lambda (wire stream depth) (declare (ignore depth)) (print-unreadable-object (wire stream) (format stream "~A" (wire-device wire)))))) (device (error "missing argument") :type device) (ibuf (make-array +buffer-size+ :element-type '(unsigned-byte 8))) (ibuf-offset 0) (ibuf-end 0) (obuf (make-array +buffer-size+ :element-type '(unsigned-byte 8))) (obuf-end 0) (object-cache (make-array +initial-cache-size+)) (cache-index 0) (object-hash (make-hash-table :test 'eq)) (encoding :utf-8)) (defun make-wire (device) (let ((wire (%make-wire device))) (setf (device-wire device) wire) wire)) (defstruct (remote-object (:constructor %make-remote-object (host pid id)) (:print-function (lambda (obj stream depth) (declare (ignore depth)) (format stream "#<Remote Object: [~x:~a] ~s>" (remote-object-host obj) (remote-object-pid obj) (remote-object-id obj))))) host pid id) (define-condition wire-error (error) ((wire :reader wire-error-wire :initarg :wire)) (:report (lambda (condition stream) (format stream "There is a problem with ~A." (wire-error-wire condition))))) (define-condition wire-eof (wire-error) () (:report (lambda (condition stream) (format stream "Recieved EOF on ~A." (wire-error-wire condition))))) (define-condition wire-io-error (wire-error) ((when :reader wire-io-error-when :initarg :when :initform "using") (msg :reader wire-io-error-msg :initarg :msg :initform "Failed.")) (:report (lambda (condition stream) (format stream "Error ~A ~A: ~A." (wire-io-error-when condition) (wire-error-wire condition) (wire-io-error-msg condition))))) (defclass serializable-object () ()) (defgeneric serialize (serializable-object)) (defgeneric deserialize-with-type (type data)) First , make sure the * this - host * and * this - pid * are set . Then test to (defun remote-object-local-p (remote) "Returns T iff the given remote object is defined locally." (declare (type remote-object remote)) (unless *this-host* (setf *this-host* (unix-gethostid)) (setf *this-pid* (unix-getpid))) (and (eql (remote-object-host remote) *this-host*) (eql (remote-object-pid remote) *this-pid*))) Remote objects are considered EQ if they refer to the same object , ie (defun remote-object-eq (remote1 remote2) "Returns T iff the two objects refer to the same (eq) object in the same process." (declare (type remote-object remote1 remote2)) (and (eql (remote-object-host remote1) (remote-object-host remote2)) (eql (remote-object-pid remote1) (remote-object-pid remote2)) (eql (remote-object-id remote1) (remote-object-id remote2)))) First assure that the remote object is defined locally . If so , look up (defun remote-object-value (remote) "Return the associated value for the given remote object. It is an error if the remote object was not created in this process or if FORGET-REMOTE-TRANSLATION has been called on this remote object." (declare (type remote-object remote)) (unless (remote-object-local-p remote) (error "~S is defined is a different process." remote)) (multiple-value-bind (value found) (gethash (remote-object-id remote) *id-to-object*) (unless found (cerror "Use the value of NIL" "No value for ~S -- FORGET-REMOTE-TRANSLATION was called to early." remote)) value)) Otherwise , grab the next i d and put add both mappings to the two hash (defun make-remote-object (local) "Convert the given local object to a remote object." (unless *this-host* (setf *this-host* (unix-gethostid)) (setf *this-pid* (unix-getpid))) (let ((id (gethash local *object-to-id*))) (unless id (setf id *next-id*) (setf (gethash local *object-to-id*) id) (setf (gethash id *id-to-object*) local) (incf *next-id*)) (%make-remote-object *this-host* *this-pid* id))) (defun forget-remote-translation (local) "Forget the translation from the given local to the corresponding remote object. Passing that remote object to remote-object-value will new return NIL." (let ((id (gethash local *object-to-id*))) (when id (remhash local *object-to-id*) (remhash id *id-to-object*))) (values)) Wire input . WIRE - LISTEN -- public (defgeneric device-listen (device)) (defun wire-listen (wire) "Return T iff anything is in the input buffer or available on the socket." (or (< (wire-ibuf-offset wire) (wire-ibuf-end wire)) #+(or) (progn (dispatch-events-no-hang) (< (wire-ibuf-offset wire) (wire-ibuf-end wire))) (device-listen (wire-device wire)))) (defmethod device-listen ((device stream-device)) (listen (device-stream device))) (defun wire-get-byte (wire) "Return the next byte from the wire." (when (<= (wire-ibuf-end wire) (wire-ibuf-offset wire)) (fill-input-buffer wire)) (prog1 (elt (wire-ibuf wire) (wire-ibuf-offset wire)) (incf (wire-ibuf-offset wire)))) a wire - io - error . If we get an EOF , signal a wire - eof error . If we get any (defun fill-input-buffer (wire) "Read data off the socket, filling the input buffer. The buffer is cleared first. If fill-input-buffer returns, it is guarenteed that there will be at least one byte in the input buffer. If EOF was reached, as wire-eof error is signaled." (setf (wire-ibuf-offset wire) 0 (wire-ibuf-end wire) 0) (incf (wire-ibuf-end wire) (device-read (wire-device wire) (or (wire-ibuf wire) (error 'wire-eof :wire wire)))) (when (zerop (wire-ibuf-end wire)) (error 'wire-eof :wire wire)) (values)) (defmethod device-read ((device stream-device) buffer) (read-sequence (device-stream device) buffer)) (defun append-to-input-buffer (wire bytes) (let* ((oldpos (wire-ibuf-end wire)) (newpos (+ oldpos (length bytes)))) (setf (wire-ibuf-end wire) newpos) (when (> newpos (length (wire-ibuf wire))) (let ((old (wire-ibuf wire))) (setf (wire-ibuf wire) (make-array newpos :element-type '(unsigned-byte 8))) (replace (wire-ibuf wire) old))) (replace (wire-ibuf wire) bytes :start1 oldpos))) (defun device-append-to-input-buffer (device bytes) (append-to-input-buffer (device-wire device) bytes)) Just read four bytes and pack them together with normal math ops . (defun wire-get-number (wire &optional (signed t)) "Read a number off the wire. Numbers are 4 bytes in network order. The optional argument controls weather or not the number should be considered signed (defaults to T)." (let* ((b1 (wire-get-byte wire)) (b2 (wire-get-byte wire)) (b3 (wire-get-byte wire)) (b4 (wire-get-byte wire)) (unsigned (+ b4 (* 256 (+ b3 (* 256 (+ b2 (* 256 b1)))))))) (if (and signed (> b1 127)) (logior (ash -1 32) unsigned) unsigned))) (defun wire-get-bignum (wire) "Reads an arbitrary integer sent by WIRE-OUTPUT-BIGNUM from the wire and return it." (let ((count-and-sign (wire-get-number wire))) (do ((count (abs count-and-sign) (1- count)) (result 0 (+ (ash result 32) (wire-get-number wire nil)))) ((not (plusp count)) (if (minusp count-and-sign) (- result) result))))) the input buffer and re - filling it with FILL - INPUT - BUFFER until we 've read (defun wire-get-string (wire) "Reads a string from the wire. The first four bytes spec the size in bytes." (let* ((nbytes (wire-get-number wire)) (bytes (make-array nbytes :element-type '(unsigned-byte 8))) (offset 0)) (declare (integer nbytes offset)) (loop (let ((avail (- (wire-ibuf-end wire) (wire-ibuf-offset wire))) (ibuf (wire-ibuf wire))) (declare (integer avail)) (cond ((<= nbytes avail) (replace bytes ibuf :start1 offset :start2 (wire-ibuf-offset wire)) (incf (wire-ibuf-offset wire) nbytes) (return nil)) ((zerop avail) (fill-input-buffer wire)) (t (replace bytes ibuf :start1 offset :start2 (wire-ibuf-offset wire) :end2 (wire-ibuf-end wire)) (incf offset avail) (decf nbytes avail) (incf (wire-ibuf-offset wire) avail))))) (babel:octets-to-string bytes :encoding (wire-encoding wire)))) First , read a byte to determine the type of the object to read . Then , (defun wire-get-object (wire) "Reads the next object from the wire and returns it." (let ((identifier (wire-get-byte wire)) (*current-wire* wire)) (declare (fixnum identifier)) (cond ((eql identifier +lookup-op+) (let ((index (wire-get-number wire)) (cache (wire-object-cache wire))) (declare (integer index)) (declare (simple-vector cache)) (when (< index (length cache)) (svref cache index)))) ((eql identifier +number-op+) (wire-get-number wire)) ((eql identifier +bignum-op+) (wire-get-bignum wire)) ((eql identifier +string-op+) (wire-get-string wire)) ((eql identifier +symbol-op+) (let* ((symbol-name (wire-get-string wire)) (package-name (wire-get-string wire)) (package (find-package package-name))) (unless package (error "Attempt to read symbol, ~A, of wire into non-existent ~ package, ~A." symbol-name package-name)) (intern symbol-name package))) ((eql identifier +cons-op+) (cons (wire-get-object wire) (wire-get-object wire))) ((eql identifier +remote-op+) (let ((host (wire-get-number wire nil)) (pid (wire-get-number wire)) (id (wire-get-number wire))) (%make-remote-object host pid id))) ((eql identifier +save-op+) (let ((index (wire-get-number wire)) (cache (wire-object-cache wire))) (declare (integer index)) (declare (simple-vector cache)) (when (>= index (length cache)) (do ((newsize (* (length cache) 2) (* newsize 2))) ((< index newsize) (let ((newcache (make-array newsize))) (declare (simple-vector newcache)) (replace newcache cache) (setf cache newcache) (setf (wire-object-cache wire) cache))))) (setf (svref cache index) (wire-get-object wire)))) ((eql identifier +funcall0-op+) (funcall (wire-get-object wire))) ((eql identifier +funcall1-op+) (funcall (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall2-op+) (funcall (wire-get-object wire) (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall3-op+) (funcall (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall4-op+) (funcall (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall5-op+) (funcall (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire) (wire-get-object wire))) ((eql identifier +funcall-op+) (let ((arg-count (wire-get-byte wire)) (function (wire-get-object wire)) (args '()) (last-cons nil) (this-cons nil)) (loop (when (zerop arg-count) (return nil)) (setf this-cons (cons (wire-get-object wire) nil)) (if (null last-cons) (setf args this-cons) (setf (cdr last-cons) this-cons)) (setf last-cons this-cons) (decf arg-count)) (apply function args)))))) (defun wire-force-output (wire) "Send any info still in the output buffer down the wire and clear it. Nothing harmfull will happen if called when the output buffer is empty." (unless (zerop (wire-obuf-end wire)) (device-write (wire-device wire) (wire-obuf wire) (wire-obuf-end wire)) (setf (wire-obuf-end wire) 0)) (values)) (defmethod device-write ((device stream-device) buffer &optional (end (length buffer))) (write-sequence (device-stream device) buffer :end end)) WIRE - OUTPUT - BYTE -- public Stick the byte in the output buffer . If there is no space , flush the (defun wire-output-byte (wire byte) "Output the given (8-bit) byte on the wire." (declare (integer byte)) (let ((fill-pointer (wire-obuf-end wire)) (obuf (wire-obuf wire))) (when (>= fill-pointer (length obuf)) (wire-force-output wire) (setf fill-pointer 0)) (setf (elt obuf fill-pointer) byte) (setf (wire-obuf-end wire) (1+ fill-pointer))) (values)) WIRE - OUTPUT - NUMBER -- public because we just crank out the low 32 bits . (defun wire-output-number (wire number) "Output the given (32-bit) number on the wire." (declare (integer number)) (wire-output-byte wire (+ 0 (ldb (byte 8 24) number))) (wire-output-byte wire (ldb (byte 8 16) number)) (wire-output-byte wire (ldb (byte 8 8) number)) (wire-output-byte wire (ldb (byte 8 0) number)) (values)) WIRE - OUTPUT - BIGNUM -- public (defun wire-output-bignum (wire number) "Outputs an arbitrary integer, but less effeciently than WIRE-OUTPUT-NUMBER." (do ((digits 0 (1+ digits)) (remaining (abs number) (ash remaining -32)) (words nil (cons (ldb (byte 32 0) remaining) words))) ((zerop remaining) (wire-output-number wire (if (minusp number) (- digits) digits)) (dolist (word words) (wire-output-number wire word))))) WIRE - OUTPUT - STRING -- public (defun wire-output-string (wire string) "Output the given string. First output the length using WIRE-OUTPUT-NUMBER, then output the bytes." (declare (simple-string string)) (let* ((bytes (babel:string-to-octets string :encoding (wire-encoding wire))) (nbytes (length bytes))) (wire-output-number wire nbytes) (let* ((obuf (wire-obuf wire)) (obuf-end (wire-obuf-end wire)) (available (- (length obuf) obuf-end))) (declare (integer available)) (cond ((>= available nbytes) (replace obuf bytes :start1 obuf-end) (incf (wire-obuf-end wire) nbytes)) ((> nbytes (length obuf)) (wire-force-output wire) (device-write (wire-device wire) bytes)) (t (wire-force-output wire) (replace obuf bytes) (setf (wire-obuf-end wire) nbytes))))) (values)) WIRE - OUTPUT - FUNCALL -- public lexical environment of the WIRE - OUTPUT - FUNCALL . (defmacro wire-output-funcall (wire-form function &rest args) "Send the function and args down the wire as a funcall." (let ((num-args (length args)) (wire (gensym))) `(let ((,wire ,wire-form)) ,@(if (> num-args 5) `((wire-output-byte ,wire +funcall-op+) (wire-output-byte ,wire ,num-args)) `((wire-output-byte ,wire ,(+ +funcall0-op+ num-args)))) (wire-output-object ,wire ,function) ,@(mapcar #'(lambda (arg) `(wire-output-object ,wire ,arg)) args) (values)))) WIRE - OUTPUT - OBJECT -- public (defun wire-output-object (wire object &optional (cache-it (symbolp object))) "Output the given object on the given wire. If cache-it is T, enter this object in the cache for future reference." (let ((cache-index (gethash object (wire-object-hash wire)))) (cond (cache-index (wire-output-byte wire +lookup-op+) (wire-output-number wire cache-index)) (t (when cache-it (wire-output-byte wire +save-op+) (let ((index (wire-cache-index wire))) (wire-output-number wire index) (setf (gethash object (wire-object-hash wire)) index) (setf (wire-cache-index wire) (1+ index)))) (typecase object (integer (cond ((typep object '(signed-byte 32)) (wire-output-byte wire +number-op+) (wire-output-number wire object)) (t (wire-output-byte wire +bignum-op+) (wire-output-bignum wire object)))) (simple-string (wire-output-byte wire +string-op+) (wire-output-string wire object)) (symbol (wire-output-byte wire +symbol-op+) (wire-output-string wire (symbol-name object)) (wire-output-string wire (package-name (symbol-package object)))) (cons (wire-output-byte wire +cons-op+) (wire-output-object wire (car object)) (wire-output-object wire (cdr object))) (remote-object (wire-output-byte wire +remote-op+) (wire-output-number wire (remote-object-host object)) (wire-output-number wire (remote-object-pid object)) (wire-output-number wire (remote-object-id object))) (serializable-object (multiple-value-bind (type data) (serialize object) (wire-output-funcall wire 'deserialize-with-type type data))) (t (error "Error: Cannot output objects of type ~s across a wire." (type-of object))))))) (values))
ee13bbe4c63ea6df5afd3f774692855094984276ce5c38024c2661f554ae4fdd
Frama-C/Frama-C-snapshot
calculus.ml
(**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) * Wp computation using the CFG open Cil_types open Cil_datatype module Cfg (W : Mcfg.S) = struct let dkey = Wp_parameters.register_category "calculus" (* Debugging key *) let debug fmt = Wp_parameters.debug ~dkey fmt (** Before storing something at a program point, we have to process the label * at that point. *) let do_labels wenv e obj = let do_lab s o l = W.label wenv s l o in let obj = do_lab None obj Clabels.here in let stmt = Cil2cfg.get_edge_stmt e in let labels = Cil2cfg.get_edge_labels e in List.fold_left (do_lab stmt) obj labels let add_hyp wenv obj h = debug "add hyp %a@." WpPropId.pp_pred_info h; W.add_hyp wenv h obj let add_goal wenv obj g = debug "add goal %a@." WpPropId.pp_pred_info g; W.add_goal wenv g obj (*[LC] Adding scopes for loop invariant preservation: WHY ???? *) [ LC ] Nevertheless , if required , this form should be used ( BTS # 1462 ) let open_scope wenv formals blocks = List.fold_right ( fun b obj - > W.scope wenv b.blocals Mcfg . SC_Block_out obj ) blocks ( W.scope wenv formals Mcfg . SC_Function_out W.empty ) match WpPropId.is_loop_preservation ( fst g ) with | None - > W.add_goal | Some stmt - > debug " add scope for loop preservation % a@. " WpPropId.pp_pred_info g ; let blocks = Kernel_function.find_all_enclosing_blocks stmt in let kf = Kernel_function.find_englobing_kf stmt in let formals = Kernel_function.get_formals kf in ( W.add_goal ( open_scope wenv formals blocks ) ) obj let open_scope wenv formals blocks = List.fold_right (fun b obj -> W.scope wenv b.blocals Mcfg.SC_Block_out obj) blocks (W.scope wenv formals Mcfg.SC_Function_out W.empty) match WpPropId.is_loop_preservation (fst g) with | None -> W.add_goal wenv g obj | Some stmt -> debug "add scope for loop preservation %a@." WpPropId.pp_pred_info g ; let blocks = Kernel_function.find_all_enclosing_blocks stmt in let kf = Kernel_function.find_englobing_kf stmt in let formals = Kernel_function.get_formals kf in W.merge wenv (W.add_goal wenv g (open_scope wenv formals blocks)) obj *) let add_assigns_goal wenv obj g_assigns = match g_assigns with | WpPropId.AssignsAny _ | WpPropId.NoAssignsInfo -> obj | WpPropId.AssignsLocations a -> debug "add assign goal (@[%a@])@." WpPropId.pretty (WpPropId.assigns_info_id a); W.add_assigns wenv a obj let add_assigns_hyp wenv obj h_assigns = match h_assigns with | WpPropId.AssignsLocations (h_id, a) -> let hid = Some h_id in let obj = W.use_assigns wenv a.WpPropId.a_stmt hid a obj in Some a.WpPropId.a_label, obj | WpPropId.AssignsAny a -> Wp_parameters.warning ~current:true ~once:true "Missing assigns clause (assigns 'everything' instead)" ; let obj = W.use_assigns wenv a.WpPropId.a_stmt None a obj in Some a.WpPropId.a_label, obj | WpPropId.NoAssignsInfo -> None, obj (** detect if the computation of the result at [edge] is possible, * or if it will loop. If [strategy] are provide, * cut are done on edges with cut properties, * and if not, cut are done on loop node back edge if any. * TODO: maybe this should be done while building the strategy ? * *) exception Stop of Cil2cfg.edge let test_edge_loop_ok cfg strategy edge = debug "[test_edge_loop_ok] (%s strategy) for %a" (match strategy with None -> "without" | Some _ -> "with") Cil2cfg.pp_edge edge; let rec collect_edge_preds set e = let cut = match strategy with None -> Cil2cfg.is_back_edge e | Some strategy -> let e_annots = WpStrategy.get_annots strategy e in (WpStrategy.get_cut e_annots <> []) in if cut then () (* normal loop cut *) else if Cil2cfg.Eset.mem e set then (* e is already in set : loop without cut ! *) raise (Stop e) add e to set and continue with its preds let set = Cil2cfg.Eset.add e set in let preds = Cil2cfg.pred_e cfg (Cil2cfg.edge_src e) in List.iter (collect_edge_preds set) preds in try let _ = collect_edge_preds Cil2cfg.Eset.empty edge in debug "[test_edge_loop_ok] ok."; true with Stop e -> begin debug "[test_edge_loop_ok] loop without cut detected at %a" Cil2cfg.pp_edge e; false end * to store the results of computations : * we store a result for each edge , and also a list of proof obligations . * * Be careful that there are two modes of computation : * the first one ( [ Pass1 ] ) is used to prove the establishment of properties * while the second ( after [ change_mode_if_needed ] ) prove the preservation . * See { ! R.set } for more details . * * we store a result for each edge, and also a list of proof obligations. * * Be careful that there are two modes of computation : * the first one ([Pass1]) is used to prove the establishment of properties * while the second (after [change_mode_if_needed]) prove the preservation. * See {!R.set} for more details. * *) module R : sig type t val empty : Cil2cfg.t -> t val is_pass1 : t -> bool val change_mode_if_needed : t -> unit val find : t -> Cil2cfg.edge -> W.t_prop val set : WpStrategy.strategy -> W.t_env -> t -> Cil2cfg.edge -> W.t_prop -> W.t_prop val add_oblig : t -> Clabels.c_label -> W.t_prop -> unit val add_memo : t -> Cil2cfg.edge -> W.t_prop -> unit end = struct type t_mode = Pass1 | Pass2 module HE = Cil2cfg.HE (struct type t = W.t_prop option end) module LabObligs : sig type t val empty : t val is_empty : t -> bool val get_of_label : t -> Clabels.c_label -> W.t_prop list val get_of_edge : t -> Cil2cfg.edge -> W.t_prop list val add_to_label : t -> Clabels.c_label -> W.t_prop -> t val add_to_edge : t -> Cil2cfg.edge -> W.t_prop -> t end = struct type key = Olab of Clabels.c_label | Oedge of Cil2cfg.edge let cmp_key k1 k2 = match k1, k2 with | Olab l1, Olab l2 when Clabels.equal l1 l2 -> true | Oedge e1, Oedge e2 when Cil2cfg.same_edge e1 e2 -> true | _ -> false (* TODOopt: could have a sorted list... *) type t = (key * W.t_prop list) list let empty = [] let is_empty obligs = (obligs = []) let add obligs k obj = let rec aux l_obligs = match l_obligs with | [] -> (k, [obj])::[] | (k', obligs)::tl when cmp_key k k' -> (k, obj::obligs)::tl | o::tl -> o::(aux tl) in aux obligs let add_to_label obligs label obj = add obligs (Olab label) obj let add_to_edge obligs e obj = add obligs (Oedge e) obj let get obligs k = let rec aux l_obligs = match l_obligs with | [] -> [] | (k', obligs)::_ when cmp_key k k' -> obligs | _::tl -> aux tl in aux obligs let get_of_label obligs label = get obligs (Olab label) let get_of_edge obligs e = get obligs (Oedge e) end type t = { mutable mode : t_mode ; cfg: Cil2cfg.t; tbl : HE.t ; mutable memo : LabObligs.t; mutable obligs : LabObligs.t; } let empty cfg = debug "start computing (pass 1)@."; { mode = Pass1; cfg = cfg; tbl = HE.create 97 ; obligs = LabObligs.empty ; memo = LabObligs.empty ;} let is_pass1 res = (res.mode = Pass1) let add_oblig res label obj = debug "add proof obligation at label %a =@. @[<hov2> %a@]@." Clabels.pretty label W.pretty obj; res.obligs <- LabObligs.add_to_label (res.obligs) label obj let add_memo res e obj = debug "Memo goal for Pass2 at %a=@. @[<hov2> %a@]@." Cil2cfg.pp_edge e W.pretty obj; res.memo <- LabObligs.add_to_edge (res.memo) e obj let find res e = let obj = HE.find res.tbl e in match obj with None -> Wp_parameters.warning "find edge annot twice (%a) ?" Cil2cfg.pp_edge e; raise Not_found | Some obj -> if (res.mode = Pass2) && (List.length (Cil2cfg.pred_e res.cfg (Cil2cfg.edge_src e)) < 2) then begin (* it should be used once only : can free it *) HE.replace res.tbl e None; debug "clear edge %a@." Cil2cfg.pp_edge e end; obj (** If needed, clear wp table to compute Pass2. * If nothing has been stored in res.memo, there is nothing to do. *) let change_mode_if_needed res = if LabObligs.is_empty res.memo then () else begin debug "change to Pass2 (clear wp table)@."; begin try let e_start = Cil2cfg.start_edge res.cfg in let start_goal = find res e_start in add_memo res e_start start_goal with Not_found -> () end; HE.clear res.tbl; move memo obligs of Pass1 to obligs for res.obligs <- res.memo; res.memo <- LabObligs.empty; res.mode <- Pass2 end let collect_oblig wenv res e obj = let labels = Cil2cfg.get_edge_labels e in let add obj obligs = List.fold_left (fun obj o -> W.merge wenv o obj) obj obligs in let obj = try debug "get proof obligation at edge %a@." Cil2cfg.pp_edge e; let obligs = LabObligs.get_of_edge res.obligs e in add obj obligs with Not_found -> obj in let add_lab_oblig obj label = try debug "get proof obligation at label %a@." Clabels.pretty label; let obligs = LabObligs.get_of_label res.obligs label in add obj obligs with Not_found -> obj in let obj = List.fold_left add_lab_oblig obj labels in obj (** We have found some assigns hypothesis in the strategy : * it means that we skip the corresponding bloc, ie. we directly compute * the result before the block : (forall assigns. P), * and continue with empty. *) let use_assigns wenv res obj h_assigns = let lab, obj = add_assigns_hyp wenv obj h_assigns in match lab with | None -> obj | Some label -> add_oblig res label obj; W.empty * store the result p for the computation of the edge e. * * - In Compute mode : if we have some hyps H about this edge , store H = > p if we have some goal G about this edge , store G /\ p if we have annotation B to be used as both H and G , store B /\ B=>P We also have to add H and G from HI ( invariants computed in Pass1 mode ) So finally , we build : [ H = > [ BG /\ ( BH = > ( G /\ P ) ) ] ] * * - In Compute mode : if we have some hyps H about this edge, store H => p if we have some goal G about this edge, store G /\ p if we have annotation B to be used as both H and G, store B /\ B=>P We also have to add H and G from HI (invariants computed in Pass1 mode) So finally, we build : [ H => [ BG /\ (BH => (G /\ P)) ] ] *) let set strategy wenv res e obj = try match (HE.find res.tbl e) with | None -> raise Not_found | Some obj -> obj (* cannot warn here because it can happen with CUT properties. * We could check that obj is the same thing than the founded result *) Wp_parameters.fatal " strange loop at % a ? " Cil2cfg.pp_edge e with Not_found -> begin let e_annot = WpStrategy.get_annots strategy e in let h_prop = WpStrategy.get_hyp_only e_annot in let g_prop = WpStrategy.get_goal_only e_annot in let bh_prop, bg_prop = WpStrategy.get_both_hyp_goals e_annot in let h_assigns = WpStrategy.get_asgn_hyp e_annot in let g_assigns = WpStrategy.get_asgn_goal e_annot in (* get_cut is ignored : see get_wp_edge *) let obj = collect_oblig wenv res e obj in let is_loop_head = match Cil2cfg.node_type (Cil2cfg.edge_src e) with | Cil2cfg.Vloop (Some _, _) -> true | _ -> false in let compute ~goal obj = let local_add_goal obj g = if goal then add_goal wenv obj g else obj in let obj = List.fold_left (local_add_goal) obj g_prop in let obj = List.fold_left (add_hyp wenv) obj bh_prop in let obj = if goal then add_assigns_goal wenv obj g_assigns else obj in let obj = List.fold_left (local_add_goal) obj bg_prop in let obj = List.fold_left (add_hyp wenv) obj h_prop in obj in let obj = match res.mode with | Pass1 -> compute ~goal:true obj | Pass2 -> compute ~goal:false obj in let obj = do_labels wenv e obj in let obj = if is_loop_head then obj (* assigns used in [wp_loop] *) else use_assigns wenv res obj h_assigns in debug "[set_wp_edge] %a@." Cil2cfg.pp_edge e; debug " = @[<hov2> %a@]@." W.pretty obj; Format.print_flush (); HE.replace res.tbl e (Some obj); find res e (* this should give back obj, but also do more things *) end end (* module R *) let use_loop_assigns strategy wenv e obj = let e_annot = WpStrategy.get_annots strategy e in let h_assigns = WpStrategy.get_asgn_hyp e_annot in let label, obj = add_assigns_hyp wenv obj h_assigns in match label with Some _ -> obj | None -> assert false (* we should have assigns hyp for loops !*) (** Compute the result for edge [e] which goes to the loop node [nloop]. * So [e] can be either a back_edge or a loop entry edge. * Be very careful not to make an infinite loop by calling [get_loop_head]... * *) let wp_loop ((_, cfg, strategy, _, wenv)) nloop e get_loop_head = let loop_with_quantif () = if Cil2cfg.is_back_edge e then (* Be careful not to use get_only_succ here (infinite loop) *) (debug "[wp_loop] cut at back edge"; W.empty) else (* edge going into the loop from outside : quantify *) begin debug "[wp_loop] quantify"; let obj = get_loop_head nloop in let head = match Cil2cfg.succ_e cfg nloop with | [h] -> h | _ -> assert false (* already detected in [get_loop_head] *) in use_loop_assigns strategy wenv head obj end in if WpStrategy.new_loop_computation strategy & & R.is_pass1 res & & loop_with_cut cfg strategy nloop then loop_with_cut_pass1 ( ) else ( * old mode or no inv or if WpStrategy.new_loop_computation strategy && R.is_pass1 res && loop_with_cut cfg strategy nloop then loop_with_cut_pass1 () else (* old mode or no inv or pass2 *) *) match Cil2cfg.node_type nloop with | Cil2cfg.Vloop (Some true, _) -> (* natural loop (has back edges) *) loop_with_quantif () | _ -> (* TODO : print info about the loop *) Wp_error.unsupported "non-natural loop without invariant property." type callenv = { pre_annots : WpStrategy.t_annots ; post_annots : WpStrategy.t_annots ; exit_annots : WpStrategy.t_annots ; } let callenv cfg strategy v = let eb = match Cil2cfg.pred_e cfg v with e::_ -> e | _ -> assert false in let en, ee = Cil2cfg.get_call_out_edges cfg v in { pre_annots = WpStrategy.get_annots strategy eb ; post_annots = WpStrategy.get_annots strategy en ; exit_annots = WpStrategy.get_annots strategy ee ; } let wp_call_any wenv cenv ~p_post ~p_exit = let obj = W.merge wenv p_post p_exit in let call_asgn = WpStrategy.get_call_asgn cenv.post_annots None in let lab, obj = add_assigns_hyp wenv obj call_asgn in match lab with | Some _ -> obj | None -> assert false let wp_call_kf wenv cenv stmt lval kf args precond ~p_post ~p_exit = let call_asgn = WpStrategy.get_call_asgn cenv.post_annots (Some kf) in let assigns = match call_asgn with | WpPropId.AssignsLocations (_, asgn_body) -> asgn_body.WpPropId.a_assigns | WpPropId.AssignsAny _ -> WritesAny | WpPropId.NoAssignsInfo -> assert false (* see above *) in let pre_hyp, pre_goals = WpStrategy.get_call_pre cenv.pre_annots kf in let obj = W.call wenv stmt lval kf args ~pre:(pre_hyp) ~post:((WpStrategy.get_call_hyp cenv.post_annots kf)) ~pexit:((WpStrategy.get_call_hyp cenv.exit_annots kf)) ~assigns ~p_post ~p_exit in if precond then W.call_goal_precond wenv stmt kf args ~pre:(pre_goals) obj else obj let wp_calls ((_, cfg, strategy, _, wenv)) res v stmt lval call args p_post p_exit = debug "[wp_calls] %a@." Cil2cfg.pp_call_type call; let cenv = callenv cfg strategy v in match call with | Cil2cfg.Static kf -> let precond = WpStrategy.is_default_behavior strategy && R.is_pass1 res in wp_call_kf wenv cenv stmt lval kf args precond ~p_post ~p_exit | Cil2cfg.Dynamic fct -> let bhv = WpStrategy.behavior_name_of_strategy strategy in match Dyncall.get ?bhv stmt with | None -> wp_call_any wenv cenv ~p_post ~p_exit | Some (prop,calls) -> let precond = R.is_pass1 res in let do_call kf = let wp = wp_call_kf wenv cenv stmt lval kf args precond ~p_post ~p_exit in kf , wp in let pid = WpPropId.mk_property prop in W.call_dynamic wenv stmt pid fct (List.map do_call calls) let wp_stmt wenv s obj = match s.skind with | Return (r, _) -> W.return wenv s r obj | Instr i -> begin match i with | Local_init (vi, AssignInit i, _) -> W.init wenv vi (Some i) obj | Local_init (_, ConsInit _, _) -> assert false | (Set (lv, e, _)) -> W.assign wenv s lv e obj | (Asm _) -> let asm = WpPropId.mk_asm_assigns_desc s in W.use_assigns wenv asm.WpPropId.a_stmt None asm obj | (Call _) -> assert false | Skip _ | Code_annot _ -> obj end | Break _ | Continue _ | Goto _ -> obj | Loop _-> (* this is not a real loop (exit before looping) just ignore it ! *) obj | If _ -> assert false | Switch _-> assert false | Block _-> assert false | UnspecifiedSequence _-> assert false | TryExcept _ | TryFinally _ | Throw _ | TryCatch _ -> assert false let wp_scope wenv vars scope obj = debug "[wp_scope] %s : %a@." (match scope with | Mcfg.SC_Global -> "global" | Mcfg.SC_Block_in -> "block in" | Mcfg.SC_Block_out -> "block out" | Mcfg.SC_Function_in -> "function in" | Mcfg.SC_Function_frame -> "function frame" | Mcfg.SC_Function_out -> "function out" ) (Pretty_utils.pp_list ~sep:", " Printer.pp_varinfo) vars; W.scope wenv vars scope obj * @return the WP stored for edge [ e ] . Compute it if it is not already * there and store it . Also handle the annotations . * there and store it. Also handle the Acut annotations. *) let rec get_wp_edge ((_kf, cfg, strategy, res, wenv) as env) e = !Db.progress (); let v = Cil2cfg.edge_dst e in debug "[get_wp_edge] get wp before %a@." Cil2cfg.pp_node v; try let res = R.find res e in debug "[get_wp_edge] %a already computed@." Cil2cfg.pp_node v; res with Not_found -> (* Notice that other hyp and goal are handled in R.set as usual *) let cutp = if R.is_pass1 res then WpStrategy.get_cut (WpStrategy.get_annots strategy e) else [] in match cutp with | [] -> let wp = compute_wp_edge env e in R.set strategy wenv res e wp | cutp -> debug "[get_wp_edge] cut at node %a@." Cil2cfg.pp_node v; let add_cut_goal (g,p) acc = if g then add_goal wenv acc p else acc in let edge_annot = List.fold_right add_cut_goal cutp W.empty in (* put cut goal properties as goals in e if any, else true *) let edge_annot = R.set strategy wenv res e edge_annot in let wp = compute_wp_edge env e in let add_cut_hyp (_,p) acc = add_hyp wenv acc p in let oblig = List.fold_right add_cut_hyp cutp wp in (* TODO : we could add hyp to the oblig if we have some in strategy *) let oblig = W.loop_step oblig in if test_edge_loop_ok cfg None e then R.add_memo res e oblig else R.add_oblig res Clabels.pre (W.close wenv oblig); edge_annot and get_only_succ env cfg v = match Cil2cfg.succ_e cfg v with | [e'] -> get_wp_edge env e' | ls -> Wp_parameters.debug "CFG node %a has %d successors instead of 1@." Cil2cfg.pp_node v (List.length ls); Wp_error.unsupported "strange loop(s)." and compute_wp_edge ((kf, cfg, _annots, res, wenv) as env) e = let v = Cil2cfg.edge_dst e in debug "[compute_edge] before %a go...@." Cil2cfg.pp_node v; let old_loc = Cil.CurrentLoc.get () in let () = match Cil2cfg.node_stmt_opt v with | Some s -> Cil.CurrentLoc.set (Stmt.loc s) | None -> () in let formals = Kernel_function.get_formals kf in let res = match Cil2cfg.node_type v with | Cil2cfg.Vstart -> Wp_parameters.debug "No CFG edge can lead to Vstart"; Wp_error.unsupported "strange CFGs." | Cil2cfg.VfctIn -> let obj = get_only_succ env cfg v in let obj = wp_scope wenv formals Mcfg.SC_Function_in obj in let obj = wp_scope wenv [] Mcfg.SC_Global obj in obj | Cil2cfg.VblkIn (Cil2cfg.Bfct, b) -> let obj = get_only_succ env cfg v in let obj = wp_scope wenv b.blocals Mcfg.SC_Block_in obj in wp_scope wenv formals Mcfg.SC_Function_frame obj | Cil2cfg.VblkIn (_, b) -> let obj = get_only_succ env cfg v in wp_scope wenv b.blocals Mcfg.SC_Block_in obj | Cil2cfg.VblkOut (_, _b) -> let obj = get_only_succ env cfg v in obj (* cf. blocks_closed_by_edge below *) | Cil2cfg.Vstmt s -> let obj = get_only_succ env cfg v in wp_stmt wenv s obj | Cil2cfg.Vcall (stmt, lval, fct, args) -> let en, ee = Cil2cfg.get_call_out_edges cfg v in let objn = get_wp_edge env en in let obje = get_wp_edge env ee in wp_calls env res v stmt lval fct args objn obje | Cil2cfg.Vtest (true, s, c) -> let et, ef = Cil2cfg.get_test_edges cfg v in let t_obj = get_wp_edge env et in let f_obj = get_wp_edge env ef in W.test wenv s c t_obj f_obj | Cil2cfg.Vtest (false, _, _) -> get_only_succ env cfg v | Cil2cfg.Vswitch (s, e) -> let cases, def_edge = Cil2cfg.get_switch_edges cfg v in let cases_obj = List.map (fun (c,e) -> c, get_wp_edge env e) cases in let def_obj = get_wp_edge env def_edge in W.switch wenv s e cases_obj def_obj | Cil2cfg.Vloop _ | Cil2cfg.Vloop2 _ -> let get_loop_head = fun n -> get_only_succ env cfg n in wp_loop env v e get_loop_head | Cil2cfg.VfctOut | Cil2cfg.Vexit -> exitpost / postcondition wp_scope wenv formals Mcfg.SC_Function_out obj | Cil2cfg.Vend -> W.empty LC : unused entry point ... let obj = W.empty in wp_scope wenv formals Mcfg . SC_Function_after_POST obj let obj = W.empty in wp_scope wenv formals Mcfg.SC_Function_after_POST obj *) in let res = let blks = Cil2cfg.blocks_closed_by_edge cfg e in let free_locals res b = wp_scope wenv b.blocals Mcfg.SC_Block_out res in List.fold_left free_locals res blks in debug "[compute_edge] before %a done@." Cil2cfg.pp_node v; Cil.CurrentLoc.set old_loc; res let compute_global_init wenv filter obj = Globals.Vars.fold_in_file_order (fun var initinfo obj -> if var.vstorage = Extern then obj else let do_init = match filter with | `All -> true | `InitConst -> WpStrategy.isGlobalInitConst var in if not do_init then obj else let old_loc = Cil.CurrentLoc.get () in Cil.CurrentLoc.set var.vdecl ; let obj = W.init wenv var initinfo.init obj in Cil.CurrentLoc.set old_loc ; obj ) obj let process_global_const wenv obj = Globals.Vars.fold_in_file_order (fun var _initinfo obj -> if WpStrategy.isGlobalInitConst var then W.const wenv var obj else obj ) obj (* WP of global initializations. *) let process_global_init wenv kf obj = if WpStrategy.is_main_init kf then begin let obj = W.label wenv None Clabels.init obj in compute_global_init wenv `All obj end else if W.has_init wenv then begin let obj = if WpStrategy.isInitConst () then process_global_const wenv obj else obj in let obj = W.use_assigns wenv None None WpPropId.mk_init_assigns obj in let obj = W.label wenv None Clabels.init obj in compute_global_init wenv `All obj end else if WpStrategy.isInitConst () then compute_global_init wenv `InitConst obj else obj let get_weakest_precondition cfg ((kf, _g, strategy, res, wenv) as env) = debug "[wp-cfg] start Pass1"; Cil2cfg.iter_edges (fun e -> ignore (get_wp_edge env e)) cfg ; debug "[wp-cfg] end of Pass1"; R.change_mode_if_needed res; (* Notice that [get_wp_edge] will start Pass2 if needed, * but if not, it will only fetch Pass1 result. *) let e_start = Cil2cfg.start_edge cfg in let obj = get_wp_edge env e_start in let obj = process_global_init wenv kf obj in let obj = match WpStrategy.strategy_kind strategy with | WpStrategy.SKannots -> obj | WpStrategy.SKfroms info -> let pre = info.WpStrategy.get_pre () in let pre = WpStrategy.get_hyp_only pre in W.build_prop_of_from wenv pre obj in debug "before close: %a@." W.pretty obj; W.close wenv obj let compute cfg strategy = debug "[wp-cfg] start computing with the strategy for %a" WpStrategy.pp_info_of_strategy strategy; if WpStrategy.strategy_has_prop_goal strategy || WpStrategy.strategy_has_asgn_goal strategy then try let kf = Cil2cfg.cfg_kf cfg in if Cil2cfg.strange_loops cfg <> [] then Wp_error.unsupported "non natural loop(s)" ; let lvars = match WpStrategy.strategy_kind strategy with | WpStrategy.SKfroms info -> info.WpStrategy.more_vars | _ -> [] in let wenv = W.new_env ~lvars kf in let res = R.empty cfg in let env = (kf, cfg, strategy, res, wenv) in List.iter (fun (pid,thm) -> W.add_axiom pid thm) (WpStrategy.global_axioms strategy) ; let goal = get_weakest_precondition cfg env in debug "[get_weakest_precondition] %a@." W.pretty goal; let pp_cfg_edges_annot res fmt e = try W.pretty fmt (R.find res e) with Not_found -> Format.fprintf fmt "<released>" in let annot_cfg = pp_cfg_edges_annot res in debug "[wp-cfg] computing done."; [goal] , annot_cfg with Wp_error.Error (_, msg) -> Wp_parameters.warning "@[calculus failed on strategy@ @[for %a@]@ \ because@ %s (abort)@]" WpStrategy.pp_info_of_strategy strategy msg; let annot_cfg fmt _e = Format.fprintf fmt "" in [], annot_cfg else begin debug "[wp-cfg] no goal in this strategy : ignore."; let annot_cfg fmt _e = Format.fprintf fmt "" in [], annot_cfg end end
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/wp/calculus.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ Debugging key * Before storing something at a program point, we have to process the label * at that point. [LC] Adding scopes for loop invariant preservation: WHY ???? * detect if the computation of the result at [edge] is possible, * or if it will loop. If [strategy] are provide, * cut are done on edges with cut properties, * and if not, cut are done on loop node back edge if any. * TODO: maybe this should be done while building the strategy ? * normal loop cut e is already in set : loop without cut ! TODOopt: could have a sorted list... it should be used once only : can free it * If needed, clear wp table to compute Pass2. * If nothing has been stored in res.memo, there is nothing to do. * We have found some assigns hypothesis in the strategy : * it means that we skip the corresponding bloc, ie. we directly compute * the result before the block : (forall assigns. P), * and continue with empty. cannot warn here because it can happen with CUT properties. * We could check that obj is the same thing than the founded result get_cut is ignored : see get_wp_edge assigns used in [wp_loop] this should give back obj, but also do more things module R we should have assigns hyp for loops ! * Compute the result for edge [e] which goes to the loop node [nloop]. * So [e] can be either a back_edge or a loop entry edge. * Be very careful not to make an infinite loop by calling [get_loop_head]... * Be careful not to use get_only_succ here (infinite loop) edge going into the loop from outside : quantify already detected in [get_loop_head] old mode or no inv or pass2 natural loop (has back edges) TODO : print info about the loop see above this is not a real loop (exit before looping) just ignore it ! Notice that other hyp and goal are handled in R.set as usual put cut goal properties as goals in e if any, else true TODO : we could add hyp to the oblig if we have some in strategy cf. blocks_closed_by_edge below WP of global initializations. Notice that [get_wp_edge] will start Pass2 if needed, * but if not, it will only fetch Pass1 result.
This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . * Wp computation using the CFG open Cil_types open Cil_datatype module Cfg (W : Mcfg.S) = struct let debug fmt = Wp_parameters.debug ~dkey fmt let do_labels wenv e obj = let do_lab s o l = W.label wenv s l o in let obj = do_lab None obj Clabels.here in let stmt = Cil2cfg.get_edge_stmt e in let labels = Cil2cfg.get_edge_labels e in List.fold_left (do_lab stmt) obj labels let add_hyp wenv obj h = debug "add hyp %a@." WpPropId.pp_pred_info h; W.add_hyp wenv h obj let add_goal wenv obj g = debug "add goal %a@." WpPropId.pp_pred_info g; W.add_goal wenv g obj [ LC ] Nevertheless , if required , this form should be used ( BTS # 1462 ) let open_scope wenv formals blocks = List.fold_right ( fun b obj - > W.scope wenv b.blocals Mcfg . SC_Block_out obj ) blocks ( W.scope wenv formals Mcfg . SC_Function_out W.empty ) match WpPropId.is_loop_preservation ( fst g ) with | None - > W.add_goal | Some stmt - > debug " add scope for loop preservation % a@. " WpPropId.pp_pred_info g ; let blocks = Kernel_function.find_all_enclosing_blocks stmt in let kf = Kernel_function.find_englobing_kf stmt in let formals = Kernel_function.get_formals kf in ( W.add_goal ( open_scope wenv formals blocks ) ) obj let open_scope wenv formals blocks = List.fold_right (fun b obj -> W.scope wenv b.blocals Mcfg.SC_Block_out obj) blocks (W.scope wenv formals Mcfg.SC_Function_out W.empty) match WpPropId.is_loop_preservation (fst g) with | None -> W.add_goal wenv g obj | Some stmt -> debug "add scope for loop preservation %a@." WpPropId.pp_pred_info g ; let blocks = Kernel_function.find_all_enclosing_blocks stmt in let kf = Kernel_function.find_englobing_kf stmt in let formals = Kernel_function.get_formals kf in W.merge wenv (W.add_goal wenv g (open_scope wenv formals blocks)) obj *) let add_assigns_goal wenv obj g_assigns = match g_assigns with | WpPropId.AssignsAny _ | WpPropId.NoAssignsInfo -> obj | WpPropId.AssignsLocations a -> debug "add assign goal (@[%a@])@." WpPropId.pretty (WpPropId.assigns_info_id a); W.add_assigns wenv a obj let add_assigns_hyp wenv obj h_assigns = match h_assigns with | WpPropId.AssignsLocations (h_id, a) -> let hid = Some h_id in let obj = W.use_assigns wenv a.WpPropId.a_stmt hid a obj in Some a.WpPropId.a_label, obj | WpPropId.AssignsAny a -> Wp_parameters.warning ~current:true ~once:true "Missing assigns clause (assigns 'everything' instead)" ; let obj = W.use_assigns wenv a.WpPropId.a_stmt None a obj in Some a.WpPropId.a_label, obj | WpPropId.NoAssignsInfo -> None, obj exception Stop of Cil2cfg.edge let test_edge_loop_ok cfg strategy edge = debug "[test_edge_loop_ok] (%s strategy) for %a" (match strategy with None -> "without" | Some _ -> "with") Cil2cfg.pp_edge edge; let rec collect_edge_preds set e = let cut = match strategy with None -> Cil2cfg.is_back_edge e | Some strategy -> let e_annots = WpStrategy.get_annots strategy e in (WpStrategy.get_cut e_annots <> []) in else if Cil2cfg.Eset.mem e set raise (Stop e) add e to set and continue with its preds let set = Cil2cfg.Eset.add e set in let preds = Cil2cfg.pred_e cfg (Cil2cfg.edge_src e) in List.iter (collect_edge_preds set) preds in try let _ = collect_edge_preds Cil2cfg.Eset.empty edge in debug "[test_edge_loop_ok] ok."; true with Stop e -> begin debug "[test_edge_loop_ok] loop without cut detected at %a" Cil2cfg.pp_edge e; false end * to store the results of computations : * we store a result for each edge , and also a list of proof obligations . * * Be careful that there are two modes of computation : * the first one ( [ Pass1 ] ) is used to prove the establishment of properties * while the second ( after [ change_mode_if_needed ] ) prove the preservation . * See { ! R.set } for more details . * * we store a result for each edge, and also a list of proof obligations. * * Be careful that there are two modes of computation : * the first one ([Pass1]) is used to prove the establishment of properties * while the second (after [change_mode_if_needed]) prove the preservation. * See {!R.set} for more details. * *) module R : sig type t val empty : Cil2cfg.t -> t val is_pass1 : t -> bool val change_mode_if_needed : t -> unit val find : t -> Cil2cfg.edge -> W.t_prop val set : WpStrategy.strategy -> W.t_env -> t -> Cil2cfg.edge -> W.t_prop -> W.t_prop val add_oblig : t -> Clabels.c_label -> W.t_prop -> unit val add_memo : t -> Cil2cfg.edge -> W.t_prop -> unit end = struct type t_mode = Pass1 | Pass2 module HE = Cil2cfg.HE (struct type t = W.t_prop option end) module LabObligs : sig type t val empty : t val is_empty : t -> bool val get_of_label : t -> Clabels.c_label -> W.t_prop list val get_of_edge : t -> Cil2cfg.edge -> W.t_prop list val add_to_label : t -> Clabels.c_label -> W.t_prop -> t val add_to_edge : t -> Cil2cfg.edge -> W.t_prop -> t end = struct type key = Olab of Clabels.c_label | Oedge of Cil2cfg.edge let cmp_key k1 k2 = match k1, k2 with | Olab l1, Olab l2 when Clabels.equal l1 l2 -> true | Oedge e1, Oedge e2 when Cil2cfg.same_edge e1 e2 -> true | _ -> false type t = (key * W.t_prop list) list let empty = [] let is_empty obligs = (obligs = []) let add obligs k obj = let rec aux l_obligs = match l_obligs with | [] -> (k, [obj])::[] | (k', obligs)::tl when cmp_key k k' -> (k, obj::obligs)::tl | o::tl -> o::(aux tl) in aux obligs let add_to_label obligs label obj = add obligs (Olab label) obj let add_to_edge obligs e obj = add obligs (Oedge e) obj let get obligs k = let rec aux l_obligs = match l_obligs with | [] -> [] | (k', obligs)::_ when cmp_key k k' -> obligs | _::tl -> aux tl in aux obligs let get_of_label obligs label = get obligs (Olab label) let get_of_edge obligs e = get obligs (Oedge e) end type t = { mutable mode : t_mode ; cfg: Cil2cfg.t; tbl : HE.t ; mutable memo : LabObligs.t; mutable obligs : LabObligs.t; } let empty cfg = debug "start computing (pass 1)@."; { mode = Pass1; cfg = cfg; tbl = HE.create 97 ; obligs = LabObligs.empty ; memo = LabObligs.empty ;} let is_pass1 res = (res.mode = Pass1) let add_oblig res label obj = debug "add proof obligation at label %a =@. @[<hov2> %a@]@." Clabels.pretty label W.pretty obj; res.obligs <- LabObligs.add_to_label (res.obligs) label obj let add_memo res e obj = debug "Memo goal for Pass2 at %a=@. @[<hov2> %a@]@." Cil2cfg.pp_edge e W.pretty obj; res.memo <- LabObligs.add_to_edge (res.memo) e obj let find res e = let obj = HE.find res.tbl e in match obj with None -> Wp_parameters.warning "find edge annot twice (%a) ?" Cil2cfg.pp_edge e; raise Not_found | Some obj -> if (res.mode = Pass2) && (List.length (Cil2cfg.pred_e res.cfg (Cil2cfg.edge_src e)) < 2) then begin HE.replace res.tbl e None; debug "clear edge %a@." Cil2cfg.pp_edge e end; obj let change_mode_if_needed res = if LabObligs.is_empty res.memo then () else begin debug "change to Pass2 (clear wp table)@."; begin try let e_start = Cil2cfg.start_edge res.cfg in let start_goal = find res e_start in add_memo res e_start start_goal with Not_found -> () end; HE.clear res.tbl; move memo obligs of Pass1 to obligs for res.obligs <- res.memo; res.memo <- LabObligs.empty; res.mode <- Pass2 end let collect_oblig wenv res e obj = let labels = Cil2cfg.get_edge_labels e in let add obj obligs = List.fold_left (fun obj o -> W.merge wenv o obj) obj obligs in let obj = try debug "get proof obligation at edge %a@." Cil2cfg.pp_edge e; let obligs = LabObligs.get_of_edge res.obligs e in add obj obligs with Not_found -> obj in let add_lab_oblig obj label = try debug "get proof obligation at label %a@." Clabels.pretty label; let obligs = LabObligs.get_of_label res.obligs label in add obj obligs with Not_found -> obj in let obj = List.fold_left add_lab_oblig obj labels in obj let use_assigns wenv res obj h_assigns = let lab, obj = add_assigns_hyp wenv obj h_assigns in match lab with | None -> obj | Some label -> add_oblig res label obj; W.empty * store the result p for the computation of the edge e. * * - In Compute mode : if we have some hyps H about this edge , store H = > p if we have some goal G about this edge , store G /\ p if we have annotation B to be used as both H and G , store B /\ B=>P We also have to add H and G from HI ( invariants computed in Pass1 mode ) So finally , we build : [ H = > [ BG /\ ( BH = > ( G /\ P ) ) ] ] * * - In Compute mode : if we have some hyps H about this edge, store H => p if we have some goal G about this edge, store G /\ p if we have annotation B to be used as both H and G, store B /\ B=>P We also have to add H and G from HI (invariants computed in Pass1 mode) So finally, we build : [ H => [ BG /\ (BH => (G /\ P)) ] ] *) let set strategy wenv res e obj = try match (HE.find res.tbl e) with | None -> raise Not_found | Some obj -> obj Wp_parameters.fatal " strange loop at % a ? " Cil2cfg.pp_edge e with Not_found -> begin let e_annot = WpStrategy.get_annots strategy e in let h_prop = WpStrategy.get_hyp_only e_annot in let g_prop = WpStrategy.get_goal_only e_annot in let bh_prop, bg_prop = WpStrategy.get_both_hyp_goals e_annot in let h_assigns = WpStrategy.get_asgn_hyp e_annot in let g_assigns = WpStrategy.get_asgn_goal e_annot in let obj = collect_oblig wenv res e obj in let is_loop_head = match Cil2cfg.node_type (Cil2cfg.edge_src e) with | Cil2cfg.Vloop (Some _, _) -> true | _ -> false in let compute ~goal obj = let local_add_goal obj g = if goal then add_goal wenv obj g else obj in let obj = List.fold_left (local_add_goal) obj g_prop in let obj = List.fold_left (add_hyp wenv) obj bh_prop in let obj = if goal then add_assigns_goal wenv obj g_assigns else obj in let obj = List.fold_left (local_add_goal) obj bg_prop in let obj = List.fold_left (add_hyp wenv) obj h_prop in obj in let obj = match res.mode with | Pass1 -> compute ~goal:true obj | Pass2 -> compute ~goal:false obj in let obj = do_labels wenv e obj in let obj = else use_assigns wenv res obj h_assigns in debug "[set_wp_edge] %a@." Cil2cfg.pp_edge e; debug " = @[<hov2> %a@]@." W.pretty obj; Format.print_flush (); HE.replace res.tbl e (Some obj); end let use_loop_assigns strategy wenv e obj = let e_annot = WpStrategy.get_annots strategy e in let h_assigns = WpStrategy.get_asgn_hyp e_annot in let label, obj = add_assigns_hyp wenv obj h_assigns in match label with Some _ -> obj let wp_loop ((_, cfg, strategy, _, wenv)) nloop e get_loop_head = let loop_with_quantif () = if Cil2cfg.is_back_edge e then (debug "[wp_loop] cut at back edge"; W.empty) begin debug "[wp_loop] quantify"; let obj = get_loop_head nloop in let head = match Cil2cfg.succ_e cfg nloop with | [h] -> h in use_loop_assigns strategy wenv head obj end in if WpStrategy.new_loop_computation strategy & & R.is_pass1 res & & loop_with_cut cfg strategy nloop then loop_with_cut_pass1 ( ) else ( * old mode or no inv or if WpStrategy.new_loop_computation strategy && R.is_pass1 res && loop_with_cut cfg strategy nloop then loop_with_cut_pass1 () *) match Cil2cfg.node_type nloop with loop_with_quantif () Wp_error.unsupported "non-natural loop without invariant property." type callenv = { pre_annots : WpStrategy.t_annots ; post_annots : WpStrategy.t_annots ; exit_annots : WpStrategy.t_annots ; } let callenv cfg strategy v = let eb = match Cil2cfg.pred_e cfg v with e::_ -> e | _ -> assert false in let en, ee = Cil2cfg.get_call_out_edges cfg v in { pre_annots = WpStrategy.get_annots strategy eb ; post_annots = WpStrategy.get_annots strategy en ; exit_annots = WpStrategy.get_annots strategy ee ; } let wp_call_any wenv cenv ~p_post ~p_exit = let obj = W.merge wenv p_post p_exit in let call_asgn = WpStrategy.get_call_asgn cenv.post_annots None in let lab, obj = add_assigns_hyp wenv obj call_asgn in match lab with | Some _ -> obj | None -> assert false let wp_call_kf wenv cenv stmt lval kf args precond ~p_post ~p_exit = let call_asgn = WpStrategy.get_call_asgn cenv.post_annots (Some kf) in let assigns = match call_asgn with | WpPropId.AssignsLocations (_, asgn_body) -> asgn_body.WpPropId.a_assigns | WpPropId.AssignsAny _ -> WritesAny in let pre_hyp, pre_goals = WpStrategy.get_call_pre cenv.pre_annots kf in let obj = W.call wenv stmt lval kf args ~pre:(pre_hyp) ~post:((WpStrategy.get_call_hyp cenv.post_annots kf)) ~pexit:((WpStrategy.get_call_hyp cenv.exit_annots kf)) ~assigns ~p_post ~p_exit in if precond then W.call_goal_precond wenv stmt kf args ~pre:(pre_goals) obj else obj let wp_calls ((_, cfg, strategy, _, wenv)) res v stmt lval call args p_post p_exit = debug "[wp_calls] %a@." Cil2cfg.pp_call_type call; let cenv = callenv cfg strategy v in match call with | Cil2cfg.Static kf -> let precond = WpStrategy.is_default_behavior strategy && R.is_pass1 res in wp_call_kf wenv cenv stmt lval kf args precond ~p_post ~p_exit | Cil2cfg.Dynamic fct -> let bhv = WpStrategy.behavior_name_of_strategy strategy in match Dyncall.get ?bhv stmt with | None -> wp_call_any wenv cenv ~p_post ~p_exit | Some (prop,calls) -> let precond = R.is_pass1 res in let do_call kf = let wp = wp_call_kf wenv cenv stmt lval kf args precond ~p_post ~p_exit in kf , wp in let pid = WpPropId.mk_property prop in W.call_dynamic wenv stmt pid fct (List.map do_call calls) let wp_stmt wenv s obj = match s.skind with | Return (r, _) -> W.return wenv s r obj | Instr i -> begin match i with | Local_init (vi, AssignInit i, _) -> W.init wenv vi (Some i) obj | Local_init (_, ConsInit _, _) -> assert false | (Set (lv, e, _)) -> W.assign wenv s lv e obj | (Asm _) -> let asm = WpPropId.mk_asm_assigns_desc s in W.use_assigns wenv asm.WpPropId.a_stmt None asm obj | (Call _) -> assert false | Skip _ | Code_annot _ -> obj end | Break _ | Continue _ | Goto _ -> obj | If _ -> assert false | Switch _-> assert false | Block _-> assert false | UnspecifiedSequence _-> assert false | TryExcept _ | TryFinally _ | Throw _ | TryCatch _ -> assert false let wp_scope wenv vars scope obj = debug "[wp_scope] %s : %a@." (match scope with | Mcfg.SC_Global -> "global" | Mcfg.SC_Block_in -> "block in" | Mcfg.SC_Block_out -> "block out" | Mcfg.SC_Function_in -> "function in" | Mcfg.SC_Function_frame -> "function frame" | Mcfg.SC_Function_out -> "function out" ) (Pretty_utils.pp_list ~sep:", " Printer.pp_varinfo) vars; W.scope wenv vars scope obj * @return the WP stored for edge [ e ] . Compute it if it is not already * there and store it . Also handle the annotations . * there and store it. Also handle the Acut annotations. *) let rec get_wp_edge ((_kf, cfg, strategy, res, wenv) as env) e = !Db.progress (); let v = Cil2cfg.edge_dst e in debug "[get_wp_edge] get wp before %a@." Cil2cfg.pp_node v; try let res = R.find res e in debug "[get_wp_edge] %a already computed@." Cil2cfg.pp_node v; res with Not_found -> let cutp = if R.is_pass1 res then WpStrategy.get_cut (WpStrategy.get_annots strategy e) else [] in match cutp with | [] -> let wp = compute_wp_edge env e in R.set strategy wenv res e wp | cutp -> debug "[get_wp_edge] cut at node %a@." Cil2cfg.pp_node v; let add_cut_goal (g,p) acc = if g then add_goal wenv acc p else acc in let edge_annot = List.fold_right add_cut_goal cutp W.empty in let edge_annot = R.set strategy wenv res e edge_annot in let wp = compute_wp_edge env e in let add_cut_hyp (_,p) acc = add_hyp wenv acc p in let oblig = List.fold_right add_cut_hyp cutp wp in let oblig = W.loop_step oblig in if test_edge_loop_ok cfg None e then R.add_memo res e oblig else R.add_oblig res Clabels.pre (W.close wenv oblig); edge_annot and get_only_succ env cfg v = match Cil2cfg.succ_e cfg v with | [e'] -> get_wp_edge env e' | ls -> Wp_parameters.debug "CFG node %a has %d successors instead of 1@." Cil2cfg.pp_node v (List.length ls); Wp_error.unsupported "strange loop(s)." and compute_wp_edge ((kf, cfg, _annots, res, wenv) as env) e = let v = Cil2cfg.edge_dst e in debug "[compute_edge] before %a go...@." Cil2cfg.pp_node v; let old_loc = Cil.CurrentLoc.get () in let () = match Cil2cfg.node_stmt_opt v with | Some s -> Cil.CurrentLoc.set (Stmt.loc s) | None -> () in let formals = Kernel_function.get_formals kf in let res = match Cil2cfg.node_type v with | Cil2cfg.Vstart -> Wp_parameters.debug "No CFG edge can lead to Vstart"; Wp_error.unsupported "strange CFGs." | Cil2cfg.VfctIn -> let obj = get_only_succ env cfg v in let obj = wp_scope wenv formals Mcfg.SC_Function_in obj in let obj = wp_scope wenv [] Mcfg.SC_Global obj in obj | Cil2cfg.VblkIn (Cil2cfg.Bfct, b) -> let obj = get_only_succ env cfg v in let obj = wp_scope wenv b.blocals Mcfg.SC_Block_in obj in wp_scope wenv formals Mcfg.SC_Function_frame obj | Cil2cfg.VblkIn (_, b) -> let obj = get_only_succ env cfg v in wp_scope wenv b.blocals Mcfg.SC_Block_in obj | Cil2cfg.VblkOut (_, _b) -> let obj = get_only_succ env cfg v in | Cil2cfg.Vstmt s -> let obj = get_only_succ env cfg v in wp_stmt wenv s obj | Cil2cfg.Vcall (stmt, lval, fct, args) -> let en, ee = Cil2cfg.get_call_out_edges cfg v in let objn = get_wp_edge env en in let obje = get_wp_edge env ee in wp_calls env res v stmt lval fct args objn obje | Cil2cfg.Vtest (true, s, c) -> let et, ef = Cil2cfg.get_test_edges cfg v in let t_obj = get_wp_edge env et in let f_obj = get_wp_edge env ef in W.test wenv s c t_obj f_obj | Cil2cfg.Vtest (false, _, _) -> get_only_succ env cfg v | Cil2cfg.Vswitch (s, e) -> let cases, def_edge = Cil2cfg.get_switch_edges cfg v in let cases_obj = List.map (fun (c,e) -> c, get_wp_edge env e) cases in let def_obj = get_wp_edge env def_edge in W.switch wenv s e cases_obj def_obj | Cil2cfg.Vloop _ | Cil2cfg.Vloop2 _ -> let get_loop_head = fun n -> get_only_succ env cfg n in wp_loop env v e get_loop_head | Cil2cfg.VfctOut | Cil2cfg.Vexit -> exitpost / postcondition wp_scope wenv formals Mcfg.SC_Function_out obj | Cil2cfg.Vend -> W.empty LC : unused entry point ... let obj = W.empty in wp_scope wenv formals Mcfg . SC_Function_after_POST obj let obj = W.empty in wp_scope wenv formals Mcfg.SC_Function_after_POST obj *) in let res = let blks = Cil2cfg.blocks_closed_by_edge cfg e in let free_locals res b = wp_scope wenv b.blocals Mcfg.SC_Block_out res in List.fold_left free_locals res blks in debug "[compute_edge] before %a done@." Cil2cfg.pp_node v; Cil.CurrentLoc.set old_loc; res let compute_global_init wenv filter obj = Globals.Vars.fold_in_file_order (fun var initinfo obj -> if var.vstorage = Extern then obj else let do_init = match filter with | `All -> true | `InitConst -> WpStrategy.isGlobalInitConst var in if not do_init then obj else let old_loc = Cil.CurrentLoc.get () in Cil.CurrentLoc.set var.vdecl ; let obj = W.init wenv var initinfo.init obj in Cil.CurrentLoc.set old_loc ; obj ) obj let process_global_const wenv obj = Globals.Vars.fold_in_file_order (fun var _initinfo obj -> if WpStrategy.isGlobalInitConst var then W.const wenv var obj else obj ) obj let process_global_init wenv kf obj = if WpStrategy.is_main_init kf then begin let obj = W.label wenv None Clabels.init obj in compute_global_init wenv `All obj end else if W.has_init wenv then begin let obj = if WpStrategy.isInitConst () then process_global_const wenv obj else obj in let obj = W.use_assigns wenv None None WpPropId.mk_init_assigns obj in let obj = W.label wenv None Clabels.init obj in compute_global_init wenv `All obj end else if WpStrategy.isInitConst () then compute_global_init wenv `InitConst obj else obj let get_weakest_precondition cfg ((kf, _g, strategy, res, wenv) as env) = debug "[wp-cfg] start Pass1"; Cil2cfg.iter_edges (fun e -> ignore (get_wp_edge env e)) cfg ; debug "[wp-cfg] end of Pass1"; R.change_mode_if_needed res; let e_start = Cil2cfg.start_edge cfg in let obj = get_wp_edge env e_start in let obj = process_global_init wenv kf obj in let obj = match WpStrategy.strategy_kind strategy with | WpStrategy.SKannots -> obj | WpStrategy.SKfroms info -> let pre = info.WpStrategy.get_pre () in let pre = WpStrategy.get_hyp_only pre in W.build_prop_of_from wenv pre obj in debug "before close: %a@." W.pretty obj; W.close wenv obj let compute cfg strategy = debug "[wp-cfg] start computing with the strategy for %a" WpStrategy.pp_info_of_strategy strategy; if WpStrategy.strategy_has_prop_goal strategy || WpStrategy.strategy_has_asgn_goal strategy then try let kf = Cil2cfg.cfg_kf cfg in if Cil2cfg.strange_loops cfg <> [] then Wp_error.unsupported "non natural loop(s)" ; let lvars = match WpStrategy.strategy_kind strategy with | WpStrategy.SKfroms info -> info.WpStrategy.more_vars | _ -> [] in let wenv = W.new_env ~lvars kf in let res = R.empty cfg in let env = (kf, cfg, strategy, res, wenv) in List.iter (fun (pid,thm) -> W.add_axiom pid thm) (WpStrategy.global_axioms strategy) ; let goal = get_weakest_precondition cfg env in debug "[get_weakest_precondition] %a@." W.pretty goal; let pp_cfg_edges_annot res fmt e = try W.pretty fmt (R.find res e) with Not_found -> Format.fprintf fmt "<released>" in let annot_cfg = pp_cfg_edges_annot res in debug "[wp-cfg] computing done."; [goal] , annot_cfg with Wp_error.Error (_, msg) -> Wp_parameters.warning "@[calculus failed on strategy@ @[for %a@]@ \ because@ %s (abort)@]" WpStrategy.pp_info_of_strategy strategy msg; let annot_cfg fmt _e = Format.fprintf fmt "" in [], annot_cfg else begin debug "[wp-cfg] no goal in this strategy : ignore."; let annot_cfg fmt _e = Format.fprintf fmt "" in [], annot_cfg end end
2b90ec3ac6107de383e90e051e5fb551b317a29dcd309763e7e7de60bfb3c876
maybe-hedgehog-later/hedgehog-golden
Aeson.hs
| This module can be used in order to create golden tests for serializers and -- -- @ { -\ # LANGUAGE TemplateHaskell \#- } -- -- import Hedgehog import qualified Hedgehog . Gen as Gen import qualified Hedgehog . Golden . Aeson as -- -- -- | A golden test for characters in the hex range -- prop_char_golden :: Property -- prop_char_golden = Aeson.goldenProperty Gen.hexit -- -- tests :: IO Bool -- tests = checkParallel $$discover -- @ module Hedgehog.Golden.Aeson ( -- * Golden tests for generators goldenProperty , goldenProperty' ) where import Prelude import Control.Monad (forM_) import Control.Monad.IO.Class (MonadIO(..)) import Data.Algorithm.Diff (PolyDiff(..), getDiff) import Data.Aeson (FromJSON, ToJSON, (.=), (.:), (.:?)) import qualified Data.Aeson as Aeson (eitherDecodeStrict) import qualified Data.Aeson.Types as Aeson import Data.Aeson.Encode.Pretty (Config(..), Indent(..), encodePretty', defConfig) import qualified Data.ByteString.Lazy as ByteString (toStrict) import Data.Maybe (fromMaybe) import Data.Proxy (Proxy(..)) import Data.Sequence (Seq) import Data.Text (Text) import qualified Data.Text as Text (intercalate, lines, pack, replace, unpack) import qualified Data.Text.Encoding as Text (decodeUtf8, encodeUtf8) import qualified Data.Text.IO as Text (readFile, writeFile) import Data.Typeable (Typeable, typeRep) import Hedgehog (Gen, Property, PropertyT, Size(..), Seed(..)) import Hedgehog.Gen (int, sample) import Hedgehog.Range (linear) import Hedgehog (success) import qualified Hedgehog.Internal.Seed as Seed import Hedgehog.Internal.Source import Hedgehog.Internal.Property (Log(..), Property(..), PropertyConfig(..)) import Hedgehog.Internal.Property (TerminationCriteria(..)) import Hedgehog.Internal.Property (defaultConfig, evalM, failWith, writeLog) import Hedgehog.Golden.Sample (genSamples) import Hedgehog.Golden.Types (GoldenTest(..), ValueGenerator, ValueReader) import qualified Hedgehog.Golden.Internal.Source as Source import System.Directory (createDirectoryIfMissing, doesFileExist, getCurrentDirectory) -- | Run a golden test on the given generator -- -- This will create a file in @golden/<TypeName>.json.new@ in case it does not -- exist. If it does exist - the golden tests will be run against it -- goldenProperty :: forall a . HasCallStack => Typeable a => FromJSON a => ToJSON a => Gen a -> Property goldenProperty = withFrozenCallStack $ goldenProperty' "golden/" -- | Same as 'goldenProperty' but allows specifying the directory -- goldenProperty' :: forall a . HasCallStack => Typeable a => FromJSON a => ToJSON a => FilePath -> Gen a -> Property goldenProperty' baseDir gen = withFrozenCallStack $ Property config . evalM $ goldenTest baseDir gen >>= \case NewFile fileName valGen -> do newGoldenFile baseDir fileName valGen ExistingFile fileName valGen readerM -> existingGoldenFile baseDir fileName valGen readerM where config = defaultConfig { propertyTerminationCriteria = NoConfidenceTermination 1 , propertyShrinkLimit = 0 } newGoldenFile :: HasCallStack => FilePath -> FilePath -> ValueGenerator -> PropertyT IO () newGoldenFile basePath fileName valueGen = do seed <- Seed.random size <- Size <$> sample (int (linear 1 10000)) -- Create new file liftIO $ do createDirectoryIfMissing True basePath Text.writeFile (fileName <> ".new") . Text.intercalate "\n" . (valueGen size) $ seed -- Annotate output currentDir <- liftIO $ getCurrentDirectory writeLog . Footnote $ "New golden file generated in: " <> currentDir <> "/" <> fileName <> ".new" failWith Nothing "No previous golden file exists" existingGoldenFile :: HasCallStack => FilePath -> FilePath -> ValueGenerator -> Maybe ValueReader -> PropertyT IO () existingGoldenFile basePath fp gen reader = getSeedAndLines >>= \case Right ((size, seed), existingLines) -> let comparison = getDiff existingLines $ gen size seed hasDifference = any $ \case Both _ _ -> False First _ -> True Second _ -> True runDecodeTest = forM_ reader $ \r -> either (failWith Nothing . (<>) "Failed to deserialize with error: " . Text.unpack) (const success) (r . Text.intercalate "\n" $ existingLines) in if hasDifference comparison then do liftIO $ do createDirectoryIfMissing False basePath Text.writeFile (fp <> ".gen") . Text.intercalate "\n" . (gen size) $ seed writeLog . Footnote $ "Different file generated as: " <> fp <> ".gen" failWith Nothing . Text.unpack . Text.intercalate "\n" $ [ "Failed in serialization comparison" , "" , Source.yellow "Difference when generating: " <> Text.pack fp , printDifference comparison ] else runDecodeTest Left err -> failWith Nothing $ "Couldn't read previous golden file (" <> fp <> ") because: " <> err where getSeedAndLines = liftIO $ do fileContents <- Text.readFile fp pure . fmap (, Text.lines fileContents) . decodeSizeAndSeed $ fileContents printDifference :: [PolyDiff Text Text] -> Text printDifference = Text.intercalate "\n" . Source.wrap Source.boxTop Source.boxBottom . addLineNumbers 1 . renderDiff where renderDiff :: [PolyDiff Text Text] -> [PolyDiff Text Text] renderDiff = fmap $ \case Both text _ -> Both (" " <> text) (" " <> text) First text -> First $ Source.red $ "-" <> text Second text -> Second $ Source.green $ "+" <> text addLineNumbers :: Int -> [PolyDiff Text Text] -> [Text] addLineNumbers _ [] = [] addLineNumbers i (d : ds) = case d of Both text _ -> Source.addLineNumber i text : addLineNumbers (i + 1) ds First text -> Source.addLineNumber i text : addLineNumbers i ds Second text -> Source.addLineNumber i text : addLineNumbers (i + 1) ds goldenTest :: forall a m . Typeable a => FromJSON a => ToJSON a => MonadIO m => FilePath -> Gen a -> m GoldenTest goldenTest prefix gen = do let typeName = Text.replace " " "_" (Text.pack . show . typeRep $ Proxy @a) fileName = prefix <> Text.unpack typeName <> ".json" aesonValueGenerator size seed = Text.lines . encodeGolden size seed $ genSamples size seed gen aesonValueReader t = either (Left . Text.pack) (const $ Right ()) $ Aeson.eitherDecodeStrict (Text.encodeUtf8 t) >>= decodeGolden @a fileExists <- liftIO $ doesFileExist fileName pure $ if fileExists then ExistingFile fileName aesonValueGenerator (Just aesonValueReader) else NewFile fileName aesonValueGenerator encodeGolden :: ToJSON a => Size -> Seed -> Seq a -> Text encodeGolden size seed samples = let aesonSeed (Seed value gamma) = Aeson.object [ "value" .= value, "gamma" .= gamma ] aesonSize (Size s) = Aeson.Number $ fromInteger $ toInteger s encodePretty = Text.decodeUtf8 . ByteString.toStrict . encodePretty' defConfig { confIndent = Spaces 2 , confCompare = compare } in encodePretty $ Aeson.object [ "seed" .= aesonSeed seed , "size" .= aesonSize size , "samples" .= Aeson.toJSON samples ] decodeSizeAndSeed :: Text -> Either String (Size, Seed) decodeSizeAndSeed text = let getSeed :: Aeson.Object -> Either String (Size, Seed) getSeed = Aeson.parseEither $ \obj -> do value <- obj .: "seed" >>= (.: "value") gamma <- obj .: "seed" >>= (.: "gamma") maybeSize <- obj .:? "size" pure $ (Size (fromMaybe 0 maybeSize), Seed value gamma) in Aeson.eitherDecodeStrict (Text.encodeUtf8 text) >>= getSeed decodeGolden :: FromJSON a => Aeson.Object -> Either String (Size, Seed, Seq a) decodeGolden = Aeson.parseEither $ \obj -> do value <- obj .: "seed" >>= (.: "value") gamma <- obj .: "seed" >>= (.: "gamma") size <- obj .: "size" samples <- obj .: "samples" pure (Size size, Seed value gamma, samples)
null
https://raw.githubusercontent.com/maybe-hedgehog-later/hedgehog-golden/c0ce794c13c570077e386e5f1dc195e05a99e702/src/Hedgehog/Golden/Aeson.hs
haskell
@ import Hedgehog -- | A golden test for characters in the hex range prop_char_golden :: Property prop_char_golden = Aeson.goldenProperty Gen.hexit tests :: IO Bool tests = checkParallel $$discover @ * Golden tests for generators | Run a golden test on the given generator This will create a file in @golden/<TypeName>.json.new@ in case it does not exist. If it does exist - the golden tests will be run against it | Same as 'goldenProperty' but allows specifying the directory Create new file Annotate output
| This module can be used in order to create golden tests for serializers and { -\ # LANGUAGE TemplateHaskell \#- } import qualified Hedgehog . Gen as Gen import qualified Hedgehog . Golden . Aeson as module Hedgehog.Golden.Aeson goldenProperty , goldenProperty' ) where import Prelude import Control.Monad (forM_) import Control.Monad.IO.Class (MonadIO(..)) import Data.Algorithm.Diff (PolyDiff(..), getDiff) import Data.Aeson (FromJSON, ToJSON, (.=), (.:), (.:?)) import qualified Data.Aeson as Aeson (eitherDecodeStrict) import qualified Data.Aeson.Types as Aeson import Data.Aeson.Encode.Pretty (Config(..), Indent(..), encodePretty', defConfig) import qualified Data.ByteString.Lazy as ByteString (toStrict) import Data.Maybe (fromMaybe) import Data.Proxy (Proxy(..)) import Data.Sequence (Seq) import Data.Text (Text) import qualified Data.Text as Text (intercalate, lines, pack, replace, unpack) import qualified Data.Text.Encoding as Text (decodeUtf8, encodeUtf8) import qualified Data.Text.IO as Text (readFile, writeFile) import Data.Typeable (Typeable, typeRep) import Hedgehog (Gen, Property, PropertyT, Size(..), Seed(..)) import Hedgehog.Gen (int, sample) import Hedgehog.Range (linear) import Hedgehog (success) import qualified Hedgehog.Internal.Seed as Seed import Hedgehog.Internal.Source import Hedgehog.Internal.Property (Log(..), Property(..), PropertyConfig(..)) import Hedgehog.Internal.Property (TerminationCriteria(..)) import Hedgehog.Internal.Property (defaultConfig, evalM, failWith, writeLog) import Hedgehog.Golden.Sample (genSamples) import Hedgehog.Golden.Types (GoldenTest(..), ValueGenerator, ValueReader) import qualified Hedgehog.Golden.Internal.Source as Source import System.Directory (createDirectoryIfMissing, doesFileExist, getCurrentDirectory) goldenProperty :: forall a . HasCallStack => Typeable a => FromJSON a => ToJSON a => Gen a -> Property goldenProperty = withFrozenCallStack $ goldenProperty' "golden/" goldenProperty' :: forall a . HasCallStack => Typeable a => FromJSON a => ToJSON a => FilePath -> Gen a -> Property goldenProperty' baseDir gen = withFrozenCallStack $ Property config . evalM $ goldenTest baseDir gen >>= \case NewFile fileName valGen -> do newGoldenFile baseDir fileName valGen ExistingFile fileName valGen readerM -> existingGoldenFile baseDir fileName valGen readerM where config = defaultConfig { propertyTerminationCriteria = NoConfidenceTermination 1 , propertyShrinkLimit = 0 } newGoldenFile :: HasCallStack => FilePath -> FilePath -> ValueGenerator -> PropertyT IO () newGoldenFile basePath fileName valueGen = do seed <- Seed.random size <- Size <$> sample (int (linear 1 10000)) liftIO $ do createDirectoryIfMissing True basePath Text.writeFile (fileName <> ".new") . Text.intercalate "\n" . (valueGen size) $ seed currentDir <- liftIO $ getCurrentDirectory writeLog . Footnote $ "New golden file generated in: " <> currentDir <> "/" <> fileName <> ".new" failWith Nothing "No previous golden file exists" existingGoldenFile :: HasCallStack => FilePath -> FilePath -> ValueGenerator -> Maybe ValueReader -> PropertyT IO () existingGoldenFile basePath fp gen reader = getSeedAndLines >>= \case Right ((size, seed), existingLines) -> let comparison = getDiff existingLines $ gen size seed hasDifference = any $ \case Both _ _ -> False First _ -> True Second _ -> True runDecodeTest = forM_ reader $ \r -> either (failWith Nothing . (<>) "Failed to deserialize with error: " . Text.unpack) (const success) (r . Text.intercalate "\n" $ existingLines) in if hasDifference comparison then do liftIO $ do createDirectoryIfMissing False basePath Text.writeFile (fp <> ".gen") . Text.intercalate "\n" . (gen size) $ seed writeLog . Footnote $ "Different file generated as: " <> fp <> ".gen" failWith Nothing . Text.unpack . Text.intercalate "\n" $ [ "Failed in serialization comparison" , "" , Source.yellow "Difference when generating: " <> Text.pack fp , printDifference comparison ] else runDecodeTest Left err -> failWith Nothing $ "Couldn't read previous golden file (" <> fp <> ") because: " <> err where getSeedAndLines = liftIO $ do fileContents <- Text.readFile fp pure . fmap (, Text.lines fileContents) . decodeSizeAndSeed $ fileContents printDifference :: [PolyDiff Text Text] -> Text printDifference = Text.intercalate "\n" . Source.wrap Source.boxTop Source.boxBottom . addLineNumbers 1 . renderDiff where renderDiff :: [PolyDiff Text Text] -> [PolyDiff Text Text] renderDiff = fmap $ \case Both text _ -> Both (" " <> text) (" " <> text) First text -> First $ Source.red $ "-" <> text Second text -> Second $ Source.green $ "+" <> text addLineNumbers :: Int -> [PolyDiff Text Text] -> [Text] addLineNumbers _ [] = [] addLineNumbers i (d : ds) = case d of Both text _ -> Source.addLineNumber i text : addLineNumbers (i + 1) ds First text -> Source.addLineNumber i text : addLineNumbers i ds Second text -> Source.addLineNumber i text : addLineNumbers (i + 1) ds goldenTest :: forall a m . Typeable a => FromJSON a => ToJSON a => MonadIO m => FilePath -> Gen a -> m GoldenTest goldenTest prefix gen = do let typeName = Text.replace " " "_" (Text.pack . show . typeRep $ Proxy @a) fileName = prefix <> Text.unpack typeName <> ".json" aesonValueGenerator size seed = Text.lines . encodeGolden size seed $ genSamples size seed gen aesonValueReader t = either (Left . Text.pack) (const $ Right ()) $ Aeson.eitherDecodeStrict (Text.encodeUtf8 t) >>= decodeGolden @a fileExists <- liftIO $ doesFileExist fileName pure $ if fileExists then ExistingFile fileName aesonValueGenerator (Just aesonValueReader) else NewFile fileName aesonValueGenerator encodeGolden :: ToJSON a => Size -> Seed -> Seq a -> Text encodeGolden size seed samples = let aesonSeed (Seed value gamma) = Aeson.object [ "value" .= value, "gamma" .= gamma ] aesonSize (Size s) = Aeson.Number $ fromInteger $ toInteger s encodePretty = Text.decodeUtf8 . ByteString.toStrict . encodePretty' defConfig { confIndent = Spaces 2 , confCompare = compare } in encodePretty $ Aeson.object [ "seed" .= aesonSeed seed , "size" .= aesonSize size , "samples" .= Aeson.toJSON samples ] decodeSizeAndSeed :: Text -> Either String (Size, Seed) decodeSizeAndSeed text = let getSeed :: Aeson.Object -> Either String (Size, Seed) getSeed = Aeson.parseEither $ \obj -> do value <- obj .: "seed" >>= (.: "value") gamma <- obj .: "seed" >>= (.: "gamma") maybeSize <- obj .:? "size" pure $ (Size (fromMaybe 0 maybeSize), Seed value gamma) in Aeson.eitherDecodeStrict (Text.encodeUtf8 text) >>= getSeed decodeGolden :: FromJSON a => Aeson.Object -> Either String (Size, Seed, Seq a) decodeGolden = Aeson.parseEither $ \obj -> do value <- obj .: "seed" >>= (.: "value") gamma <- obj .: "seed" >>= (.: "gamma") size <- obj .: "size" samples <- obj .: "samples" pure (Size size, Seed value gamma, samples)
89b00cbbbbe6d666ddfea0eefa1de52626fa4ad5d3ad2ed7e9fd2099e90749f3
blarney-lang/blarney
Derive.hs
import Blarney import System.Environment data MemReq = MemReq { memOp :: Bit 1 -- Is it a load or a store request? 32 - bit address 32 - bit data for stores } deriving (Generic, Bits, FShow) -- Top-level module top :: Module () top = always do let req = MemReq { memOp = 0, memAddr = 100, memData = 0 } display "req = " req finish -- Main function main :: IO () main = do args <- getArgs if | "--simulate" `elem` args -> simulate top | otherwise -> writeVerilogTop top "Derive" "Derive-Verilog/"
null
https://raw.githubusercontent.com/blarney-lang/blarney/506d2d4f02f5a3dc0a7f55956767d2c2c6b40eca/Examples/Derive/Derive.hs
haskell
Is it a load or a store request? Top-level module Main function
import Blarney import System.Environment data MemReq = MemReq { 32 - bit address 32 - bit data for stores } deriving (Generic, Bits, FShow) top :: Module () top = always do let req = MemReq { memOp = 0, memAddr = 100, memData = 0 } display "req = " req finish main :: IO () main = do args <- getArgs if | "--simulate" `elem` args -> simulate top | otherwise -> writeVerilogTop top "Derive" "Derive-Verilog/"
f41bb29a3d88506de4c45cab6f6cd3f704459259eb431475eb986178dacf46df
janestreet/async_kernel
eager_deferred_memo.mli
include Async_kernel.Deferred.Memo.S with type 'a deferred := 'a Eager_deferred0.t * @inline
null
https://raw.githubusercontent.com/janestreet/async_kernel/5807f6d4ef415408e8ec5afe74cdff5d27f277d4/eager_deferred/src/eager_deferred_memo.mli
ocaml
include Async_kernel.Deferred.Memo.S with type 'a deferred := 'a Eager_deferred0.t * @inline
ae3cb1106afabe3de240e23b4125616d815f010efc2c676de7d5362c89fb7ba2
spechub/Hets
Parse.hs
module NeSyPatterns.Parse (basicSpec, symb, symbItems, symbMapItems) where import Common.Keywords import Common.AnnoState import Common.Id import Common.IRI import Common.Lexer import Common.Parsec import qualified Common.GlobalAnnotations as GA (PrefixMap) import NeSyPatterns.AS import Data.Maybe (isJust, catMaybes) import Text.ParserCombinators.Parsec symb :: GA.PrefixMap -> AParser st SYMB symb = fmap Symb_id . node symbItems :: GA.PrefixMap -> AParser st SYMB_ITEMS symbItems pm = do is <- fst <$> symb pm `separatedBy` anComma let range = concatMapRange getRange is return $ Symb_items is range symbOrMap :: GA.PrefixMap -> AParser st SYMB_OR_MAP symbOrMap pm = do s1 <- symb pm s2M <- optionMaybe (asKey mapsTo >> symb pm) case s2M of Nothing -> return $ Symb s1 Just s2 -> return $ Symb_map s1 s2 (concatMapRange getRange [s1, s2]) symbMapItems :: GA.PrefixMap -> AParser st SYMB_MAP_ITEMS symbMapItems pm = do is <- fst <$> symbOrMap pm `separatedBy` anComma let range = concatMapRange getRange is return $ Symb_map_items is range nesyKeywords :: [String] nesyKeywords = [endS] uriQ :: CharParser st IRI uriQ = iriCurie expUriP :: GA.PrefixMap -> CharParser st IRI expUriP pm = uriP >>= return . expandIRI pm uriP :: CharParser st IRI uriP = try $ do startsWithColon <- isJust <$> (optionMaybe . try . lookAhead $ char ':') checkWithUsing (\i -> "keyword \"" ++ showIRI i ++ "\"") uriQ $ \ q -> let p = prefixName q in (not (isAbbrev q) || startsWithColon) || (not (null p) || iFragment q `notElem` nesyKeywords) name :: GA.PrefixMap -> AParser st IRI name pm = wrapAnnos $ expUriP pm node :: GA.PrefixMap -> AParser st Node node pm = do n <- name pm classM <- optionMaybe (asKey ":" >> name pm) let range = getRange . catMaybes $ [Just n, classM] return $ case classM of Nothing -> Node n Nothing range Just ot -> Node ot (Just n) range basicItem :: GA.PrefixMap -> AParser st BASIC_ITEM basicItem pm = Path <$> fst <$> separatedBy (node pm) (asKey "->") << anSemi basicSpec :: GA.PrefixMap -> AParser st BASIC_SPEC basicSpec pm = Basic_spec <$> annosParser (basicItem pm) -- -- Function for easier testing test : : ( ) a - > String - > a test p s = case ( emptyAnnos ( ) ) " " s of -- Left e -> error $ "***Error:" ++ show e -- Right a -> a
null
https://raw.githubusercontent.com/spechub/Hets/fc26b4947bf52be6baf7819a75d7e7f127e290dd/NeSyPatterns/Parse.hs
haskell
-- Function for easier testing Left e -> error $ "***Error:" ++ show e Right a -> a
module NeSyPatterns.Parse (basicSpec, symb, symbItems, symbMapItems) where import Common.Keywords import Common.AnnoState import Common.Id import Common.IRI import Common.Lexer import Common.Parsec import qualified Common.GlobalAnnotations as GA (PrefixMap) import NeSyPatterns.AS import Data.Maybe (isJust, catMaybes) import Text.ParserCombinators.Parsec symb :: GA.PrefixMap -> AParser st SYMB symb = fmap Symb_id . node symbItems :: GA.PrefixMap -> AParser st SYMB_ITEMS symbItems pm = do is <- fst <$> symb pm `separatedBy` anComma let range = concatMapRange getRange is return $ Symb_items is range symbOrMap :: GA.PrefixMap -> AParser st SYMB_OR_MAP symbOrMap pm = do s1 <- symb pm s2M <- optionMaybe (asKey mapsTo >> symb pm) case s2M of Nothing -> return $ Symb s1 Just s2 -> return $ Symb_map s1 s2 (concatMapRange getRange [s1, s2]) symbMapItems :: GA.PrefixMap -> AParser st SYMB_MAP_ITEMS symbMapItems pm = do is <- fst <$> symbOrMap pm `separatedBy` anComma let range = concatMapRange getRange is return $ Symb_map_items is range nesyKeywords :: [String] nesyKeywords = [endS] uriQ :: CharParser st IRI uriQ = iriCurie expUriP :: GA.PrefixMap -> CharParser st IRI expUriP pm = uriP >>= return . expandIRI pm uriP :: CharParser st IRI uriP = try $ do startsWithColon <- isJust <$> (optionMaybe . try . lookAhead $ char ':') checkWithUsing (\i -> "keyword \"" ++ showIRI i ++ "\"") uriQ $ \ q -> let p = prefixName q in (not (isAbbrev q) || startsWithColon) || (not (null p) || iFragment q `notElem` nesyKeywords) name :: GA.PrefixMap -> AParser st IRI name pm = wrapAnnos $ expUriP pm node :: GA.PrefixMap -> AParser st Node node pm = do n <- name pm classM <- optionMaybe (asKey ":" >> name pm) let range = getRange . catMaybes $ [Just n, classM] return $ case classM of Nothing -> Node n Nothing range Just ot -> Node ot (Just n) range basicItem :: GA.PrefixMap -> AParser st BASIC_ITEM basicItem pm = Path <$> fst <$> separatedBy (node pm) (asKey "->") << anSemi basicSpec :: GA.PrefixMap -> AParser st BASIC_SPEC basicSpec pm = Basic_spec <$> annosParser (basicItem pm) test : : ( ) a - > String - > a test p s = case ( emptyAnnos ( ) ) " " s of
d008ebe82b4235efe711a6aea5b588011d4db28fd5ce012a36eba4c873c3d58f
well-typed/optics
Re.hs
module MMP.Optics.Re where import Control.Monad import Optics import MetaMetaPost import MMP.Optics.Common reOptics :: Stmts s () reOptics = do clippath <- vardef3 "clippath" SPath SPicture SPicture $ \p a b -> do t1 <- bindSnd_ $ bbox_ a `IntersectionTimes` p t2 <- bindSnd_ $ bbox_ b `IntersectionTimes` reverse_ p return $ subpath_ (t1, length_ p .- t2) p clippath' <- vardef3 "clippath" SPath SPath SPath $ \p a b -> do t1 <- bindSnd_ $ bbox_ a `IntersectionTimes` p t2 <- bindSnd_ $ bbox_ b `IntersectionTimes` reverse_ p return $ subpath_ (t1, length_ p .- t2) p clippathend <- vardef2 "clippathend" SPath SPicture $ \p a -> do t2 <- bindSnd_ $ bbox_ a `IntersectionTimes` reverse_ p return $ subpath_ (L 0, length_ p .- t2) p z <- traverse bind_ positions q <- itraverse (\k -> bind_ . TheLabel ("\\mathit{" ++ okName k ++ "}")) z ifor_ q $ \k pic -> when (isRe k) $ draw_ pic -- arrows let path a b = P $ z ^. rix a .... z ^. rix b let arrow a b = drawarrow_ $ clippath (path a b) (q ^. rix a) (q ^. rix b) arrow Tag_Iso Tag_Lens arrow Tag_Iso Tag_Prism arrow Tag_Iso Tag_ReversedLens arrow Tag_Iso Tag_ReversedPrism arrow Tag_ReversedLens Tag_Review arrow Tag_Prism Tag_Review arrow Tag_Lens Tag_Getter arrow Tag_ReversedPrism Tag_Getter -- Getter <-> Review red <- bind_ $ RGB (L 0.5) (L 0) (L 0) getterReview <- bind_ $ P $ (z ^. rix Tag_Getter, L 160) .... (z ^. rix Tag_Review) getterReview1 <- bind_ $ subpath_ (L 0.5 .* length_ getterReview, length_ getterReview) getterReview getterReview2 <- bind_ $ reverse_ $ subpath_ (L 0, L 0.5 .* length_ getterReview) getterReview drawarrowC_ red $ clippathend getterReview1 (q ^. rix Tag_Review) drawarrowC_ red $ clippathend getterReview2 (q ^. rix Tag_Getter) -- Lens <-> ReversedLens & Prism <-> ReversedPrism prismReview <- bind_ $ path Tag_Prism Tag_Review lensGetter <- bind_ $ path Tag_Lens Tag_Getter prismReversedPrism <- bind_ $ P $ (z ^. rix Tag_ReversedPrism, L 168) .... (z ^. rix Tag_Prism) lensReversedLens <- bind_ $ P $ (z ^. rix Tag_Lens, L 168) .... (z ^. rix Tag_ReversedLens) it1 <- bindSnd_ $ lensGetter `IntersectionTimes` prismReversedPrism ip1 <- bind_ $ lensGetter `IntersectionPoint` prismReversedPrism ic1 <- bind_ $ Circle (L 2) ip1 it2 <- bindSnd_ $ prismReversedPrism `IntersectionTimes` lensReversedLens ip2 <- bind_ $ prismReversedPrism `IntersectionPoint` lensReversedLens ic2 <- bind_ $ Circle (L 8) ip2 it3 <- bindSnd_ $ prismReview `IntersectionTimes` lensReversedLens ip3 <- bind_ $ prismReview `IntersectionPoint` lensReversedLens ic3 <- bind_ $ Circle (L 2) ip3 -- Prism <-> ReversedPrism drawarrowC_ red $ clippath' (subpath_ (L 0, it1) prismReversedPrism) ic1 (bbox_ $ q ^. rix Tag_ReversedPrism) drawarrowC_ red $ reverse_ $ clippath' (subpath_ (it1, length_ prismReversedPrism) prismReversedPrism) (bbox_ $ q ^. rix Tag_Prism) ic1 -- Lens <-> ReversedLens pieces drawarrowC_ red $ clippath' (subpath_ (it3, length_ lensReversedLens) lensReversedLens) ic3 (bbox_ $ q ^. rix Tag_ReversedLens) drawC_ red $ clippath' (subpath_ (it3, it2) lensReversedLens) ic3 ic2 drawarrowC_ red $ reverse_ $ clippath' (subpath_ (L 0, it2) lensReversedLens) (bbox_ $ q ^. rix Tag_Lens) ic2 -- TODO: add crossings... drawarrowC_ red $ P $ (z ^. rix Tag_Iso .+ Pair 5 5, L 80) ... (z ^. rix Tag_Iso .+ Pair 20 0, L 270) .... (z ^. rix Tag_Iso .+ Pair 5 (-5), L 100) where isRe Tag_Iso = True isRe Tag_Lens = True isRe Tag_Prism = True isRe Tag_ReversedLens = True isRe Tag_ReversedPrism = True isRe Tag_Getter = True isRe Tag_Review = True isRe _ = False
null
https://raw.githubusercontent.com/well-typed/optics/1832f316c7b01fdd0526fd0362fc0495e5b97319/metametapost/src/MMP/Optics/Re.hs
haskell
arrows Getter <-> Review Lens <-> ReversedLens & Prism <-> ReversedPrism Prism <-> ReversedPrism Lens <-> ReversedLens pieces TODO: add crossings...
module MMP.Optics.Re where import Control.Monad import Optics import MetaMetaPost import MMP.Optics.Common reOptics :: Stmts s () reOptics = do clippath <- vardef3 "clippath" SPath SPicture SPicture $ \p a b -> do t1 <- bindSnd_ $ bbox_ a `IntersectionTimes` p t2 <- bindSnd_ $ bbox_ b `IntersectionTimes` reverse_ p return $ subpath_ (t1, length_ p .- t2) p clippath' <- vardef3 "clippath" SPath SPath SPath $ \p a b -> do t1 <- bindSnd_ $ bbox_ a `IntersectionTimes` p t2 <- bindSnd_ $ bbox_ b `IntersectionTimes` reverse_ p return $ subpath_ (t1, length_ p .- t2) p clippathend <- vardef2 "clippathend" SPath SPicture $ \p a -> do t2 <- bindSnd_ $ bbox_ a `IntersectionTimes` reverse_ p return $ subpath_ (L 0, length_ p .- t2) p z <- traverse bind_ positions q <- itraverse (\k -> bind_ . TheLabel ("\\mathit{" ++ okName k ++ "}")) z ifor_ q $ \k pic -> when (isRe k) $ draw_ pic let path a b = P $ z ^. rix a .... z ^. rix b let arrow a b = drawarrow_ $ clippath (path a b) (q ^. rix a) (q ^. rix b) arrow Tag_Iso Tag_Lens arrow Tag_Iso Tag_Prism arrow Tag_Iso Tag_ReversedLens arrow Tag_Iso Tag_ReversedPrism arrow Tag_ReversedLens Tag_Review arrow Tag_Prism Tag_Review arrow Tag_Lens Tag_Getter arrow Tag_ReversedPrism Tag_Getter red <- bind_ $ RGB (L 0.5) (L 0) (L 0) getterReview <- bind_ $ P $ (z ^. rix Tag_Getter, L 160) .... (z ^. rix Tag_Review) getterReview1 <- bind_ $ subpath_ (L 0.5 .* length_ getterReview, length_ getterReview) getterReview getterReview2 <- bind_ $ reverse_ $ subpath_ (L 0, L 0.5 .* length_ getterReview) getterReview drawarrowC_ red $ clippathend getterReview1 (q ^. rix Tag_Review) drawarrowC_ red $ clippathend getterReview2 (q ^. rix Tag_Getter) prismReview <- bind_ $ path Tag_Prism Tag_Review lensGetter <- bind_ $ path Tag_Lens Tag_Getter prismReversedPrism <- bind_ $ P $ (z ^. rix Tag_ReversedPrism, L 168) .... (z ^. rix Tag_Prism) lensReversedLens <- bind_ $ P $ (z ^. rix Tag_Lens, L 168) .... (z ^. rix Tag_ReversedLens) it1 <- bindSnd_ $ lensGetter `IntersectionTimes` prismReversedPrism ip1 <- bind_ $ lensGetter `IntersectionPoint` prismReversedPrism ic1 <- bind_ $ Circle (L 2) ip1 it2 <- bindSnd_ $ prismReversedPrism `IntersectionTimes` lensReversedLens ip2 <- bind_ $ prismReversedPrism `IntersectionPoint` lensReversedLens ic2 <- bind_ $ Circle (L 8) ip2 it3 <- bindSnd_ $ prismReview `IntersectionTimes` lensReversedLens ip3 <- bind_ $ prismReview `IntersectionPoint` lensReversedLens ic3 <- bind_ $ Circle (L 2) ip3 drawarrowC_ red $ clippath' (subpath_ (L 0, it1) prismReversedPrism) ic1 (bbox_ $ q ^. rix Tag_ReversedPrism) drawarrowC_ red $ reverse_ $ clippath' (subpath_ (it1, length_ prismReversedPrism) prismReversedPrism) (bbox_ $ q ^. rix Tag_Prism) ic1 drawarrowC_ red $ clippath' (subpath_ (it3, length_ lensReversedLens) lensReversedLens) ic3 (bbox_ $ q ^. rix Tag_ReversedLens) drawC_ red $ clippath' (subpath_ (it3, it2) lensReversedLens) ic3 ic2 drawarrowC_ red $ reverse_ $ clippath' (subpath_ (L 0, it2) lensReversedLens) (bbox_ $ q ^. rix Tag_Lens) ic2 drawarrowC_ red $ P $ (z ^. rix Tag_Iso .+ Pair 5 5, L 80) ... (z ^. rix Tag_Iso .+ Pair 20 0, L 270) .... (z ^. rix Tag_Iso .+ Pair 5 (-5), L 100) where isRe Tag_Iso = True isRe Tag_Lens = True isRe Tag_Prism = True isRe Tag_ReversedLens = True isRe Tag_ReversedPrism = True isRe Tag_Getter = True isRe Tag_Review = True isRe _ = False
8a858f73a3f6f244bc85c18d4ff0d6622eed9efecd33421761e695da9a7a0e88
mu-chaco/ReWire
CaseInsertion.hs
# OPTIONS_GHC -fwarn - incomplete - patterns # module ReWire.Core.Transformations.CaseInsertion where import ReWire.Core.Syntax import ReWire.Core.Transformations.Types import ReWire.Core.Transformations.Monad import Control.Monad import Unbound.LocallyNameless --ciAlt = undefined data Decon = WillDecon | WillMatch | WontDecon deriving Show patDecon :: RWCPat -> RWCExp -> Name RWCExp -> RW Decon patDecon (RWCPatCon i _) (RWCCon i doesDeconstr : : RWCExp - > Name RWCExp - > RW Bool doesDeconstr ( RWCApp t e1 _ ) x = doesDeconstr e1 x -- FIXME : not too sure about this case . Is e2 really irrelevant ? doesDeconstr ( RWCLam t b ) x ( \(_,e ) - > doesDeconstr e x ) doesDeconstr ( RWCVar t n ) x = return False doesDeconstr ( RWCCon t i ) x = return False doesDeconstr ( RWCLiteral t l ) x = return False doesDeconstr :: RWCExp -> Name RWCExp -> RW Bool doesDeconstr (RWCApp t e1 _) x = doesDeconstr e1 x -- FIXME: not too sure about this case. Is e2 really irrelevant? doesDeconstr (RWCLam t b) x = lunbind b (\(_,e) -> doesDeconstr e x) doesDeconstr (RWCVar t n) x = return False doesDeconstr (RWCCon t i) x = return False doesDeconstr (RWCLiteral t l) x = return False-} doesDeconstr ( RWCCase t e alts ) x = doCI : : Name RWCExp - > RWCTy - > RWCExp - > RW RWCExp doCI x tx e = do dd < - doesDeconstr e x ciExp : : RWCExp - > RW RWCExp ciExp ( RWCApp t e1 e2 ) = liftM2 ( RWCApp t ) ( ciExp e1 ) ( ciExp e2 ) ciExp ( RWCLam t b ) = b ( \(x , e ) - > do let arrowLeft t e ' e '' < - doCI x tx e ' return ( RWCLam t ( bind x e '' ) ) ) ciExp ( RWCVar t n ) = return ( RWCVar t n ) ciExp ( RWCCon t i ) = return ( RWCCon t i ) ciExp ( RWCLiteral t l ) = return ( RWCLiteral t l ) ciExp ( RWCCase t e alts ) = do e ' < - ciExp e alts ' < - mapM ( ciAlt ( typeOf e ) ) alts return ( RWCCase t e ' alts ' ) doCI :: Name RWCExp -> RWCTy -> RWCExp -> RW RWCExp doCI x tx e = do dd <- doesDeconstr e x ciExp :: RWCExp -> RW RWCExp ciExp (RWCApp t e1 e2) = liftM2 (RWCApp t) (ciExp e1) (ciExp e2) ciExp (RWCLam t b) = lunbind b (\(x,e) -> do let tx = arrowLeft t e' <- ciExp e e'' <- doCI x tx e' return (RWCLam t (bind x e''))) ciExp (RWCVar t n) = return (RWCVar t n) ciExp (RWCCon t i) = return (RWCCon t i) ciExp (RWCLiteral t l) = return (RWCLiteral t l) ciExp (RWCCase t e alts) = do e' <- ciExp e alts' <- mapM (ciAlt (typeOf e)) alts return (RWCCase t e' alts')-}
null
https://raw.githubusercontent.com/mu-chaco/ReWire/a8dcea6ab0989474988a758179a1d876e2c32370/cruft/CaseInsertion.hs
haskell
ciAlt = undefined FIXME : not too sure about this case . Is e2 really irrelevant ? FIXME: not too sure about this case. Is e2 really irrelevant?
# OPTIONS_GHC -fwarn - incomplete - patterns # module ReWire.Core.Transformations.CaseInsertion where import ReWire.Core.Syntax import ReWire.Core.Transformations.Types import ReWire.Core.Transformations.Monad import Control.Monad import Unbound.LocallyNameless data Decon = WillDecon | WillMatch | WontDecon deriving Show patDecon :: RWCPat -> RWCExp -> Name RWCExp -> RW Decon patDecon (RWCPatCon i _) (RWCCon i doesDeconstr : : RWCExp - > Name RWCExp - > RW Bool doesDeconstr ( RWCLam t b ) x ( \(_,e ) - > doesDeconstr e x ) doesDeconstr ( RWCVar t n ) x = return False doesDeconstr ( RWCCon t i ) x = return False doesDeconstr ( RWCLiteral t l ) x = return False doesDeconstr :: RWCExp -> Name RWCExp -> RW Bool doesDeconstr (RWCLam t b) x = lunbind b (\(_,e) -> doesDeconstr e x) doesDeconstr (RWCVar t n) x = return False doesDeconstr (RWCCon t i) x = return False doesDeconstr (RWCLiteral t l) x = return False-} doesDeconstr ( RWCCase t e alts ) x = doCI : : Name RWCExp - > RWCTy - > RWCExp - > RW RWCExp doCI x tx e = do dd < - doesDeconstr e x ciExp : : RWCExp - > RW RWCExp ciExp ( RWCApp t e1 e2 ) = liftM2 ( RWCApp t ) ( ciExp e1 ) ( ciExp e2 ) ciExp ( RWCLam t b ) = b ( \(x , e ) - > do let arrowLeft t e ' e '' < - doCI x tx e ' return ( RWCLam t ( bind x e '' ) ) ) ciExp ( RWCVar t n ) = return ( RWCVar t n ) ciExp ( RWCCon t i ) = return ( RWCCon t i ) ciExp ( RWCLiteral t l ) = return ( RWCLiteral t l ) ciExp ( RWCCase t e alts ) = do e ' < - ciExp e alts ' < - mapM ( ciAlt ( typeOf e ) ) alts return ( RWCCase t e ' alts ' ) doCI :: Name RWCExp -> RWCTy -> RWCExp -> RW RWCExp doCI x tx e = do dd <- doesDeconstr e x ciExp :: RWCExp -> RW RWCExp ciExp (RWCApp t e1 e2) = liftM2 (RWCApp t) (ciExp e1) (ciExp e2) ciExp (RWCLam t b) = lunbind b (\(x,e) -> do let tx = arrowLeft t e' <- ciExp e e'' <- doCI x tx e' return (RWCLam t (bind x e''))) ciExp (RWCVar t n) = return (RWCVar t n) ciExp (RWCCon t i) = return (RWCCon t i) ciExp (RWCLiteral t l) = return (RWCLiteral t l) ciExp (RWCCase t e alts) = do e' <- ciExp e alts' <- mapM (ciAlt (typeOf e)) alts return (RWCCase t e' alts')-}
42b3e4f061cc93b88e86ffdcc7b0155437c5668c4ce82deb99c7ebb6fbedd647
hjcapple/reading-sicp
exercise_5_32.scm
#lang sicp P402 - [ 练习 5.32 - a ] (#%require "ch5-regsim.scm") (#%require "ch5-eceval-support.scm") (define (simple-application? exp) (and (pair? exp) (symbol? (car exp)))) (define eceval-operations (list ;;primitive Scheme operations (list 'read read) ;;operations in syntax.scm (list 'self-evaluating? self-evaluating?) (list 'quoted? quoted?) (list 'text-of-quotation text-of-quotation) (list 'variable? variable?) (list 'assignment? assignment?) (list 'assignment-variable assignment-variable) (list 'assignment-value assignment-value) (list 'definition? definition?) (list 'definition-variable definition-variable) (list 'definition-value definition-value) (list 'lambda? lambda?) (list 'lambda-parameters lambda-parameters) (list 'lambda-body lambda-body) (list 'if? if?) (list 'if-predicate if-predicate) (list 'if-consequent if-consequent) (list 'if-alternative if-alternative) (list 'begin? begin?) (list 'begin-actions begin-actions) (list 'last-exp? last-exp?) (list 'first-exp first-exp) (list 'rest-exps rest-exps) (list 'application? application?) 练习 5.32 - a (list 'simple-application? simple-application?) (list 'operator operator) (list 'operands operands) (list 'no-operands? no-operands?) (list 'first-operand first-operand) (list 'rest-operands rest-operands) ;;operations in eceval-support.scm (list 'true? true?) (list 'make-procedure make-procedure) (list 'compound-procedure? compound-procedure?) (list 'procedure-parameters procedure-parameters) (list 'procedure-body procedure-body) (list 'procedure-environment procedure-environment) (list 'extend-environment extend-environment) (list 'lookup-variable-value lookup-variable-value) (list 'set-variable-value! set-variable-value!) (list 'define-variable! define-variable!) (list 'primitive-procedure? primitive-procedure?) (list 'apply-primitive-procedure apply-primitive-procedure) (list 'prompt-for-input prompt-for-input) (list 'announce-output announce-output) (list 'user-print user-print) (list 'empty-arglist empty-arglist) (list 'adjoin-arg adjoin-arg) (list 'last-operand? last-operand?) (list 'no-more-exps? no-more-exps?) ;for non-tail-recursive machine (list 'get-global-environment get-global-environment)) ) (define eceval (make-machine '(exp env val proc argl continue unev) eceval-operations '( ;;SECTION 5.4.4 read-eval-print-loop (perform (op initialize-stack)) (perform (op prompt-for-input) (const ";;; EC-Eval input:")) (assign exp (op read)) (assign env (op get-global-environment)) (assign continue (label print-result)) (goto (label eval-dispatch)) print-result ;;**following instruction optional -- if use it, need monitored stack (perform (op print-stack-statistics)) (perform (op announce-output) (const ";;; EC-Eval value:")) (perform (op user-print) (reg val)) (goto (label read-eval-print-loop)) unknown-expression-type (assign val (const unknown-expression-type-error)) (goto (label signal-error)) unknown-procedure-type (restore continue) (assign val (const unknown-procedure-type-error)) (goto (label signal-error)) signal-error (perform (op user-print) (reg val)) (goto (label read-eval-print-loop)) ;;SECTION 5.4.1 eval-dispatch (test (op self-evaluating?) (reg exp)) (branch (label ev-self-eval)) (test (op variable?) (reg exp)) (branch (label ev-variable)) (test (op quoted?) (reg exp)) (branch (label ev-quoted)) (test (op assignment?) (reg exp)) (branch (label ev-assignment)) (test (op definition?) (reg exp)) (branch (label ev-definition)) (test (op if?) (reg exp)) (branch (label ev-if)) (test (op lambda?) (reg exp)) (branch (label ev-lambda)) (test (op begin?) (reg exp)) (branch (label ev-begin)) 练习 5.32 - a (test (op simple-application?) (reg exp)) (branch (label ev-simple-application)) (test (op application?) (reg exp)) (branch (label ev-application)) (goto (label unknown-expression-type)) ev-self-eval (assign val (reg exp)) (goto (reg continue)) ev-variable (assign val (op lookup-variable-value) (reg exp) (reg env)) (goto (reg continue)) ev-quoted (assign val (op text-of-quotation) (reg exp)) (goto (reg continue)) ev-lambda (assign unev (op lambda-parameters) (reg exp)) (assign exp (op lambda-body) (reg exp)) (assign val (op make-procedure) (reg unev) (reg exp) (reg env)) (goto (reg continue)) 练习 5.32 - a ev-simple-application (save continue) (assign unev (op operands) (reg exp)) (assign proc (op operator) (reg exp)) (assign proc (op lookup-variable-value) (reg proc) (reg env)) (assign argl (op empty-arglist)) (test (op no-operands?) (reg unev)) (branch (label apply-dispatch)) (save proc) (goto (label ev-appl-operand-loop)) ev-application (save continue) (save env) (assign unev (op operands) (reg exp)) (save unev) (assign exp (op operator) (reg exp)) (assign continue (label ev-appl-did-operator)) (goto (label eval-dispatch)) ev-appl-did-operator (restore unev) (restore env) (assign argl (op empty-arglist)) (assign proc (reg val)) (test (op no-operands?) (reg unev)) (branch (label apply-dispatch)) (save proc) ev-appl-operand-loop (save argl) (assign exp (op first-operand) (reg unev)) (test (op last-operand?) (reg unev)) (branch (label ev-appl-last-arg)) (save env) (save unev) (assign continue (label ev-appl-accumulate-arg)) (goto (label eval-dispatch)) ev-appl-accumulate-arg (restore unev) (restore env) (restore argl) (assign argl (op adjoin-arg) (reg val) (reg argl)) (assign unev (op rest-operands) (reg unev)) (goto (label ev-appl-operand-loop)) ev-appl-last-arg (assign continue (label ev-appl-accum-last-arg)) (goto (label eval-dispatch)) ev-appl-accum-last-arg (restore argl) (assign argl (op adjoin-arg) (reg val) (reg argl)) (restore proc) (goto (label apply-dispatch)) apply-dispatch (test (op primitive-procedure?) (reg proc)) (branch (label primitive-apply)) (test (op compound-procedure?) (reg proc)) (branch (label compound-apply)) (goto (label unknown-procedure-type)) primitive-apply (assign val (op apply-primitive-procedure) (reg proc) (reg argl)) (restore continue) (goto (reg continue)) compound-apply (assign unev (op procedure-parameters) (reg proc)) (assign env (op procedure-environment) (reg proc)) (assign env (op extend-environment) (reg unev) (reg argl) (reg env)) (assign unev (op procedure-body) (reg proc)) (goto (label ev-sequence)) ;;;SECTION 5.4.2 ev-begin (assign unev (op begin-actions) (reg exp)) (save continue) (goto (label ev-sequence)) ev-sequence (assign exp (op first-exp) (reg unev)) (test (op last-exp?) (reg unev)) (branch (label ev-sequence-last-exp)) (save unev) (save env) (assign continue (label ev-sequence-continue)) (goto (label eval-dispatch)) ev-sequence-continue (restore env) (restore unev) (assign unev (op rest-exps) (reg unev)) (goto (label ev-sequence)) ev-sequence-last-exp (restore continue) (goto (label eval-dispatch)) ;;;SECTION 5.4.3 ev-if (save exp) (save env) (save continue) (assign continue (label ev-if-decide)) (assign exp (op if-predicate) (reg exp)) (goto (label eval-dispatch)) ev-if-decide (restore continue) (restore env) (restore exp) (test (op true?) (reg val)) (branch (label ev-if-consequent)) ev-if-alternative (assign exp (op if-alternative) (reg exp)) (goto (label eval-dispatch)) ev-if-consequent (assign exp (op if-consequent) (reg exp)) (goto (label eval-dispatch)) ev-assignment (assign unev (op assignment-variable) (reg exp)) (save unev) (assign exp (op assignment-value) (reg exp)) (save env) (save continue) (assign continue (label ev-assignment-1)) (goto (label eval-dispatch)) ev-assignment-1 (restore continue) (restore env) (restore unev) (perform (op set-variable-value!) (reg unev) (reg val) (reg env)) (assign val (const ok)) (goto (reg continue)) ev-definition (assign unev (op definition-variable) (reg exp)) (save unev) (assign exp (op definition-value) (reg exp)) (save env) (save continue) (assign continue (label ev-definition-1)) (goto (label eval-dispatch)) ev-definition-1 (restore continue) (restore env) (restore unev) (perform (op define-variable!) (reg unev) (reg val) (reg env)) (assign val (const ok)) (goto (reg continue)) ))) (#%require (only racket module*)) (module* main #f (start eceval) '(EXPLICIT CONTROL EVALUATOR LOADED) )
null
https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_5/exercise_5_32.scm
scheme
primitive Scheme operations operations in syntax.scm operations in eceval-support.scm for non-tail-recursive machine SECTION 5.4.4 **following instruction optional -- if use it, need monitored stack SECTION 5.4.1 SECTION 5.4.2 SECTION 5.4.3
#lang sicp P402 - [ 练习 5.32 - a ] (#%require "ch5-regsim.scm") (#%require "ch5-eceval-support.scm") (define (simple-application? exp) (and (pair? exp) (symbol? (car exp)))) (define eceval-operations (list (list 'read read) (list 'self-evaluating? self-evaluating?) (list 'quoted? quoted?) (list 'text-of-quotation text-of-quotation) (list 'variable? variable?) (list 'assignment? assignment?) (list 'assignment-variable assignment-variable) (list 'assignment-value assignment-value) (list 'definition? definition?) (list 'definition-variable definition-variable) (list 'definition-value definition-value) (list 'lambda? lambda?) (list 'lambda-parameters lambda-parameters) (list 'lambda-body lambda-body) (list 'if? if?) (list 'if-predicate if-predicate) (list 'if-consequent if-consequent) (list 'if-alternative if-alternative) (list 'begin? begin?) (list 'begin-actions begin-actions) (list 'last-exp? last-exp?) (list 'first-exp first-exp) (list 'rest-exps rest-exps) (list 'application? application?) 练习 5.32 - a (list 'simple-application? simple-application?) (list 'operator operator) (list 'operands operands) (list 'no-operands? no-operands?) (list 'first-operand first-operand) (list 'rest-operands rest-operands) (list 'true? true?) (list 'make-procedure make-procedure) (list 'compound-procedure? compound-procedure?) (list 'procedure-parameters procedure-parameters) (list 'procedure-body procedure-body) (list 'procedure-environment procedure-environment) (list 'extend-environment extend-environment) (list 'lookup-variable-value lookup-variable-value) (list 'set-variable-value! set-variable-value!) (list 'define-variable! define-variable!) (list 'primitive-procedure? primitive-procedure?) (list 'apply-primitive-procedure apply-primitive-procedure) (list 'prompt-for-input prompt-for-input) (list 'announce-output announce-output) (list 'user-print user-print) (list 'empty-arglist empty-arglist) (list 'adjoin-arg adjoin-arg) (list 'last-operand? last-operand?) (list 'get-global-environment get-global-environment)) ) (define eceval (make-machine '(exp env val proc argl continue unev) eceval-operations '( read-eval-print-loop (perform (op initialize-stack)) (perform (op prompt-for-input) (const ";;; EC-Eval input:")) (assign exp (op read)) (assign env (op get-global-environment)) (assign continue (label print-result)) (goto (label eval-dispatch)) print-result (perform (op print-stack-statistics)) (perform (op announce-output) (const ";;; EC-Eval value:")) (perform (op user-print) (reg val)) (goto (label read-eval-print-loop)) unknown-expression-type (assign val (const unknown-expression-type-error)) (goto (label signal-error)) unknown-procedure-type (restore continue) (assign val (const unknown-procedure-type-error)) (goto (label signal-error)) signal-error (perform (op user-print) (reg val)) (goto (label read-eval-print-loop)) eval-dispatch (test (op self-evaluating?) (reg exp)) (branch (label ev-self-eval)) (test (op variable?) (reg exp)) (branch (label ev-variable)) (test (op quoted?) (reg exp)) (branch (label ev-quoted)) (test (op assignment?) (reg exp)) (branch (label ev-assignment)) (test (op definition?) (reg exp)) (branch (label ev-definition)) (test (op if?) (reg exp)) (branch (label ev-if)) (test (op lambda?) (reg exp)) (branch (label ev-lambda)) (test (op begin?) (reg exp)) (branch (label ev-begin)) 练习 5.32 - a (test (op simple-application?) (reg exp)) (branch (label ev-simple-application)) (test (op application?) (reg exp)) (branch (label ev-application)) (goto (label unknown-expression-type)) ev-self-eval (assign val (reg exp)) (goto (reg continue)) ev-variable (assign val (op lookup-variable-value) (reg exp) (reg env)) (goto (reg continue)) ev-quoted (assign val (op text-of-quotation) (reg exp)) (goto (reg continue)) ev-lambda (assign unev (op lambda-parameters) (reg exp)) (assign exp (op lambda-body) (reg exp)) (assign val (op make-procedure) (reg unev) (reg exp) (reg env)) (goto (reg continue)) 练习 5.32 - a ev-simple-application (save continue) (assign unev (op operands) (reg exp)) (assign proc (op operator) (reg exp)) (assign proc (op lookup-variable-value) (reg proc) (reg env)) (assign argl (op empty-arglist)) (test (op no-operands?) (reg unev)) (branch (label apply-dispatch)) (save proc) (goto (label ev-appl-operand-loop)) ev-application (save continue) (save env) (assign unev (op operands) (reg exp)) (save unev) (assign exp (op operator) (reg exp)) (assign continue (label ev-appl-did-operator)) (goto (label eval-dispatch)) ev-appl-did-operator (restore unev) (restore env) (assign argl (op empty-arglist)) (assign proc (reg val)) (test (op no-operands?) (reg unev)) (branch (label apply-dispatch)) (save proc) ev-appl-operand-loop (save argl) (assign exp (op first-operand) (reg unev)) (test (op last-operand?) (reg unev)) (branch (label ev-appl-last-arg)) (save env) (save unev) (assign continue (label ev-appl-accumulate-arg)) (goto (label eval-dispatch)) ev-appl-accumulate-arg (restore unev) (restore env) (restore argl) (assign argl (op adjoin-arg) (reg val) (reg argl)) (assign unev (op rest-operands) (reg unev)) (goto (label ev-appl-operand-loop)) ev-appl-last-arg (assign continue (label ev-appl-accum-last-arg)) (goto (label eval-dispatch)) ev-appl-accum-last-arg (restore argl) (assign argl (op adjoin-arg) (reg val) (reg argl)) (restore proc) (goto (label apply-dispatch)) apply-dispatch (test (op primitive-procedure?) (reg proc)) (branch (label primitive-apply)) (test (op compound-procedure?) (reg proc)) (branch (label compound-apply)) (goto (label unknown-procedure-type)) primitive-apply (assign val (op apply-primitive-procedure) (reg proc) (reg argl)) (restore continue) (goto (reg continue)) compound-apply (assign unev (op procedure-parameters) (reg proc)) (assign env (op procedure-environment) (reg proc)) (assign env (op extend-environment) (reg unev) (reg argl) (reg env)) (assign unev (op procedure-body) (reg proc)) (goto (label ev-sequence)) ev-begin (assign unev (op begin-actions) (reg exp)) (save continue) (goto (label ev-sequence)) ev-sequence (assign exp (op first-exp) (reg unev)) (test (op last-exp?) (reg unev)) (branch (label ev-sequence-last-exp)) (save unev) (save env) (assign continue (label ev-sequence-continue)) (goto (label eval-dispatch)) ev-sequence-continue (restore env) (restore unev) (assign unev (op rest-exps) (reg unev)) (goto (label ev-sequence)) ev-sequence-last-exp (restore continue) (goto (label eval-dispatch)) ev-if (save exp) (save env) (save continue) (assign continue (label ev-if-decide)) (assign exp (op if-predicate) (reg exp)) (goto (label eval-dispatch)) ev-if-decide (restore continue) (restore env) (restore exp) (test (op true?) (reg val)) (branch (label ev-if-consequent)) ev-if-alternative (assign exp (op if-alternative) (reg exp)) (goto (label eval-dispatch)) ev-if-consequent (assign exp (op if-consequent) (reg exp)) (goto (label eval-dispatch)) ev-assignment (assign unev (op assignment-variable) (reg exp)) (save unev) (assign exp (op assignment-value) (reg exp)) (save env) (save continue) (assign continue (label ev-assignment-1)) (goto (label eval-dispatch)) ev-assignment-1 (restore continue) (restore env) (restore unev) (perform (op set-variable-value!) (reg unev) (reg val) (reg env)) (assign val (const ok)) (goto (reg continue)) ev-definition (assign unev (op definition-variable) (reg exp)) (save unev) (assign exp (op definition-value) (reg exp)) (save env) (save continue) (assign continue (label ev-definition-1)) (goto (label eval-dispatch)) ev-definition-1 (restore continue) (restore env) (restore unev) (perform (op define-variable!) (reg unev) (reg val) (reg env)) (assign val (const ok)) (goto (reg continue)) ))) (#%require (only racket module*)) (module* main #f (start eceval) '(EXPLICIT CONTROL EVALUATOR LOADED) )
7753b0f54bd763be1edb2af22a31436b4643c242809e581ee3d3314487fffb61
OCamlPro/techelson
bigArith.ml
open Base open Common (* Factors Int/Nat stuff. *) module BigInt = struct type t = Z.t let fmt = Z.pp_print let to_string = Z.to_string let of_string = Z.of_string let of_native = Z.of_int let to_native = Z.to_int let add = Z.add let mul = Z.mul let div = Z.div let compare = Z.compare let zero = Z.zero end module BInt = struct include BigInt let sub = Z.sub end module BNat = struct include BigInt let fmt fmt n = fprintf fmt "%ap" Z.pp_print n let of_string (s : string) : t = let nat = Z.of_string s in if Z.geq nat Z.zero then nat else sprintf "illegal string for `Nat.of_string \"%s\"`" s |> Exc.throw let of_native (n : int) : t = let nat = Z.of_int n in if Z.geq nat Z.zero then nat else sprintf "illegal int for `Nat.of_native \"%i\"`" n |> Exc.throw let lshift_lft (n : t) (shift : t) : t = to_native shift |> Z.shift_left n let lshift_rgt (n : t) (shift : t) : t = to_native shift |> Z.shift_right n let xor = Z.logxor let conj = Z.logand let disj = Z.logor end module BNatConv = struct type int = BInt.t type nat = BNat.t let int_to_nat (n : int) : nat option = if Z.geq n Z.zero then Some n else None let nat_to_int (n : nat) : int = n let nat_sub (n_1 : nat) (n_2 : nat) : int = Z.sub n_1 n_2 let int_abs (i_1 : int) : nat = Z.abs i_1 let ediv (i_1 : int) (i_2 : int) : (int * nat) option = if Z.equal i_2 Z.zero then None else ( try ( let q, r = Z.div_rem i_1 i_2 in let q, r = if Z.lt r Z.zero && Z.geq q Z.zero then ( Z.add q Z.one, Z.sub r i_2 ) else if Z.lt r Z.zero && Z.lt q Z.zero then ( Z.sub q Z.one, Z.add r i_2 ) else ( q, r ) in Some (q, r) ) with | Division_by_zero -> None ) let int_nat_conj (i_1 : int) (n_2 : nat) : nat = Z.logand i_1 n_2 end module NaiveStrConv = struct type str = Naive.Str.t type nat = BNat.t type int = BInt.t let size (str : str) : nat = String.length str |> BNat.of_native let slice (start : nat) (len : nat) (str : str) : str option = let slice_len = BNat.add start len in let string_len = size str in if BNat.compare slice_len string_len > 0 then None else Some (String.sub str (BNat.to_native start) (BNat.to_native len)) let compare (s_1 : str) (s_2 : str) : int = String.compare s_1 s_2 |> BNat.of_native end module NaiveTStampConv = struct type t_stamp = Naive.TStamp.t type int = BInt.t let int_to_tstamp (i : int) : t_stamp = (BInt.to_native i) * 100 let add (t : t_stamp) (i : int) : t_stamp = let i = BInt.to_native i in t + (i * 100) let sub_int (t : t_stamp) (i : int) : t_stamp = let i = BInt.to_native i in t - (i * 100) let sub (t_1 : t_stamp) (t_2 : t_stamp) : int = t_1 - t_2 |> BInt.of_native end module BTStamp = struct type t = BInt.t let epoch : t = BInt.zero let to_string (t : t) : string = BInt.to_string t let of_native (s : string) : t = BInt.of_string s let compare (t_1 : t) (t_2 : t) : int = BInt.compare t_1 t_2 let fmt (fmt : formatter) (t : t) : unit = BInt.fmt fmt t end module PTStamp = struct type t = Ptime.t let epoch : t = Ptime.epoch let to_string (t : t) : string = asprintf "%a" Ptime.pp t let of_native (s : string) : t = match Ptime.of_rfc3339 ~strict:false ~start:0 ~sub:false s with | Result.Ok (t, _, _) -> t | Result.Error (`RFC3339 (_, e)) -> Exc.throws [ asprintf "%a" Ptime.pp_rfc3339_error e ; sprintf "while parsing timestamp `%s`" s ; ] let compare (t_1 : t) (t_2 : t) : int = Ptime.compare t_1 t_2 let fmt (fmt : formatter) (t : t) : unit = Ptime.pp fmt t end module BTStampConv = struct type t_stamp = BTStamp.t type int = BInt.t let int_to_tstamp (i : int) : t_stamp = i let add (t : t_stamp) (i : int) : t_stamp = BInt.add t i let sub_int (t : t_stamp) (i : int) : t_stamp = BInt.sub t i let sub (t_1 : t_stamp) (t_2 : t_stamp) : int = BInt.sub t_1 t_2 end module PTStampConv = struct type t_stamp = PTStamp.t type int = BInt.t let int_to_tstamp (i : int) : t_stamp = let span = Z.to_float i |> Ptime.Span.of_float_s in match span |> Opt.and_then (PTStamp.epoch |> Ptime.add_span) with | Some res -> res | None -> asprintf "failed to convert integer %a to timestamp" BInt.fmt i |> Exc.throw let add (t : t_stamp) (i : int) : t_stamp = let span = BInt.to_native i |> Ptime.Span.of_int_s in match Ptime.add_span PTStamp.epoch span with | Some res -> res | None -> asprintf "failed to add %a seconds to timestamp %a" BInt.fmt i PTStamp.fmt t |> Exc.throw let sub_int (t : t_stamp) (i : int) : t_stamp = let span = BInt.to_native i |> Ptime.Span.of_int_s in match Ptime.sub_span PTStamp.epoch span with | Some res -> res | None -> asprintf "failed to sub %a seconds to timestamp %a" BInt.fmt i PTStamp.fmt t |> Exc.throw let sub (t_1 : t_stamp) (t_2 : t_stamp) : int = match Ptime.diff t_1 t_2 |> Ptime.Span.to_int_s with | Some res -> BInt.of_native res | None -> asprintf "failed to sub %a to %a" PTStamp.fmt t_1 PTStamp.fmt t_2 |> Exc.throw end module BigNaivePrimitive = struct module Int = BInt module Nat = BNat module NatConv = BNatConv module Str = Naive.Str module StrConv = NaiveStrConv module Bytes = Naive.Bytes module BytesConv = NaiveStrConv module TStamp = PTStamp module TStampConv = PTStampConv module Key = Naive.Key module KeyH = Naive.KeyH module KeyHConv = Naive.KeyHConv module Address = Naive.Address end module Theory = Make.Theory (BigNaivePrimitive)
null
https://raw.githubusercontent.com/OCamlPro/techelson/932fbf08675cd13d34a07e3b3d77234bdafcf5bc/src/4_theory/bigArith.ml
ocaml
Factors Int/Nat stuff.
open Base open Common module BigInt = struct type t = Z.t let fmt = Z.pp_print let to_string = Z.to_string let of_string = Z.of_string let of_native = Z.of_int let to_native = Z.to_int let add = Z.add let mul = Z.mul let div = Z.div let compare = Z.compare let zero = Z.zero end module BInt = struct include BigInt let sub = Z.sub end module BNat = struct include BigInt let fmt fmt n = fprintf fmt "%ap" Z.pp_print n let of_string (s : string) : t = let nat = Z.of_string s in if Z.geq nat Z.zero then nat else sprintf "illegal string for `Nat.of_string \"%s\"`" s |> Exc.throw let of_native (n : int) : t = let nat = Z.of_int n in if Z.geq nat Z.zero then nat else sprintf "illegal int for `Nat.of_native \"%i\"`" n |> Exc.throw let lshift_lft (n : t) (shift : t) : t = to_native shift |> Z.shift_left n let lshift_rgt (n : t) (shift : t) : t = to_native shift |> Z.shift_right n let xor = Z.logxor let conj = Z.logand let disj = Z.logor end module BNatConv = struct type int = BInt.t type nat = BNat.t let int_to_nat (n : int) : nat option = if Z.geq n Z.zero then Some n else None let nat_to_int (n : nat) : int = n let nat_sub (n_1 : nat) (n_2 : nat) : int = Z.sub n_1 n_2 let int_abs (i_1 : int) : nat = Z.abs i_1 let ediv (i_1 : int) (i_2 : int) : (int * nat) option = if Z.equal i_2 Z.zero then None else ( try ( let q, r = Z.div_rem i_1 i_2 in let q, r = if Z.lt r Z.zero && Z.geq q Z.zero then ( Z.add q Z.one, Z.sub r i_2 ) else if Z.lt r Z.zero && Z.lt q Z.zero then ( Z.sub q Z.one, Z.add r i_2 ) else ( q, r ) in Some (q, r) ) with | Division_by_zero -> None ) let int_nat_conj (i_1 : int) (n_2 : nat) : nat = Z.logand i_1 n_2 end module NaiveStrConv = struct type str = Naive.Str.t type nat = BNat.t type int = BInt.t let size (str : str) : nat = String.length str |> BNat.of_native let slice (start : nat) (len : nat) (str : str) : str option = let slice_len = BNat.add start len in let string_len = size str in if BNat.compare slice_len string_len > 0 then None else Some (String.sub str (BNat.to_native start) (BNat.to_native len)) let compare (s_1 : str) (s_2 : str) : int = String.compare s_1 s_2 |> BNat.of_native end module NaiveTStampConv = struct type t_stamp = Naive.TStamp.t type int = BInt.t let int_to_tstamp (i : int) : t_stamp = (BInt.to_native i) * 100 let add (t : t_stamp) (i : int) : t_stamp = let i = BInt.to_native i in t + (i * 100) let sub_int (t : t_stamp) (i : int) : t_stamp = let i = BInt.to_native i in t - (i * 100) let sub (t_1 : t_stamp) (t_2 : t_stamp) : int = t_1 - t_2 |> BInt.of_native end module BTStamp = struct type t = BInt.t let epoch : t = BInt.zero let to_string (t : t) : string = BInt.to_string t let of_native (s : string) : t = BInt.of_string s let compare (t_1 : t) (t_2 : t) : int = BInt.compare t_1 t_2 let fmt (fmt : formatter) (t : t) : unit = BInt.fmt fmt t end module PTStamp = struct type t = Ptime.t let epoch : t = Ptime.epoch let to_string (t : t) : string = asprintf "%a" Ptime.pp t let of_native (s : string) : t = match Ptime.of_rfc3339 ~strict:false ~start:0 ~sub:false s with | Result.Ok (t, _, _) -> t | Result.Error (`RFC3339 (_, e)) -> Exc.throws [ asprintf "%a" Ptime.pp_rfc3339_error e ; sprintf "while parsing timestamp `%s`" s ; ] let compare (t_1 : t) (t_2 : t) : int = Ptime.compare t_1 t_2 let fmt (fmt : formatter) (t : t) : unit = Ptime.pp fmt t end module BTStampConv = struct type t_stamp = BTStamp.t type int = BInt.t let int_to_tstamp (i : int) : t_stamp = i let add (t : t_stamp) (i : int) : t_stamp = BInt.add t i let sub_int (t : t_stamp) (i : int) : t_stamp = BInt.sub t i let sub (t_1 : t_stamp) (t_2 : t_stamp) : int = BInt.sub t_1 t_2 end module PTStampConv = struct type t_stamp = PTStamp.t type int = BInt.t let int_to_tstamp (i : int) : t_stamp = let span = Z.to_float i |> Ptime.Span.of_float_s in match span |> Opt.and_then (PTStamp.epoch |> Ptime.add_span) with | Some res -> res | None -> asprintf "failed to convert integer %a to timestamp" BInt.fmt i |> Exc.throw let add (t : t_stamp) (i : int) : t_stamp = let span = BInt.to_native i |> Ptime.Span.of_int_s in match Ptime.add_span PTStamp.epoch span with | Some res -> res | None -> asprintf "failed to add %a seconds to timestamp %a" BInt.fmt i PTStamp.fmt t |> Exc.throw let sub_int (t : t_stamp) (i : int) : t_stamp = let span = BInt.to_native i |> Ptime.Span.of_int_s in match Ptime.sub_span PTStamp.epoch span with | Some res -> res | None -> asprintf "failed to sub %a seconds to timestamp %a" BInt.fmt i PTStamp.fmt t |> Exc.throw let sub (t_1 : t_stamp) (t_2 : t_stamp) : int = match Ptime.diff t_1 t_2 |> Ptime.Span.to_int_s with | Some res -> BInt.of_native res | None -> asprintf "failed to sub %a to %a" PTStamp.fmt t_1 PTStamp.fmt t_2 |> Exc.throw end module BigNaivePrimitive = struct module Int = BInt module Nat = BNat module NatConv = BNatConv module Str = Naive.Str module StrConv = NaiveStrConv module Bytes = Naive.Bytes module BytesConv = NaiveStrConv module TStamp = PTStamp module TStampConv = PTStampConv module Key = Naive.Key module KeyH = Naive.KeyH module KeyHConv = Naive.KeyHConv module Address = Naive.Address end module Theory = Make.Theory (BigNaivePrimitive)
75ee8dbfcc7d7aa12614fda747253c0c0a2eb6bbc4e3995416247716bba39f51
Workiva/eva
core.clj
Copyright 2015 - 2019 Workiva Inc. ;; ;; Licensed under the Eclipse Public License 1.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -1.0.php ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns eva.v2.messaging.jms.beta.core (:require [clojure.spec.alpha :as s]) (:import (java.time Instant) (javax.jms Destination Session MessageProducer Topic Queue Connection ConnectionFactory DeliveryMode BytesMessage Message MessageConsumer MessageListener))) ;;;;;;;;;; SPEC ; ; ;;;;;;;;;; (s/def ::delivery-mode-value #{DeliveryMode/PERSISTENT DeliveryMode/NON_PERSISTENT}) (s/def ::delivery-mode-keyword #{:persistent :non-persistent}) (s/def ::delivery-mode (s/or :name ::delivery-mode-keyword :value ::delivery-mode-value)) (defn delivery-mode-keyword "Coerces a valid delivery-mode value to the human readable keywords: - :persistent - :non-persistent If passed, these keywords are returned unchanged. Any other value will result in an IllegalArgumentException." [mode] (condp = mode DeliveryMode/PERSISTENT :persistent DeliveryMode/NON_PERSISTENT :non-persistent :persistent :persistent :non-persistent :non-persistent)) (s/fdef delivery-mode-keyword :args (s/cat :mode ::delivery-mode) :ret ::delivery-mode-keyword) (defn ^Integer delivery-mode-value "Coerces a representation of a delivery mode to the integer value recognized by JMS. Valid keyword inputs are: - :persistent - :non-persistent If a valid integer value is passed, it will be returned unchanged. Invalid integer values will throw an IllegalArgumentException. Any other value will result in an IllegalArgumentException." [mode] (condp = mode DeliveryMode/PERSISTENT DeliveryMode/PERSISTENT DeliveryMode/NON_PERSISTENT DeliveryMode/NON_PERSISTENT :persistent DeliveryMode/PERSISTENT :non-persistent DeliveryMode/NON_PERSISTENT)) (s/fdef delivery-mode-value :args (s/cat :mode ::delivery-mode) :ret ::delivery-mode-value) (s/def ::acknowledge-mode-value #{Session/AUTO_ACKNOWLEDGE Session/CLIENT_ACKNOWLEDGE Session/DUPS_OK_ACKNOWLEDGE}) (s/def ::acknowledge-mode-keyword #{:auto :client :dups-ok}) (s/def ::acknowledge-mode (s/or :name ::acknowledge-mode-keyword :value ::acknowledge-mode-value)) (defn acknowledge-mode-keyword "Coerces a valid acknowledge-mode value to the human-readable keywords: - :auto - :client - :dups-ok If any of these keywords are passed, they will be returned unchanged. Any other value will result in an IllegalArgumentException." [mode] (condp contains? mode #{:auto Session/AUTO_ACKNOWLEDGE} :auto #{:client Session/CLIENT_ACKNOWLEDGE} :client #{:dups-ok Session/DUPS_OK_ACKNOWLEDGE} :dups-ok (throw (IllegalArgumentException. (str "invalid acknowledge-mode: " mode ";" "must be one of: " ":auto, :client, :dups-ok, " "java.jms.Session/AUTO_ACKNOWLEDGE, " "java.jms.Session/CLIENT_ACKNOWLEDGE, " "or java.jms.Session/DUPS_OK_ACKNOWLEDGE"))))) (s/fdef acknowledge-mode-keyword :args (s/cat :mode ::acknowledge-mode) :ret ::acknowledge-mode-keyword) (defn acknowledge-mode-value "Coerces the value to a JMS acknowledge-mode integer value. If a valid acknowledge-mode integer value is passed, it will be returned unchanged. The following keywords are also accepted: - :auto -> javax.jms.Session/AUTO_ACKNOWLEDGE - :client -> javax.jms.Session/CLIENT_ACKNOWLEDGE - :dups-ok -> javax.jms.Session/DUPS_OK_ACKNOWLEDGE Any other value will result in an IllegalArgumentException." [mode] (condp contains? mode #{:auto Session/AUTO_ACKNOWLEDGE} Session/AUTO_ACKNOWLEDGE #{:client Session/CLIENT_ACKNOWLEDGE} Session/CLIENT_ACKNOWLEDGE #{:dups-ok Session/DUPS_OK_ACKNOWLEDGE} Session/DUPS_OK_ACKNOWLEDGE (throw (IllegalArgumentException. (str "invalid acknowledge-mode: " mode ";" "must be one of: " ":auto, :client, :dups-ok, " "java.jms.Session/AUTO_ACKNOWLEDGE, " "java.jms.Session/CLIENT_ACKNOWLEDGE, " "or java.jms.Session/DUPS_OK_ACKNOWLEDGE"))))) (s/fdef acknowledge-mode-value :args (s/cat :mode ::acknowledge-mode) :ret ::acknowledge-mode-value) (defn connection-factory? "Predicate that tests if the argument is a javax.jms.ConnectionFactory" [cf] (instance? ConnectionFactory cf)) (s/def ::connection-factory connection-factory?) (defn connection? "Predicate that tests if the argument is a javax.jms.Connection" [c] (instance? Connection c)) (s/def ::connection connection?) (s/def ::connection-opts (s/keys :opt-un [::start? ::user ::password])) (s/def ::start? boolean?) (s/def ::user string?) (s/def ::password string?) (defn ^Connection create-connection "Produces a javax.jms.Connection from a javax.jms.ConnectionFactory" ([^ConnectionFactory cf] (create-connection cf {})) ([^ConnectionFactory cf {:as opts :keys [start? user password] :or {start? false}}] (cond (and user password) :ok user (throw (IllegalArgumentException. (str "Incomplete connection options: provided :user but missing :password"))) password (throw (IllegalArgumentException. (str "Incomplete connection options: provided :password missing :user")))) (let [c (if user (.createConnection cf user password) (.createConnection cf))] (when start? (.start c)) c))) (s/fdef create-connection :args (s/cat :cf connection-factory? :opts (s/? ::connection-opts)) :ret connection?) (defn session? "Predicate that tests if the argument is a javax.jms.Session" [s] (instance? Session s)) (s/def ::session-opts (s/keys :opt-un [::transacted? ::acknowledge-mode])) (s/def ::transacted? boolean?) (defn ^Session create-session "Produces a javax.jms.Session on a javax.jms.Connection. Accepts an optional, options map that can specify: - whether the session is transactional - the session's acknowledge-mode Defaults to creating a non-transactional session with :auto acknowledge-mode." ([^Connection c] (create-session c {})) ([^Connection c {transacted? :transacted? ack-mode :acknowledge-mode :or {transacted? false ack-mode :auto}}] (.createSession c transacted? (acknowledge-mode-value ack-mode)))) (s/fdef create-session :args (s/cat :c connection? :opts (s/? ::session-opts)) :ret session?) (defn session-options "Given a javax.jms.Session, returns a map of the options used to create/configure that session. The resulting option map is valid to pass to create-session." [^Session session] {:transacted? (.getTransacted session) :acknowledge-mode (condp = (.getAcknowledgeMode session) Session/AUTO_ACKNOWLEDGE :auto Session/CLIENT_ACKNOWLEDGE :client Session/DUPS_OK_ACKNOWLEDGE :dups-ok)}) (s/fdef session-options :args (s/cat :session session?) :ret ::session-opts) (defn destination? "Predicate that tests if the value is a javax.jms.Destination" [dest] (instance? Destination dest)) (defn queue? "Predicate that tests if the value is a javax.jms.Queue" [dest] (instance? Queue dest)) (defn topic? "Predicate that tests if the value is a javax.jms.Topic" [dest] (instance? Topic dest)) (s/def ::destination destination?) (defn ^Queue queue "Given a Session s, and a Queue identity string q, returns a javax.jms.Queue instance for the identified Queue. If q is already an instance of javax.jms.Queue, then it is returned unchanged. Any other value for q will result in an IllegalArgumentException." [^Session s q] (cond (instance? Queue q) q (string? q) (.createQueue s ^String q) :else (throw (IllegalArgumentException. "expected Queue or string")))) (s/fdef queue :args (s/cat :s session? :q (s/alt :queue-name string? :queue-inst queue?)) :ret queue?) (defn ^Topic topic "Given a Session s, and a Topic identity string t, returns a javax.jms.Topic instance for the identified Topic. If t is already an instance of javax.jms.Topic, then it is returned unchanged. Any other value for t will result in an IllegalArgumentException." [^Session s t] (cond (instance? Topic t) t (string? t) (.createTopic s ^String t) :else (throw (IllegalArgumentException. "expected Topic or string")))) (s/fdef topic :args (s/cat :s session? :t (s/alt :topic-name string? :topic-inst topic?)) :ret topic?) (defn destination-name "Returns the string name of a Queue or Topic." [d] (condp instance? d Queue (.getQueueName ^Queue d) Topic (.getTopicName ^Topic d))) (s/fdef destination-name :args (s/cat :d destination?) :ret string?) (defn message-producer? "Predicate that tests if p is a javax.jms.MessageProducer." [p] (instance? MessageProducer p)) (s/def ::message-producer-opts (s/keys :opt-un [::delivery-mode ::message-ttl])) (s/def ::message-ttl pos-int?) (defn message-producer "Creates a javax.jms.MessageProducer on Session s that will send messages to Destination d. May optionally pass a map of {:delivery-mode dm, :message-ttl ttl} to configure the default delivery-mode and time-to-live for messages sent by the MessageProducer." ([^Session s ^Destination d] (message-producer s d {})) ([^Session s ^Destination d {dm :delivery-mode ttl :message-ttl}] (let [^MessageProducer p (.createProducer s d)] (when dm (.setDeliveryMode p (delivery-mode-value dm))) (when ttl (when-not (integer? ttl) (throw (IllegalArgumentException. "message-expiration must be an integer"))) (.setTimeToLive p ttl)) p))) (s/fdef message-producer :args (s/cat :s session? :d destination? :opts (s/? ::message-producer-opts)) :ret message-producer?) (defn message? "Predicate that tests if m is an instance of javax.jms.Message." [m] (instance? Message m)) (defn send-message! "Sends a Message m via MessageProducer p. The single arity call is a no-op that allow send-message! to be used in a reducing or transducing context." ([^MessageProducer p] p) ;; no-op completing form ([^MessageProducer p ^Message m] (.send p m) p) ([^MessageProducer p ^Destination d ^Message m] (.send p d m) p)) (s/fdef send-message! :args (s/alt :completing (s/cat :p message-producer?) :producer-dest (s/cat :p message-producer? :m message?) :explicit-dest (s/cat :p message-producer? :d destination? :m message?)) :ret message-producer?) (defn message-consumer? "Predicate that tests if c is a javax.jms.MessageConsumer." [c] (instance? MessageConsumer c)) (s/def ::consume-messages-opts (s/keys :opt-un [::message-selector ::no-local? ::on-message])) (s/def ::consume-message-opts* (s/keys* :opt-un [::message-selector ::no-local? ::on-message])) (s/def ::message-selector string?) (s/def ::no-local? boolean?) (s/def ::on-message fn?) (defn- set-message-listener! [^MessageConsumer consumer on-message] (if (fn? on-message) (->> (reify MessageListener (onMessage [_ msg] (on-message msg))) (.setMessageListener consumer)) (throw (IllegalArgumentException. "on-message must be a function")))) (defn ^MessageConsumer message-consumer "Creates a javax.jms.MessageConsumer on Session s which consumes messages sent to Destination d. Accepts an optional map with the following keys: - :message-selector :: a JMS message selection expression string; - :no-local? :: if true, the consumer will not receive messages that were sent by producers using the same local, connection; - on-message :: a function that will be called asynchronously whenever the consumer receives a message. The function must accept a single-argument which will be the that was message received." ([^Session s ^Destination d] (.createConsumer s d)) ([^Session s ^Destination d & {:keys [message-selector no-local? on-message]}] (let [c (.createConsumer s d message-selector (boolean no-local?))] (when (some? on-message) (set-message-listener! c on-message)) c))) (s/fdef message-consumer :args (s/cat :s session? :d destination? :opts ::consume-message-opts*) :ret message-consumer?) (s/def ::message-id string?) (s/def ::message-type string?) (s/def ::timestamp inst?) (s/def ::expiration inst?) (s/def ::correlation-id string?) (s/def ::reply-to ::destination) (s/def ::priority integer?) (s/def ::redelivered? boolean?) (s/def ::bytes-body bytes?) (s/def ::message-info (s/keys :opt-un [::message-id ::message-type ::timestamp ::expiration ::correlation-id ::destination ::reply-to ::delivery-mode ::priority ::redelivered?])) (defn message-info "Returns a map of the metadata common to all instances of javax.jms.Message. Includes ONLY non-nil entries for: - :message-id from Message#getJMSMessageID() - :message-type from Message#getJMSTypes() - :timestamp Instant derived from Message#getJMSTimeStamp() - :expiration Instant derived from Message#getJMSExpiration - :correlation-id from Message#getJMSCorrelationID - :destination from Message#getJMSDestination - :reply-to from Message#getJMSReplyTo() - :delivery-mode derived from Message#getJMSDeliveryMode() - :priority from Message#getJMSPriority() - :redelivered? from Message#getJMSRedelivered()" [^Message m] (cond-> {} (.getJMSMessageID m) (assoc :message-id (.getJMSMessageID m)) (.getJMSType m) (assoc :message-type (.getJMSType m)) (.getJMSTimestamp m) (assoc :timestamp (Instant/ofEpochMilli (.getJMSTimestamp m))) (.getJMSExpiration m) (assoc :expiration (Instant/ofEpochMilli (.getJMSExpiration m))) (.getJMSCorrelationID m) (assoc :correlation-id (.getJMSCorrelationID m)) (.getJMSDestination m) (assoc :destination (.getJMSDestination m)) (.getJMSReplyTo m) (assoc :reply-to (.getJMSReplyTo m)) (.getJMSDeliveryMode m) (assoc :delivery-mode (delivery-mode-keyword (.getJMSDeliveryMode m))) (.getJMSPriority m) (assoc :priority (.getJMSPriority m)) (.getJMSRedelivered m) (assoc :redelivered? (.getJMSRedelivered m)))) (s/fdef message-info :args (s/cat :m message?) :ret ::message-info) (defmacro ^:private cond-doto [expr & clauses] (assert (even? (count clauses))) (let [ret (gensym)] `(let [~ret ~expr] ~@(map (fn [[pred-expr form]] (with-meta (if (seq? form) `(when ~pred-expr (~(first form) ~ret ~@(next form))) `(when ~pred-expr `(~form ~ret))) (meta form))) (partition 2 clauses)) ~ret))) (comment (macroexpand-1 '(cond-doto (StringBuilder.) true (.append "1") false (.append "2")))) (defn ^Message set-message-info! "Sets common metadata on a Message." [^Message m {:keys [message-id message-type timestamp expiration correlation-id destination reply-to delivery-mode priority redelivered?]}] (cond-doto m message-id (.setJMSMessageID message-id) message-type (.setJMSType message-type) timestamp (.setJMSTimestamp (inst-ms timestamp)) expiration (.setJMSExpiration (inst-ms expiration)) correlation-id (.setJMSCorrelationID correlation-id) destination (.setJMSDestination destination) reply-to (.setJMSReplyTo reply-to) delivery-mode (.setJMSDeliveryMode (delivery-mode-value delivery-mode)) priority (.setJMSPriority priority) redelivered? (.setJMSRedelivered redelivered?))) (s/fdef set-message-info! :args (s/cat :m message? :info ::message-info) :ret message? :fn #(identical? (:ret %) (-> % :args :m))) (defn bytes-message? "Predicate that tests if m is a javax.jms.BytesMessage" [m] (instance? BytesMessage m)) (defn read-bytes "Reads bytes from a javax.jms.BytesMessage. This only works with and mutates byte-arrays Arities: 1. Pass a BytesMessage: returns a byte-array containing the contents of the message. 2. Pass BytesMessage and a byte-array: reads contents of message into the byte-array argument up-to the length of the byte-array; returns the byte-array. 3. Pass BytesMessage, byte-array, and integer length: reads upto 'length' bytes into byte-array from the BytesMessage; returns the byte-array." ([^BytesMessage m] (let [l (.getBodyLength m) arr (byte-array l)] (read-bytes m arr l) arr)) ([^BytesMessage m ^bytes arr] (.readBytes m arr) arr) ([^BytesMessage m ^bytes arr length] (.readBytes m arr length) arr)) (s/fdef read-bytes :args (s/cat :m bytes-message? :out-args (s/? (s/cat :arr bytes? :length (s/? integer?)))) :ret bytes?) (defn write-bytes "Writes the contents of byte-array 'arr' into the body of BytesMessage 'm'. May optionally pass integer 'offset' and 'length' which will write the contents of 'arr[offset]..arr[length-1]' into message 'm'." ([^BytesMessage m ^bytes arr] (.writeBytes m arr) m) ([^BytesMessage m ^bytes arr offset length] (.writeBytes m arr offset length) m)) (s/fdef write-bytes :args (s/cat :m bytes-message? :arr bytes? :offset-length (s/? (s/cat :offset pos-int? :length pos-int?))) :ret bytes-message?) ;;;;;;;;;;;;;; ;; END SPEC ;; ;;;;;;;;;;;;;;
null
https://raw.githubusercontent.com/Workiva/eva/b7b8a6a5215cccb507a92aa67e0168dc777ffeac/core/src/eva/v2/messaging/jms/beta/core.clj
clojure
Licensed under the Eclipse Public License 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -1.0.php Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ; no-op completing form returns the byte-array. returns the byte-array." END SPEC ;;
Copyright 2015 - 2019 Workiva Inc. distributed under the License is distributed on an " AS IS " BASIS , (ns eva.v2.messaging.jms.beta.core (:require [clojure.spec.alpha :as s]) (:import (java.time Instant) (javax.jms Destination Session MessageProducer Topic Queue Connection ConnectionFactory DeliveryMode BytesMessage Message MessageConsumer MessageListener))) (s/def ::delivery-mode-value #{DeliveryMode/PERSISTENT DeliveryMode/NON_PERSISTENT}) (s/def ::delivery-mode-keyword #{:persistent :non-persistent}) (s/def ::delivery-mode (s/or :name ::delivery-mode-keyword :value ::delivery-mode-value)) (defn delivery-mode-keyword "Coerces a valid delivery-mode value to the human readable keywords: - :persistent - :non-persistent If passed, these keywords are returned unchanged. Any other value will result in an IllegalArgumentException." [mode] (condp = mode DeliveryMode/PERSISTENT :persistent DeliveryMode/NON_PERSISTENT :non-persistent :persistent :persistent :non-persistent :non-persistent)) (s/fdef delivery-mode-keyword :args (s/cat :mode ::delivery-mode) :ret ::delivery-mode-keyword) (defn ^Integer delivery-mode-value "Coerces a representation of a delivery mode to the integer value recognized by JMS. Valid keyword inputs are: - :persistent - :non-persistent If a valid integer value is passed, it will be returned unchanged. Invalid integer values will throw an IllegalArgumentException. Any other value will result in an IllegalArgumentException." [mode] (condp = mode DeliveryMode/PERSISTENT DeliveryMode/PERSISTENT DeliveryMode/NON_PERSISTENT DeliveryMode/NON_PERSISTENT :persistent DeliveryMode/PERSISTENT :non-persistent DeliveryMode/NON_PERSISTENT)) (s/fdef delivery-mode-value :args (s/cat :mode ::delivery-mode) :ret ::delivery-mode-value) (s/def ::acknowledge-mode-value #{Session/AUTO_ACKNOWLEDGE Session/CLIENT_ACKNOWLEDGE Session/DUPS_OK_ACKNOWLEDGE}) (s/def ::acknowledge-mode-keyword #{:auto :client :dups-ok}) (s/def ::acknowledge-mode (s/or :name ::acknowledge-mode-keyword :value ::acknowledge-mode-value)) (defn acknowledge-mode-keyword "Coerces a valid acknowledge-mode value to the human-readable keywords: - :auto - :client - :dups-ok If any of these keywords are passed, they will be returned unchanged. Any other value will result in an IllegalArgumentException." [mode] (condp contains? mode #{:auto Session/AUTO_ACKNOWLEDGE} :auto #{:client Session/CLIENT_ACKNOWLEDGE} :client #{:dups-ok Session/DUPS_OK_ACKNOWLEDGE} :dups-ok (throw (IllegalArgumentException. (str "invalid acknowledge-mode: " mode ";" "must be one of: " ":auto, :client, :dups-ok, " "java.jms.Session/AUTO_ACKNOWLEDGE, " "java.jms.Session/CLIENT_ACKNOWLEDGE, " "or java.jms.Session/DUPS_OK_ACKNOWLEDGE"))))) (s/fdef acknowledge-mode-keyword :args (s/cat :mode ::acknowledge-mode) :ret ::acknowledge-mode-keyword) (defn acknowledge-mode-value "Coerces the value to a JMS acknowledge-mode integer value. If a valid acknowledge-mode integer value is passed, it will be returned unchanged. The following keywords are also accepted: - :auto -> javax.jms.Session/AUTO_ACKNOWLEDGE - :client -> javax.jms.Session/CLIENT_ACKNOWLEDGE - :dups-ok -> javax.jms.Session/DUPS_OK_ACKNOWLEDGE Any other value will result in an IllegalArgumentException." [mode] (condp contains? mode #{:auto Session/AUTO_ACKNOWLEDGE} Session/AUTO_ACKNOWLEDGE #{:client Session/CLIENT_ACKNOWLEDGE} Session/CLIENT_ACKNOWLEDGE #{:dups-ok Session/DUPS_OK_ACKNOWLEDGE} Session/DUPS_OK_ACKNOWLEDGE (throw (IllegalArgumentException. (str "invalid acknowledge-mode: " mode ";" "must be one of: " ":auto, :client, :dups-ok, " "java.jms.Session/AUTO_ACKNOWLEDGE, " "java.jms.Session/CLIENT_ACKNOWLEDGE, " "or java.jms.Session/DUPS_OK_ACKNOWLEDGE"))))) (s/fdef acknowledge-mode-value :args (s/cat :mode ::acknowledge-mode) :ret ::acknowledge-mode-value) (defn connection-factory? "Predicate that tests if the argument is a javax.jms.ConnectionFactory" [cf] (instance? ConnectionFactory cf)) (s/def ::connection-factory connection-factory?) (defn connection? "Predicate that tests if the argument is a javax.jms.Connection" [c] (instance? Connection c)) (s/def ::connection connection?) (s/def ::connection-opts (s/keys :opt-un [::start? ::user ::password])) (s/def ::start? boolean?) (s/def ::user string?) (s/def ::password string?) (defn ^Connection create-connection "Produces a javax.jms.Connection from a javax.jms.ConnectionFactory" ([^ConnectionFactory cf] (create-connection cf {})) ([^ConnectionFactory cf {:as opts :keys [start? user password] :or {start? false}}] (cond (and user password) :ok user (throw (IllegalArgumentException. (str "Incomplete connection options: provided :user but missing :password"))) password (throw (IllegalArgumentException. (str "Incomplete connection options: provided :password missing :user")))) (let [c (if user (.createConnection cf user password) (.createConnection cf))] (when start? (.start c)) c))) (s/fdef create-connection :args (s/cat :cf connection-factory? :opts (s/? ::connection-opts)) :ret connection?) (defn session? "Predicate that tests if the argument is a javax.jms.Session" [s] (instance? Session s)) (s/def ::session-opts (s/keys :opt-un [::transacted? ::acknowledge-mode])) (s/def ::transacted? boolean?) (defn ^Session create-session "Produces a javax.jms.Session on a javax.jms.Connection. Accepts an optional, options map that can specify: - whether the session is transactional - the session's acknowledge-mode Defaults to creating a non-transactional session with :auto acknowledge-mode." ([^Connection c] (create-session c {})) ([^Connection c {transacted? :transacted? ack-mode :acknowledge-mode :or {transacted? false ack-mode :auto}}] (.createSession c transacted? (acknowledge-mode-value ack-mode)))) (s/fdef create-session :args (s/cat :c connection? :opts (s/? ::session-opts)) :ret session?) (defn session-options "Given a javax.jms.Session, returns a map of the options used to create/configure that session. The resulting option map is valid to pass to create-session." [^Session session] {:transacted? (.getTransacted session) :acknowledge-mode (condp = (.getAcknowledgeMode session) Session/AUTO_ACKNOWLEDGE :auto Session/CLIENT_ACKNOWLEDGE :client Session/DUPS_OK_ACKNOWLEDGE :dups-ok)}) (s/fdef session-options :args (s/cat :session session?) :ret ::session-opts) (defn destination? "Predicate that tests if the value is a javax.jms.Destination" [dest] (instance? Destination dest)) (defn queue? "Predicate that tests if the value is a javax.jms.Queue" [dest] (instance? Queue dest)) (defn topic? "Predicate that tests if the value is a javax.jms.Topic" [dest] (instance? Topic dest)) (s/def ::destination destination?) (defn ^Queue queue "Given a Session s, and a Queue identity string q, returns a javax.jms.Queue instance for the identified Queue. If q is already an instance of javax.jms.Queue, then it is returned unchanged. Any other value for q will result in an IllegalArgumentException." [^Session s q] (cond (instance? Queue q) q (string? q) (.createQueue s ^String q) :else (throw (IllegalArgumentException. "expected Queue or string")))) (s/fdef queue :args (s/cat :s session? :q (s/alt :queue-name string? :queue-inst queue?)) :ret queue?) (defn ^Topic topic "Given a Session s, and a Topic identity string t, returns a javax.jms.Topic instance for the identified Topic. If t is already an instance of javax.jms.Topic, then it is returned unchanged. Any other value for t will result in an IllegalArgumentException." [^Session s t] (cond (instance? Topic t) t (string? t) (.createTopic s ^String t) :else (throw (IllegalArgumentException. "expected Topic or string")))) (s/fdef topic :args (s/cat :s session? :t (s/alt :topic-name string? :topic-inst topic?)) :ret topic?) (defn destination-name "Returns the string name of a Queue or Topic." [d] (condp instance? d Queue (.getQueueName ^Queue d) Topic (.getTopicName ^Topic d))) (s/fdef destination-name :args (s/cat :d destination?) :ret string?) (defn message-producer? "Predicate that tests if p is a javax.jms.MessageProducer." [p] (instance? MessageProducer p)) (s/def ::message-producer-opts (s/keys :opt-un [::delivery-mode ::message-ttl])) (s/def ::message-ttl pos-int?) (defn message-producer "Creates a javax.jms.MessageProducer on Session s that will send messages to Destination d. May optionally pass a map of {:delivery-mode dm, :message-ttl ttl} to configure the default delivery-mode and time-to-live for messages sent by the MessageProducer." ([^Session s ^Destination d] (message-producer s d {})) ([^Session s ^Destination d {dm :delivery-mode ttl :message-ttl}] (let [^MessageProducer p (.createProducer s d)] (when dm (.setDeliveryMode p (delivery-mode-value dm))) (when ttl (when-not (integer? ttl) (throw (IllegalArgumentException. "message-expiration must be an integer"))) (.setTimeToLive p ttl)) p))) (s/fdef message-producer :args (s/cat :s session? :d destination? :opts (s/? ::message-producer-opts)) :ret message-producer?) (defn message? "Predicate that tests if m is an instance of javax.jms.Message." [m] (instance? Message m)) (defn send-message! "Sends a Message m via MessageProducer p. The single arity call is a no-op that allow send-message! to be used in a reducing or transducing context." ([^MessageProducer p ^Message m] (.send p m) p) ([^MessageProducer p ^Destination d ^Message m] (.send p d m) p)) (s/fdef send-message! :args (s/alt :completing (s/cat :p message-producer?) :producer-dest (s/cat :p message-producer? :m message?) :explicit-dest (s/cat :p message-producer? :d destination? :m message?)) :ret message-producer?) (defn message-consumer? "Predicate that tests if c is a javax.jms.MessageConsumer." [c] (instance? MessageConsumer c)) (s/def ::consume-messages-opts (s/keys :opt-un [::message-selector ::no-local? ::on-message])) (s/def ::consume-message-opts* (s/keys* :opt-un [::message-selector ::no-local? ::on-message])) (s/def ::message-selector string?) (s/def ::no-local? boolean?) (s/def ::on-message fn?) (defn- set-message-listener! [^MessageConsumer consumer on-message] (if (fn? on-message) (->> (reify MessageListener (onMessage [_ msg] (on-message msg))) (.setMessageListener consumer)) (throw (IllegalArgumentException. "on-message must be a function")))) (defn ^MessageConsumer message-consumer "Creates a javax.jms.MessageConsumer on Session s which consumes messages sent to Destination d. Accepts an optional map with the following keys: - :no-local? :: if true, the consumer will not receive messages that were - on-message :: a function that will be called asynchronously whenever the consumer receives a message. The function must accept a single-argument which will be the that was message received." ([^Session s ^Destination d] (.createConsumer s d)) ([^Session s ^Destination d & {:keys [message-selector no-local? on-message]}] (let [c (.createConsumer s d message-selector (boolean no-local?))] (when (some? on-message) (set-message-listener! c on-message)) c))) (s/fdef message-consumer :args (s/cat :s session? :d destination? :opts ::consume-message-opts*) :ret message-consumer?) (s/def ::message-id string?) (s/def ::message-type string?) (s/def ::timestamp inst?) (s/def ::expiration inst?) (s/def ::correlation-id string?) (s/def ::reply-to ::destination) (s/def ::priority integer?) (s/def ::redelivered? boolean?) (s/def ::bytes-body bytes?) (s/def ::message-info (s/keys :opt-un [::message-id ::message-type ::timestamp ::expiration ::correlation-id ::destination ::reply-to ::delivery-mode ::priority ::redelivered?])) (defn message-info "Returns a map of the metadata common to all instances of javax.jms.Message. Includes ONLY non-nil entries for: - :message-id from Message#getJMSMessageID() - :message-type from Message#getJMSTypes() - :timestamp Instant derived from Message#getJMSTimeStamp() - :expiration Instant derived from Message#getJMSExpiration - :correlation-id from Message#getJMSCorrelationID - :destination from Message#getJMSDestination - :reply-to from Message#getJMSReplyTo() - :delivery-mode derived from Message#getJMSDeliveryMode() - :priority from Message#getJMSPriority() - :redelivered? from Message#getJMSRedelivered()" [^Message m] (cond-> {} (.getJMSMessageID m) (assoc :message-id (.getJMSMessageID m)) (.getJMSType m) (assoc :message-type (.getJMSType m)) (.getJMSTimestamp m) (assoc :timestamp (Instant/ofEpochMilli (.getJMSTimestamp m))) (.getJMSExpiration m) (assoc :expiration (Instant/ofEpochMilli (.getJMSExpiration m))) (.getJMSCorrelationID m) (assoc :correlation-id (.getJMSCorrelationID m)) (.getJMSDestination m) (assoc :destination (.getJMSDestination m)) (.getJMSReplyTo m) (assoc :reply-to (.getJMSReplyTo m)) (.getJMSDeliveryMode m) (assoc :delivery-mode (delivery-mode-keyword (.getJMSDeliveryMode m))) (.getJMSPriority m) (assoc :priority (.getJMSPriority m)) (.getJMSRedelivered m) (assoc :redelivered? (.getJMSRedelivered m)))) (s/fdef message-info :args (s/cat :m message?) :ret ::message-info) (defmacro ^:private cond-doto [expr & clauses] (assert (even? (count clauses))) (let [ret (gensym)] `(let [~ret ~expr] ~@(map (fn [[pred-expr form]] (with-meta (if (seq? form) `(when ~pred-expr (~(first form) ~ret ~@(next form))) `(when ~pred-expr `(~form ~ret))) (meta form))) (partition 2 clauses)) ~ret))) (comment (macroexpand-1 '(cond-doto (StringBuilder.) true (.append "1") false (.append "2")))) (defn ^Message set-message-info! "Sets common metadata on a Message." [^Message m {:keys [message-id message-type timestamp expiration correlation-id destination reply-to delivery-mode priority redelivered?]}] (cond-doto m message-id (.setJMSMessageID message-id) message-type (.setJMSType message-type) timestamp (.setJMSTimestamp (inst-ms timestamp)) expiration (.setJMSExpiration (inst-ms expiration)) correlation-id (.setJMSCorrelationID correlation-id) destination (.setJMSDestination destination) reply-to (.setJMSReplyTo reply-to) delivery-mode (.setJMSDeliveryMode (delivery-mode-value delivery-mode)) priority (.setJMSPriority priority) redelivered? (.setJMSRedelivered redelivered?))) (s/fdef set-message-info! :args (s/cat :m message? :info ::message-info) :ret message? :fn #(identical? (:ret %) (-> % :args :m))) (defn bytes-message? "Predicate that tests if m is a javax.jms.BytesMessage" [m] (instance? BytesMessage m)) (defn read-bytes "Reads bytes from a javax.jms.BytesMessage. This only works with and mutates byte-arrays Arities: 1. Pass a BytesMessage: returns a byte-array containing the contents of the message. 2. Pass BytesMessage and a byte-array: reads contents of message into the byte-array argument 3. Pass BytesMessage, byte-array, and integer length: reads upto 'length' bytes into byte-array from ([^BytesMessage m] (let [l (.getBodyLength m) arr (byte-array l)] (read-bytes m arr l) arr)) ([^BytesMessage m ^bytes arr] (.readBytes m arr) arr) ([^BytesMessage m ^bytes arr length] (.readBytes m arr length) arr)) (s/fdef read-bytes :args (s/cat :m bytes-message? :out-args (s/? (s/cat :arr bytes? :length (s/? integer?)))) :ret bytes?) (defn write-bytes "Writes the contents of byte-array 'arr' into the body of BytesMessage 'm'. May optionally pass integer 'offset' and 'length' which will write the contents of 'arr[offset]..arr[length-1]' into message 'm'." ([^BytesMessage m ^bytes arr] (.writeBytes m arr) m) ([^BytesMessage m ^bytes arr offset length] (.writeBytes m arr offset length) m)) (s/fdef write-bytes :args (s/cat :m bytes-message? :arr bytes? :offset-length (s/? (s/cat :offset pos-int? :length pos-int?))) :ret bytes-message?)
ab9e7a44e9bb8f2b66f5f0c90680a811d05a5d8310dba4ef666d14cdd024cd07
gigasquid/eodermdrome
parser.clj
(ns eodermdrome.parser (:require [eodermdrome.graph :as eg] [clojure.set :as set] [instaparse.core :as insta])) (def parser (insta/parser "program = cmdline (<'\n'> cmdline)* cmdline = (<comment> <space>*)* cmd (<space>* <comment>)* cmd = cmd-part <seperator> cmd-part cmd-part = (io <seperator>)* graph io = <'('> #'[A-z0-9\\s]*'+ <')'> seperator = space | space comment space comment = #'\\,.*\\,' space = #'[\\s]'+ graph = #'[a-z]*'+")) (def transform-options {:program vector :cmdline identity :cmd-part vector :cmd (fn [& v] (let [[in out] v input (:io (first (filter :io in))) output (:io (first (filter :io out))) g-in (:g (first (filter :g in))) g-out (:g (first (filter :g out)))] {:input input :output output :g-in g-in :g-out g-out})) :graph (fn [v] {:g (eg/make-graph v)}) :io (fn [v] {:io (str v)})}) (defn parse [input] (->> (parser input) (insta/transform transform-options)))
null
https://raw.githubusercontent.com/gigasquid/eodermdrome/681b9205a8d27c86c72e5a22ae5d82496cbd29f0/src/eodermdrome/parser.clj
clojure
(ns eodermdrome.parser (:require [eodermdrome.graph :as eg] [clojure.set :as set] [instaparse.core :as insta])) (def parser (insta/parser "program = cmdline (<'\n'> cmdline)* cmdline = (<comment> <space>*)* cmd (<space>* <comment>)* cmd = cmd-part <seperator> cmd-part cmd-part = (io <seperator>)* graph io = <'('> #'[A-z0-9\\s]*'+ <')'> seperator = space | space comment space comment = #'\\,.*\\,' space = #'[\\s]'+ graph = #'[a-z]*'+")) (def transform-options {:program vector :cmdline identity :cmd-part vector :cmd (fn [& v] (let [[in out] v input (:io (first (filter :io in))) output (:io (first (filter :io out))) g-in (:g (first (filter :g in))) g-out (:g (first (filter :g out)))] {:input input :output output :g-in g-in :g-out g-out})) :graph (fn [v] {:g (eg/make-graph v)}) :io (fn [v] {:io (str v)})}) (defn parse [input] (->> (parser input) (insta/transform transform-options)))
1b5af8f140dcda12652ff31e8df96a7a7f9d4f1124c68e1e0a3524b5e9f60b00
Metaxal/rwind
launcher-base.rkt
#lang racket/base ; launcher-base.rkt (require rwind/base rwind/util rwind/doc-string racket/file racket/list) (define history-max-length 50) (define rwind-launcher-history-file (find-user-config-file rwind-dir-name "rwind-launcher-history.txt")) (define* (launcher-history) "History of launched commands from the Rwind launcher." (define hist (if (file-exists? rwind-launcher-history-file) (reverse (file->lines rwind-launcher-history-file)) null)) ;; If history is too long, truncate it and rewrite the file ;; (we don't want the history to grow indefinitely) (when (> (length hist) (* 2 history-max-length)) (display-lines-to-file (reverse (take hist history-max-length)) rwind-launcher-history-file #:mode 'text #:exists 'replace)) hist) (define* (add-launcher-history! command) "Add to the history of launched commands." (with-output-to-file rwind-launcher-history-file (λ () (printf "~a~n" command)) #:mode 'text #:exists 'append)) (define* (open-launcher) "Show the program launcher." (rwind-system "racket -l rwind/launcher"))
null
https://raw.githubusercontent.com/Metaxal/rwind/5a4f580b0882452f3938aaa1711a6d99570f006f/launcher-base.rkt
racket
launcher-base.rkt If history is too long, truncate it and rewrite the file (we don't want the history to grow indefinitely)
#lang racket/base (require rwind/base rwind/util rwind/doc-string racket/file racket/list) (define history-max-length 50) (define rwind-launcher-history-file (find-user-config-file rwind-dir-name "rwind-launcher-history.txt")) (define* (launcher-history) "History of launched commands from the Rwind launcher." (define hist (if (file-exists? rwind-launcher-history-file) (reverse (file->lines rwind-launcher-history-file)) null)) (when (> (length hist) (* 2 history-max-length)) (display-lines-to-file (reverse (take hist history-max-length)) rwind-launcher-history-file #:mode 'text #:exists 'replace)) hist) (define* (add-launcher-history! command) "Add to the history of launched commands." (with-output-to-file rwind-launcher-history-file (λ () (printf "~a~n" command)) #:mode 'text #:exists 'append)) (define* (open-launcher) "Show the program launcher." (rwind-system "racket -l rwind/launcher"))
86b13d17b4f4865d1a937432aafbbf1fa38c20e0aacfa2e055b015564892e0c0
disco-framework/disco
changer_tests.erl
%% @hidden to edoc -module(changer_tests). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). %% %% tests change_state_test() -> MockedMods = [port_utils, json], meck:new(MockedMods, [passthrough]), meck:new(application, [passthrough, unstick]), meck:expect(port_utils, easy_open_killer_port, fun(_) -> foo_port end), PortCmdDoubleAnswer = fun(_,_) -> self() ! {foo_port, {data, {bar, <<"somebinstring">>}}}, self() ! {foo_port, {data, {bar, <<"somebinstring">>}}} end, PortCmdNoAnswer = fun(_,_) -> ok end, meck:expect(application, get_env, fun(port_call_timeout) -> {ok, 10} end), meck:expect(json, default_decoder, fun() -> ok end), meck:sequence(json, process, 2, [{incomplete, foo}, {ok, [{<<"state">>, <<"AnswerString">>}]}, {bad_json, bar}]), {ok, SupPid} = changer_sup:start_link("ignored executable path"), try meck:expect(port_utils, port_command, PortCmdDoubleAnswer), ?assertEqual({ok, "AnswerString"}, changer:change_state("OldState", "Proposition")), ?assertEqual({error, illegal_json}, changer:change_state("OldState", "Proposition")), meck:expect(port_utils, port_command, PortCmdNoAnswer), ?assertEqual({error, timeout}, changer:change_state("OldState", "Proposition")) after exit(SupPid, normal), ?assert(meck:validate(MockedMods)), meck:unload(MockedMods), meck:unload(application) end. -endif.
null
https://raw.githubusercontent.com/disco-framework/disco/f55f35d46d43ef5f4fa1466bdf8d662f5f01f30f/src/test/changer_tests.erl
erlang
@hidden to edoc tests
-module(changer_tests). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). change_state_test() -> MockedMods = [port_utils, json], meck:new(MockedMods, [passthrough]), meck:new(application, [passthrough, unstick]), meck:expect(port_utils, easy_open_killer_port, fun(_) -> foo_port end), PortCmdDoubleAnswer = fun(_,_) -> self() ! {foo_port, {data, {bar, <<"somebinstring">>}}}, self() ! {foo_port, {data, {bar, <<"somebinstring">>}}} end, PortCmdNoAnswer = fun(_,_) -> ok end, meck:expect(application, get_env, fun(port_call_timeout) -> {ok, 10} end), meck:expect(json, default_decoder, fun() -> ok end), meck:sequence(json, process, 2, [{incomplete, foo}, {ok, [{<<"state">>, <<"AnswerString">>}]}, {bad_json, bar}]), {ok, SupPid} = changer_sup:start_link("ignored executable path"), try meck:expect(port_utils, port_command, PortCmdDoubleAnswer), ?assertEqual({ok, "AnswerString"}, changer:change_state("OldState", "Proposition")), ?assertEqual({error, illegal_json}, changer:change_state("OldState", "Proposition")), meck:expect(port_utils, port_command, PortCmdNoAnswer), ?assertEqual({error, timeout}, changer:change_state("OldState", "Proposition")) after exit(SupPid, normal), ?assert(meck:validate(MockedMods)), meck:unload(MockedMods), meck:unload(application) end. -endif.
55f7b325f3da2671a3289841e3ea4170fcd74e53376bc99d9694d0b2928f3de3
HJianBo/sserl
sserl_sup.erl
%%%------------------------------------------------------------------- %% @doc sserl top level supervisor. %% @end %%%------------------------------------------------------------------- -module(sserl_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -include("sserl.hrl"). -define(SERVER, ?MODULE). %%==================================================================== %% API functions %%==================================================================== start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%==================================================================== %% Supervisor callbacks %%==================================================================== Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules } init([]) -> TrafficEvent = {?TRAFFIC_EVENT, {gen_event, start_link, [{local, ?TRAFFIC_EVENT}]}, permanent, 5000, worker, dynamic}, StatEvent = {?STAT_EVENT, {gen_event, start_link, [{local, ?STAT_EVENT}]}, permanent, 5000, worker, dynamic}, Storage = {sserl_storage, {sserl_storage, start_link, []}, transient, brutal_kill, worker, []}, ListenerSup = {sserl_listener_sup, {sserl_listener_sup, start_link, []}, transient, brutal_kill, supervisor, [sserl_listener_sup]}, Manager = {sserl_manager, {sserl_manager, start_link, []}, transient, brutal_kill, worker, [sserl_port_manager]}, Mutil = {sserl_mutil, {sserl_mutil, start_link, []}, transient, brutal_kill, worker, []}, {ok, { {one_for_one, 2, 10}, [TrafficEvent, StatEvent, Storage, ListenerSup, Manager, Mutil]} }. %%==================================================================== Internal functions %%====================================================================
null
https://raw.githubusercontent.com/HJianBo/sserl/9e42930caf8bfe90ae9ed2edac2e0672f7e5e55e/apps/sserl/src/sserl_sup.erl
erlang
------------------------------------------------------------------- @doc sserl top level supervisor. @end ------------------------------------------------------------------- API Supervisor callbacks ==================================================================== API functions ==================================================================== ==================================================================== Supervisor callbacks ==================================================================== ==================================================================== ====================================================================
-module(sserl_sup). -behaviour(supervisor). -export([start_link/0]). -export([init/1]). -include("sserl.hrl"). -define(SERVER, ?MODULE). start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). Child : : { Id , StartFunc , Restart , Shutdown , Type , Modules } init([]) -> TrafficEvent = {?TRAFFIC_EVENT, {gen_event, start_link, [{local, ?TRAFFIC_EVENT}]}, permanent, 5000, worker, dynamic}, StatEvent = {?STAT_EVENT, {gen_event, start_link, [{local, ?STAT_EVENT}]}, permanent, 5000, worker, dynamic}, Storage = {sserl_storage, {sserl_storage, start_link, []}, transient, brutal_kill, worker, []}, ListenerSup = {sserl_listener_sup, {sserl_listener_sup, start_link, []}, transient, brutal_kill, supervisor, [sserl_listener_sup]}, Manager = {sserl_manager, {sserl_manager, start_link, []}, transient, brutal_kill, worker, [sserl_port_manager]}, Mutil = {sserl_mutil, {sserl_mutil, start_link, []}, transient, brutal_kill, worker, []}, {ok, { {one_for_one, 2, 10}, [TrafficEvent, StatEvent, Storage, ListenerSup, Manager, Mutil]} }. Internal functions
d915002ce55b46c116f698624e2ad377b69d151559b633cfcba0e24ac3eb15b2
huangjs/cl
dlasq1.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ " " f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ " " f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ " " f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ " " f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ " " f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " macros.l , v 1.112 2009/01/08 12:57:19 " ) Using Lisp CMU Common Lisp 19f ( 19F ) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format double-float)) (in-package :lapack) (let* ((zero 0.0)) (declare (type (double-float 0.0 0.0) zero) (ignorable zero)) (defun dlasq1 (n d e work info) (declare (type (array double-float (*)) work e d) (type (f2cl-lib:integer4) info n)) (f2cl-lib:with-multi-array-data ((d double-float d-%data% d-%offset%) (e double-float e-%data% e-%offset%) (work double-float work-%data% work-%offset%)) (prog ((eps 0.0) (scale 0.0) (safmin 0.0) (sigmn 0.0) (sigmx 0.0) (i 0) (iinfo 0)) (declare (type (double-float) eps scale safmin sigmn sigmx) (type (f2cl-lib:integer4) i iinfo)) (setf info 0) (cond ((< n 0) (setf info -2) (xerbla "DLASQ1" (f2cl-lib:int-sub info)) (go end_label)) ((= n 0) (go end_label)) ((= n 1) (setf (f2cl-lib:fref d-%data% (1) ((1 *)) d-%offset%) (abs (f2cl-lib:fref d-%data% (1) ((1 *)) d-%offset%))) (go end_label)) ((= n 2) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4) (dlas2 (f2cl-lib:fref d-%data% (1) ((1 *)) d-%offset%) (f2cl-lib:fref e-%data% (1) ((1 *)) e-%offset%) (f2cl-lib:fref d-%data% (2) ((1 *)) d-%offset%) sigmn sigmx) (declare (ignore var-0 var-1 var-2)) (setf sigmn var-3) (setf sigmx var-4)) (setf (f2cl-lib:fref d-%data% (1) ((1 *)) d-%offset%) sigmx) (setf (f2cl-lib:fref d-%data% (2) ((1 *)) d-%offset%) sigmn) (go end_label))) (setf sigmx zero) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i (f2cl-lib:int-add n (f2cl-lib:int-sub 1))) nil) (tagbody (setf (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%) (abs (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))) (setf sigmx (max sigmx (abs (f2cl-lib:fref e-%data% (i) ((1 *)) e-%offset%)))) label10)) (setf (f2cl-lib:fref d-%data% (n) ((1 *)) d-%offset%) (abs (f2cl-lib:fref d-%data% (n) ((1 *)) d-%offset%))) (cond ((= sigmx zero) (multiple-value-bind (var-0 var-1 var-2 var-3) (dlasrt "D" n d iinfo) (declare (ignore var-0 var-1 var-2)) (setf iinfo var-3)) (go end_label))) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf sigmx (max sigmx (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))) label20)) (setf eps (dlamch "Precision")) (setf safmin (dlamch "Safe minimum")) (setf scale (f2cl-lib:fsqrt (/ eps safmin))) (dcopy n d 1 (f2cl-lib:array-slice work double-float (1) ((1 *))) 2) (dcopy (f2cl-lib:int-sub n 1) e 1 (f2cl-lib:array-slice work double-float (2) ((1 *))) 2) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9) (dlascl "G" 0 0 sigmx scale (f2cl-lib:int-sub (f2cl-lib:int-mul 2 n) 1) 1 work (f2cl-lib:int-sub (f2cl-lib:int-mul 2 n) 1) iinfo) (declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8)) (setf iinfo var-9)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i (f2cl-lib:int-add (f2cl-lib:int-mul 2 n) (f2cl-lib:int-sub 1))) nil) (tagbody (setf (f2cl-lib:fref work-%data% (i) ((1 *)) work-%offset%) (expt (f2cl-lib:fref work-%data% (i) ((1 *)) work-%offset%) 2)) label30)) (setf (f2cl-lib:fref work-%data% ((f2cl-lib:int-mul 2 n)) ((1 *)) work-%offset%) zero) (multiple-value-bind (var-0 var-1 var-2) (dlasq2 n work info) (declare (ignore var-0 var-1)) (setf info var-2)) (cond ((= info 0) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%) (f2cl-lib:fsqrt (f2cl-lib:fref work-%data% (i) ((1 *)) work-%offset%))) label40)) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9) (dlascl "G" 0 0 scale sigmx n 1 d n iinfo) (declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8)) (setf iinfo var-9)))) (go end_label) end_label (return (values nil nil nil nil info)))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dlasq1 fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (array double-float (*)) (array double-float (*)) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil fortran-to-lisp::info) :calls '(fortran-to-lisp::dlasq2 fortran-to-lisp::dlascl fortran-to-lisp::dcopy fortran-to-lisp::dlamch fortran-to-lisp::dlasrt fortran-to-lisp::dlas2 fortran-to-lisp::xerbla))))
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/maxima/share/lapack/lapack/dlasq1.lisp
lisp
Compiled by f2cl version: Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format double-float))
( " f2cl1.l , v 1.215 2009/04/07 22:05:21 rtoy Exp $ " " f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ " " f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ " " f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ " " f2cl5.l , v 1.200 2009/01/19 02:38:17 rtoy Exp $ " " f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " macros.l , v 1.112 2009/01/08 12:57:19 " ) Using Lisp CMU Common Lisp 19f ( 19F ) (in-package :lapack) (let* ((zero 0.0)) (declare (type (double-float 0.0 0.0) zero) (ignorable zero)) (defun dlasq1 (n d e work info) (declare (type (array double-float (*)) work e d) (type (f2cl-lib:integer4) info n)) (f2cl-lib:with-multi-array-data ((d double-float d-%data% d-%offset%) (e double-float e-%data% e-%offset%) (work double-float work-%data% work-%offset%)) (prog ((eps 0.0) (scale 0.0) (safmin 0.0) (sigmn 0.0) (sigmx 0.0) (i 0) (iinfo 0)) (declare (type (double-float) eps scale safmin sigmn sigmx) (type (f2cl-lib:integer4) i iinfo)) (setf info 0) (cond ((< n 0) (setf info -2) (xerbla "DLASQ1" (f2cl-lib:int-sub info)) (go end_label)) ((= n 0) (go end_label)) ((= n 1) (setf (f2cl-lib:fref d-%data% (1) ((1 *)) d-%offset%) (abs (f2cl-lib:fref d-%data% (1) ((1 *)) d-%offset%))) (go end_label)) ((= n 2) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4) (dlas2 (f2cl-lib:fref d-%data% (1) ((1 *)) d-%offset%) (f2cl-lib:fref e-%data% (1) ((1 *)) e-%offset%) (f2cl-lib:fref d-%data% (2) ((1 *)) d-%offset%) sigmn sigmx) (declare (ignore var-0 var-1 var-2)) (setf sigmn var-3) (setf sigmx var-4)) (setf (f2cl-lib:fref d-%data% (1) ((1 *)) d-%offset%) sigmx) (setf (f2cl-lib:fref d-%data% (2) ((1 *)) d-%offset%) sigmn) (go end_label))) (setf sigmx zero) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i (f2cl-lib:int-add n (f2cl-lib:int-sub 1))) nil) (tagbody (setf (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%) (abs (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))) (setf sigmx (max sigmx (abs (f2cl-lib:fref e-%data% (i) ((1 *)) e-%offset%)))) label10)) (setf (f2cl-lib:fref d-%data% (n) ((1 *)) d-%offset%) (abs (f2cl-lib:fref d-%data% (n) ((1 *)) d-%offset%))) (cond ((= sigmx zero) (multiple-value-bind (var-0 var-1 var-2 var-3) (dlasrt "D" n d iinfo) (declare (ignore var-0 var-1 var-2)) (setf iinfo var-3)) (go end_label))) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf sigmx (max sigmx (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%))) label20)) (setf eps (dlamch "Precision")) (setf safmin (dlamch "Safe minimum")) (setf scale (f2cl-lib:fsqrt (/ eps safmin))) (dcopy n d 1 (f2cl-lib:array-slice work double-float (1) ((1 *))) 2) (dcopy (f2cl-lib:int-sub n 1) e 1 (f2cl-lib:array-slice work double-float (2) ((1 *))) 2) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9) (dlascl "G" 0 0 sigmx scale (f2cl-lib:int-sub (f2cl-lib:int-mul 2 n) 1) 1 work (f2cl-lib:int-sub (f2cl-lib:int-mul 2 n) 1) iinfo) (declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8)) (setf iinfo var-9)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i (f2cl-lib:int-add (f2cl-lib:int-mul 2 n) (f2cl-lib:int-sub 1))) nil) (tagbody (setf (f2cl-lib:fref work-%data% (i) ((1 *)) work-%offset%) (expt (f2cl-lib:fref work-%data% (i) ((1 *)) work-%offset%) 2)) label30)) (setf (f2cl-lib:fref work-%data% ((f2cl-lib:int-mul 2 n)) ((1 *)) work-%offset%) zero) (multiple-value-bind (var-0 var-1 var-2) (dlasq2 n work info) (declare (ignore var-0 var-1)) (setf info var-2)) (cond ((= info 0) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf (f2cl-lib:fref d-%data% (i) ((1 *)) d-%offset%) (f2cl-lib:fsqrt (f2cl-lib:fref work-%data% (i) ((1 *)) work-%offset%))) label40)) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8 var-9) (dlascl "G" 0 0 scale sigmx n 1 d n iinfo) (declare (ignore var-0 var-1 var-2 var-3 var-4 var-5 var-6 var-7 var-8)) (setf iinfo var-9)))) (go end_label) end_label (return (values nil nil nil nil info)))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dlasq1 fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (array double-float (*)) (array double-float (*)) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil fortran-to-lisp::info) :calls '(fortran-to-lisp::dlasq2 fortran-to-lisp::dlascl fortran-to-lisp::dcopy fortran-to-lisp::dlamch fortran-to-lisp::dlasrt fortran-to-lisp::dlas2 fortran-to-lisp::xerbla))))
e590530c5d6e77dce82f15728923adfba9b9759760ca230a484b6f816a888dc2
mstepniowski/project-euler
euler_016.clj
Solution to Project Euler problem 16 ;; ;; 2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26 . ;; What is the sum of the digits of the number 2 ^ 1000 ? (ns com.stepniowski.euler-016) (defn power [x y] (. (. java.math.BigInteger (valueOf x)) (pow y))) (defn solution [] (let [digits (map #(Integer/parseInt (str %)) (str (power 2 1000)))] (reduce + digits)))
null
https://raw.githubusercontent.com/mstepniowski/project-euler/01d64aa46b21d96fc5291fdf216bf4bad8249029/src/com/stepniowski/euler_016.clj
clojure
Solution to Project Euler problem 16 2 ^ 15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26 . What is the sum of the digits of the number 2 ^ 1000 ? (ns com.stepniowski.euler-016) (defn power [x y] (. (. java.math.BigInteger (valueOf x)) (pow y))) (defn solution [] (let [digits (map #(Integer/parseInt (str %)) (str (power 2 1000)))] (reduce + digits)))
e3aa564aeb3c3201b85963ec8258aebf0084d87767374e01201968b6a2d06713
slipstream/SlipStreamServer
cookies_test.clj
(ns com.sixsq.slipstream.auth.cookies-test (:refer-clojure :exclude [update]) (:require [clj-time.coerce :as c] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :refer :all] [com.sixsq.slipstream.auth.cookies :as t] [com.sixsq.slipstream.auth.env-fixture :as env-fixture] [com.sixsq.slipstream.auth.utils.sign :as s] [environ.core :as environ] [ring.util.codec :as codec])) (defn serialize-cookie-value "replaces the map cookie value with a serialized string" [{:keys [value] :as cookie}] (assoc cookie :value (codec/form-encode value))) (defn damaged-cookie-value "replaces the map cookie value with a serialized string, but modifies it to make it invalid" [{:keys [value] :as cookie}] (assoc cookie :value (str (codec/form-encode value) "-INVALID"))) (deftest revoked-cookie-ok (let [revoked (t/revoked-cookie)] (is (map? revoked)) (is (= "INVALID" (get-in revoked [:value])))) (let [k "cookie.name" revoked (t/revoked-cookie k)] (is (map? revoked)) (is (= "INVALID" (get-in revoked [k :value]))))) (deftest claims-cookie-ok (with-redefs [environ/env env-fixture/env-map] (let [claims {:alpha "a", :beta "b", :gamma 3} cookie (t/claims-cookie claims) k "cookie.name" named-cookie (t/claims-cookie claims k)] (is (map? cookie)) (is (not= "INVALID" (:value cookie))) (is (-> cookie :value :token)) (is (map? named-cookie)) (is (not= "INVALID" (get-in named-cookie [k :value]))) (is (get-in named-cookie [k :value :token]))))) (deftest check-extract-claims (with-redefs [environ/env env-fixture/env-map] (let [claims {:alpha "a", :beta "b", :gamma 3}] (is (nil? (t/extract-claims nil))) (is (nil? (t/extract-claims {:value nil}))) (is (thrown? Exception (t/extract-claims {:value "token=INVALID"}))) (is (thrown? Exception (t/extract-claims {:value "unknown-token"}))) (is (= claims (-> claims t/claims-cookie serialize-cookie-value t/extract-claims (dissoc :exp))))))) (deftest check-claims->authn-info (are [expected claims] (= expected (t/claims->authn-info claims)) nil nil nil {} ["user" #{}] {:username "user"} ["user" #{"session"}] {:username "user" :session "session"} ["user" #{"role1"}] {:username "user", :roles "role1"} ["user" #{"role1" "role2"}] {:username "user", :roles "role1 role2"} ["user" #{"session" "role1"}] {:username "user", :roles "role1" :session "session"} ["user" #{"session" "role1" "role2"}] {:username "user", :roles "role1 role2" :session "session"})) (deftest check-extract-cookie-claims (with-redefs [environ/env env-fixture/env-map] (let [claims {:username "user" :roles "role1 role2" :session "session/81469d29-40dc-438e-b60f-e8748e3c7ee6"}] (is (nil? (t/extract-cookie-claims nil))) (is (nil? (-> claims t/claims-cookie damaged-cookie-value t/extract-cookie-claims (dissoc :exp)))) (is (= claims (-> claims t/claims-cookie serialize-cookie-value t/extract-cookie-claims (dissoc :exp))))))) (deftest check-extract-cookie-info (with-redefs [environ/env env-fixture/env-map] (let [claims {:username "user" :roles "role1 role2" :session "session"}] (is (nil? (t/extract-cookie-info nil))) (is (nil? (-> claims t/claims-cookie damaged-cookie-value t/extract-cookie-info))) (is (= ["user" #{"session" "role1" "role2"}] (-> claims t/claims-cookie serialize-cookie-value t/extract-cookie-info))))))
null
https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/token/clj/test/com/sixsq/slipstream/auth/cookies_test.clj
clojure
(ns com.sixsq.slipstream.auth.cookies-test (:refer-clojure :exclude [update]) (:require [clj-time.coerce :as c] [clojure.java.io :as io] [clojure.string :as str] [clojure.test :refer :all] [com.sixsq.slipstream.auth.cookies :as t] [com.sixsq.slipstream.auth.env-fixture :as env-fixture] [com.sixsq.slipstream.auth.utils.sign :as s] [environ.core :as environ] [ring.util.codec :as codec])) (defn serialize-cookie-value "replaces the map cookie value with a serialized string" [{:keys [value] :as cookie}] (assoc cookie :value (codec/form-encode value))) (defn damaged-cookie-value "replaces the map cookie value with a serialized string, but modifies it to make it invalid" [{:keys [value] :as cookie}] (assoc cookie :value (str (codec/form-encode value) "-INVALID"))) (deftest revoked-cookie-ok (let [revoked (t/revoked-cookie)] (is (map? revoked)) (is (= "INVALID" (get-in revoked [:value])))) (let [k "cookie.name" revoked (t/revoked-cookie k)] (is (map? revoked)) (is (= "INVALID" (get-in revoked [k :value]))))) (deftest claims-cookie-ok (with-redefs [environ/env env-fixture/env-map] (let [claims {:alpha "a", :beta "b", :gamma 3} cookie (t/claims-cookie claims) k "cookie.name" named-cookie (t/claims-cookie claims k)] (is (map? cookie)) (is (not= "INVALID" (:value cookie))) (is (-> cookie :value :token)) (is (map? named-cookie)) (is (not= "INVALID" (get-in named-cookie [k :value]))) (is (get-in named-cookie [k :value :token]))))) (deftest check-extract-claims (with-redefs [environ/env env-fixture/env-map] (let [claims {:alpha "a", :beta "b", :gamma 3}] (is (nil? (t/extract-claims nil))) (is (nil? (t/extract-claims {:value nil}))) (is (thrown? Exception (t/extract-claims {:value "token=INVALID"}))) (is (thrown? Exception (t/extract-claims {:value "unknown-token"}))) (is (= claims (-> claims t/claims-cookie serialize-cookie-value t/extract-claims (dissoc :exp))))))) (deftest check-claims->authn-info (are [expected claims] (= expected (t/claims->authn-info claims)) nil nil nil {} ["user" #{}] {:username "user"} ["user" #{"session"}] {:username "user" :session "session"} ["user" #{"role1"}] {:username "user", :roles "role1"} ["user" #{"role1" "role2"}] {:username "user", :roles "role1 role2"} ["user" #{"session" "role1"}] {:username "user", :roles "role1" :session "session"} ["user" #{"session" "role1" "role2"}] {:username "user", :roles "role1 role2" :session "session"})) (deftest check-extract-cookie-claims (with-redefs [environ/env env-fixture/env-map] (let [claims {:username "user" :roles "role1 role2" :session "session/81469d29-40dc-438e-b60f-e8748e3c7ee6"}] (is (nil? (t/extract-cookie-claims nil))) (is (nil? (-> claims t/claims-cookie damaged-cookie-value t/extract-cookie-claims (dissoc :exp)))) (is (= claims (-> claims t/claims-cookie serialize-cookie-value t/extract-cookie-claims (dissoc :exp))))))) (deftest check-extract-cookie-info (with-redefs [environ/env env-fixture/env-map] (let [claims {:username "user" :roles "role1 role2" :session "session"}] (is (nil? (t/extract-cookie-info nil))) (is (nil? (-> claims t/claims-cookie damaged-cookie-value t/extract-cookie-info))) (is (= ["user" #{"session" "role1" "role2"}] (-> claims t/claims-cookie serialize-cookie-value t/extract-cookie-info))))))