_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
af1c0166800fde261165a124ad4609c98bd9ee581257a9eb597d139514ee7b6f
logicmoo/logicmoo_nlu
subsumes.lsp
;;; % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % Example code from the book " Natural Language Processing in LISP " % % published by % % Copyright ( c ) 1989 , . % ;;; % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % ;;; subsumes.lsp [ Chapter 7 ] subsumption for dags does the first subsume the second ? ;;; This function attempts to construct a substitution which when applied to the first structure gives the second . ;;; This is put in var_map. var_map is used to hold values for some variables in the first structure . These are the only ;;; substitutions that can be made for these variables. ;;; The code here will not always correctly handle remainders when the first dag contains a variable that only occurs once and the second has no entry for the relevant feature (uses 'dagunify) (defvar var_map) (defun subsumes (dag1 dag2) (setq var_map nil) (subsumes1 dag1 dag2)) (defun subsumes1 (dag1 dag2) (if (equal dag1 dag2) t (if (and (isvar dag1) (assoc dag1 var_map)) (same_dag dag2 (cadr (assoc dag1 var_map))) (if (isvar dag1) (progn (setq var_map (cons (list dag1 dag2) var_map)) t) (if (and (consp dag1) (consp dag2)) (do ((d1 dag1) (d2 dag2)) ((or (not d2) (isvar d1)) (and d2 (subsumes1 d1 d2))) (let ((fpair (car d1))) (if (equal (car fpair) '&) (setq d1 (cadr fpair)) (progn (setq d1 (cdr d1)) (setq d2 (find_and_remove fpair d2)))))) nil))))) (defun same_dag (dag1 dag2) (equal (unify dag1 dag2) empty_subst)) ;;; Given a pair (FEATURE VAL), find the value of FEATURE in dag , checking that it is subsumed by VAL . If so , return the remainder of dag . Otherwise return nil . (defun find_and_remove (fpair dag) (if (consp dag) (let ((value (assoc (car fpair) dag))) (if value (and (subsumes1 (cadr fpair) (cadr value)) (delete_feature_entry (car fpair) dag)) dag must have a continuation entry (let ((rest (cadar (last dag))) (first (butlast dag))) (if (isvar rest) feature in the first has no analogue in the second , but the second is open . this will only work if the feature value in the first is a variable which only occurs once . (and (subsumes1 (cadr fpair) (newvar)) dag) ;; INCORRECT (let ((rest1 (find_and_remove fpair rest))) (and rest1 (append first rest1))))))) nil)) delete the entry for a given feature in a dag ;;; (guaranteed to come before the continuation entry) (defun delete_feature_entry (feature dag) (if (equal feature (caar dag)) (cdr dag) (cons (car dag) (delete_feature_entry feature (cdr dag)))))
null
https://raw.githubusercontent.com/logicmoo/logicmoo_nlu/c066897f55b3ff45aa9155ebcf799fda9741bf74/ext/nlp_book/lisp/subsumes.lsp
lisp
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % This function attempts to construct a substitution which This is put in var_map. var_map is used to hold values for substitutions that can be made for these variables. The code here will not always correctly handle remainders Given a pair (FEATURE VAL), INCORRECT (guaranteed to come before the continuation entry)
% Example code from the book " Natural Language Processing in LISP " % % published by % % Copyright ( c ) 1989 , . % subsumes.lsp [ Chapter 7 ] subsumption for dags does the first subsume the second ? when applied to the first structure gives the second . some variables in the first structure . These are the only when the first dag contains a variable that only occurs once and the second has no entry for the relevant feature (uses 'dagunify) (defvar var_map) (defun subsumes (dag1 dag2) (setq var_map nil) (subsumes1 dag1 dag2)) (defun subsumes1 (dag1 dag2) (if (equal dag1 dag2) t (if (and (isvar dag1) (assoc dag1 var_map)) (same_dag dag2 (cadr (assoc dag1 var_map))) (if (isvar dag1) (progn (setq var_map (cons (list dag1 dag2) var_map)) t) (if (and (consp dag1) (consp dag2)) (do ((d1 dag1) (d2 dag2)) ((or (not d2) (isvar d1)) (and d2 (subsumes1 d1 d2))) (let ((fpair (car d1))) (if (equal (car fpair) '&) (setq d1 (cadr fpair)) (progn (setq d1 (cdr d1)) (setq d2 (find_and_remove fpair d2)))))) nil))))) (defun same_dag (dag1 dag2) (equal (unify dag1 dag2) empty_subst)) find the value of FEATURE in dag , checking that it is subsumed by VAL . If so , return the remainder of dag . Otherwise return nil . (defun find_and_remove (fpair dag) (if (consp dag) (let ((value (assoc (car fpair) dag))) (if value (and (subsumes1 (cadr fpair) (cadr value)) (delete_feature_entry (car fpair) dag)) dag must have a continuation entry (let ((rest (cadar (last dag))) (first (butlast dag))) (if (isvar rest) feature in the first has no analogue in the second , but the second is open . this will only work if the feature value in the first is a variable which only occurs once . (and (subsumes1 (cadr fpair) (newvar)) (let ((rest1 (find_and_remove fpair rest))) (and rest1 (append first rest1))))))) nil)) delete the entry for a given feature in a dag (defun delete_feature_entry (feature dag) (if (equal feature (caar dag)) (cdr dag) (cons (car dag) (delete_feature_entry feature (cdr dag)))))
51655bf8c64e5734038b9b3184d2ba43c30571b2f250e13f5872f2e68eecd978
agda/agda
SparseMatrix.hs
# LANGUAGE TemplateHaskell # module Internal.Termination.SparseMatrix ( matrix , tests ) where import Agda.Termination.Semiring (HasZero(..), Semiring) import qualified Agda.Termination.Semiring as Semiring import Agda.Termination.SparseMatrix import Agda.Utils.Functor import Agda.Utils.Tuple import Data.Array import Data.Function (on) import qualified Data.List as List import Internal.Helpers ------------------------------------------------------------------------ -- * Generators, properties and tests ------------------------------------------------------------------------ -- ** Size ------------------------------------------------------------------------ instance Integral i => Arbitrary (Size i) where arbitrary = do r <- natural c <- natural return $ Size { rows = fromInteger r, cols = fromInteger c } instance CoArbitrary i => CoArbitrary (Size i) where coarbitrary (Size rs cs) = coarbitrary rs . coarbitrary cs -- | Size invariant: dimensions are non-negative. sizeInvariant :: (Ord i, Num i) => Size i -> Bool sizeInvariant sz = rows sz >= 0 && cols sz >= 0 prop_Arbitrary_Size :: Size Integer -> Bool prop_Arbitrary_Size = sizeInvariant prop_size :: TM -> Bool prop_size m = sizeInvariant (size m) -- ** Matrix indices ------------------------------------------------------------------------ instance Integral i => Arbitrary (MIx i) where arbitrary = MIx <$> positive <*> positive instance CoArbitrary i => CoArbitrary (MIx i) where coarbitrary (MIx r c) = coarbitrary r . coarbitrary c -- | Indices must be positive, @>= 1@. mIxInvariant :: (Ord i, Num i) => MIx i -> Bool mIxInvariant i = row i >= 1 && col i >= 1 prop_Arbitrary_MIx :: MIx Integer -> Bool prop_Arbitrary_MIx = mIxInvariant -- ** Matrices ------------------------------------------------------------------------ -- | Matrix indices are lexicographically sorted with no duplicates. -- All indices must be within bounds. matrixInvariant :: (Num i, Ix i, HasZero b) => Matrix i b -> Bool matrixInvariant (Matrix size@Size{ rows, cols} m) = sizeInvariant size && all inBounds m && all nonZero m && strictlySorted (MIx 0 0) m where inBounds (MIx i j, _) = 1 <= i && i <= rows && 1 <= j && j <= cols nonZero (_, b) = b /= zeroElement -- | Check whether an association list is ordered and deterministic , a partial function from @i@ to @b@. strictlySorted :: (Ord i) => i -> [(i, b)] -> Bool strictlySorted i [] = True strictlySorted i ((i', _) : l) = i < i' && strictlySorted i' l Ord MIx should be the lexicographic order already ( report ) . -- | Generates a matrix of the given size, using the given generator -- to generate the rows. matrixUsingRowGen :: (Integral i, HasZero b) => Size i -> (i -> Gen [b]) -- ^ The generator is parameterised on the size of the row. -> Gen (Matrix i b) matrixUsingRowGen sz rowGen = do rows <- vectorOf (fromIntegral $ rows sz) (rowGen $ cols sz) return $ fromLists sz rows -- | Generates a matrix of the given size. matrix :: (Integral i, Arbitrary b, HasZero b) => Size i -> Gen (Matrix i b) matrix sz = matrixUsingRowGen sz (\n -> vectorOf (fromIntegral n) arbitrary) prop_matrix :: Size Int -> Property prop_matrix sz = forAll (matrix sz :: Gen TM) $ \ m -> size m == sz -- | Generate a matrix of arbitrary size. instance (Integral i, Arbitrary b, HasZero b) => Arbitrary (Matrix i b) where arbitrary = matrix =<< arbitrary instance (Integral i, CoArbitrary b, HasZero b) => CoArbitrary (Matrix i b) where coarbitrary m = coarbitrary (toLists m) -- | This matrix type is used for tests. type TM = Matrix Int Int prop_Arbitrary_Matrix :: TM -> Bool prop_Arbitrary_Matrix = matrixInvariant -- ** Matrix operations -- | 'fromIndexList' is identity on well-formed sparse matrices. prop_fromIndexList :: TM -> Bool prop_fromIndexList m@(Matrix size vs) = fromIndexList size vs == m -- | Converting a matrix to a list of lists and back is the identity. prop_fromLists_toLists :: TM -> Bool prop_fromLists_toLists m = fromLists (size m) (toLists m) == m | Any 1x1 matrix is a singleton . prop_isSingleton :: Int -> Bool prop_isSingleton b = Just b == (isSingleton (fromLists (Size 1 1) [[b]] :: TM)) -- | The length of the diagonal is the minimum of the number of -- rows and columns of the matrix. prop_diagonal :: TM -> Bool prop_diagonal m@(Matrix (Size r c) _) = length (diagonal m) == min r c -- prop_diagonal' n = -- forAll natural $ \n -> forAll ( matrix ( Size n n ) : : ) $ \m - > -- length (diagonal m) == n -- | Transposing twice is the identity. prop_transpose :: TM -> Bool prop_transpose m = matrixInvariant m' && m == transpose m' where m' = transpose m -- | Verify 'toSparseRows' against an alternative implementation which -- serves as specification. toSparseRows' :: (Eq i) => Matrix i b -> [(i,[(i,b)])] toSparseRows' (Matrix _ m) = -- group list by row index for (List.groupBy ((==) `on` (row . fst)) m) $ \ ((MIx i j, b) : vs) -> -- turn each group into a sparse row (i, (j,b) : map (mapFst col) vs) prop_toSparseRows :: TM -> Bool prop_toSparseRows m = toSparseRows m == toSparseRows' m prop_addColumn :: TM -> Bool prop_addColumn m = matrixInvariant m' && map init (toLists m') == toLists m where m' = addColumn zeroElement m prop_addRow :: TM -> Bool prop_addRow m = matrixInvariant m' && init (toLists m') == toLists m where m' = addRow zeroElement m -- ** Matrix addition -- | Old implementation of 'zipMatrices'. zipMatrices' :: forall a b c i . (Ord i) => (a -> c) -- ^ Element only present in left matrix. -> (b -> c) -- ^ Element only present in right matrix. -> (a -> b -> c) -- ^ Element present in both matrices. ^ Result counts as zero ? -> Matrix i a -> Matrix i b -> Matrix i c zipMatrices' f g h zero m1 m2 = Matrix (supSize m1 m2) (merge (unM m1) (unM m2)) where merge :: [(MIx i,a)] -> [(MIx i,b)] -> [(MIx i,c)] merge [] m2 = filter (not . zero . snd) $ map (mapSnd g) m2 merge m1 [] = filter (not . zero . snd) $ map (mapSnd f) m1 merge m1@((i,a):m1') m2@((j,b):m2') = case compare i j of LT -> if zero c then r else (i,c) : r where c = f a ; r = merge m1' m2 GT -> if zero c then r else (j,c) : r where c = g b ; r = merge m1 m2' EQ -> if zero c then r else (i,c) : r where c = h a b ; r = merge m1' m2' -- | Verify 'zipMatrices' against older implementation prop_zipMatrices_correct :: TM -> TM -> Bool prop_zipMatrices_correct m1 m2 = zipMatrices id id (+) (== 0) m1 m2 == zipMatrices' id id (+) (== 0) m1 m2 -- | Matrix addition is well-defined, associative and commutative. prop_add :: Size Int -> Property prop_add sz = forAll (three (matrix sz :: Gen TM)) $ \(m1, m2, m3) -> let m' = add (+) m1 m2 in isAssociative (add (+)) m1 m2 m3 && isCommutative (add (+)) m1 m2 && matrixInvariant m' && size m' == size m1 -- | Verify addition against an older implementation. -- -- The older implementation did not fully preserve sparsity, i.e. , introduced zeros . Thus , we need to convert to lists to -- obtain equal results. prop_add_correct :: TM -> TM -> Bool prop_add_correct m1 m2 = toLists (add (+) m1 m2) == toLists (add' (+) m1 m2) where add' :: (Ord i) => (a -> a -> a) -> Matrix i a -> Matrix i a -> Matrix i a add' plus m1 m2 = Matrix (supSize m1 m2) $ mergeAssocWith plus (unM m1) (unM m2) where mergeAssocWith :: (Ord i) => (a -> a -> a) -> [(i,a)] -> [(i,a)] -> [(i,a)] mergeAssocWith f [] m = m mergeAssocWith f l [] = l mergeAssocWith f l@((i,a):l') m@((j,b):m') | i < j = (i,a) : mergeAssocWith f l' m | i > j = (j,b) : mergeAssocWith f l m' | otherwise = (i, f a b) : mergeAssocWith f l' m' -- ** Matrix multiplication -- | Specification of 'interAssocWith'. interAssocWith' :: (Eq i) => (a -> a -> a) -> [(i,a)] -> [(i,a)] -> [(i,a)] interAssocWith' f l l' = [ (i, f a b) | (i,a) <- l, (j,b) <- l', i == j ] -- | Efficient implementation of 'interAssocWith' matches its specification. no_tested_prop_interAssocWith_correct :: [(Int,Int)] -> [(Int,Int)] -> Bool no_tested_prop_interAssocWith_correct xs ys = interAssocWith (*) l l' == interAssocWith' (*) l l' where l = List.sortBy (compare `on` fst) xs l' = List.sortBy (compare `on` fst) ys interAssocWith2 :: Ord i => (a -> a -> a) -> [(i,a)] -> [(i,a)] -> [(i,a)] interAssocWith2 f = zipAssocWith (const []) (const []) (const Nothing) (const Nothing) (\ a -> Just . f a) no_tested_prop_interAssocWith_correct2 :: [(Int,Int)] -> [(Int,Int)] -> Bool no_tested_prop_interAssocWith_correct2 xs ys = interAssocWith (*) xs ys == interAssocWith2 (*) xs ys where l = List.sortBy (compare `on` fst) xs l' = List.sortBy (compare `on` fst) ys -- | Matrix multiplication is well-defined and associative. prop_mul :: Size Int -> Property prop_mul sz = mapSize (`div` 2) $ forAll (two natural) $ \(c2, c3) -> forAll (matrix sz :: Gen TM) $ \m1 -> forAll (matrix (Size { rows = cols sz, cols = c2 })) $ \m2 -> forAll (matrix (Size { rows = c2, cols = c3 })) $ \m3 -> let m' = mult m1 m2 in isAssociative mult m1 m2 m3 && matrixInvariant m' && size m' == Size { rows = rows sz, cols = c2 } where mult = mul Semiring.intSemiring ------------------------------------------------------------------------ -- * All tests ------------------------------------------------------------------------ Template Haskell hack to make the following $ allProperties work under ghc-7.8 . return [] -- KEEP! | All tests as collected by ' allProperties ' . -- Using ' allProperties ' is convenient and superior to the manual -- enumeration of tests, since the name of the property is added -- automatically. tests :: TestTree tests = testProperties "Internal.Termination.SparseMatrix" $allProperties
null
https://raw.githubusercontent.com/agda/agda/4f3899c597792fa4455e0f8134dfd63bc89b1c07/test/Internal/Termination/SparseMatrix.hs
haskell
---------------------------------------------------------------------- * Generators, properties and tests ---------------------------------------------------------------------- ** Size ---------------------------------------------------------------------- | Size invariant: dimensions are non-negative. ** Matrix indices ---------------------------------------------------------------------- | Indices must be positive, @>= 1@. ** Matrices ---------------------------------------------------------------------- | Matrix indices are lexicographically sorted with no duplicates. All indices must be within bounds. | Check whether an association list is ordered and | Generates a matrix of the given size, using the given generator to generate the rows. ^ The generator is parameterised on the size of the row. | Generates a matrix of the given size. | Generate a matrix of arbitrary size. | This matrix type is used for tests. ** Matrix operations | 'fromIndexList' is identity on well-formed sparse matrices. | Converting a matrix to a list of lists and back is the identity. | The length of the diagonal is the minimum of the number of rows and columns of the matrix. prop_diagonal' n = forAll natural $ \n -> length (diagonal m) == n | Transposing twice is the identity. | Verify 'toSparseRows' against an alternative implementation which serves as specification. group list by row index turn each group into a sparse row ** Matrix addition | Old implementation of 'zipMatrices'. ^ Element only present in left matrix. ^ Element only present in right matrix. ^ Element present in both matrices. | Verify 'zipMatrices' against older implementation | Matrix addition is well-defined, associative and commutative. | Verify addition against an older implementation. The older implementation did not fully preserve sparsity, obtain equal results. ** Matrix multiplication | Specification of 'interAssocWith'. | Efficient implementation of 'interAssocWith' matches its specification. | Matrix multiplication is well-defined and associative. ---------------------------------------------------------------------- * All tests ---------------------------------------------------------------------- KEEP! enumeration of tests, since the name of the property is added automatically.
# LANGUAGE TemplateHaskell # module Internal.Termination.SparseMatrix ( matrix , tests ) where import Agda.Termination.Semiring (HasZero(..), Semiring) import qualified Agda.Termination.Semiring as Semiring import Agda.Termination.SparseMatrix import Agda.Utils.Functor import Agda.Utils.Tuple import Data.Array import Data.Function (on) import qualified Data.List as List import Internal.Helpers instance Integral i => Arbitrary (Size i) where arbitrary = do r <- natural c <- natural return $ Size { rows = fromInteger r, cols = fromInteger c } instance CoArbitrary i => CoArbitrary (Size i) where coarbitrary (Size rs cs) = coarbitrary rs . coarbitrary cs sizeInvariant :: (Ord i, Num i) => Size i -> Bool sizeInvariant sz = rows sz >= 0 && cols sz >= 0 prop_Arbitrary_Size :: Size Integer -> Bool prop_Arbitrary_Size = sizeInvariant prop_size :: TM -> Bool prop_size m = sizeInvariant (size m) instance Integral i => Arbitrary (MIx i) where arbitrary = MIx <$> positive <*> positive instance CoArbitrary i => CoArbitrary (MIx i) where coarbitrary (MIx r c) = coarbitrary r . coarbitrary c mIxInvariant :: (Ord i, Num i) => MIx i -> Bool mIxInvariant i = row i >= 1 && col i >= 1 prop_Arbitrary_MIx :: MIx Integer -> Bool prop_Arbitrary_MIx = mIxInvariant matrixInvariant :: (Num i, Ix i, HasZero b) => Matrix i b -> Bool matrixInvariant (Matrix size@Size{ rows, cols} m) = sizeInvariant size && all inBounds m && all nonZero m && strictlySorted (MIx 0 0) m where inBounds (MIx i j, _) = 1 <= i && i <= rows && 1 <= j && j <= cols nonZero (_, b) = b /= zeroElement deterministic , a partial function from @i@ to @b@. strictlySorted :: (Ord i) => i -> [(i, b)] -> Bool strictlySorted i [] = True strictlySorted i ((i', _) : l) = i < i' && strictlySorted i' l Ord MIx should be the lexicographic order already ( report ) . matrixUsingRowGen :: (Integral i, HasZero b) => Size i -> (i -> Gen [b]) -> Gen (Matrix i b) matrixUsingRowGen sz rowGen = do rows <- vectorOf (fromIntegral $ rows sz) (rowGen $ cols sz) return $ fromLists sz rows matrix :: (Integral i, Arbitrary b, HasZero b) => Size i -> Gen (Matrix i b) matrix sz = matrixUsingRowGen sz (\n -> vectorOf (fromIntegral n) arbitrary) prop_matrix :: Size Int -> Property prop_matrix sz = forAll (matrix sz :: Gen TM) $ \ m -> size m == sz instance (Integral i, Arbitrary b, HasZero b) => Arbitrary (Matrix i b) where arbitrary = matrix =<< arbitrary instance (Integral i, CoArbitrary b, HasZero b) => CoArbitrary (Matrix i b) where coarbitrary m = coarbitrary (toLists m) type TM = Matrix Int Int prop_Arbitrary_Matrix :: TM -> Bool prop_Arbitrary_Matrix = matrixInvariant prop_fromIndexList :: TM -> Bool prop_fromIndexList m@(Matrix size vs) = fromIndexList size vs == m prop_fromLists_toLists :: TM -> Bool prop_fromLists_toLists m = fromLists (size m) (toLists m) == m | Any 1x1 matrix is a singleton . prop_isSingleton :: Int -> Bool prop_isSingleton b = Just b == (isSingleton (fromLists (Size 1 1) [[b]] :: TM)) prop_diagonal :: TM -> Bool prop_diagonal m@(Matrix (Size r c) _) = length (diagonal m) == min r c forAll ( matrix ( Size n n ) : : ) $ \m - > prop_transpose :: TM -> Bool prop_transpose m = matrixInvariant m' && m == transpose m' where m' = transpose m toSparseRows' :: (Eq i) => Matrix i b -> [(i,[(i,b)])] toSparseRows' (Matrix _ m) = for (List.groupBy ((==) `on` (row . fst)) m) $ \ ((MIx i j, b) : vs) -> (i, (j,b) : map (mapFst col) vs) prop_toSparseRows :: TM -> Bool prop_toSparseRows m = toSparseRows m == toSparseRows' m prop_addColumn :: TM -> Bool prop_addColumn m = matrixInvariant m' && map init (toLists m') == toLists m where m' = addColumn zeroElement m prop_addRow :: TM -> Bool prop_addRow m = matrixInvariant m' && init (toLists m') == toLists m where m' = addRow zeroElement m zipMatrices' :: forall a b c i . (Ord i) ^ Result counts as zero ? -> Matrix i a -> Matrix i b -> Matrix i c zipMatrices' f g h zero m1 m2 = Matrix (supSize m1 m2) (merge (unM m1) (unM m2)) where merge :: [(MIx i,a)] -> [(MIx i,b)] -> [(MIx i,c)] merge [] m2 = filter (not . zero . snd) $ map (mapSnd g) m2 merge m1 [] = filter (not . zero . snd) $ map (mapSnd f) m1 merge m1@((i,a):m1') m2@((j,b):m2') = case compare i j of LT -> if zero c then r else (i,c) : r where c = f a ; r = merge m1' m2 GT -> if zero c then r else (j,c) : r where c = g b ; r = merge m1 m2' EQ -> if zero c then r else (i,c) : r where c = h a b ; r = merge m1' m2' prop_zipMatrices_correct :: TM -> TM -> Bool prop_zipMatrices_correct m1 m2 = zipMatrices id id (+) (== 0) m1 m2 == zipMatrices' id id (+) (== 0) m1 m2 prop_add :: Size Int -> Property prop_add sz = forAll (three (matrix sz :: Gen TM)) $ \(m1, m2, m3) -> let m' = add (+) m1 m2 in isAssociative (add (+)) m1 m2 m3 && isCommutative (add (+)) m1 m2 && matrixInvariant m' && size m' == size m1 i.e. , introduced zeros . Thus , we need to convert to lists to prop_add_correct :: TM -> TM -> Bool prop_add_correct m1 m2 = toLists (add (+) m1 m2) == toLists (add' (+) m1 m2) where add' :: (Ord i) => (a -> a -> a) -> Matrix i a -> Matrix i a -> Matrix i a add' plus m1 m2 = Matrix (supSize m1 m2) $ mergeAssocWith plus (unM m1) (unM m2) where mergeAssocWith :: (Ord i) => (a -> a -> a) -> [(i,a)] -> [(i,a)] -> [(i,a)] mergeAssocWith f [] m = m mergeAssocWith f l [] = l mergeAssocWith f l@((i,a):l') m@((j,b):m') | i < j = (i,a) : mergeAssocWith f l' m | i > j = (j,b) : mergeAssocWith f l m' | otherwise = (i, f a b) : mergeAssocWith f l' m' interAssocWith' :: (Eq i) => (a -> a -> a) -> [(i,a)] -> [(i,a)] -> [(i,a)] interAssocWith' f l l' = [ (i, f a b) | (i,a) <- l, (j,b) <- l', i == j ] no_tested_prop_interAssocWith_correct :: [(Int,Int)] -> [(Int,Int)] -> Bool no_tested_prop_interAssocWith_correct xs ys = interAssocWith (*) l l' == interAssocWith' (*) l l' where l = List.sortBy (compare `on` fst) xs l' = List.sortBy (compare `on` fst) ys interAssocWith2 :: Ord i => (a -> a -> a) -> [(i,a)] -> [(i,a)] -> [(i,a)] interAssocWith2 f = zipAssocWith (const []) (const []) (const Nothing) (const Nothing) (\ a -> Just . f a) no_tested_prop_interAssocWith_correct2 :: [(Int,Int)] -> [(Int,Int)] -> Bool no_tested_prop_interAssocWith_correct2 xs ys = interAssocWith (*) xs ys == interAssocWith2 (*) xs ys where l = List.sortBy (compare `on` fst) xs l' = List.sortBy (compare `on` fst) ys prop_mul :: Size Int -> Property prop_mul sz = mapSize (`div` 2) $ forAll (two natural) $ \(c2, c3) -> forAll (matrix sz :: Gen TM) $ \m1 -> forAll (matrix (Size { rows = cols sz, cols = c2 })) $ \m2 -> forAll (matrix (Size { rows = c2, cols = c3 })) $ \m3 -> let m' = mult m1 m2 in isAssociative mult m1 m2 m3 && matrixInvariant m' && size m' == Size { rows = rows sz, cols = c2 } where mult = mul Semiring.intSemiring Template Haskell hack to make the following $ allProperties work under ghc-7.8 . | All tests as collected by ' allProperties ' . Using ' allProperties ' is convenient and superior to the manual tests :: TestTree tests = testProperties "Internal.Termination.SparseMatrix" $allProperties
9c4a737eef7cc1fe2fd0c35ce6fa6b5809417a03db7ca15e5735b0ac56b83cc9
incanter/incanter
cubic_spline_tests.clj
(ns incanter.interp.cubic-spline-tests (:use incanter.core) (:require [clojure.test :refer :all] [incanter.interp [cubic-spline :refer :all] [test-common :refer :all]])) (deftest compliance-test (doseq [impl [:clatrix :ndarray :persistent-vector :vectorz]] (set-current-implementation impl) (println (str "compliance test " impl)) (test-interpolate interpolate {:boundaries :natural}) (test-interpolate-grid interpolate-grid {:boundaries :natural}) (test-interpolate interpolate {:boundaries :closed}) (test-interpolate-grid interpolate-grid {:boundaries :closed}) (test-interpolate interpolate-hermite nil) (test-interpolate-grid interpolate-grid-hermite nil)))
null
https://raw.githubusercontent.com/incanter/incanter/e0a03aac237fcc60587278a36bd2e76266fc6356/modules/incanter-core/test/incanter/interp/cubic_spline_tests.clj
clojure
(ns incanter.interp.cubic-spline-tests (:use incanter.core) (:require [clojure.test :refer :all] [incanter.interp [cubic-spline :refer :all] [test-common :refer :all]])) (deftest compliance-test (doseq [impl [:clatrix :ndarray :persistent-vector :vectorz]] (set-current-implementation impl) (println (str "compliance test " impl)) (test-interpolate interpolate {:boundaries :natural}) (test-interpolate-grid interpolate-grid {:boundaries :natural}) (test-interpolate interpolate {:boundaries :closed}) (test-interpolate-grid interpolate-grid {:boundaries :closed}) (test-interpolate interpolate-hermite nil) (test-interpolate-grid interpolate-grid-hermite nil)))
e2f5eeca69191051388977aa311a3eecb49477823f39cee7240fc5759c76149c
homegrownlabs/sim-template
actions.clj
(ns {{namespace}}.actions "Support for actions, incl. logging success or failure to the action log." (:require [simulant.sim :as sim] [simulant.util :refer [e solo only]] [datomic.api :as d] [cheshire.core :as json])) (defmacro timed "Evaluate expression, returning a pair of [result nsecs-taken]" [expr] `(let [start# (System/nanoTime) result# ~expr nsecs# (- (System/nanoTime) start#)] [result# nsecs#])) (defn- ex-data-trimmed "Remove known anonymous functions in exception data (clj-http's `client`, in particular)" [ex] (let [{:keys [environment] :as data} (ex-data ex)] (-> (ex-data ex) (assoc :environment (dissoc (:environment ex) (symbol "client")))))) (defn- log-entity [action process response nsec extras] (merge (cond-> {:db/id (d/tempid :log) :actionLog/action (e action) :action/type (:action/type action) :actionLog/nsec nsec :actionLog/sim (e (-> process :sim/_processes only))} response (assoc :actionLog/responseMap (pr-str response) :actionLog/responseCode (:status response)) (get-in response [:headers "content-type"]) (assoc :actionLog/contentType (get-in response [:headers "content-type"]))) extras)) (defn- stack-trace [ex] (let [s (java.io.StringWriter.) p (java.io.PrintWriter. s)] (.printStackTrace ex p) (str s))) (defn- exception-entity [ex] (cond-> {:exception/type (.getName (class ex)) :exception/message (or (.getMessage ex) "No message available.") :exception/stackTrace (stack-trace ex)} (ex-data ex) (assoc :exception/exceptionData (json/generate-string (ex-data-trimmed ex))) (.getCause ex) (assoc :exception/cause (exception-entity (.getCause ex))))) (defn log [action process response nsec & {:as extras}] (let [log-fn (get sim/*services* :simulant.sim/actionLog)] (log-fn [(log-entity action process response nsec extras)]))) (defn log-error [action process exception nsec & {:as extras}] (let [log-fn (get sim/*services* :simulant.sim/actionLog) ex-ent (assoc extras :actionLog/exceptions (exception-entity exception)) resp (get (ex-data exception) :object)] (log-fn [(log-entity action process resp nsec ex-ent)])))
null
https://raw.githubusercontent.com/homegrownlabs/sim-template/2ddba7c1a3c2a17aff1e1ed30bada941bcb938a3/src/leiningen/new/sim_test/src/actions.clj
clojure
(ns {{namespace}}.actions "Support for actions, incl. logging success or failure to the action log." (:require [simulant.sim :as sim] [simulant.util :refer [e solo only]] [datomic.api :as d] [cheshire.core :as json])) (defmacro timed "Evaluate expression, returning a pair of [result nsecs-taken]" [expr] `(let [start# (System/nanoTime) result# ~expr nsecs# (- (System/nanoTime) start#)] [result# nsecs#])) (defn- ex-data-trimmed "Remove known anonymous functions in exception data (clj-http's `client`, in particular)" [ex] (let [{:keys [environment] :as data} (ex-data ex)] (-> (ex-data ex) (assoc :environment (dissoc (:environment ex) (symbol "client")))))) (defn- log-entity [action process response nsec extras] (merge (cond-> {:db/id (d/tempid :log) :actionLog/action (e action) :action/type (:action/type action) :actionLog/nsec nsec :actionLog/sim (e (-> process :sim/_processes only))} response (assoc :actionLog/responseMap (pr-str response) :actionLog/responseCode (:status response)) (get-in response [:headers "content-type"]) (assoc :actionLog/contentType (get-in response [:headers "content-type"]))) extras)) (defn- stack-trace [ex] (let [s (java.io.StringWriter.) p (java.io.PrintWriter. s)] (.printStackTrace ex p) (str s))) (defn- exception-entity [ex] (cond-> {:exception/type (.getName (class ex)) :exception/message (or (.getMessage ex) "No message available.") :exception/stackTrace (stack-trace ex)} (ex-data ex) (assoc :exception/exceptionData (json/generate-string (ex-data-trimmed ex))) (.getCause ex) (assoc :exception/cause (exception-entity (.getCause ex))))) (defn log [action process response nsec & {:as extras}] (let [log-fn (get sim/*services* :simulant.sim/actionLog)] (log-fn [(log-entity action process response nsec extras)]))) (defn log-error [action process exception nsec & {:as extras}] (let [log-fn (get sim/*services* :simulant.sim/actionLog) ex-ent (assoc extras :actionLog/exceptions (exception-entity exception)) resp (get (ex-data exception) :object)] (log-fn [(log-entity action process resp nsec ex-ent)])))
8bd1b304bb10b0fdfb21fdfb1d7ca9ae5118a78568f23fe240675116ca950537
vydd/sketch
pen.lisp
;;;; pen.lisp (in-package #:sketch) ;;; ____ _____ _ _ ;;; | _ \| ____| \ | | ;;; | |_) | _| | \| | | _ _ /| |___| |\ | |_| |_____|_| \_| (defstruct pen (fill nil) (stroke nil) (weight 1) (curve-steps 100)) (defmacro with-pen (pen &body body) (alexandria:once-only (pen) `(alexandria:with-gensyms (previous-pen) (progn (setf previous-pen (env-pen *env*) (env-pen *env*) ,pen) ,@body (setf (env-pen *env*) previous-pen))))) (defun set-pen (pen) "Sets environment pen to PEN." (setf (env-pen *env*) pen)) (defun flip-pen (pen) "Makes a new pen by swapping PEN's fill and stroke colors." (make-pen :weight (pen-weight pen) :stroke (pen-fill pen) :fill (pen-stroke pen) :weight (pen-weight pen) :curve-steps (pen-curve-steps pen))) (defun background (color) "Fills the sketch window with COLOR." (apply #'gl:clear-color (color-rgba color)) (gl:clear :color-buffer)) (let ((pen)) (defun make-default-pen () (setf pen (or pen (make-pen :weight 1 :fill +white+ :stroke +black+)))))
null
https://raw.githubusercontent.com/vydd/sketch/1a2e4bba865d5083889c68f8755ef6c0e2a7d5a2/src/pen.lisp
lisp
pen.lisp ____ _____ _ _ | _ \| ____| \ | | | |_) | _| | \| |
(in-package #:sketch) | _ _ /| |___| |\ | |_| |_____|_| \_| (defstruct pen (fill nil) (stroke nil) (weight 1) (curve-steps 100)) (defmacro with-pen (pen &body body) (alexandria:once-only (pen) `(alexandria:with-gensyms (previous-pen) (progn (setf previous-pen (env-pen *env*) (env-pen *env*) ,pen) ,@body (setf (env-pen *env*) previous-pen))))) (defun set-pen (pen) "Sets environment pen to PEN." (setf (env-pen *env*) pen)) (defun flip-pen (pen) "Makes a new pen by swapping PEN's fill and stroke colors." (make-pen :weight (pen-weight pen) :stroke (pen-fill pen) :fill (pen-stroke pen) :weight (pen-weight pen) :curve-steps (pen-curve-steps pen))) (defun background (color) "Fills the sketch window with COLOR." (apply #'gl:clear-color (color-rgba color)) (gl:clear :color-buffer)) (let ((pen)) (defun make-default-pen () (setf pen (or pen (make-pen :weight 1 :fill +white+ :stroke +black+)))))
a13bfa01869daab320a34eee6d4e17ee209d2c7f2ea6e153919fddd21c3d5357
ocaml/dune
promotion.mli
open Import val group : unit Cmd.t val promote : unit Cmd.t
null
https://raw.githubusercontent.com/ocaml/dune/3eaf83cd678009c586a0a506bc4755a3896be0f8/bin/promotion.mli
ocaml
open Import val group : unit Cmd.t val promote : unit Cmd.t
d63afcf70e53e0482f55efa9db2596c76aff35bca268c3b29d2963c9e58746db
ollef/sixty
Hydrated.hs
# LANGUAGE BlockArguments # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedRecordDot # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE NoFieldSelectors # module Error.Hydrated where import qualified Core.Pretty as Pretty import Data.Coerce import Data.Persist import qualified Data.Text as Text import qualified Data.Text.Unsafe as Text import Error (Error) import qualified Error import qualified Error.Parsing import qualified Module import Name (Name) import qualified Name import Plicity import qualified Position import Prettyprinter as Doc import Protolude hiding (moduleName) import Query (Query) import qualified Query import Rock import qualified Span import qualified System.Directory as Directory data Hydrated = Hydrated { filePath :: FilePath , lineColumn :: !Span.LineColumn , lineText :: !Text , error :: !Error } deriving (Show, Generic, Persist) headingAndBody :: (MonadFetch Query m, MonadIO m) => Error -> m (Doc ann, Doc ann) headingAndBody error = case error of Error.Parse _ parse -> pure ( "Parse error" , Doc.pretty (Error.Parsing.reason parse) <> case Error.Parsing.expected parse of [] -> mempty expected -> line <> "Expected: " <> hcat (punctuate comma $ Doc.pretty <$> expected) ) Error.DuplicateName definitionKind name _span -> do (filePath, maybeOldSpan) <- fetch $ Query.DefinitionPosition definitionKind name text <- fetch $ Query.FileText filePath let (lineColumn, _) = Position.lineColumn (fromMaybe 0 maybeOldSpan) text pure ( "Duplicate name:" <+> Doc.pretty name , Doc.pretty name <+> "has already been defined at" <+> Doc.pretty (Span.LineColumns lineColumn lineColumn) <> "." ) Error.ImportNotFound _ import_ -> let prettyModule = Doc.pretty import_.module_ in pure ( "Module not found:" <+> prettyModule , "The imported module" <+> prettyModule <+> "wasn't found in the current project." ) Error.MultipleFilesWithModuleName moduleName file1 file2 -> do file1' <- liftIO $ Directory.makeRelativeToCurrentDirectory file1 file2' <- liftIO $ Directory.makeRelativeToCurrentDirectory file2 pure ( "Multiple files use the module name" <+> Doc.pretty moduleName , "Both" <> line <> indent 2 (Doc.pretty file1') <> line <> "and" <> line <> indent 2 (Doc.pretty file2') <> line <> "use the same module name." ) Error.ModuleFileNameMismatch givenModuleName expectedModuleName _ _ -> pure ( "Module name doesn't match file name" , "The module name given in the module header is" <> line <> indent 2 (Doc.pretty givenModuleName) <> line <> "but from the file's location I expected it to be" <> line <> indent 2 (Doc.pretty expectedModuleName) <> "." ) Error.Elaboration definitionKind definitionName (Error.Spanned _ err') -> case err' of Error.NotInScope name -> pure ( "Not in scope:" <+> Doc.pretty name , Doc.pretty name <+> "is not defined here." ) Error.Ambiguous name constrCandidates nameCandidates -> pure ( "Ambiguous name:" <+> Doc.pretty name , "Candidates are:" <+> hcat ( punctuate comma $ Doc.pretty <$> toList constrCandidates <|> Doc.pretty <$> toList nameCandidates ) ) Error.DuplicateLetName name previousSpan -> do (filePath, maybeDefSpan) <- fetch $ Query.DefinitionPosition definitionKind definitionName text <- fetch $ Query.FileText filePath let (previousLineColumn, _) = Span.lineColumn (Span.absoluteFrom (fromMaybe 0 maybeDefSpan) previousSpan) text pure ( "Duplicate name in let block:" <+> Doc.pretty name , Doc.pretty name <+> "has already been defined at" <+> Doc.pretty previousLineColumn <> "." ) Error.UndefinedLetName name -> pure ( "Undefined name in let block:" <+> Doc.pretty name , "The type of" <+> Doc.pretty name <+> "was declared here, but not its value." ) Error.TypeMismatch mismatches -> do mismatches' <- forM mismatches \(inferred, expected) -> do inferred' <- prettyPrettyableTerm 0 inferred expected' <- prettyPrettyableTerm 0 expected pure (inferred', expected') pure ( "Type mismatch" , vcat ( intercalate ["", "while trying to unify"] [ [ "Inferred:" <+> inferred , "Expected:" <+> expected ] | (inferred, expected) <- toList mismatches' ] ) ) Error.OccursCheck mismatches -> do mismatches' <- forM mismatches \(inferred, expected) -> do inferred' <- prettyPrettyableTerm 0 inferred expected' <- prettyPrettyableTerm 0 expected pure (inferred', expected') pure ( "Occurs check failed" , vcat ( intercalate ["", "while trying to unify"] [ [ "Inferred:" <+> inferred , "Expected:" <+> expected ] | (inferred, expected) <- toList mismatches' ] ) <> line <> line <> "Unifying these values would produce a cyclic term." ) Error.UnsolvedMetaVariable index type_ -> do type' <- prettyPrettyableTerm 0 type_ pure ( "Unsolved meta variable" , "A meta variable was created here but was never solved:" <> line <> line <> Doc.pretty index <+> ":" <+> type' ) Error.NonExhaustivePatterns patterns -> do prettyPatterns <- mapM (mapM $ prettyPrettyablePattern $ Pretty.appPrec + 1) patterns pure ( "Non-exhaustive patterns" , "Patterns not matched:" <> line <> line <> vcat (hsep <$> prettyPatterns) ) Error.RedundantMatch matchKind -> pure ("Redundant" <+> Doc.pretty matchKind, "This" <+> Doc.pretty matchKind <+> "is unreachable") Error.IndeterminateIndexUnification fieldOrArg -> pure ( "Indeterminate index unification" , "I don't know whether this" <+> Doc.pretty fieldOrArg <+> "applies or not, because the unification of a constructor type's indices failed to produce a definite result." ) Error.PlicityMismatch fieldOrArg plicityMismatch -> pure $ case plicityMismatch of Error.Mismatch expected_ actual -> ( "Plicity mismatch" , "Expected an" <+> Doc.pretty expected_ <+> Doc.pretty fieldOrArg <+> "but got an" <+> Doc.pretty actual <+> Doc.pretty fieldOrArg ) Error.Missing expected_ -> ( "Missing" <+> Doc.pretty fieldOrArg , "Expected an" <+> Doc.pretty expected_ <+> Doc.pretty fieldOrArg <+> "but didn't get any" ) Error.Extra -> ( "Unexpected" <+> Doc.pretty fieldOrArg , "Didn't expect a" <+> Doc.pretty fieldOrArg <+> "here" ) Error.UnableToInferImplicitLambda -> pure ("Unable to infer implicit lambda", mempty) Error.ImplicitApplicationMismatch names term type_ -> do term' <- prettyPrettyableTerm 0 term type' <- prettyPrettyableTerm 0 type_ pure ( "Plicity mismatch" , "The term" <> line <> line <> indent 4 term' <> line <> line <> "doesn't accept implicit arguments named" <> line <> line <> indent 4 (hcat $ punctuate comma $ Doc.pretty <$> toList names) <> line <> line <> "Its type is:" <> line <> line <> type' ) pretty :: (MonadFetch Query m, MonadIO m) => Hydrated -> m (Doc ann) pretty h = do filePath <- liftIO $ Directory.makeRelativeToCurrentDirectory h.filePath (heading, body) <- headingAndBody h.error pure $ Doc.pretty filePath <> ":" <> Doc.pretty h.lineColumn <> ":" <+> heading <> line <> line <> body <> line <> line <> spannedLine where spannedLine = let Span.LineColumns (Position.LineColumn startLineNumber startColumnNumber) (Position.LineColumn endLineNumber endColumnNumber) = h.lineColumn lineNumberText = show (startLineNumber + 1) lineNumberTextLength = Text.lengthWord16 lineNumberText (spanLength, spanEnding) | startLineNumber == endLineNumber = (endColumnNumber - startColumnNumber, mempty) | otherwise = (Text.lengthWord16 h.lineText - startColumnNumber, "...") in Doc.pretty (Text.replicate (lineNumberTextLength + 1) " ") <> "| " <> line <> Doc.pretty lineNumberText <> " | " <> Doc.pretty h.lineText <> line <> Doc.pretty (Text.replicate (lineNumberTextLength + 1) " ") <> "| " <> Doc.pretty (Text.replicate startColumnNumber " " <> "^" <> Text.replicate (spanLength - 1) "~" <> spanEnding) fromError :: Error -> Task Query Hydrated fromError err = do (filePath, eofOrSpan) <- case err of Error.Parse filePath parseError -> pure ( filePath , (\p -> Span.Absolute p p) <$> Error.Parsing.position parseError ) Error.DuplicateName _definitionKind (Name.Qualified module_ _) span -> do maybeModuleFile <- fetch $ Query.ModuleFile module_ pure (fromMaybe "<no file>" maybeModuleFile, Right span) Error.ImportNotFound module_ import_ -> do maybeModuleFile <- fetch $ Query.ModuleFile module_ pure (fromMaybe "<no file>" maybeModuleFile, Right $ import_.span) Error.MultipleFilesWithModuleName _ _ file2 -> pure (file2, Right $ Span.Absolute 0 0) Error.ModuleFileNameMismatch _ _ span file -> pure (file, Right span) Error.Elaboration definitionKind name (Error.Spanned relativeSpan _) -> do (file, maybeAbsolutePosition) <- fetch $ Query.DefinitionPosition definitionKind name pure (file, Right $ Span.absoluteFrom (fromMaybe 0 maybeAbsolutePosition) relativeSpan) text <- fetch $ Query.FileText filePath let (lineColumn, lineText) = case eofOrSpan of Left Error.Parsing.EOF -> do let eofPos = Position.Absolute $ Text.lengthWord16 text Span.lineColumn (Span.Absolute eofPos eofPos) text Right span -> Span.lineColumn span text pure Hydrated { filePath = filePath , lineColumn = lineColumn , lineText = lineText , error = err } ------------------------------------------------------------------------------- lineNumber :: Hydrated -> Int lineNumber err = l where Span.LineColumns (Position.LineColumn l _) _ = err.lineColumn prettyPrettyableTerm :: MonadFetch Query m => Int -> Error.PrettyableTerm -> m (Doc ann) prettyPrettyableTerm prec (Error.PrettyableTerm moduleName_ names term) = do env <- Pretty.emptyM moduleName_ pure $ go names env where go :: [Name] -> Pretty.Environment v -> Doc ann go names' env' = case names' of [] -> Pretty.prettyTerm prec (coerce env') term name : names'' -> let (env'', _) = Pretty.extend env' name in go names'' env'' prettyPrettyablePattern :: MonadFetch Query m => Int -> (Plicity, Error.PrettyablePattern) -> m (Doc ann) prettyPrettyablePattern prec (plicity, Error.PrettyablePattern moduleName_ names pattern_) = do env <- Pretty.emptyM moduleName_ pure $ go names env where go :: [Name] -> Pretty.Environment v -> Doc ann go names' env' = case names' of [] -> Plicity.prettyAnnotation plicity <> Pretty.prettyPattern prec env' pattern_ name : names'' -> let (env'', _) = Pretty.extend env' name in go names'' env''
null
https://raw.githubusercontent.com/ollef/sixty/5d630ca6fde91da5a691dc7cd195f5cbf6491eb0/src/Error/Hydrated.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE OverloadedStrings # -----------------------------------------------------------------------------
# LANGUAGE BlockArguments # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedRecordDot # # LANGUAGE NoFieldSelectors # module Error.Hydrated where import qualified Core.Pretty as Pretty import Data.Coerce import Data.Persist import qualified Data.Text as Text import qualified Data.Text.Unsafe as Text import Error (Error) import qualified Error import qualified Error.Parsing import qualified Module import Name (Name) import qualified Name import Plicity import qualified Position import Prettyprinter as Doc import Protolude hiding (moduleName) import Query (Query) import qualified Query import Rock import qualified Span import qualified System.Directory as Directory data Hydrated = Hydrated { filePath :: FilePath , lineColumn :: !Span.LineColumn , lineText :: !Text , error :: !Error } deriving (Show, Generic, Persist) headingAndBody :: (MonadFetch Query m, MonadIO m) => Error -> m (Doc ann, Doc ann) headingAndBody error = case error of Error.Parse _ parse -> pure ( "Parse error" , Doc.pretty (Error.Parsing.reason parse) <> case Error.Parsing.expected parse of [] -> mempty expected -> line <> "Expected: " <> hcat (punctuate comma $ Doc.pretty <$> expected) ) Error.DuplicateName definitionKind name _span -> do (filePath, maybeOldSpan) <- fetch $ Query.DefinitionPosition definitionKind name text <- fetch $ Query.FileText filePath let (lineColumn, _) = Position.lineColumn (fromMaybe 0 maybeOldSpan) text pure ( "Duplicate name:" <+> Doc.pretty name , Doc.pretty name <+> "has already been defined at" <+> Doc.pretty (Span.LineColumns lineColumn lineColumn) <> "." ) Error.ImportNotFound _ import_ -> let prettyModule = Doc.pretty import_.module_ in pure ( "Module not found:" <+> prettyModule , "The imported module" <+> prettyModule <+> "wasn't found in the current project." ) Error.MultipleFilesWithModuleName moduleName file1 file2 -> do file1' <- liftIO $ Directory.makeRelativeToCurrentDirectory file1 file2' <- liftIO $ Directory.makeRelativeToCurrentDirectory file2 pure ( "Multiple files use the module name" <+> Doc.pretty moduleName , "Both" <> line <> indent 2 (Doc.pretty file1') <> line <> "and" <> line <> indent 2 (Doc.pretty file2') <> line <> "use the same module name." ) Error.ModuleFileNameMismatch givenModuleName expectedModuleName _ _ -> pure ( "Module name doesn't match file name" , "The module name given in the module header is" <> line <> indent 2 (Doc.pretty givenModuleName) <> line <> "but from the file's location I expected it to be" <> line <> indent 2 (Doc.pretty expectedModuleName) <> "." ) Error.Elaboration definitionKind definitionName (Error.Spanned _ err') -> case err' of Error.NotInScope name -> pure ( "Not in scope:" <+> Doc.pretty name , Doc.pretty name <+> "is not defined here." ) Error.Ambiguous name constrCandidates nameCandidates -> pure ( "Ambiguous name:" <+> Doc.pretty name , "Candidates are:" <+> hcat ( punctuate comma $ Doc.pretty <$> toList constrCandidates <|> Doc.pretty <$> toList nameCandidates ) ) Error.DuplicateLetName name previousSpan -> do (filePath, maybeDefSpan) <- fetch $ Query.DefinitionPosition definitionKind definitionName text <- fetch $ Query.FileText filePath let (previousLineColumn, _) = Span.lineColumn (Span.absoluteFrom (fromMaybe 0 maybeDefSpan) previousSpan) text pure ( "Duplicate name in let block:" <+> Doc.pretty name , Doc.pretty name <+> "has already been defined at" <+> Doc.pretty previousLineColumn <> "." ) Error.UndefinedLetName name -> pure ( "Undefined name in let block:" <+> Doc.pretty name , "The type of" <+> Doc.pretty name <+> "was declared here, but not its value." ) Error.TypeMismatch mismatches -> do mismatches' <- forM mismatches \(inferred, expected) -> do inferred' <- prettyPrettyableTerm 0 inferred expected' <- prettyPrettyableTerm 0 expected pure (inferred', expected') pure ( "Type mismatch" , vcat ( intercalate ["", "while trying to unify"] [ [ "Inferred:" <+> inferred , "Expected:" <+> expected ] | (inferred, expected) <- toList mismatches' ] ) ) Error.OccursCheck mismatches -> do mismatches' <- forM mismatches \(inferred, expected) -> do inferred' <- prettyPrettyableTerm 0 inferred expected' <- prettyPrettyableTerm 0 expected pure (inferred', expected') pure ( "Occurs check failed" , vcat ( intercalate ["", "while trying to unify"] [ [ "Inferred:" <+> inferred , "Expected:" <+> expected ] | (inferred, expected) <- toList mismatches' ] ) <> line <> line <> "Unifying these values would produce a cyclic term." ) Error.UnsolvedMetaVariable index type_ -> do type' <- prettyPrettyableTerm 0 type_ pure ( "Unsolved meta variable" , "A meta variable was created here but was never solved:" <> line <> line <> Doc.pretty index <+> ":" <+> type' ) Error.NonExhaustivePatterns patterns -> do prettyPatterns <- mapM (mapM $ prettyPrettyablePattern $ Pretty.appPrec + 1) patterns pure ( "Non-exhaustive patterns" , "Patterns not matched:" <> line <> line <> vcat (hsep <$> prettyPatterns) ) Error.RedundantMatch matchKind -> pure ("Redundant" <+> Doc.pretty matchKind, "This" <+> Doc.pretty matchKind <+> "is unreachable") Error.IndeterminateIndexUnification fieldOrArg -> pure ( "Indeterminate index unification" , "I don't know whether this" <+> Doc.pretty fieldOrArg <+> "applies or not, because the unification of a constructor type's indices failed to produce a definite result." ) Error.PlicityMismatch fieldOrArg plicityMismatch -> pure $ case plicityMismatch of Error.Mismatch expected_ actual -> ( "Plicity mismatch" , "Expected an" <+> Doc.pretty expected_ <+> Doc.pretty fieldOrArg <+> "but got an" <+> Doc.pretty actual <+> Doc.pretty fieldOrArg ) Error.Missing expected_ -> ( "Missing" <+> Doc.pretty fieldOrArg , "Expected an" <+> Doc.pretty expected_ <+> Doc.pretty fieldOrArg <+> "but didn't get any" ) Error.Extra -> ( "Unexpected" <+> Doc.pretty fieldOrArg , "Didn't expect a" <+> Doc.pretty fieldOrArg <+> "here" ) Error.UnableToInferImplicitLambda -> pure ("Unable to infer implicit lambda", mempty) Error.ImplicitApplicationMismatch names term type_ -> do term' <- prettyPrettyableTerm 0 term type' <- prettyPrettyableTerm 0 type_ pure ( "Plicity mismatch" , "The term" <> line <> line <> indent 4 term' <> line <> line <> "doesn't accept implicit arguments named" <> line <> line <> indent 4 (hcat $ punctuate comma $ Doc.pretty <$> toList names) <> line <> line <> "Its type is:" <> line <> line <> type' ) pretty :: (MonadFetch Query m, MonadIO m) => Hydrated -> m (Doc ann) pretty h = do filePath <- liftIO $ Directory.makeRelativeToCurrentDirectory h.filePath (heading, body) <- headingAndBody h.error pure $ Doc.pretty filePath <> ":" <> Doc.pretty h.lineColumn <> ":" <+> heading <> line <> line <> body <> line <> line <> spannedLine where spannedLine = let Span.LineColumns (Position.LineColumn startLineNumber startColumnNumber) (Position.LineColumn endLineNumber endColumnNumber) = h.lineColumn lineNumberText = show (startLineNumber + 1) lineNumberTextLength = Text.lengthWord16 lineNumberText (spanLength, spanEnding) | startLineNumber == endLineNumber = (endColumnNumber - startColumnNumber, mempty) | otherwise = (Text.lengthWord16 h.lineText - startColumnNumber, "...") in Doc.pretty (Text.replicate (lineNumberTextLength + 1) " ") <> "| " <> line <> Doc.pretty lineNumberText <> " | " <> Doc.pretty h.lineText <> line <> Doc.pretty (Text.replicate (lineNumberTextLength + 1) " ") <> "| " <> Doc.pretty (Text.replicate startColumnNumber " " <> "^" <> Text.replicate (spanLength - 1) "~" <> spanEnding) fromError :: Error -> Task Query Hydrated fromError err = do (filePath, eofOrSpan) <- case err of Error.Parse filePath parseError -> pure ( filePath , (\p -> Span.Absolute p p) <$> Error.Parsing.position parseError ) Error.DuplicateName _definitionKind (Name.Qualified module_ _) span -> do maybeModuleFile <- fetch $ Query.ModuleFile module_ pure (fromMaybe "<no file>" maybeModuleFile, Right span) Error.ImportNotFound module_ import_ -> do maybeModuleFile <- fetch $ Query.ModuleFile module_ pure (fromMaybe "<no file>" maybeModuleFile, Right $ import_.span) Error.MultipleFilesWithModuleName _ _ file2 -> pure (file2, Right $ Span.Absolute 0 0) Error.ModuleFileNameMismatch _ _ span file -> pure (file, Right span) Error.Elaboration definitionKind name (Error.Spanned relativeSpan _) -> do (file, maybeAbsolutePosition) <- fetch $ Query.DefinitionPosition definitionKind name pure (file, Right $ Span.absoluteFrom (fromMaybe 0 maybeAbsolutePosition) relativeSpan) text <- fetch $ Query.FileText filePath let (lineColumn, lineText) = case eofOrSpan of Left Error.Parsing.EOF -> do let eofPos = Position.Absolute $ Text.lengthWord16 text Span.lineColumn (Span.Absolute eofPos eofPos) text Right span -> Span.lineColumn span text pure Hydrated { filePath = filePath , lineColumn = lineColumn , lineText = lineText , error = err } lineNumber :: Hydrated -> Int lineNumber err = l where Span.LineColumns (Position.LineColumn l _) _ = err.lineColumn prettyPrettyableTerm :: MonadFetch Query m => Int -> Error.PrettyableTerm -> m (Doc ann) prettyPrettyableTerm prec (Error.PrettyableTerm moduleName_ names term) = do env <- Pretty.emptyM moduleName_ pure $ go names env where go :: [Name] -> Pretty.Environment v -> Doc ann go names' env' = case names' of [] -> Pretty.prettyTerm prec (coerce env') term name : names'' -> let (env'', _) = Pretty.extend env' name in go names'' env'' prettyPrettyablePattern :: MonadFetch Query m => Int -> (Plicity, Error.PrettyablePattern) -> m (Doc ann) prettyPrettyablePattern prec (plicity, Error.PrettyablePattern moduleName_ names pattern_) = do env <- Pretty.emptyM moduleName_ pure $ go names env where go :: [Name] -> Pretty.Environment v -> Doc ann go names' env' = case names' of [] -> Plicity.prettyAnnotation plicity <> Pretty.prettyPattern prec env' pattern_ name : names'' -> let (env'', _) = Pretty.extend env' name in go names'' env''
c1a069850142e7870299e22f70cace934673cb8a030adbc2ce87f71340fbd903
ghcjs/jsaddle-dom
SVGPointList.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.SVGPointList (clear, initialize, initialize_, getItem, getItem_, insertItemBefore, insertItemBefore_, replaceItem, replaceItem_, removeItem, removeItem_, appendItem, appendItem_, getNumberOfItems, SVGPointList(..), gTypeSVGPointList) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/SVGPointList.clear Mozilla SVGPointList.clear documentation > clear :: (MonadDOM m) => SVGPointList -> m () clear self = liftDOM (void (self ^. jsf "clear" ())) | < -US/docs/Web/API/SVGPointList.initialize Mozilla SVGPointList.initialize documentation > initialize :: (MonadDOM m) => SVGPointList -> SVGPoint -> m SVGPoint initialize self item = liftDOM ((self ^. jsf "initialize" [toJSVal item]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.initialize Mozilla SVGPointList.initialize documentation > initialize_ :: (MonadDOM m) => SVGPointList -> SVGPoint -> m () initialize_ self item = liftDOM (void (self ^. jsf "initialize" [toJSVal item])) | < -US/docs/Web/API/SVGPointList.getItem Mozilla SVGPointList.getItem documentation > getItem :: (MonadDOM m) => SVGPointList -> Word -> m SVGPoint getItem self index = liftDOM ((self ^. jsf "getItem" [toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.getItem Mozilla SVGPointList.getItem documentation > getItem_ :: (MonadDOM m) => SVGPointList -> Word -> m () getItem_ self index = liftDOM (void (self ^. jsf "getItem" [toJSVal index])) | < -US/docs/Web/API/SVGPointList.insertItemBefore Mozilla SVGPointList.insertItemBefore documentation > insertItemBefore :: (MonadDOM m) => SVGPointList -> SVGPoint -> Word -> m SVGPoint insertItemBefore self item index = liftDOM ((self ^. jsf "insertItemBefore" [toJSVal item, toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.insertItemBefore Mozilla SVGPointList.insertItemBefore documentation > insertItemBefore_ :: (MonadDOM m) => SVGPointList -> SVGPoint -> Word -> m () insertItemBefore_ self item index = liftDOM (void (self ^. jsf "insertItemBefore" [toJSVal item, toJSVal index])) | < -US/docs/Web/API/SVGPointList.replaceItem Mozilla SVGPointList.replaceItem documentation > replaceItem :: (MonadDOM m) => SVGPointList -> SVGPoint -> Word -> m SVGPoint replaceItem self item index = liftDOM ((self ^. jsf "replaceItem" [toJSVal item, toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.replaceItem Mozilla SVGPointList.replaceItem documentation > replaceItem_ :: (MonadDOM m) => SVGPointList -> SVGPoint -> Word -> m () replaceItem_ self item index = liftDOM (void (self ^. jsf "replaceItem" [toJSVal item, toJSVal index])) | < -US/docs/Web/API/SVGPointList.removeItem Mozilla documentation > removeItem :: (MonadDOM m) => SVGPointList -> Word -> m SVGPoint removeItem self index = liftDOM ((self ^. jsf "removeItem" [toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.removeItem Mozilla documentation > removeItem_ :: (MonadDOM m) => SVGPointList -> Word -> m () removeItem_ self index = liftDOM (void (self ^. jsf "removeItem" [toJSVal index])) | < -US/docs/Web/API/SVGPointList.appendItem Mozilla SVGPointList.appendItem documentation > appendItem :: (MonadDOM m) => SVGPointList -> SVGPoint -> m SVGPoint appendItem self item = liftDOM ((self ^. jsf "appendItem" [toJSVal item]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.appendItem Mozilla SVGPointList.appendItem documentation > appendItem_ :: (MonadDOM m) => SVGPointList -> SVGPoint -> m () appendItem_ self item = liftDOM (void (self ^. jsf "appendItem" [toJSVal item])) -- | <-US/docs/Web/API/SVGPointList.numberOfItems Mozilla SVGPointList.numberOfItems documentation> getNumberOfItems :: (MonadDOM m) => SVGPointList -> m Word getNumberOfItems self = liftDOM (round <$> ((self ^. js "numberOfItems") >>= valToNumber))
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/SVGPointList.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | <-US/docs/Web/API/SVGPointList.numberOfItems Mozilla SVGPointList.numberOfItems documentation>
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.SVGPointList (clear, initialize, initialize_, getItem, getItem_, insertItemBefore, insertItemBefore_, replaceItem, replaceItem_, removeItem, removeItem_, appendItem, appendItem_, getNumberOfItems, SVGPointList(..), gTypeSVGPointList) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/SVGPointList.clear Mozilla SVGPointList.clear documentation > clear :: (MonadDOM m) => SVGPointList -> m () clear self = liftDOM (void (self ^. jsf "clear" ())) | < -US/docs/Web/API/SVGPointList.initialize Mozilla SVGPointList.initialize documentation > initialize :: (MonadDOM m) => SVGPointList -> SVGPoint -> m SVGPoint initialize self item = liftDOM ((self ^. jsf "initialize" [toJSVal item]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.initialize Mozilla SVGPointList.initialize documentation > initialize_ :: (MonadDOM m) => SVGPointList -> SVGPoint -> m () initialize_ self item = liftDOM (void (self ^. jsf "initialize" [toJSVal item])) | < -US/docs/Web/API/SVGPointList.getItem Mozilla SVGPointList.getItem documentation > getItem :: (MonadDOM m) => SVGPointList -> Word -> m SVGPoint getItem self index = liftDOM ((self ^. jsf "getItem" [toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.getItem Mozilla SVGPointList.getItem documentation > getItem_ :: (MonadDOM m) => SVGPointList -> Word -> m () getItem_ self index = liftDOM (void (self ^. jsf "getItem" [toJSVal index])) | < -US/docs/Web/API/SVGPointList.insertItemBefore Mozilla SVGPointList.insertItemBefore documentation > insertItemBefore :: (MonadDOM m) => SVGPointList -> SVGPoint -> Word -> m SVGPoint insertItemBefore self item index = liftDOM ((self ^. jsf "insertItemBefore" [toJSVal item, toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.insertItemBefore Mozilla SVGPointList.insertItemBefore documentation > insertItemBefore_ :: (MonadDOM m) => SVGPointList -> SVGPoint -> Word -> m () insertItemBefore_ self item index = liftDOM (void (self ^. jsf "insertItemBefore" [toJSVal item, toJSVal index])) | < -US/docs/Web/API/SVGPointList.replaceItem Mozilla SVGPointList.replaceItem documentation > replaceItem :: (MonadDOM m) => SVGPointList -> SVGPoint -> Word -> m SVGPoint replaceItem self item index = liftDOM ((self ^. jsf "replaceItem" [toJSVal item, toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.replaceItem Mozilla SVGPointList.replaceItem documentation > replaceItem_ :: (MonadDOM m) => SVGPointList -> SVGPoint -> Word -> m () replaceItem_ self item index = liftDOM (void (self ^. jsf "replaceItem" [toJSVal item, toJSVal index])) | < -US/docs/Web/API/SVGPointList.removeItem Mozilla documentation > removeItem :: (MonadDOM m) => SVGPointList -> Word -> m SVGPoint removeItem self index = liftDOM ((self ^. jsf "removeItem" [toJSVal index]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.removeItem Mozilla documentation > removeItem_ :: (MonadDOM m) => SVGPointList -> Word -> m () removeItem_ self index = liftDOM (void (self ^. jsf "removeItem" [toJSVal index])) | < -US/docs/Web/API/SVGPointList.appendItem Mozilla SVGPointList.appendItem documentation > appendItem :: (MonadDOM m) => SVGPointList -> SVGPoint -> m SVGPoint appendItem self item = liftDOM ((self ^. jsf "appendItem" [toJSVal item]) >>= fromJSValUnchecked) | < -US/docs/Web/API/SVGPointList.appendItem Mozilla SVGPointList.appendItem documentation > appendItem_ :: (MonadDOM m) => SVGPointList -> SVGPoint -> m () appendItem_ self item = liftDOM (void (self ^. jsf "appendItem" [toJSVal item])) getNumberOfItems :: (MonadDOM m) => SVGPointList -> m Word getNumberOfItems self = liftDOM (round <$> ((self ^. js "numberOfItems") >>= valToNumber))
5f8b36d6e45c2d5e1f78aecde3906907b53a60b82da34bb3e4a466813ced75fb
tnelson/FlowLog
Flowlog_Types.ml
(****************************************************************) (* Most type definitions and a few helpers *) (* Includes both AST-level and program-level types *) (****************************************************************) open Printf open ExtList.List open NetCore_Types (***********************************************) Formula types are shared by AST and program type term = | TConst of string | TVar of string | TField of string * string;; type formula = | FTrue | FFalse | FEquals of term * term pkt.nwsrc in 10.0.1.1/24 | FIn of term * term * term | FNot of formula module , , args | FAtom of string * string * term list | FAnd of formula * formula | FOr of formula * formula;; type typeid = string;; (**************************************************) AST - level definitions for syntactic rules , etc . type action = | ADelete of string * term list * formula | AInsert of string * term list * formula | ADo of string * term list * formula (* pkt var to stash; where clause; until clause; then clause*) | AStash of term * formula * formula * action list | AForward of term * formula * int option;; type refresh = (* number, units *) | RefreshTimeout of int * string | RefreshNever | RefreshEvery;; (*type assignment = {afield: string; atupvar: string};; *) SameAsOnFields : Unary relation . Type of argument is same type from the ON trigger . Used by " forward " . : Any arity , any types . Used for behavior like " print"ing . Fixedfield : single event type Used by "forward". AnyFields: Any arity, any types. Used for behavior like "print"ing. Fixedfield: single event type *) type outgoing_fields = | SameAsOnFields | AnyFields | FixedEvent of typeid;; type spec_out = | OutForward | OutEmit of typeid | OutLoopback | OutPrint | OutSend of typeid * string * string;; Where is the incoming event coming from ? Used to disambiguate packets coming from the DP vs. coming from the CP . Used to disambiguate packets coming from the DP vs. coming from the CP. *) (* TODO: this really ought to be part of every event, not standalone *) type eventsource = | IncDP | IncCP | IncThrift;; type sreactive = (* table name, query name, ip, port, refresh settings *) | ReactRemote of string * typeid list * string * string * string * refresh (* out relation name, outgoing type, spec*) | ReactOut of string * outgoing_fields * spec_out (* incoming event type, trigger relation name*) | ReactInc of typeid * eventsource * string;; type sdecl = | DeclTable of string * typeid list | DeclRemoteTable of string * typeid list | DeclInc of string * string | DeclOut of string * outgoing_fields | DeclEvent of string * (string * typeid) list;; AST elements pre desugaring type astdecl = | ASTDeclVar of string * typeid * term option | ASTDeclTable of string * typeid list | ASTDeclRemoteTable of string * typeid list | ASTDeclInc of string * string | ASTDeclOut of string * outgoing_fields | ASTDeclEvent of string * (string * typeid) list;; type srule = {onrel: string; onvar: string; action: action};; type aststmt = | ASTReactive of sreactive | ASTDecl of astdecl | ASTRule of srule;; type stmt = | SReactive of sreactive | SDecl of sdecl | SRule of srule;; type flowlog_ast = {includes: string list; statements: aststmt list};; (*************************************************************) (* Split out a formula by ORs for use with XSB *) (* In new semantics, no longer have "on" in clause body. It just gets made an EDB fact. *) (* REQUIRE: head, body fmlas atomic or equality *) type clause = { orig_rule: srule; head: formula; body: formula; (* should be always conjunctive *) };; Every event has a name and a string of fieldnames , each with a type . type event_def = { eventname: string; evfields: (string * typeid) list };; (* partial-evaluation needs to know what variable is being used for the old packet in a clause. Also store dependencies and handle to current NetCore policy for efficiency *) type triggered_clause = {clause: clause; oldpkt: string; dependencies: string list; id: string};; type outgoing_def = { outname: string; outarity: outgoing_fields; react: spec_out};; type queryid = string;; type agent = string * string;; type table_source = | LocalTable | RemoteTable of queryid * agent * refresh;; type table_def = { tablename: string; tablearity: typeid list; source: table_source };; (* triggers: inrels -> outrels *) We use 's built in find_all function to extend the values to string list . type program_memos = {out_triggers: (string, string) Hashtbl.t; insert_triggers: (string, string) Hashtbl.t; delete_triggers: (string, string) Hashtbl.t; tablemap: (string, table_def) Hashtbl.t; eventmap: (string, event_def) Hashtbl.t; incomingmap: ((string*eventsource),string) Hashtbl.t; outgoingmap: (string, outgoing_def) Hashtbl.t; atoms_used_in_bodies: formula list; };; type flowlog_program = { desugared_decls: sdecl list; (* for use in errors, alloy conversion, etc. *) desugared_reacts: sreactive list; (* for use in errors, alloy conversion, etc. *) vartablenames: string list; (* for state tables only (local or remote)*) tables: table_def list; (* events and outgoings will require some built_ins *) incomings are entirely defined by event defns events: event_def list; outgoings: outgoing_def list; clauses: clause list; (* subsets of <clauses> used to avoid recomputation*) can_fully_compile_to_fwd_clauses: triggered_clause list; weakened_cannot_compile_pt_clauses: triggered_clause list; (* These are *UNWEAKENED* for direct use in XSB. *) not_fully_compiled_clauses: clause list; (* Additional info used to avoid recomputation *) memos: program_memos};; (* context for values given by decls *) module StringMap = Map.Make(String);; type event = { typeid: string; values: string StringMap.t};; module FmlaMap = Map.Make(struct type t = formula let compare = compare end);; (*************************************************************) let allportsatom = SwitchAction({id with outPort = NetCore_Pattern.All});; type printmode = Verbose | Brief;; type xsbmode = Xsb | XsbForcePositive | XsbAddUnderscoreVars;; (*************************************************************) let rec gather_nonneg_equalities ?(exempt: term list = []) ?(vars_only: bool = false) (f: formula) (neg: bool): (term * term) list = match f with | FTrue -> [] | FFalse -> [] Make sure to use WHEN here , not a condition after - > . Suppose exempt=[y ] and y = x. Want 2nd option to apply . | FEquals((TVar(_) as thevar), t) when (not neg) && (not (thevar = t)) && (not (mem thevar exempt)) -> [(thevar, t)] | FEquals(t, (TVar(_) as thevar)) when (not neg) && (not (thevar = t)) && (not (mem thevar exempt)) -> [(thevar, t)] | FEquals(t1, t2) when (not neg) && (not vars_only) -> [(t1, t2)] | FEquals(_, _) -> [] | FIn(_,_,_) -> [] | FAtom(modstr, relstr, argterms) -> [] | FOr(f1, f2) -> unique ((gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f1 neg) @ (gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f2 neg)) | FAnd(f1, f2) -> unique ((gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f1 neg) @ (gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f2 neg)) | FNot(f2) -> (gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f2 (not neg));; For every non - negated equality that has one TVar in it that is NOT in the exempt list , produces a tuple for substitution . ( Exempt list is so that vars in the head of a clause wo n't get substituted out ) that is NOT in the exempt list, produces a tuple for substitution. (Exempt list is so that vars in the head of a clause won't get substituted out) *) let rec gather_nonneg_equalities_involving_vars ?(exempt: term list = []) (f: formula) (neg: bool): (term * term) list = gather_nonneg_equalities ~exempt:exempt ~vars_only:true f neg;; exception SubstitutionLedToInconsistency of formula;; (* If about to substitute in something like 5=7, abort because the whole conjunction is unsatisfiable Alternatively, return a FFalse *) let equals_if_consistent (report_inconsistency: bool) (t1: term) (t2: term): formula = match (t1, t2) with | (TConst(str1), TConst(str2)) when str1 <> str2 -> if report_inconsistency then raise (SubstitutionLedToInconsistency((FEquals(t1, t2)))) else FFalse | _ -> FEquals(t1, t2);; let int32_allones = Int32.lognot (Int32.zero);; let is_in_ip_range (v: Int32.t) (addr: Int32.t) (mask: int): bool = MAXINT ( 32 bit ) let nwfield = Int32.shift_left int32_allones (32-mask) in (Int32.logand v nwfield) = (Int32.logand addr nwfield);; let in_if_consistent (report_inconsistency: bool) (v: term) (addr: term) (mask: term): formula = match v, addr, mask with | TConst(vval), TConst(addrval), TConst(maskval) when not (is_in_ip_range (Int32.of_string vval) (Int32.of_string addrval) (int_of_string maskval)) -> if report_inconsistency then raise (SubstitutionLedToInconsistency((FIn(v, addr, mask)))) else FFalse | _ -> FIn(v, addr, mask);; (* f[v -> t] Substitutions of variables apply to fields of that variable, too. *) let rec substitute_term (report_inconsistency: bool) (f: formula) (v: term) (t: term): formula = let substitute_term_result (curr: term): term = match curr, v, t with | x, y, _ when x = y -> t curr is a field of v , replace with field of t | TField(x, fx), TVar(y), TVar(z) when x = y -> TField(z, fx) | _ -> curr in match f with | FTrue -> f | FFalse -> f | FEquals(t1, t2) -> let st1 = substitute_term_result t1 in let st2 = substitute_term_result t2 in (* Remove fmlas which will be "x=x"; avoids inf. loop. *) if st1 = st2 then FTrue else equals_if_consistent report_inconsistency st1 st2 | FIn(t, addr, mask) -> let newt = substitute_term_result t in let newaddr = substitute_term_result addr in let newmask = substitute_term_result mask in in_if_consistent report_inconsistency newt newaddr newmask | FAtom(modstr, relstr, argterms) -> let newargterms = map (fun arg -> substitute_term_result arg) argterms in FAtom(modstr, relstr, newargterms) | FOr(f1, f2) -> let subs1 = substitute_term report_inconsistency f1 v t in let subs2 = substitute_term report_inconsistency f2 v t in if subs1 = FFalse then subs2 else if subs2 = FFalse then subs1 else FOr(subs1, subs2) | FAnd(f1, f2) -> remove superfluous FTrues / FFalses let subs1 = substitute_term report_inconsistency f1 v t in let subs2 = substitute_term report_inconsistency f2 v t in if subs1 = FTrue then subs2 else if subs2 = FTrue then subs1 else FAnd(subs1, subs2) | FNot(f2) -> let innerresult = substitute_term report_inconsistency f2 v t in if innerresult = FFalse then FTrue else if innerresult = FTrue then FFalse else FNot(innerresult);; let substitute_terms ?(report_inconsistency: bool = true) (f: formula) (subs: (term * term) list): formula = fold_left (fun fm (v, t) -> substitute_term report_inconsistency fm v t) f subs;; (* assume a clause body. exempt gives the terms that are in the head, and thus need to not be removed *) let rec minimize_variables ?(exempt: term list = []) (f: formula): formula = (* OPTIMIZATION: don't need to do gathering step repeatedly: *) let var_equals_fmlas = gather_nonneg_equalities_involving_vars ~exempt:exempt f false in (*printf "at fmla = %s\n%!" (string_of_formula f); iter (fun pr -> let (t1, t2) = pr in (printf "pair: %s, %s\n%!" (string_of_term t1) (string_of_term t2))) var_equals_fmlas; *) if length var_equals_fmlas < 1 then f else select equalities involving constants first , so we do n't lose their context let constpairs = filter (function | (TVar(_), TConst(_)) -> true | _ -> false) var_equals_fmlas in let (x, t) = if length constpairs > 0 then hd constpairs else hd var_equals_fmlas in subst process will discover inconsistency due to multiple vals e.g. x=7 , x=9 , and throw exception try let newf = (substitute_term true f x t) in printf " will subs out % s to % s. New is : % s.\n% ! " ( string_of_term x ) ( string_of_term t ) ( string_of_formula newf ) ; minimize_variables ~exempt:exempt newf with SubstitutionLedToInconsistency(_) -> FFalse;; let add_conjunct_to_action (act: action) (f: formula) = match act with | _ when f = FTrue -> act | ADelete(a, b, fmla) -> ADelete(a, b, FAnd(f, fmla)) | AInsert(a, b, fmla) -> AInsert(a, b, FAnd(f, fmla)) | ADo(a, b, fmla) -> ADo(a, b, FAnd(f, fmla)) | AForward(p, fmla, tout) -> AForward(p, FAnd(f, fmla), tout) | AStash(p, where, until, thens) -> AStash(p, FAnd(f, where), until, thens);; (* | AForward(p, fmla, tout) -> | AStash(p, where, until, thens) -> *) (************************************************************************************) BUILT - IN CONSTANTS , MAGIC - NUMBERS , EVENTS , REACTIVE DEFINITIONS , ETC . (* Packet flavors and built-in relations are governed by the Flowlog_Packets *) (************************************************************************************) (* Note: all program text is lowercased by parser *) These are prepended to relation names when we pass insert / delete rules to Prolog let plus_prefix = "plus";; let minus_prefix = "minus";; (* Avoid using strings for hard-coded type names and relation names. Use these definitions instead. *) let packet_in_relname = "packet_in";; let switch_reg_relname = "switch_port";; let switch_down_relname = "switch_down";; let startup_relname = "startup";; let switch_has_port_relname = "switch_has_port";;
null
https://raw.githubusercontent.com/tnelson/FlowLog/8be5051a4b3fa05c6299cdfa70f6a3def3893cf1/interpreter/Flowlog_Types.ml
ocaml
************************************************************** Most type definitions and a few helpers Includes both AST-level and program-level types ************************************************************** ********************************************* ************************************************ pkt var to stash; where clause; until clause; then clause number, units type assignment = {afield: string; atupvar: string};; TODO: this really ought to be part of every event, not standalone table name, query name, ip, port, refresh settings out relation name, outgoing type, spec incoming event type, trigger relation name *********************************************************** Split out a formula by ORs for use with XSB In new semantics, no longer have "on" in clause body. It just gets made an EDB fact. REQUIRE: head, body fmlas atomic or equality should be always conjunctive partial-evaluation needs to know what variable is being used for the old packet in a clause. Also store dependencies and handle to current NetCore policy for efficiency triggers: inrels -> outrels for use in errors, alloy conversion, etc. for use in errors, alloy conversion, etc. for state tables only (local or remote) events and outgoings will require some built_ins subsets of <clauses> used to avoid recomputation These are *UNWEAKENED* for direct use in XSB. Additional info used to avoid recomputation context for values given by decls *********************************************************** *********************************************************** If about to substitute in something like 5=7, abort because the whole conjunction is unsatisfiable Alternatively, return a FFalse f[v -> t] Substitutions of variables apply to fields of that variable, too. Remove fmlas which will be "x=x"; avoids inf. loop. assume a clause body. exempt gives the terms that are in the head, and thus need to not be removed OPTIMIZATION: don't need to do gathering step repeatedly: printf "at fmla = %s\n%!" (string_of_formula f); iter (fun pr -> let (t1, t2) = pr in (printf "pair: %s, %s\n%!" (string_of_term t1) (string_of_term t2))) var_equals_fmlas; | AForward(p, fmla, tout) -> | AStash(p, where, until, thens) -> ********************************************************************************** Packet flavors and built-in relations are governed by the Flowlog_Packets ********************************************************************************** Note: all program text is lowercased by parser Avoid using strings for hard-coded type names and relation names. Use these definitions instead.
open Printf open ExtList.List open NetCore_Types Formula types are shared by AST and program type term = | TConst of string | TVar of string | TField of string * string;; type formula = | FTrue | FFalse | FEquals of term * term pkt.nwsrc in 10.0.1.1/24 | FIn of term * term * term | FNot of formula module , , args | FAtom of string * string * term list | FAnd of formula * formula | FOr of formula * formula;; type typeid = string;; AST - level definitions for syntactic rules , etc . type action = | ADelete of string * term list * formula | AInsert of string * term list * formula | ADo of string * term list * formula | AStash of term * formula * formula * action list | AForward of term * formula * int option;; type refresh = | RefreshTimeout of int * string | RefreshNever | RefreshEvery;; SameAsOnFields : Unary relation . Type of argument is same type from the ON trigger . Used by " forward " . : Any arity , any types . Used for behavior like " print"ing . Fixedfield : single event type Used by "forward". AnyFields: Any arity, any types. Used for behavior like "print"ing. Fixedfield: single event type *) type outgoing_fields = | SameAsOnFields | AnyFields | FixedEvent of typeid;; type spec_out = | OutForward | OutEmit of typeid | OutLoopback | OutPrint | OutSend of typeid * string * string;; Where is the incoming event coming from ? Used to disambiguate packets coming from the DP vs. coming from the CP . Used to disambiguate packets coming from the DP vs. coming from the CP. *) type eventsource = | IncDP | IncCP | IncThrift;; type sreactive = | ReactRemote of string * typeid list * string * string * string * refresh | ReactOut of string * outgoing_fields * spec_out | ReactInc of typeid * eventsource * string;; type sdecl = | DeclTable of string * typeid list | DeclRemoteTable of string * typeid list | DeclInc of string * string | DeclOut of string * outgoing_fields | DeclEvent of string * (string * typeid) list;; AST elements pre desugaring type astdecl = | ASTDeclVar of string * typeid * term option | ASTDeclTable of string * typeid list | ASTDeclRemoteTable of string * typeid list | ASTDeclInc of string * string | ASTDeclOut of string * outgoing_fields | ASTDeclEvent of string * (string * typeid) list;; type srule = {onrel: string; onvar: string; action: action};; type aststmt = | ASTReactive of sreactive | ASTDecl of astdecl | ASTRule of srule;; type stmt = | SReactive of sreactive | SDecl of sdecl | SRule of srule;; type flowlog_ast = {includes: string list; statements: aststmt list};; type clause = { orig_rule: srule; head: formula; };; Every event has a name and a string of fieldnames , each with a type . type event_def = { eventname: string; evfields: (string * typeid) list };; type triggered_clause = {clause: clause; oldpkt: string; dependencies: string list; id: string};; type outgoing_def = { outname: string; outarity: outgoing_fields; react: spec_out};; type queryid = string;; type agent = string * string;; type table_source = | LocalTable | RemoteTable of queryid * agent * refresh;; type table_def = { tablename: string; tablearity: typeid list; source: table_source };; We use 's built in find_all function to extend the values to string list . type program_memos = {out_triggers: (string, string) Hashtbl.t; insert_triggers: (string, string) Hashtbl.t; delete_triggers: (string, string) Hashtbl.t; tablemap: (string, table_def) Hashtbl.t; eventmap: (string, event_def) Hashtbl.t; incomingmap: ((string*eventsource),string) Hashtbl.t; outgoingmap: (string, outgoing_def) Hashtbl.t; atoms_used_in_bodies: formula list; };; vartablenames: string list; tables: table_def list; incomings are entirely defined by event defns events: event_def list; outgoings: outgoing_def list; clauses: clause list; can_fully_compile_to_fwd_clauses: triggered_clause list; weakened_cannot_compile_pt_clauses: triggered_clause list; not_fully_compiled_clauses: clause list; memos: program_memos};; module StringMap = Map.Make(String);; type event = { typeid: string; values: string StringMap.t};; module FmlaMap = Map.Make(struct type t = formula let compare = compare end);; let allportsatom = SwitchAction({id with outPort = NetCore_Pattern.All});; type printmode = Verbose | Brief;; type xsbmode = Xsb | XsbForcePositive | XsbAddUnderscoreVars;; let rec gather_nonneg_equalities ?(exempt: term list = []) ?(vars_only: bool = false) (f: formula) (neg: bool): (term * term) list = match f with | FTrue -> [] | FFalse -> [] Make sure to use WHEN here , not a condition after - > . Suppose exempt=[y ] and y = x. Want 2nd option to apply . | FEquals((TVar(_) as thevar), t) when (not neg) && (not (thevar = t)) && (not (mem thevar exempt)) -> [(thevar, t)] | FEquals(t, (TVar(_) as thevar)) when (not neg) && (not (thevar = t)) && (not (mem thevar exempt)) -> [(thevar, t)] | FEquals(t1, t2) when (not neg) && (not vars_only) -> [(t1, t2)] | FEquals(_, _) -> [] | FIn(_,_,_) -> [] | FAtom(modstr, relstr, argterms) -> [] | FOr(f1, f2) -> unique ((gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f1 neg) @ (gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f2 neg)) | FAnd(f1, f2) -> unique ((gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f1 neg) @ (gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f2 neg)) | FNot(f2) -> (gather_nonneg_equalities ~exempt:exempt ~vars_only:vars_only f2 (not neg));; For every non - negated equality that has one TVar in it that is NOT in the exempt list , produces a tuple for substitution . ( Exempt list is so that vars in the head of a clause wo n't get substituted out ) that is NOT in the exempt list, produces a tuple for substitution. (Exempt list is so that vars in the head of a clause won't get substituted out) *) let rec gather_nonneg_equalities_involving_vars ?(exempt: term list = []) (f: formula) (neg: bool): (term * term) list = gather_nonneg_equalities ~exempt:exempt ~vars_only:true f neg;; exception SubstitutionLedToInconsistency of formula;; let equals_if_consistent (report_inconsistency: bool) (t1: term) (t2: term): formula = match (t1, t2) with | (TConst(str1), TConst(str2)) when str1 <> str2 -> if report_inconsistency then raise (SubstitutionLedToInconsistency((FEquals(t1, t2)))) else FFalse | _ -> FEquals(t1, t2);; let int32_allones = Int32.lognot (Int32.zero);; let is_in_ip_range (v: Int32.t) (addr: Int32.t) (mask: int): bool = MAXINT ( 32 bit ) let nwfield = Int32.shift_left int32_allones (32-mask) in (Int32.logand v nwfield) = (Int32.logand addr nwfield);; let in_if_consistent (report_inconsistency: bool) (v: term) (addr: term) (mask: term): formula = match v, addr, mask with | TConst(vval), TConst(addrval), TConst(maskval) when not (is_in_ip_range (Int32.of_string vval) (Int32.of_string addrval) (int_of_string maskval)) -> if report_inconsistency then raise (SubstitutionLedToInconsistency((FIn(v, addr, mask)))) else FFalse | _ -> FIn(v, addr, mask);; let rec substitute_term (report_inconsistency: bool) (f: formula) (v: term) (t: term): formula = let substitute_term_result (curr: term): term = match curr, v, t with | x, y, _ when x = y -> t curr is a field of v , replace with field of t | TField(x, fx), TVar(y), TVar(z) when x = y -> TField(z, fx) | _ -> curr in match f with | FTrue -> f | FFalse -> f | FEquals(t1, t2) -> let st1 = substitute_term_result t1 in let st2 = substitute_term_result t2 in if st1 = st2 then FTrue else equals_if_consistent report_inconsistency st1 st2 | FIn(t, addr, mask) -> let newt = substitute_term_result t in let newaddr = substitute_term_result addr in let newmask = substitute_term_result mask in in_if_consistent report_inconsistency newt newaddr newmask | FAtom(modstr, relstr, argterms) -> let newargterms = map (fun arg -> substitute_term_result arg) argterms in FAtom(modstr, relstr, newargterms) | FOr(f1, f2) -> let subs1 = substitute_term report_inconsistency f1 v t in let subs2 = substitute_term report_inconsistency f2 v t in if subs1 = FFalse then subs2 else if subs2 = FFalse then subs1 else FOr(subs1, subs2) | FAnd(f1, f2) -> remove superfluous FTrues / FFalses let subs1 = substitute_term report_inconsistency f1 v t in let subs2 = substitute_term report_inconsistency f2 v t in if subs1 = FTrue then subs2 else if subs2 = FTrue then subs1 else FAnd(subs1, subs2) | FNot(f2) -> let innerresult = substitute_term report_inconsistency f2 v t in if innerresult = FFalse then FTrue else if innerresult = FTrue then FFalse else FNot(innerresult);; let substitute_terms ?(report_inconsistency: bool = true) (f: formula) (subs: (term * term) list): formula = fold_left (fun fm (v, t) -> substitute_term report_inconsistency fm v t) f subs;; let rec minimize_variables ?(exempt: term list = []) (f: formula): formula = let var_equals_fmlas = gather_nonneg_equalities_involving_vars ~exempt:exempt f false in if length var_equals_fmlas < 1 then f else select equalities involving constants first , so we do n't lose their context let constpairs = filter (function | (TVar(_), TConst(_)) -> true | _ -> false) var_equals_fmlas in let (x, t) = if length constpairs > 0 then hd constpairs else hd var_equals_fmlas in subst process will discover inconsistency due to multiple vals e.g. x=7 , x=9 , and throw exception try let newf = (substitute_term true f x t) in printf " will subs out % s to % s. New is : % s.\n% ! " ( string_of_term x ) ( string_of_term t ) ( string_of_formula newf ) ; minimize_variables ~exempt:exempt newf with SubstitutionLedToInconsistency(_) -> FFalse;; let add_conjunct_to_action (act: action) (f: formula) = match act with | _ when f = FTrue -> act | ADelete(a, b, fmla) -> ADelete(a, b, FAnd(f, fmla)) | AInsert(a, b, fmla) -> AInsert(a, b, FAnd(f, fmla)) | ADo(a, b, fmla) -> ADo(a, b, FAnd(f, fmla)) | AForward(p, fmla, tout) -> AForward(p, FAnd(f, fmla), tout) | AStash(p, where, until, thens) -> AStash(p, FAnd(f, where), until, thens);; BUILT - IN CONSTANTS , MAGIC - NUMBERS , EVENTS , REACTIVE DEFINITIONS , ETC . These are prepended to relation names when we pass insert / delete rules to Prolog let plus_prefix = "plus";; let minus_prefix = "minus";; let packet_in_relname = "packet_in";; let switch_reg_relname = "switch_port";; let switch_down_relname = "switch_down";; let startup_relname = "startup";; let switch_has_port_relname = "switch_has_port";;
979b73c14373a4a03c65d3e2eaf708a7acac4342519f83f967b3e4aeda743d57
Clozure/ccl-tests
remove-method.lsp
;-*- Mode: Lisp -*- Author : Created : Sun May 11 19:53:37 2003 ;;;; Contains: Tests of REMOVE-METHOD (in-package :cl-test) (defparameter *remove-meth-gf-01* (defgeneric remove-meth-gf-01 (x))) (defparameter *remove-meth-gf-01-method-t* (defmethod remove-meth-gf-01 ((x t)) x)) (defparameter *remove-meth-gf-02* (defgeneric remove-meth-gf-02 (x))) (defparameter *remove-meth-gf-02-method-t* (defmethod remove-meth-gf-02 ((x t)) x)) ;;; remove method must not signal an error if the method ;;; does not belong to the generic function (deftest remove-method.1 (and (eqt (remove-method *remove-meth-gf-01* *remove-meth-gf-02-method-t*) *remove-meth-gf-01*) (remove-meth-gf-01 :good)) :good) ;;; Add, then remove, a method (deftest remove-method.2 (let (meth) (values (remove-meth-gf-01 10) (progn (setf meth (eval '(defmethod remove-meth-gf-01 ((x integer)) (1+ x)))) nil) (remove-meth-gf-01 10) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth)) (remove-meth-gf-01 10))) 10 nil 11 t 10) Add two disjoint methods , then remove (deftest remove-method.3 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(19 a)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x symbol)) (list x)))) (mapcar #'remove-meth-gf-01 '(19 a))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(19 a))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(19 a)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(19 a)))) (19 a) (19 (a)) (20 (a)) t (20 a) t (19 a)) ;;; Remove in the other order (deftest remove-method.4 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(19 a)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x symbol)) (list x)))) (mapcar #'remove-meth-gf-01 '(19 a))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(19 a))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(19 a)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(19 a)))) (19 a) (19 (a)) (20 (a)) t (19 (a)) t (19 a)) Now methods that shadow one another (deftest remove-method.5 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(10 20.0)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x integer)) (1- x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(10 20.0)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(10 20.0)))) (10 20.0) (9 20.0) (9 21.0) t (11 21.0) t (10 20.0)) (deftest remove-method.6 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(10 20.0)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x integer)) (1- x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(10 20.0)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(10 20.0)))) (10 20.0) (9 20.0) (9 21.0) t (9 20.0) t (10 20.0)) (deftest remove-method.7 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(10 20.0)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x integer)) (1- x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(10 20.0)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(10 20.0)))) (10 20.0) (11 21.0) (9 21.0) t (9 20.0) t (10 20.0)) (deftest remove-method.8 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(10 20.0)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x integer)) (1- x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(10 20.0)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(10 20.0)))) (10 20.0) (11 21.0) (9 21.0) t (11 21.0) t (10 20.0)) ;;; Adding and removing auxiliary methods (declaim (special *rmgf-03-var*)) (defparameter *remove-meth-gf-03* (defgeneric remove-meth-gf-03 (x))) (defparameter *remove-meth-gf-03-method-t* (defmethod remove-meth-gf-03 ((x t)) (list *rmgf-03-var* x))) (deftest remove-method.9 (let (meth (*rmgf-03-var* 0)) (values (mapcar #'remove-meth-gf-03 '(5 a)) (progn (setf meth (eval '(defmethod remove-meth-gf-03 :before ((x number)) (incf *rmgf-03-var*)))) (mapcar #'remove-meth-gf-03 '(5 a))) (eqt *remove-meth-gf-03* (remove-method *remove-meth-gf-03* meth)) (mapcar #'remove-meth-gf-03 '(5 a)))) ((0 5) (0 a)) ((1 5) (1 a)) t ((1 5) (1 a))) (deftest remove-method.10 (let (meth (*rmgf-03-var* 0)) (values (mapcar #'remove-meth-gf-03 '(5 a)) (progn (setf meth (eval '(defmethod remove-meth-gf-03 :after ((x number)) (incf *rmgf-03-var*)))) (mapcar #'remove-meth-gf-03 '(5 a))) (eqt *remove-meth-gf-03* (remove-method *remove-meth-gf-03* meth)) (mapcar #'remove-meth-gf-03 '(5 a)))) ((0 5) (0 a)) ((0 5) (1 a)) t ((1 5) (1 a))) (deftest remove-method.11 (let (meth (*rmgf-03-var* 0)) (values (mapcar #'remove-meth-gf-03 '(5 a)) (progn (setf meth (eval '(defmethod remove-meth-gf-03 :around ((x number)) (incf *rmgf-03-var*) (prog1 (call-next-method) (decf *rmgf-03-var*))))) (mapcar #'remove-meth-gf-03 '(5 a))) (eqt *remove-meth-gf-03* (remove-method *remove-meth-gf-03* meth)) (mapcar #'remove-meth-gf-03 '(5 a)))) ((0 5) (0 a)) ((1 5) (0 a)) t ((0 5) (0 a))) ;;; Must add tests for nonstandard method combinations
null
https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/remove-method.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of REMOVE-METHOD remove method must not signal an error if the method does not belong to the generic function Add, then remove, a method Remove in the other order Adding and removing auxiliary methods Must add tests for nonstandard method combinations
Author : Created : Sun May 11 19:53:37 2003 (in-package :cl-test) (defparameter *remove-meth-gf-01* (defgeneric remove-meth-gf-01 (x))) (defparameter *remove-meth-gf-01-method-t* (defmethod remove-meth-gf-01 ((x t)) x)) (defparameter *remove-meth-gf-02* (defgeneric remove-meth-gf-02 (x))) (defparameter *remove-meth-gf-02-method-t* (defmethod remove-meth-gf-02 ((x t)) x)) (deftest remove-method.1 (and (eqt (remove-method *remove-meth-gf-01* *remove-meth-gf-02-method-t*) *remove-meth-gf-01*) (remove-meth-gf-01 :good)) :good) (deftest remove-method.2 (let (meth) (values (remove-meth-gf-01 10) (progn (setf meth (eval '(defmethod remove-meth-gf-01 ((x integer)) (1+ x)))) nil) (remove-meth-gf-01 10) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth)) (remove-meth-gf-01 10))) 10 nil 11 t 10) Add two disjoint methods , then remove (deftest remove-method.3 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(19 a)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x symbol)) (list x)))) (mapcar #'remove-meth-gf-01 '(19 a))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(19 a))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(19 a)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(19 a)))) (19 a) (19 (a)) (20 (a)) t (20 a) t (19 a)) (deftest remove-method.4 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(19 a)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x symbol)) (list x)))) (mapcar #'remove-meth-gf-01 '(19 a))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(19 a))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(19 a)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(19 a)))) (19 a) (19 (a)) (20 (a)) t (19 (a)) t (19 a)) Now methods that shadow one another (deftest remove-method.5 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(10 20.0)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x integer)) (1- x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(10 20.0)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(10 20.0)))) (10 20.0) (9 20.0) (9 21.0) t (11 21.0) t (10 20.0)) (deftest remove-method.6 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(10 20.0)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x integer)) (1- x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(10 20.0)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(10 20.0)))) (10 20.0) (9 20.0) (9 21.0) t (9 20.0) t (10 20.0)) (deftest remove-method.7 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(10 20.0)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x integer)) (1- x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(10 20.0)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(10 20.0)))) (10 20.0) (11 21.0) (9 21.0) t (9 20.0) t (10 20.0)) (deftest remove-method.8 (let (meth1 meth2) (values (mapcar #'remove-meth-gf-01 '(10 20.0)) (progn (setf meth1 (eval '(defmethod remove-meth-gf-01 ((x number)) (1+ x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (progn (setf meth2 (eval '(defmethod remove-meth-gf-01 ((x integer)) (1- x)))) (mapcar #'remove-meth-gf-01 '(10 20.0))) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth2)) (mapcar #'remove-meth-gf-01 '(10 20.0)) (eqt *remove-meth-gf-01* (remove-method *remove-meth-gf-01* meth1)) (mapcar #'remove-meth-gf-01 '(10 20.0)))) (10 20.0) (11 21.0) (9 21.0) t (11 21.0) t (10 20.0)) (declaim (special *rmgf-03-var*)) (defparameter *remove-meth-gf-03* (defgeneric remove-meth-gf-03 (x))) (defparameter *remove-meth-gf-03-method-t* (defmethod remove-meth-gf-03 ((x t)) (list *rmgf-03-var* x))) (deftest remove-method.9 (let (meth (*rmgf-03-var* 0)) (values (mapcar #'remove-meth-gf-03 '(5 a)) (progn (setf meth (eval '(defmethod remove-meth-gf-03 :before ((x number)) (incf *rmgf-03-var*)))) (mapcar #'remove-meth-gf-03 '(5 a))) (eqt *remove-meth-gf-03* (remove-method *remove-meth-gf-03* meth)) (mapcar #'remove-meth-gf-03 '(5 a)))) ((0 5) (0 a)) ((1 5) (1 a)) t ((1 5) (1 a))) (deftest remove-method.10 (let (meth (*rmgf-03-var* 0)) (values (mapcar #'remove-meth-gf-03 '(5 a)) (progn (setf meth (eval '(defmethod remove-meth-gf-03 :after ((x number)) (incf *rmgf-03-var*)))) (mapcar #'remove-meth-gf-03 '(5 a))) (eqt *remove-meth-gf-03* (remove-method *remove-meth-gf-03* meth)) (mapcar #'remove-meth-gf-03 '(5 a)))) ((0 5) (0 a)) ((0 5) (1 a)) t ((1 5) (1 a))) (deftest remove-method.11 (let (meth (*rmgf-03-var* 0)) (values (mapcar #'remove-meth-gf-03 '(5 a)) (progn (setf meth (eval '(defmethod remove-meth-gf-03 :around ((x number)) (incf *rmgf-03-var*) (prog1 (call-next-method) (decf *rmgf-03-var*))))) (mapcar #'remove-meth-gf-03 '(5 a))) (eqt *remove-meth-gf-03* (remove-method *remove-meth-gf-03* meth)) (mapcar #'remove-meth-gf-03 '(5 a)))) ((0 5) (0 a)) ((1 5) (0 a)) t ((0 5) (0 a)))
1dadc2ec539ac847da8c8b7cdec7dae0ed38cd3be6c30138d4725993d8041de4
retro/keechma-next-realworld-app
api.cljs
(ns app.api (:require [keechma.next.toolbox.ajax :refer [GET POST DELETE PUT]] [app.settings :as settings] [promesa.core :as p])) (def default-request-config {:response-format :json :keywords? true :format :json}) (defn add-auth-header [req-params jwt] (if jwt (assoc-in req-params [:headers :authorization] (str "Token " jwt)) req-params)) (defn add-params [req-params params] (if params (assoc req-params :params params) req-params)) (defn req-params [& {:keys [jwt data]}] (-> default-request-config (add-auth-header jwt) (add-params data))) (defn tag->entity [tag] (if (string? tag) {:tag tag} tag)) (defn process-articles [data] {:data (map (fn [article] (assoc article :tagList (map tag->entity (:tagList article)))) (:articles data)) :meta {:count (:articlesCount data)}}) (defn process-article [data] (let [article (:article data) tag-list (:tagList article)] (assoc article :tagList (map tag->entity (if (fn? tag-list) (tag-list) tag-list))))) (defn process-tags [data] (map tag->entity (:tags data))) (defn process-author [data] (:profile data)) (defn process-comments [data] (:comments data)) (defn process-user [data] (:user data)) (defn comment-create [{:keys [jwt article-slug comment]}] (->> (POST (str settings/api-endpoint "/articles/" article-slug "/comments") (req-params :jwt jwt :data {:comment comment})) (p/map :comment))) (defn comments-get [{:keys [article-slug]}] (->> (GET (str settings/api-endpoint "/articles/" article-slug "/comments") (req-params)) (p/map process-comments))) (defn article-create [{:keys [jwt article]}] (->> (POST (str settings/api-endpoint "/articles") (req-params :jwt jwt :data {:article article})) (p/map process-article))) (defn article-update [{:keys [jwt article-slug article]}] (->> (PUT (str settings/api-endpoint "/articles/" article-slug) (req-params :jwt jwt :data {:article article})) (p/map process-article))) (defn article-delete [{:keys [jwt article-slug]}] (DELETE (str settings/api-endpoint "/articles/" article-slug) (req-params :jwt jwt))) (defn article-get [{:keys [article-slug jwt]}] (->> (GET (str settings/api-endpoint "/articles/" article-slug) (req-params :jwt jwt)) (p/map process-article))) (defn articles-get [{:keys [feed-type params jwt]}] (let [url (if (and jwt (= :personal feed-type)) "/articles/feed" "/articles")] (->> (GET (str settings/api-endpoint url) (req-params :data params :jwt jwt)) (p/map process-articles)))) (defn login [user] (->> (POST (str settings/api-endpoint "/users/login") (req-params :data {:user user})) (p/map process-user))) (defn register [user] (->> (POST (str settings/api-endpoint "/users") (req-params :data {:user user})) (p/map process-user))) (defn user-update [{:keys [jwt user]}] (->> (PUT (str settings/api-endpoint "/user") (req-params :jwt jwt :data {:user user})) (p/map process-user))) (defn current-user-get [{:keys [jwt]}] (->> (GET (str settings/api-endpoint "/user") (req-params :jwt jwt)) (p/map process-user))) (defn user-get [{:keys [jwt user]}] (->> (GET (str settings/api-endpoint "/profiles/" user) (req-params :jwt jwt)) (p/map process-author))) (defn follow-create [{:keys [jwt username]}] (->> (POST (str settings/api-endpoint "/profiles/" username "/follow") (req-params :jwt jwt)) (p/map process-author))) (defn follow-delete [{:keys [jwt username]}] (->> (DELETE (str settings/api-endpoint "/profiles/" username "/follow") (req-params :jwt jwt)) (p/map process-author))) (defn favorite-create [{:keys [jwt article-slug]}] (->> (POST (str settings/api-endpoint "/articles/" article-slug "/favorite") (req-params :jwt jwt)) (p/map process-article))) (defn favorite-delete [{:keys [jwt article-slug]}] (->> (DELETE (str settings/api-endpoint "/articles/" article-slug "/favorite") (req-params :jwt jwt)) (p/map process-article))) (defn tags-get [_] (->> (GET (str settings/api-endpoint "/tags") (req-params)) (p/map process-tags)))
null
https://raw.githubusercontent.com/retro/keechma-next-realworld-app/47a14f4f3f6d56be229cd82f7806d7397e559ebe/classes/production/realworld-2/app/api.cljs
clojure
(ns app.api (:require [keechma.next.toolbox.ajax :refer [GET POST DELETE PUT]] [app.settings :as settings] [promesa.core :as p])) (def default-request-config {:response-format :json :keywords? true :format :json}) (defn add-auth-header [req-params jwt] (if jwt (assoc-in req-params [:headers :authorization] (str "Token " jwt)) req-params)) (defn add-params [req-params params] (if params (assoc req-params :params params) req-params)) (defn req-params [& {:keys [jwt data]}] (-> default-request-config (add-auth-header jwt) (add-params data))) (defn tag->entity [tag] (if (string? tag) {:tag tag} tag)) (defn process-articles [data] {:data (map (fn [article] (assoc article :tagList (map tag->entity (:tagList article)))) (:articles data)) :meta {:count (:articlesCount data)}}) (defn process-article [data] (let [article (:article data) tag-list (:tagList article)] (assoc article :tagList (map tag->entity (if (fn? tag-list) (tag-list) tag-list))))) (defn process-tags [data] (map tag->entity (:tags data))) (defn process-author [data] (:profile data)) (defn process-comments [data] (:comments data)) (defn process-user [data] (:user data)) (defn comment-create [{:keys [jwt article-slug comment]}] (->> (POST (str settings/api-endpoint "/articles/" article-slug "/comments") (req-params :jwt jwt :data {:comment comment})) (p/map :comment))) (defn comments-get [{:keys [article-slug]}] (->> (GET (str settings/api-endpoint "/articles/" article-slug "/comments") (req-params)) (p/map process-comments))) (defn article-create [{:keys [jwt article]}] (->> (POST (str settings/api-endpoint "/articles") (req-params :jwt jwt :data {:article article})) (p/map process-article))) (defn article-update [{:keys [jwt article-slug article]}] (->> (PUT (str settings/api-endpoint "/articles/" article-slug) (req-params :jwt jwt :data {:article article})) (p/map process-article))) (defn article-delete [{:keys [jwt article-slug]}] (DELETE (str settings/api-endpoint "/articles/" article-slug) (req-params :jwt jwt))) (defn article-get [{:keys [article-slug jwt]}] (->> (GET (str settings/api-endpoint "/articles/" article-slug) (req-params :jwt jwt)) (p/map process-article))) (defn articles-get [{:keys [feed-type params jwt]}] (let [url (if (and jwt (= :personal feed-type)) "/articles/feed" "/articles")] (->> (GET (str settings/api-endpoint url) (req-params :data params :jwt jwt)) (p/map process-articles)))) (defn login [user] (->> (POST (str settings/api-endpoint "/users/login") (req-params :data {:user user})) (p/map process-user))) (defn register [user] (->> (POST (str settings/api-endpoint "/users") (req-params :data {:user user})) (p/map process-user))) (defn user-update [{:keys [jwt user]}] (->> (PUT (str settings/api-endpoint "/user") (req-params :jwt jwt :data {:user user})) (p/map process-user))) (defn current-user-get [{:keys [jwt]}] (->> (GET (str settings/api-endpoint "/user") (req-params :jwt jwt)) (p/map process-user))) (defn user-get [{:keys [jwt user]}] (->> (GET (str settings/api-endpoint "/profiles/" user) (req-params :jwt jwt)) (p/map process-author))) (defn follow-create [{:keys [jwt username]}] (->> (POST (str settings/api-endpoint "/profiles/" username "/follow") (req-params :jwt jwt)) (p/map process-author))) (defn follow-delete [{:keys [jwt username]}] (->> (DELETE (str settings/api-endpoint "/profiles/" username "/follow") (req-params :jwt jwt)) (p/map process-author))) (defn favorite-create [{:keys [jwt article-slug]}] (->> (POST (str settings/api-endpoint "/articles/" article-slug "/favorite") (req-params :jwt jwt)) (p/map process-article))) (defn favorite-delete [{:keys [jwt article-slug]}] (->> (DELETE (str settings/api-endpoint "/articles/" article-slug "/favorite") (req-params :jwt jwt)) (p/map process-article))) (defn tags-get [_] (->> (GET (str settings/api-endpoint "/tags") (req-params)) (p/map process-tags)))
2bc66fc140adc1028dd283494bb58dfbe850ce114bb8425adfd8fe56dedafab9
bellissimogiorno/nominal
UntypedLambda.hs
| Module : Description : Syntax and reductions of the untyped lambda - calculus using the Nominal package Copyright : ( c ) , 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Untyped lambda - calculus : syntax , substitution , nominal - style recursion , weak head normal form function , and a couple of examples . Compare with an example in < the Bound package > . Module : Untyped Lambda-Calculus Description : Syntax and reductions of the untyped lambda-calculus using the Nominal package Copyright : (c) Murdoch J. Gabbay, 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Untyped lambda-calculus: syntax, substitution, nominal-style recursion, weak head normal form function, and a couple of examples. Compare with an example in < the Bound package>. -} # LANGUAGE InstanceSigs , DeriveGeneric , LambdaCase , MultiParamTypeClasses , -- to derive ' Swappable ' , DeriveDataTypeable -- to derive ' Data ' , FlexibleInstances # , DeriveGeneric , LambdaCase , MultiParamTypeClasses , DeriveAnyClass -- to derive 'Swappable' , DeriveDataTypeable -- to derive 'Data' , FlexibleInstances #-} module Language.Nominal.Examples.UntypedLambda ( Var, Exp (..), whnf, lam, example1, example1whnf, example2, example2whnf ) where import GHC.Generics import Data.Generics hiding (Generic, typeOf) import Language.Nominal.Utilities import Language.Nominal.Name import Language.Nominal.Nom import Language.Nominal.Binder import Language.Nominal.Abs import Language.Nominal.Sub -- | Variables are string-labelled names type Var = Name String infixl 9 :@ -- | Terms of the untyped lambda-calculus data Exp = V Var -- ^ Variable | Exp :@ Exp -- ^ Application | Lam (KAbs Var Exp) -- ^ Lambda, using abstraction-type deriving (Eq, Generic, Data, Swappable) -- , Show) -- | helper for building lambda-abstractions lam :: Var -> Exp -> Exp lam x a = Lam (x @> a) -- | Substitution. Capture-avoidance is automatic. instance KSub Var Exp Exp where sub :: Var -> Exp -> Exp -> Exp sub v t = rewrite $ \case -- 'rewrite' comes from Scrap-Your-Boilerplate generics. It recurses properly under the binder. V v' | v' == v -> Just t -- If @V v'@, replace with @t@ ... _ -> Nothing -- ... otherwise recurse. The substitution instance above is equivalent to the following : -- | Explicit recursion . expRec : : ( Var - > a ) - > ( Exp - > Exp - > a ) - > ( Var - > Exp - > a ) - > Exp - > a expRec f0 _ _ ( V n ) = f1 n expRec _ f1 _ ( s1 : @ s2 ) = f2 s1 s2 expRec _ _ f2 ( ) = f3 ` genApp ` x ' instance KSub Var Exp Exp where sub : : Var - > Exp - > Exp - > Exp sub v t = expRec ( ' - > if v ' = = v then t else V v ' ) ( \a b - > sub v t a : @ sub v t b ) ( ' a - > lam v ' $ sub v t a ) -- | Explicit recursion. expRec :: (Var -> a) -> (Exp -> Exp -> a) -> (Var -> Exp -> a) -> Exp -> a expRec f0 _ _ (V n) = f1 n expRec _ f1 _ (s1 :@ s2) = f2 s1 s2 expRec _ _ f2 (Lam x') = f3 `genApp` x' instance KSub Var Exp Exp where sub :: Var -> Exp -> Exp -> Exp sub v t = expRec (\v' -> if v' == v then t else V v') (\a b -> sub v t a :@ sub v t b) (\v' a -> lam v' $ sub v t a) -} -- | weak head normal form of a lambda-term. whnf :: Exp -> Exp whnf (Lam b' :@ a) = whnf $ b' `conc` a whnf e = e | ( \x x ) y example1 :: Exp example1 = (\[x, y] -> lam x (V x) :@ V y) `genAppC` freshNames ["x", "y"] -- | y example1whnf :: Exp example1whnf = whnf example1 | ( \x xy ) x example2 :: Exp example2 = (\[x, y] -> lam x (V x :@ V y) :@ V x) `genAppC` freshNames ["x", "y"] -- | xy example2whnf :: Exp example2whnf = whnf example2 instance Show Exp where show (V v) = show v show (Lam e) = "(λ" ++ (show e) ++ ")" show (e :@ e') = (show e) ++ " " ++ (show e')
null
https://raw.githubusercontent.com/bellissimogiorno/nominal/ab3306ee349dc481d2e2e6d103d90ffdd14ccaa9/src/Language/Nominal/Examples/UntypedLambda.hs
haskell
to derive ' Swappable ' to derive ' Data ' to derive 'Swappable' to derive 'Data' | Variables are string-labelled names | Terms of the untyped lambda-calculus ^ Variable ^ Application ^ Lambda, using abstraction-type , Show) | helper for building lambda-abstractions | Substitution. Capture-avoidance is automatic. 'rewrite' comes from Scrap-Your-Boilerplate generics. It recurses properly under the binder. If @V v'@, replace with @t@ ... ... otherwise recurse. | Explicit recursion . | Explicit recursion. | weak head normal form of a lambda-term. | y | xy
| Module : Description : Syntax and reductions of the untyped lambda - calculus using the Nominal package Copyright : ( c ) , 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Untyped lambda - calculus : syntax , substitution , nominal - style recursion , weak head normal form function , and a couple of examples . Compare with an example in < the Bound package > . Module : Untyped Lambda-Calculus Description : Syntax and reductions of the untyped lambda-calculus using the Nominal package Copyright : (c) Murdoch J. Gabbay, 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Untyped lambda-calculus: syntax, substitution, nominal-style recursion, weak head normal form function, and a couple of examples. Compare with an example in < the Bound package>. -} # LANGUAGE InstanceSigs , DeriveGeneric , LambdaCase , MultiParamTypeClasses , FlexibleInstances # , DeriveGeneric , LambdaCase , MultiParamTypeClasses , FlexibleInstances #-} module Language.Nominal.Examples.UntypedLambda ( Var, Exp (..), whnf, lam, example1, example1whnf, example2, example2whnf ) where import GHC.Generics import Data.Generics hiding (Generic, typeOf) import Language.Nominal.Utilities import Language.Nominal.Name import Language.Nominal.Nom import Language.Nominal.Binder import Language.Nominal.Abs import Language.Nominal.Sub type Var = Name String infixl 9 :@ lam :: Var -> Exp -> Exp lam x a = Lam (x @> a) instance KSub Var Exp Exp where sub :: Var -> Exp -> Exp -> Exp The substitution instance above is equivalent to the following : expRec : : ( Var - > a ) - > ( Exp - > Exp - > a ) - > ( Var - > Exp - > a ) - > Exp - > a expRec f0 _ _ ( V n ) = f1 n expRec _ f1 _ ( s1 : @ s2 ) = f2 s1 s2 expRec _ _ f2 ( ) = f3 ` genApp ` x ' instance KSub Var Exp Exp where sub : : Var - > Exp - > Exp - > Exp sub v t = expRec ( ' - > if v ' = = v then t else V v ' ) ( \a b - > sub v t a : @ sub v t b ) ( ' a - > lam v ' $ sub v t a ) expRec :: (Var -> a) -> (Exp -> Exp -> a) -> (Var -> Exp -> a) -> Exp -> a expRec f0 _ _ (V n) = f1 n expRec _ f1 _ (s1 :@ s2) = f2 s1 s2 expRec _ _ f2 (Lam x') = f3 `genApp` x' instance KSub Var Exp Exp where sub :: Var -> Exp -> Exp -> Exp sub v t = expRec (\v' -> if v' == v then t else V v') (\a b -> sub v t a :@ sub v t b) (\v' a -> lam v' $ sub v t a) -} whnf :: Exp -> Exp whnf (Lam b' :@ a) = whnf $ b' `conc` a whnf e = e | ( \x x ) y example1 :: Exp example1 = (\[x, y] -> lam x (V x) :@ V y) `genAppC` freshNames ["x", "y"] example1whnf :: Exp example1whnf = whnf example1 | ( \x xy ) x example2 :: Exp example2 = (\[x, y] -> lam x (V x :@ V y) :@ V x) `genAppC` freshNames ["x", "y"] example2whnf :: Exp example2whnf = whnf example2 instance Show Exp where show (V v) = show v show (Lam e) = "(λ" ++ (show e) ++ ")" show (e :@ e') = (show e) ++ " " ++ (show e')
4029442068070ce15d318108b3cba195151d7c18806bba08ad3eaa23a0bf247b
Copilot-Language/copilot
Analyze.hs
Copyright © 2011 National Institute of Aerospace / Galois , Inc. {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE GADTs # {-# LANGUAGE Safe #-} # LANGUAGE ScopedTypeVariables # -- | Copilot specification sanity check. module Copilot.Language.Analyze ( AnalyzeException (..) , analyze ) where import Copilot.Core (DropIdx) import qualified Copilot.Core as C import Copilot.Language.Stream (Stream (..), Arg (..)) import Copilot.Language.Spec import Copilot.Language.Error (badUsage) import Data.List (groupBy) import Data.IORef import Data.Typeable import System.Mem.StableName.Dynamic import System.Mem.StableName.Map (Map(..)) import qualified System.Mem.StableName.Map as M import Control.Monad (when, foldM_, foldM) import Control.Exception (Exception, throw) -- | Exceptions or kinds of errors in Copilot specifications that the analysis -- implemented is able to detect. data AnalyzeException = DropAppliedToNonAppend | DropIndexOverflow | ReferentialCycle | DropMaxViolation | NestedArray | TooMuchRecursion | InvalidField | DifferentTypes String | Redeclared String | BadNumberOfArgs String | BadFunctionArgType String deriving Typeable -- | Show instance that prints a detailed message for each kind of exception. instance Show AnalyzeException where show DropAppliedToNonAppend = badUsage $ "Drop applied to non-append operation!" show DropIndexOverflow = badUsage $ "Drop index overflow!" show ReferentialCycle = badUsage $ "Referential cycle!" show DropMaxViolation = badUsage $ "Maximum drop violation (" ++ show (maxBound :: DropIdx) ++ ")!" show NestedArray = badUsage $ "An external function cannot take another external function or external array as an argument. Try defining a stream, and using the stream values in the other definition." show TooMuchRecursion = badUsage $ "You have exceeded the limit of " ++ show maxRecursion ++ " recursive calls in a stream definition. Likely, you have accidently defined a circular stream, such as 'x = x'. Another possibility is you have defined a a polymorphic function with type constraints that references other streams. For example,\n\n nats :: (Typed a, Num a) => Stream a\n nats = [0] ++ nats + 1\n\nis not allowed. Make the definition monomorphic, or add a level of indirection, like \n\n nats :: (Typed a, Num a) => Stream a\n nats = n\n where\n n = [0] ++ n + 1\n\nFinally, you may have intended to generate a very large expression. You can try shrinking the expression by using local variables. It all else fails, you can increase the maximum size of ecursive calls by modifying 'maxRecursion' in copilot-language." show InvalidField = badUsage $ "A struct can only take external variables, arrays, or other structs as fields." show (DifferentTypes name) = badUsage $ "The external symbol \'" ++ name ++ "\' has been declared to have two different types!" show (Redeclared name) = badUsage $ "The external symbol \'" ++ name ++ "\' has been redeclared to be a different symbol (e.g., a variable and an array, or a variable and a funciton symbol, etc.)." show (BadNumberOfArgs name) = badUsage $ "The function symbol \'" ++ name ++ "\' has been redeclared to have different number of arguments." show (BadFunctionArgType name) = badUsage $ "The function symbol \'" ++ name ++ "\' has been redeclared to an argument with different types." -- | 'Exception' instance so we can throw and catch 'AnalyzeExcetion's. instance Exception AnalyzeException | level of recursion supported . Any level above this constant -- will result in a 'TooMuchRecursion' exception. maxRecursion :: Int maxRecursion = 100000 -- | An environment that contains the nodes visited. type Env = Map () -- | Analyze a Copilot specification and report any errors detected. -- This function can fail with one of the exceptions in ' AnalyzeException ' . analyze :: Spec' a -> IO () analyze spec = do refStreams <- newIORef M.empty mapM_ (analyzeTrigger refStreams) (triggers $ runSpec spec) mapM_ (analyzeObserver refStreams) (observers $ runSpec spec) mapM_ (analyzeProperty refStreams) (properties $ runSpec spec) mapM_ (analyzeProperty refStreams) (map fst $ theorems $ runSpec spec) specExts refStreams spec >>= analyzeExts -- | Analyze a Copilot trigger and report any errors detected. -- This function can fail with one of the exceptions in ' AnalyzeException ' . analyzeTrigger :: IORef Env -> Trigger -> IO () analyzeTrigger refStreams (Trigger _ e0 args) = analyzeExpr refStreams e0 >> mapM_ analyzeTriggerArg args where analyzeTriggerArg :: Arg -> IO () analyzeTriggerArg (Arg e) = analyzeExpr refStreams e -- | Analyze a Copilot observer and report any errors detected. -- This function can fail with one of the exceptions in ' AnalyzeException ' . analyzeObserver :: IORef Env -> Observer -> IO () analyzeObserver refStreams (Observer _ e) = analyzeExpr refStreams e -- | Analyze a Copilot property and report any errors detected. -- This function can fail with one of the exceptions in ' AnalyzeException ' . analyzeProperty :: IORef Env -> Property -> IO () analyzeProperty refStreams (Property _ e) = analyzeExpr refStreams e data SeenExtern = NoExtern | SeenFun | SeenArr | SeenStruct -- | Analyze a Copilot stream and report any errors detected. -- This function can fail with one of the exceptions in ' AnalyzeException ' . analyzeExpr :: IORef Env -> Stream a -> IO () analyzeExpr refStreams s = do b <- mapCheck refStreams when b (throw TooMuchRecursion) go NoExtern M.empty s where go :: SeenExtern -> Env -> Stream b -> IO () go seenExt nodes e0 = do dstn <- makeDynStableName e0 assertNotVisited e0 dstn nodes let nodes' = M.insert dstn () nodes case e0 of Append _ _ e -> analyzeAppend refStreams dstn e () analyzeExpr Const _ -> return () Drop k e1 -> analyzeDrop (fromIntegral k) e1 Extern _ _ -> return () Local e f -> go seenExt nodes' e >> go seenExt nodes' (f (Var "dummy")) Var _ -> return () Op1 _ e -> go seenExt nodes' e Op2 _ e1 e2 -> go seenExt nodes' e1 >> go seenExt nodes' e2 Op3 _ e1 e2 e3 -> go seenExt nodes' e1 >> go seenExt nodes' e2 >> go seenExt nodes' e3 Label _ e -> go seenExt nodes' e -- | Detect whether the given stream name has already been visited. -- This function throws a ' ReferentialCycle ' exception if the second argument -- represents a name that has already been visited. assertNotVisited :: Stream a -> DynStableName -> Env -> IO () assertNotVisited (Append _ _ _) _ _ = return () assertNotVisited _ dstn nodes = case M.lookup dstn nodes of Just () -> throw ReferentialCycle Nothing -> return () | Check that the level of recursion is not above the recursion allowed . mapCheck :: IORef Env -> IO Bool mapCheck refStreams = do ref <- readIORef refStreams return $ getSize ref > maxRecursion -- | Analyze a Copilot stream append and report any errors detected. analyzeAppend :: IORef Env -> DynStableName -> Stream a -> b -> (IORef Env -> Stream a -> IO b) -> IO b analyzeAppend refStreams dstn e b f = do streams <- readIORef refStreams case M.lookup dstn streams of Just () -> return b Nothing -> do modifyIORef refStreams $ M.insert dstn () f refStreams e -- | Analyze a Copilot stream drop and report any errors detected. -- -- This function can fail if the drop is exercised over a stream that is not an -- append, or if the length of the drop is larger than that of the subsequent -- append. analyzeDrop :: Int -> Stream a -> IO () analyzeDrop k (Append xs _ _) | k >= length xs = throw DropIndexOverflow | k > fromIntegral (maxBound :: DropIdx) = throw DropMaxViolation | otherwise = return () analyzeDrop _ _ = throw DropAppliedToNonAppend -- Analyzing external variables. We check that every reference to an external -- variable has the same type, and for external functions, they have the same -- typed arguments. -- | An environment to store external variables, arrays, functions and structs, -- so that we can check types in the expression---e.g., if we declare the same external to have two different types . data ExternEnv = ExternEnv { externVarEnv :: [(String, C.SimpleType)] , externArrEnv :: [(String, C.SimpleType)] , externStructEnv :: [(String, C.SimpleType)] , externStructArgs :: [(String, [C.SimpleType])] } -- | Make sure external variables, functions, arrays, and structs are correctly -- typed. analyzeExts :: ExternEnv -> IO () analyzeExts ExternEnv { externVarEnv = vars , externArrEnv = arrs , externStructEnv = datastructs , externStructArgs = struct_args } = do findDups vars arrs findDups vars datastructs findDups arrs datastructs conflictingTypes vars conflictingTypes arrs funcArgCheck struct_args where findDups :: [(String, a)] -> [(String, b)] -> IO () findDups ls0 ls1 = mapM_ (\(name,_) -> dup name) ls0 where dup nm = mapM_ ( \(name',_) -> if name' == nm then throw (Redeclared nm) else return () ) ls1 conflictingTypes :: [(String, C.SimpleType)] -> IO () conflictingTypes ls = let grps = groupByPred ls in mapM_ sameType grps where sameType :: [(String, C.SimpleType)] -> IO () sameType grp = foldCheck check grp check name c0 c1 = if c0 == c1 then return (name,c0) -- a dummy---we -- discard the result else throw (DifferentTypes name) funcArgCheck :: [(String, [C.SimpleType])] -> IO () funcArgCheck ls = let grps = groupByPred ls in mapM_ argCheck grps where argCheck :: [(String, [C.SimpleType])] -> IO () argCheck grp = foldCheck check grp check name args0 args1 = if length args0 == length args1 then if args0 == args1 then return (name,args0) -- a dummy---we discard the -- result else throw (BadFunctionArgType name) else throw (BadNumberOfArgs name) groupByPred :: [(String, a)] -> [[(String, a)]] groupByPred = groupBy (\(n0,_) (n1,_) -> n0 == n1) foldCheck :: (String -> a -> a -> IO (String, a)) -> [(String, a)] -> IO () foldCheck check grp = foldM_ ( \(name, c0) (_, c1) -> check name c0 c1) (head grp) -- should be typesafe, since this is from groupBy grp -- | Obtain all the externs in a specification. specExts :: IORef Env -> Spec' a -> IO ExternEnv specExts refStreams spec = do env <- foldM triggerExts (ExternEnv [] [] [] []) (triggers $ runSpec spec) foldM observerExts env (observers $ runSpec spec) where observerExts :: ExternEnv -> Observer -> IO ExternEnv observerExts env (Observer _ stream) = collectExts refStreams stream env triggerExts :: ExternEnv -> Trigger -> IO ExternEnv triggerExts env (Trigger _ guard args) = do env' <- collectExts refStreams guard env foldM (\env'' (Arg arg_) -> collectExts refStreams arg_ env'') env' args -- | Obtain all the externs in a stream. collectExts :: C.Typed a => IORef Env -> Stream a -> ExternEnv -> IO ExternEnv collectExts refStreams stream_ env_ = do b <- mapCheck refStreams when b (throw TooMuchRecursion) go M.empty env_ stream_ where go :: Env -> ExternEnv -> Stream b -> IO ExternEnv go nodes env stream = do dstn <- makeDynStableName stream assertNotVisited stream dstn nodes case stream of Append _ _ e -> analyzeAppend refStreams dstn e env (\refs str -> collectExts refs str env) Const _ -> return env Drop _ e1 -> go nodes env e1 Extern name _ -> let ext = ( name, getSimpleType stream ) in return env { externVarEnv = ext : externVarEnv env } Local e _ -> go nodes env e Var _ -> return env Op1 _ e -> go nodes env e Op2 _ e1 e2 -> do env' <- go nodes env e1 go nodes env' e2 Op3 _ e1 e2 e3 -> do env' <- go nodes env e1 env'' <- go nodes env' e2 go nodes env'' e3 Label _ e -> go nodes env e -- | Return the simple C type representation of the type of the values carried -- by a stream. getSimpleType :: forall a. C.Typed a => Stream a -> C.SimpleType getSimpleType _ = C.simpleType (C.typeOf :: C.Type a)
null
https://raw.githubusercontent.com/Copilot-Language/copilot/17a9b45eea4e95a465d6e773c6fbcf9bf810b6cc/copilot-language/src/Copilot/Language/Analyze.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE Safe # | Copilot specification sanity check. | Exceptions or kinds of errors in Copilot specifications that the analysis implemented is able to detect. | Show instance that prints a detailed message for each kind of exception. | 'Exception' instance so we can throw and catch 'AnalyzeExcetion's. will result in a 'TooMuchRecursion' exception. | An environment that contains the nodes visited. | Analyze a Copilot specification and report any errors detected. | Analyze a Copilot trigger and report any errors detected. | Analyze a Copilot observer and report any errors detected. | Analyze a Copilot property and report any errors detected. | Analyze a Copilot stream and report any errors detected. | Detect whether the given stream name has already been visited. represents a name that has already been visited. | Analyze a Copilot stream append and report any errors detected. | Analyze a Copilot stream drop and report any errors detected. This function can fail if the drop is exercised over a stream that is not an append, or if the length of the drop is larger than that of the subsequent append. Analyzing external variables. We check that every reference to an external variable has the same type, and for external functions, they have the same typed arguments. | An environment to store external variables, arrays, functions and structs, so that we can check types in the expression---e.g., if we declare the same | Make sure external variables, functions, arrays, and structs are correctly typed. a dummy---we discard the result a dummy---we discard the result should be typesafe, since this is from groupBy | Obtain all the externs in a specification. | Obtain all the externs in a stream. | Return the simple C type representation of the type of the values carried by a stream.
Copyright © 2011 National Institute of Aerospace / Galois , Inc. # LANGUAGE GADTs # # LANGUAGE ScopedTypeVariables # module Copilot.Language.Analyze ( AnalyzeException (..) , analyze ) where import Copilot.Core (DropIdx) import qualified Copilot.Core as C import Copilot.Language.Stream (Stream (..), Arg (..)) import Copilot.Language.Spec import Copilot.Language.Error (badUsage) import Data.List (groupBy) import Data.IORef import Data.Typeable import System.Mem.StableName.Dynamic import System.Mem.StableName.Map (Map(..)) import qualified System.Mem.StableName.Map as M import Control.Monad (when, foldM_, foldM) import Control.Exception (Exception, throw) data AnalyzeException = DropAppliedToNonAppend | DropIndexOverflow | ReferentialCycle | DropMaxViolation | NestedArray | TooMuchRecursion | InvalidField | DifferentTypes String | Redeclared String | BadNumberOfArgs String | BadFunctionArgType String deriving Typeable instance Show AnalyzeException where show DropAppliedToNonAppend = badUsage $ "Drop applied to non-append operation!" show DropIndexOverflow = badUsage $ "Drop index overflow!" show ReferentialCycle = badUsage $ "Referential cycle!" show DropMaxViolation = badUsage $ "Maximum drop violation (" ++ show (maxBound :: DropIdx) ++ ")!" show NestedArray = badUsage $ "An external function cannot take another external function or external array as an argument. Try defining a stream, and using the stream values in the other definition." show TooMuchRecursion = badUsage $ "You have exceeded the limit of " ++ show maxRecursion ++ " recursive calls in a stream definition. Likely, you have accidently defined a circular stream, such as 'x = x'. Another possibility is you have defined a a polymorphic function with type constraints that references other streams. For example,\n\n nats :: (Typed a, Num a) => Stream a\n nats = [0] ++ nats + 1\n\nis not allowed. Make the definition monomorphic, or add a level of indirection, like \n\n nats :: (Typed a, Num a) => Stream a\n nats = n\n where\n n = [0] ++ n + 1\n\nFinally, you may have intended to generate a very large expression. You can try shrinking the expression by using local variables. It all else fails, you can increase the maximum size of ecursive calls by modifying 'maxRecursion' in copilot-language." show InvalidField = badUsage $ "A struct can only take external variables, arrays, or other structs as fields." show (DifferentTypes name) = badUsage $ "The external symbol \'" ++ name ++ "\' has been declared to have two different types!" show (Redeclared name) = badUsage $ "The external symbol \'" ++ name ++ "\' has been redeclared to be a different symbol (e.g., a variable and an array, or a variable and a funciton symbol, etc.)." show (BadNumberOfArgs name) = badUsage $ "The function symbol \'" ++ name ++ "\' has been redeclared to have different number of arguments." show (BadFunctionArgType name) = badUsage $ "The function symbol \'" ++ name ++ "\' has been redeclared to an argument with different types." instance Exception AnalyzeException | level of recursion supported . Any level above this constant maxRecursion :: Int maxRecursion = 100000 type Env = Map () This function can fail with one of the exceptions in ' AnalyzeException ' . analyze :: Spec' a -> IO () analyze spec = do refStreams <- newIORef M.empty mapM_ (analyzeTrigger refStreams) (triggers $ runSpec spec) mapM_ (analyzeObserver refStreams) (observers $ runSpec spec) mapM_ (analyzeProperty refStreams) (properties $ runSpec spec) mapM_ (analyzeProperty refStreams) (map fst $ theorems $ runSpec spec) specExts refStreams spec >>= analyzeExts This function can fail with one of the exceptions in ' AnalyzeException ' . analyzeTrigger :: IORef Env -> Trigger -> IO () analyzeTrigger refStreams (Trigger _ e0 args) = analyzeExpr refStreams e0 >> mapM_ analyzeTriggerArg args where analyzeTriggerArg :: Arg -> IO () analyzeTriggerArg (Arg e) = analyzeExpr refStreams e This function can fail with one of the exceptions in ' AnalyzeException ' . analyzeObserver :: IORef Env -> Observer -> IO () analyzeObserver refStreams (Observer _ e) = analyzeExpr refStreams e This function can fail with one of the exceptions in ' AnalyzeException ' . analyzeProperty :: IORef Env -> Property -> IO () analyzeProperty refStreams (Property _ e) = analyzeExpr refStreams e data SeenExtern = NoExtern | SeenFun | SeenArr | SeenStruct This function can fail with one of the exceptions in ' AnalyzeException ' . analyzeExpr :: IORef Env -> Stream a -> IO () analyzeExpr refStreams s = do b <- mapCheck refStreams when b (throw TooMuchRecursion) go NoExtern M.empty s where go :: SeenExtern -> Env -> Stream b -> IO () go seenExt nodes e0 = do dstn <- makeDynStableName e0 assertNotVisited e0 dstn nodes let nodes' = M.insert dstn () nodes case e0 of Append _ _ e -> analyzeAppend refStreams dstn e () analyzeExpr Const _ -> return () Drop k e1 -> analyzeDrop (fromIntegral k) e1 Extern _ _ -> return () Local e f -> go seenExt nodes' e >> go seenExt nodes' (f (Var "dummy")) Var _ -> return () Op1 _ e -> go seenExt nodes' e Op2 _ e1 e2 -> go seenExt nodes' e1 >> go seenExt nodes' e2 Op3 _ e1 e2 e3 -> go seenExt nodes' e1 >> go seenExt nodes' e2 >> go seenExt nodes' e3 Label _ e -> go seenExt nodes' e This function throws a ' ReferentialCycle ' exception if the second argument assertNotVisited :: Stream a -> DynStableName -> Env -> IO () assertNotVisited (Append _ _ _) _ _ = return () assertNotVisited _ dstn nodes = case M.lookup dstn nodes of Just () -> throw ReferentialCycle Nothing -> return () | Check that the level of recursion is not above the recursion allowed . mapCheck :: IORef Env -> IO Bool mapCheck refStreams = do ref <- readIORef refStreams return $ getSize ref > maxRecursion analyzeAppend :: IORef Env -> DynStableName -> Stream a -> b -> (IORef Env -> Stream a -> IO b) -> IO b analyzeAppend refStreams dstn e b f = do streams <- readIORef refStreams case M.lookup dstn streams of Just () -> return b Nothing -> do modifyIORef refStreams $ M.insert dstn () f refStreams e analyzeDrop :: Int -> Stream a -> IO () analyzeDrop k (Append xs _ _) | k >= length xs = throw DropIndexOverflow | k > fromIntegral (maxBound :: DropIdx) = throw DropMaxViolation | otherwise = return () analyzeDrop _ _ = throw DropAppliedToNonAppend external to have two different types . data ExternEnv = ExternEnv { externVarEnv :: [(String, C.SimpleType)] , externArrEnv :: [(String, C.SimpleType)] , externStructEnv :: [(String, C.SimpleType)] , externStructArgs :: [(String, [C.SimpleType])] } analyzeExts :: ExternEnv -> IO () analyzeExts ExternEnv { externVarEnv = vars , externArrEnv = arrs , externStructEnv = datastructs , externStructArgs = struct_args } = do findDups vars arrs findDups vars datastructs findDups arrs datastructs conflictingTypes vars conflictingTypes arrs funcArgCheck struct_args where findDups :: [(String, a)] -> [(String, b)] -> IO () findDups ls0 ls1 = mapM_ (\(name,_) -> dup name) ls0 where dup nm = mapM_ ( \(name',_) -> if name' == nm then throw (Redeclared nm) else return () ) ls1 conflictingTypes :: [(String, C.SimpleType)] -> IO () conflictingTypes ls = let grps = groupByPred ls in mapM_ sameType grps where sameType :: [(String, C.SimpleType)] -> IO () sameType grp = foldCheck check grp else throw (DifferentTypes name) funcArgCheck :: [(String, [C.SimpleType])] -> IO () funcArgCheck ls = let grps = groupByPred ls in mapM_ argCheck grps where argCheck :: [(String, [C.SimpleType])] -> IO () argCheck grp = foldCheck check grp check name args0 args1 = if length args0 == length args1 then if args0 == args1 else throw (BadFunctionArgType name) else throw (BadNumberOfArgs name) groupByPred :: [(String, a)] -> [[(String, a)]] groupByPred = groupBy (\(n0,_) (n1,_) -> n0 == n1) foldCheck :: (String -> a -> a -> IO (String, a)) -> [(String, a)] -> IO () foldCheck check grp = foldM_ ( \(name, c0) (_, c1) -> check name c0 c1) grp specExts :: IORef Env -> Spec' a -> IO ExternEnv specExts refStreams spec = do env <- foldM triggerExts (ExternEnv [] [] [] []) (triggers $ runSpec spec) foldM observerExts env (observers $ runSpec spec) where observerExts :: ExternEnv -> Observer -> IO ExternEnv observerExts env (Observer _ stream) = collectExts refStreams stream env triggerExts :: ExternEnv -> Trigger -> IO ExternEnv triggerExts env (Trigger _ guard args) = do env' <- collectExts refStreams guard env foldM (\env'' (Arg arg_) -> collectExts refStreams arg_ env'') env' args collectExts :: C.Typed a => IORef Env -> Stream a -> ExternEnv -> IO ExternEnv collectExts refStreams stream_ env_ = do b <- mapCheck refStreams when b (throw TooMuchRecursion) go M.empty env_ stream_ where go :: Env -> ExternEnv -> Stream b -> IO ExternEnv go nodes env stream = do dstn <- makeDynStableName stream assertNotVisited stream dstn nodes case stream of Append _ _ e -> analyzeAppend refStreams dstn e env (\refs str -> collectExts refs str env) Const _ -> return env Drop _ e1 -> go nodes env e1 Extern name _ -> let ext = ( name, getSimpleType stream ) in return env { externVarEnv = ext : externVarEnv env } Local e _ -> go nodes env e Var _ -> return env Op1 _ e -> go nodes env e Op2 _ e1 e2 -> do env' <- go nodes env e1 go nodes env' e2 Op3 _ e1 e2 e3 -> do env' <- go nodes env e1 env'' <- go nodes env' e2 go nodes env'' e3 Label _ e -> go nodes env e getSimpleType :: forall a. C.Typed a => Stream a -> C.SimpleType getSimpleType _ = C.simpleType (C.typeOf :: C.Type a)
baf5aa2302926e609aae865bb5d5e3a21ae52073a5996726b6b5e2a9ea6767c0
dinosaure/tuyau
tuyau_mirage_tcp.mli
type ('stack, 'ip) endpoint = { stack : 'stack ; keepalive : Mirage_protocols.Keepalive.t option ; nodelay : bool ; ip : 'ip ; port : int } type 'stack configuration = { stack : 'stack ; keepalive : Mirage_protocols.Keepalive.t option ; nodelay : bool ; port : int } module Make (StackV4 : Mirage_stack.V4) : sig include Tuyau_mirage.T with type endpoint = (StackV4.t, Ipaddr.V4.t) endpoint and type configuration = StackV4.t configuration val dst : protocol -> Ipaddr.V4.t * int end
null
https://raw.githubusercontent.com/dinosaure/tuyau/8ed849805153f5dfad6c045782e3d20ef06cd9b6/mirage/tuyau_mirage_tcp.mli
ocaml
type ('stack, 'ip) endpoint = { stack : 'stack ; keepalive : Mirage_protocols.Keepalive.t option ; nodelay : bool ; ip : 'ip ; port : int } type 'stack configuration = { stack : 'stack ; keepalive : Mirage_protocols.Keepalive.t option ; nodelay : bool ; port : int } module Make (StackV4 : Mirage_stack.V4) : sig include Tuyau_mirage.T with type endpoint = (StackV4.t, Ipaddr.V4.t) endpoint and type configuration = StackV4.t configuration val dst : protocol -> Ipaddr.V4.t * int end
ac3dc9d2aa8336336c68a4da2a0c4cd3080b7013202dab684dd8718b10831f3c
mlabs-haskell/ogmios-datum-cache
Error.hs
module Api.Error ( throwJsonError, JsonError (JsonError), ) where import Control.Monad.Catch (MonadThrow, throwM) import Data.Aeson (ToJSON (toJSON), encode, object, (.=)) import Data.String (IsString) import Data.Text (Text) import Network.HTTP.Types (hContentType) import Servant ( ServerError, errBody, errHeaders, ) newtype JsonError = JsonError { jsonError :: Text } deriving newtype (IsString) instance ToJSON JsonError where toJSON err = object ["error" .= err.jsonError] -- fourmolu is broken :( {- ORMOLU_DISABLE -} throwJsonError :: (MonadThrow m) => ServerError -> JsonError -> m b throwJsonError err json = throwM err { errBody = encode json , errHeaders = [jsonHeader] } where jsonHeader = (hContentType, "application/json;charset=utf-8") ORMOLU_ENABLE
null
https://raw.githubusercontent.com/mlabs-haskell/ogmios-datum-cache/f7c748ef240b83ca1f1415d5cb7dd8f87400a426/src/Api/Error.hs
haskell
fourmolu is broken :( ORMOLU_DISABLE
module Api.Error ( throwJsonError, JsonError (JsonError), ) where import Control.Monad.Catch (MonadThrow, throwM) import Data.Aeson (ToJSON (toJSON), encode, object, (.=)) import Data.String (IsString) import Data.Text (Text) import Network.HTTP.Types (hContentType) import Servant ( ServerError, errBody, errHeaders, ) newtype JsonError = JsonError { jsonError :: Text } deriving newtype (IsString) instance ToJSON JsonError where toJSON err = object ["error" .= err.jsonError] throwJsonError :: (MonadThrow m) => ServerError -> JsonError -> m b throwJsonError err json = throwM err { errBody = encode json , errHeaders = [jsonHeader] } where jsonHeader = (hContentType, "application/json;charset=utf-8") ORMOLU_ENABLE
f5afc215632a9f5ee3a0475447a797f6ab956c3ff642a9186f4a0bee607bcfc3
spechub/Hets
Print.hs
| Module : ./THF / Print.hs Description : Seveal Pretty instances . Copyright : ( c ) , DFKI Bremen 2011 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : portable Pretty instances some data structures of As , Sign and Cons Module : ./THF/Print.hs Description : Seveal Pretty instances. Copyright : (c) A. Tsogias, DFKI Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : portable Pretty instances some data structures of As, Sign and Cons -} module THF.Print where import Common.DocUtils import Common.Doc import Common.AS_Annotation import THF.Cons import THF.Sign import THF.PrintTHF import THF.As (THFFormula, FormulaRole (..)) import qualified Data.Map as Map import Data.Maybe (fromMaybe) {- ----------------------------------------------------------------------------- Some pretty instances for datastructures defined in Cons and Sign and other print methods ----------------------------------------------------------------------------- -} instance Pretty BasicSpecTHF where pretty (BasicSpecTHF a) = printTPTPTHF a instance Pretty SymbolTHF where pretty s = case symType s of ST_Const t -> pretty (symId s) <+> text ":" <+> pretty t ST_Type k -> pretty (symId s) <+> text ":" <+> pretty k instance Pretty SignTHF where pretty s = let ts = Map.foldr (\ ti d -> d $+$ pretty ti) empty (types s) cs = Map.foldr (\ ci d -> d $+$ pretty ci) empty (consts s) in text "%Types:" $+$ ts $++$ text "%Constants: " $+$ cs instance Pretty Kind where pretty k = case k of Kind -> text "$tType" instance Pretty Type where pretty t = case t of TType -> text "$tType" OType -> text "$o" IType -> text "$i" MapType t1 t2 -> pretty t1 <+> text ">" <+> pretty t2 CType c -> prettyConstant c SType st -> prettyAtomicSystemWord st VType v -> prettyUpperWord v ParType t1 -> parens $ pretty t1 ProdType ts -> parens $ sepBy (map pretty ts) starSign instance Pretty TypeInfo where pretty ti = text "thf" <> parens (pretty (typeName ti) <> comma <+> text "type" <> comma <+> (pretty (typeId ti) <+> colon <+> pretty (typeKind ti)) <> pretty (typeAnno ti)) <> text "." instance Pretty ConstInfo where pretty ci = text "thf" <> parens (pretty (constName ci) <> comma <+> text "type" <> comma <+> (pretty (constId ci) <+> colon <+> pretty (constType ci)) <> pretty (constAnno ci)) <> text "." -- print the signature, with axioms and the proof goal printProblemTHF :: SignTHF -> [Named THFFormula] -> Named THFFormula -> Doc printProblemTHF sig ax gl = pretty sig $++$ text "%Axioms:" $+$ foldl (\ d e -> d $+$ printNamedSentenceTHF (Just Axiom) e) empty ax $++$ text "%Goal:" $+$ printNamedSentenceTHF (Just Conjecture) gl -- print a Named Sentence printNamedSentenceTHF :: Maybe FormulaRole -> Named THFFormula -> Doc printNamedSentenceTHF r' f = let r = fromMaybe (if isAxiom f then Axiom else Conjecture) r' in text "thf" <> parens (text (senAttr f) <> comma <+> pretty r <> comma <+> pretty (sentence f)) <> text "."
null
https://raw.githubusercontent.com/spechub/Hets/bbaa9dd2d2e5eb1f2fd3ec6c799a6dde7dee6da2/THF/Print.hs
haskell
----------------------------------------------------------------------------- Some pretty instances for datastructures defined in Cons and Sign and other print methods ----------------------------------------------------------------------------- print the signature, with axioms and the proof goal print a Named Sentence
| Module : ./THF / Print.hs Description : Seveal Pretty instances . Copyright : ( c ) , DFKI Bremen 2011 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : provisional Portability : portable Pretty instances some data structures of As , Sign and Cons Module : ./THF/Print.hs Description : Seveal Pretty instances. Copyright : (c) A. Tsogias, DFKI Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : provisional Portability : portable Pretty instances some data structures of As, Sign and Cons -} module THF.Print where import Common.DocUtils import Common.Doc import Common.AS_Annotation import THF.Cons import THF.Sign import THF.PrintTHF import THF.As (THFFormula, FormulaRole (..)) import qualified Data.Map as Map import Data.Maybe (fromMaybe) instance Pretty BasicSpecTHF where pretty (BasicSpecTHF a) = printTPTPTHF a instance Pretty SymbolTHF where pretty s = case symType s of ST_Const t -> pretty (symId s) <+> text ":" <+> pretty t ST_Type k -> pretty (symId s) <+> text ":" <+> pretty k instance Pretty SignTHF where pretty s = let ts = Map.foldr (\ ti d -> d $+$ pretty ti) empty (types s) cs = Map.foldr (\ ci d -> d $+$ pretty ci) empty (consts s) in text "%Types:" $+$ ts $++$ text "%Constants: " $+$ cs instance Pretty Kind where pretty k = case k of Kind -> text "$tType" instance Pretty Type where pretty t = case t of TType -> text "$tType" OType -> text "$o" IType -> text "$i" MapType t1 t2 -> pretty t1 <+> text ">" <+> pretty t2 CType c -> prettyConstant c SType st -> prettyAtomicSystemWord st VType v -> prettyUpperWord v ParType t1 -> parens $ pretty t1 ProdType ts -> parens $ sepBy (map pretty ts) starSign instance Pretty TypeInfo where pretty ti = text "thf" <> parens (pretty (typeName ti) <> comma <+> text "type" <> comma <+> (pretty (typeId ti) <+> colon <+> pretty (typeKind ti)) <> pretty (typeAnno ti)) <> text "." instance Pretty ConstInfo where pretty ci = text "thf" <> parens (pretty (constName ci) <> comma <+> text "type" <> comma <+> (pretty (constId ci) <+> colon <+> pretty (constType ci)) <> pretty (constAnno ci)) <> text "." printProblemTHF :: SignTHF -> [Named THFFormula] -> Named THFFormula -> Doc printProblemTHF sig ax gl = pretty sig $++$ text "%Axioms:" $+$ foldl (\ d e -> d $+$ printNamedSentenceTHF (Just Axiom) e) empty ax $++$ text "%Goal:" $+$ printNamedSentenceTHF (Just Conjecture) gl printNamedSentenceTHF :: Maybe FormulaRole -> Named THFFormula -> Doc printNamedSentenceTHF r' f = let r = fromMaybe (if isAxiom f then Axiom else Conjecture) r' in text "thf" <> parens (text (senAttr f) <> comma <+> pretty r <> comma <+> pretty (sentence f)) <> text "."
5964f9708aeb2c3270f352afc9fbe640265daff6ef5097acfcf5200ec2c8e663
mlabs-haskell/plutus-pioneer-program
Model.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE NumericUnderscores #-} # LANGUAGE OverloadedStrings # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} module Spec.Model ( tests , test , TSModel (..) ) where import Control.Lens hiding (elements) import Control.Monad (void, when) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (isJust, isNothing) import Data.Monoid (Last (..)) import Data.String (IsString (..)) import Data.Text (Text) import Plutus.Contract.Test import Plutus.Contract.Test.ContractModel import Plutus.Trace.Emulator import Ledger hiding (singleton) import Ledger.Ada as Ada import Ledger.Value import Test.QuickCheck import Test.Tasty import Test.Tasty.QuickCheck import Week08.TokenSale (TokenSale (..), TSStartSchema', TSUseSchema, startEndpoint', useEndpoints, nftName) data TSState = TSState { _tssPrice :: !Integer , _tssLovelace :: !Integer , _tssToken :: !Integer } deriving Show makeLenses ''TSState newtype TSModel = TSModel {_tsModel :: Map Wallet TSState} deriving Show makeLenses ''TSModel tests :: TestTree tests = testProperty "token sale model" prop_TS instance ContractModel TSModel where data Action TSModel = Start Wallet | SetPrice Wallet Wallet Integer | AddTokens Wallet Wallet Integer | Withdraw Wallet Wallet Integer Integer | BuyTokens Wallet Wallet Integer deriving (Show, Eq) data ContractInstanceKey TSModel w s e where StartKey :: Wallet -> ContractInstanceKey TSModel (Last TokenSale) TSStartSchema' Text UseKey :: Wallet -> Wallet -> ContractInstanceKey TSModel () TSUseSchema Text instanceTag key _ = fromString $ "instance tag for: " ++ show key arbitraryAction _ = oneof $ (Start <$> genWallet) : [ SetPrice <$> genWallet <*> genWallet <*> genNonNeg ] ++ [ AddTokens <$> genWallet <*> genWallet <*> genNonNeg ] ++ [ BuyTokens <$> genWallet <*> genWallet <*> genNonNeg ] ++ [ Withdraw <$> genWallet <*> genWallet <*> genNonNeg <*> genNonNeg ] initialState = TSModel Map.empty nextState (Start w) = do withdraw w $ nfts Map.! w (tsModel . at w) $= Just (TSState 0 0 0) wait 1 nextState (SetPrice v w p) = do when (v == w) $ (tsModel . ix v . tssPrice) $= p wait 1 nextState (AddTokens v w n) = do started <- hasStarted v -- has the token sale started? when (n > 0 && started) $ do bc <- askModelState $ view $ balanceChange w let token = tokens Map.! v when (tokenAmt + assetClassValueOf bc token >= n) $ do -- does the wallet have the tokens to give? withdraw w $ assetClassValue token n (tsModel . ix v . tssToken) $~ (+ n) wait 1 nextState (BuyTokens v w n) = do when (n > 0) $ do m <- getTSState v case m of Just t | t ^. tssToken >= n -> do let p = t ^. tssPrice l = p * n withdraw w $ lovelaceValueOf l deposit w $ assetClassValue (tokens Map.! v) n (tsModel . ix v . tssLovelace) $~ (+ l) (tsModel . ix v . tssToken) $~ (+ (- n)) _ -> return () wait 1 nextState (Withdraw v w n l) = do when (v == w) $ do m <- getTSState v case m of Just t | t ^. tssToken >= n && t ^. tssLovelace >= l -> do deposit w $ lovelaceValueOf l <> assetClassValue (tokens Map.! w) n (tsModel . ix v . tssLovelace) $~ (+ (- l)) (tsModel . ix v . tssToken) $~ (+ (- n)) _ -> return () wait 1 perform h _ cmd = case cmd of (Start w) -> callEndpoint @"start" (h $ StartKey w) (nftCurrencies Map.! w, tokenCurrencies Map.! w, tokenNames Map.! w) >> delay 1 (SetPrice v w p) -> callEndpoint @"set price" (h $ UseKey v w) p >> delay 1 (AddTokens v w n) -> callEndpoint @"add tokens" (h $ UseKey v w) n >> delay 1 (BuyTokens v w n) -> callEndpoint @"buy tokens" (h $ UseKey v w) n >> delay 1 (Withdraw v w n l) -> callEndpoint @"withdraw" (h $ UseKey v w) (n, l) >> delay 1 precondition s (Start w) = isNothing $ getTSState' s w precondition s (SetPrice v _ _) = isJust $ getTSState' s v precondition s (AddTokens v _ _) = isJust $ getTSState' s v precondition s (BuyTokens v _ _) = isJust $ getTSState' s v precondition s (Withdraw v _ _ _) = isJust $ getTSState' s v deriving instance Eq (ContractInstanceKey TSModel w s e) deriving instance Show (ContractInstanceKey TSModel w s e) getTSState' :: ModelState TSModel -> Wallet -> Maybe TSState getTSState' s v = s ^. contractState . tsModel . at v getTSState :: Wallet -> Spec TSModel (Maybe TSState) getTSState v = do s <- getModelState return $ getTSState' s v hasStarted :: Wallet -> Spec TSModel Bool hasStarted v = isJust <$> getTSState v w1, w2 :: Wallet w1 = Wallet 1 w2 = Wallet 2 wallets :: [Wallet] wallets = [w1, w2] tokenCurrencies, nftCurrencies :: Map Wallet CurrencySymbol tokenCurrencies = Map.fromList $ zip wallets ["aa", "bb"] nftCurrencies = Map.fromList $ zip wallets ["01", "02"] tokenNames :: Map Wallet TokenName tokenNames = Map.fromList $ zip wallets ["A", "B"] tokens :: Map Wallet AssetClass tokens = Map.fromList [(w, AssetClass (tokenCurrencies Map.! w, tokenNames Map.! w)) | w <- wallets] nftAssets :: Map Wallet AssetClass nftAssets = Map.fromList [(w, AssetClass (nftCurrencies Map.! w, nftName)) | w <- wallets] nfts :: Map Wallet Value nfts = Map.fromList [(w, assetClassValue (nftAssets Map.! w) 1) | w <- wallets] tss :: Map Wallet TokenSale tss = Map.fromList [ (w, TokenSale { tsSeller = pubKeyHash $ walletPubKey w , tsToken = tokens Map.! w , tsNFT = nftAssets Map.! w }) | w <- wallets ] delay :: Int -> EmulatorTrace () delay = void . waitNSlots . fromIntegral instanceSpec :: [ContractInstanceSpec TSModel] instanceSpec = [ContractInstanceSpec (StartKey w) w startEndpoint' | w <- wallets] ++ [ContractInstanceSpec (UseKey v w) w $ useEndpoints $ tss Map.! v | v <- wallets, w <- wallets] genWallet :: Gen Wallet genWallet = elements wallets genNonNeg :: Gen Integer genNonNeg = getNonNegative <$> arbitrary tokenAmt :: Integer tokenAmt = 1_000 prop_TS :: Actions TSModel -> Property prop_TS = withMaxSuccess 100 . propRunActionsWithOptions (defaultCheckOptions & emulatorConfig .~ EmulatorConfig (Left d)) instanceSpec (const $ pure True) where d :: InitialDistribution d = Map.fromList $ [ ( w , lovelaceValueOf 1000_000_000 <> (nfts Map.! w) <> mconcat [assetClassValue t tokenAmt | t <- Map.elems tokens]) | w <- wallets ] test :: IO () test = quickCheck prop_TS
null
https://raw.githubusercontent.com/mlabs-haskell/plutus-pioneer-program/b50b196d57dc35559b7526fe17b49dd2ba4790bc/code/week08/test/Spec/Model.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveAnyClass # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE NumericUnderscores # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE TypeOperators # has the token sale started? does the wallet have the tokens to give?
# LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Spec.Model ( tests , test , TSModel (..) ) where import Control.Lens hiding (elements) import Control.Monad (void, when) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (isJust, isNothing) import Data.Monoid (Last (..)) import Data.String (IsString (..)) import Data.Text (Text) import Plutus.Contract.Test import Plutus.Contract.Test.ContractModel import Plutus.Trace.Emulator import Ledger hiding (singleton) import Ledger.Ada as Ada import Ledger.Value import Test.QuickCheck import Test.Tasty import Test.Tasty.QuickCheck import Week08.TokenSale (TokenSale (..), TSStartSchema', TSUseSchema, startEndpoint', useEndpoints, nftName) data TSState = TSState { _tssPrice :: !Integer , _tssLovelace :: !Integer , _tssToken :: !Integer } deriving Show makeLenses ''TSState newtype TSModel = TSModel {_tsModel :: Map Wallet TSState} deriving Show makeLenses ''TSModel tests :: TestTree tests = testProperty "token sale model" prop_TS instance ContractModel TSModel where data Action TSModel = Start Wallet | SetPrice Wallet Wallet Integer | AddTokens Wallet Wallet Integer | Withdraw Wallet Wallet Integer Integer | BuyTokens Wallet Wallet Integer deriving (Show, Eq) data ContractInstanceKey TSModel w s e where StartKey :: Wallet -> ContractInstanceKey TSModel (Last TokenSale) TSStartSchema' Text UseKey :: Wallet -> Wallet -> ContractInstanceKey TSModel () TSUseSchema Text instanceTag key _ = fromString $ "instance tag for: " ++ show key arbitraryAction _ = oneof $ (Start <$> genWallet) : [ SetPrice <$> genWallet <*> genWallet <*> genNonNeg ] ++ [ AddTokens <$> genWallet <*> genWallet <*> genNonNeg ] ++ [ BuyTokens <$> genWallet <*> genWallet <*> genNonNeg ] ++ [ Withdraw <$> genWallet <*> genWallet <*> genNonNeg <*> genNonNeg ] initialState = TSModel Map.empty nextState (Start w) = do withdraw w $ nfts Map.! w (tsModel . at w) $= Just (TSState 0 0 0) wait 1 nextState (SetPrice v w p) = do when (v == w) $ (tsModel . ix v . tssPrice) $= p wait 1 nextState (AddTokens v w n) = do when (n > 0 && started) $ do bc <- askModelState $ view $ balanceChange w let token = tokens Map.! v withdraw w $ assetClassValue token n (tsModel . ix v . tssToken) $~ (+ n) wait 1 nextState (BuyTokens v w n) = do when (n > 0) $ do m <- getTSState v case m of Just t | t ^. tssToken >= n -> do let p = t ^. tssPrice l = p * n withdraw w $ lovelaceValueOf l deposit w $ assetClassValue (tokens Map.! v) n (tsModel . ix v . tssLovelace) $~ (+ l) (tsModel . ix v . tssToken) $~ (+ (- n)) _ -> return () wait 1 nextState (Withdraw v w n l) = do when (v == w) $ do m <- getTSState v case m of Just t | t ^. tssToken >= n && t ^. tssLovelace >= l -> do deposit w $ lovelaceValueOf l <> assetClassValue (tokens Map.! w) n (tsModel . ix v . tssLovelace) $~ (+ (- l)) (tsModel . ix v . tssToken) $~ (+ (- n)) _ -> return () wait 1 perform h _ cmd = case cmd of (Start w) -> callEndpoint @"start" (h $ StartKey w) (nftCurrencies Map.! w, tokenCurrencies Map.! w, tokenNames Map.! w) >> delay 1 (SetPrice v w p) -> callEndpoint @"set price" (h $ UseKey v w) p >> delay 1 (AddTokens v w n) -> callEndpoint @"add tokens" (h $ UseKey v w) n >> delay 1 (BuyTokens v w n) -> callEndpoint @"buy tokens" (h $ UseKey v w) n >> delay 1 (Withdraw v w n l) -> callEndpoint @"withdraw" (h $ UseKey v w) (n, l) >> delay 1 precondition s (Start w) = isNothing $ getTSState' s w precondition s (SetPrice v _ _) = isJust $ getTSState' s v precondition s (AddTokens v _ _) = isJust $ getTSState' s v precondition s (BuyTokens v _ _) = isJust $ getTSState' s v precondition s (Withdraw v _ _ _) = isJust $ getTSState' s v deriving instance Eq (ContractInstanceKey TSModel w s e) deriving instance Show (ContractInstanceKey TSModel w s e) getTSState' :: ModelState TSModel -> Wallet -> Maybe TSState getTSState' s v = s ^. contractState . tsModel . at v getTSState :: Wallet -> Spec TSModel (Maybe TSState) getTSState v = do s <- getModelState return $ getTSState' s v hasStarted :: Wallet -> Spec TSModel Bool hasStarted v = isJust <$> getTSState v w1, w2 :: Wallet w1 = Wallet 1 w2 = Wallet 2 wallets :: [Wallet] wallets = [w1, w2] tokenCurrencies, nftCurrencies :: Map Wallet CurrencySymbol tokenCurrencies = Map.fromList $ zip wallets ["aa", "bb"] nftCurrencies = Map.fromList $ zip wallets ["01", "02"] tokenNames :: Map Wallet TokenName tokenNames = Map.fromList $ zip wallets ["A", "B"] tokens :: Map Wallet AssetClass tokens = Map.fromList [(w, AssetClass (tokenCurrencies Map.! w, tokenNames Map.! w)) | w <- wallets] nftAssets :: Map Wallet AssetClass nftAssets = Map.fromList [(w, AssetClass (nftCurrencies Map.! w, nftName)) | w <- wallets] nfts :: Map Wallet Value nfts = Map.fromList [(w, assetClassValue (nftAssets Map.! w) 1) | w <- wallets] tss :: Map Wallet TokenSale tss = Map.fromList [ (w, TokenSale { tsSeller = pubKeyHash $ walletPubKey w , tsToken = tokens Map.! w , tsNFT = nftAssets Map.! w }) | w <- wallets ] delay :: Int -> EmulatorTrace () delay = void . waitNSlots . fromIntegral instanceSpec :: [ContractInstanceSpec TSModel] instanceSpec = [ContractInstanceSpec (StartKey w) w startEndpoint' | w <- wallets] ++ [ContractInstanceSpec (UseKey v w) w $ useEndpoints $ tss Map.! v | v <- wallets, w <- wallets] genWallet :: Gen Wallet genWallet = elements wallets genNonNeg :: Gen Integer genNonNeg = getNonNegative <$> arbitrary tokenAmt :: Integer tokenAmt = 1_000 prop_TS :: Actions TSModel -> Property prop_TS = withMaxSuccess 100 . propRunActionsWithOptions (defaultCheckOptions & emulatorConfig .~ EmulatorConfig (Left d)) instanceSpec (const $ pure True) where d :: InitialDistribution d = Map.fromList $ [ ( w , lovelaceValueOf 1000_000_000 <> (nfts Map.! w) <> mconcat [assetClassValue t tokenAmt | t <- Map.elems tokens]) | w <- wallets ] test :: IO () test = quickCheck prop_TS
9fe3912ed201d2c3ca246a4227be5869e923ff4769609d382650843c3732fe6c
ocaml-multicore/ocaml-tsan
test_caml_runparams.ml
(* TEST include runtime_events ocamlrunparam += ",e=4" *) (* We set the ring buffer size smaller and witness that we do indeed lose events. *) open Runtime_events let lost_any_events = ref false let lost_events _domain_id num = if num > 0 then lost_any_events := true let () = start (); let cursor = create_cursor None in let callbacks = Callbacks.create ~lost_events () in for epoch = 1 to 20 do Gc.full_major () done; ignore(read_poll cursor callbacks None); assert(!lost_any_events)
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/f54002470cc6ab780963cc81b11a85a820a40819/testsuite/tests/lib-runtime-events/test_caml_runparams.ml
ocaml
TEST include runtime_events ocamlrunparam += ",e=4" We set the ring buffer size smaller and witness that we do indeed lose events.
open Runtime_events let lost_any_events = ref false let lost_events _domain_id num = if num > 0 then lost_any_events := true let () = start (); let cursor = create_cursor None in let callbacks = Callbacks.create ~lost_events () in for epoch = 1 to 20 do Gc.full_major () done; ignore(read_poll cursor callbacks None); assert(!lost_any_events)
a349f451ef38c7922c08ea353c095aee2bf80bc71332ed1cc35736e3bedb8090
onyx-platform/learn-onyx
challenge_6_1_test.clj
(ns workshop.jobs.challenge-6-1-test (:require [clojure.test :refer [deftest is]] [onyx.test-helper :refer [with-test-env feedback-exception!]] [workshop.challenge-6-1 :as c] [workshop.workshop-utils :as u] [onyx.api])) In the previous challenge , we used the aggregate to ;; buffer all segments in memory. It's more common to maintain ;; a running, compounded aggregate. In this challenge, your goal is to create a 2 hour fixed window that sums the values of : bytes - sent in every segment . To help you avoid the cruft ;; of coordindating job completion, we reused all of the atom ;; and promise code from the previous example. Make sure you understand ;; how that works so you'll have a smooth learning experience ;; with the rest of the challenges. ;; ;; Try it with: ;; ` lein test workshop.jobs.challenge-6 - 1 - test ` ;; (def input [{:event-id 1 :event-time #inst "2015-11-20T02:59:00.000-00:00" :bytes-sent 400} {:event-id 2 :event-time #inst "2015-11-20T06:58:00.000-00:00" :bytes-sent 50} {:event-id 3 :event-time #inst "2015-11-20T09:04:00.000-00:00" :bytes-sent 320} {:event-id 4 :event-time #inst "2015-11-20T04:00:00.000-00:00" :bytes-sent 1560} {:event-id 5 :event-time #inst "2015-11-20T06:05:00.000-00:00" :bytes-sent 350} {:event-id 6 :event-time #inst "2015-11-20T03:00:00.000-00:00" :bytes-sent 120} {:event-id 7 :event-time #inst "2015-11-20T07:23:00.000-00:00" :bytes-sent 640} {:event-id 8 :event-time #inst "2015-11-20T04:26:00.000-00:00" :bytes-sent 560} {:event-id 9 :event-time #inst "2015-11-20T01:41:59.000-00:00" :bytes-sent 1024}]) (def expected-output {[#inst "2015-11-20T00:00:00.000-00:00" #inst "2015-11-20T01:59:59.999-00:00"] 1024 [#inst "2015-11-20T02:00:00.000-00:00" #inst "2015-11-20T03:59:59.999-00:00"] 520 [#inst "2015-11-20T04:00:00.000-00:00" #inst "2015-11-20T05:59:59.999-00:00"] 2120 [#inst "2015-11-20T06:00:00.000-00:00" #inst "2015-11-20T07:59:59.999-00:00"] 1040 [#inst "2015-11-20T08:00:00.000-00:00" #inst "2015-11-20T09:59:59.999-00:00"] 320}) (deftest test-level-6-challenge-1 (let [cluster-id (java.util.UUID/randomUUID) env-config (u/load-env-config cluster-id) peer-config (u/load-peer-config cluster-id) catalog (c/build-catalog) lifecycles (c/build-lifecycles) n-peers (u/n-peers catalog c/workflow) n-trigger-fires (atom 0) p (promise)] (reset! c/fired-window-state {}) (with-test-env [test-env [n-peers env-config peer-config]] (add-watch c/fired-window-state :watcher (fn [k r old new] (let [n (swap! n-trigger-fires inc)] This time , we have 5 discete buckets - so we wait for 5 updates . (when (= n 5) (deliver p true))))) (u/bind-inputs! lifecycles {:read-segments input}) (let [job {:workflow c/workflow :catalog catalog :lifecycles lifecycles :windows c/windows :triggers c/triggers :task-scheduler :onyx.task-scheduler/balanced} job-id (:job-id (onyx.api/submit-job peer-config job))] (assert job-id "Job was not successfully submitted") (feedback-exception! peer-config job-id) @p (is (= expected-output @c/fired-window-state))))))
null
https://raw.githubusercontent.com/onyx-platform/learn-onyx/6bf1936f35d26e3c8cf171b5971e1bc95e82b3c8/test/workshop/jobs/challenge_6_1_test.clj
clojure
buffer all segments in memory. It's more common to maintain a running, compounded aggregate. In this challenge, your of coordindating job completion, we reused all of the atom and promise code from the previous example. Make sure you understand how that works so you'll have a smooth learning experience with the rest of the challenges. Try it with:
(ns workshop.jobs.challenge-6-1-test (:require [clojure.test :refer [deftest is]] [onyx.test-helper :refer [with-test-env feedback-exception!]] [workshop.challenge-6-1 :as c] [workshop.workshop-utils :as u] [onyx.api])) In the previous challenge , we used the aggregate to goal is to create a 2 hour fixed window that sums the values of : bytes - sent in every segment . To help you avoid the cruft ` lein test workshop.jobs.challenge-6 - 1 - test ` (def input [{:event-id 1 :event-time #inst "2015-11-20T02:59:00.000-00:00" :bytes-sent 400} {:event-id 2 :event-time #inst "2015-11-20T06:58:00.000-00:00" :bytes-sent 50} {:event-id 3 :event-time #inst "2015-11-20T09:04:00.000-00:00" :bytes-sent 320} {:event-id 4 :event-time #inst "2015-11-20T04:00:00.000-00:00" :bytes-sent 1560} {:event-id 5 :event-time #inst "2015-11-20T06:05:00.000-00:00" :bytes-sent 350} {:event-id 6 :event-time #inst "2015-11-20T03:00:00.000-00:00" :bytes-sent 120} {:event-id 7 :event-time #inst "2015-11-20T07:23:00.000-00:00" :bytes-sent 640} {:event-id 8 :event-time #inst "2015-11-20T04:26:00.000-00:00" :bytes-sent 560} {:event-id 9 :event-time #inst "2015-11-20T01:41:59.000-00:00" :bytes-sent 1024}]) (def expected-output {[#inst "2015-11-20T00:00:00.000-00:00" #inst "2015-11-20T01:59:59.999-00:00"] 1024 [#inst "2015-11-20T02:00:00.000-00:00" #inst "2015-11-20T03:59:59.999-00:00"] 520 [#inst "2015-11-20T04:00:00.000-00:00" #inst "2015-11-20T05:59:59.999-00:00"] 2120 [#inst "2015-11-20T06:00:00.000-00:00" #inst "2015-11-20T07:59:59.999-00:00"] 1040 [#inst "2015-11-20T08:00:00.000-00:00" #inst "2015-11-20T09:59:59.999-00:00"] 320}) (deftest test-level-6-challenge-1 (let [cluster-id (java.util.UUID/randomUUID) env-config (u/load-env-config cluster-id) peer-config (u/load-peer-config cluster-id) catalog (c/build-catalog) lifecycles (c/build-lifecycles) n-peers (u/n-peers catalog c/workflow) n-trigger-fires (atom 0) p (promise)] (reset! c/fired-window-state {}) (with-test-env [test-env [n-peers env-config peer-config]] (add-watch c/fired-window-state :watcher (fn [k r old new] (let [n (swap! n-trigger-fires inc)] This time , we have 5 discete buckets - so we wait for 5 updates . (when (= n 5) (deliver p true))))) (u/bind-inputs! lifecycles {:read-segments input}) (let [job {:workflow c/workflow :catalog catalog :lifecycles lifecycles :windows c/windows :triggers c/triggers :task-scheduler :onyx.task-scheduler/balanced} job-id (:job-id (onyx.api/submit-job peer-config job))] (assert job-id "Job was not successfully submitted") (feedback-exception! peer-config job-id) @p (is (= expected-output @c/fired-window-state))))))
41d1775bb09d6e0ebbbeb37a7564ea20b4d76eb02012ff7694dbe1b80d29c2b9
well-typed/recover-rtti
Classify.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE NamedFieldPuns # {-# LANGUAGE PatternSynonyms #-} # LANGUAGE QuantifiedConstraints # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} # LANGUAGE TupleSections # # LANGUAGE TypeApplications # {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - orphans # module Debug.RecoverRTTI.Classify ( -- * Classification classify -- * User-defined types , Classified(..) , fromUserDefined -- * Showing values , anythingToString , canShowPrim , canShowClassified , canShowClassified_ * Patterns for common shapes of ' Elems ' ( exported for the tests ) , pattern ElemK , pattern ElemU , pattern ElemKK , pattern ElemUU , pattern ElemKU , pattern ElemUK ) where import Control.Monad.Except import Data.HashMap.Lazy (HashMap) import Data.IntMap (IntMap) import Data.Map (Map) import Data.Sequence (Seq) import Data.Set (Set) import Data.SOP import Data.SOP.Dict import Data.Tree (Tree) import Data.Void import GHC.Exts.Heap (Closure) import GHC.Real import System.IO.Unsafe (unsafePerformIO) import Unsafe.Coerce (unsafeCoerce) import qualified Data.Foldable as Foldable import qualified Data.HashMap.Internal.Array as HashMap (Array) import qualified Data.HashMap.Internal.Array as HashMap.Array import qualified Data.HashMap.Lazy as HashMap import qualified Data.Map as Map import qualified Data.Primitive.Array as Prim.Array import qualified Data.Primitive.Array as Prim (Array) import qualified Data.Tree as Tree import qualified Data.Vector as Vector.Boxed import Debug.RecoverRTTI.Classifier import Debug.RecoverRTTI.Constraint import Debug.RecoverRTTI.FlatClosure import Debug.RecoverRTTI.Modules import Debug.RecoverRTTI.Nat import Debug.RecoverRTTI.Tuple import Debug.RecoverRTTI.Util import Debug.RecoverRTTI.Wrappers {------------------------------------------------------------------------------- Classification -------------------------------------------------------------------------------} classifyIO :: a -> ExceptT Closure IO (Classifier a) classifyIO x = do closure <- lift $ getBoxedClosureData (asBox x) case closure of -- Primitive ( ghc - prim ) -- -- GHC.Types (inKnownModule GhcTypes -> Just "True") -> return $ mustBe $ C_Prim C_Bool (inKnownModule GhcTypes -> Just "False") -> return $ mustBe $ C_Prim C_Bool (inKnownModule GhcTypes -> Just "C#") -> return $ mustBe $ C_Prim C_Char (inKnownModule GhcTypes -> Just "D#") -> return $ mustBe $ C_Prim C_Double (inKnownModule GhcTypes -> Just "F#") -> return $ mustBe $ C_Prim C_Float (inKnownModule GhcTypes -> Just "I#") -> return $ mustBe $ C_Prim C_Int (inKnownModule GhcTypes -> Just "LT") -> return $ mustBe $ C_Prim C_Ordering (inKnownModule GhcTypes -> Just "GT") -> return $ mustBe $ C_Prim C_Ordering (inKnownModule GhcTypes -> Just "EQ") -> return $ mustBe $ C_Prim C_Ordering (inKnownModule GhcTypes -> Just "W#") -> return $ mustBe $ C_Prim C_Word -- GHC.Tuple (inKnownModule GhcTuple -> Just "()") -> return $ mustBe $ C_Prim C_Unit -- GHC.Int (inKnownModule GhcInt -> Just "I8#") -> return $ mustBe $ C_Prim C_Int8 (inKnownModule GhcInt -> Just "I16#") -> return $ mustBe $ C_Prim C_Int16 (inKnownModule GhcInt -> Just "I32#") -> return $ mustBe $ C_Prim C_Int32 (inKnownModule GhcInt -> Just "I64#") -> return $ mustBe $ C_Prim C_Int64 -- GHC.Integer (inKnownModule GhcIntegerType -> Just "S#") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcIntegerType -> Just "Jp#") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcIntegerType -> Just "Jn#") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcNumInteger -> Just "IS") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcNumInteger -> Just "IP") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcNumInteger -> Just "IN") -> return $ mustBe $ C_Prim C_Integer GHC.Word (inKnownModule GhcWord -> Just "W8#") -> return $ mustBe $ C_Prim C_Word8 (inKnownModule GhcWord -> Just "W16#") -> return $ mustBe $ C_Prim C_Word16 (inKnownModule GhcWord -> Just "W32#") -> return $ mustBe $ C_Prim C_Word32 (inKnownModule GhcWord -> Just "W64#") -> return $ mustBe $ C_Prim C_Word64 -- -- String types -- -- bytestring -- bytestring changed from PS to BS in version 0.11 (inKnownModule DataByteStringInternal -> Just "PS") -> return $ mustBe $ C_Prim C_BS_Strict (inKnownModule DataByteStringInternal -> Just "BS") -> return $ mustBe $ C_Prim C_BS_Strict (inKnownModule DataByteStringLazyInternal -> Just "Empty") -> return $ mustBe $ C_Prim C_BS_Lazy (inKnownModule DataByteStringLazyInternal -> Just "Chunk") -> return $ mustBe $ C_Prim C_BS_Lazy (inKnownModule DataByteStringShortInternal -> Just "SBS") -> return $ mustBe $ C_Prim C_BS_Short -- text (inKnownModule DataTextInternal -> Just "Text") -> return $ mustBe $ C_Prim C_Text_Strict (inKnownModule DataTextInternalLazy -> Just "Chunk") -> return $ mustBe $ C_Prim C_Text_Lazy (inKnownModule DataTextInternalLazy -> Just "Empty") -> return $ mustBe $ C_Prim C_Text_Lazy -- -- Aeson -- (inKnownModule DataAesonTypesInternal -> Just "Object") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "Array") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "String") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "Number") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "Bool") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "Null") -> return $ mustBe $ C_Prim C_Value -- Compound ( ghc - prim ) -- -- Maybe (inKnownModule GhcMaybe -> Just "Nothing") -> mustBe <$> classifyMaybe (unsafeCoerce x) (inKnownModule GhcMaybe -> Just "Just") -> mustBe <$> classifyMaybe (unsafeCoerce x) -- Either (inKnownModule DataEither -> Just "Left") -> mustBe <$> classifyEither (unsafeCoerce x) (inKnownModule DataEither -> Just "Right") -> mustBe <$> classifyEither (unsafeCoerce x) -- Lists (this includes the 'String' case) (inKnownModule GhcTypes -> Just "[]") -> mustBe <$> classifyList (unsafeCoerce x) (inKnownModule GhcTypes -> Just ":") -> mustBe <$> classifyList (unsafeCoerce x) -- Ratio (inKnownModule GhcReal -> Just ":%") -> mustBe <$> classifyRatio (unsafeCoerce x) -- Set (inKnownModule DataSetInternal -> Just "Tip") -> mustBe <$> classifySet (unsafeCoerce x) (inKnownModule DataSetInternal -> Just "Bin") -> mustBe <$> classifySet (unsafeCoerce x) -- Map (inKnownModule DataMapInternal -> Just "Tip") -> mustBe <$> classifyMap (unsafeCoerce x) (inKnownModule DataMapInternal -> Just "Bin") -> mustBe <$> classifyMap (unsafeCoerce x) -- IntSet (inKnownModule DataIntSetInternal -> Just "Bin") -> return $ mustBe $ C_Prim C_IntSet (inKnownModule DataIntSetInternal -> Just "Tip") -> return $ mustBe $ C_Prim C_IntSet (inKnownModule DataIntSetInternal -> Just "Nil") -> return $ mustBe $ C_Prim C_IntSet IntMap (inKnownModule DataIntMapInternal -> Just "Nil") -> mustBe <$> classifyIntMap (unsafeCoerce x) (inKnownModule DataIntMapInternal -> Just "Tip") -> mustBe <$> classifyIntMap (unsafeCoerce x) (inKnownModule DataIntMapInternal -> Just "Bin") -> mustBe <$> classifyIntMap (unsafeCoerce x) -- Sequence (inKnownModule DataSequenceInternal -> Just "EmptyT") -> mustBe <$> classifySequence (unsafeCoerce x) (inKnownModule DataSequenceInternal -> Just "Single") -> mustBe <$> classifySequence (unsafeCoerce x) (inKnownModule DataSequenceInternal -> Just "Deep") -> mustBe <$> classifySequence (unsafeCoerce x) -- Tree (inKnownModule DataTree -> Just "Node") -> mustBe <$> classifyTree (unsafeCoerce x) Tuples ( of size 2 .. 62 ) (inKnownModuleNested GhcTuple -> Just ( isTuple -> Just (Some validSize@(ValidSize sz _)) , verifySize sz -> Just (VerifiedSize ptrs) )) -> case liftValidSize validSize of Dict -> mustBe <$> classifyTuple ptrs -- This could also be a HashSet , which is a newtype around a HashMap ; -- we distinguish in 'classifyHashMap'. (inKnownModule DataHashMapInternal -> Just "Empty") -> mustBe <$> classifyHashMap (unsafeCoerce x) (inKnownModule DataHashMapInternal -> Just "BitmapIndexed") -> mustBe <$> classifyHashMap (unsafeCoerce x) (inKnownModule DataHashMapInternal -> Just "Leaf") -> mustBe <$> classifyHashMap (unsafeCoerce x) (inKnownModule DataHashMapInternal -> Just "Full") -> mustBe <$> classifyHashMap (unsafeCoerce x) (inKnownModule DataHashMapInternal -> Just "Collision") -> mustBe <$> classifyHashMap (unsafeCoerce x) HashMap 's internal Array type (inKnownModule DataHashMapInternalArray -> Just "Array") -> mustBe <$> classifyHMArray (unsafeCoerce x) -- Arrays from @primitive@ (inKnownModule DataPrimitiveArray -> Just "Array") -> mustBe <$> classifyPrimArray (unsafeCoerce x) (inKnownModule DataPrimitiveArray -> Just "MutableArray") -> return $ mustBe $ C_Prim C_Prim_ArrayM -- Boxed vectors (inKnownModule DataVector -> Just "Vector") -> mustBe <$> classifyVectorBoxed (unsafeCoerce x) -- Storable vectors (inKnownModule DataVectorStorable -> Just "Vector") -> return $ mustBe $ C_Prim C_Vector_Storable (inKnownModule DataVectorStorableMutable -> Just "MVector") -> return $ mustBe $ C_Prim C_Vector_StorableM -- Primitive vectors (inKnownModule DataVectorPrimitive -> Just "Vector") -> return $ mustBe $ C_Prim C_Vector_Primitive (inKnownModule DataVectorPrimitiveMutable -> Just "MVector") -> return $ mustBe $ C_Prim C_Vector_PrimitiveM -- -- Reference cells -- (inKnownModule GhcSTRef -> Just "STRef") -> return $ mustBe $ C_Prim C_STRef (inKnownModule GhcMVar -> Just "MVar") -> return $ mustBe $ C_Prim C_MVar (inKnownModule GhcConcSync -> Just "TVar") -> return $ mustBe $ C_Prim C_TVar -- -- Functions -- FunClosure {} -> return $ mustBe $ C_Prim C_Fun -- -- User defined -- ConstrClosure {} -> return $ mustBe $ C_Other (IsUserDefined (unsafeCoerce x)) -- Classification failed -- OtherClosure other -> ExceptT $ return (Left other) mustBe :: Classifier_ o b -> Classifier_ o a mustBe = unsafeCoerce -- | Classify a value -- -- Given a value of some unknown type @a@ and a classifier @Classifier a@, -- it should be sound to coerce the value to the type indicated by the -- classifier. -- -- This is also the reason not all values can be classified; in particular, -- we cannot classify values of unlifted types, as for these types coercion does not work ( this would result in a ghc runtime crash ) . classify :: a -> Either Closure (Classifier a) classify = unsafePerformIO . runExceptT . classifyIO {------------------------------------------------------------------------------- Classification for compound types -------------------------------------------------------------------------------} classifyMaybe :: Maybe a -> ExceptT Closure IO (Classifier (Maybe a)) classifyMaybe = classifyFoldable C_Maybe classifyEither :: Either a b -> ExceptT Closure IO (Classifier (Either a b)) classifyEither x = case x of Left x' -> (mustBe . C_Either . ElemKU) <$> classifyIO x' Right y' -> (mustBe . C_Either . ElemUK) <$> classifyIO y' classifyList :: [a] -> ExceptT Closure IO (Classifier [a]) classifyList = classifyFoldable c_list where -- We special case for @String@, so that @show@ will use the (overlapped) -- instance for @String@ instead of the general instance for @[a]@ c_list :: Elems o '[x] -> Classifier_ o [x] c_list (ElemK (C_Prim C_Char)) = C_Prim C_String c_list c = C_List c classifyRatio :: Ratio a -> ExceptT Closure IO (Classifier (Ratio a)) classifyRatio (x' :% _) = mustBe . C_Ratio . ElemK <$> classifyIO x' classifySet :: Set a -> ExceptT Closure IO (Classifier (Set a)) classifySet = classifyFoldable C_Set classifyMap :: Map a b -> ExceptT Closure IO (Classifier (Map a b)) classifyMap = classifyFoldablePair C_Map Map.toList classifyIntMap :: IntMap a -> ExceptT Closure IO (Classifier (IntMap a)) classifyIntMap = classifyFoldable C_IntMap classifySequence :: Seq a -> ExceptT Closure IO (Classifier (Seq a)) classifySequence = classifyFoldable C_Sequence classifyTree :: Tree a -> ExceptT Closure IO (Classifier (Tree a)) classifyTree (Tree.Node x' _) = mustBe . C_Tree . ElemK <$> classifyIO x' classifyHashMap :: HashMap a b -> ExceptT Closure IO (Classifier (HashMap a b)) classifyHashMap = classifyFoldablePair c_hashmap HashMap.toList where HashSet is a newtype around c_hashmap :: Elems o '[x, y] -> Classifier_ o (HashMap x y) c_hashmap (ElemKK c (C_Prim C_Unit)) = mustBe $ C_HashSet (ElemK c) c_hashmap c = C_HashMap c classifyHMArray :: HashMap.Array a -> ExceptT Closure IO (Classifier (HashMap.Array a)) classifyHMArray = classifyArrayLike C_HM_Array HashMap.Array.length (`HashMap.Array.index` 0) classifyPrimArray :: Prim.Array a -> ExceptT Closure IO (Classifier (Prim.Array a)) classifyPrimArray = classifyArrayLike C_Prim_Array Prim.Array.sizeofArray (`Prim.Array.indexArray` 0) classifyVectorBoxed :: Vector.Boxed.Vector a -> ExceptT Closure IO (Classifier (Vector.Boxed.Vector a)) classifyVectorBoxed = classifyArrayLike C_Vector_Boxed Vector.Boxed.length Vector.Boxed.head classifyTuple :: (SListI xs, IsValidSize (Length xs)) => NP (K Box) xs -> ExceptT Closure IO (Classifier (WrappedTuple xs)) classifyTuple ptrs = do cs <- hsequence' (hmap aux ptrs) return $ C_Tuple (Elems (hmap Elem cs)) where aux :: K Box a -> (ExceptT Closure IO :.: Classifier) a aux (K (Box x)) = Comp $ classifyIO (unsafeCoerce x) {------------------------------------------------------------------------------- Helper functions for defining classifiers -------------------------------------------------------------------------------} classifyFoldable :: Foldable f => (forall o x. Elems o '[x] -> Classifier_ o (f x)) -> f a -> ExceptT Closure IO (Classifier (f a)) classifyFoldable cc x = case Foldable.toList x of [] -> return $ mustBe $ cc ElemU x':_ -> mustBe . cc . ElemK <$> classifyIO x' classifyFoldablePair :: (forall o x y. Elems o '[x, y] -> Classifier_ o (f x y)) -> (f a b -> [(a, b)]) -> f a b -> ExceptT Closure IO (Classifier (f a b)) classifyFoldablePair cc toList x = case toList x of [] -> return $ mustBe $ cc ElemUU (x', y'):_ -> (\ca cb -> mustBe $ cc (ElemKK ca cb)) <$> classifyIO x' <*> classifyIO y' classifyArrayLike :: (forall o x. Elems o '[x] -> Classifier_ o (f x)) -> (f a -> Int) -- ^ Get the length of the array ^ Get the first element ( provided the array is not empty ) -> f a -> ExceptT Closure IO (Classifier (f a)) classifyArrayLike cc getLen getFirst x = if getLen x == 0 then return $ mustBe $ cc ElemU else do let x' = getFirst x mustBe . cc . ElemK <$> classifyIO x' ------------------------------------------------------------------------------ Patterns for common shapes of ' Elems ' This is mostly useful internally ; we export these only for the benefit of the QuickCheck generator . Most other code can treat the all types uniformly . We distinguish between which elements are ( K)nown and which ( U)nknown ------------------------------------------------------------------------------ Patterns for common shapes of 'Elems' This is mostly useful internally; we export these only for the benefit of the QuickCheck generator. Most other code can treat the all types uniformly. We distinguish between which elements are (K)nown and which (U)nknown -------------------------------------------------------------------------------} pattern ElemK :: Classifier_ o a -> Elems o '[a] pattern ElemK c = Elems (Elem c :* Nil) pattern ElemU :: Elems o '[Void] pattern ElemU = Elems (NoElem :* Nil) pattern ElemKK :: Classifier_ o a -> Classifier_ o b -> Elems o '[a, b] pattern ElemKK ca cb = Elems (Elem ca :* Elem cb :* Nil) pattern ElemUU :: Elems o '[Void, Void] pattern ElemUU = Elems (NoElem :* NoElem :* Nil) pattern ElemKU :: Classifier_ o a -> Elems o '[a, Void] pattern ElemKU c = Elems (Elem c :* NoElem :* Nil) pattern ElemUK :: Classifier_ o b -> Elems o '[Void, b] pattern ElemUK c = Elems (NoElem :* Elem c :* Nil) {------------------------------------------------------------------------------- Recognizing tuples -------------------------------------------------------------------------------} isTuple :: String -> Maybe (Some ValidSize) isTuple typ = do (a, xs, z) <- dropEnds typ guard $ a == '(' && all (== ',') xs && z == ')' toValidSize (length xs + 1) {------------------------------------------------------------------------------- Classify constructor arguments -------------------------------------------------------------------------------} -- | Bundle a value with its classifier data Classified a = Classified (Classifier a) a -- | Classify the arguments to the constructor -- -- Additionally returns the constructor name itself. fromUserDefined :: UserDefined -> (String, [Some Classified]) fromUserDefined = \(UserDefined x) -> unsafePerformIO $ go x where go :: x -> IO (String, [Some Classified]) go x = do closure <- getBoxedClosureData (asBox x) case closure of ConstrClosure {name, ptrArgs} -> (name,) <$> goArgs [] ptrArgs _otherwise -> error $ "elimUserDefined: unexpected closure: " ++ show closure goArgs :: [Some Classified] -> [Box] -> IO [Some Classified] goArgs acc [] = return (reverse acc) goArgs acc (Box b:bs) = do mc <- runExceptT $ classifyIO b case mc of Right c -> goArgs (Some (Classified c (unsafeCoerce b)) : acc) bs Left _ -> goArgs acc bs {------------------------------------------------------------------------------- Show Showing values is mutually recursive with classification: when we show a value classified as @UserDefined@, we recursively classify the nested values /when/ we show the value. -------------------------------------------------------------------------------} -- | Show any value -- -- This shows any value, as long as it's not unlifted. The result should be -- equal to show instances, with the following caveats: -- -- * User-defined types (types not explicitly known to this library) with a -- /custom/ Show instance will still be showable, but the result will be -- what the /derived/ show instance would have done. -- * Record field names are not known at runtime, so they are not shown. * UNPACKed data is not visible to this library ( if you compile with @-O0@ @ghc@ will not unpack data , so that might be a workaround if necessary ) . -- -- If classification fails, we show the actual closure. anythingToString :: forall a. a -> String anythingToString x = case classify x of Left closure -> show closure Right classifier -> case canShowClassified classifier of Dict -> show x deriving instance Show (Some Classified) instance Show (Classified a) where showsPrec p (Classified c x) = showParen (p >= 11) $ case canShowClassified c of Dict -> showString "Classified " . showsPrec 11 c . showString " " . showsPrec 11 x -- | Show the classified value (without the classifier) showClassifiedValue :: Int -> Classified a -> ShowS showClassifiedValue p (Classified c x) = case canShowClassified c of Dict -> showsPrec p x canShowClassified :: Classifier a -> Dict Show a canShowClassified = canShowClassified_ showOther where showOther :: IsUserDefined a -> Dict Show a showOther (IsUserDefined _) = Dict canShowPrim :: PrimClassifier a -> Dict Show a canShowPrim = primSatisfies canShowClassified_ :: forall o. (forall a. o a -> Dict Show a) -> (forall a. Classifier_ o a -> Dict Show a) canShowClassified_ = classifiedSatisfies instance Show UserDefined where showsPrec p x = case args of [] -> showString constrName xs -> showParen (p >= 11) . (showString constrName .) . foldl (.) id . map (\(Some x') -> showString " " . showClassifiedValue 11 x') $ xs where (constrName, args) = fromUserDefined x
null
https://raw.githubusercontent.com/well-typed/recover-rtti/c9409621188d0209919c2297a2012341607a4b0b/src/Debug/RecoverRTTI/Classify.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE PatternSynonyms # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeOperators # * Classification * User-defined types * Showing values ------------------------------------------------------------------------------ Classification ------------------------------------------------------------------------------ GHC.Types GHC.Tuple GHC.Int GHC.Integer String types bytestring text Aeson Maybe Either Lists (this includes the 'String' case) Ratio Set Map IntSet Sequence Tree we distinguish in 'classifyHashMap'. Arrays from @primitive@ Boxed vectors Storable vectors Primitive vectors Reference cells Functions User defined | Classify a value Given a value of some unknown type @a@ and a classifier @Classifier a@, it should be sound to coerce the value to the type indicated by the classifier. This is also the reason not all values can be classified; in particular, we cannot classify values of unlifted types, as for these types coercion ------------------------------------------------------------------------------ Classification for compound types ------------------------------------------------------------------------------ We special case for @String@, so that @show@ will use the (overlapped) instance for @String@ instead of the general instance for @[a]@ ------------------------------------------------------------------------------ Helper functions for defining classifiers ------------------------------------------------------------------------------ ^ Get the length of the array ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} ------------------------------------------------------------------------------ Recognizing tuples ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Classify constructor arguments ------------------------------------------------------------------------------ | Bundle a value with its classifier | Classify the arguments to the constructor Additionally returns the constructor name itself. ------------------------------------------------------------------------------ Show Showing values is mutually recursive with classification: when we show a value classified as @UserDefined@, we recursively classify the nested values /when/ we show the value. ------------------------------------------------------------------------------ | Show any value This shows any value, as long as it's not unlifted. The result should be equal to show instances, with the following caveats: * User-defined types (types not explicitly known to this library) with a /custom/ Show instance will still be showable, but the result will be what the /derived/ show instance would have done. * Record field names are not known at runtime, so they are not shown. If classification fails, we show the actual closure. | Show the classified value (without the classifier)
# LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE NamedFieldPuns # # LANGUAGE QuantifiedConstraints # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - orphans # module Debug.RecoverRTTI.Classify ( classify , Classified(..) , fromUserDefined , anythingToString , canShowPrim , canShowClassified , canShowClassified_ * Patterns for common shapes of ' Elems ' ( exported for the tests ) , pattern ElemK , pattern ElemU , pattern ElemKK , pattern ElemUU , pattern ElemKU , pattern ElemUK ) where import Control.Monad.Except import Data.HashMap.Lazy (HashMap) import Data.IntMap (IntMap) import Data.Map (Map) import Data.Sequence (Seq) import Data.Set (Set) import Data.SOP import Data.SOP.Dict import Data.Tree (Tree) import Data.Void import GHC.Exts.Heap (Closure) import GHC.Real import System.IO.Unsafe (unsafePerformIO) import Unsafe.Coerce (unsafeCoerce) import qualified Data.Foldable as Foldable import qualified Data.HashMap.Internal.Array as HashMap (Array) import qualified Data.HashMap.Internal.Array as HashMap.Array import qualified Data.HashMap.Lazy as HashMap import qualified Data.Map as Map import qualified Data.Primitive.Array as Prim.Array import qualified Data.Primitive.Array as Prim (Array) import qualified Data.Tree as Tree import qualified Data.Vector as Vector.Boxed import Debug.RecoverRTTI.Classifier import Debug.RecoverRTTI.Constraint import Debug.RecoverRTTI.FlatClosure import Debug.RecoverRTTI.Modules import Debug.RecoverRTTI.Nat import Debug.RecoverRTTI.Tuple import Debug.RecoverRTTI.Util import Debug.RecoverRTTI.Wrappers classifyIO :: a -> ExceptT Closure IO (Classifier a) classifyIO x = do closure <- lift $ getBoxedClosureData (asBox x) case closure of Primitive ( ghc - prim ) (inKnownModule GhcTypes -> Just "True") -> return $ mustBe $ C_Prim C_Bool (inKnownModule GhcTypes -> Just "False") -> return $ mustBe $ C_Prim C_Bool (inKnownModule GhcTypes -> Just "C#") -> return $ mustBe $ C_Prim C_Char (inKnownModule GhcTypes -> Just "D#") -> return $ mustBe $ C_Prim C_Double (inKnownModule GhcTypes -> Just "F#") -> return $ mustBe $ C_Prim C_Float (inKnownModule GhcTypes -> Just "I#") -> return $ mustBe $ C_Prim C_Int (inKnownModule GhcTypes -> Just "LT") -> return $ mustBe $ C_Prim C_Ordering (inKnownModule GhcTypes -> Just "GT") -> return $ mustBe $ C_Prim C_Ordering (inKnownModule GhcTypes -> Just "EQ") -> return $ mustBe $ C_Prim C_Ordering (inKnownModule GhcTypes -> Just "W#") -> return $ mustBe $ C_Prim C_Word (inKnownModule GhcTuple -> Just "()") -> return $ mustBe $ C_Prim C_Unit (inKnownModule GhcInt -> Just "I8#") -> return $ mustBe $ C_Prim C_Int8 (inKnownModule GhcInt -> Just "I16#") -> return $ mustBe $ C_Prim C_Int16 (inKnownModule GhcInt -> Just "I32#") -> return $ mustBe $ C_Prim C_Int32 (inKnownModule GhcInt -> Just "I64#") -> return $ mustBe $ C_Prim C_Int64 (inKnownModule GhcIntegerType -> Just "S#") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcIntegerType -> Just "Jp#") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcIntegerType -> Just "Jn#") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcNumInteger -> Just "IS") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcNumInteger -> Just "IP") -> return $ mustBe $ C_Prim C_Integer (inKnownModule GhcNumInteger -> Just "IN") -> return $ mustBe $ C_Prim C_Integer GHC.Word (inKnownModule GhcWord -> Just "W8#") -> return $ mustBe $ C_Prim C_Word8 (inKnownModule GhcWord -> Just "W16#") -> return $ mustBe $ C_Prim C_Word16 (inKnownModule GhcWord -> Just "W32#") -> return $ mustBe $ C_Prim C_Word32 (inKnownModule GhcWord -> Just "W64#") -> return $ mustBe $ C_Prim C_Word64 bytestring changed from PS to BS in version 0.11 (inKnownModule DataByteStringInternal -> Just "PS") -> return $ mustBe $ C_Prim C_BS_Strict (inKnownModule DataByteStringInternal -> Just "BS") -> return $ mustBe $ C_Prim C_BS_Strict (inKnownModule DataByteStringLazyInternal -> Just "Empty") -> return $ mustBe $ C_Prim C_BS_Lazy (inKnownModule DataByteStringLazyInternal -> Just "Chunk") -> return $ mustBe $ C_Prim C_BS_Lazy (inKnownModule DataByteStringShortInternal -> Just "SBS") -> return $ mustBe $ C_Prim C_BS_Short (inKnownModule DataTextInternal -> Just "Text") -> return $ mustBe $ C_Prim C_Text_Strict (inKnownModule DataTextInternalLazy -> Just "Chunk") -> return $ mustBe $ C_Prim C_Text_Lazy (inKnownModule DataTextInternalLazy -> Just "Empty") -> return $ mustBe $ C_Prim C_Text_Lazy (inKnownModule DataAesonTypesInternal -> Just "Object") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "Array") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "String") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "Number") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "Bool") -> return $ mustBe $ C_Prim C_Value (inKnownModule DataAesonTypesInternal -> Just "Null") -> return $ mustBe $ C_Prim C_Value Compound ( ghc - prim ) (inKnownModule GhcMaybe -> Just "Nothing") -> mustBe <$> classifyMaybe (unsafeCoerce x) (inKnownModule GhcMaybe -> Just "Just") -> mustBe <$> classifyMaybe (unsafeCoerce x) (inKnownModule DataEither -> Just "Left") -> mustBe <$> classifyEither (unsafeCoerce x) (inKnownModule DataEither -> Just "Right") -> mustBe <$> classifyEither (unsafeCoerce x) (inKnownModule GhcTypes -> Just "[]") -> mustBe <$> classifyList (unsafeCoerce x) (inKnownModule GhcTypes -> Just ":") -> mustBe <$> classifyList (unsafeCoerce x) (inKnownModule GhcReal -> Just ":%") -> mustBe <$> classifyRatio (unsafeCoerce x) (inKnownModule DataSetInternal -> Just "Tip") -> mustBe <$> classifySet (unsafeCoerce x) (inKnownModule DataSetInternal -> Just "Bin") -> mustBe <$> classifySet (unsafeCoerce x) (inKnownModule DataMapInternal -> Just "Tip") -> mustBe <$> classifyMap (unsafeCoerce x) (inKnownModule DataMapInternal -> Just "Bin") -> mustBe <$> classifyMap (unsafeCoerce x) (inKnownModule DataIntSetInternal -> Just "Bin") -> return $ mustBe $ C_Prim C_IntSet (inKnownModule DataIntSetInternal -> Just "Tip") -> return $ mustBe $ C_Prim C_IntSet (inKnownModule DataIntSetInternal -> Just "Nil") -> return $ mustBe $ C_Prim C_IntSet IntMap (inKnownModule DataIntMapInternal -> Just "Nil") -> mustBe <$> classifyIntMap (unsafeCoerce x) (inKnownModule DataIntMapInternal -> Just "Tip") -> mustBe <$> classifyIntMap (unsafeCoerce x) (inKnownModule DataIntMapInternal -> Just "Bin") -> mustBe <$> classifyIntMap (unsafeCoerce x) (inKnownModule DataSequenceInternal -> Just "EmptyT") -> mustBe <$> classifySequence (unsafeCoerce x) (inKnownModule DataSequenceInternal -> Just "Single") -> mustBe <$> classifySequence (unsafeCoerce x) (inKnownModule DataSequenceInternal -> Just "Deep") -> mustBe <$> classifySequence (unsafeCoerce x) (inKnownModule DataTree -> Just "Node") -> mustBe <$> classifyTree (unsafeCoerce x) Tuples ( of size 2 .. 62 ) (inKnownModuleNested GhcTuple -> Just ( isTuple -> Just (Some validSize@(ValidSize sz _)) , verifySize sz -> Just (VerifiedSize ptrs) )) -> case liftValidSize validSize of Dict -> mustBe <$> classifyTuple ptrs This could also be a HashSet , which is a newtype around a HashMap ; (inKnownModule DataHashMapInternal -> Just "Empty") -> mustBe <$> classifyHashMap (unsafeCoerce x) (inKnownModule DataHashMapInternal -> Just "BitmapIndexed") -> mustBe <$> classifyHashMap (unsafeCoerce x) (inKnownModule DataHashMapInternal -> Just "Leaf") -> mustBe <$> classifyHashMap (unsafeCoerce x) (inKnownModule DataHashMapInternal -> Just "Full") -> mustBe <$> classifyHashMap (unsafeCoerce x) (inKnownModule DataHashMapInternal -> Just "Collision") -> mustBe <$> classifyHashMap (unsafeCoerce x) HashMap 's internal Array type (inKnownModule DataHashMapInternalArray -> Just "Array") -> mustBe <$> classifyHMArray (unsafeCoerce x) (inKnownModule DataPrimitiveArray -> Just "Array") -> mustBe <$> classifyPrimArray (unsafeCoerce x) (inKnownModule DataPrimitiveArray -> Just "MutableArray") -> return $ mustBe $ C_Prim C_Prim_ArrayM (inKnownModule DataVector -> Just "Vector") -> mustBe <$> classifyVectorBoxed (unsafeCoerce x) (inKnownModule DataVectorStorable -> Just "Vector") -> return $ mustBe $ C_Prim C_Vector_Storable (inKnownModule DataVectorStorableMutable -> Just "MVector") -> return $ mustBe $ C_Prim C_Vector_StorableM (inKnownModule DataVectorPrimitive -> Just "Vector") -> return $ mustBe $ C_Prim C_Vector_Primitive (inKnownModule DataVectorPrimitiveMutable -> Just "MVector") -> return $ mustBe $ C_Prim C_Vector_PrimitiveM (inKnownModule GhcSTRef -> Just "STRef") -> return $ mustBe $ C_Prim C_STRef (inKnownModule GhcMVar -> Just "MVar") -> return $ mustBe $ C_Prim C_MVar (inKnownModule GhcConcSync -> Just "TVar") -> return $ mustBe $ C_Prim C_TVar FunClosure {} -> return $ mustBe $ C_Prim C_Fun ConstrClosure {} -> return $ mustBe $ C_Other (IsUserDefined (unsafeCoerce x)) Classification failed OtherClosure other -> ExceptT $ return (Left other) mustBe :: Classifier_ o b -> Classifier_ o a mustBe = unsafeCoerce does not work ( this would result in a ghc runtime crash ) . classify :: a -> Either Closure (Classifier a) classify = unsafePerformIO . runExceptT . classifyIO classifyMaybe :: Maybe a -> ExceptT Closure IO (Classifier (Maybe a)) classifyMaybe = classifyFoldable C_Maybe classifyEither :: Either a b -> ExceptT Closure IO (Classifier (Either a b)) classifyEither x = case x of Left x' -> (mustBe . C_Either . ElemKU) <$> classifyIO x' Right y' -> (mustBe . C_Either . ElemUK) <$> classifyIO y' classifyList :: [a] -> ExceptT Closure IO (Classifier [a]) classifyList = classifyFoldable c_list where c_list :: Elems o '[x] -> Classifier_ o [x] c_list (ElemK (C_Prim C_Char)) = C_Prim C_String c_list c = C_List c classifyRatio :: Ratio a -> ExceptT Closure IO (Classifier (Ratio a)) classifyRatio (x' :% _) = mustBe . C_Ratio . ElemK <$> classifyIO x' classifySet :: Set a -> ExceptT Closure IO (Classifier (Set a)) classifySet = classifyFoldable C_Set classifyMap :: Map a b -> ExceptT Closure IO (Classifier (Map a b)) classifyMap = classifyFoldablePair C_Map Map.toList classifyIntMap :: IntMap a -> ExceptT Closure IO (Classifier (IntMap a)) classifyIntMap = classifyFoldable C_IntMap classifySequence :: Seq a -> ExceptT Closure IO (Classifier (Seq a)) classifySequence = classifyFoldable C_Sequence classifyTree :: Tree a -> ExceptT Closure IO (Classifier (Tree a)) classifyTree (Tree.Node x' _) = mustBe . C_Tree . ElemK <$> classifyIO x' classifyHashMap :: HashMap a b -> ExceptT Closure IO (Classifier (HashMap a b)) classifyHashMap = classifyFoldablePair c_hashmap HashMap.toList where HashSet is a newtype around c_hashmap :: Elems o '[x, y] -> Classifier_ o (HashMap x y) c_hashmap (ElemKK c (C_Prim C_Unit)) = mustBe $ C_HashSet (ElemK c) c_hashmap c = C_HashMap c classifyHMArray :: HashMap.Array a -> ExceptT Closure IO (Classifier (HashMap.Array a)) classifyHMArray = classifyArrayLike C_HM_Array HashMap.Array.length (`HashMap.Array.index` 0) classifyPrimArray :: Prim.Array a -> ExceptT Closure IO (Classifier (Prim.Array a)) classifyPrimArray = classifyArrayLike C_Prim_Array Prim.Array.sizeofArray (`Prim.Array.indexArray` 0) classifyVectorBoxed :: Vector.Boxed.Vector a -> ExceptT Closure IO (Classifier (Vector.Boxed.Vector a)) classifyVectorBoxed = classifyArrayLike C_Vector_Boxed Vector.Boxed.length Vector.Boxed.head classifyTuple :: (SListI xs, IsValidSize (Length xs)) => NP (K Box) xs -> ExceptT Closure IO (Classifier (WrappedTuple xs)) classifyTuple ptrs = do cs <- hsequence' (hmap aux ptrs) return $ C_Tuple (Elems (hmap Elem cs)) where aux :: K Box a -> (ExceptT Closure IO :.: Classifier) a aux (K (Box x)) = Comp $ classifyIO (unsafeCoerce x) classifyFoldable :: Foldable f => (forall o x. Elems o '[x] -> Classifier_ o (f x)) -> f a -> ExceptT Closure IO (Classifier (f a)) classifyFoldable cc x = case Foldable.toList x of [] -> return $ mustBe $ cc ElemU x':_ -> mustBe . cc . ElemK <$> classifyIO x' classifyFoldablePair :: (forall o x y. Elems o '[x, y] -> Classifier_ o (f x y)) -> (f a b -> [(a, b)]) -> f a b -> ExceptT Closure IO (Classifier (f a b)) classifyFoldablePair cc toList x = case toList x of [] -> return $ mustBe $ cc ElemUU (x', y'):_ -> (\ca cb -> mustBe $ cc (ElemKK ca cb)) <$> classifyIO x' <*> classifyIO y' classifyArrayLike :: (forall o x. Elems o '[x] -> Classifier_ o (f x)) ^ Get the first element ( provided the array is not empty ) -> f a -> ExceptT Closure IO (Classifier (f a)) classifyArrayLike cc getLen getFirst x = if getLen x == 0 then return $ mustBe $ cc ElemU else do let x' = getFirst x mustBe . cc . ElemK <$> classifyIO x' Patterns for common shapes of ' Elems ' This is mostly useful internally ; we export these only for the benefit of the QuickCheck generator . Most other code can treat the all types uniformly . We distinguish between which elements are ( K)nown and which ( U)nknown Patterns for common shapes of 'Elems' This is mostly useful internally; we export these only for the benefit of the QuickCheck generator. Most other code can treat the all types uniformly. We distinguish between which elements are (K)nown and which (U)nknown pattern ElemK :: Classifier_ o a -> Elems o '[a] pattern ElemK c = Elems (Elem c :* Nil) pattern ElemU :: Elems o '[Void] pattern ElemU = Elems (NoElem :* Nil) pattern ElemKK :: Classifier_ o a -> Classifier_ o b -> Elems o '[a, b] pattern ElemKK ca cb = Elems (Elem ca :* Elem cb :* Nil) pattern ElemUU :: Elems o '[Void, Void] pattern ElemUU = Elems (NoElem :* NoElem :* Nil) pattern ElemKU :: Classifier_ o a -> Elems o '[a, Void] pattern ElemKU c = Elems (Elem c :* NoElem :* Nil) pattern ElemUK :: Classifier_ o b -> Elems o '[Void, b] pattern ElemUK c = Elems (NoElem :* Elem c :* Nil) isTuple :: String -> Maybe (Some ValidSize) isTuple typ = do (a, xs, z) <- dropEnds typ guard $ a == '(' && all (== ',') xs && z == ')' toValidSize (length xs + 1) data Classified a = Classified (Classifier a) a fromUserDefined :: UserDefined -> (String, [Some Classified]) fromUserDefined = \(UserDefined x) -> unsafePerformIO $ go x where go :: x -> IO (String, [Some Classified]) go x = do closure <- getBoxedClosureData (asBox x) case closure of ConstrClosure {name, ptrArgs} -> (name,) <$> goArgs [] ptrArgs _otherwise -> error $ "elimUserDefined: unexpected closure: " ++ show closure goArgs :: [Some Classified] -> [Box] -> IO [Some Classified] goArgs acc [] = return (reverse acc) goArgs acc (Box b:bs) = do mc <- runExceptT $ classifyIO b case mc of Right c -> goArgs (Some (Classified c (unsafeCoerce b)) : acc) bs Left _ -> goArgs acc bs * UNPACKed data is not visible to this library ( if you compile with @-O0@ @ghc@ will not unpack data , so that might be a workaround if necessary ) . anythingToString :: forall a. a -> String anythingToString x = case classify x of Left closure -> show closure Right classifier -> case canShowClassified classifier of Dict -> show x deriving instance Show (Some Classified) instance Show (Classified a) where showsPrec p (Classified c x) = showParen (p >= 11) $ case canShowClassified c of Dict -> showString "Classified " . showsPrec 11 c . showString " " . showsPrec 11 x showClassifiedValue :: Int -> Classified a -> ShowS showClassifiedValue p (Classified c x) = case canShowClassified c of Dict -> showsPrec p x canShowClassified :: Classifier a -> Dict Show a canShowClassified = canShowClassified_ showOther where showOther :: IsUserDefined a -> Dict Show a showOther (IsUserDefined _) = Dict canShowPrim :: PrimClassifier a -> Dict Show a canShowPrim = primSatisfies canShowClassified_ :: forall o. (forall a. o a -> Dict Show a) -> (forall a. Classifier_ o a -> Dict Show a) canShowClassified_ = classifiedSatisfies instance Show UserDefined where showsPrec p x = case args of [] -> showString constrName xs -> showParen (p >= 11) . (showString constrName .) . foldl (.) id . map (\(Some x') -> showString " " . showClassifiedValue 11 x') $ xs where (constrName, args) = fromUserDefined x
dfc846c539a7636e52820666e1c551e0c0d99fe098b6d31276e86d98157d58b6
chiroptical/optics-by-example
Lib.hs
# LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE TemplateHaskell # module Lib where import Control.Lens import Control.Monad.IO.Class import Control.Monad.Trans.Reader import Control.Monad.Trans.State import Data.Foldable import qualified Data.Map as M import Text.Printf newtype Username = Username { _username :: String } deriving newtype (Show, Eq, Ord) newtype Password = Password { _password :: String } deriving newtype (Show, Eq, Ord) data Env = Env { _currentUser :: Username, _users :: M.Map Username Password } deriving (Show) makeLenses ''Username makeLenses ''Password makeLenses ''Env printUser :: ReaderT Env IO () printUser = do user <- view (currentUser . username) liftIO . putStrLn $ "Current user: " <> user getUserPassword :: ReaderT Env IO () getUserPassword = do user <- view currentUser mPassword <- preview (users . ix user) liftIO $ print mPassword a :: IO () a = do let user = username # "jenkins" pass = password # "hunter2" runReaderT printUser (Env user (M.singleton user pass)) b :: IO () b = do let user = username # "jenkins" pass = password # "hunter2" runReaderT getUserPassword (Env user (M.singleton user pass)) data Till = Till { _total :: Double, _sales :: [Double], _taxRate :: Double } deriving (Show) makeLenses ''Till tuesdaySales :: StateT Till IO () tuesdaySales = do sales <>= pure 8.55 sales <>= pure 7.36 taxRate' <- use taxRate salesWithTax <- (taxRate' *) <$> use (sales . to sum) total .= salesWithTax totalSales <- use total liftIO $ printf "Total sale: $%.2f\n" totalSales c :: IO () c = execStateT tuesdaySales (Till 0 [] 1.11) >>= print data Weather = Weather { _temperature :: Float, _pressure :: Float } deriving (Show) makeLenses ''Weather printData :: String -> ReaderT Float IO () printData statName = do num <- ask liftIO . putStrLn $ statName <> ": " <> show num weatherStats :: ReaderT Weather IO () weatherStats = do magnify temperature (printData "temperature") magnify pressure (printData "pressure") d :: IO () d = runReaderT weatherStats (Weather 15 7.2) convertCelsiusToFahrenheit :: StateT Float IO () convertCelsiusToFahrenheit = do modify (\celsius -> (celsius * (9 / 5)) + 32) weatherStatsFahrenheit :: StateT Weather IO () weatherStatsFahrenheit = zoom temperature convertCelsiusToFahrenheit e :: IO () e = execStateT weatherStatsFahrenheit (Weather 32 12) >>= print
null
https://raw.githubusercontent.com/chiroptical/optics-by-example/3ee33546ee18c3a6f5510eec17a69d34e750198e/chapter13/src/Lib.hs
haskell
# LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE TemplateHaskell # module Lib where import Control.Lens import Control.Monad.IO.Class import Control.Monad.Trans.Reader import Control.Monad.Trans.State import Data.Foldable import qualified Data.Map as M import Text.Printf newtype Username = Username { _username :: String } deriving newtype (Show, Eq, Ord) newtype Password = Password { _password :: String } deriving newtype (Show, Eq, Ord) data Env = Env { _currentUser :: Username, _users :: M.Map Username Password } deriving (Show) makeLenses ''Username makeLenses ''Password makeLenses ''Env printUser :: ReaderT Env IO () printUser = do user <- view (currentUser . username) liftIO . putStrLn $ "Current user: " <> user getUserPassword :: ReaderT Env IO () getUserPassword = do user <- view currentUser mPassword <- preview (users . ix user) liftIO $ print mPassword a :: IO () a = do let user = username # "jenkins" pass = password # "hunter2" runReaderT printUser (Env user (M.singleton user pass)) b :: IO () b = do let user = username # "jenkins" pass = password # "hunter2" runReaderT getUserPassword (Env user (M.singleton user pass)) data Till = Till { _total :: Double, _sales :: [Double], _taxRate :: Double } deriving (Show) makeLenses ''Till tuesdaySales :: StateT Till IO () tuesdaySales = do sales <>= pure 8.55 sales <>= pure 7.36 taxRate' <- use taxRate salesWithTax <- (taxRate' *) <$> use (sales . to sum) total .= salesWithTax totalSales <- use total liftIO $ printf "Total sale: $%.2f\n" totalSales c :: IO () c = execStateT tuesdaySales (Till 0 [] 1.11) >>= print data Weather = Weather { _temperature :: Float, _pressure :: Float } deriving (Show) makeLenses ''Weather printData :: String -> ReaderT Float IO () printData statName = do num <- ask liftIO . putStrLn $ statName <> ": " <> show num weatherStats :: ReaderT Weather IO () weatherStats = do magnify temperature (printData "temperature") magnify pressure (printData "pressure") d :: IO () d = runReaderT weatherStats (Weather 15 7.2) convertCelsiusToFahrenheit :: StateT Float IO () convertCelsiusToFahrenheit = do modify (\celsius -> (celsius * (9 / 5)) + 32) weatherStatsFahrenheit :: StateT Weather IO () weatherStatsFahrenheit = zoom temperature convertCelsiusToFahrenheit e :: IO () e = execStateT weatherStatsFahrenheit (Weather 32 12) >>= print
4e9cf9d7e4129bbe7c78dc83b172badf33faa474decde0037de358aa6df7fe96
biegunka/biegunka
IO.hs
module Control.Biegunka.Execute.IO ( compareContents , hash , prepareDestination ) where import Control.Exception (handleJust) import Control.Monad (guard, void) import Control.Monad.Trans.Resource (runResourceT) import qualified Crypto.Hash as Hash import Data.Conduit import Data.Conduit.Binary (sourceFile) import System.FilePath (dropFileName) import qualified System.Directory as D import qualified System.IO.Error as IO import qualified System.Posix as Posix import qualified Control.Biegunka.Patience as Patience {-# ANN module "HLint: ignore Use const" #-} | Compare the contents of two files . Returns @Just ( Left digest)@ if the destination does not exist , @Just ( Right ( digestSource , digestDestination))@ -- if both files exist and are readable but differ, and @Nothing@ if both files -- exist, are readable and their contents are the same. compareContents :: Hash.HashAlgorithm a => proxy a -> FilePath -- ^ source -> FilePath -- ^ destination, may not exist -> IO (Maybe (Either (Hash.Digest a) (Hash.Digest a, Hash.Digest a, Patience.FileDiff))) compareContents _ src dst = do x <- hash src my <- handleDoesNotExist (return Nothing) (fmap Just (hash dst)) case my of Nothing -> return (Just (Left x)) Just y | x /= y -> do d <- Patience.fileDiff dst src -- `src` is a new `dst` return (Just (Right (x, y, d))) | otherwise -> return Nothing -- | Create a directory for a file with a given filepath to reside in and -- unlink the filepath if there's a resident already. prepareDestination :: FilePath -> IO () prepareDestination fp = void $ do D.createDirectoryIfMissing True (dropFileName fp) IO.tryIOError (Posix.removeLink fp) handleDoesNotExist :: IO a -> IO a -> IO a handleDoesNotExist h = handleJust (guard . IO.isDoesNotExistError) (\_ -> h) -- | Take a hashing algorithm and a filepath and produce a digest. hash :: Hash.HashAlgorithm a => FilePath -> IO (Hash.Digest a) hash fp = runResourceT (runConduit (sourceFile fp .| go Hash.hashInit)) where go x = maybe (return $! Hash.hashFinalize x) (\bs -> go $! Hash.hashUpdate x bs) =<< await
null
https://raw.githubusercontent.com/biegunka/biegunka/74fc93326d5f29761125d7047d5418899fa2469d/src/Control/Biegunka/Execute/IO.hs
haskell
# ANN module "HLint: ignore Use const" # if both files exist and are readable but differ, and @Nothing@ if both files exist, are readable and their contents are the same. ^ source ^ destination, may not exist `src` is a new `dst` | Create a directory for a file with a given filepath to reside in and unlink the filepath if there's a resident already. | Take a hashing algorithm and a filepath and produce a digest.
module Control.Biegunka.Execute.IO ( compareContents , hash , prepareDestination ) where import Control.Exception (handleJust) import Control.Monad (guard, void) import Control.Monad.Trans.Resource (runResourceT) import qualified Crypto.Hash as Hash import Data.Conduit import Data.Conduit.Binary (sourceFile) import System.FilePath (dropFileName) import qualified System.Directory as D import qualified System.IO.Error as IO import qualified System.Posix as Posix import qualified Control.Biegunka.Patience as Patience | Compare the contents of two files . Returns @Just ( Left digest)@ if the destination does not exist , @Just ( Right ( digestSource , digestDestination))@ compareContents :: Hash.HashAlgorithm a => proxy a -> IO (Maybe (Either (Hash.Digest a) (Hash.Digest a, Hash.Digest a, Patience.FileDiff))) compareContents _ src dst = do x <- hash src my <- handleDoesNotExist (return Nothing) (fmap Just (hash dst)) case my of Nothing -> return (Just (Left x)) Just y | x /= y -> do return (Just (Right (x, y, d))) | otherwise -> return Nothing prepareDestination :: FilePath -> IO () prepareDestination fp = void $ do D.createDirectoryIfMissing True (dropFileName fp) IO.tryIOError (Posix.removeLink fp) handleDoesNotExist :: IO a -> IO a -> IO a handleDoesNotExist h = handleJust (guard . IO.isDoesNotExistError) (\_ -> h) hash :: Hash.HashAlgorithm a => FilePath -> IO (Hash.Digest a) hash fp = runResourceT (runConduit (sourceFile fp .| go Hash.hashInit)) where go x = maybe (return $! Hash.hashFinalize x) (\bs -> go $! Hash.hashUpdate x bs) =<< await
9452c071ee5d07bfa100500cb999026059d506c0b30301b85235dac614cd1847
xxyzz/SICP
Exercise_3_16.rkt
#lang racket/base (define (count-pairs x) (if (not (mpair? x)) 0 (+ (count-pairs (mcar x)) (count-pairs (mcdr x)) 1))) (define (last-pair x) (if (null? (mcdr x)) x (last-pair (mcdr x)))) (count-pairs (mcons 'a (mcons 'b (mcons 'c null)))) 3 (define count-4-list (mcons 'a (mcons 'b (mcons 'c null)))) (set-mcar! count-4-list (last-pair count-4-list)) (count-pairs count-4-list) 4 ; 🚫 is null ; __________ ; | | ; | v ; ⬛⬛->⬛⬛->⬛🚫 ; | | ; b c (define count-7-list (mcons 'a (mcons 'b (mcons 'c null)))) (set-mcar! count-7-list (mcdr count-7-list)) (set-mcar! (mcdr count-7-list) (last-pair count-7-list)) (count-pairs count-7-list) 7 ; 1 + (1 + 1 + 1) + (1 + 1 + 1) ; ____ ; | | ; | v ; ⬛⬛->⬛⬛->⬛🚫 ; | ^ | ; | | c ; ----- (define infinite-list (mcons 'a (mcons 'b (mcons 'c null)))) (let ([last (last-pair infinite-list)]) (set-mcdr! last last)) (count-pairs infinite-list) ; infinite loop ; _ ; | | ; v | ; ⬛⬛->⬛⬛->⬛⬛
null
https://raw.githubusercontent.com/xxyzz/SICP/e26aea1c58fd896297dbf5406f7fcd32bb4f8f78/3_Modularity_Objects_and_State/3.3_Modeling_with_Mutable_Data/Exercise_3_16.rkt
racket
🚫 is null __________ | | | v ⬛⬛->⬛⬛->⬛🚫 | | b c 1 + (1 + 1 + 1) + (1 + 1 + 1) ____ | | | v ⬛⬛->⬛⬛->⬛🚫 | ^ | | | c ----- infinite loop _ | | v | ⬛⬛->⬛⬛->⬛⬛
#lang racket/base (define (count-pairs x) (if (not (mpair? x)) 0 (+ (count-pairs (mcar x)) (count-pairs (mcdr x)) 1))) (define (last-pair x) (if (null? (mcdr x)) x (last-pair (mcdr x)))) (count-pairs (mcons 'a (mcons 'b (mcons 'c null)))) 3 (define count-4-list (mcons 'a (mcons 'b (mcons 'c null)))) (set-mcar! count-4-list (last-pair count-4-list)) (count-pairs count-4-list) 4 (define count-7-list (mcons 'a (mcons 'b (mcons 'c null)))) (set-mcar! count-7-list (mcdr count-7-list)) (set-mcar! (mcdr count-7-list) (last-pair count-7-list)) (count-pairs count-7-list) 7 (define infinite-list (mcons 'a (mcons 'b (mcons 'c null)))) (let ([last (last-pair infinite-list)]) (set-mcdr! last last)) (count-pairs infinite-list)
f38ae7bb7f8177a3e868fd6fa0f3d8bf3b7f0b5b4e2619906e252ffcd448da7b
VERIMAG-Polyhedra/VPL
EqSet_t.ml
open Vpl module Cs = Cstr.Rat let factory : Cs.t Factory.t = { Factory.name = "Cstr"; Factory.top = (Cs.mk Cstr_type.Eq [] Scalar.Rat.z); Factory.triv = (fun cmp n -> Cs.mk cmp [] n); Factory.add = Cs.add; Factory.mul = Cs.mulc; Factory.to_le = (fun c -> {c with Cs.typ = Cstr_type.Le}); Factory.merge = (fun c1 c2 -> let c1' = {c1 with Cs.typ = Cstr_type.Eq} and c2' = {c2 with Cs.typ = Cstr_type.Eq} in if Cs.equal c1' c2' then c1' else failwith "merge"); Factory.to_string = Cs.to_string Var.to_string; Factory.rename = Cs.rename; } EqSet let x = Var.fromInt 1 let y = Var.fromInt 2 let z = Var.fromInt 3 let t = Var.fromInt 4 let nxt = 5 let varPr: Var.t -> string = fun _x -> let vars: (Var.t * string) list = [x, "x"; y, "y"; z, "z"; t, "t"] in try List.assoc _x vars with | Not_found -> "v" ^ (Var.to_string _x) let mkc t v c = Cs.mk t (List.map (fun (n, x) -> (Cs.Vec.Coeff.of_int n, x)) v) (Cs.Vec.Coeff.of_int c) let eq = mkc Cstr_type.Eq let le = mkc Cstr_type.Le let lt = mkc Cstr_type.Lt let mask l = List.fold_left (fun m x -> Rtree.set None m x (Some x)) Rtree.empty l (* XXX: This function does not do any check on the inputs. *) let mkCons : Cs.t -> Cs.t Cons.t = fun c -> (c, c) let mk: (Var.t * Cs.t) list -> Cs.t EqSet.t = fun l -> List.fold_left (fun s (x,c) -> (x, (mkCons c))::s) (EqSet.nil) l let mks: Cs.t list -> Cs.t EqSet.t = fun l -> match EqSet.addM factory EqSet.nil (List.map (fun x -> (x,x)) l) with | EqSet.Added s -> s | EqSet.Bot _ -> invalid_arg "EqSet_t.mks" let mkl: Cs.t list -> Cs.t EqSet.t = fun l -> mks (List.rev l) let optxpr = function | None -> "None" | Some x -> "Some " ^ (varPr x) let prProp = function | Cs.Trivial -> "trivial" | Cs.Contrad -> "contrad" | Cs.Nothing -> "nothing" let impliesEq: Cs.t list -> Cs.t list -> bool = fun l1 l2 -> Misc.list_eq2 Cs.equal l1 l2 let impliesPr: Cs.t list -> string = Cs.list_to_string let relEq: Cs.t EqSet.rel_t -> Cs.t EqSet.rel_t -> bool = fun r1 r2 -> match r1, r2 with | EqSet.NoIncl, EqSet.NoIncl -> true | EqSet.Incl l1, EqSet.Incl l2 -> impliesEq l1 l2 | EqSet.NoIncl, EqSet.Incl _ | EqSet.Incl _, EqSet.NoIncl -> false let relPr: Cs.t EqSet.rel_t -> string = function | EqSet.NoIncl -> "NoIncl" | EqSet.Incl l -> Printf.sprintf "Incl l with l =\n%s" (impliesPr l) (* EqSet.filter *) let filterTs: Test.t = fun () -> let chkNo (name, _, c, s, _) = fun state -> let (c1,cert1) = EqSet.filter factory s c in let vars = List.map (fun (x, _) -> x) s in let zcoef x = Cs.Vec.Coeff.cmpz (Cs.Vec.get (Cs.get_v c1) x) = 0 in if List.for_all zcoef vars then Test.succeed state else let err = Printf.sprintf "some variable has non-zero coefficient in %s\n" (Cons.to_string_ext factory varPr (c1,cert1)) in Test.fail name err state in let chkProp (name, p, c, s, _) = fun state -> let (c1,cert1) = EqSet.filter factory s c in let p1 = Cs.tellProp c1 in if p = p1 then Test.succeed state else let e = (prProp p) ^ " != " ^ (prProp p1) in Test.fail name e state in let chkLin (name, _, c, s, cert) = fun state -> let (c1,cert1) = EqSet.filter factory s c in if Cs.equal cert1 cert then Test.succeed state else let err = Printf.sprintf "expected: %s\nbut got: %s" (factory.Factory.to_string cert) (factory.Factory.to_string cert1) in Test.fail name err state in let tcs = [ "nil0", Cs.Nothing, mkCons (eq [1, x] 0), mkl [], (eq [1, x] 0); "nil1", Cs.Nothing, mkCons (eq [1, x] 1), mkl [], (eq [1, x] 1); "nil2", Cs.Nothing, mkCons (eq [1, x; 2, y] 0), mkl [], (eq [1, x; 2, y] 0); "one0", Cs.Nothing, mkCons (eq [2, x; 3, y] 1), mkl [eq [1, y] 1 ], (eq [2, x] (-2)); "incl0", Cs.Trivial, mkCons (eq [2, x; 3, y] 1), mkl [ eq [1, x; 1, y] 1; eq [1, y] (-1) ], eq [] 0 ; "incl1", Cs.Trivial, mkCons (le [2, x; 3, y] 1), mkl [ eq [1, x; 1, y] 1; eq [1, y] (-1) ], le [] 0 ; "triv0", Cs.Trivial, mkCons (le [] 1), mkl [ eq [1, x] 1; eq [1, y] 2 ], le [] 1; "contrad0", Cs.Contrad, mkCons (eq [2, x; 1, z] 1), mkl [ eq [1, x; 1, z] 0; eq [1, x] 2 ], Cs.eq [] (Q.of_float (-1.)) ] in Test.suite "filter" [ Test.suite "no" (List.map chkNo tcs); Test.suite "prop" (List.map chkProp tcs); Test.suite "lin" (List.map chkLin tcs) ] (* XXX: check that all is fine when adding multiple equalities *) let addMTs: Test.t = fun () -> let chk (nm, s, l, r) = fun st -> try let ar = EqSet.addM factory s l in if EqSet.meetEq r ar then Test.succeed st else let estr = Printf.sprintf "expected:\n%s\ngot:\n%s\n" (EqSet.meet_to_string factory varPr r) (EqSet.meet_to_string factory varPr ar) in Test.fail nm estr st with Failure s when s = "EqSet.addM" -> Test.fail nm "caught Failure exception" st in let tcs: (string * 'c EqSet.t * Cs.t Cons.t list * 'c EqSet.meetT) list = [ "concat0", EqSet.nil, [], EqSet.Added EqSet.nil; "concat1", mks [], [eq [1, x] 0], EqSet.Added (mks [eq [1, x] 0]); "concat2", mks [eq [1, x] 0], [], EqSet.Added (mks [eq [1, x] 0]); "concat3", mks [eq [1, y] 1], [eq [1, x] 0], EqSet.Added (mks [ eq [1, y] 1; eq [1, x] 0]); "adj0", mks [], [eq [2, x] 0], EqSet.Added (mks [eq [1, x] 0]); "adj1", mks [], [eq [-1, x] 0], EqSet.Added (mks [eq [1, x] 0]); "comb0", mks [eq [1, x] 0], [eq [1, x; 1, y] 0], EqSet.Added (mks [ eq [1, x] 0; eq [1, y] 0]); "comb+adj0", mks [eq [1, x] 0], [eq [1, x; 2, y] 0], EqSet.Added (mks [ eq [1, x] 0; eq [1, y] 0]); "redundant0", mks [eq [1, x] 0], [eq [1, x] 0], EqSet.Added (mks [eq [1, x] 0]); "redundant1", mks [ eq [1, x] 0; eq [1, y] 1], [eq [1, x; 2, y] 2], EqSet.Added (mks [ eq [1, x] 0; eq [1, y] 1]); "contrad0", mks [], [eq [] 1], EqSet.Bot (eq [] 1); "contrad1", mks [eq [1, x] 0], [eq [1, x] 1], EqSet.Bot (eq [] (-1)); "contrad2", mks [ eq [1, x] 0; eq [1, y] 0], [eq [1, x; 2, y] 1], EqSet.Bot (eq [] 1); ] |> List.map (fun (nm, s, l, r) -> nm, s, (List.map mkCons l), r) in Test.suite "addM" (List.map chk tcs) EqSet.pick let pickTs: Test.t = fun () -> let chk (name, msk, c, r) = fun state -> let r1 = EqSet.pick msk c in if r = r1 then Test.succeed state else let e = "expected " ^ (optxpr r) ^ " but got " ^ (optxpr r1) in Test.fail name e state in let tcs = [ "nil0", mask [], mkCons (eq [] 0), None; "nil1", mask [x], mkCons (eq [] 0), None; "nil2", mask [y], mkCons (eq [] 0), None; "nil3", mask [], mkCons (eq [1, x] 0), None; "diff0", mask [x], mkCons (eq [1, y] 0), None; "one0", mask [x], mkCons (eq [1, x] 0), Some x; "one1", mask [x], mkCons (eq [1, x; 1, y] 0), Some x; "one2", mask [y], mkCons (eq [1, x; 1, y] 0), Some y; "m0", mask [x; y], mkCons (eq [1, y] 0), Some y; "m1", mask [x; y], mkCons (eq [1, y; 1, z] 0), Some y; (* implementation detail *) "m2", mask [x; y], mkCons (eq [1, x; 1, y] 0), Some x ] in Test.suite "pick" (List.map chk tcs) (* EqSet.subst *) let substTs: Test.t = fun () -> let chkCons (name, x, c, s, s1) = fun state -> let c1 = mkCons c in let s2 = EqSet.subst factory x c1 s in if EqSet.equal s1 s2 then Test.succeed state else let e = "expected:\n" ^ (EqSet.to_string_ext factory varPr s1) ^ "but got:\n" ^ (EqSet.to_string_ext factory varPr s2) in Test.fail name e state in let tcs = [ "nil0", x, eq [1, x] 0, mk [], mk []; "nil1", y, eq [1, x] 0, mk [], mk []; "nil2", y, eq [1, x] 0, mk [], mk []; "one0", x, eq [1, x] 0, mk [y, eq [1, x; 1, y] 1], mk [y, eq [1, y] 1]; "one1", x, eq [1, x] 0, mk [y, eq [1, x; 1, y] 1], mk [y, eq [1, y] 1]; "no0", x, eq [1, x] 0, mk [y, eq [1, y] 1], mk [y, eq [1, y] 1]; "m0", x, eq [1, x] 0, mk [ z, eq [1, z] 1; y, eq [1, x; 1, y] 1 ], mk [ z, eq [1, z] 1; y, eq [1, y] 1 ]; ] in Test.suite "subst" [ Test.suite "cons" (List.map chkCons tcs) ] (* EqSet.tryDefs *) let tryDefsTs: Test.t = fun () -> let chk_res (t, r, msk, s) = fun state -> let (def, _) = EqSet.tryDefs factory msk s in let a = if def = None then false else true in if a = r then Test.succeed state else Test.fail t "bad conclusion" state in let chk_def (t, _, msk, s) = fun state -> let (def, _) = EqSet.tryDefs factory msk s in match def with | None -> Test.succeed state | Some (_, x) -> if List.exists (fun (x1, _) -> x = x1) s then Test.succeed state else let e = "not found" in Test.fail t e state in let chk_nox (t, _, msk, s) = fun state -> let (def, s1) = EqSet.tryDefs factory msk s in match def with | None -> Test.succeed state | Some (_, x) -> let noXPred c = Cs.Vec.Coeff.cmpz (Cs.Vec.get (Cs.get_v (Cons.get_c c)) x) = 0 in if List.for_all (fun (_, c) -> noXPred c) s1 then Test.succeed state else Test.fail t "x remaining" state in let tcs = [ "nil0", false, mask [], mkl []; "nil1", false, mask [x], mkl []; "one0", true, mask [x], mkl [eq [1, x] 0]; "one0", true, mask [x], mkl [ eq [1, x] 0; eq [1, x; 1, y] 0 ]; "no0", false, mask [z], mkl [ eq [1, x; 1, z] 0; eq [1, y] 0 ] ] in Test.suite "tryDefs" [ Test.suite "res" (List.map chk_res tcs); Test.suite "def" (List.map chk_def tcs); Test.suite "nox" (List.map chk_nox tcs) ] (* EqSet.trySubstM *) let trySubstMTs: Test.t = fun () -> let chk_var (t, x, msk, s) = fun state -> let (optx1, _) = EqSet.trySubstM factory msk s in match optx1 with | None -> if x = None then Test.succeed state else let e = "expected " ^ (optxpr x) ^ " but got None" in Test.fail t e state | Some (_, x1) -> if x = Some x1 then Test.succeed state else let e = "expected " ^ (optxpr x) ^ " but got " ^ (optxpr (Some x1)) in Test.fail t e state in let chk_nox (t, x, msk, s) = fun state -> let (e, s1, s2) = let (_, s1) = EqSet.trySubstM factory msk s in match x with | None -> ("trySubstM did change s", s, s1) | Some x -> let c = mkCons (eq [1, x] 0) in let s2 = EqSet.subst factory x c s1 in let e = "still some " ^ (varPr x) ^ " in\n" ^ (EqSet.to_string_ext factory varPr s1) in (e, s1, s2) in if EqSet.equal s1 s2 then Test.succeed state else Test.fail t e state in let tcs = [ "x0", Some x, mask [x], mk [ y, eq [1, x; 1, y] 0; x, eq [1, x] 0 ]; "no0", None, mask [z], mk [ x, eq [1, x] 0 ] ] in Test.suite "trySubstM" [ Test.suite "var" (List.map chk_var tcs); Test.suite "nox" (List.map chk_nox tcs) ] (* (* EqSet.joinSetup *) let joinSetupTs: Test.t = let alpha = Var.fromInt nxt in let nxt' = nxt + 1 in let chk_id0 dup (t, idOff, s) = fun state -> let (_, _, s1) = EqSet.joinSetup dup (Var.fromInt nxt') Rtree.empty alpha idOff s in let sorted = let ids = List.map (fun c -> (Cons.get_id c)) (EqSet.list s) in List.sort Stdlib.compare ids in let sorted1 = let ids1 = List.map (fun c -> (Cons.get_id c) - idOff) (EqSet.list s1) in List.sort Stdlib.compare ids1 in if sorted = sorted1 then Test.succeed state else Test.fail t "not equal" state in let chk_def0 dup (t, i0, s) = fun state -> let (_, reloc, s1) = EqSet.joinSetup dup (Var.fromInt nxt') Rtree.empty alpha i0 s in let a = let chk (x1, _) (x2, _) = if dup then x1 = x2 else Rtree.get None reloc x1 = Some x2 in List.for_all2 chk s s1 in if a then Test.succeed state else let err = Printf.sprintf "wrong defined variables: s:\n%s\ns1:\n%s\n" (EqSet.to_string_ext varPr s) (EqSet.to_string_ext varPr s1) in Test.fail t err state in let chk_frag0 dup (t, i0, s) = fun state -> let (_, _, s1) = EqSet.joinSetup dup (Var.fromInt nxt') Rtree.empty alpha i0 s in let a = let chk c = match Cons.get_f c with | [] -> false | (id, coef)::[] -> id = (Cons.get_id c) && Cs.Vec.Coeff.cmp Cs.Vec.Coeff.u coef = 0 | _ -> false in List.for_all chk (EqSet.list s1) in if a then Test.succeed state else Test.fail t "bad fragments" state in let tcs = [ "one0", 10, mk [ x, eq [1, x] 1 ]; "one1", 10, mk [ x, eq [1, x; 1, y] 1 ]; "one2", 10, mk [ y, eq [1, x; 1, y] 1 ]; "m0", 10, mk [ x, eq [1, x; 1, y] 1; y, eq [2, y; 1, z] 1; z, eq [1, z; 2, t] 1 ] ] in let chk_id = chk_id0 false in let chk_idd = chk_id0 true in let chk_def = chk_def0 false in let chk_frag = chk_frag0 false in let chk_defd = chk_def0 true in let chk_fragd = chk_frag0 true in Test.suite "joinSetup" [ Test.suite "id" (List.map chk_id tcs); Test.suite "idd" (List.map chk_idd tcs); Test.suite "def" (List.map chk_def tcs); Test.suite "defd" (List.map chk_defd tcs); Test.suite "frag" (List.map chk_frag tcs); Test.suite "fragd" (List.map chk_fragd tcs) ] *) EqSet.incl let inclTs: Test.t = fun () -> let chk (name, s1, s2, expected) = fun state -> let actual = EqSet.leq factory s1 s2 in if relEq actual expected then Test.succeed state else Test.fail name (relPr actual) state in let tcs = [ "id0", mks [eq [1, x] 0 ], mks [eq [1, x] 0 ], EqSet.Incl [eq [1, x] 0]; "id1", mks [ eq [1, y] 0; eq [1, x] 0], mks [eq [1, x] 0 ], EqSet.Incl [eq [1, x] 0]; "bin0", mks [ eq [1, y] 0; eq [1, x] 0 ], mks [eq [1, x; 1, y] 0 ], EqSet.Incl [eq [1, x; 1, y] 0] ] in Test.suite "incl" (List.map chk tcs) (* EqSet.rename *) let renameTs: Test.t = fun () -> let x' = Var.fromInt nxt in let chkVar (t, fromX, toY, s0) = fun state -> let defVars s = List.map (fun (v, _) -> v) s in let s = EqSet.rename factory s0 fromX toY in if List.for_all (fun v -> v <> fromX) (defVars s) then Test.succeed state else let e = (varPr fromX) ^ " remaining\n" ^ (EqSet.to_string_ext factory varPr s) in Test.fail t e state in let chkCoef (t, fromX, toY, s0) = fun state -> let aX s = let coef (c,cert) x = Cs.Vec.get (Cs.get_v c) x in List.map (fun (_, c) -> coef c fromX) s in let s = EqSet.rename factory s0 fromX toY in if List.for_all (fun a -> Cs.Vec.Coeff.cmpz a = 0) (aX s) then Test.succeed state else let e = (varPr fromX) ^ " remaining\n" ^ (EqSet.to_string_ext factory varPr s) in Test.fail t e state in let tcs = [ "one0", x', x, mkl [ eq [1, x'] 0 ]; "one1", x', x, mkl [ eq [1, x'; 1, y] 0 ]; "no0", x', x, mkl [ eq [1, y] 0 ]; "m0", x', x ,mkl [ eq [1, x'; 1, y] 1; eq [1, x'; 2, y] 2 ]; ] in Test.suite "rename" [ Test.suite "var" (List.map chkVar tcs); Test.suite "coef" (List.map chkCoef tcs) ] let ts: Test.t = fun () -> List.map Test.run [filterTs; addMTs; pickTs; substTs; tryDefsTs; trySubstMTs; (*joinSetupTs;*) inclTs; renameTs] |> Test.suite "EqSet"
null
https://raw.githubusercontent.com/VERIMAG-Polyhedra/VPL/cd78d6e7d120508fd5a694bdb01300477e5646f8/test/core/EqSet_t.ml
ocaml
XXX: This function does not do any check on the inputs. EqSet.filter XXX: check that all is fine when adding multiple equalities implementation detail EqSet.subst EqSet.tryDefs EqSet.trySubstM (* EqSet.joinSetup EqSet.rename joinSetupTs;
open Vpl module Cs = Cstr.Rat let factory : Cs.t Factory.t = { Factory.name = "Cstr"; Factory.top = (Cs.mk Cstr_type.Eq [] Scalar.Rat.z); Factory.triv = (fun cmp n -> Cs.mk cmp [] n); Factory.add = Cs.add; Factory.mul = Cs.mulc; Factory.to_le = (fun c -> {c with Cs.typ = Cstr_type.Le}); Factory.merge = (fun c1 c2 -> let c1' = {c1 with Cs.typ = Cstr_type.Eq} and c2' = {c2 with Cs.typ = Cstr_type.Eq} in if Cs.equal c1' c2' then c1' else failwith "merge"); Factory.to_string = Cs.to_string Var.to_string; Factory.rename = Cs.rename; } EqSet let x = Var.fromInt 1 let y = Var.fromInt 2 let z = Var.fromInt 3 let t = Var.fromInt 4 let nxt = 5 let varPr: Var.t -> string = fun _x -> let vars: (Var.t * string) list = [x, "x"; y, "y"; z, "z"; t, "t"] in try List.assoc _x vars with | Not_found -> "v" ^ (Var.to_string _x) let mkc t v c = Cs.mk t (List.map (fun (n, x) -> (Cs.Vec.Coeff.of_int n, x)) v) (Cs.Vec.Coeff.of_int c) let eq = mkc Cstr_type.Eq let le = mkc Cstr_type.Le let lt = mkc Cstr_type.Lt let mask l = List.fold_left (fun m x -> Rtree.set None m x (Some x)) Rtree.empty l let mkCons : Cs.t -> Cs.t Cons.t = fun c -> (c, c) let mk: (Var.t * Cs.t) list -> Cs.t EqSet.t = fun l -> List.fold_left (fun s (x,c) -> (x, (mkCons c))::s) (EqSet.nil) l let mks: Cs.t list -> Cs.t EqSet.t = fun l -> match EqSet.addM factory EqSet.nil (List.map (fun x -> (x,x)) l) with | EqSet.Added s -> s | EqSet.Bot _ -> invalid_arg "EqSet_t.mks" let mkl: Cs.t list -> Cs.t EqSet.t = fun l -> mks (List.rev l) let optxpr = function | None -> "None" | Some x -> "Some " ^ (varPr x) let prProp = function | Cs.Trivial -> "trivial" | Cs.Contrad -> "contrad" | Cs.Nothing -> "nothing" let impliesEq: Cs.t list -> Cs.t list -> bool = fun l1 l2 -> Misc.list_eq2 Cs.equal l1 l2 let impliesPr: Cs.t list -> string = Cs.list_to_string let relEq: Cs.t EqSet.rel_t -> Cs.t EqSet.rel_t -> bool = fun r1 r2 -> match r1, r2 with | EqSet.NoIncl, EqSet.NoIncl -> true | EqSet.Incl l1, EqSet.Incl l2 -> impliesEq l1 l2 | EqSet.NoIncl, EqSet.Incl _ | EqSet.Incl _, EqSet.NoIncl -> false let relPr: Cs.t EqSet.rel_t -> string = function | EqSet.NoIncl -> "NoIncl" | EqSet.Incl l -> Printf.sprintf "Incl l with l =\n%s" (impliesPr l) let filterTs: Test.t = fun () -> let chkNo (name, _, c, s, _) = fun state -> let (c1,cert1) = EqSet.filter factory s c in let vars = List.map (fun (x, _) -> x) s in let zcoef x = Cs.Vec.Coeff.cmpz (Cs.Vec.get (Cs.get_v c1) x) = 0 in if List.for_all zcoef vars then Test.succeed state else let err = Printf.sprintf "some variable has non-zero coefficient in %s\n" (Cons.to_string_ext factory varPr (c1,cert1)) in Test.fail name err state in let chkProp (name, p, c, s, _) = fun state -> let (c1,cert1) = EqSet.filter factory s c in let p1 = Cs.tellProp c1 in if p = p1 then Test.succeed state else let e = (prProp p) ^ " != " ^ (prProp p1) in Test.fail name e state in let chkLin (name, _, c, s, cert) = fun state -> let (c1,cert1) = EqSet.filter factory s c in if Cs.equal cert1 cert then Test.succeed state else let err = Printf.sprintf "expected: %s\nbut got: %s" (factory.Factory.to_string cert) (factory.Factory.to_string cert1) in Test.fail name err state in let tcs = [ "nil0", Cs.Nothing, mkCons (eq [1, x] 0), mkl [], (eq [1, x] 0); "nil1", Cs.Nothing, mkCons (eq [1, x] 1), mkl [], (eq [1, x] 1); "nil2", Cs.Nothing, mkCons (eq [1, x; 2, y] 0), mkl [], (eq [1, x; 2, y] 0); "one0", Cs.Nothing, mkCons (eq [2, x; 3, y] 1), mkl [eq [1, y] 1 ], (eq [2, x] (-2)); "incl0", Cs.Trivial, mkCons (eq [2, x; 3, y] 1), mkl [ eq [1, x; 1, y] 1; eq [1, y] (-1) ], eq [] 0 ; "incl1", Cs.Trivial, mkCons (le [2, x; 3, y] 1), mkl [ eq [1, x; 1, y] 1; eq [1, y] (-1) ], le [] 0 ; "triv0", Cs.Trivial, mkCons (le [] 1), mkl [ eq [1, x] 1; eq [1, y] 2 ], le [] 1; "contrad0", Cs.Contrad, mkCons (eq [2, x; 1, z] 1), mkl [ eq [1, x; 1, z] 0; eq [1, x] 2 ], Cs.eq [] (Q.of_float (-1.)) ] in Test.suite "filter" [ Test.suite "no" (List.map chkNo tcs); Test.suite "prop" (List.map chkProp tcs); Test.suite "lin" (List.map chkLin tcs) ] let addMTs: Test.t = fun () -> let chk (nm, s, l, r) = fun st -> try let ar = EqSet.addM factory s l in if EqSet.meetEq r ar then Test.succeed st else let estr = Printf.sprintf "expected:\n%s\ngot:\n%s\n" (EqSet.meet_to_string factory varPr r) (EqSet.meet_to_string factory varPr ar) in Test.fail nm estr st with Failure s when s = "EqSet.addM" -> Test.fail nm "caught Failure exception" st in let tcs: (string * 'c EqSet.t * Cs.t Cons.t list * 'c EqSet.meetT) list = [ "concat0", EqSet.nil, [], EqSet.Added EqSet.nil; "concat1", mks [], [eq [1, x] 0], EqSet.Added (mks [eq [1, x] 0]); "concat2", mks [eq [1, x] 0], [], EqSet.Added (mks [eq [1, x] 0]); "concat3", mks [eq [1, y] 1], [eq [1, x] 0], EqSet.Added (mks [ eq [1, y] 1; eq [1, x] 0]); "adj0", mks [], [eq [2, x] 0], EqSet.Added (mks [eq [1, x] 0]); "adj1", mks [], [eq [-1, x] 0], EqSet.Added (mks [eq [1, x] 0]); "comb0", mks [eq [1, x] 0], [eq [1, x; 1, y] 0], EqSet.Added (mks [ eq [1, x] 0; eq [1, y] 0]); "comb+adj0", mks [eq [1, x] 0], [eq [1, x; 2, y] 0], EqSet.Added (mks [ eq [1, x] 0; eq [1, y] 0]); "redundant0", mks [eq [1, x] 0], [eq [1, x] 0], EqSet.Added (mks [eq [1, x] 0]); "redundant1", mks [ eq [1, x] 0; eq [1, y] 1], [eq [1, x; 2, y] 2], EqSet.Added (mks [ eq [1, x] 0; eq [1, y] 1]); "contrad0", mks [], [eq [] 1], EqSet.Bot (eq [] 1); "contrad1", mks [eq [1, x] 0], [eq [1, x] 1], EqSet.Bot (eq [] (-1)); "contrad2", mks [ eq [1, x] 0; eq [1, y] 0], [eq [1, x; 2, y] 1], EqSet.Bot (eq [] 1); ] |> List.map (fun (nm, s, l, r) -> nm, s, (List.map mkCons l), r) in Test.suite "addM" (List.map chk tcs) EqSet.pick let pickTs: Test.t = fun () -> let chk (name, msk, c, r) = fun state -> let r1 = EqSet.pick msk c in if r = r1 then Test.succeed state else let e = "expected " ^ (optxpr r) ^ " but got " ^ (optxpr r1) in Test.fail name e state in let tcs = [ "nil0", mask [], mkCons (eq [] 0), None; "nil1", mask [x], mkCons (eq [] 0), None; "nil2", mask [y], mkCons (eq [] 0), None; "nil3", mask [], mkCons (eq [1, x] 0), None; "diff0", mask [x], mkCons (eq [1, y] 0), None; "one0", mask [x], mkCons (eq [1, x] 0), Some x; "one1", mask [x], mkCons (eq [1, x; 1, y] 0), Some x; "one2", mask [y], mkCons (eq [1, x; 1, y] 0), Some y; "m0", mask [x; y], mkCons (eq [1, y] 0), Some y; "m1", mask [x; y], mkCons (eq [1, y; 1, z] 0), Some y; "m2", mask [x; y], mkCons (eq [1, x; 1, y] 0), Some x ] in Test.suite "pick" (List.map chk tcs) let substTs: Test.t = fun () -> let chkCons (name, x, c, s, s1) = fun state -> let c1 = mkCons c in let s2 = EqSet.subst factory x c1 s in if EqSet.equal s1 s2 then Test.succeed state else let e = "expected:\n" ^ (EqSet.to_string_ext factory varPr s1) ^ "but got:\n" ^ (EqSet.to_string_ext factory varPr s2) in Test.fail name e state in let tcs = [ "nil0", x, eq [1, x] 0, mk [], mk []; "nil1", y, eq [1, x] 0, mk [], mk []; "nil2", y, eq [1, x] 0, mk [], mk []; "one0", x, eq [1, x] 0, mk [y, eq [1, x; 1, y] 1], mk [y, eq [1, y] 1]; "one1", x, eq [1, x] 0, mk [y, eq [1, x; 1, y] 1], mk [y, eq [1, y] 1]; "no0", x, eq [1, x] 0, mk [y, eq [1, y] 1], mk [y, eq [1, y] 1]; "m0", x, eq [1, x] 0, mk [ z, eq [1, z] 1; y, eq [1, x; 1, y] 1 ], mk [ z, eq [1, z] 1; y, eq [1, y] 1 ]; ] in Test.suite "subst" [ Test.suite "cons" (List.map chkCons tcs) ] let tryDefsTs: Test.t = fun () -> let chk_res (t, r, msk, s) = fun state -> let (def, _) = EqSet.tryDefs factory msk s in let a = if def = None then false else true in if a = r then Test.succeed state else Test.fail t "bad conclusion" state in let chk_def (t, _, msk, s) = fun state -> let (def, _) = EqSet.tryDefs factory msk s in match def with | None -> Test.succeed state | Some (_, x) -> if List.exists (fun (x1, _) -> x = x1) s then Test.succeed state else let e = "not found" in Test.fail t e state in let chk_nox (t, _, msk, s) = fun state -> let (def, s1) = EqSet.tryDefs factory msk s in match def with | None -> Test.succeed state | Some (_, x) -> let noXPred c = Cs.Vec.Coeff.cmpz (Cs.Vec.get (Cs.get_v (Cons.get_c c)) x) = 0 in if List.for_all (fun (_, c) -> noXPred c) s1 then Test.succeed state else Test.fail t "x remaining" state in let tcs = [ "nil0", false, mask [], mkl []; "nil1", false, mask [x], mkl []; "one0", true, mask [x], mkl [eq [1, x] 0]; "one0", true, mask [x], mkl [ eq [1, x] 0; eq [1, x; 1, y] 0 ]; "no0", false, mask [z], mkl [ eq [1, x; 1, z] 0; eq [1, y] 0 ] ] in Test.suite "tryDefs" [ Test.suite "res" (List.map chk_res tcs); Test.suite "def" (List.map chk_def tcs); Test.suite "nox" (List.map chk_nox tcs) ] let trySubstMTs: Test.t = fun () -> let chk_var (t, x, msk, s) = fun state -> let (optx1, _) = EqSet.trySubstM factory msk s in match optx1 with | None -> if x = None then Test.succeed state else let e = "expected " ^ (optxpr x) ^ " but got None" in Test.fail t e state | Some (_, x1) -> if x = Some x1 then Test.succeed state else let e = "expected " ^ (optxpr x) ^ " but got " ^ (optxpr (Some x1)) in Test.fail t e state in let chk_nox (t, x, msk, s) = fun state -> let (e, s1, s2) = let (_, s1) = EqSet.trySubstM factory msk s in match x with | None -> ("trySubstM did change s", s, s1) | Some x -> let c = mkCons (eq [1, x] 0) in let s2 = EqSet.subst factory x c s1 in let e = "still some " ^ (varPr x) ^ " in\n" ^ (EqSet.to_string_ext factory varPr s1) in (e, s1, s2) in if EqSet.equal s1 s2 then Test.succeed state else Test.fail t e state in let tcs = [ "x0", Some x, mask [x], mk [ y, eq [1, x; 1, y] 0; x, eq [1, x] 0 ]; "no0", None, mask [z], mk [ x, eq [1, x] 0 ] ] in Test.suite "trySubstM" [ Test.suite "var" (List.map chk_var tcs); Test.suite "nox" (List.map chk_nox tcs) ] let joinSetupTs: Test.t = let alpha = Var.fromInt nxt in let nxt' = nxt + 1 in let chk_id0 dup (t, idOff, s) = fun state -> let (_, _, s1) = EqSet.joinSetup dup (Var.fromInt nxt') Rtree.empty alpha idOff s in let sorted = let ids = List.map (fun c -> (Cons.get_id c)) (EqSet.list s) in List.sort Stdlib.compare ids in let sorted1 = let ids1 = List.map (fun c -> (Cons.get_id c) - idOff) (EqSet.list s1) in List.sort Stdlib.compare ids1 in if sorted = sorted1 then Test.succeed state else Test.fail t "not equal" state in let chk_def0 dup (t, i0, s) = fun state -> let (_, reloc, s1) = EqSet.joinSetup dup (Var.fromInt nxt') Rtree.empty alpha i0 s in let a = let chk (x1, _) (x2, _) = if dup then x1 = x2 else Rtree.get None reloc x1 = Some x2 in List.for_all2 chk s s1 in if a then Test.succeed state else let err = Printf.sprintf "wrong defined variables: s:\n%s\ns1:\n%s\n" (EqSet.to_string_ext varPr s) (EqSet.to_string_ext varPr s1) in Test.fail t err state in let chk_frag0 dup (t, i0, s) = fun state -> let (_, _, s1) = EqSet.joinSetup dup (Var.fromInt nxt') Rtree.empty alpha i0 s in let a = let chk c = match Cons.get_f c with | [] -> false | (id, coef)::[] -> id = (Cons.get_id c) && Cs.Vec.Coeff.cmp Cs.Vec.Coeff.u coef = 0 | _ -> false in List.for_all chk (EqSet.list s1) in if a then Test.succeed state else Test.fail t "bad fragments" state in let tcs = [ "one0", 10, mk [ x, eq [1, x] 1 ]; "one1", 10, mk [ x, eq [1, x; 1, y] 1 ]; "one2", 10, mk [ y, eq [1, x; 1, y] 1 ]; "m0", 10, mk [ x, eq [1, x; 1, y] 1; y, eq [2, y; 1, z] 1; z, eq [1, z; 2, t] 1 ] ] in let chk_id = chk_id0 false in let chk_idd = chk_id0 true in let chk_def = chk_def0 false in let chk_frag = chk_frag0 false in let chk_defd = chk_def0 true in let chk_fragd = chk_frag0 true in Test.suite "joinSetup" [ Test.suite "id" (List.map chk_id tcs); Test.suite "idd" (List.map chk_idd tcs); Test.suite "def" (List.map chk_def tcs); Test.suite "defd" (List.map chk_defd tcs); Test.suite "frag" (List.map chk_frag tcs); Test.suite "fragd" (List.map chk_fragd tcs) ] *) EqSet.incl let inclTs: Test.t = fun () -> let chk (name, s1, s2, expected) = fun state -> let actual = EqSet.leq factory s1 s2 in if relEq actual expected then Test.succeed state else Test.fail name (relPr actual) state in let tcs = [ "id0", mks [eq [1, x] 0 ], mks [eq [1, x] 0 ], EqSet.Incl [eq [1, x] 0]; "id1", mks [ eq [1, y] 0; eq [1, x] 0], mks [eq [1, x] 0 ], EqSet.Incl [eq [1, x] 0]; "bin0", mks [ eq [1, y] 0; eq [1, x] 0 ], mks [eq [1, x; 1, y] 0 ], EqSet.Incl [eq [1, x; 1, y] 0] ] in Test.suite "incl" (List.map chk tcs) let renameTs: Test.t = fun () -> let x' = Var.fromInt nxt in let chkVar (t, fromX, toY, s0) = fun state -> let defVars s = List.map (fun (v, _) -> v) s in let s = EqSet.rename factory s0 fromX toY in if List.for_all (fun v -> v <> fromX) (defVars s) then Test.succeed state else let e = (varPr fromX) ^ " remaining\n" ^ (EqSet.to_string_ext factory varPr s) in Test.fail t e state in let chkCoef (t, fromX, toY, s0) = fun state -> let aX s = let coef (c,cert) x = Cs.Vec.get (Cs.get_v c) x in List.map (fun (_, c) -> coef c fromX) s in let s = EqSet.rename factory s0 fromX toY in if List.for_all (fun a -> Cs.Vec.Coeff.cmpz a = 0) (aX s) then Test.succeed state else let e = (varPr fromX) ^ " remaining\n" ^ (EqSet.to_string_ext factory varPr s) in Test.fail t e state in let tcs = [ "one0", x', x, mkl [ eq [1, x'] 0 ]; "one1", x', x, mkl [ eq [1, x'; 1, y] 0 ]; "no0", x', x, mkl [ eq [1, y] 0 ]; "m0", x', x ,mkl [ eq [1, x'; 1, y] 1; eq [1, x'; 2, y] 2 ]; ] in Test.suite "rename" [ Test.suite "var" (List.map chkVar tcs); Test.suite "coef" (List.map chkCoef tcs) ] let ts: Test.t = fun () -> |> Test.suite "EqSet"
2ed499db84a0ca0d284169bc56162e68e356c5a32cba25c3fa985b0489f47a8e
hammerlab/ketrew
client.mli
(**************************************************************************) Copyright 2014 , 2015 : < > , < > , Arun < > , < > (* *) 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. *) (**************************************************************************) (** The “client” is the frontend to an HTTP client talking to a server/engine. *) open Ketrew_pure open Internal_pervasives open Unix_io (** [Error.t] is the type of the error kinds that this module introduces. *) module Error : sig type t = [ `Http of [ `Call of [ `GET | `POST ] * Uri.t | `Targets | `Target_query of Unique_id.t * string | `Process_holder ] * [ `Exn of exn | `Json_parsing of string * [ `Exn of exn ] | `Unexpected_message of Ketrew_pure.Protocol.Down_message.t | `Wrong_json of Yojson.Safe.json | `Wrong_response of Cohttp.Response.t * string ] | `Server_error_response of [ `Call of [ `GET | `POST ] * Uri.t ] * string ] val log : t -> Log.t end type t (** The handle of the client. *) val as_client: configuration:Configuration.t -> f:(client:t -> ('result, [> `Database of Persistent_data.Error.database | `Dyn_plugin of [> `Dynlink_error of Dynlink.error | `Findlib of exn ] | `Failure of string | `Wrong_configuration of [> `Found of string ] * [> `Exn of exn ] ] as 'a) Deferred_result.t) -> ('result, 'a) Deferred_result.t (** Run the function [f] with a fresh-client created with the [configuration]. *) val configuration: t -> Configuration.t (** Retrieve the configuration used to create the client. *) val get_list_of_target_ids : t -> query:Ketrew_pure.Protocol.Up_message.target_query -> (Ketrew_pure.Target.id list, [> `Client of Error.t | `Database of Persistent_data.Error.database]) Deferred_result.t (** Get a list of target IDs given the [query]. *) val get_target: t -> id:Ketrew_pure.Target.id -> (Ketrew_pure.Target.t, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t (** The latest contents of a given target. *) val get_targets: t -> id_list:Ketrew_pure.Target.id list -> (Ketrew_pure.Target.t list, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t (** Same as {!get_target} but “in bulk.” *) val call_query: t -> target:Ketrew_pure.Target.t -> string -> (string, Log.t) Deferred_result.t (** Call a target's plugin query by name. *) val kill: t -> Ketrew_pure.Target.id list -> (unit, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t (** Kill a set of targets. *) val restart: t -> Ketrew_pure.Target.id list -> (unit, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t (** Restart a set of targets. *) val add_targets: t -> Ketrew_pure.Target.t list -> (unit, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t * Submit a list of targets to the server / engine . This is the low - level API dealing with { ! . } values ; for use in the EDSL please see { ! submit_workflow } below . dealing with {!Ketrew_pure.Target.t} values; for use in the EDSL please see {!submit_workflow} below. *) val submit_workflow: ?safe_ids: bool -> ?override_configuration:Configuration.t -> ?add_tags:string list -> 'any EDSL.product EDSL.workflow_node -> unit (** Submit a high-level workflow description to the engine; this function calls [Lwt_main.run]. One can add tags to all the targets in the workflow before submitting with the [add_tags] option. For experienced users: by default {!submit_workflow} makes IDs unique within the workflow, one can override this by setting [~safe_ids:false]. *) val submit: ?override_configuration:Configuration.t -> ?add_tags: string list -> EDSL.user_target -> unit * This is like { ! submit_workflow } but for the deprecated / legacy API ( i.e. created with calls to { ! EDSL.user_target } ) . (i.e. created with calls to {!EDSL.user_target}). *)
null
https://raw.githubusercontent.com/hammerlab/ketrew/8940d48fbe174709f076b7130974ecd0ed831d58/src/lib/client.mli
ocaml
************************************************************************ 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. ************************************************************************ * The “client” is the frontend to an HTTP client talking to a server/engine. * [Error.t] is the type of the error kinds that this module introduces. * The handle of the client. * Run the function [f] with a fresh-client created with the [configuration]. * Retrieve the configuration used to create the client. * Get a list of target IDs given the [query]. * The latest contents of a given target. * Same as {!get_target} but “in bulk.” * Call a target's plugin query by name. * Kill a set of targets. * Restart a set of targets. * Submit a high-level workflow description to the engine; this function calls [Lwt_main.run]. One can add tags to all the targets in the workflow before submitting with the [add_tags] option. For experienced users: by default {!submit_workflow} makes IDs unique within the workflow, one can override this by setting [~safe_ids:false].
Copyright 2014 , 2015 : < > , < > , Arun < > , < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , open Ketrew_pure open Internal_pervasives open Unix_io module Error : sig type t = [ `Http of [ `Call of [ `GET | `POST ] * Uri.t | `Targets | `Target_query of Unique_id.t * string | `Process_holder ] * [ `Exn of exn | `Json_parsing of string * [ `Exn of exn ] | `Unexpected_message of Ketrew_pure.Protocol.Down_message.t | `Wrong_json of Yojson.Safe.json | `Wrong_response of Cohttp.Response.t * string ] | `Server_error_response of [ `Call of [ `GET | `POST ] * Uri.t ] * string ] val log : t -> Log.t end type t val as_client: configuration:Configuration.t -> f:(client:t -> ('result, [> `Database of Persistent_data.Error.database | `Dyn_plugin of [> `Dynlink_error of Dynlink.error | `Findlib of exn ] | `Failure of string | `Wrong_configuration of [> `Found of string ] * [> `Exn of exn ] ] as 'a) Deferred_result.t) -> ('result, 'a) Deferred_result.t val configuration: t -> Configuration.t val get_list_of_target_ids : t -> query:Ketrew_pure.Protocol.Up_message.target_query -> (Ketrew_pure.Target.id list, [> `Client of Error.t | `Database of Persistent_data.Error.database]) Deferred_result.t val get_target: t -> id:Ketrew_pure.Target.id -> (Ketrew_pure.Target.t, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t val get_targets: t -> id_list:Ketrew_pure.Target.id list -> (Ketrew_pure.Target.t list, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t val call_query: t -> target:Ketrew_pure.Target.t -> string -> (string, Log.t) Deferred_result.t val kill: t -> Ketrew_pure.Target.id list -> (unit, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t val restart: t -> Ketrew_pure.Target.id list -> (unit, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t val add_targets: t -> Ketrew_pure.Target.t list -> (unit, [> `Client of Error.t | `Database of Persistent_data.Error.database ]) Deferred_result.t * Submit a list of targets to the server / engine . This is the low - level API dealing with { ! . } values ; for use in the EDSL please see { ! submit_workflow } below . dealing with {!Ketrew_pure.Target.t} values; for use in the EDSL please see {!submit_workflow} below. *) val submit_workflow: ?safe_ids: bool -> ?override_configuration:Configuration.t -> ?add_tags:string list -> 'any EDSL.product EDSL.workflow_node -> unit val submit: ?override_configuration:Configuration.t -> ?add_tags: string list -> EDSL.user_target -> unit * This is like { ! submit_workflow } but for the deprecated / legacy API ( i.e. created with calls to { ! EDSL.user_target } ) . (i.e. created with calls to {!EDSL.user_target}). *)
6e08a67397fb6948cd643419df7c3e88485e46a3e9146a5c4a5e1a120fe9aadd
bzliu94/cs61a_fa07
query_modified.scm
;;;;QUERY SYSTEM FROM SECTION 4.4.4 OF ;;;; STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS ;;;;Matches code in ch4.scm ;;;;Includes: -- supporting code from 4.1 , chapter 3 , and instructor 's manual -- data base from Section 4.4.1 -- see microshaft - data - base below ;;;;This file can be loaded into Scheme as a whole. ;;;;In order to run the query system, the Scheme must support streams. NB . PUT 's are commented out and no top - level table is set up . ;;;;Instead use initialize-data-base (from manual), supplied in this file. ;;;SECTION 4.4.4.1 The Driver Loop and Instantiation (define input-prompt ";;; Query input:") (define output-prompt ";;; Query results:") (define (query-driver-loop) (prompt-for-input input-prompt) (let ((q (query-syntax-process (read)))) (cond ((assertion-to-be-added? q) (add-rule-or-assertion! (add-assertion-body q)) (newline) (display "Assertion added to data base.") (query-driver-loop)) (else (newline) (display output-prompt) ;; [extra newline at end] (announce-output output-prompt) (display-stream (stream-map (lambda (frame) (instantiate q frame (lambda (v f) (contract-question-mark v)))) (qeval q (singleton-stream '())))) (query-driver-loop))))) (define (instantiate exp frame unbound-var-handler) (define (copy exp) (cond ((var? exp) (let ((binding (binding-in-frame exp frame))) (if binding (copy (binding-value binding)) (unbound-var-handler exp frame)))) ((pair? exp) (cons (copy (car exp)) (copy (cdr exp)))) (else exp))) (copy exp)) ;;;SECTION 4.4.4.2 ;;;The Evaluator (define (qeval query frame-stream) (let ((qproc (get (type query) 'qeval))) (if qproc (qproc (contents query) frame-stream) (simple-query query frame-stream)))) ;;;Simple queries (define (simple-query query-pattern frame-stream) (stream-flatmap (lambda (frame) (stream-append-delayed (find-assertions query-pattern frame) (delay (apply-rules query-pattern frame)))) frame-stream)) ;;;Compound queries (define (conjoin conjuncts frame-stream) (if (empty-conjunction? conjuncts) frame-stream (conjoin (rest-conjuncts conjuncts) (qeval (first-conjunct conjuncts) frame-stream)))) ;;(put 'and 'qeval conjoin) (define (disjoin disjuncts frame-stream) (if (empty-disjunction? disjuncts) the-empty-stream (interleave-delayed (qeval (first-disjunct disjuncts) frame-stream) (delay (disjoin (rest-disjuncts disjuncts) frame-stream))))) ( put ' or ' qeval disjoin ) ;;;Filters (define (negate operands frame-stream) (stream-flatmap (lambda (frame) (if (stream-null? (qeval (negated-query operands) (singleton-stream frame))) (singleton-stream frame) the-empty-stream)) frame-stream)) ;;(put 'not 'qeval negate) (define (lisp-value call frame-stream) (stream-flatmap (lambda (frame) (if (execute (instantiate call frame (lambda (v f) (error "Unknown pat var -- LISP-VALUE" v)))) (singleton-stream frame) the-empty-stream)) frame-stream)) ;;(put 'lisp-value 'qeval lisp-value) (define (execute exp) (apply (eval (predicate exp)) ; (eval (...) user-initial-environment) (args exp))) (define (always-true ignore frame-stream) frame-stream) ;;(put 'always-true 'qeval always-true) ;;;SECTION 4.4.4.3 ;;;Finding Assertions by Pattern Matching (define (find-assertions pattern frame) (stream-flatmap (lambda (datum) (check-an-assertion datum pattern frame)) (fetch-assertions pattern frame))) (define (check-an-assertion assertion query-pat query-frame) (let ((match-result (pattern-match query-pat assertion query-frame))) (if (eq? match-result 'failed) the-empty-stream (singleton-stream match-result)))) (define (pattern-match pat dat frame) (cond ((eq? frame 'failed) 'failed) ((equal? pat dat) frame) ((var? pat) (extend-if-consistent pat dat frame)) ((and (pair? pat) (pair? dat)) (pattern-match (cdr pat) (cdr dat) (pattern-match (car pat) (car dat) frame))) (else 'failed))) (define (extend-if-consistent var dat frame) (let ((binding (binding-in-frame var frame))) (if binding (pattern-match (binding-value binding) dat frame) (extend var dat frame)))) SECTION 4.4.4.4 ;;;Rules and Unification (define (apply-rules pattern frame) (stream-flatmap (lambda (rule) (apply-a-rule rule pattern frame)) (fetch-rules pattern frame))) (define (apply-a-rule rule query-pattern query-frame) (let ((clean-rule (rename-variables-in rule))) (let ((unify-result (unify-match query-pattern (conclusion clean-rule) query-frame))) (if (eq? unify-result 'failed) the-empty-stream (qeval (rule-body clean-rule) (singleton-stream unify-result)))))) (define (rename-variables-in rule) (let ((rule-application-id (new-rule-application-id))) (define (tree-walk exp) (cond ((var? exp) (make-new-variable exp rule-application-id)) ((pair? exp) (cons (tree-walk (car exp)) (tree-walk (cdr exp)))) (else exp))) (tree-walk rule))) (define (unify-match p1 p2 frame) (cond ((eq? frame 'failed) 'failed) ((equal? p1 p2) frame) ((var? p1) (extend-if-possible p1 p2 frame)) ; * * * } ((and (pair? p1) (pair? p2)) (unify-match (cdr p1) (cdr p2) (unify-match (car p1) (car p2) frame))) (else 'failed))) (define (extend-if-possible var val frame) (let ((binding (binding-in-frame var frame))) (cond (binding (unify-match (binding-value binding) val frame)) ; * * * } (let ((binding (binding-in-frame val frame))) (if binding (unify-match var (binding-value binding) frame) (extend var val frame)))) ; * * * } 'failed) (else (extend var val frame))))) (define (depends-on? exp var frame) (define (tree-walk e) (cond ((var? e) (if (equal? var e) true (let ((b (binding-in-frame e frame))) (if b (tree-walk (binding-value b)) false)))) ((pair? e) (or (tree-walk (car e)) (tree-walk (cdr e)))) (else false))) (tree-walk exp)) ;;;SECTION 4.4.4.5 ;;;Maintaining the Data Base (define THE-ASSERTIONS the-empty-stream) (define (fetch-assertions pattern frame) (if (use-index? pattern) (get-indexed-assertions pattern) (get-all-assertions))) (define (get-all-assertions) THE-ASSERTIONS) (define (get-indexed-assertions pattern) (get-stream (index-key-of pattern) 'assertion-stream)) (define (get-stream key1 key2) (let ((s (get key1 key2))) (if s s the-empty-stream))) (define THE-RULES the-empty-stream) (define (fetch-rules pattern frame) (if (use-index? pattern) (get-indexed-rules pattern) (get-all-rules))) (define (get-all-rules) THE-RULES) (define (get-indexed-rules pattern) (stream-append (get-stream (index-key-of pattern) 'rule-stream) (get-stream '? 'rule-stream))) (define (add-rule-or-assertion! assertion) (if (rule? assertion) (add-rule! assertion) (add-assertion! assertion))) (define (add-assertion! assertion) (store-assertion-in-index assertion) (let ((old-assertions THE-ASSERTIONS)) (set! THE-ASSERTIONS (cons-stream assertion old-assertions)) 'ok)) (define (add-rule! rule) (store-rule-in-index rule) (let ((old-rules THE-RULES)) (set! THE-RULES (cons-stream rule old-rules)) 'ok)) (define (store-assertion-in-index assertion) (if (indexable? assertion) (let ((key (index-key-of assertion))) (let ((current-assertion-stream (get-stream key 'assertion-stream))) (put key 'assertion-stream (cons-stream assertion current-assertion-stream)))))) (define (store-rule-in-index rule) (let ((pattern (conclusion rule))) (if (indexable? pattern) (let ((key (index-key-of pattern))) (let ((current-rule-stream (get-stream key 'rule-stream))) (put key 'rule-stream (cons-stream rule current-rule-stream))))))) (define (indexable? pat) (or (constant-symbol? (car pat)) (var? (car pat)))) (define (index-key-of pat) (let ((key (car pat))) (if (var? key) '? key))) (define (use-index? pat) (constant-symbol? (car pat))) ;;;SECTION 4.4.4.6 ;;;Stream operations (define (stream-append-delayed s1 delayed-s2) (if (stream-null? s1) (force delayed-s2) (cons-stream (stream-car s1) (stream-append-delayed (stream-cdr s1) delayed-s2)))) (define (interleave-delayed s1 delayed-s2) (if (stream-null? s1) (force delayed-s2) (cons-stream (stream-car s1) (interleave-delayed (force delayed-s2) (delay (stream-cdr s1)))))) (define (stream-flatmap proc s) (flatten-stream (stream-map proc s))) (define (flatten-stream stream) (if (stream-null? stream) the-empty-stream (interleave-delayed (stream-car stream) (delay (flatten-stream (stream-cdr stream)))))) (define (singleton-stream x) (cons-stream x the-empty-stream)) ;;;SECTION 4.4.4.7 ;;;Query syntax procedures (define (type exp) (if (pair? exp) (car exp) (error "Unknown expression TYPE" exp))) (define (contents exp) (if (pair? exp) (cdr exp) (error "Unknown expression CONTENTS" exp))) (define (assertion-to-be-added? exp) (eq? (type exp) 'assert!)) (define (add-assertion-body exp) (car (contents exp))) (define (empty-conjunction? exps) (null? exps)) (define (first-conjunct exps) (car exps)) (define (rest-conjuncts exps) (cdr exps)) (define (empty-disjunction? exps) (null? exps)) (define (first-disjunct exps) (car exps)) (define (rest-disjuncts exps) (cdr exps)) (define (negated-query exps) (car exps)) (define (predicate exps) (car exps)) (define (args exps) (cdr exps)) (define (rule? statement) (tagged-list? statement 'rule)) (define (conclusion rule) (cadr rule)) (define (rule-body rule) (if (null? (cddr rule)) '(always-true) (caddr rule))) (define (query-syntax-process exp) (map-over-symbols expand-question-mark exp)) (define (map-over-symbols proc exp) (cond ((pair? exp) (cons (map-over-symbols proc (car exp)) (map-over-symbols proc (cdr exp)))) ((symbol? exp) (proc exp)) (else exp))) (define (expand-question-mark symbol) (let ((chars (symbol->string symbol))) (if (string=? (substring chars 0 1) "?") (list '? (string->symbol (substring chars 1 (string-length chars)))) symbol))) (define (var? exp) (tagged-list? exp '?)) (define (constant-symbol? exp) (symbol? exp)) (define rule-counter 0) (define (new-rule-application-id) (set! rule-counter (+ 1 rule-counter)) rule-counter) (define (make-new-variable var rule-application-id) (cons '? (cons rule-application-id (cdr var)))) (define (contract-question-mark variable) (string->symbol (string-append "?" (if (number? (cadr variable)) (string-append (symbol->string (caddr variable)) "-" (number->string (cadr variable))) (symbol->string (cadr variable)))))) ;;;SECTION 4.4.4.8 ;;;Frames and bindings (define (make-binding variable value) (cons variable value)) (define (binding-variable binding) (car binding)) (define (binding-value binding) (cdr binding)) (define (binding-in-frame variable frame) (assoc variable frame)) (define (extend variable value frame) (cons (make-binding variable value) frame)) ;;;;From Section 4.1 (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) false)) (define (prompt-for-input string) (newline) (newline) (display string) (newline)) Stream support from Chapter 3 (define (stream-map proc s) (if (stream-null? s) the-empty-stream (cons-stream (proc (stream-car s)) (stream-map proc (stream-cdr s))))) (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (define (display-stream s) (stream-for-each display-line s)) (define (display-line x) (newline) (display x)) (define (stream-filter pred stream) (cond ((stream-null? stream) the-empty-stream) ((pred (stream-car stream)) (cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream)))) (else (stream-filter pred (stream-cdr stream))))) (define (stream-append s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (stream-append (stream-cdr s1) s2)))) (define (interleave s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) Table support from Chapter 3 , Section 3.3.3 ( local tables ) (define (make-table) (let ((local-table (list '*table*))) (define (lookup key-1 key-2) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (cdr record) false)) false))) (define (insert! key-1 key-2 value) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! local-table (cons (list key-1 (cons key-2 value)) (cdr local-table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) ;;;; From instructor's manual (define get '()) (define put '()) (define (initialize-data-base rules-and-assertions) (define (deal-out r-and-a rules assertions) (cond ((null? r-and-a) (set! THE-ASSERTIONS (list->stream assertions)) (set! THE-RULES (list->stream rules)) 'done) (else (let ((s (query-syntax-process (car r-and-a)))) (cond ((rule? s) (store-rule-in-index s) (deal-out (cdr r-and-a) (cons s rules) assertions)) (else (store-assertion-in-index s) (deal-out (cdr r-and-a) rules (cons s assertions)))))))) (let ((operation-table (make-table))) (set! get (operation-table 'lookup-proc)) (set! put (operation-table 'insert-proc!))) (put 'and 'qeval conjoin) (put 'or 'qeval disjoin) (put 'not 'qeval negate) (put 'lisp-value 'qeval lisp-value) (put 'always-true 'qeval always-true) (deal-out rules-and-assertions '() '())) ;; Do following to reinit the data base from microshaft-data-base ;; in Scheme (not in the query driver loop) ;; (initialize-data-base microshaft-data-base) (define microshaft-data-base '( from section 4.4.1 (address (Bitdiddle Ben) (Slumerville (Ridge Road) 10)) (job (Bitdiddle Ben) (computer wizard)) (salary (Bitdiddle Ben) 60000) (address (Hacker Alyssa P) (Cambridge (Mass Ave) 78)) (job (Hacker Alyssa P) (computer programmer)) (salary (Hacker Alyssa P) 40000) (supervisor (Hacker Alyssa P) (Bitdiddle Ben)) (address (Fect Cy D) (Cambridge (Ames Street) 3)) (job (Fect Cy D) (computer programmer)) (salary (Fect Cy D) 35000) (supervisor (Fect Cy D) (Bitdiddle Ben)) (address (Tweakit Lem E) (Boston (Bay State Road) 22)) (job (Tweakit Lem E) (computer technician)) (salary (Tweakit Lem E) 25000) (supervisor (Tweakit Lem E) (Bitdiddle Ben)) (address (Reasoner Louis) (Slumerville (Pine Tree Road) 80)) (job (Reasoner Louis) (computer programmer trainee)) (salary (Reasoner Louis) 30000) (supervisor (Reasoner Louis) (Hacker Alyssa P)) (supervisor (Bitdiddle Ben) (Warbucks Oliver)) (address (Warbucks Oliver) (Swellesley (Top Heap Road))) (job (Warbucks Oliver) (administration big wheel)) (salary (Warbucks Oliver) 150000) (address (Scrooge Eben) (Weston (Shady Lane) 10)) (job (Scrooge Eben) (accounting chief accountant)) (salary (Scrooge Eben) 75000) (supervisor (Scrooge Eben) (Warbucks Oliver)) (address (Cratchet Robert) (Allston (N Harvard Street) 16)) (job (Cratchet Robert) (accounting scrivener)) (salary (Cratchet Robert) 18000) (supervisor (Cratchet Robert) (Scrooge Eben)) (address (Aull DeWitt) (Slumerville (Onion Square) 5)) (job (Aull DeWitt) (administration secretary)) (salary (Aull DeWitt) 25000) (supervisor (Aull DeWitt) (Warbucks Oliver)) (can-do-job (computer wizard) (computer programmer)) (can-do-job (computer wizard) (computer technician)) (can-do-job (computer programmer) (computer programmer trainee)) (can-do-job (administration secretary) (administration big wheel)) (rule (lives-near ?person-1 ?person-2) (and (address ?person-1 (?town . ?rest-1)) (address ?person-2 (?town . ?rest-2)) (not (same ?person-1 ?person-2)))) (rule (same ?x ?x)) (rule (wheel ?person) (and (supervisor ?middle-manager ?person) (supervisor ?x ?middle-manager))) (rule (outranked-by ?staff-person ?boss) (or (supervisor ?staff-person ?boss) (and (supervisor ?staff-person ?middle-manager) (outranked-by ?middle-manager ?boss)))) )) Added at Berkeley : (define (query) ; commented out because we want access to microshaft-data-base ; (initialize-data-base '()) (query-driver-loop)) (define (aa query) (add-rule-or-assertion! (add-assertion-body (query-syntax-process (list 'assert! query))))) ; (initialize-data-base '()) (initialize-data-base microshaft-data-base)
null
https://raw.githubusercontent.com/bzliu94/cs61a_fa07/12a62689f149ef035a36b326351928928f6e7b5d/02%20-%20labs/lab15/query_modified.scm
scheme
QUERY SYSTEM FROM SECTION 4.4.4 OF STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS Matches code in ch4.scm Includes: This file can be loaded into Scheme as a whole. In order to run the query system, the Scheme must support streams. Instead use initialize-data-base (from manual), supplied in this file. SECTION 4.4.4.1 [extra newline at end] (announce-output output-prompt) SECTION 4.4.4.2 The Evaluator Simple queries Compound queries (put 'and 'qeval conjoin) Filters (put 'not 'qeval negate) (put 'lisp-value 'qeval lisp-value) (eval (...) user-initial-environment) (put 'always-true 'qeval always-true) SECTION 4.4.4.3 Finding Assertions by Pattern Matching Rules and Unification * * * } * * * } * * * } SECTION 4.4.4.5 Maintaining the Data Base SECTION 4.4.4.6 Stream operations SECTION 4.4.4.7 Query syntax procedures SECTION 4.4.4.8 Frames and bindings From Section 4.1 From instructor's manual Do following to reinit the data base from microshaft-data-base in Scheme (not in the query driver loop) (initialize-data-base microshaft-data-base) commented out because we want access to microshaft-data-base (initialize-data-base '()) (initialize-data-base '())
-- supporting code from 4.1 , chapter 3 , and instructor 's manual -- data base from Section 4.4.1 -- see microshaft - data - base below NB . PUT 's are commented out and no top - level table is set up . The Driver Loop and Instantiation (define input-prompt ";;; Query input:") (define output-prompt ";;; Query results:") (define (query-driver-loop) (prompt-for-input input-prompt) (let ((q (query-syntax-process (read)))) (cond ((assertion-to-be-added? q) (add-rule-or-assertion! (add-assertion-body q)) (newline) (display "Assertion added to data base.") (query-driver-loop)) (else (newline) (display output-prompt) (display-stream (stream-map (lambda (frame) (instantiate q frame (lambda (v f) (contract-question-mark v)))) (qeval q (singleton-stream '())))) (query-driver-loop))))) (define (instantiate exp frame unbound-var-handler) (define (copy exp) (cond ((var? exp) (let ((binding (binding-in-frame exp frame))) (if binding (copy (binding-value binding)) (unbound-var-handler exp frame)))) ((pair? exp) (cons (copy (car exp)) (copy (cdr exp)))) (else exp))) (copy exp)) (define (qeval query frame-stream) (let ((qproc (get (type query) 'qeval))) (if qproc (qproc (contents query) frame-stream) (simple-query query frame-stream)))) (define (simple-query query-pattern frame-stream) (stream-flatmap (lambda (frame) (stream-append-delayed (find-assertions query-pattern frame) (delay (apply-rules query-pattern frame)))) frame-stream)) (define (conjoin conjuncts frame-stream) (if (empty-conjunction? conjuncts) frame-stream (conjoin (rest-conjuncts conjuncts) (qeval (first-conjunct conjuncts) frame-stream)))) (define (disjoin disjuncts frame-stream) (if (empty-disjunction? disjuncts) the-empty-stream (interleave-delayed (qeval (first-disjunct disjuncts) frame-stream) (delay (disjoin (rest-disjuncts disjuncts) frame-stream))))) ( put ' or ' qeval disjoin ) (define (negate operands frame-stream) (stream-flatmap (lambda (frame) (if (stream-null? (qeval (negated-query operands) (singleton-stream frame))) (singleton-stream frame) the-empty-stream)) frame-stream)) (define (lisp-value call frame-stream) (stream-flatmap (lambda (frame) (if (execute (instantiate call frame (lambda (v f) (error "Unknown pat var -- LISP-VALUE" v)))) (singleton-stream frame) the-empty-stream)) frame-stream)) (define (execute exp) (args exp))) (define (always-true ignore frame-stream) frame-stream) (define (find-assertions pattern frame) (stream-flatmap (lambda (datum) (check-an-assertion datum pattern frame)) (fetch-assertions pattern frame))) (define (check-an-assertion assertion query-pat query-frame) (let ((match-result (pattern-match query-pat assertion query-frame))) (if (eq? match-result 'failed) the-empty-stream (singleton-stream match-result)))) (define (pattern-match pat dat frame) (cond ((eq? frame 'failed) 'failed) ((equal? pat dat) frame) ((var? pat) (extend-if-consistent pat dat frame)) ((and (pair? pat) (pair? dat)) (pattern-match (cdr pat) (cdr dat) (pattern-match (car pat) (car dat) frame))) (else 'failed))) (define (extend-if-consistent var dat frame) (let ((binding (binding-in-frame var frame))) (if binding (pattern-match (binding-value binding) dat frame) (extend var dat frame)))) SECTION 4.4.4.4 (define (apply-rules pattern frame) (stream-flatmap (lambda (rule) (apply-a-rule rule pattern frame)) (fetch-rules pattern frame))) (define (apply-a-rule rule query-pattern query-frame) (let ((clean-rule (rename-variables-in rule))) (let ((unify-result (unify-match query-pattern (conclusion clean-rule) query-frame))) (if (eq? unify-result 'failed) the-empty-stream (qeval (rule-body clean-rule) (singleton-stream unify-result)))))) (define (rename-variables-in rule) (let ((rule-application-id (new-rule-application-id))) (define (tree-walk exp) (cond ((var? exp) (make-new-variable exp rule-application-id)) ((pair? exp) (cons (tree-walk (car exp)) (tree-walk (cdr exp)))) (else exp))) (tree-walk rule))) (define (unify-match p1 p2 frame) (cond ((eq? frame 'failed) 'failed) ((equal? p1 p2) frame) ((var? p1) (extend-if-possible p1 p2 frame)) ((and (pair? p1) (pair? p2)) (unify-match (cdr p1) (cdr p2) (unify-match (car p1) (car p2) frame))) (else 'failed))) (define (extend-if-possible var val frame) (let ((binding (binding-in-frame var frame))) (cond (binding (unify-match (binding-value binding) val frame)) (let ((binding (binding-in-frame val frame))) (if binding (unify-match var (binding-value binding) frame) (extend var val frame)))) 'failed) (else (extend var val frame))))) (define (depends-on? exp var frame) (define (tree-walk e) (cond ((var? e) (if (equal? var e) true (let ((b (binding-in-frame e frame))) (if b (tree-walk (binding-value b)) false)))) ((pair? e) (or (tree-walk (car e)) (tree-walk (cdr e)))) (else false))) (tree-walk exp)) (define THE-ASSERTIONS the-empty-stream) (define (fetch-assertions pattern frame) (if (use-index? pattern) (get-indexed-assertions pattern) (get-all-assertions))) (define (get-all-assertions) THE-ASSERTIONS) (define (get-indexed-assertions pattern) (get-stream (index-key-of pattern) 'assertion-stream)) (define (get-stream key1 key2) (let ((s (get key1 key2))) (if s s the-empty-stream))) (define THE-RULES the-empty-stream) (define (fetch-rules pattern frame) (if (use-index? pattern) (get-indexed-rules pattern) (get-all-rules))) (define (get-all-rules) THE-RULES) (define (get-indexed-rules pattern) (stream-append (get-stream (index-key-of pattern) 'rule-stream) (get-stream '? 'rule-stream))) (define (add-rule-or-assertion! assertion) (if (rule? assertion) (add-rule! assertion) (add-assertion! assertion))) (define (add-assertion! assertion) (store-assertion-in-index assertion) (let ((old-assertions THE-ASSERTIONS)) (set! THE-ASSERTIONS (cons-stream assertion old-assertions)) 'ok)) (define (add-rule! rule) (store-rule-in-index rule) (let ((old-rules THE-RULES)) (set! THE-RULES (cons-stream rule old-rules)) 'ok)) (define (store-assertion-in-index assertion) (if (indexable? assertion) (let ((key (index-key-of assertion))) (let ((current-assertion-stream (get-stream key 'assertion-stream))) (put key 'assertion-stream (cons-stream assertion current-assertion-stream)))))) (define (store-rule-in-index rule) (let ((pattern (conclusion rule))) (if (indexable? pattern) (let ((key (index-key-of pattern))) (let ((current-rule-stream (get-stream key 'rule-stream))) (put key 'rule-stream (cons-stream rule current-rule-stream))))))) (define (indexable? pat) (or (constant-symbol? (car pat)) (var? (car pat)))) (define (index-key-of pat) (let ((key (car pat))) (if (var? key) '? key))) (define (use-index? pat) (constant-symbol? (car pat))) (define (stream-append-delayed s1 delayed-s2) (if (stream-null? s1) (force delayed-s2) (cons-stream (stream-car s1) (stream-append-delayed (stream-cdr s1) delayed-s2)))) (define (interleave-delayed s1 delayed-s2) (if (stream-null? s1) (force delayed-s2) (cons-stream (stream-car s1) (interleave-delayed (force delayed-s2) (delay (stream-cdr s1)))))) (define (stream-flatmap proc s) (flatten-stream (stream-map proc s))) (define (flatten-stream stream) (if (stream-null? stream) the-empty-stream (interleave-delayed (stream-car stream) (delay (flatten-stream (stream-cdr stream)))))) (define (singleton-stream x) (cons-stream x the-empty-stream)) (define (type exp) (if (pair? exp) (car exp) (error "Unknown expression TYPE" exp))) (define (contents exp) (if (pair? exp) (cdr exp) (error "Unknown expression CONTENTS" exp))) (define (assertion-to-be-added? exp) (eq? (type exp) 'assert!)) (define (add-assertion-body exp) (car (contents exp))) (define (empty-conjunction? exps) (null? exps)) (define (first-conjunct exps) (car exps)) (define (rest-conjuncts exps) (cdr exps)) (define (empty-disjunction? exps) (null? exps)) (define (first-disjunct exps) (car exps)) (define (rest-disjuncts exps) (cdr exps)) (define (negated-query exps) (car exps)) (define (predicate exps) (car exps)) (define (args exps) (cdr exps)) (define (rule? statement) (tagged-list? statement 'rule)) (define (conclusion rule) (cadr rule)) (define (rule-body rule) (if (null? (cddr rule)) '(always-true) (caddr rule))) (define (query-syntax-process exp) (map-over-symbols expand-question-mark exp)) (define (map-over-symbols proc exp) (cond ((pair? exp) (cons (map-over-symbols proc (car exp)) (map-over-symbols proc (cdr exp)))) ((symbol? exp) (proc exp)) (else exp))) (define (expand-question-mark symbol) (let ((chars (symbol->string symbol))) (if (string=? (substring chars 0 1) "?") (list '? (string->symbol (substring chars 1 (string-length chars)))) symbol))) (define (var? exp) (tagged-list? exp '?)) (define (constant-symbol? exp) (symbol? exp)) (define rule-counter 0) (define (new-rule-application-id) (set! rule-counter (+ 1 rule-counter)) rule-counter) (define (make-new-variable var rule-application-id) (cons '? (cons rule-application-id (cdr var)))) (define (contract-question-mark variable) (string->symbol (string-append "?" (if (number? (cadr variable)) (string-append (symbol->string (caddr variable)) "-" (number->string (cadr variable))) (symbol->string (cadr variable)))))) (define (make-binding variable value) (cons variable value)) (define (binding-variable binding) (car binding)) (define (binding-value binding) (cdr binding)) (define (binding-in-frame variable frame) (assoc variable frame)) (define (extend variable value frame) (cons (make-binding variable value) frame)) (define (tagged-list? exp tag) (if (pair? exp) (eq? (car exp) tag) false)) (define (prompt-for-input string) (newline) (newline) (display string) (newline)) Stream support from Chapter 3 (define (stream-map proc s) (if (stream-null? s) the-empty-stream (cons-stream (proc (stream-car s)) (stream-map proc (stream-cdr s))))) (define (stream-for-each proc s) (if (stream-null? s) 'done (begin (proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (define (display-stream s) (stream-for-each display-line s)) (define (display-line x) (newline) (display x)) (define (stream-filter pred stream) (cond ((stream-null? stream) the-empty-stream) ((pred (stream-car stream)) (cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream)))) (else (stream-filter pred (stream-cdr stream))))) (define (stream-append s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (stream-append (stream-cdr s1) s2)))) (define (interleave s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) Table support from Chapter 3 , Section 3.3.3 ( local tables ) (define (make-table) (let ((local-table (list '*table*))) (define (lookup key-1 key-2) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (cdr record) false)) false))) (define (insert! key-1 key-2 value) (let ((subtable (assoc key-1 (cdr local-table)))) (if subtable (let ((record (assoc key-2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key-2 value) (cdr subtable))))) (set-cdr! local-table (cons (list key-1 (cons key-2 value)) (cdr local-table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define get '()) (define put '()) (define (initialize-data-base rules-and-assertions) (define (deal-out r-and-a rules assertions) (cond ((null? r-and-a) (set! THE-ASSERTIONS (list->stream assertions)) (set! THE-RULES (list->stream rules)) 'done) (else (let ((s (query-syntax-process (car r-and-a)))) (cond ((rule? s) (store-rule-in-index s) (deal-out (cdr r-and-a) (cons s rules) assertions)) (else (store-assertion-in-index s) (deal-out (cdr r-and-a) rules (cons s assertions)))))))) (let ((operation-table (make-table))) (set! get (operation-table 'lookup-proc)) (set! put (operation-table 'insert-proc!))) (put 'and 'qeval conjoin) (put 'or 'qeval disjoin) (put 'not 'qeval negate) (put 'lisp-value 'qeval lisp-value) (put 'always-true 'qeval always-true) (deal-out rules-and-assertions '() '())) (define microshaft-data-base '( from section 4.4.1 (address (Bitdiddle Ben) (Slumerville (Ridge Road) 10)) (job (Bitdiddle Ben) (computer wizard)) (salary (Bitdiddle Ben) 60000) (address (Hacker Alyssa P) (Cambridge (Mass Ave) 78)) (job (Hacker Alyssa P) (computer programmer)) (salary (Hacker Alyssa P) 40000) (supervisor (Hacker Alyssa P) (Bitdiddle Ben)) (address (Fect Cy D) (Cambridge (Ames Street) 3)) (job (Fect Cy D) (computer programmer)) (salary (Fect Cy D) 35000) (supervisor (Fect Cy D) (Bitdiddle Ben)) (address (Tweakit Lem E) (Boston (Bay State Road) 22)) (job (Tweakit Lem E) (computer technician)) (salary (Tweakit Lem E) 25000) (supervisor (Tweakit Lem E) (Bitdiddle Ben)) (address (Reasoner Louis) (Slumerville (Pine Tree Road) 80)) (job (Reasoner Louis) (computer programmer trainee)) (salary (Reasoner Louis) 30000) (supervisor (Reasoner Louis) (Hacker Alyssa P)) (supervisor (Bitdiddle Ben) (Warbucks Oliver)) (address (Warbucks Oliver) (Swellesley (Top Heap Road))) (job (Warbucks Oliver) (administration big wheel)) (salary (Warbucks Oliver) 150000) (address (Scrooge Eben) (Weston (Shady Lane) 10)) (job (Scrooge Eben) (accounting chief accountant)) (salary (Scrooge Eben) 75000) (supervisor (Scrooge Eben) (Warbucks Oliver)) (address (Cratchet Robert) (Allston (N Harvard Street) 16)) (job (Cratchet Robert) (accounting scrivener)) (salary (Cratchet Robert) 18000) (supervisor (Cratchet Robert) (Scrooge Eben)) (address (Aull DeWitt) (Slumerville (Onion Square) 5)) (job (Aull DeWitt) (administration secretary)) (salary (Aull DeWitt) 25000) (supervisor (Aull DeWitt) (Warbucks Oliver)) (can-do-job (computer wizard) (computer programmer)) (can-do-job (computer wizard) (computer technician)) (can-do-job (computer programmer) (computer programmer trainee)) (can-do-job (administration secretary) (administration big wheel)) (rule (lives-near ?person-1 ?person-2) (and (address ?person-1 (?town . ?rest-1)) (address ?person-2 (?town . ?rest-2)) (not (same ?person-1 ?person-2)))) (rule (same ?x ?x)) (rule (wheel ?person) (and (supervisor ?middle-manager ?person) (supervisor ?x ?middle-manager))) (rule (outranked-by ?staff-person ?boss) (or (supervisor ?staff-person ?boss) (and (supervisor ?staff-person ?middle-manager) (outranked-by ?middle-manager ?boss)))) )) Added at Berkeley : (define (query) (query-driver-loop)) (define (aa query) (add-rule-or-assertion! (add-assertion-body (query-syntax-process (list 'assert! query))))) (initialize-data-base microshaft-data-base)
c1dae2924185b13a64910cf6a30be5162717c0ec714b63ae8fef3a6a5e0138c5
DaMSL/K3
Imperative.hs
# LANGUAGE LambdaCase # # LANGUAGE ViewPatterns # # LANGUAGE TypeFamilies # | Imperative code generation for K3 . This module provides functions which perform the first stage tree transformation to the -- imperative embedding. Stringification to a target language must be done subsequently. module Language.K3.Codegen.Imperative ( -- * Transformation Types ImperativeE, ImperativeS(..), ImperativeM, -- * Transformation Actions runImperativeM, defaultImperativeS, -- * Tree Forms declaration, expression ) where import Control.Arrow ((&&&)) import Control.Monad.State import Control.Monad.Trans.Either import Data.Maybe import Data.Functor import Data.Tree import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Declaration import Language.K3.Core.Expression import Language.K3.Core.Type type ImperativeE = () type SetFlag = Bool type IsBuiltIn = Bool data ImperativeS = ImperativeS { globals :: [(Identifier, (K3 Type, IsBuiltIn))], triggers :: [(Identifier, K3 Type)], patchables :: [(Identifier, (K3 Type, SetFlag))], showables :: [(Identifier, K3 Type)], mutables :: [Identifier] } type ImperativeM a = EitherT ImperativeE (State ImperativeS) a runImperativeM :: ImperativeM a -> ImperativeS -> (Either ImperativeE a, ImperativeS) runImperativeM m s = flip runState s $ runEitherT m defaultImperativeS :: ImperativeS defaultImperativeS = ImperativeS { globals = [], patchables = [], mutables = [], showables = [], triggers = []} withMutable :: Identifier -> ImperativeM a -> ImperativeM a withMutable i m = do oldS <- get put $ oldS { mutables = i : mutables oldS } result <- m newS <- get case mutables newS of (_:xs) -> put (newS { mutables = xs }) [] -> left () return result addGlobal :: Identifier -> K3 Type -> IsBuiltIn -> ImperativeM () addGlobal i t b = modify $ \s -> s { globals = (i, (t, b)) : globals s } addTrigger :: Identifier -> K3 Type -> ImperativeM () addTrigger i t = modify $ \s -> s { triggers = (i, t) : triggers s } addPatchable :: Identifier -> K3 Type -> Bool -> ImperativeM () addPatchable i t setFlag = modify $ \s -> s { patchables = (i, (t, setFlag)) : patchables s } -- | Add a new showable variable addShowable :: Identifier -> K3 Type -> ImperativeM () addShowable i t = modify $ \s -> s { showables = (i,t) : showables s } isCachedMutable :: Identifier -> ImperativeM Bool isCachedMutable i = elem i . mutables <$> get isFunction :: K3 Type -> Bool isFunction (tag -> TFunction) = True isFunction (tag -> TForall _) = True isFunction (tag -> TSource) = True isFunction (tag -> TSink) = True isFunction _ = False declaration :: K3 Declaration -> ImperativeM (K3 Declaration) declaration (Node t@(DGlobal i y Nothing :@: as) cs) = do let isF = isFunction y let isP = isJust $ as @~ (\case { DProperty (dPropertyV -> ("Pinned", Nothing)) -> True; _ -> False }) addGlobal i y isF unless isF (addPatchable i y False >> unless isP (addShowable i y)) Node t <$> mapM declaration cs declaration (Node (DGlobal i t (Just e) :@: as) cs) = do addGlobal i t False (if tag t == TSink then addTrigger i (head $ children t) else return ()) let isP = isJust $ as @~ (\case { DProperty (dPropertyV -> ("Pinned", Nothing)) -> True; _ -> False }) unless (isFunction t || isTid i t) (addPatchable i t True >> unless isP (addShowable i t)) me' <- expression e cs' <- mapM declaration cs return $ Node (DGlobal i t (Just me') :@: as) cs' where isTid n (tag -> TInt) | drop (length n - 4) n == "_tid" = True isTid _ _ = False declaration (Node (DTrigger i t e :@: as) cs) = do addGlobal i t False addTrigger i t ne' <- expression e cs' <- mapM declaration cs return $ Node (DTrigger i t ne' :@: as) cs' declaration t@(tag -> DDataAnnotation _ _ amds) = do forM_ amds $ \case Lifted Provides j u _ _ -> addGlobal j u False _ -> return () let (Node t' cs') = t in Node t' <$> mapM declaration cs' declaration (Node t cs) = Node t <$> mapM declaration cs expression :: K3 Expression -> ImperativeM (K3 Expression) expression e@(tag &&& children -> (ELetIn _, [v@(tag -> EVariable i), _])) = do let isMutable = isJust $ v @~ (\case {EMutable -> True; _ -> False}) let modifier = if isMutable then withMutable i else id let (Node t cs) = e in modifier $ Node t <$> mapM expression cs expression e@(tag -> EVariable i) = do b <- isCachedMutable i return $ if b then e @+ EMutable else e expression (Node t cs) = Node t <$> mapM expression cs
null
https://raw.githubusercontent.com/DaMSL/K3/51749157844e76ae79dba619116fc5ad9d685643/src/Language/K3/Codegen/Imperative.hs
haskell
imperative embedding. Stringification to a target language must be done subsequently. * Transformation Types * Transformation Actions * Tree Forms | Add a new showable variable
# LANGUAGE LambdaCase # # LANGUAGE ViewPatterns # # LANGUAGE TypeFamilies # | Imperative code generation for K3 . This module provides functions which perform the first stage tree transformation to the module Language.K3.Codegen.Imperative ( ImperativeE, ImperativeS(..), ImperativeM, runImperativeM, defaultImperativeS, declaration, expression ) where import Control.Arrow ((&&&)) import Control.Monad.State import Control.Monad.Trans.Either import Data.Maybe import Data.Functor import Data.Tree import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Declaration import Language.K3.Core.Expression import Language.K3.Core.Type type ImperativeE = () type SetFlag = Bool type IsBuiltIn = Bool data ImperativeS = ImperativeS { globals :: [(Identifier, (K3 Type, IsBuiltIn))], triggers :: [(Identifier, K3 Type)], patchables :: [(Identifier, (K3 Type, SetFlag))], showables :: [(Identifier, K3 Type)], mutables :: [Identifier] } type ImperativeM a = EitherT ImperativeE (State ImperativeS) a runImperativeM :: ImperativeM a -> ImperativeS -> (Either ImperativeE a, ImperativeS) runImperativeM m s = flip runState s $ runEitherT m defaultImperativeS :: ImperativeS defaultImperativeS = ImperativeS { globals = [], patchables = [], mutables = [], showables = [], triggers = []} withMutable :: Identifier -> ImperativeM a -> ImperativeM a withMutable i m = do oldS <- get put $ oldS { mutables = i : mutables oldS } result <- m newS <- get case mutables newS of (_:xs) -> put (newS { mutables = xs }) [] -> left () return result addGlobal :: Identifier -> K3 Type -> IsBuiltIn -> ImperativeM () addGlobal i t b = modify $ \s -> s { globals = (i, (t, b)) : globals s } addTrigger :: Identifier -> K3 Type -> ImperativeM () addTrigger i t = modify $ \s -> s { triggers = (i, t) : triggers s } addPatchable :: Identifier -> K3 Type -> Bool -> ImperativeM () addPatchable i t setFlag = modify $ \s -> s { patchables = (i, (t, setFlag)) : patchables s } addShowable :: Identifier -> K3 Type -> ImperativeM () addShowable i t = modify $ \s -> s { showables = (i,t) : showables s } isCachedMutable :: Identifier -> ImperativeM Bool isCachedMutable i = elem i . mutables <$> get isFunction :: K3 Type -> Bool isFunction (tag -> TFunction) = True isFunction (tag -> TForall _) = True isFunction (tag -> TSource) = True isFunction (tag -> TSink) = True isFunction _ = False declaration :: K3 Declaration -> ImperativeM (K3 Declaration) declaration (Node t@(DGlobal i y Nothing :@: as) cs) = do let isF = isFunction y let isP = isJust $ as @~ (\case { DProperty (dPropertyV -> ("Pinned", Nothing)) -> True; _ -> False }) addGlobal i y isF unless isF (addPatchable i y False >> unless isP (addShowable i y)) Node t <$> mapM declaration cs declaration (Node (DGlobal i t (Just e) :@: as) cs) = do addGlobal i t False (if tag t == TSink then addTrigger i (head $ children t) else return ()) let isP = isJust $ as @~ (\case { DProperty (dPropertyV -> ("Pinned", Nothing)) -> True; _ -> False }) unless (isFunction t || isTid i t) (addPatchable i t True >> unless isP (addShowable i t)) me' <- expression e cs' <- mapM declaration cs return $ Node (DGlobal i t (Just me') :@: as) cs' where isTid n (tag -> TInt) | drop (length n - 4) n == "_tid" = True isTid _ _ = False declaration (Node (DTrigger i t e :@: as) cs) = do addGlobal i t False addTrigger i t ne' <- expression e cs' <- mapM declaration cs return $ Node (DTrigger i t ne' :@: as) cs' declaration t@(tag -> DDataAnnotation _ _ amds) = do forM_ amds $ \case Lifted Provides j u _ _ -> addGlobal j u False _ -> return () let (Node t' cs') = t in Node t' <$> mapM declaration cs' declaration (Node t cs) = Node t <$> mapM declaration cs expression :: K3 Expression -> ImperativeM (K3 Expression) expression e@(tag &&& children -> (ELetIn _, [v@(tag -> EVariable i), _])) = do let isMutable = isJust $ v @~ (\case {EMutable -> True; _ -> False}) let modifier = if isMutable then withMutable i else id let (Node t cs) = e in modifier $ Node t <$> mapM expression cs expression e@(tag -> EVariable i) = do b <- isCachedMutable i return $ if b then e @+ EMutable else e expression (Node t cs) = Node t <$> mapM expression cs
404f5d3dbf240549115f48e3994a5175343169b6a631c6e373f3819210c87c74
solbloch/stumpwm-configs
battery.lisp
(in-package :stumpwm) (defun battery-list () (remove-if-not #'(lambda (supply) (search "BAT" (namestring supply))) (uiop:subdirectories "/sys/class/power_supply/"))) (defun battery-alist (battery) (with-open-file (stream (str:concat (namestring battery) "uevent")) (loop for line = (read-line stream nil) while line collect (let ((line-split (str:split #\= line))) (cons (car line-split) (cadr line-split)))))) (defun cdr-assoc-string (item alist) (cdr (assoc item alist :test #'string=))) (defun battery-string () (when (battery-list) (flet ((f (str obj) (parse-integer (cdr-assoc-string str obj)))) (multiple-value-bind (energy power capacity status-list perc-list) (loop for bat in (mapcar #'battery-alist (battery-list)) summing (f "POWER_SUPPLY_ENERGY_NOW" bat) into energy summing (f "POWER_SUPPLY_POWER_NOW" bat) into power summing (f "POWER_SUPPLY_ENERGY_FULL" bat) into capacity collecting (cdr-assoc-string "POWER_SUPPLY_STATUS" bat) into status-list collecting (mapcar #'(lambda (string) (cdr-assoc-string string bat)) '("POWER_SUPPLY_NAME" "POWER_SUPPLY_CAPACITY")) into perc-list finally (return (values energy power capacity status-list perc-list))) (let ((time-remaining (if (= power 0) 0 (if (find "Charging" status-list :test #'string=) (/ (- capacity energy) power) (/ energy power))))) (format nil "~a:~2,'0D - ~{~{~a~^:~}%~^ ~}" (floor time-remaining) (round (* 60 (rem time-remaining 1.0))) perc-list))))))
null
https://raw.githubusercontent.com/solbloch/stumpwm-configs/687118d5202e3e3c8317ba1ba8404034a5bca667/battery.lisp
lisp
(in-package :stumpwm) (defun battery-list () (remove-if-not #'(lambda (supply) (search "BAT" (namestring supply))) (uiop:subdirectories "/sys/class/power_supply/"))) (defun battery-alist (battery) (with-open-file (stream (str:concat (namestring battery) "uevent")) (loop for line = (read-line stream nil) while line collect (let ((line-split (str:split #\= line))) (cons (car line-split) (cadr line-split)))))) (defun cdr-assoc-string (item alist) (cdr (assoc item alist :test #'string=))) (defun battery-string () (when (battery-list) (flet ((f (str obj) (parse-integer (cdr-assoc-string str obj)))) (multiple-value-bind (energy power capacity status-list perc-list) (loop for bat in (mapcar #'battery-alist (battery-list)) summing (f "POWER_SUPPLY_ENERGY_NOW" bat) into energy summing (f "POWER_SUPPLY_POWER_NOW" bat) into power summing (f "POWER_SUPPLY_ENERGY_FULL" bat) into capacity collecting (cdr-assoc-string "POWER_SUPPLY_STATUS" bat) into status-list collecting (mapcar #'(lambda (string) (cdr-assoc-string string bat)) '("POWER_SUPPLY_NAME" "POWER_SUPPLY_CAPACITY")) into perc-list finally (return (values energy power capacity status-list perc-list))) (let ((time-remaining (if (= power 0) 0 (if (find "Charging" status-list :test #'string=) (/ (- capacity energy) power) (/ energy power))))) (format nil "~a:~2,'0D - ~{~{~a~^:~}%~^ ~}" (floor time-remaining) (round (* 60 (rem time-remaining 1.0))) perc-list))))))
df06eca719c531d84873a5e244975e79d25d5797ea9ace9fa336690866530f95
well-typed/lens-sop
Named.hs
module Generics.SOP.Lens.Named ( * total lens , abstracted over target LensName , NamedLens(..) , get , modify , set -- * Generic construction , gnamedLenses ) where import Generics.SOP import Generics.SOP.Lens (GLens) import qualified Generics.SOP.Lens as GLens {------------------------------------------------------------------------------- Wrapper around Data.Label -------------------------------------------------------------------------------} type LensName = String -- | Total abstract lens data NamedLens a ctxt = forall b. ctxt b => NamedLens { unNamedLens :: GLens I I a b } instance Show (NamedLens a ctxt) where show _ = "<<NamedLens>" get :: NamedLens a ctxt -> (forall b. ctxt b => b -> c) -> a -> c get (NamedLens l) k = k . unI . GLens.get l modify :: NamedLens a ctxt -> (forall b. ctxt b => b -> b) -> a -> a modify (NamedLens l) f = unI . GLens.modify l (I . f) set :: NamedLens a ctxt -> (forall b. ctxt b => b) -> a -> a set (NamedLens l) b = unI . GLens.set l b ------------------------------------------------------------------------------ Construct named lenses ------------------------------------------------------------------------------ Construct named lenses -------------------------------------------------------------------------------} | Construct named lenses for a record type -- -- NOTE: This will throw a runtime error for non-record types gnamedLenses :: forall a ctxt xs. (HasDatatypeInfo a, Code a ~ '[xs], All ctxt xs) => (DatatypeName -> ConstructorName -> LensName) -> [(String, NamedLens a ctxt)] gnamedLenses mkName = case sList :: SList (Code a) of SCons -> zip (fieldNames mkName (datatypeInfo pa)) (hcollapse $ hcliftA pc (K . NamedLens) totalLenses) where totalLenses :: NP (GLens I I a) xs totalLenses = GLens.glenses pa :: Proxy a pa = Proxy pc :: Proxy ctxt pc = Proxy fieldNames :: (DatatypeName -> FieldName -> LensName) -> DatatypeInfo '[xs] -> [String] fieldNames mkName d = fieldNames' (mkName (datatypeName d)) (hd (constructorInfo d)) fieldNames' :: (FieldName -> LensName) -> ConstructorInfo xs -> [String] fieldNames' _ (Constructor _) = error "not a record type" fieldNames' _ (Infix _ _ _) = error "not a record type" fieldNames' mkName (Record _ fs) = hcollapse $ hliftA aux fs where aux :: FieldInfo a -> K String a aux (FieldInfo n) = K (mkName n)
null
https://raw.githubusercontent.com/well-typed/lens-sop/7ec872f5e7ece02b366c5deae21327153bdc7360/src/Generics/SOP/Lens/Named.hs
haskell
* Generic construction ------------------------------------------------------------------------------ Wrapper around Data.Label ------------------------------------------------------------------------------ | Total abstract lens ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} NOTE: This will throw a runtime error for non-record types
module Generics.SOP.Lens.Named ( * total lens , abstracted over target LensName , NamedLens(..) , get , modify , set , gnamedLenses ) where import Generics.SOP import Generics.SOP.Lens (GLens) import qualified Generics.SOP.Lens as GLens type LensName = String data NamedLens a ctxt = forall b. ctxt b => NamedLens { unNamedLens :: GLens I I a b } instance Show (NamedLens a ctxt) where show _ = "<<NamedLens>" get :: NamedLens a ctxt -> (forall b. ctxt b => b -> c) -> a -> c get (NamedLens l) k = k . unI . GLens.get l modify :: NamedLens a ctxt -> (forall b. ctxt b => b -> b) -> a -> a modify (NamedLens l) f = unI . GLens.modify l (I . f) set :: NamedLens a ctxt -> (forall b. ctxt b => b) -> a -> a set (NamedLens l) b = unI . GLens.set l b Construct named lenses Construct named lenses | Construct named lenses for a record type gnamedLenses :: forall a ctxt xs. (HasDatatypeInfo a, Code a ~ '[xs], All ctxt xs) => (DatatypeName -> ConstructorName -> LensName) -> [(String, NamedLens a ctxt)] gnamedLenses mkName = case sList :: SList (Code a) of SCons -> zip (fieldNames mkName (datatypeInfo pa)) (hcollapse $ hcliftA pc (K . NamedLens) totalLenses) where totalLenses :: NP (GLens I I a) xs totalLenses = GLens.glenses pa :: Proxy a pa = Proxy pc :: Proxy ctxt pc = Proxy fieldNames :: (DatatypeName -> FieldName -> LensName) -> DatatypeInfo '[xs] -> [String] fieldNames mkName d = fieldNames' (mkName (datatypeName d)) (hd (constructorInfo d)) fieldNames' :: (FieldName -> LensName) -> ConstructorInfo xs -> [String] fieldNames' _ (Constructor _) = error "not a record type" fieldNames' _ (Infix _ _ _) = error "not a record type" fieldNames' mkName (Record _ fs) = hcollapse $ hliftA aux fs where aux :: FieldInfo a -> K String a aux (FieldInfo n) = K (mkName n)
ba859bcae2d241f6999ccfe64c34a649349b598de360258bc9e923395bf3a6a6
MinaProtocol/mina
ledger_hash.ml
open Core_kernel open Mina_base_import open Snark_params open Snarky_backendless open Tick open Let_syntax let merge_var ~height h1 h2 = Random_oracle.Checked.hash ~init:(Hash_prefix.merkle_tree height) [| h1; h2 |] module Merkle_tree = Snarky_backendless.Merkle_tree.Checked (Tick) (struct type value = Field.t type var = Field.Var.t let typ = Field.typ let merge ~height h1 h2 = Tick.make_checked (fun () -> merge_var ~height h1 h2) let assert_equal h1 h2 = Field.Checked.Assert.equal h1 h2 let if_ = Field.Checked.if_ end) (struct include Account let hash = Checked.digest end) include Ledger_hash0 (* End boilerplate *) let merge ~height (h1 : t) (h2 : t) = Random_oracle.hash ~init:(Hash_prefix.merkle_tree height) [| (h1 :> field); (h2 :> field) |] |> of_hash let empty_hash = of_hash Outside_hash_image.t let%bench "Ledger_hash.merge ~height:1 empty_hash empty_hash" = merge ~height:1 empty_hash empty_hash let of_digest = Fn.compose Fn.id of_hash type path = Random_oracle.Digest.t list type _ Request.t += | Get_path : Account.Index.t -> path Request.t | Get_element : Account.Index.t -> (Account.t * path) Request.t | Set : Account.Index.t * Account.t -> unit Request.t | Find_index : Account_id.t -> Account.Index.t Request.t let reraise_merkle_requests (With { request; respond }) = match request with | Merkle_tree.Get_path addr -> respond (Delegate (Get_path addr)) | Merkle_tree.Set (addr, account) -> respond (Delegate (Set (addr, account))) | Merkle_tree.Get_element addr -> respond (Delegate (Get_element addr)) | _ -> unhandled let get ~depth t addr = handle (fun () -> Merkle_tree.get_req ~depth (var_to_hash_packed t) addr) reraise_merkle_requests (* [modify_account t aid ~filter ~f] implements the following spec: - finds an account [account] in [t] for [aid] at path [addr] where [filter account] holds. note that the account is not guaranteed to have identifier [aid]; it might be a new account created to satisfy this request. - returns a root [t'] of a tree of depth [depth] which is [t] but with the account [f account] at path [addr]. *) let%snarkydef_ modify_account ~depth t aid ~(filter : Account.var -> 'a Checked.t) ~f = let%bind addr = request_witness (Account.Index.Unpacked.typ ~ledger_depth:depth) As_prover.(map (read Account_id.typ aid) ~f:(fun s -> Find_index s)) in handle (fun () -> Merkle_tree.modify_req ~depth (var_to_hash_packed t) addr ~f:(fun account -> let%bind x = filter account in f x account ) ) reraise_merkle_requests >>| var_of_hash_packed (* [modify_account_send t aid ~f] implements the following spec: - finds an account [account] in [t] at path [addr] whose account id is [aid] OR it is a fee transfer and is an empty account - returns a root [t'] of a tree of depth [depth] which is [t] but with the account [f account] at path [addr]. *) let%snarkydef_ modify_account_send ~depth t aid ~is_writeable ~f = modify_account ~depth t aid ~filter:(fun account -> [%with_label_ "modify_account_send filter"] (fun () -> let%bind account_already_there = Account_id.Checked.equal (Account.identifier_of_var account) aid in let%bind account_not_there = Public_key.Compressed.Checked.equal account.public_key Public_key.Compressed.(var_of_t empty) in let%bind not_there_but_writeable = Boolean.(account_not_there && is_writeable) in let%bind () = [%with_label_ "account is either present or empty and writeable"] (fun () -> Boolean.Assert.any [ account_already_there; not_there_but_writeable ] ) in return not_there_but_writeable ) ) ~f:(fun is_empty_and_writeable x -> f ~is_empty_and_writeable x) (* [modify_account_recv t aid ~f] implements the following spec: - finds an account [account] in [t] at path [addr] whose account id is [aid] OR which is an empty account - returns a root [t'] of a tree of depth [depth] which is [t] but with the account [f account] at path [addr]. *) let%snarkydef_ modify_account_recv ~depth t aid ~f = modify_account ~depth t aid ~filter:(fun account -> [%with_label_ "modify_account_recv filter"] (fun () -> let%bind account_already_there = Account_id.Checked.equal (Account.identifier_of_var account) aid in let%bind account_not_there = Public_key.Compressed.Checked.equal account.public_key Public_key.Compressed.(var_of_t empty) in let%bind () = [%with_label_ "account is either present or empty"] (fun () -> Boolean.Assert.any [ account_already_there; account_not_there ] ) in return account_not_there ) ) ~f:(fun is_empty_and_writeable x -> f ~is_empty_and_writeable x)
null
https://raw.githubusercontent.com/MinaProtocol/mina/774ee06e0aa9472f9eb8f71f346c13b7e283af4b/src/lib/mina_base/ledger_hash.ml
ocaml
End boilerplate [modify_account t aid ~filter ~f] implements the following spec: - finds an account [account] in [t] for [aid] at path [addr] where [filter account] holds. note that the account is not guaranteed to have identifier [aid]; it might be a new account created to satisfy this request. - returns a root [t'] of a tree of depth [depth] which is [t] but with the account [f account] at path [addr]. [modify_account_send t aid ~f] implements the following spec: - finds an account [account] in [t] at path [addr] whose account id is [aid] OR it is a fee transfer and is an empty account - returns a root [t'] of a tree of depth [depth] which is [t] but with the account [f account] at path [addr]. [modify_account_recv t aid ~f] implements the following spec: - finds an account [account] in [t] at path [addr] whose account id is [aid] OR which is an empty account - returns a root [t'] of a tree of depth [depth] which is [t] but with the account [f account] at path [addr].
open Core_kernel open Mina_base_import open Snark_params open Snarky_backendless open Tick open Let_syntax let merge_var ~height h1 h2 = Random_oracle.Checked.hash ~init:(Hash_prefix.merkle_tree height) [| h1; h2 |] module Merkle_tree = Snarky_backendless.Merkle_tree.Checked (Tick) (struct type value = Field.t type var = Field.Var.t let typ = Field.typ let merge ~height h1 h2 = Tick.make_checked (fun () -> merge_var ~height h1 h2) let assert_equal h1 h2 = Field.Checked.Assert.equal h1 h2 let if_ = Field.Checked.if_ end) (struct include Account let hash = Checked.digest end) include Ledger_hash0 let merge ~height (h1 : t) (h2 : t) = Random_oracle.hash ~init:(Hash_prefix.merkle_tree height) [| (h1 :> field); (h2 :> field) |] |> of_hash let empty_hash = of_hash Outside_hash_image.t let%bench "Ledger_hash.merge ~height:1 empty_hash empty_hash" = merge ~height:1 empty_hash empty_hash let of_digest = Fn.compose Fn.id of_hash type path = Random_oracle.Digest.t list type _ Request.t += | Get_path : Account.Index.t -> path Request.t | Get_element : Account.Index.t -> (Account.t * path) Request.t | Set : Account.Index.t * Account.t -> unit Request.t | Find_index : Account_id.t -> Account.Index.t Request.t let reraise_merkle_requests (With { request; respond }) = match request with | Merkle_tree.Get_path addr -> respond (Delegate (Get_path addr)) | Merkle_tree.Set (addr, account) -> respond (Delegate (Set (addr, account))) | Merkle_tree.Get_element addr -> respond (Delegate (Get_element addr)) | _ -> unhandled let get ~depth t addr = handle (fun () -> Merkle_tree.get_req ~depth (var_to_hash_packed t) addr) reraise_merkle_requests let%snarkydef_ modify_account ~depth t aid ~(filter : Account.var -> 'a Checked.t) ~f = let%bind addr = request_witness (Account.Index.Unpacked.typ ~ledger_depth:depth) As_prover.(map (read Account_id.typ aid) ~f:(fun s -> Find_index s)) in handle (fun () -> Merkle_tree.modify_req ~depth (var_to_hash_packed t) addr ~f:(fun account -> let%bind x = filter account in f x account ) ) reraise_merkle_requests >>| var_of_hash_packed let%snarkydef_ modify_account_send ~depth t aid ~is_writeable ~f = modify_account ~depth t aid ~filter:(fun account -> [%with_label_ "modify_account_send filter"] (fun () -> let%bind account_already_there = Account_id.Checked.equal (Account.identifier_of_var account) aid in let%bind account_not_there = Public_key.Compressed.Checked.equal account.public_key Public_key.Compressed.(var_of_t empty) in let%bind not_there_but_writeable = Boolean.(account_not_there && is_writeable) in let%bind () = [%with_label_ "account is either present or empty and writeable"] (fun () -> Boolean.Assert.any [ account_already_there; not_there_but_writeable ] ) in return not_there_but_writeable ) ) ~f:(fun is_empty_and_writeable x -> f ~is_empty_and_writeable x) let%snarkydef_ modify_account_recv ~depth t aid ~f = modify_account ~depth t aid ~filter:(fun account -> [%with_label_ "modify_account_recv filter"] (fun () -> let%bind account_already_there = Account_id.Checked.equal (Account.identifier_of_var account) aid in let%bind account_not_there = Public_key.Compressed.Checked.equal account.public_key Public_key.Compressed.(var_of_t empty) in let%bind () = [%with_label_ "account is either present or empty"] (fun () -> Boolean.Assert.any [ account_already_there; account_not_there ] ) in return account_not_there ) ) ~f:(fun is_empty_and_writeable x -> f ~is_empty_and_writeable x)
862e38ddb989f6f8fff9d4b1b18e717c2cdd7e27bdec333d93607de39f62ae20
BoeingX/haskell-programming-from-first-principles
ConstantExerciseSpec.hs
module Applicative.ApplicativeInUse.ConstantExerciseSpec where import Data.Monoid (Sum (..)) import Test.Hspec import Applicative.ApplicativeInUse.ConstantExercise spec :: Spec spec = do describe "Test Constant implementation" $ do it "Constant (Sum 1) <*> Constant (Sum 2) should equal Constant (Sum 3)" $ do Constant (Sum 1) <*> Constant (Sum 2) `shouldBe` Constant (Sum 3) it "pure 1 :: Constant String Int should be Constant \"\"" $ do (pure 1 :: Constant String Int) `shouldBe` Constant ""
null
https://raw.githubusercontent.com/BoeingX/haskell-programming-from-first-principles/ffb637f536597f552a4e4567fee848ed27f3ba74/test/Applicative/ApplicativeInUse/ConstantExerciseSpec.hs
haskell
module Applicative.ApplicativeInUse.ConstantExerciseSpec where import Data.Monoid (Sum (..)) import Test.Hspec import Applicative.ApplicativeInUse.ConstantExercise spec :: Spec spec = do describe "Test Constant implementation" $ do it "Constant (Sum 1) <*> Constant (Sum 2) should equal Constant (Sum 3)" $ do Constant (Sum 1) <*> Constant (Sum 2) `shouldBe` Constant (Sum 3) it "pure 1 :: Constant String Int should be Constant \"\"" $ do (pure 1 :: Constant String Int) `shouldBe` Constant ""
12d56b8e92eb6772fe01bf567e8ab1d567686a3f6ca5d18728fb94b47ada7044
ezrakilty/narc
Pretty.hs
module Database.Narc.SQL.Pretty where import Database.Narc.Pretty import Database.Narc.SQL import Database.Narc.Util (mapstrcat) instance Pretty Query where pretty (Select{rslt=flds, tabs=tabs, cond=cond}) = "select " ++ mapstrcat ", " (\(alias, expr) -> pretty expr ++ " as " ++ alias) flds ++ (if null tabs then "" else " from " ++ mapstrcat ", " (\(name, alias, _ty) -> serialize name ++ " as " ++ alias) tabs) ++ " where " ++ pretty_conds cond pretty (Union a b) = pretty a ++ " union all " ++ pretty b pretty_conds :: Pretty a => [a] -> String pretty_conds [] = "true" pretty_conds cond = mapstrcat " and " pretty cond instance Pretty QBase where pretty (Lit lit) = pretty lit pretty (Field a b) = a ++ "." ++ b pretty (Not b) = "not " ++ pretty b pretty (Op lhs op rhs) = pretty lhs ++ pretty op ++ pretty rhs pretty (If c t f) = "if " ++ pretty c ++ " then " ++ pretty t ++ " else " ++ pretty f pretty (Exists q) = "exists (" ++ pretty q ++ ")" instance Pretty DataItem where pretty (Num n) = show n FIXME use SQL - style quoting . pretty (Bool True) = "true" pretty (Bool False) = "false" Pretty - printing for Op , common to both AST and SQL languages . instance Pretty Op where pretty Plus = " + " pretty Minus = " - " pretty Times = " * " pretty Divide = " / " pretty Eq = " = " pretty NonEq = " <> " pretty Less = " < " pretty Greater= " > " pretty LessOrEq = " <= " pretty GreaterOrEq= " >= "
null
https://raw.githubusercontent.com/ezrakilty/narc/76310e6ac528fe038d8bdd4aa78fa8c555501fad/Database/Narc/SQL/Pretty.hs
haskell
module Database.Narc.SQL.Pretty where import Database.Narc.Pretty import Database.Narc.SQL import Database.Narc.Util (mapstrcat) instance Pretty Query where pretty (Select{rslt=flds, tabs=tabs, cond=cond}) = "select " ++ mapstrcat ", " (\(alias, expr) -> pretty expr ++ " as " ++ alias) flds ++ (if null tabs then "" else " from " ++ mapstrcat ", " (\(name, alias, _ty) -> serialize name ++ " as " ++ alias) tabs) ++ " where " ++ pretty_conds cond pretty (Union a b) = pretty a ++ " union all " ++ pretty b pretty_conds :: Pretty a => [a] -> String pretty_conds [] = "true" pretty_conds cond = mapstrcat " and " pretty cond instance Pretty QBase where pretty (Lit lit) = pretty lit pretty (Field a b) = a ++ "." ++ b pretty (Not b) = "not " ++ pretty b pretty (Op lhs op rhs) = pretty lhs ++ pretty op ++ pretty rhs pretty (If c t f) = "if " ++ pretty c ++ " then " ++ pretty t ++ " else " ++ pretty f pretty (Exists q) = "exists (" ++ pretty q ++ ")" instance Pretty DataItem where pretty (Num n) = show n FIXME use SQL - style quoting . pretty (Bool True) = "true" pretty (Bool False) = "false" Pretty - printing for Op , common to both AST and SQL languages . instance Pretty Op where pretty Plus = " + " pretty Minus = " - " pretty Times = " * " pretty Divide = " / " pretty Eq = " = " pretty NonEq = " <> " pretty Less = " < " pretty Greater= " > " pretty LessOrEq = " <= " pretty GreaterOrEq= " >= "
18b8075e17c3335530b9cf0ceffc376c4c2529655ed4f2f6864df00a4e559a8d
replikativ/hitchhiker-tree
testing.cljc
(ns hitchhiker.tree.backend.testing (:require [hitchhiker.tree.utils.async :as ha] [hitchhiker.tree.node :as n] [hitchhiker.tree.node.testing :as tn] [hitchhiker.tree :as tree] [hitchhiker.tree.backend :as b])) (defrecord TestingBackend [] b/IBackend (-new-session [_] (atom {:writes 0})) (-anchor-root [_ root] root) (-write-node [_ node session] (swap! session update-in [:writes] inc) (ha/go-try (tn/testing-addr (n/-last-key node) (assoc node :*last-key-cache (tree/cache))))) (-delete-addr [_ addr session]))
null
https://raw.githubusercontent.com/replikativ/hitchhiker-tree/9279fb75a581717e7b52a9d3f4c5e2e537458372/test/hitchhiker/tree/backend/testing.cljc
clojure
(ns hitchhiker.tree.backend.testing (:require [hitchhiker.tree.utils.async :as ha] [hitchhiker.tree.node :as n] [hitchhiker.tree.node.testing :as tn] [hitchhiker.tree :as tree] [hitchhiker.tree.backend :as b])) (defrecord TestingBackend [] b/IBackend (-new-session [_] (atom {:writes 0})) (-anchor-root [_ root] root) (-write-node [_ node session] (swap! session update-in [:writes] inc) (ha/go-try (tn/testing-addr (n/-last-key node) (assoc node :*last-key-cache (tree/cache))))) (-delete-addr [_ addr session]))
b3b6753591928b83d1dbc0215787e20127d8130805af9428eb107cdfa3b8e492
hidaris/thinking-dumps
07-friends_and_relations.rkt
#lang racket/base (define atom? (lambda (a) (and (not (null? a)) (not (pair? a))))) (define eqan? (lambda (a1 a2) (cond ((and (number? a1) (number? a2)) (= a1 a2)) ((or (number? a1) (number? a2)) #f) (else (eq? a1 a2))))) (define eqlist? (lambda (l1 l2) (cond ((and (null? l1) (null? l2)) #t) ((or (null? l1) (null? l2)) #f) (else (and (equal? (car l1) (car l2)) (eqlist? (cdr l1) (cdr l2))))))) (define equal? (lambda (s1 s2) (cond ((and (atom? s1) (atom? s2)) (eqan? s1 s2)) ((or (atom? s1) (atom? s2)) #f) (else (eqlist? s1 s2))))) (define member? (lambda (a lat) (cond ((null? lat) #f) ((equal? a (car lat)) #t) (else (member? a (cdr lat)))))) (define my-set? (lambda (lat) (cond ((null? lat) #t) ((member? (car lat) (cdr lat)) #f) (else (my-set? (cdr lat)))))) (my-set? '(apple 3 pear 4 9 apple 3 4)) (define makeset (lambda (lat) (cond ((null? lat) '()) ((member? (car lat) (cdr lat)) (makeset (cdr lat))) (else (cons (car lat) (makeset (cdr lat))))))) (makeset '(apple peach pear peach plum apple lemon peach)) (define multirember (lambda (a l) (cond ((null? l) (quote ())) ((equal? a (car l)) (multirember a (cdr l))) (else (cons (car l) (multirember a (cdr l))))))) (multirember 'a '(b a c a)) (define makeset2 (lambda (lat) (cond ((null? lat) (quote ())) (else (cons (car lat) (makeset2 (multirember (car lat) (cdr lat)))))))) (makeset2 '(apple peach pear peach plum apple lemon peach)) (define my-subset? (lambda (s1 s2) (cond ((null? s1) #t) (else (and (member? (car s1) s2) (my-subset? (cdr s1) s2)))))) (my-subset? '(1 1 2) '(1 2)) (define eqset? (lambda (s1 s2) (and (my-subset? s1 s2) (my-subset? s2 s1)))) (eqset? '((a) 3) '((a) 3)) (define intersect? (lambda (set1 set2) (cond ((null? set1) #f) (else (or (member? (car set1) set2) (intersect? (cdr set1) set2)))))) (define intersect (lambda (set1 set2) (cond ((null? set1) '()) ((member? (car set1) set2) (cons (car set1) (intersect (cdr set1) set2))) (else (intersect (cdr set1) set2))))) (intersect '(a b e c) '(b a d c)) (define union (lambda (set1 set2) (cond ((null? set1) set2) ((member? (car set1) set2) (union (cdr set1) set2)) (else (cons (car set1) (union (cdr set1) set2)))))) (define xxx (lambda (set1 set2) (cond ((null? set1) '()) ((member? (car set1) set2) (xxx (cdr set1) set2)) (else (cons (car set1) (xxx (cdr set1) set2)))))) (define intersectall (lambda (l-set) (cond ((null? (cdr l-set)) (car l-set)) (else (intersect (car l-set) (intersectall (cdr l-set))))))) (intersectall '((a b) (b d) (e b))) (define a-pair? (lambda (x) (cond ((atom? x) #f) ((null? x) #f) ((null? (cdr x)) #f) ((null? (cdr (cdr x))) #t) (else #f)))) (a-pair? '((a (b)) (b c d))) (define (first p) (car p)) (define (second p) (car (cdr p))) (define (build s1 s2) (cons s1 (cons s2 '()))) (define third (lambda (p) (car (cdr (cdr p))))) (define firsts (lambda (l) (cond ((null? l) '()) (else (cons (car (car l)) (firsts (cdr l))))))) (define fun? (lambda (rel) (my-set? (firsts rel)))) (define revpair (lambda (pair) (build (second pair) (first pair)))) (define revrel (lambda (rel) (cond ((null? rel) '()) (else (cons (revpair (car rel)) (revrel (cdr rel))))))) (define seconds (lambda (l) (cond ((null? l) '()) (else (cons (cdr (car l)) (seconds (cdr l))))))) (seconds '((a b) (d e) (j f))) (define fullfun? (lambda (fun) (my-set? (seconds fun)))) (fullfun? '((grape raisin) (plum prune) (stewed prune))) (define one-to-one? (lambda (fun) (fun? (revrel fun))))
null
https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/the-little-series/the-little-schemer/07-friends_and_relations.rkt
racket
#lang racket/base (define atom? (lambda (a) (and (not (null? a)) (not (pair? a))))) (define eqan? (lambda (a1 a2) (cond ((and (number? a1) (number? a2)) (= a1 a2)) ((or (number? a1) (number? a2)) #f) (else (eq? a1 a2))))) (define eqlist? (lambda (l1 l2) (cond ((and (null? l1) (null? l2)) #t) ((or (null? l1) (null? l2)) #f) (else (and (equal? (car l1) (car l2)) (eqlist? (cdr l1) (cdr l2))))))) (define equal? (lambda (s1 s2) (cond ((and (atom? s1) (atom? s2)) (eqan? s1 s2)) ((or (atom? s1) (atom? s2)) #f) (else (eqlist? s1 s2))))) (define member? (lambda (a lat) (cond ((null? lat) #f) ((equal? a (car lat)) #t) (else (member? a (cdr lat)))))) (define my-set? (lambda (lat) (cond ((null? lat) #t) ((member? (car lat) (cdr lat)) #f) (else (my-set? (cdr lat)))))) (my-set? '(apple 3 pear 4 9 apple 3 4)) (define makeset (lambda (lat) (cond ((null? lat) '()) ((member? (car lat) (cdr lat)) (makeset (cdr lat))) (else (cons (car lat) (makeset (cdr lat))))))) (makeset '(apple peach pear peach plum apple lemon peach)) (define multirember (lambda (a l) (cond ((null? l) (quote ())) ((equal? a (car l)) (multirember a (cdr l))) (else (cons (car l) (multirember a (cdr l))))))) (multirember 'a '(b a c a)) (define makeset2 (lambda (lat) (cond ((null? lat) (quote ())) (else (cons (car lat) (makeset2 (multirember (car lat) (cdr lat)))))))) (makeset2 '(apple peach pear peach plum apple lemon peach)) (define my-subset? (lambda (s1 s2) (cond ((null? s1) #t) (else (and (member? (car s1) s2) (my-subset? (cdr s1) s2)))))) (my-subset? '(1 1 2) '(1 2)) (define eqset? (lambda (s1 s2) (and (my-subset? s1 s2) (my-subset? s2 s1)))) (eqset? '((a) 3) '((a) 3)) (define intersect? (lambda (set1 set2) (cond ((null? set1) #f) (else (or (member? (car set1) set2) (intersect? (cdr set1) set2)))))) (define intersect (lambda (set1 set2) (cond ((null? set1) '()) ((member? (car set1) set2) (cons (car set1) (intersect (cdr set1) set2))) (else (intersect (cdr set1) set2))))) (intersect '(a b e c) '(b a d c)) (define union (lambda (set1 set2) (cond ((null? set1) set2) ((member? (car set1) set2) (union (cdr set1) set2)) (else (cons (car set1) (union (cdr set1) set2)))))) (define xxx (lambda (set1 set2) (cond ((null? set1) '()) ((member? (car set1) set2) (xxx (cdr set1) set2)) (else (cons (car set1) (xxx (cdr set1) set2)))))) (define intersectall (lambda (l-set) (cond ((null? (cdr l-set)) (car l-set)) (else (intersect (car l-set) (intersectall (cdr l-set))))))) (intersectall '((a b) (b d) (e b))) (define a-pair? (lambda (x) (cond ((atom? x) #f) ((null? x) #f) ((null? (cdr x)) #f) ((null? (cdr (cdr x))) #t) (else #f)))) (a-pair? '((a (b)) (b c d))) (define (first p) (car p)) (define (second p) (car (cdr p))) (define (build s1 s2) (cons s1 (cons s2 '()))) (define third (lambda (p) (car (cdr (cdr p))))) (define firsts (lambda (l) (cond ((null? l) '()) (else (cons (car (car l)) (firsts (cdr l))))))) (define fun? (lambda (rel) (my-set? (firsts rel)))) (define revpair (lambda (pair) (build (second pair) (first pair)))) (define revrel (lambda (rel) (cond ((null? rel) '()) (else (cons (revpair (car rel)) (revrel (cdr rel))))))) (define seconds (lambda (l) (cond ((null? l) '()) (else (cons (cdr (car l)) (seconds (cdr l))))))) (seconds '((a b) (d e) (j f))) (define fullfun? (lambda (fun) (my-set? (seconds fun)))) (fullfun? '((grape raisin) (plum prune) (stewed prune))) (define one-to-one? (lambda (fun) (fun? (revrel fun))))
cf39524495c383313fc05d1eeddfbfe1d93610e21a6b17a07d6a28f538afc333
pva701/Haskell-Practices
Task3.hs
# LANGUAGE LambdaCase # module Task3 ( main3 ) where import Prelude import Control.Monad (forM_, liftM2) import Data.Array.IO (IOArray, getElems, newListArray, readArray, writeArray) import Data.List (intercalate) import Data.IORef (newIORef, readIORef, writeIORef) selectionSort :: [Int] -> IO [Int] selectionSort xs = do let l = length xs a <- newListArray (0, l - 1) xs :: IO (IOArray Int Int) forM_ [0..l-1] $ \i -> do mn <- newIORef i forM_ [i+1..l-1] $ \j -> do mnidx <- readIORef mn liftM2 (>) (readArray a mnidx) (readArray a j) >>= \case True -> writeIORef mn j False -> pure () mnIndex <- readIORef mn tmp <- readArray a mnIndex writeArray a mnIndex =<< readArray a i writeArray a i tmp getElems a main3 :: IO () main3 = map read . words <$> getLine >>= selectionSort >>= putStrLn . intercalate " " . map show
null
https://raw.githubusercontent.com/pva701/Haskell-Practices/71b9241cf92c757fa793fd0c0c053af77e68205d/lecture6-practice/src/Task3.hs
haskell
# LANGUAGE LambdaCase # module Task3 ( main3 ) where import Prelude import Control.Monad (forM_, liftM2) import Data.Array.IO (IOArray, getElems, newListArray, readArray, writeArray) import Data.List (intercalate) import Data.IORef (newIORef, readIORef, writeIORef) selectionSort :: [Int] -> IO [Int] selectionSort xs = do let l = length xs a <- newListArray (0, l - 1) xs :: IO (IOArray Int Int) forM_ [0..l-1] $ \i -> do mn <- newIORef i forM_ [i+1..l-1] $ \j -> do mnidx <- readIORef mn liftM2 (>) (readArray a mnidx) (readArray a j) >>= \case True -> writeIORef mn j False -> pure () mnIndex <- readIORef mn tmp <- readArray a mnIndex writeArray a mnIndex =<< readArray a i writeArray a i tmp getElems a main3 :: IO () main3 = map read . words <$> getLine >>= selectionSort >>= putStrLn . intercalate " " . map show
c4be4064412d3384327ed61f8d5e8555fd4333e8c91bb9b56ea468c1014953f1
komadori/HsQML
MayGen.hs
module Graphics.QML.Test.MayGen where import Test.QuickCheck.Gen import Control.Applicative import Data.Maybe I wanted so badly to write a Monad instance for MayGen , but actually -- Applicative captures the legal operations perfectly. newtype MayGen a = MayGen {mayGen :: Maybe (Gen a)} instance Functor MayGen where fmap f (MayGen v) = MayGen $ (fmap . fmap) f v instance Applicative MayGen where pure = MayGen . Just . return (MayGen mf) <*> (MayGen v) = MayGen $ liftA2 (<*>) mf v noGen :: MayGen a noGen = MayGen Nothing fromGen :: Gen a -> MayGen a fromGen = MayGen . Just mayElements :: [a] -> MayGen a mayElements [] = noGen mayElements xs = fromGen $ elements xs mayOneof :: [MayGen a] -> MayGen a mayOneof xs = case mapMaybe mayGen xs of [] -> noGen xs' -> fromGen $ oneof xs'
null
https://raw.githubusercontent.com/komadori/HsQML/f57cffe4e3595bdf743bdbe6f44bf45a4001d35f/test/Graphics/QML/Test/MayGen.hs
haskell
Applicative captures the legal operations perfectly.
module Graphics.QML.Test.MayGen where import Test.QuickCheck.Gen import Control.Applicative import Data.Maybe I wanted so badly to write a Monad instance for MayGen , but actually newtype MayGen a = MayGen {mayGen :: Maybe (Gen a)} instance Functor MayGen where fmap f (MayGen v) = MayGen $ (fmap . fmap) f v instance Applicative MayGen where pure = MayGen . Just . return (MayGen mf) <*> (MayGen v) = MayGen $ liftA2 (<*>) mf v noGen :: MayGen a noGen = MayGen Nothing fromGen :: Gen a -> MayGen a fromGen = MayGen . Just mayElements :: [a] -> MayGen a mayElements [] = noGen mayElements xs = fromGen $ elements xs mayOneof :: [MayGen a] -> MayGen a mayOneof xs = case mapMaybe mayGen xs of [] -> noGen xs' -> fromGen $ oneof xs'
c7b56422e75b8857b44f029c1df1a309130c37a87d18338e6705145645fdf81d
WorksHub/client
fragments.cljc
(ns wh.graphql.fragments (#?(:clj :require :cljs :require-macros) [wh.graphql-macros :refer [deffragment]])) ;; Jobs (deffragment jobCardFields :Job [:id :slug :title :tagline [:tags :fragment/tagFields] :published :userScore :roleType :sponsorshipOffered :remote :companyId :lastModified [:company [:name :slug :logo :size]] [:location [:city :state :country :countryCode]] [:remuneration [:competitive :currency :timePeriod :min :max :equity]]]) (deffragment jobFields :Job [:id :slug :title :companyId :tagline :descriptionHtml [:tags :fragment/tagFields] :roleType :manager :locationDescription :remote :sponsorshipOffered :applied :published :lastModified [:company :fragment/companyCardFields] [:location [:street :city :country :countryCode :state :postCode :longitude :latitude]] [:remuneration [:competitive :currency :timePeriod :min :max :equity]] [:remoteInfo [:regionRestrictions [:timezoneRestrictions [:timezoneName [:timezoneDelta [:plus :minus]]]]]]]) ;; Company (deffragment companyCardFields :Company [:id :slug :name :logo :size :description :profileEnabled :totalPublishedJobCount :totalPublishedIssueCount [:tags :fragment/tagFields] [:locations [:city :country :countryCode :region :subRegion :state]]]) ;; Issues (deffragment issueFields :issue [:id :pr_count :url :number :body_html :title :viewer_contributed :published :status :level :created_at [:compensation [:amount :currency]] [:contributors [:id :name [:other_urls [:url]] [:github_info [:login]]]] [:repo [:owner :name :description :primary_language [:community [:readme_url :contributing_url]]]] [:company [:id :name :logo]] [:author [:login :name]] [:labels [:name]]]) (deffragment issueListFields :issue [:id :url :number :title :pr_count :level :status :published :created_at [:compensation [:amount :currency]] [:contributors [:id]] [:labels [:name]] [:company [:id :name :logo :slug]] [:repo [:name :owner :primary_language]]]) (deffragment tagFields :tag [:id :slug :type :subtype :label :weight]) ;; Articles/Blogs (deffragment blogCardFields :Blog [:id :title :feature :author :formattedDate :readingTime :creatorId :upvoteCount :published [:authorInfo [:id :imageUrl :name]] [:tags :fragment/tagFields]]) (deffragment likedJobId :Job [:id]) (deffragment likedBlogId :Blog [:id])
null
https://raw.githubusercontent.com/WorksHub/client/428afde8ac6dc20ae00972d5fc79880a8c4a92e1/common/src/wh/graphql/fragments.cljc
clojure
Jobs Company Issues Articles/Blogs
(ns wh.graphql.fragments (#?(:clj :require :cljs :require-macros) [wh.graphql-macros :refer [deffragment]])) (deffragment jobCardFields :Job [:id :slug :title :tagline [:tags :fragment/tagFields] :published :userScore :roleType :sponsorshipOffered :remote :companyId :lastModified [:company [:name :slug :logo :size]] [:location [:city :state :country :countryCode]] [:remuneration [:competitive :currency :timePeriod :min :max :equity]]]) (deffragment jobFields :Job [:id :slug :title :companyId :tagline :descriptionHtml [:tags :fragment/tagFields] :roleType :manager :locationDescription :remote :sponsorshipOffered :applied :published :lastModified [:company :fragment/companyCardFields] [:location [:street :city :country :countryCode :state :postCode :longitude :latitude]] [:remuneration [:competitive :currency :timePeriod :min :max :equity]] [:remoteInfo [:regionRestrictions [:timezoneRestrictions [:timezoneName [:timezoneDelta [:plus :minus]]]]]]]) (deffragment companyCardFields :Company [:id :slug :name :logo :size :description :profileEnabled :totalPublishedJobCount :totalPublishedIssueCount [:tags :fragment/tagFields] [:locations [:city :country :countryCode :region :subRegion :state]]]) (deffragment issueFields :issue [:id :pr_count :url :number :body_html :title :viewer_contributed :published :status :level :created_at [:compensation [:amount :currency]] [:contributors [:id :name [:other_urls [:url]] [:github_info [:login]]]] [:repo [:owner :name :description :primary_language [:community [:readme_url :contributing_url]]]] [:company [:id :name :logo]] [:author [:login :name]] [:labels [:name]]]) (deffragment issueListFields :issue [:id :url :number :title :pr_count :level :status :published :created_at [:compensation [:amount :currency]] [:contributors [:id]] [:labels [:name]] [:company [:id :name :logo :slug]] [:repo [:name :owner :primary_language]]]) (deffragment tagFields :tag [:id :slug :type :subtype :label :weight]) (deffragment blogCardFields :Blog [:id :title :feature :author :formattedDate :readingTime :creatorId :upvoteCount :published [:authorInfo [:id :imageUrl :name]] [:tags :fragment/tagFields]]) (deffragment likedJobId :Job [:id]) (deffragment likedBlogId :Blog [:id])
53da7657c377aef88f0aeea8cf3a8b39515921bae8174480a6beed40a5b23121
mirage/encore
encore.ml
module Lavoisier = Lavoisier module Either = Either module Bij = Bij let always x _ = x type 'a t = | Product : 'a t * 'b t -> ('a * 'b) t | Map : ('a, 'b) Bij.t * 'a t -> 'b t | Either : 'a t * 'a t -> 'a t | Fix : ('a t -> 'a t) -> 'a t | Symbol : char t | IgnR : 'a t * unit t -> 'a t | IgnL : unit t * 'b t -> 'b t | Fail : string -> 'a t | Payload : (char -> bool) * int * n -> string t | Const : string -> string t | Commit : unit t | Pure : ('a -> 'a -> bool) * 'a -> 'a t | Peek : 'a t * 'b t -> ('a, 'b) Either.t t | Unsafe : ('a, 'k) v -> 'a t and n = Infinite | Fixed of int and ('a, 'k) v = | Angstrom : 'a Angstrom.t -> ('a, angstrom) v | Lavoisier : 'a Lavoisier.t -> ('a, lavoisier) v and angstrom = | and lavoisier = | let take_while_with_max ~max p = let open Angstrom in scan_string 0 (fun n chr -> if p chr && n < max then Some (succ n) else None) let string_for_all f x = let rec go a i = if i < String.length x then go (f x.[i] && a) (succ i) else a in go true 0 let rec to_angstrom : type a. a t -> a Angstrom.t = function | Product (a, b) -> let pa = to_angstrom a in let pb = to_angstrom b in Angstrom.( pa >>= fun a -> pb >>= fun b -> return (a, b)) | Map (bij, x) -> ( let px = to_angstrom x in Angstrom.( px >>= fun x -> try return (bij.Bij.to_ x) with Bij.Bijection -> fail "bijection")) | Either (a, b) -> let pa = to_angstrom a in let pb = to_angstrom b in Angstrom.(pa <|> pb) | Fix f -> Angstrom.fix @@ fun m -> to_angstrom (f (Unsafe (Angstrom m))) | Const str -> Angstrom.string str | Unsafe (Angstrom p) -> p | Unsafe (Lavoisier _) -> assert false | Symbol -> Angstrom.any_char | Pure (_compare, v) -> Angstrom.return v | Payload (p, 0, Infinite) -> Angstrom.take_while p | IgnL (p, q) -> let p = to_angstrom p in let q = to_angstrom q in Angstrom.(p *> q) | IgnR (p, q) -> let p = to_angstrom p in let q = to_angstrom q in Angstrom.(p <* q) | Payload (p, 1, Infinite) -> Angstrom.take_while1 p | Payload (p, a, Fixed b) -> Angstrom.( take a >>= fun v -> if string_for_all p v then take_while_with_max ~max:(b - a) p >>= fun w -> return (v ^ w) else fail "Invalid payload") | Payload (p, a, Infinite) -> Angstrom.( take a >>= fun v -> if string_for_all p v then take_while p >>= fun w -> return (v ^ w) else fail "Invalid payload") | Peek (a, b) -> ( let pa = to_angstrom a in let pb = to_angstrom b in Angstrom.( peek_char >>= function | Some _ -> pa >>| fun x -> Either.L x | None -> pb >>| fun y -> Either.R y)) | Fail err -> Angstrom.fail err | Commit -> Angstrom.commit let rec to_lavoisier : type a. a t -> a Lavoisier.t = function | Product (a, b) -> let da = to_lavoisier a in let db = to_lavoisier b in Lavoisier.product da db | Map (bij, x) -> let dx = to_lavoisier x in Lavoisier.map dx bij.of_ | Commit -> Lavoisier.commit | Either (a, b) -> let da = to_lavoisier a in let db = to_lavoisier b in Lavoisier.choose da db | Symbol -> Lavoisier.char | Payload (p, 0, Infinite) -> Lavoisier.put_while0 p | Payload (p, 1, Infinite) -> Lavoisier.put_while1 p | Payload (p, a, Fixed b) -> Lavoisier.range ~a ~b p | Payload (p, a, Infinite) -> Lavoisier.at_least_put p a | Const str -> Lavoisier.string str | IgnL (p, q) -> let p = to_lavoisier p in let q = to_lavoisier q in Lavoisier.(p *> q) | IgnR (p, q) -> let p = to_lavoisier p in let q = to_lavoisier q in Lavoisier.(p <* q) | Pure (compare, v) -> Lavoisier.pure ~compare v | Peek (a, b) -> let da = to_lavoisier a in let db = to_lavoisier b in Lavoisier.peek da db | Fail err -> Lavoisier.fail err | Unsafe (Lavoisier d) -> d | Unsafe (Angstrom _) -> assert false | Fix f -> Lavoisier.fix @@ fun m -> to_lavoisier (f (Unsafe (Lavoisier m))) module Syntax = struct let fail err = Fail err let map f x = Map (f, x) let product p q = Product (p, q) let ( <$> ) f x = map f x let ( <|> ) p q = Either (p, q) let ( *> ) p q = IgnL (p, q) let ( <* ) p q = IgnR (p, q) let ( <*> ) p q = Product (p, q) let fix f = Fix f let const str = Const str let any = Symbol let while1 p = Payload (p, 1, Infinite) let while0 p = Payload (p, 0, Infinite) let nil = Pure ((fun l0 l1 -> match (l0, l1) with [], [] -> true | _ -> false), []) let none = Pure ( (fun o0 o1 -> match (o0, o1) with None, None -> true | _ -> false), None ) let commit = Commit let rep1 p = fix @@ fun m -> Bij.cons <$> (p <*> (m <|> nil)) let rep0 p = rep1 p <|> nil let sep_by1 ~sep p = Bij.cons <$> (p <*> rep0 (sep *> p)) let sep_by0 ~sep p = sep_by1 ~sep p <|> nil let pure ~compare v = Pure (compare, v) let peek a b = Peek (a, b) let fixed n = Payload (always true, n, Fixed n) let identity x = x let rec fold_right ~k f l a = match l with | [] -> k a | x :: r -> (fold_right [@tailcall]) ~k:(fun r -> k (f x r)) f r a let choice l = fold_right ~k:identity ( <|> ) l (fail "choice") let sequence l = let fold x r = Bij.cons <$> (x <*> r) in fold_right ~k:identity fold l nil let count n t = let rec make a = function 0 -> a | n -> make (t :: a) (pred n) in sequence (make [] n) let option t = Bij.some <$> t <|> none let is_lower = function 'a' .. 'z' -> true | _ -> false let is_upper = function 'A' .. 'Z' -> true | _ -> false let is_digit = function '0' .. '9' -> true | _ -> false let is_alpha = function 'a' .. 'z' -> true | 'A' .. 'Z' -> true | _ -> false let lower = Bij.element is_lower <$> any let upper = Bij.element is_upper <$> any let alpha = Bij.element is_alpha <$> any let digit = Bij.element is_digit <$> any end
null
https://raw.githubusercontent.com/mirage/encore/55d8377c9fd3cb8f71cfe16d90aede0487a214cc/lib/encore.ml
ocaml
module Lavoisier = Lavoisier module Either = Either module Bij = Bij let always x _ = x type 'a t = | Product : 'a t * 'b t -> ('a * 'b) t | Map : ('a, 'b) Bij.t * 'a t -> 'b t | Either : 'a t * 'a t -> 'a t | Fix : ('a t -> 'a t) -> 'a t | Symbol : char t | IgnR : 'a t * unit t -> 'a t | IgnL : unit t * 'b t -> 'b t | Fail : string -> 'a t | Payload : (char -> bool) * int * n -> string t | Const : string -> string t | Commit : unit t | Pure : ('a -> 'a -> bool) * 'a -> 'a t | Peek : 'a t * 'b t -> ('a, 'b) Either.t t | Unsafe : ('a, 'k) v -> 'a t and n = Infinite | Fixed of int and ('a, 'k) v = | Angstrom : 'a Angstrom.t -> ('a, angstrom) v | Lavoisier : 'a Lavoisier.t -> ('a, lavoisier) v and angstrom = | and lavoisier = | let take_while_with_max ~max p = let open Angstrom in scan_string 0 (fun n chr -> if p chr && n < max then Some (succ n) else None) let string_for_all f x = let rec go a i = if i < String.length x then go (f x.[i] && a) (succ i) else a in go true 0 let rec to_angstrom : type a. a t -> a Angstrom.t = function | Product (a, b) -> let pa = to_angstrom a in let pb = to_angstrom b in Angstrom.( pa >>= fun a -> pb >>= fun b -> return (a, b)) | Map (bij, x) -> ( let px = to_angstrom x in Angstrom.( px >>= fun x -> try return (bij.Bij.to_ x) with Bij.Bijection -> fail "bijection")) | Either (a, b) -> let pa = to_angstrom a in let pb = to_angstrom b in Angstrom.(pa <|> pb) | Fix f -> Angstrom.fix @@ fun m -> to_angstrom (f (Unsafe (Angstrom m))) | Const str -> Angstrom.string str | Unsafe (Angstrom p) -> p | Unsafe (Lavoisier _) -> assert false | Symbol -> Angstrom.any_char | Pure (_compare, v) -> Angstrom.return v | Payload (p, 0, Infinite) -> Angstrom.take_while p | IgnL (p, q) -> let p = to_angstrom p in let q = to_angstrom q in Angstrom.(p *> q) | IgnR (p, q) -> let p = to_angstrom p in let q = to_angstrom q in Angstrom.(p <* q) | Payload (p, 1, Infinite) -> Angstrom.take_while1 p | Payload (p, a, Fixed b) -> Angstrom.( take a >>= fun v -> if string_for_all p v then take_while_with_max ~max:(b - a) p >>= fun w -> return (v ^ w) else fail "Invalid payload") | Payload (p, a, Infinite) -> Angstrom.( take a >>= fun v -> if string_for_all p v then take_while p >>= fun w -> return (v ^ w) else fail "Invalid payload") | Peek (a, b) -> ( let pa = to_angstrom a in let pb = to_angstrom b in Angstrom.( peek_char >>= function | Some _ -> pa >>| fun x -> Either.L x | None -> pb >>| fun y -> Either.R y)) | Fail err -> Angstrom.fail err | Commit -> Angstrom.commit let rec to_lavoisier : type a. a t -> a Lavoisier.t = function | Product (a, b) -> let da = to_lavoisier a in let db = to_lavoisier b in Lavoisier.product da db | Map (bij, x) -> let dx = to_lavoisier x in Lavoisier.map dx bij.of_ | Commit -> Lavoisier.commit | Either (a, b) -> let da = to_lavoisier a in let db = to_lavoisier b in Lavoisier.choose da db | Symbol -> Lavoisier.char | Payload (p, 0, Infinite) -> Lavoisier.put_while0 p | Payload (p, 1, Infinite) -> Lavoisier.put_while1 p | Payload (p, a, Fixed b) -> Lavoisier.range ~a ~b p | Payload (p, a, Infinite) -> Lavoisier.at_least_put p a | Const str -> Lavoisier.string str | IgnL (p, q) -> let p = to_lavoisier p in let q = to_lavoisier q in Lavoisier.(p *> q) | IgnR (p, q) -> let p = to_lavoisier p in let q = to_lavoisier q in Lavoisier.(p <* q) | Pure (compare, v) -> Lavoisier.pure ~compare v | Peek (a, b) -> let da = to_lavoisier a in let db = to_lavoisier b in Lavoisier.peek da db | Fail err -> Lavoisier.fail err | Unsafe (Lavoisier d) -> d | Unsafe (Angstrom _) -> assert false | Fix f -> Lavoisier.fix @@ fun m -> to_lavoisier (f (Unsafe (Lavoisier m))) module Syntax = struct let fail err = Fail err let map f x = Map (f, x) let product p q = Product (p, q) let ( <$> ) f x = map f x let ( <|> ) p q = Either (p, q) let ( *> ) p q = IgnL (p, q) let ( <* ) p q = IgnR (p, q) let ( <*> ) p q = Product (p, q) let fix f = Fix f let const str = Const str let any = Symbol let while1 p = Payload (p, 1, Infinite) let while0 p = Payload (p, 0, Infinite) let nil = Pure ((fun l0 l1 -> match (l0, l1) with [], [] -> true | _ -> false), []) let none = Pure ( (fun o0 o1 -> match (o0, o1) with None, None -> true | _ -> false), None ) let commit = Commit let rep1 p = fix @@ fun m -> Bij.cons <$> (p <*> (m <|> nil)) let rep0 p = rep1 p <|> nil let sep_by1 ~sep p = Bij.cons <$> (p <*> rep0 (sep *> p)) let sep_by0 ~sep p = sep_by1 ~sep p <|> nil let pure ~compare v = Pure (compare, v) let peek a b = Peek (a, b) let fixed n = Payload (always true, n, Fixed n) let identity x = x let rec fold_right ~k f l a = match l with | [] -> k a | x :: r -> (fold_right [@tailcall]) ~k:(fun r -> k (f x r)) f r a let choice l = fold_right ~k:identity ( <|> ) l (fail "choice") let sequence l = let fold x r = Bij.cons <$> (x <*> r) in fold_right ~k:identity fold l nil let count n t = let rec make a = function 0 -> a | n -> make (t :: a) (pred n) in sequence (make [] n) let option t = Bij.some <$> t <|> none let is_lower = function 'a' .. 'z' -> true | _ -> false let is_upper = function 'A' .. 'Z' -> true | _ -> false let is_digit = function '0' .. '9' -> true | _ -> false let is_alpha = function 'a' .. 'z' -> true | 'A' .. 'Z' -> true | _ -> false let lower = Bij.element is_lower <$> any let upper = Bij.element is_upper <$> any let alpha = Bij.element is_alpha <$> any let digit = Bij.element is_digit <$> any end
d88e1a67697d082555921cba3b77e89acf28b306e6876a8b37d180bc69d3b278
brabster/dynamodb-expressions
core_test.clj
(ns dynamodb-expression.core-test (:require [clojure.test :refer [deftest use-fixtures is are testing]] [dynamodb-expression.core :as dx] [dynamodb-expression.grammar-test :as g])) (defn strip-newlines [s] (clojure.string/replace s #"\n" "")) (use-fixtures :each (fn [f] (let [cnt (atom 0)] (with-redefs [gensym (fn [& [prefix]] (str prefix "G__" (swap! cnt inc)))] (f))))) (defn invalid-expr? [expected-expr generated-expr] (cond (not (g/parsed? (g/parse expected-expr))) ["Expected expression not valid : " expected-expr (g/parse expected-expr)] (not (g/parsed? (g/parse generated-expr))) ["Generated expression not valid : " generated-expr (g/parse generated-expr)] (not= expected-expr generated-expr) ["Unexpected expression" generated-expr "expected" expected-expr] :else false)) (deftest a-test (testing "A basic integration test" (let [x 4 id {:id "12"} {:keys [update-expression expression-attribute-names expression-attribute-values key] :as ex} (-> (dx/update-expr id) (dx/add "foo.bar" x) (dx/add :bar.baz 8) (dx/add "-goof-" 76) dx/expr) parsed-exp (g/parse update-expression)] (is (= id key)) (is (= {"#nfoo_bar_G__1" "foo.bar" "#nbar_baz_G__2" "bar.baz" "#n_goof__G__3" "-goof-"} expression-attribute-names)) (is (= {":vfoo_bar_G__1" 4 ":vbar_baz_G__2" 8 ":v_goof__G__3" 76} expression-attribute-values)) (is (not (invalid-expr? "ADD #nfoo_bar_G__1 :vfoo_bar_G__1, #nbar_baz_G__2 :vbar_baz_G__2, #n_goof__G__3 :v_goof__G__3" update-expression)))))) (deftest set-and-add-test (testing "Another basic integration test" (let [x 4 {:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/set :x x) (dx/add :8x (* x 8)) (dx/add :fish 12) dx/expr) parsed-exp (g/parse update-expression)] (is (= {"#nx_G__1" "x" "#n8x_G__2" "8x" "#nfish_G__3" "fish"} expression-attribute-names)) (is (= {":vx_G__1" 4 ":v8x_G__2" 32 ":vfish_G__3" 12} expression-attribute-values)) (is (not (invalid-expr? update-expression "SET #nx_G__1 = :vx_G__1 ADD #n8x_G__2 :v8x_G__2, #nfish_G__3 :vfish_G__3")))))) (deftest set-test (testing "Another basic integration test" (let [x 4 {:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/set :fish + 33) (dx/set :something :something-else "+" 4) dx/expr) parsed-exp (g/parse update-expression)] (is (= {"#nfish_G__1" "fish" "#nsomething_G__3" "something" "#nsomething_else_G__2" "something-else"} expression-attribute-names)) (is (= {":vsomething_G__3" 4 ":vfish_G__1" 33} expression-attribute-values)) (is (not (invalid-expr? (str "SET #nfish_G__1 = #nfish_G__1 + :vfish_G__1, " "#nsomething_G__3 = #nsomething_else_G__2 + :vsomething_G__3") update-expression)))))) (deftest grouping-test (testing "operations are grouped together" (let [x 4 {:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/set :fish + 33) (dx/remove :remove-me) (dx/set :something :something-else "+" 4) dx/expr) parsed-exp (g/parse update-expression)] (is (not (invalid-expr? (str "SET #nfish_G__1 = #nfish_G__1 + :vfish_G__1, " "#nsomething_G__4 = #nsomething_else_G__3 + :vsomething_G__4 " "REMOVE #nremove_me_G__2") update-expression)))))) (deftest delete-test (testing "Yet another basic integration test" (let [{:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/delete :something "value") dx/expr) parsed-exp (g/parse update-expression)] (is (= {"#nsomething_G__1" "something"} expression-attribute-names)) (is (= {":vsomething_G__1" "value"} expression-attribute-values)) (is (not (invalid-expr? "DELETE #nsomething_G__1 :vsomething_G__1" update-expression)))))) (deftest remove-test (testing "Yet another basic integration test" (let [{:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/remove :something) dx/expr) parsed-exp (g/parse update-expression)] (is (= {"#nsomething_G__1" "something"} expression-attribute-names)) (is (= nil expression-attribute-values)) (is (not (invalid-expr? "REMOVE #nsomething_G__1" update-expression)))))) (deftest path-test (testing "Yet another basic integration test" (let [{:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/add [:something :else] 12) (dx/add [:something :new] "munge") (dx/add [:fish 0] 21) dx/expr) parsed-exp (g/parse update-expression)] (testing "names" (is (= {"#nsomething_else_G__2" "else" "#nsomething_G__1" "something" "#nsomething_new_G__4" "new" "#nsomething_G__3" "something" "#nfish_0_G__5" "fish[0]"} expression-attribute-names))) (testing "values" (is (= {":vsomething_else_G__2" 12 ":vsomething_new_G__4" "munge" ":vfish_0_G__5" 21} expression-attribute-values))) (testing "expression" (is (not (invalid-expr? (str "ADD #nsomething_G__1.#nsomething_else_G__2 :vsomething_else_G__2, " "#nsomething_G__3.#nsomething_new_G__4 :vsomething_new_G__4, " "#nfish_0_G__5 :vfish_0_G__5") update-expression)))) (testing "set" (is (not (invalid-expr? "SET #nsomething_G__7.#nsomething_else_G__8 = #ndog_G__6 + :vsomething_else_G__8" (-> (dx/update-expr {:id "12"}) (dx/set [:something :else] :dog + 1) dx/expr :update-expression))))))))
null
https://raw.githubusercontent.com/brabster/dynamodb-expressions/8ca5ca758485fa272cec6e836e71279cd08b0104/test/dynamodb_expression/core_test.clj
clojure
(ns dynamodb-expression.core-test (:require [clojure.test :refer [deftest use-fixtures is are testing]] [dynamodb-expression.core :as dx] [dynamodb-expression.grammar-test :as g])) (defn strip-newlines [s] (clojure.string/replace s #"\n" "")) (use-fixtures :each (fn [f] (let [cnt (atom 0)] (with-redefs [gensym (fn [& [prefix]] (str prefix "G__" (swap! cnt inc)))] (f))))) (defn invalid-expr? [expected-expr generated-expr] (cond (not (g/parsed? (g/parse expected-expr))) ["Expected expression not valid : " expected-expr (g/parse expected-expr)] (not (g/parsed? (g/parse generated-expr))) ["Generated expression not valid : " generated-expr (g/parse generated-expr)] (not= expected-expr generated-expr) ["Unexpected expression" generated-expr "expected" expected-expr] :else false)) (deftest a-test (testing "A basic integration test" (let [x 4 id {:id "12"} {:keys [update-expression expression-attribute-names expression-attribute-values key] :as ex} (-> (dx/update-expr id) (dx/add "foo.bar" x) (dx/add :bar.baz 8) (dx/add "-goof-" 76) dx/expr) parsed-exp (g/parse update-expression)] (is (= id key)) (is (= {"#nfoo_bar_G__1" "foo.bar" "#nbar_baz_G__2" "bar.baz" "#n_goof__G__3" "-goof-"} expression-attribute-names)) (is (= {":vfoo_bar_G__1" 4 ":vbar_baz_G__2" 8 ":v_goof__G__3" 76} expression-attribute-values)) (is (not (invalid-expr? "ADD #nfoo_bar_G__1 :vfoo_bar_G__1, #nbar_baz_G__2 :vbar_baz_G__2, #n_goof__G__3 :v_goof__G__3" update-expression)))))) (deftest set-and-add-test (testing "Another basic integration test" (let [x 4 {:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/set :x x) (dx/add :8x (* x 8)) (dx/add :fish 12) dx/expr) parsed-exp (g/parse update-expression)] (is (= {"#nx_G__1" "x" "#n8x_G__2" "8x" "#nfish_G__3" "fish"} expression-attribute-names)) (is (= {":vx_G__1" 4 ":v8x_G__2" 32 ":vfish_G__3" 12} expression-attribute-values)) (is (not (invalid-expr? update-expression "SET #nx_G__1 = :vx_G__1 ADD #n8x_G__2 :v8x_G__2, #nfish_G__3 :vfish_G__3")))))) (deftest set-test (testing "Another basic integration test" (let [x 4 {:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/set :fish + 33) (dx/set :something :something-else "+" 4) dx/expr) parsed-exp (g/parse update-expression)] (is (= {"#nfish_G__1" "fish" "#nsomething_G__3" "something" "#nsomething_else_G__2" "something-else"} expression-attribute-names)) (is (= {":vsomething_G__3" 4 ":vfish_G__1" 33} expression-attribute-values)) (is (not (invalid-expr? (str "SET #nfish_G__1 = #nfish_G__1 + :vfish_G__1, " "#nsomething_G__3 = #nsomething_else_G__2 + :vsomething_G__3") update-expression)))))) (deftest grouping-test (testing "operations are grouped together" (let [x 4 {:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/set :fish + 33) (dx/remove :remove-me) (dx/set :something :something-else "+" 4) dx/expr) parsed-exp (g/parse update-expression)] (is (not (invalid-expr? (str "SET #nfish_G__1 = #nfish_G__1 + :vfish_G__1, " "#nsomething_G__4 = #nsomething_else_G__3 + :vsomething_G__4 " "REMOVE #nremove_me_G__2") update-expression)))))) (deftest delete-test (testing "Yet another basic integration test" (let [{:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/delete :something "value") dx/expr) parsed-exp (g/parse update-expression)] (is (= {"#nsomething_G__1" "something"} expression-attribute-names)) (is (= {":vsomething_G__1" "value"} expression-attribute-values)) (is (not (invalid-expr? "DELETE #nsomething_G__1 :vsomething_G__1" update-expression)))))) (deftest remove-test (testing "Yet another basic integration test" (let [{:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/remove :something) dx/expr) parsed-exp (g/parse update-expression)] (is (= {"#nsomething_G__1" "something"} expression-attribute-names)) (is (= nil expression-attribute-values)) (is (not (invalid-expr? "REMOVE #nsomething_G__1" update-expression)))))) (deftest path-test (testing "Yet another basic integration test" (let [{:keys [update-expression expression-attribute-names expression-attribute-values] :as ex} (-> (dx/update-expr {:id "12"}) (dx/add [:something :else] 12) (dx/add [:something :new] "munge") (dx/add [:fish 0] 21) dx/expr) parsed-exp (g/parse update-expression)] (testing "names" (is (= {"#nsomething_else_G__2" "else" "#nsomething_G__1" "something" "#nsomething_new_G__4" "new" "#nsomething_G__3" "something" "#nfish_0_G__5" "fish[0]"} expression-attribute-names))) (testing "values" (is (= {":vsomething_else_G__2" 12 ":vsomething_new_G__4" "munge" ":vfish_0_G__5" 21} expression-attribute-values))) (testing "expression" (is (not (invalid-expr? (str "ADD #nsomething_G__1.#nsomething_else_G__2 :vsomething_else_G__2, " "#nsomething_G__3.#nsomething_new_G__4 :vsomething_new_G__4, " "#nfish_0_G__5 :vfish_0_G__5") update-expression)))) (testing "set" (is (not (invalid-expr? "SET #nsomething_G__7.#nsomething_else_G__8 = #ndog_G__6 + :vsomething_else_G__8" (-> (dx/update-expr {:id "12"}) (dx/set [:something :else] :dog + 1) dx/expr :update-expression))))))))
082bfd271ccc741fab4523cc474452ddf33829e388198ce01264fbaa2075dc5e
morphismtech/squeal
Type.hs
| Module : Squeal . PostgreSQL.Expression Description : type expressions Copyright : ( c ) , 2019 Maintainer : Stability : experimental type expressions Module: Squeal.PostgreSQL.Expression Description: type expressions Copyright: (c) Eitan Chatav, 2019 Maintainer: Stability: experimental type expressions -} # LANGUAGE AllowAmbiguousTypes , , DeriveGeneric , DerivingStrategies , FlexibleContexts , FlexibleInstances , GADTs , , , MultiParamTypeClasses , OverloadedStrings , RankNTypes , ScopedTypeVariables , TypeApplications , TypeOperators , UndecidableInstances # AllowAmbiguousTypes , DataKinds , DeriveGeneric , DerivingStrategies , FlexibleContexts , FlexibleInstances , GADTs , GeneralizedNewtypeDeriving , KindSignatures , MultiParamTypeClasses , OverloadedStrings , RankNTypes , ScopedTypeVariables , TypeApplications , TypeOperators , UndecidableInstances #-} module Squeal.PostgreSQL.Expression.Type ( -- * Type Cast cast , astype , inferredtype -- * Type Expression , TypeExpression (..) , typerow , typeenum , typedef , typetable , typeview , bool , int2 , smallint , int4 , int , integer , int8 , bigint , numeric , float4 , real , float8 , doublePrecision , money , text , char , character , varchar , characterVarying , bytea , timestamp , timestampWithTimeZone , timestamptz , date , time , timeWithTimeZone , timetz , interval , uuid , inet , json , jsonb , vararray , fixarray , tsvector , tsquery , oid , int4range , int8range , numrange , tsrange , tstzrange , daterange , record -- * Column Type , ColumnTypeExpression (..) , nullable , notNullable , default_ , serial2 , smallserial , serial4 , serial , serial8 , bigserial -- * Type Inference , PGTyped (..) , pgtypeFrom , NullTyped (..) , nulltypeFrom , ColumnTyped (..) , columntypeFrom , FieldTyped (..) ) where import Control.DeepSeq import Data.ByteString import Data.String import GHC.TypeLits import qualified Data.ByteString as ByteString import qualified GHC.Generics as GHC import qualified Generics.SOP as SOP import Squeal.PostgreSQL.Type.Alias import Squeal.PostgreSQL.Expression import Squeal.PostgreSQL.Type.PG import Squeal.PostgreSQL.Render import Squeal.PostgreSQL.Type.Schema -- $setup -- >>> import Squeal.PostgreSQL -- When a `cast` is applied to an `Expression` of a known type, it -- represents a run-time type conversion. The cast will succeed only if a -- suitable type conversion operation has been defined. -- -- | >>> printSQL $ true & cast int4 ( TRUE : : int4 ) cast :: TypeExpression db ty1 -- ^ type to cast as -> Expression grp lat with db params from ty0 -- ^ value to convert -> Expression grp lat with db params from ty1 cast ty x = UnsafeExpression $ parenthesized $ renderSQL x <+> "::" <+> renderSQL ty -- | A safe version of `cast` which just matches a value with its type. -- > > > printSQL ( 1 & astype int ) ( ( 1 : : int4 ) : : int ) astype :: TypeExpression db ty -- ^ type to specify as -> Expression grp lat with db params from ty -- ^ value -> Expression grp lat with db params from ty astype = cast -- | `inferredtype` will add a type annotation to an `Expression` -- which can be useful for fixing the storage type of a value. -- > > > printSQL ( ) -- (TRUE :: bool) inferredtype :: NullTyped db ty => Expression lat common grp db params from ty -- ^ value -> Expression lat common grp db params from ty inferredtype = astype nulltype {----------------------------------------- type expressions -----------------------------------------} -- | `TypeExpression`s are used in `cast`s and -- `Squeal.PostgreSQL.Definition.createTable` commands. newtype TypeExpression (db :: SchemasType) (ty :: NullType) = UnsafeTypeExpression { renderTypeExpression :: ByteString } deriving stock (GHC.Generic,Show,Eq,Ord) deriving newtype (NFData) instance RenderSQL (TypeExpression db ty) where renderSQL = renderTypeExpression -- | The composite type corresponding to a relation can be expressed -- by its alias. A relation is either a composite type, a table or a view. -- It subsumes `typetable` and `typeview` and partly overlaps `typedef`. typerow :: ( relss ~ DbRelations db , Has sch relss rels , Has rel rels row ) => QualifiedAlias sch rel -- ^ type alias -> TypeExpression db (null ('PGcomposite row)) typerow = UnsafeTypeExpression . renderSQL -- | An enumerated type can be expressed by its alias. -- `typeenum` is subsumed by `typedef`. typeenum :: ( enumss ~ DbEnums db , Has sch enumss enums , Has enum enums labels ) => QualifiedAlias sch enum -- ^ type alias -> TypeExpression db (null ('PGenum labels)) typeenum = UnsafeTypeExpression . renderSQL | The enum or composite type in a ` Typedef ` can be expressed by its alias . typedef :: (Has sch db schema, Has td schema ('Typedef ty)) => QualifiedAlias sch td -- ^ type alias -> TypeExpression db (null ty) typedef = UnsafeTypeExpression . renderSQL -- | The composite type corresponding to a `Table` definition can be expressed -- by its alias. It is subsumed by `typerow` typetable :: (Has sch db schema, Has tab schema ('Table table)) => QualifiedAlias sch tab -- ^ table alias -> TypeExpression db (null ('PGcomposite (TableToRow table))) typetable = UnsafeTypeExpression . renderSQL -- | The composite type corresponding to a `View` definition can be expressed -- by its alias. It is subsumed by `typerow`. typeview :: (Has sch db schema, Has vw schema ('View view)) => QualifiedAlias sch vw -- ^ view alias -> TypeExpression db (null ('PGcomposite view)) typeview = UnsafeTypeExpression . renderSQL -- | logical Boolean (true/false) bool :: TypeExpression db (null 'PGbool) bool = UnsafeTypeExpression "bool" | signed two - byte integer int2, smallint :: TypeExpression db (null 'PGint2) int2 = UnsafeTypeExpression "int2" smallint = UnsafeTypeExpression "smallint" | signed four - byte integer int4, int, integer :: TypeExpression db (null 'PGint4) int4 = UnsafeTypeExpression "int4" int = UnsafeTypeExpression "int" integer = UnsafeTypeExpression "integer" | signed eight - byte integer int8, bigint :: TypeExpression db (null 'PGint8) int8 = UnsafeTypeExpression "int8" bigint = UnsafeTypeExpression "bigint" -- | arbitrary precision numeric type numeric :: TypeExpression db (null 'PGnumeric) numeric = UnsafeTypeExpression "numeric" | single precision floating - point number ( 4 bytes ) float4, real :: TypeExpression db (null 'PGfloat4) float4 = UnsafeTypeExpression "float4" real = UnsafeTypeExpression "real" | double precision floating - point number ( 8 bytes ) float8, doublePrecision :: TypeExpression db (null 'PGfloat8) float8 = UnsafeTypeExpression "float8" doublePrecision = UnsafeTypeExpression "double precision" -- | currency amount money :: TypeExpression schema (null 'PGmoney) money = UnsafeTypeExpression "money" -- | variable-length character string text :: TypeExpression db (null 'PGtext) text = UnsafeTypeExpression "text" -- | fixed-length character string char, character :: forall n db null. (KnownNat n, 1 <= n) => TypeExpression db (null ('PGchar n)) char = UnsafeTypeExpression $ "char(" <> renderNat @n <> ")" character = UnsafeTypeExpression $ "character(" <> renderNat @n <> ")" -- | variable-length character string varchar, characterVarying :: forall n db null. (KnownNat n, 1 <= n) => TypeExpression db (null ('PGvarchar n)) varchar = UnsafeTypeExpression $ "varchar(" <> renderNat @n <> ")" characterVarying = UnsafeTypeExpression $ "character varying(" <> renderNat @n <> ")" -- | binary data ("byte array") bytea :: TypeExpression db (null 'PGbytea) bytea = UnsafeTypeExpression "bytea" -- | date and time (no time zone) timestamp :: TypeExpression db (null 'PGtimestamp) timestamp = UnsafeTypeExpression "timestamp" -- | date and time, including time zone timestampWithTimeZone, timestamptz :: TypeExpression db (null 'PGtimestamptz) timestampWithTimeZone = UnsafeTypeExpression "timestamp with time zone" timestamptz = UnsafeTypeExpression "timestamptz" -- | calendar date (year, month, day) date :: TypeExpression db (null 'PGdate) date = UnsafeTypeExpression "date" -- | time of day (no time zone) time :: TypeExpression db (null 'PGtime) time = UnsafeTypeExpression "time" -- | time of day, including time zone timeWithTimeZone, timetz :: TypeExpression db (null 'PGtimetz) timeWithTimeZone = UnsafeTypeExpression "time with time zone" timetz = UnsafeTypeExpression "timetz" -- | time span interval :: TypeExpression db (null 'PGinterval) interval = UnsafeTypeExpression "interval" -- | universally unique identifier uuid :: TypeExpression db (null 'PGuuid) uuid = UnsafeTypeExpression "uuid" -- | IPv4 or IPv6 host address inet :: TypeExpression db (null 'PGinet) inet = UnsafeTypeExpression "inet" -- | textual JSON data json :: TypeExpression db (null 'PGjson) json = UnsafeTypeExpression "json" -- | binary JSON data, decomposed jsonb :: TypeExpression db (null 'PGjsonb) jsonb = UnsafeTypeExpression "jsonb" -- | variable length array vararray :: TypeExpression db pg -> TypeExpression db (null ('PGvararray pg)) vararray ty = UnsafeTypeExpression $ renderSQL ty <> "[]" -- | fixed length array -- -- >>> renderSQL (fixarray @'[2] json) -- "json[2]" fixarray :: forall dims db null pg. SOP.All KnownNat dims => TypeExpression db pg -> TypeExpression db (null ('PGfixarray dims pg)) fixarray ty = UnsafeTypeExpression $ renderSQL ty <> renderDims @dims where renderDims :: forall ns. SOP.All KnownNat ns => ByteString renderDims = ("[" <>) . (<> "]") . ByteString.intercalate "][" . SOP.hcollapse $ SOP.hcmap (SOP.Proxy @KnownNat) (SOP.K . fromString . show . natVal) (SOP.hpure SOP.Proxy :: SOP.NP SOP.Proxy ns) -- | text search query tsvector :: TypeExpression db (null 'PGtsvector) tsvector = UnsafeTypeExpression "tsvector" -- | text search document tsquery :: TypeExpression db (null 'PGtsquery) tsquery = UnsafeTypeExpression "tsquery" -- | Object identifiers (OIDs) are used internally by PostgreSQL -- as primary keys for various system tables. oid :: TypeExpression db (null 'PGoid) oid = UnsafeTypeExpression "oid" -- | Range of integer int4range :: TypeExpression db (null ('PGrange 'PGint4)) int4range = UnsafeTypeExpression "int4range" -- | Range of bigint int8range :: TypeExpression db (null ('PGrange 'PGint8)) int8range = UnsafeTypeExpression "int8range" -- | Range of numeric numrange :: TypeExpression db (null ('PGrange 'PGnumeric)) numrange = UnsafeTypeExpression "numrange" -- | Range of timestamp without time zone tsrange :: TypeExpression db (null ('PGrange 'PGtimestamp)) tsrange = UnsafeTypeExpression "tsrange" -- | Range of timestamp with time zone tstzrange :: TypeExpression db (null ('PGrange 'PGtimestamptz)) tstzrange = UnsafeTypeExpression "tstzrange" -- | Range of date daterange :: TypeExpression db (null ('PGrange 'PGdate)) daterange = UnsafeTypeExpression "daterange" -- | Anonymous composite record record :: TypeExpression db (null ('PGcomposite record)) record = UnsafeTypeExpression "record" -- | `pgtype` is a demoted version of a `PGType` class PGTyped db (ty :: PGType) where pgtype :: TypeExpression db (null ty) instance PGTyped db 'PGbool where pgtype = bool instance PGTyped db 'PGint2 where pgtype = int2 instance PGTyped db 'PGint4 where pgtype = int4 instance PGTyped db 'PGint8 where pgtype = int8 instance PGTyped db 'PGnumeric where pgtype = numeric instance PGTyped db 'PGfloat4 where pgtype = float4 instance PGTyped db 'PGfloat8 where pgtype = float8 instance PGTyped db 'PGmoney where pgtype = money instance PGTyped db 'PGtext where pgtype = text instance (KnownNat n, 1 <= n) => PGTyped db ('PGchar n) where pgtype = char @n instance (KnownNat n, 1 <= n) => PGTyped db ('PGvarchar n) where pgtype = varchar @n instance PGTyped db 'PGbytea where pgtype = bytea instance PGTyped db 'PGtimestamp where pgtype = timestamp instance PGTyped db 'PGtimestamptz where pgtype = timestampWithTimeZone instance PGTyped db 'PGdate where pgtype = date instance PGTyped db 'PGtime where pgtype = time instance PGTyped db 'PGtimetz where pgtype = timeWithTimeZone instance PGTyped db 'PGinterval where pgtype = interval instance PGTyped db 'PGuuid where pgtype = uuid instance PGTyped db 'PGinet where pgtype = inet instance PGTyped db 'PGjson where pgtype = json instance PGTyped db 'PGjsonb where pgtype = jsonb instance PGTyped db pg => PGTyped db ('PGvararray (null pg)) where pgtype = vararray (pgtype @db @pg) instance (SOP.All KnownNat dims, PGTyped db pg) => PGTyped db ('PGfixarray dims (null pg)) where pgtype = fixarray @dims (pgtype @db @pg) instance PGTyped db 'PGtsvector where pgtype = tsvector instance PGTyped db 'PGtsquery where pgtype = tsquery instance PGTyped db 'PGoid where pgtype = oid instance PGTyped db ('PGrange 'PGint4) where pgtype = int4range instance PGTyped db ('PGrange 'PGint8) where pgtype = int8range instance PGTyped db ('PGrange 'PGnumeric) where pgtype = numrange instance PGTyped db ('PGrange 'PGtimestamp) where pgtype = tsrange instance PGTyped db ('PGrange 'PGtimestamptz) where pgtype = tstzrange instance PGTyped db ('PGrange 'PGdate) where pgtype = daterange instance ( relss ~ DbRelations db , Has sch relss rels , Has rel rels row , FindQualified "no relation found with row:" relss row ~ '(sch,rel) ) => PGTyped db ('PGcomposite row) where pgtype = typerow (QualifiedAlias @sch @rel) instance ( enums ~ DbEnums db , FindQualified "no enum found with labels:" enums labels ~ '(sch,td) , Has sch db schema , Has td schema ('Typedef ('PGenum labels)) ) => PGTyped db ('PGenum labels) where pgtype = typedef (QualifiedAlias @sch @td) | Specify ` TypeExpression ` from a type . -- -- >>> printSQL $ pgtypeFrom @String -- text -- -- >>> printSQL $ pgtypeFrom @Double -- float8 pgtypeFrom :: forall hask db null. PGTyped db (PG hask) => TypeExpression db (null (PG hask)) pgtypeFrom = pgtype @db @(PG hask) | Lift ` PGTyped ` to a field class FieldTyped db ty where fieldtype :: Aliased (TypeExpression db) ty instance (KnownSymbol alias, NullTyped db ty) => FieldTyped db (alias ::: ty) where fieldtype = nulltype `As` Alias -- | `ColumnTypeExpression`s are used in -- `Squeal.PostgreSQL.Definition.createTable` commands. newtype ColumnTypeExpression (db :: SchemasType) (ty :: ColumnType) = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString } deriving stock (GHC.Generic,Show,Eq,Ord) deriving newtype (NFData) instance RenderSQL (ColumnTypeExpression db ty) where renderSQL = renderColumnTypeExpression -- | used in `Squeal.PostgreSQL.Definition.createTable` -- commands as a column constraint to note that -- @NULL@ may be present in a column nullable :: TypeExpression db (null ty) -- ^ type -> ColumnTypeExpression db ('NoDef :=> 'Null ty) nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL" -- | used in `Squeal.PostgreSQL.Definition.createTable` -- commands as a column constraint to ensure -- @NULL@ is not present in a column notNullable :: TypeExpression db (null ty) -- ^ type -> ColumnTypeExpression db ('NoDef :=> 'NotNull ty) notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL" -- | used in `Squeal.PostgreSQL.Definition.createTable` -- commands as a column constraint to give a default default_ :: Expression 'Ungrouped '[] '[] db '[] '[] ty -- ^ default value -> ColumnTypeExpression db ('NoDef :=> ty) -- ^ column type -> ColumnTypeExpression db ('Def :=> ty) default_ x ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "DEFAULT" <+> renderExpression x -- | not a true type, but merely a notational convenience for creating unique identifier columns with type ` PGint2 ` serial2, smallserial :: ColumnTypeExpression db ('Def :=> 'NotNull 'PGint2) serial2 = UnsafeColumnTypeExpression "serial2" smallserial = UnsafeColumnTypeExpression "smallserial" -- | not a true type, but merely a notational convenience for creating -- unique identifier columns with type `PGint4` serial4, serial :: ColumnTypeExpression db ('Def :=> 'NotNull 'PGint4) serial4 = UnsafeColumnTypeExpression "serial4" serial = UnsafeColumnTypeExpression "serial" -- | not a true type, but merely a notational convenience for creating -- unique identifier columns with type `PGint8` serial8, bigserial :: ColumnTypeExpression db ('Def :=> 'NotNull 'PGint8) serial8 = UnsafeColumnTypeExpression "serial8" bigserial = UnsafeColumnTypeExpression "bigserial" | Like but also accounts for null . class NullTyped db (ty :: NullType) where nulltype :: TypeExpression db ty instance PGTyped db ty => NullTyped db (null ty) where nulltype = pgtype @db @ty | Specify null ` TypeExpression ` from a type . -- -- >>> printSQL $ nulltypeFrom @(Maybe String) -- text -- -- >>> printSQL $ nulltypeFrom @Double -- float8 nulltypeFrom :: forall hask db. NullTyped db (NullPG hask) => TypeExpression db (NullPG hask) nulltypeFrom = nulltype @db @(NullPG hask) | Like but also accounts for null . class ColumnTyped db (column :: ColumnType) where columntype :: ColumnTypeExpression db column instance NullTyped db ('Null ty) => ColumnTyped db ('NoDef :=> 'Null ty) where columntype = nullable (nulltype @db @('Null ty)) instance NullTyped db ('NotNull ty) => ColumnTyped db ('NoDef :=> 'NotNull ty) where columntype = notNullable (nulltype @db @('NotNull ty)) | Specify ` ColumnTypeExpression ` from a type . -- > > > printSQL $ columntypeFrom @(Maybe String ) -- text NULL -- -- >>> printSQL $ columntypeFrom @Double -- float8 NOT NULL columntypeFrom :: forall hask db. (ColumnTyped db ('NoDef :=> NullPG hask)) => ColumnTypeExpression db ('NoDef :=> NullPG hask) columntypeFrom = columntype @db @('NoDef :=> NullPG hask)
null
https://raw.githubusercontent.com/morphismtech/squeal/599ebb9a0036ac7e5627be980a2a8de1a38ea4f0/squeal-postgresql/src/Squeal/PostgreSQL/Expression/Type.hs
haskell
* Type Cast * Type Expression * Column Type * Type Inference $setup >>> import Squeal.PostgreSQL When a `cast` is applied to an `Expression` of a known type, it represents a run-time type conversion. The cast will succeed only if a suitable type conversion operation has been defined. | >>> printSQL $ true & cast int4 ^ type to cast as ^ value to convert | A safe version of `cast` which just matches a value with its type. ^ type to specify as ^ value | `inferredtype` will add a type annotation to an `Expression` which can be useful for fixing the storage type of a value. (TRUE :: bool) ^ value ---------------------------------------- type expressions ---------------------------------------- | `TypeExpression`s are used in `cast`s and `Squeal.PostgreSQL.Definition.createTable` commands. | The composite type corresponding to a relation can be expressed by its alias. A relation is either a composite type, a table or a view. It subsumes `typetable` and `typeview` and partly overlaps `typedef`. ^ type alias | An enumerated type can be expressed by its alias. `typeenum` is subsumed by `typedef`. ^ type alias ^ type alias | The composite type corresponding to a `Table` definition can be expressed by its alias. It is subsumed by `typerow` ^ table alias | The composite type corresponding to a `View` definition can be expressed by its alias. It is subsumed by `typerow`. ^ view alias | logical Boolean (true/false) | arbitrary precision numeric type | currency amount | variable-length character string | fixed-length character string | variable-length character string | binary data ("byte array") | date and time (no time zone) | date and time, including time zone | calendar date (year, month, day) | time of day (no time zone) | time of day, including time zone | time span | universally unique identifier | IPv4 or IPv6 host address | textual JSON data | binary JSON data, decomposed | variable length array | fixed length array >>> renderSQL (fixarray @'[2] json) "json[2]" | text search query | text search document | Object identifiers (OIDs) are used internally by PostgreSQL as primary keys for various system tables. | Range of integer | Range of bigint | Range of numeric | Range of timestamp without time zone | Range of timestamp with time zone | Range of date | Anonymous composite record | `pgtype` is a demoted version of a `PGType` >>> printSQL $ pgtypeFrom @String text >>> printSQL $ pgtypeFrom @Double float8 | `ColumnTypeExpression`s are used in `Squeal.PostgreSQL.Definition.createTable` commands. | used in `Squeal.PostgreSQL.Definition.createTable` commands as a column constraint to note that @NULL@ may be present in a column ^ type | used in `Squeal.PostgreSQL.Definition.createTable` commands as a column constraint to ensure @NULL@ is not present in a column ^ type | used in `Squeal.PostgreSQL.Definition.createTable` commands as a column constraint to give a default ^ default value ^ column type | not a true type, but merely a notational convenience for creating | not a true type, but merely a notational convenience for creating unique identifier columns with type `PGint4` | not a true type, but merely a notational convenience for creating unique identifier columns with type `PGint8` >>> printSQL $ nulltypeFrom @(Maybe String) text >>> printSQL $ nulltypeFrom @Double float8 text NULL >>> printSQL $ columntypeFrom @Double float8 NOT NULL
| Module : Squeal . PostgreSQL.Expression Description : type expressions Copyright : ( c ) , 2019 Maintainer : Stability : experimental type expressions Module: Squeal.PostgreSQL.Expression Description: type expressions Copyright: (c) Eitan Chatav, 2019 Maintainer: Stability: experimental type expressions -} # LANGUAGE AllowAmbiguousTypes , , DeriveGeneric , DerivingStrategies , FlexibleContexts , FlexibleInstances , GADTs , , , MultiParamTypeClasses , OverloadedStrings , RankNTypes , ScopedTypeVariables , TypeApplications , TypeOperators , UndecidableInstances # AllowAmbiguousTypes , DataKinds , DeriveGeneric , DerivingStrategies , FlexibleContexts , FlexibleInstances , GADTs , GeneralizedNewtypeDeriving , KindSignatures , MultiParamTypeClasses , OverloadedStrings , RankNTypes , ScopedTypeVariables , TypeApplications , TypeOperators , UndecidableInstances #-} module Squeal.PostgreSQL.Expression.Type cast , astype , inferredtype , TypeExpression (..) , typerow , typeenum , typedef , typetable , typeview , bool , int2 , smallint , int4 , int , integer , int8 , bigint , numeric , float4 , real , float8 , doublePrecision , money , text , char , character , varchar , characterVarying , bytea , timestamp , timestampWithTimeZone , timestamptz , date , time , timeWithTimeZone , timetz , interval , uuid , inet , json , jsonb , vararray , fixarray , tsvector , tsquery , oid , int4range , int8range , numrange , tsrange , tstzrange , daterange , record , ColumnTypeExpression (..) , nullable , notNullable , default_ , serial2 , smallserial , serial4 , serial , serial8 , bigserial , PGTyped (..) , pgtypeFrom , NullTyped (..) , nulltypeFrom , ColumnTyped (..) , columntypeFrom , FieldTyped (..) ) where import Control.DeepSeq import Data.ByteString import Data.String import GHC.TypeLits import qualified Data.ByteString as ByteString import qualified GHC.Generics as GHC import qualified Generics.SOP as SOP import Squeal.PostgreSQL.Type.Alias import Squeal.PostgreSQL.Expression import Squeal.PostgreSQL.Type.PG import Squeal.PostgreSQL.Render import Squeal.PostgreSQL.Type.Schema ( TRUE : : int4 ) cast :: TypeExpression db ty1 -> Expression grp lat with db params from ty0 -> Expression grp lat with db params from ty1 cast ty x = UnsafeExpression $ parenthesized $ renderSQL x <+> "::" <+> renderSQL ty > > > printSQL ( 1 & astype int ) ( ( 1 : : int4 ) : : int ) astype :: TypeExpression db ty -> Expression grp lat with db params from ty -> Expression grp lat with db params from ty astype = cast > > > printSQL ( ) inferredtype :: NullTyped db ty => Expression lat common grp db params from ty -> Expression lat common grp db params from ty inferredtype = astype nulltype newtype TypeExpression (db :: SchemasType) (ty :: NullType) = UnsafeTypeExpression { renderTypeExpression :: ByteString } deriving stock (GHC.Generic,Show,Eq,Ord) deriving newtype (NFData) instance RenderSQL (TypeExpression db ty) where renderSQL = renderTypeExpression typerow :: ( relss ~ DbRelations db , Has sch relss rels , Has rel rels row ) => QualifiedAlias sch rel -> TypeExpression db (null ('PGcomposite row)) typerow = UnsafeTypeExpression . renderSQL typeenum :: ( enumss ~ DbEnums db , Has sch enumss enums , Has enum enums labels ) => QualifiedAlias sch enum -> TypeExpression db (null ('PGenum labels)) typeenum = UnsafeTypeExpression . renderSQL | The enum or composite type in a ` Typedef ` can be expressed by its alias . typedef :: (Has sch db schema, Has td schema ('Typedef ty)) => QualifiedAlias sch td -> TypeExpression db (null ty) typedef = UnsafeTypeExpression . renderSQL typetable :: (Has sch db schema, Has tab schema ('Table table)) => QualifiedAlias sch tab -> TypeExpression db (null ('PGcomposite (TableToRow table))) typetable = UnsafeTypeExpression . renderSQL typeview :: (Has sch db schema, Has vw schema ('View view)) => QualifiedAlias sch vw -> TypeExpression db (null ('PGcomposite view)) typeview = UnsafeTypeExpression . renderSQL bool :: TypeExpression db (null 'PGbool) bool = UnsafeTypeExpression "bool" | signed two - byte integer int2, smallint :: TypeExpression db (null 'PGint2) int2 = UnsafeTypeExpression "int2" smallint = UnsafeTypeExpression "smallint" | signed four - byte integer int4, int, integer :: TypeExpression db (null 'PGint4) int4 = UnsafeTypeExpression "int4" int = UnsafeTypeExpression "int" integer = UnsafeTypeExpression "integer" | signed eight - byte integer int8, bigint :: TypeExpression db (null 'PGint8) int8 = UnsafeTypeExpression "int8" bigint = UnsafeTypeExpression "bigint" numeric :: TypeExpression db (null 'PGnumeric) numeric = UnsafeTypeExpression "numeric" | single precision floating - point number ( 4 bytes ) float4, real :: TypeExpression db (null 'PGfloat4) float4 = UnsafeTypeExpression "float4" real = UnsafeTypeExpression "real" | double precision floating - point number ( 8 bytes ) float8, doublePrecision :: TypeExpression db (null 'PGfloat8) float8 = UnsafeTypeExpression "float8" doublePrecision = UnsafeTypeExpression "double precision" money :: TypeExpression schema (null 'PGmoney) money = UnsafeTypeExpression "money" text :: TypeExpression db (null 'PGtext) text = UnsafeTypeExpression "text" char, character :: forall n db null. (KnownNat n, 1 <= n) => TypeExpression db (null ('PGchar n)) char = UnsafeTypeExpression $ "char(" <> renderNat @n <> ")" character = UnsafeTypeExpression $ "character(" <> renderNat @n <> ")" varchar, characterVarying :: forall n db null. (KnownNat n, 1 <= n) => TypeExpression db (null ('PGvarchar n)) varchar = UnsafeTypeExpression $ "varchar(" <> renderNat @n <> ")" characterVarying = UnsafeTypeExpression $ "character varying(" <> renderNat @n <> ")" bytea :: TypeExpression db (null 'PGbytea) bytea = UnsafeTypeExpression "bytea" timestamp :: TypeExpression db (null 'PGtimestamp) timestamp = UnsafeTypeExpression "timestamp" timestampWithTimeZone, timestamptz :: TypeExpression db (null 'PGtimestamptz) timestampWithTimeZone = UnsafeTypeExpression "timestamp with time zone" timestamptz = UnsafeTypeExpression "timestamptz" date :: TypeExpression db (null 'PGdate) date = UnsafeTypeExpression "date" time :: TypeExpression db (null 'PGtime) time = UnsafeTypeExpression "time" timeWithTimeZone, timetz :: TypeExpression db (null 'PGtimetz) timeWithTimeZone = UnsafeTypeExpression "time with time zone" timetz = UnsafeTypeExpression "timetz" interval :: TypeExpression db (null 'PGinterval) interval = UnsafeTypeExpression "interval" uuid :: TypeExpression db (null 'PGuuid) uuid = UnsafeTypeExpression "uuid" inet :: TypeExpression db (null 'PGinet) inet = UnsafeTypeExpression "inet" json :: TypeExpression db (null 'PGjson) json = UnsafeTypeExpression "json" jsonb :: TypeExpression db (null 'PGjsonb) jsonb = UnsafeTypeExpression "jsonb" vararray :: TypeExpression db pg -> TypeExpression db (null ('PGvararray pg)) vararray ty = UnsafeTypeExpression $ renderSQL ty <> "[]" fixarray :: forall dims db null pg. SOP.All KnownNat dims => TypeExpression db pg -> TypeExpression db (null ('PGfixarray dims pg)) fixarray ty = UnsafeTypeExpression $ renderSQL ty <> renderDims @dims where renderDims :: forall ns. SOP.All KnownNat ns => ByteString renderDims = ("[" <>) . (<> "]") . ByteString.intercalate "][" . SOP.hcollapse $ SOP.hcmap (SOP.Proxy @KnownNat) (SOP.K . fromString . show . natVal) (SOP.hpure SOP.Proxy :: SOP.NP SOP.Proxy ns) tsvector :: TypeExpression db (null 'PGtsvector) tsvector = UnsafeTypeExpression "tsvector" tsquery :: TypeExpression db (null 'PGtsquery) tsquery = UnsafeTypeExpression "tsquery" oid :: TypeExpression db (null 'PGoid) oid = UnsafeTypeExpression "oid" int4range :: TypeExpression db (null ('PGrange 'PGint4)) int4range = UnsafeTypeExpression "int4range" int8range :: TypeExpression db (null ('PGrange 'PGint8)) int8range = UnsafeTypeExpression "int8range" numrange :: TypeExpression db (null ('PGrange 'PGnumeric)) numrange = UnsafeTypeExpression "numrange" tsrange :: TypeExpression db (null ('PGrange 'PGtimestamp)) tsrange = UnsafeTypeExpression "tsrange" tstzrange :: TypeExpression db (null ('PGrange 'PGtimestamptz)) tstzrange = UnsafeTypeExpression "tstzrange" daterange :: TypeExpression db (null ('PGrange 'PGdate)) daterange = UnsafeTypeExpression "daterange" record :: TypeExpression db (null ('PGcomposite record)) record = UnsafeTypeExpression "record" class PGTyped db (ty :: PGType) where pgtype :: TypeExpression db (null ty) instance PGTyped db 'PGbool where pgtype = bool instance PGTyped db 'PGint2 where pgtype = int2 instance PGTyped db 'PGint4 where pgtype = int4 instance PGTyped db 'PGint8 where pgtype = int8 instance PGTyped db 'PGnumeric where pgtype = numeric instance PGTyped db 'PGfloat4 where pgtype = float4 instance PGTyped db 'PGfloat8 where pgtype = float8 instance PGTyped db 'PGmoney where pgtype = money instance PGTyped db 'PGtext where pgtype = text instance (KnownNat n, 1 <= n) => PGTyped db ('PGchar n) where pgtype = char @n instance (KnownNat n, 1 <= n) => PGTyped db ('PGvarchar n) where pgtype = varchar @n instance PGTyped db 'PGbytea where pgtype = bytea instance PGTyped db 'PGtimestamp where pgtype = timestamp instance PGTyped db 'PGtimestamptz where pgtype = timestampWithTimeZone instance PGTyped db 'PGdate where pgtype = date instance PGTyped db 'PGtime where pgtype = time instance PGTyped db 'PGtimetz where pgtype = timeWithTimeZone instance PGTyped db 'PGinterval where pgtype = interval instance PGTyped db 'PGuuid where pgtype = uuid instance PGTyped db 'PGinet where pgtype = inet instance PGTyped db 'PGjson where pgtype = json instance PGTyped db 'PGjsonb where pgtype = jsonb instance PGTyped db pg => PGTyped db ('PGvararray (null pg)) where pgtype = vararray (pgtype @db @pg) instance (SOP.All KnownNat dims, PGTyped db pg) => PGTyped db ('PGfixarray dims (null pg)) where pgtype = fixarray @dims (pgtype @db @pg) instance PGTyped db 'PGtsvector where pgtype = tsvector instance PGTyped db 'PGtsquery where pgtype = tsquery instance PGTyped db 'PGoid where pgtype = oid instance PGTyped db ('PGrange 'PGint4) where pgtype = int4range instance PGTyped db ('PGrange 'PGint8) where pgtype = int8range instance PGTyped db ('PGrange 'PGnumeric) where pgtype = numrange instance PGTyped db ('PGrange 'PGtimestamp) where pgtype = tsrange instance PGTyped db ('PGrange 'PGtimestamptz) where pgtype = tstzrange instance PGTyped db ('PGrange 'PGdate) where pgtype = daterange instance ( relss ~ DbRelations db , Has sch relss rels , Has rel rels row , FindQualified "no relation found with row:" relss row ~ '(sch,rel) ) => PGTyped db ('PGcomposite row) where pgtype = typerow (QualifiedAlias @sch @rel) instance ( enums ~ DbEnums db , FindQualified "no enum found with labels:" enums labels ~ '(sch,td) , Has sch db schema , Has td schema ('Typedef ('PGenum labels)) ) => PGTyped db ('PGenum labels) where pgtype = typedef (QualifiedAlias @sch @td) | Specify ` TypeExpression ` from a type . pgtypeFrom :: forall hask db null. PGTyped db (PG hask) => TypeExpression db (null (PG hask)) pgtypeFrom = pgtype @db @(PG hask) | Lift ` PGTyped ` to a field class FieldTyped db ty where fieldtype :: Aliased (TypeExpression db) ty instance (KnownSymbol alias, NullTyped db ty) => FieldTyped db (alias ::: ty) where fieldtype = nulltype `As` Alias newtype ColumnTypeExpression (db :: SchemasType) (ty :: ColumnType) = UnsafeColumnTypeExpression { renderColumnTypeExpression :: ByteString } deriving stock (GHC.Generic,Show,Eq,Ord) deriving newtype (NFData) instance RenderSQL (ColumnTypeExpression db ty) where renderSQL = renderColumnTypeExpression nullable :: TypeExpression db (null ty) -> ColumnTypeExpression db ('NoDef :=> 'Null ty) nullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NULL" notNullable :: TypeExpression db (null ty) -> ColumnTypeExpression db ('NoDef :=> 'NotNull ty) notNullable ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "NOT NULL" default_ :: Expression 'Ungrouped '[] '[] db '[] '[] ty -> ColumnTypeExpression db ('NoDef :=> ty) -> ColumnTypeExpression db ('Def :=> ty) default_ x ty = UnsafeColumnTypeExpression $ renderSQL ty <+> "DEFAULT" <+> renderExpression x unique identifier columns with type ` PGint2 ` serial2, smallserial :: ColumnTypeExpression db ('Def :=> 'NotNull 'PGint2) serial2 = UnsafeColumnTypeExpression "serial2" smallserial = UnsafeColumnTypeExpression "smallserial" serial4, serial :: ColumnTypeExpression db ('Def :=> 'NotNull 'PGint4) serial4 = UnsafeColumnTypeExpression "serial4" serial = UnsafeColumnTypeExpression "serial" serial8, bigserial :: ColumnTypeExpression db ('Def :=> 'NotNull 'PGint8) serial8 = UnsafeColumnTypeExpression "serial8" bigserial = UnsafeColumnTypeExpression "bigserial" | Like but also accounts for null . class NullTyped db (ty :: NullType) where nulltype :: TypeExpression db ty instance PGTyped db ty => NullTyped db (null ty) where nulltype = pgtype @db @ty | Specify null ` TypeExpression ` from a type . nulltypeFrom :: forall hask db. NullTyped db (NullPG hask) => TypeExpression db (NullPG hask) nulltypeFrom = nulltype @db @(NullPG hask) | Like but also accounts for null . class ColumnTyped db (column :: ColumnType) where columntype :: ColumnTypeExpression db column instance NullTyped db ('Null ty) => ColumnTyped db ('NoDef :=> 'Null ty) where columntype = nullable (nulltype @db @('Null ty)) instance NullTyped db ('NotNull ty) => ColumnTyped db ('NoDef :=> 'NotNull ty) where columntype = notNullable (nulltype @db @('NotNull ty)) | Specify ` ColumnTypeExpression ` from a type . > > > printSQL $ columntypeFrom @(Maybe String ) columntypeFrom :: forall hask db. (ColumnTyped db ('NoDef :=> NullPG hask)) => ColumnTypeExpression db ('NoDef :=> NullPG hask) columntypeFrom = columntype @db @('NoDef :=> NullPG hask)
ce77936b22b4e4ec22f8e29053f20a3f7fa07d15682c04b2d7ef8c90d3f54b01
hendry19901990/erlang-ipfs-http-client
jsone.erl
%%% @doc JSON decoding/encoding module %%% @end %%% Copyright ( c ) 2017 , %%% %%% The MIT License %%% %%% Permission is hereby granted, free of charge, to any person obtaining a copy %%% of this software and associated documentation files (the "Software"), to deal in the Software without restriction , including without limitation the rights %%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is %%% furnished to do so, subject to the following conditions: %%% %%% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %%% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR %%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, %%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE %%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , %%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN %%% THE SOFTWARE. %%% %%%--------------------------------------------------------------------------------------- -module(jsone). %%-------------------------------------------------------------------------------- %% Exported API %%-------------------------------------------------------------------------------- -export([ decode/1, decode/2, try_decode/1, try_decode/2, encode/1, encode/2, try_encode/1, try_encode/2 ]). -export_type([ json_value/0, json_boolean/0, json_number/0, json_string/0, json_array/0, json_object/0, json_object_members/0, json_term/0, json_object_format_tuple/0, json_object_format_proplist/0, json_object_format_map/0, json_scalar/0, encode_option/0, decode_option/0, float_format_option/0, datetime_encode_format/0, datetime_format/0, timezone/0, utc_offset_seconds/0, stack_item/0 ]). %%-------------------------------------------------------------------------------- Types & Macros %%-------------------------------------------------------------------------------- -type json_value() :: json_number() | json_string() | json_array() | json_object() | json_boolean() | null | json_term(). -type json_boolean() :: boolean(). -type json_number() :: number(). -type json_string() :: binary() | atom() | calendar:datetime(). % NOTE: `decode/1' always returns `binary()' value -type json_array() :: [json_value()]. -type json_object() :: json_object_format_tuple() | json_object_format_proplist() | json_object_format_map(). -type json_object_members() :: [{json_string(), json_value()}]. -type json_term() :: {{json, iolist()}} | {{json_utf8, unicode:chardata()}}. %% `json_term()' allows inline already encoded JSON value. `json' variant %% expects byte encoded utf8 data values as list members. `json_utf8' expect Unicode code points as list members . Binaries are copied " as is " in both variants except ` json_utf8 ' will check if binary contain valid ` UTF-8 ' encoded data . In short , ` json ' uses ` erlang : iolist_to_binary/1 ' and %% `json_utf8' uses `unicode:chardata_to_binary/1' for encoding. %% A simple example is worth a thousand words . %% %% ``` 1 > S = " hélo " . %% "hélo" 2 > shell : strings(false ) . %% true 3 > S. [ 104,233,108,111 ] 4 > B = jsone : } } ) . % invalid UTF-8 < < 104,233,108,111 > > 5 > B2 = jsone : encode({{json_utf8 , S } } ) . % valid UTF-8 < < 104,195,169,108,111 > > 6 : , B } } ) . < < 104,233,108,111 > > 7 : encode({{json_utf8 , B } } ) . %% ** exception error: {invalid_json_utf8,<<104>>,<<233,108,111>>} %% in function jsone_encode:value/4 called as jsone_encode : value({json_utf8,<<104,233,108,111 > > } , %% [],<<>>, %% {encode_opt_v2,false, %% [{scientific,20}], %% {iso8601,0}, %% string,0,0}) in call from jsone : encode/2 ( /home / hynek / work / altworx / jsone/_build / default / lib / jsone / src / jsone.erl , line 302 ) 8 : encode({{json_utf8 , B2 } } ) . < < 104,195,169,108,111 > > 9 > shell : strings(true ) . %% false 10 : encode({{json_utf8 , B2 } } ) . %% <<"hélo"/utf8>> 11 : , binary_to_list(B2 ) } } ) . % UTF-8 encoded list leads to valid UTF-8 %% <<"hélo"/utf8>> %% ''' %% -type json_object_format_tuple() :: {json_object_members()}. -type json_object_format_proplist() :: [{}] | json_object_members(). -ifdef('NO_MAP_TYPE'). -opaque json_object_format_map() :: json_object_format_proplist(). %% `maps' is not supported in this erts version -else. -type json_object_format_map() :: map(). -endif. -type json_scalar() :: json_boolean() | json_number() | json_string(). -type float_format_option() :: {scientific, Decimals :: 0..249} | {decimals, Decimals :: 0..253} | compact. %% `scientific': <br /> %% - The float will be formatted using scientific notation with `Decimals' digits of precision. <br /> %% %% `decimals': <br /> %% - The encoded string will contain at most `Decimals' number of digits past the decimal point. <br /> - If ` compact ' is provided the trailing zeros at the end of the string are truncated . < br / > %% For more details , see < a href=" / doc / man / erlang.html#float_to_list-2">erlang : flaot_to_list/2</a > . %% %% ``` %% > jsone:encode(1.23). < < " 1.22999999999999998224e+00 " > > %% > jsone : encode(1.23 , [ { float_format , [ { scientific , 4 } ] } ] ) . %% <"1.2300e+00">> %% > jsone : encode(1.23 , [ { float_format , [ { scientific , 1 } ] } ] ) . < < " 1.2e+00 " > > %% > jsone : encode(1.23 , [ { float_format , [ { decimals , 4 } ] } ] ) . < < " 1.2300 " > > %% > jsone : encode(1.23 , [ { float_format , [ { decimals , 4 } , compact ] } ] ) . < < " 1.23 " > > %% ''' -type datetime_encode_format() :: Format::datetime_format() | {Format::datetime_format(), TimeZone::timezone()}. %% Datetime encoding format. %% The default value of ` TimeZone ' is ` utc ' . %% %% ``` %% % % Universal Time %% % > jsone : encode({{2000 , 3 , 10 } , { 10 , 3 , 58 } } , [ { datetime_format , iso8601 } ] ) . %% <<"\"2000-03-10T10:03:58Z\"">> %% %% % % Local Time ( JST ) %% % > jsone : encode({{2000 , 3 , 10 } , { 10 , 3 , 58 } } , [ { datetime_format , { iso8601 , local } } ] ) . %% <<"\"2000-03-10T10:03:58+09:00\"">> %% %% % % Explicit TimeZone Offset %% % > jsone : encode({{2000 , 3 , 10 } , { 10 , 3 , 58 } } , [ { datetime_format , { iso8601 , -2 * 60 * 60 } } ] ) . %% <<"\"2000-03-10T10:03:58-02:00\"">> %% ''' -type datetime_format() :: iso8601. -type timezone() :: utc | local | utc_offset_seconds(). -type utc_offset_seconds() :: -86399..86399. -type encode_option() :: native_utf8 | canonical_form | {float_format, [float_format_option()]} | {datetime_format, datetime_encode_format()} | {object_key_type, string | scalar | value} | {space, non_neg_integer()} | {indent, non_neg_integer()} | undefined_as_null. %% `native_utf8': <br /> - Encodes UTF-8 characters as a human - readable(non - escaped ) string < br / > %% %% `canonical_form': <br /> %% - produce a canonical form of a JSON document <br /> %% %% `{float_format, Optoins}': %% - Encodes a `float()` value in the format which specified by `Options' <br /> - default : ` [ { scientific , 20 } ] ' < br / > %% %% `{datetime_format, Format}`: %% - Encodes a `calendar:datetime()` value in the format which specified by `Format' <br /> - default : ` { iso8601 , } ' < br / > %% %% `object_key_type': %% - Allowable object key type <br /> %% - `string': Only string values are allowed (i.e. `json_string()' type) <br /> %% - `scalar': In addition to `string', following values are allowed: nulls, booleans, numerics (i.e. `json_scalar()' type) <br /> %% - `value': Any json compatible values are allowed (i.e. `json_value()' type) <br /> %% - default: `string' <br /> - NOTE : If ` scalar ' or ` value ' option is specified , non ` json_string ( ) ' key will be automatically converted to a ` binary ( ) ' value ( e.g. ` 1 ' = > ` < < " 1 " > > ' , ` # { } ' = > ` < < " { } " > > ' ) < br / > %% %% `{space, N}': <br /> %% - Inserts `N' spaces after every commna and colon <br /> %% - default: `0' <br /> %% %% `{indent, N}': <br /> %% - Inserts a newline and `N' spaces for each level of indentation <br /> %% - default: `0' <br /> %% %% `undefined_as_null': <br /> %% - Encodes atom `undefined' as null value <br /> -type decode_option() :: {object_format, tuple | proplist | map} | {allow_ctrl_chars, boolean()} | {'keys', 'binary' | 'atom' | 'existing_atom' | 'attempt_atom'}. %% `object_format': <br /> %% - Decoded JSON object format <br /> %% - `tuple': An object is decoded as `{[]}' if it is empty, otherwise `{[{Key, Value}]}'. <br /> %% - `proplist': An object is decoded as `[{}]' if it is empty, otherwise `[{Key, Value}]'. <br /> %% - `map': An object is decoded as `#{}' if it is empty, otherwise `#{Key => Value}'. <br /> - default : ` map ' if OTP version is OTP-17 or more , ` tuple ' otherwise < br / > %% %% `allow_ctrl_chars': <br /> %% - If the value is `true', strings which contain ununescaped control characters will be regarded as a legal JSON string <br /> %% - default: `false'<br /> %% %% `keys': <br /> %% Defines way how object keys are decoded. The default value is `binary'. %% The option is compatible with `labels' option in `jsx'. <br /> %% - `binary': The key is left as a string which is encoded as binary. It's default %% and backward compatible behaviour. <br /> %% - `atom': The key is converted to an atom. Results in `badarg' if Key value regarded as UTF-8 is not a valid atom . < br / > - ` existing_atom ' : Returns existing atom . Any key value which is not %% existing atom raises `badarg' exception. <br /> - ` attempt_atom ' : Returns existing atom as ` existing_atom ' but returns a %% binary string if fails find one. -type stack_item() :: {Module :: module(), Function :: atom(), Arity :: arity() | (Args :: [term()]), Location :: [{file, Filename :: string()} | {line, Line :: pos_integer()}]}. %% An item in a stack back-trace. %% %% Note that the `erlang' module already defines the same `stack_item/0' type, %% but it is not exported from the module. %% So, maybe as a temporary measure, we redefine this type for passing full dialyzer analysis. %%-------------------------------------------------------------------------------- %% Exported Functions %%-------------------------------------------------------------------------------- %% @equiv decode(Json, []) -spec decode(binary()) -> json_value(). decode(Json) -> decode(Json, []). @doc an erlang term from json text ( a utf8 encoded binary ) %% %% Raises an error exception if input is not valid json %% %% ``` %% > jsone:decode(<<"1">>, []). 1 %% > jsone : > > , [ ] ) . %% ** exception error: bad argument %% in function jsone_decode:number_integer_part/4 called as jsone_decode : , [ ] , < < > > ) in call from jsone : decode/1 ( src / jsone.erl , line 71 ) %% ''' -spec decode(binary(), [decode_option()]) -> json_value(). decode(Json, Options) -> try {ok, Value, _} = try_decode(Json, Options), Value catch error:{badmatch, {error, {Reason, [StackItem]}}} -> erlang:raise(error, Reason, [StackItem | erlang:get_stacktrace()]) end. %% @equiv try_decode(Json, []) -spec try_decode(binary()) -> {ok, json_value(), Remainings::binary()} | {error, {Reason::term(), [stack_item()]}}. try_decode(Json) -> try_decode(Json, []). @doc an erlang term from json text ( a utf8 encoded binary ) %% %% ``` > jsone : try_decode(<<"[1,2,3 ] \"next " " > > , [ ] ) . { ok,[1,2,3 ] , < < " \"next " " > > } %% %% > jsone:try_decode(<<"wrong json">>, []). %% {error,{badarg,[{jsone_decode,number_integer_part, %% [<<"wrong json">>,1,[],<<>>], %% [{line,208}]}]}} %% ''' -spec try_decode(binary(), [decode_option()]) -> {ok, json_value(), Remainings::binary()} | {error, {Reason::term(), [stack_item()]}}. try_decode(Json, Options) -> jsone_decode:decode(Json, Options). %% @equiv encode(JsonValue, []) -spec encode(json_value()) -> binary(). encode(JsonValue) -> encode(JsonValue, []). @doc Encodes an erlang term into json text ( a utf8 encoded binary ) %% %% Raises an error exception if input is not an instance of type `json_value()' %% %% ``` > jsone : , null , 2 ] ) . %% <<"[1,null,2]">> %% > jsone : , self ( ) , 2 ] ) . % A pid is not a json value %% ** exception error: bad argument %% in function jsone_encode:value/3 %% called as jsone_encode:value(<0,34,0>,[{array_values,[2]}],<<"[1,">>) in call from jsone : ( src / jsone.erl , line 97 ) %% ''' -spec encode(json_value(), [encode_option()]) -> binary(). encode(JsonValue, Options) -> try {ok, Binary} = try_encode(JsonValue, Options), Binary catch error:{badmatch, {error, {Reason, [StackItem]}}} -> erlang:raise(error, Reason, [StackItem | erlang:get_stacktrace()]) end. %% @equiv try_encode(JsonValue, []) -spec try_encode(json_value()) -> {ok, binary()} | {error, {Reason::term(), [stack_item()]}}. try_encode(JsonValue) -> try_encode(JsonValue, []). @doc Encodes an erlang term into json text ( a utf8 encoded binary ) %% %% ``` > jsone : try_encode([1 , null , 2 ] ) . %% {ok,<<"[1,null,2]">>} %% > jsone : try_encode([1 , , 2 ] ) . % ' ' atom is not a json value %% {error,{badarg,[{jsone_encode,value, %% [hoge,[{array_values,[2]}],<<"[1,">>], [ { line,86 } ] } ] } } %% ''' -spec try_encode(json_value(), [encode_option()]) -> {ok, binary()} | {error, {Reason::term(), [stack_item()]}}. try_encode(JsonValue, Options) -> jsone_encode:encode(JsonValue, Options).
null
https://raw.githubusercontent.com/hendry19901990/erlang-ipfs-http-client/f7e18cabe2901d64733027622677bbaea89f1587/src/jsone.erl
erlang
@doc JSON decoding/encoding module @end The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Exported API -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- NOTE: `decode/1' always returns `binary()' value `json_term()' allows inline already encoded JSON value. `json' variant expects byte encoded utf8 data values as list members. `json_utf8' expect `json_utf8' uses `unicode:chardata_to_binary/1' for encoding. ``` "hélo" true invalid UTF-8 valid UTF-8 ** exception error: {invalid_json_utf8,<<104>>,<<233,108,111>>} in function jsone_encode:value/4 [],<<>>, {encode_opt_v2,false, [{scientific,20}], {iso8601,0}, string,0,0}) false <<"hélo"/utf8>> UTF-8 encoded list leads to valid UTF-8 <<"hélo"/utf8>> ''' `maps' is not supported in this erts version `scientific': <br /> - The float will be formatted using scientific notation with `Decimals' digits of precision. <br /> `decimals': <br /> - The encoded string will contain at most `Decimals' number of digits past the decimal point. <br /> ``` > jsone:encode(1.23). <"1.2300e+00">> ''' Datetime encoding format. ``` % Universal Time % <<"\"2000-03-10T10:03:58Z\"">> % Local Time ( JST ) % <<"\"2000-03-10T10:03:58+09:00\"">> % Explicit TimeZone Offset % <<"\"2000-03-10T10:03:58-02:00\"">> ''' `native_utf8': <br /> `canonical_form': <br /> - produce a canonical form of a JSON document <br /> `{float_format, Optoins}': - Encodes a `float()` value in the format which specified by `Options' <br /> `{datetime_format, Format}`: - Encodes a `calendar:datetime()` value in the format which specified by `Format' <br /> `object_key_type': - Allowable object key type <br /> - `string': Only string values are allowed (i.e. `json_string()' type) <br /> - `scalar': In addition to `string', following values are allowed: nulls, booleans, numerics (i.e. `json_scalar()' type) <br /> - `value': Any json compatible values are allowed (i.e. `json_value()' type) <br /> - default: `string' <br /> `{space, N}': <br /> - Inserts `N' spaces after every commna and colon <br /> - default: `0' <br /> `{indent, N}': <br /> - Inserts a newline and `N' spaces for each level of indentation <br /> - default: `0' <br /> `undefined_as_null': <br /> - Encodes atom `undefined' as null value <br /> `object_format': <br /> - Decoded JSON object format <br /> - `tuple': An object is decoded as `{[]}' if it is empty, otherwise `{[{Key, Value}]}'. <br /> - `proplist': An object is decoded as `[{}]' if it is empty, otherwise `[{Key, Value}]'. <br /> - `map': An object is decoded as `#{}' if it is empty, otherwise `#{Key => Value}'. <br /> `allow_ctrl_chars': <br /> - If the value is `true', strings which contain ununescaped control characters will be regarded as a legal JSON string <br /> - default: `false'<br /> `keys': <br /> Defines way how object keys are decoded. The default value is `binary'. The option is compatible with `labels' option in `jsx'. <br /> - `binary': The key is left as a string which is encoded as binary. It's default and backward compatible behaviour. <br /> - `atom': The key is converted to an atom. Results in `badarg' if Key value existing atom raises `badarg' exception. <br /> binary string if fails find one. An item in a stack back-trace. Note that the `erlang' module already defines the same `stack_item/0' type, but it is not exported from the module. So, maybe as a temporary measure, we redefine this type for passing full dialyzer analysis. -------------------------------------------------------------------------------- Exported Functions -------------------------------------------------------------------------------- @equiv decode(Json, []) Raises an error exception if input is not valid json ``` > jsone:decode(<<"1">>, []). ** exception error: bad argument in function jsone_decode:number_integer_part/4 ''' @equiv try_decode(Json, []) ``` > jsone:try_decode(<<"wrong json">>, []). {error,{badarg,[{jsone_decode,number_integer_part, [<<"wrong json">>,1,[],<<>>], [{line,208}]}]}} ''' @equiv encode(JsonValue, []) Raises an error exception if input is not an instance of type `json_value()' ``` <<"[1,null,2]">> A pid is not a json value ** exception error: bad argument in function jsone_encode:value/3 called as jsone_encode:value(<0,34,0>,[{array_values,[2]}],<<"[1,">>) ''' @equiv try_encode(JsonValue, []) ``` {ok,<<"[1,null,2]">>} ' ' atom is not a json value {error,{badarg,[{jsone_encode,value, [hoge,[{array_values,[2]}],<<"[1,">>], '''
Copyright ( c ) 2017 , in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , -module(jsone). -export([ decode/1, decode/2, try_decode/1, try_decode/2, encode/1, encode/2, try_encode/1, try_encode/2 ]). -export_type([ json_value/0, json_boolean/0, json_number/0, json_string/0, json_array/0, json_object/0, json_object_members/0, json_term/0, json_object_format_tuple/0, json_object_format_proplist/0, json_object_format_map/0, json_scalar/0, encode_option/0, decode_option/0, float_format_option/0, datetime_encode_format/0, datetime_format/0, timezone/0, utc_offset_seconds/0, stack_item/0 ]). Types & Macros -type json_value() :: json_number() | json_string() | json_array() | json_object() | json_boolean() | null | json_term(). -type json_boolean() :: boolean(). -type json_number() :: number(). -type json_array() :: [json_value()]. -type json_object() :: json_object_format_tuple() | json_object_format_proplist() | json_object_format_map(). -type json_object_members() :: [{json_string(), json_value()}]. -type json_term() :: {{json, iolist()}} | {{json_utf8, unicode:chardata()}}. Unicode code points as list members . Binaries are copied " as is " in both variants except ` json_utf8 ' will check if binary contain valid ` UTF-8 ' encoded data . In short , ` json ' uses ` erlang : iolist_to_binary/1 ' and A simple example is worth a thousand words . 1 > S = " hélo " . 2 > shell : strings(false ) . 3 > S. [ 104,233,108,111 ] < < 104,233,108,111 > > < < 104,195,169,108,111 > > 6 : , B } } ) . < < 104,233,108,111 > > 7 : encode({{json_utf8 , B } } ) . called as jsone_encode : value({json_utf8,<<104,233,108,111 > > } , in call from jsone : encode/2 ( /home / hynek / work / altworx / jsone/_build / default / lib / jsone / src / jsone.erl , line 302 ) 8 : encode({{json_utf8 , B2 } } ) . < < 104,195,169,108,111 > > 9 > shell : strings(true ) . 10 : encode({{json_utf8 , B2 } } ) . -type json_object_format_tuple() :: {json_object_members()}. -type json_object_format_proplist() :: [{}] | json_object_members(). -ifdef('NO_MAP_TYPE'). -opaque json_object_format_map() :: json_object_format_proplist(). -else. -type json_object_format_map() :: map(). -endif. -type json_scalar() :: json_boolean() | json_number() | json_string(). -type float_format_option() :: {scientific, Decimals :: 0..249} | {decimals, Decimals :: 0..253} | compact. - If ` compact ' is provided the trailing zeros at the end of the string are truncated . < br / > For more details , see < a href=" / doc / man / erlang.html#float_to_list-2">erlang : flaot_to_list/2</a > . < < " 1.22999999999999998224e+00 " > > > jsone : encode(1.23 , [ { float_format , [ { scientific , 4 } ] } ] ) . > jsone : encode(1.23 , [ { float_format , [ { scientific , 1 } ] } ] ) . < < " 1.2e+00 " > > > jsone : encode(1.23 , [ { float_format , [ { decimals , 4 } ] } ] ) . < < " 1.2300 " > > > jsone : encode(1.23 , [ { float_format , [ { decimals , 4 } , compact ] } ] ) . < < " 1.23 " > > -type datetime_encode_format() :: Format::datetime_format() | {Format::datetime_format(), TimeZone::timezone()}. The default value of ` TimeZone ' is ` utc ' . > jsone : encode({{2000 , 3 , 10 } , { 10 , 3 , 58 } } , [ { datetime_format , iso8601 } ] ) . > jsone : encode({{2000 , 3 , 10 } , { 10 , 3 , 58 } } , [ { datetime_format , { iso8601 , local } } ] ) . > jsone : encode({{2000 , 3 , 10 } , { 10 , 3 , 58 } } , [ { datetime_format , { iso8601 , -2 * 60 * 60 } } ] ) . -type datetime_format() :: iso8601. -type timezone() :: utc | local | utc_offset_seconds(). -type utc_offset_seconds() :: -86399..86399. -type encode_option() :: native_utf8 | canonical_form | {float_format, [float_format_option()]} | {datetime_format, datetime_encode_format()} | {object_key_type, string | scalar | value} | {space, non_neg_integer()} | {indent, non_neg_integer()} | undefined_as_null. - Encodes UTF-8 characters as a human - readable(non - escaped ) string < br / > - default : ` [ { scientific , 20 } ] ' < br / > - default : ` { iso8601 , } ' < br / > - NOTE : If ` scalar ' or ` value ' option is specified , non ` json_string ( ) ' key will be automatically converted to a ` binary ( ) ' value ( e.g. ` 1 ' = > ` < < " 1 " > > ' , ` # { } ' = > ` < < " { } " > > ' ) < br / > -type decode_option() :: {object_format, tuple | proplist | map} | {allow_ctrl_chars, boolean()} | {'keys', 'binary' | 'atom' | 'existing_atom' | 'attempt_atom'}. - default : ` map ' if OTP version is OTP-17 or more , ` tuple ' otherwise < br / > regarded as UTF-8 is not a valid atom . < br / > - ` existing_atom ' : Returns existing atom . Any key value which is not - ` attempt_atom ' : Returns existing atom as ` existing_atom ' but returns a -type stack_item() :: {Module :: module(), Function :: atom(), Arity :: arity() | (Args :: [term()]), Location :: [{file, Filename :: string()} | {line, Line :: pos_integer()}]}. -spec decode(binary()) -> json_value(). decode(Json) -> decode(Json, []). @doc an erlang term from json text ( a utf8 encoded binary ) 1 > jsone : > > , [ ] ) . called as jsone_decode : , [ ] , < < > > ) in call from jsone : decode/1 ( src / jsone.erl , line 71 ) -spec decode(binary(), [decode_option()]) -> json_value(). decode(Json, Options) -> try {ok, Value, _} = try_decode(Json, Options), Value catch error:{badmatch, {error, {Reason, [StackItem]}}} -> erlang:raise(error, Reason, [StackItem | erlang:get_stacktrace()]) end. -spec try_decode(binary()) -> {ok, json_value(), Remainings::binary()} | {error, {Reason::term(), [stack_item()]}}. try_decode(Json) -> try_decode(Json, []). @doc an erlang term from json text ( a utf8 encoded binary ) > jsone : try_decode(<<"[1,2,3 ] \"next " " > > , [ ] ) . { ok,[1,2,3 ] , < < " \"next " " > > } -spec try_decode(binary(), [decode_option()]) -> {ok, json_value(), Remainings::binary()} | {error, {Reason::term(), [stack_item()]}}. try_decode(Json, Options) -> jsone_decode:decode(Json, Options). -spec encode(json_value()) -> binary(). encode(JsonValue) -> encode(JsonValue, []). @doc Encodes an erlang term into json text ( a utf8 encoded binary ) > jsone : , null , 2 ] ) . in call from jsone : ( src / jsone.erl , line 97 ) -spec encode(json_value(), [encode_option()]) -> binary(). encode(JsonValue, Options) -> try {ok, Binary} = try_encode(JsonValue, Options), Binary catch error:{badmatch, {error, {Reason, [StackItem]}}} -> erlang:raise(error, Reason, [StackItem | erlang:get_stacktrace()]) end. -spec try_encode(json_value()) -> {ok, binary()} | {error, {Reason::term(), [stack_item()]}}. try_encode(JsonValue) -> try_encode(JsonValue, []). @doc Encodes an erlang term into json text ( a utf8 encoded binary ) > jsone : try_encode([1 , null , 2 ] ) . [ { line,86 } ] } ] } } -spec try_encode(json_value(), [encode_option()]) -> {ok, binary()} | {error, {Reason::term(), [stack_item()]}}. try_encode(JsonValue, Options) -> jsone_encode:encode(JsonValue, Options).
f55cb64b82823df020356d74b888c2f26f4fc7120ddace5598c6bb2446d37c09
kyleburton/sandbox
compojure.clj
(ns com.github.kyleburton.sandbox.compojure (:use compojure)) (defn resource-link [lnk] (format "%s?%s" lnk (.getTime (java.util.Date.)))) (defmacro mresource-link [lnk] (format "%s?%s" lnk (.getTime (java.util.Date.)))) (defn template-page [request title & body] (let [title (str "Compojure App - " title)] (html [:head [:title title] [:link {:href (mresource-link "/stylesheet/app.css") :rel "stylesheet" :type "text/css"}]] [:div {:id "header"} [:h1 title]] (if-let [flash (-> request :mailx-params :flash)] [:div {:id "flash"} flash]) [:div {:id "main-body"} body] [:div {:id "footer"} [:a {:href "/"} "Home"] " | " [:a {:href "/items"} "Items"] " | " [:a {:href "/about"} "About"] " | " [:a {:href ""} "Compojure"]]))) (defn index-page [request] (template-page request "Home" [:div "Welcome."])) (defn xlink-to [text controller & params] [:a {:href (format "/%s/%s" (name controller) (first params))} text]) (defn items-page [request] (template-page request "Items" [:div "Items."] [:ul (for [item-id (range 10)] [:li (xlink-to (str "Item: " item-id) :item item-id)])])) (defn item-page [request] (let [item-id (-> request :route-params :id)] (template-page request (str "Item: " item-id) [:div "Item: " item-id] [:div "Request: " [:table {:id "session-dump"} [:tr [:th "Key"] [:th "Value"] (map (fn [key] [:tr [:td key] [:td (request key)]]) (keys request))]]]))) (defn about-page [request] (template-page request "About" [:div "This is a " [:a {:href ""} "Compojure"] " application."])) (defn stylesheet-page [request] {:status 200 :headers { "Content-Type" "text/css" } :body " body { background: #EEE; } #main-body { margin-left: 20%; margin-right: 20%; margin-top: 1em; margin-bottom: 1em; border-style: solid; border-width: 2px; border-color: #AAA; padding: 0.5em; } #header { text-align: left; background: #CCC; padding: 1em; margin-left: 20%; margin-right: 20%; } #footer { text-align: center; background: #CCC; margin-top: 1em; padding: 0.5em; margin-left: 20%; margin-right: 20%; } /* #session-dump { border-width: 1px; border-style: outset; border-spacing: 2px; border-collapse: collapse; // separate } #session-dump td { border-width: 1px; } */ "}) (defroutes my-app (GET "/" index-page) (GET "/items" items-page) (GET "/item/:id" item-page) (GET "/about" about-page) (GET "/stylesheet/app.css" stylesheet-page) (ANY "*" (page-not-found))) (comment ;; execute the next form to run the server (defserver *jetty* {:port 8080} "/*" (servlet my-app)) (start *jetty*) ;; execute to stop the server (stop *jetty*) )
null
https://raw.githubusercontent.com/kyleburton/sandbox/cccbcc9a97026336691063a0a7eb59293a35c31a/clojure-utils/kburton-clojure-utils/src/main/clj/com/github/kyleburton/sandbox/compojure.clj
clojure
// separate execute the next form to run the server execute to stop the server
(ns com.github.kyleburton.sandbox.compojure (:use compojure)) (defn resource-link [lnk] (format "%s?%s" lnk (.getTime (java.util.Date.)))) (defmacro mresource-link [lnk] (format "%s?%s" lnk (.getTime (java.util.Date.)))) (defn template-page [request title & body] (let [title (str "Compojure App - " title)] (html [:head [:title title] [:link {:href (mresource-link "/stylesheet/app.css") :rel "stylesheet" :type "text/css"}]] [:div {:id "header"} [:h1 title]] (if-let [flash (-> request :mailx-params :flash)] [:div {:id "flash"} flash]) [:div {:id "main-body"} body] [:div {:id "footer"} [:a {:href "/"} "Home"] " | " [:a {:href "/items"} "Items"] " | " [:a {:href "/about"} "About"] " | " [:a {:href ""} "Compojure"]]))) (defn index-page [request] (template-page request "Home" [:div "Welcome."])) (defn xlink-to [text controller & params] [:a {:href (format "/%s/%s" (name controller) (first params))} text]) (defn items-page [request] (template-page request "Items" [:div "Items."] [:ul (for [item-id (range 10)] [:li (xlink-to (str "Item: " item-id) :item item-id)])])) (defn item-page [request] (let [item-id (-> request :route-params :id)] (template-page request (str "Item: " item-id) [:div "Item: " item-id] [:div "Request: " [:table {:id "session-dump"} [:tr [:th "Key"] [:th "Value"] (map (fn [key] [:tr [:td key] [:td (request key)]]) (keys request))]]]))) (defn about-page [request] (template-page request "About" [:div "This is a " [:a {:href ""} "Compojure"] " application."])) (defn stylesheet-page [request] {:status 200 :headers { "Content-Type" "text/css" } :body " body { } #main-body { } #header { } #footer { } /* #session-dump { } #session-dump td { } */ "}) (defroutes my-app (GET "/" index-page) (GET "/items" items-page) (GET "/item/:id" item-page) (GET "/about" about-page) (GET "/stylesheet/app.css" stylesheet-page) (ANY "*" (page-not-found))) (comment (defserver *jetty* {:port 8080} "/*" (servlet my-app)) (start *jetty*) (stop *jetty*) )
321f66932ca023da6b35c7418775e9f70b3fe3ea9363baf31849f1449270d92a
opencog/pln
icl.scm
;; Contain the main inference control meta-learning experiment loop ;; Load utils (load "icl-parameters.scm") (load "icl-utilities.scm") (load "mk-history.scm") (load "mk-control-rules.scm") (load "mine-control-rules.scm") ;; Set the random seed of the experiment (cog-randgen-set-seed! 1) ;; Set loggers levels (cog-logger-set-level! "info") (icl-logger-set-level! "info") (ure-logger-set-level! "info") ;; Set loggers stdout ;; (cog-logger-set-stdout! #t) (icl-logger-set-stdout! #t) ;; (ure-logger-set-stdout! #t) ;; Set loggers sync (for debugging) (cog-logger-set-sync! #t) (icl-logger-set-sync! #t) (ure-logger-set-sync! #t) ;; Clear and reload the kb and rb (define (reload) (clear) (load "kb.scm") (load "pln-rb.scm")) AtomSpace containing the targets in there to no forget them (define targets-as (cog-new-atomspace)) (define (run-experiment) (icl-logger-info "Start experiment") Switch to targets - as (targets (gen-random-targets pss))) ; Generate targets Switch back to the default atomspace (cog-set-atomspace! default-as) ;; Run all iterations (map (lambda (i) (run-iteration targets i)) (iota niter)))) ;; Run iteration i over the given targets and return the list of ;; solved problems. (define (run-iteration targets i) (icl-logger-info "Run iteration (i=~a/~a)" (+ i 1) niter) Run the BC and build the inference history corpus for that run (run (lambda (j) Target (trg (list-ref targets j)) Run the BC , return a pair with produced ;; history and result (true or false) (result (run-bc-mk-history trg i j))) result))) (histories-results (map run (iota pss))) (histories (map car histories-results)) (results (map cdr histories-results)) (sol_count (count values results))) (icl-logger-info "Number of solved problems = ~a/~a" sol_count pss) ;; Copy all atomspaces for histories to history-as (icl-logger-info "Move all problem histories to history-as") (union-as history-as histories) ;; Remove dangling atoms from history-as. These are produced due ;; to alpha-conversion. It creates inconsistencies, see . It 's not too ;; harmful for now but it will have to be remedied at some point. (icl-logger-info "Remove dangling atoms from history-as") (remove-dangling-atoms history-as) ;; Build inference control rules for the next iteration (icl-logger-info "Build inference control rules from history-as") (mk-control-rules) ;; Return results for each problem results)) ;; Run the backward chainer on the given target, postprocess its trace ;; and fill an history atomspace with it. Return a pair with history as first element and the result of running the BC ( true or false ) . (define (run-bc-mk-history target i j) (let* ((trace-as (cog-new-atomspace)) (result (run-bc target i j trace-as)) (history-as (mk-history trace-as))) (cons history-as result))) Run the backward chainer on target , given the atomspace where to ;; record the inference traces, trace-as, and inference-control rules used for guidance , ic - rules , with for jth target in iteration ;; i. Return #t iff target has been successfully proved. (define (run-bc target i j trace-as) (icl-logger-info "Run BC (i=~a/~a,j=~a/~a) with target:\n~a" (+ i 1) niter (+ j 1) pss target) (reload) (let* ((result (pln-bc target #:trace-as trace-as #:control-as control-as)) (result-size (length (cog-outgoing-set result))) (success (if (= 1 result-size) (tv->bool (cog-tv (gar result))) #f))) (icl-logger-info (if success "Success" "Failure")) success)) (run-experiment)
null
https://raw.githubusercontent.com/opencog/pln/52dc099e21393892cf5529fef687a69682436b2d/examples/pln/inference-control-meta-learning/icl.scm
scheme
Contain the main inference control meta-learning experiment loop Load utils Set the random seed of the experiment Set loggers levels Set loggers stdout (cog-logger-set-stdout! #t) (ure-logger-set-stdout! #t) Set loggers sync (for debugging) Clear and reload the kb and rb Generate targets Run all iterations Run iteration i over the given targets and return the list of solved problems. history and result (true or false) Copy all atomspaces for histories to history-as Remove dangling atoms from history-as. These are produced due to alpha-conversion. It creates inconsistencies, see harmful for now but it will have to be remedied at some point. Build inference control rules for the next iteration Return results for each problem Run the backward chainer on the given target, postprocess its trace and fill an history atomspace with it. Return a pair with history record the inference traces, trace-as, and inference-control rules i. Return #t iff target has been successfully proved.
(load "icl-parameters.scm") (load "icl-utilities.scm") (load "mk-history.scm") (load "mk-control-rules.scm") (load "mine-control-rules.scm") (cog-randgen-set-seed! 1) (cog-logger-set-level! "info") (icl-logger-set-level! "info") (ure-logger-set-level! "info") (icl-logger-set-stdout! #t) (cog-logger-set-sync! #t) (icl-logger-set-sync! #t) (ure-logger-set-sync! #t) (define (reload) (clear) (load "kb.scm") (load "pln-rb.scm")) AtomSpace containing the targets in there to no forget them (define targets-as (cog-new-atomspace)) (define (run-experiment) (icl-logger-info "Start experiment") Switch to targets - as Switch back to the default atomspace (cog-set-atomspace! default-as) (map (lambda (i) (run-iteration targets i)) (iota niter)))) (define (run-iteration targets i) (icl-logger-info "Run iteration (i=~a/~a)" (+ i 1) niter) Run the BC and build the inference history corpus for that run (run (lambda (j) Target (trg (list-ref targets j)) Run the BC , return a pair with produced (result (run-bc-mk-history trg i j))) result))) (histories-results (map run (iota pss))) (histories (map car histories-results)) (results (map cdr histories-results)) (sol_count (count values results))) (icl-logger-info "Number of solved problems = ~a/~a" sol_count pss) (icl-logger-info "Move all problem histories to history-as") (union-as history-as histories) . It 's not too (icl-logger-info "Remove dangling atoms from history-as") (remove-dangling-atoms history-as) (icl-logger-info "Build inference control rules from history-as") (mk-control-rules) results)) as first element and the result of running the BC ( true or false ) . (define (run-bc-mk-history target i j) (let* ((trace-as (cog-new-atomspace)) (result (run-bc target i j trace-as)) (history-as (mk-history trace-as))) (cons history-as result))) Run the backward chainer on target , given the atomspace where to used for guidance , ic - rules , with for jth target in iteration (define (run-bc target i j trace-as) (icl-logger-info "Run BC (i=~a/~a,j=~a/~a) with target:\n~a" (+ i 1) niter (+ j 1) pss target) (reload) (let* ((result (pln-bc target #:trace-as trace-as #:control-as control-as)) (result-size (length (cog-outgoing-set result))) (success (if (= 1 result-size) (tv->bool (cog-tv (gar result))) #f))) (icl-logger-info (if success "Success" "Failure")) success)) (run-experiment)
b607a38c15801a72646aeb7c15fc2c4f6eda53942638b6434d89e24f7ecc57de
ghc/testsuite
TcCoercibleFail3.hs
# LANGUAGE RoleAnnotations , RankNTypes , ScopedTypeVariables # import GHC.Prim (coerce, Coercible) newtype List a = List [a] data T f = T (f Int) newtype NT1 a = NT1 (a -> Int) newtype NT2 a = NT2 (a -> Int) foo :: T NT1 -> T NT2 foo = coerce main = return ()
null
https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_fail/TcCoercibleFail3.hs
haskell
# LANGUAGE RoleAnnotations , RankNTypes , ScopedTypeVariables # import GHC.Prim (coerce, Coercible) newtype List a = List [a] data T f = T (f Int) newtype NT1 a = NT1 (a -> Int) newtype NT2 a = NT2 (a -> Int) foo :: T NT1 -> T NT2 foo = coerce main = return ()
ce65b87703b7ca04d7734db29938a72fc5cb10161105ed0ae16e558d74299a1c
jorgetavares/core-gp
evaluation.lisp
(in-package #:core-gp) ;;; ;;; classes ;;; ;; ;; fitness values (defclass fitness () ((raw-score :initarg :raw-score :initform nil :accessor raw-score :documentation "Value obtained from the evaluation function.") (fitness-score :accessor fitness-score :documentation "Scaled value of raw-score."))) (defmethod initialize-instance :after ((fitness fitness) &key scaling-function) (setf (slot-value fitness 'fitness-score) (if scaling-function (funcall scaling-function (slot-value fitness 'raw-score)) (slot-value fitness 'raw-score)))) (defun make-fitness (fitness-type &key raw-score scaling-function) "Create an empty of filled fitness." (if raw-score (if scaling-function (make-instance fitness-type :raw-score raw-score :scaling-function scaling-function) (make-instance fitness-type :raw-score raw-score)) (make-instance fitness-type))) (defmethod copy ((fitness fitness)) (let ((copy (make-instance 'fitness :raw-score (raw-score fitness)))) (setf (fitness-score copy) (fitness-score fitness)) copy)) (defmethod print-object ((object fitness) stream) (print-unreadable-object (object stream :type t) (with-slots (raw-score fitness-score) object (format stream "raw-score: ~a fitness-score: ~a" raw-score fitness-score)))) ;;; ;;; methods ;;; ;; ;; fitness values (defgeneric set-fitness (fitness raw-score evaluation-config) (:documentation "Set fitness. Compute its scaled value if scaling is set.")) (defmethod set-fitness ((fitness fitness) raw-score (config evaluation-config)) (setf (raw-score fitness) raw-score)) (defmethod set-fitness :after ((fitness fitness) raw-score (config evaluation-config)) (setf (fitness-score fitness) (if (scaling-p config) (funcall (scaling-function config) raw-score) raw-score))) ;; ;; genome (defgeneric evaluate-genome (genome evaluation-config) (:documentation "Evaluate a genome.")) (defmethod evaluate-genome ((genome genome) (config evaluation-config)) (if (mapping-function config) (funcall (evaluation-function config) (funcall (mapping-function config) (chromossome genome))) (funcall (evaluation-function config) (chromossome genome)))) ;; ;; individual (defgeneric evaluate-individual (individual evaluation-config) (:documentation "Evaluate an individual.")) (defmethod evaluate-individual ((individual individual) (config evaluation-config)) (when (eval-p individual) (set-fitness (fitness individual) (evaluate-genome (genome individual) config) config) (setf (eval-p individual) nil))) ;; ;; population (defgeneric evaluate-population (population evaluation-config) (:documentation "Evaluate a population.")) (defmethod evaluate-population ((population population) (config evaluation-config)) (funcall (population-evaluator config) population config)) (defgeneric normal-evaluation (poplation config) (:documentation "Standard pop evaluation.")) (defmethod normal-evaluation ((population population) (config evaluation-config)) (loop for individual across (individuals population) do (evaluate-individual individual config))) ;;; ;;; scaling functions ;;; (defun linear-scaling (max-size) "Scales the raw fitness between 0 and 1." #'(lambda (raw-fitness) (/ raw-fitness max-size)))
null
https://raw.githubusercontent.com/jorgetavares/core-gp/90ec1c4599a19c5a911be1f703f78d5108aee160/src/evaluation.lisp
lisp
classes fitness values methods fitness values genome individual population scaling functions
(in-package #:core-gp) (defclass fitness () ((raw-score :initarg :raw-score :initform nil :accessor raw-score :documentation "Value obtained from the evaluation function.") (fitness-score :accessor fitness-score :documentation "Scaled value of raw-score."))) (defmethod initialize-instance :after ((fitness fitness) &key scaling-function) (setf (slot-value fitness 'fitness-score) (if scaling-function (funcall scaling-function (slot-value fitness 'raw-score)) (slot-value fitness 'raw-score)))) (defun make-fitness (fitness-type &key raw-score scaling-function) "Create an empty of filled fitness." (if raw-score (if scaling-function (make-instance fitness-type :raw-score raw-score :scaling-function scaling-function) (make-instance fitness-type :raw-score raw-score)) (make-instance fitness-type))) (defmethod copy ((fitness fitness)) (let ((copy (make-instance 'fitness :raw-score (raw-score fitness)))) (setf (fitness-score copy) (fitness-score fitness)) copy)) (defmethod print-object ((object fitness) stream) (print-unreadable-object (object stream :type t) (with-slots (raw-score fitness-score) object (format stream "raw-score: ~a fitness-score: ~a" raw-score fitness-score)))) (defgeneric set-fitness (fitness raw-score evaluation-config) (:documentation "Set fitness. Compute its scaled value if scaling is set.")) (defmethod set-fitness ((fitness fitness) raw-score (config evaluation-config)) (setf (raw-score fitness) raw-score)) (defmethod set-fitness :after ((fitness fitness) raw-score (config evaluation-config)) (setf (fitness-score fitness) (if (scaling-p config) (funcall (scaling-function config) raw-score) raw-score))) (defgeneric evaluate-genome (genome evaluation-config) (:documentation "Evaluate a genome.")) (defmethod evaluate-genome ((genome genome) (config evaluation-config)) (if (mapping-function config) (funcall (evaluation-function config) (funcall (mapping-function config) (chromossome genome))) (funcall (evaluation-function config) (chromossome genome)))) (defgeneric evaluate-individual (individual evaluation-config) (:documentation "Evaluate an individual.")) (defmethod evaluate-individual ((individual individual) (config evaluation-config)) (when (eval-p individual) (set-fitness (fitness individual) (evaluate-genome (genome individual) config) config) (setf (eval-p individual) nil))) (defgeneric evaluate-population (population evaluation-config) (:documentation "Evaluate a population.")) (defmethod evaluate-population ((population population) (config evaluation-config)) (funcall (population-evaluator config) population config)) (defgeneric normal-evaluation (poplation config) (:documentation "Standard pop evaluation.")) (defmethod normal-evaluation ((population population) (config evaluation-config)) (loop for individual across (individuals population) do (evaluate-individual individual config))) (defun linear-scaling (max-size) "Scales the raw fitness between 0 and 1." #'(lambda (raw-fitness) (/ raw-fitness max-size)))
818888599d836d858d80f28dc8aacb3060a8deecd10cd5fd3523c68b84d2bc75
KaroshiBee/weevil
mdb_traced_interpreter.mli
open Mdb_import.Tez type t type cfg_t (* old cfg *) val make_log : Ctxt.context -> Tezos_micheline.Micheline_parser.location -> ('a * 's) -> ('a, 's) Prot.Script_typed_ir.stack_ty -> cfg_t (* old cfg *) val unparsing_mode : Prot.Script_ir_unparser.unparsing_mode (* old cfg *) TODO why err.tzresult ? val unparse_stack : cfg_t -> (Ctxt.Script.expr * string option * bool) list Err.tzresult Lwt.t (* old cfg *) val get_loc : cfg_t -> Tezos_micheline.Micheline_parser.location (* old cfg *) val get_gas : cfg_t -> Ctxt.Gas.t (* old interp.trace_interp *) val make : in_channel:in_channel -> out_channel:out_channel -> Mdb_michelson.File_locations.locs -> t old interp.execute without interp ctor function TODO why err.tzresult ? val execute : Ctxt.context -> Prot.Script_typed_ir.step_constants -> script:Ctxt.Script.t -> entrypoint:Ctxt.Entrypoint.t -> parameter:Ctxt.Script.expr -> interp:t -> (Prot.Script_interpreter.execution_result * Ctxt.context) Err.tzresult Lwt.t
null
https://raw.githubusercontent.com/KaroshiBee/weevil/8565bf833db5114654495b361db5a4d53879e48b/bin/weevil_mdb_015/src/mdb_traced_interpreter.mli
ocaml
old cfg old cfg old cfg old cfg old cfg old interp.trace_interp
open Mdb_import.Tez type t type cfg_t val make_log : Ctxt.context -> Tezos_micheline.Micheline_parser.location -> ('a * 's) -> ('a, 's) Prot.Script_typed_ir.stack_ty -> cfg_t val unparsing_mode : Prot.Script_ir_unparser.unparsing_mode TODO why err.tzresult ? val unparse_stack : cfg_t -> (Ctxt.Script.expr * string option * bool) list Err.tzresult Lwt.t val get_loc : cfg_t -> Tezos_micheline.Micheline_parser.location val get_gas : cfg_t -> Ctxt.Gas.t val make : in_channel:in_channel -> out_channel:out_channel -> Mdb_michelson.File_locations.locs -> t old interp.execute without interp ctor function TODO why err.tzresult ? val execute : Ctxt.context -> Prot.Script_typed_ir.step_constants -> script:Ctxt.Script.t -> entrypoint:Ctxt.Entrypoint.t -> parameter:Ctxt.Script.expr -> interp:t -> (Prot.Script_interpreter.execution_result * Ctxt.context) Err.tzresult Lwt.t
31cddaeb5267e5d7c4e98d3f16736e1867c7232ba545131e2a7a93fc7c79f768
boxer-project/boxer-sunrise
loader-tests.lisp
(in-package :boxer-sunrise-test) (plan nil) (let ((boxer::*supress-graphics-recording?* t) (boxer::*draw-status-line* nil) (henri-sun-v5 (merge-pathnames "data/boxfiles-v5/henri-sun-v5.box" (make-pathname :directory (pathname-directory *load-truename*))))) ;; Ensure this is the actual original bits, and has never been resaved ;; and updated/fixed as part of the save process. (is "24C084326289A1021BB0EF266838EF00" (with-output-to-string (str) (loop for x across (md5:md5sum-file henri-sun-v5) do (format str "~2,'0X" x)))) (is t (boxer:data-box? (boxer::load-binary-box-internal henri-sun-v5))) ) (finalize)
null
https://raw.githubusercontent.com/boxer-project/boxer-sunrise/922bd8d476ed4780b98476a93916d34d0f61c90c/tests/loader-tests.lisp
lisp
Ensure this is the actual original bits, and has never been resaved and updated/fixed as part of the save process.
(in-package :boxer-sunrise-test) (plan nil) (let ((boxer::*supress-graphics-recording?* t) (boxer::*draw-status-line* nil) (henri-sun-v5 (merge-pathnames "data/boxfiles-v5/henri-sun-v5.box" (make-pathname :directory (pathname-directory *load-truename*))))) (is "24C084326289A1021BB0EF266838EF00" (with-output-to-string (str) (loop for x across (md5:md5sum-file henri-sun-v5) do (format str "~2,'0X" x)))) (is t (boxer:data-box? (boxer::load-binary-box-internal henri-sun-v5))) ) (finalize)
46f9dc6d3913901535293ee83a9aeff93f04d04f99c6df42e81c4914e7f1decf
jfeser/L2
library.mli
open Core type t = { exprs: (string * Expr.t) list ; expr_ctx: Expr.t String.Map.t ; value_ctx: Value.t String.Map.t ; exprvalue_ctx: ExprValue.t String.Map.t ; type_ctx: Infer.Type.t String.Map.t ; builtins: Expr.Op.t list } val empty : t val from_channel_exn : file:string -> In_channel.t -> t val from_channel : file:string -> In_channel.t -> t Or_error.t val from_file_exn : string -> t val from_file : string -> t Or_error.t val filter_keys : t -> f:(string -> bool) -> t
null
https://raw.githubusercontent.com/jfeser/L2/a66659c7d75f75788c48a17b531045fb3d5f8351/lib/library.mli
ocaml
open Core type t = { exprs: (string * Expr.t) list ; expr_ctx: Expr.t String.Map.t ; value_ctx: Value.t String.Map.t ; exprvalue_ctx: ExprValue.t String.Map.t ; type_ctx: Infer.Type.t String.Map.t ; builtins: Expr.Op.t list } val empty : t val from_channel_exn : file:string -> In_channel.t -> t val from_channel : file:string -> In_channel.t -> t Or_error.t val from_file_exn : string -> t val from_file : string -> t Or_error.t val filter_keys : t -> f:(string -> bool) -> t
504797739e0f4b357ca388cd03c7651a444486be08c6eb6f65be9d005dd42cff
lexi-lambda/clojure-fuzzy-urls
lens.clj
(ns fuzzy-urls.lens (:require [fuzzy-urls.url :refer :all])) (declare fuzzy-equal?) (defrecord UrlLens [scheme-fn user-fn host-fn port-fn path-fn query-fn fragment-fn] ; lenses are applicable clojure.lang.IFn ; they're also auto-curried for use in filter and similar functions (invoke [this a] (fn [b] (this a b))) (invoke [this a b] (fuzzy-equal? this a b)) ; this is required for implementing IFn properly (applyTo [this args] (clojure.lang.AFn/applyToHelper this args))) ; General lenses and lens constructors ; ----------------------------------------------------------------------------- (defn ignore "A simple lens that ignores its arguments and always returns true." [& _] true) (defn exact "A simple lens that performs exact equality on its arguments." [& args] (apply = args)) (defn in-set "A lens constructor that produces a lens that checks if its two arguments exist within the same set." [sets] (fn [a b] ; get all the sets that contain a... (let [relevant-sets (filter #(contains? % a) sets)] ; ...then check if any of them contain b (boolean (some #(contains? % b) relevant-sets))))) Convenience lenses ; ----------------------------------------------------------------------------- (def common-schemes "A lens that detects common similar schemes, such as HTTP and HTTPS." (in-set #{#{"http" "https"} #{"ws" "wss"}})) ; ----------------------------------------------------------------------------- (defn build-url-lens "Creates a fuzzy url lens, using default values for unprovided lenses." [& {:keys [scheme user host port path query fragment] :or {scheme common-schemes user ignore host exact port exact path exact query exact fragment ignore}}] (->UrlLens scheme user host port path query fragment)) (defn fuzzy-equal? [lens a b] {:pre [(instance? UrlLens lens) (url? a) (url? b)]} (boolean (and ((:scheme-fn lens) (:scheme a) (:scheme b)) ((:user-fn lens) (:user a) (:user b)) ((:host-fn lens) (:host a) (:host b)) ((:port-fn lens) (:port a) (:port b)) ((:path-fn lens) (:path a) (:path b)) ((:query-fn lens) (:query a) (:query b)) ((:fragment-fn lens) (:fragment a) (:fragment b)))))
null
https://raw.githubusercontent.com/lexi-lambda/clojure-fuzzy-urls/4a4cd81476d016634cedb3073ab201f8cbc0b606/src/fuzzy_urls/lens.clj
clojure
lenses are applicable they're also auto-curried for use in filter and similar functions this is required for implementing IFn properly General lenses and lens constructors ----------------------------------------------------------------------------- get all the sets that contain a... ...then check if any of them contain b ----------------------------------------------------------------------------- -----------------------------------------------------------------------------
(ns fuzzy-urls.lens (:require [fuzzy-urls.url :refer :all])) (declare fuzzy-equal?) (defrecord UrlLens [scheme-fn user-fn host-fn port-fn path-fn query-fn fragment-fn] clojure.lang.IFn (invoke [this a] (fn [b] (this a b))) (invoke [this a b] (fuzzy-equal? this a b)) (applyTo [this args] (clojure.lang.AFn/applyToHelper this args))) (defn ignore "A simple lens that ignores its arguments and always returns true." [& _] true) (defn exact "A simple lens that performs exact equality on its arguments." [& args] (apply = args)) (defn in-set "A lens constructor that produces a lens that checks if its two arguments exist within the same set." [sets] (fn [a b] (let [relevant-sets (filter #(contains? % a) sets)] (boolean (some #(contains? % b) relevant-sets))))) Convenience lenses (def common-schemes "A lens that detects common similar schemes, such as HTTP and HTTPS." (in-set #{#{"http" "https"} #{"ws" "wss"}})) (defn build-url-lens "Creates a fuzzy url lens, using default values for unprovided lenses." [& {:keys [scheme user host port path query fragment] :or {scheme common-schemes user ignore host exact port exact path exact query exact fragment ignore}}] (->UrlLens scheme user host port path query fragment)) (defn fuzzy-equal? [lens a b] {:pre [(instance? UrlLens lens) (url? a) (url? b)]} (boolean (and ((:scheme-fn lens) (:scheme a) (:scheme b)) ((:user-fn lens) (:user a) (:user b)) ((:host-fn lens) (:host a) (:host b)) ((:port-fn lens) (:port a) (:port b)) ((:path-fn lens) (:path a) (:path b)) ((:query-fn lens) (:query a) (:query b)) ((:fragment-fn lens) (:fragment a) (:fragment b)))))
ba7cfb9034aa216ed68f8127dd97bafb772095a325848ca3e66ad426ada97b5c
axolotl-lang/axolotl
FunctionDef.hs
module Analyser.Analysers.FunctionDef where import Analyser.Util ( AnalyserResult, Def (Argument, Function, IncompleteFunction), Env, getTypeOfExpr, hUnion, hUnion', isFnCall, makeLeft, ) import Control.Monad.State ( MonadIO (liftIO), MonadState (get), StateT (runStateT), modify, ) import Data.Bifunctor (Bifunctor (first, second)) import Data.Either.Combinators (fromRight') import qualified Data.HashTable.IO as H import qualified Data.Text as T import Parser.Ast (Expr (FunctionDef, Nil), VDataType (Inferred)) In case of a , the things we need to check for are : * whether something with the same name has already been defined . this is not possible because redefinitions are not allowed . * whether the function return type is not explicitly defined but the return value is a call to the same function . this is not possible because it 's impossible to determine the return type . * whether the regular analyseExprs check on all Exprs of the function body succeeds . * whether the actual return type of the function is the same as the expected return type in case the return type was explicitly defined by the user . In case it was n't explicitly defined , the type of the value being returned is automatically the inferred return type of the function . In case of a FunctionDef, the things we need to check for are: * whether something with the same name has already been defined. this is not possible because redefinitions are not allowed. * whether the function return type is not explicitly defined but the return value is a call to the same function. this is not possible because it's impossible to determine the return type. * whether the regular analyseExprs check on all Exprs of the function body succeeds. * whether the actual return type of the function is the same as the expected return type in case the return type was explicitly defined by the user. In case it wasn't explicitly defined, the type of the value being returned is automatically the inferred return type of the function. -} type AnalyseExprsFn = StateT Env IO AnalyserResult -> Expr -> StateT Env IO AnalyserResult analyseFunctionDef :: AnalyserResult -> AnalyseExprsFn -> T.Text -> VDataType -> ([(T.Text, VDataType)], Bool) -> [Expr] -> Bool -> StateT Env IO AnalyserResult acc : : [ Either Text Expr ] - > the resultant accumulator for analyseExprs analyseExprs : : AnalyseExprsFn - > the analyseExprs function from Analyser.hs -- name :: Text -> the name of the function vtype : : > data type of the return value of the function args : : ( [ ( Text , VDataType ) ] , ) - > the arguments expected to be passed to the function body : : [ Expr ] - > the Exprs that make up the function body ; last expr is returned native : : > whether the function is a native function analyseFunctionDef acc analyseExprs name vtype args body native = do env <- get -- lookup name in global defs (gd) v <- liftIO $ H.lookup (fst env) name case v of Just _ -> pure $ makeLeft $ "Redefinition of function " <> name -- Nothing -> do h1 <- liftIO $ H.newSized 500 h2 <- liftIO $ H.newSized 500 There are two extra things we need to be able to refer to compared -- to the definitions previously made (global definitions -- fst env) -- First is the function itself , since we should be able to make recursive calls . For this purpose we add an IncompleteFunction , -- which essentially is Function but without the body, since we -- don't need it here. At the end, this will be replaced by the proper Function Def , while this allows us to be able to use -- recursive calls without getting "undefined function" errors. -- Second is the set of arguments that the function receives . TODO fix redef bug , arguments need to shadow prev . -- We just add the Argument Def to global defs here. During -- a function call, the Evaluator can union the global defs -- with the actual value that was passed during the call. -- To add these two , we use hUnion ' that adds all elements of a list to a hashtable . let v = [(name, IncompleteFunction args vtype native)] <> map (second Argument) (fst args) liftIO $ hUnion' v (fst env) liftIO $ fst env `hUnion` h1 -- analyse body using analyseExprs result <- liftIO $ runStateT (foldl analyseExprs (pure []) body) (h1, h2) the to be returned from the function let re = if null body then Nil else last body -- whether the return type was unspecified let inferred = vtype == Inferred -- we now add the definitions made inside of our function -- body to a hashtable v' and get the type of it in reType. reType <- liftIO $ getTypeOfExpr re h1 -- if the last Expr in the function body is a call to -- itself (a recursive call), we have no way of knowing -- what the return type should be, so make it a Left if -- that is the case. let reType' = if isFnCall name re && inferred then Left $ "cannot infer the return type of function '" <> name <> "' that returns a call to itself" else reType case reType' of Left err -> pure $ makeLeft err -- Right dvdt -> do -- We can now add the Function as a Def to our global defs, overwriting the previous IncompleteFunction def . let fn = Analyser.Util.Function (if inferred then dvdt else vtype) args body native liftIO $ H.insert (fst env) name fn -- We also need to add the definitions made inside this function to the local defs ( snd env ) . v' <- liftIO $ [(name, fn)] `hUnion'` (fst . snd) result liftIO $ H.insert (snd env) name v' -- we can now use `sequence` to convert out [Either Text Expr] -- into Either Text [Expr] and add the result to our accumulator. let res = acc <> [ sequence (fst result) >>= \v -> Right $ FunctionDef name dvdt args v native ] -- check if the user explicitly defined a return type -- for this function, but returned a value of a different -- type. doesn't matter if type not explicitly defined. -- also ignore if the function is a native function -- since the body in axl can't be used to determine -- it's return type since the body will be a placeholder if inferred || (vtype == dvdt) || native then pure res else pure $ makeLeft $ "Expected function '" <> name <> "' to return " <> (T.toLower . T.pack . show) vtype <> ", instead got " <> (T.toLower . T.pack . show) dvdt
null
https://raw.githubusercontent.com/axolotl-lang/axolotl/4ce1b95827fac791dbe6e30fe48d3aa3c3740cae/src/Analyser/Analysers/FunctionDef.hs
haskell
name :: Text -> the name of the function lookup name in global defs (gd) to the definitions previously made (global definitions -- fst env) which essentially is Function but without the body, since we don't need it here. At the end, this will be replaced by the recursive calls without getting "undefined function" errors. We just add the Argument Def to global defs here. During a function call, the Evaluator can union the global defs with the actual value that was passed during the call. analyse body using analyseExprs whether the return type was unspecified we now add the definitions made inside of our function body to a hashtable v' and get the type of it in reType. if the last Expr in the function body is a call to itself (a recursive call), we have no way of knowing what the return type should be, so make it a Left if that is the case. We can now add the Function as a Def to our global defs, We also need to add the definitions made inside this we can now use `sequence` to convert out [Either Text Expr] into Either Text [Expr] and add the result to our accumulator. check if the user explicitly defined a return type for this function, but returned a value of a different type. doesn't matter if type not explicitly defined. also ignore if the function is a native function since the body in axl can't be used to determine it's return type since the body will be a placeholder
module Analyser.Analysers.FunctionDef where import Analyser.Util ( AnalyserResult, Def (Argument, Function, IncompleteFunction), Env, getTypeOfExpr, hUnion, hUnion', isFnCall, makeLeft, ) import Control.Monad.State ( MonadIO (liftIO), MonadState (get), StateT (runStateT), modify, ) import Data.Bifunctor (Bifunctor (first, second)) import Data.Either.Combinators (fromRight') import qualified Data.HashTable.IO as H import qualified Data.Text as T import Parser.Ast (Expr (FunctionDef, Nil), VDataType (Inferred)) In case of a , the things we need to check for are : * whether something with the same name has already been defined . this is not possible because redefinitions are not allowed . * whether the function return type is not explicitly defined but the return value is a call to the same function . this is not possible because it 's impossible to determine the return type . * whether the regular analyseExprs check on all Exprs of the function body succeeds . * whether the actual return type of the function is the same as the expected return type in case the return type was explicitly defined by the user . In case it was n't explicitly defined , the type of the value being returned is automatically the inferred return type of the function . In case of a FunctionDef, the things we need to check for are: * whether something with the same name has already been defined. this is not possible because redefinitions are not allowed. * whether the function return type is not explicitly defined but the return value is a call to the same function. this is not possible because it's impossible to determine the return type. * whether the regular analyseExprs check on all Exprs of the function body succeeds. * whether the actual return type of the function is the same as the expected return type in case the return type was explicitly defined by the user. In case it wasn't explicitly defined, the type of the value being returned is automatically the inferred return type of the function. -} type AnalyseExprsFn = StateT Env IO AnalyserResult -> Expr -> StateT Env IO AnalyserResult analyseFunctionDef :: AnalyserResult -> AnalyseExprsFn -> T.Text -> VDataType -> ([(T.Text, VDataType)], Bool) -> [Expr] -> Bool -> StateT Env IO AnalyserResult acc : : [ Either Text Expr ] - > the resultant accumulator for analyseExprs analyseExprs : : AnalyseExprsFn - > the analyseExprs function from Analyser.hs vtype : : > data type of the return value of the function args : : ( [ ( Text , VDataType ) ] , ) - > the arguments expected to be passed to the function body : : [ Expr ] - > the Exprs that make up the function body ; last expr is returned native : : > whether the function is a native function analyseFunctionDef acc analyseExprs name vtype args body native = do env <- get v <- liftIO $ H.lookup (fst env) name case v of Just _ -> pure $ makeLeft $ "Redefinition of function " <> name Nothing -> do h1 <- liftIO $ H.newSized 500 h2 <- liftIO $ H.newSized 500 There are two extra things we need to be able to refer to compared First is the function itself , since we should be able to make recursive calls . For this purpose we add an IncompleteFunction , proper Function Def , while this allows us to be able to use Second is the set of arguments that the function receives . TODO fix redef bug , arguments need to shadow prev . To add these two , we use hUnion ' that adds all elements of a list to a hashtable . let v = [(name, IncompleteFunction args vtype native)] <> map (second Argument) (fst args) liftIO $ hUnion' v (fst env) liftIO $ fst env `hUnion` h1 result <- liftIO $ runStateT (foldl analyseExprs (pure []) body) (h1, h2) the to be returned from the function let re = if null body then Nil else last body let inferred = vtype == Inferred reType <- liftIO $ getTypeOfExpr re h1 let reType' = if isFnCall name re && inferred then Left $ "cannot infer the return type of function '" <> name <> "' that returns a call to itself" else reType case reType' of Left err -> pure $ makeLeft err Right dvdt -> do overwriting the previous IncompleteFunction def . let fn = Analyser.Util.Function (if inferred then dvdt else vtype) args body native liftIO $ H.insert (fst env) name fn function to the local defs ( snd env ) . v' <- liftIO $ [(name, fn)] `hUnion'` (fst . snd) result liftIO $ H.insert (snd env) name v' let res = acc <> [ sequence (fst result) >>= \v -> Right $ FunctionDef name dvdt args v native ] if inferred || (vtype == dvdt) || native then pure res else pure $ makeLeft $ "Expected function '" <> name <> "' to return " <> (T.toLower . T.pack . show) vtype <> ", instead got " <> (T.toLower . T.pack . show) dvdt
19d1adb4ddaed7bf3ca595bdc9205206775de488e0d0e0b6b41e7bc3a1affb67
exercism/ocaml
test.ml
open Base open OUnit2 open Robot_name let assert_matches_spec name = let is_valid_letter ch = Char.('A' <= ch && ch <= 'Z') in let is_valid_digit ch = Char.('0' <= ch && ch <= '9') in assert_equal ~printer:Int.to_string 5 (String.length name); assert_bool ("First character must be from A to Z") (is_valid_letter @@ name.[0]); assert_bool ("Second character must be from A to Z") (is_valid_letter @@ name.[1]); assert_bool ("Third character must be from 0 to 9") (is_valid_digit @@ name.[2]); assert_bool ("Fourth character must be from 0 to 9") (is_valid_digit @@ name.[3]); assert_bool ("Fifth character must be from 0 to 9") (is_valid_digit @@ name.[4]);; let basic_tests = [ "a robot has a name of 2 letters followed by 3 numbers" >:: (fun _ctxt -> let n = name (new_robot ()) in assert_matches_spec n ); "resetting a robot's name gives it a different name" >:: (fun _ctxt -> let r = new_robot () in let n1 = name r in reset r; let n2 = name r in assert_bool ("'" ^ n1 ^ "' was repeated") String.(n1 <> n2) ); "after reset the robot's name still matches the specification" >:: (fun _ctxt -> let r = new_robot () in reset r; let n = name r in assert_matches_spec n ); ] Optionally : make this test pass . There are 26 * 26 * 10 * 10 * 10 = 676,000 possible names . This test generates all possible names , and checks that there are no duplicates . It 's harder to make pass than the other tests , so it is left as optional . To enable it , uncomment the code in the run_test_tt_main line at the bottom of this module . Optionally: make this test pass. There are 26 * 26 * 10 * 10 * 10 = 676,000 possible Robot names. This test generates all possible Robot names, and checks that there are no duplicates. It's harder to make pass than the other tests, so it is left as optional. To enable it, uncomment the code in the run_test_tt_main line at the bottom of this module. *) let unique_name_tests = [ "all possible robot names are distinct" >:: (fun _ctxt -> let rs = Array.init (26 * 26 * 1000) ~f:(fun _ -> new_robot ()) in let empty = Set.empty (module String) in let (repeated, _) = Array.fold rs ~init:(empty, empty) ~f:(fun (repeated, seen) r -> let n = name r in if Set.mem seen n then (Set.add repeated n, seen) else (repeated, Set.add seen n) ) in let first_few_repeats = Array.sub (Set.to_array repeated) ~pos:0 ~len:(min 20 (Set.length repeated)) in let failure_message = "first few repeats: " ^ (String.concat_array first_few_repeats ~sep:",") in assert_bool failure_message (Set.is_empty repeated) ); ] let () = run_test_tt_main ("robot-name tests" >::: List.concat [basic_tests (* ; unique_name_tests *)])
null
https://raw.githubusercontent.com/exercism/ocaml/bfd6121f757817865a34db06c3188b5e0ccab518/exercises/practice/robot-name/test.ml
ocaml
; unique_name_tests
open Base open OUnit2 open Robot_name let assert_matches_spec name = let is_valid_letter ch = Char.('A' <= ch && ch <= 'Z') in let is_valid_digit ch = Char.('0' <= ch && ch <= '9') in assert_equal ~printer:Int.to_string 5 (String.length name); assert_bool ("First character must be from A to Z") (is_valid_letter @@ name.[0]); assert_bool ("Second character must be from A to Z") (is_valid_letter @@ name.[1]); assert_bool ("Third character must be from 0 to 9") (is_valid_digit @@ name.[2]); assert_bool ("Fourth character must be from 0 to 9") (is_valid_digit @@ name.[3]); assert_bool ("Fifth character must be from 0 to 9") (is_valid_digit @@ name.[4]);; let basic_tests = [ "a robot has a name of 2 letters followed by 3 numbers" >:: (fun _ctxt -> let n = name (new_robot ()) in assert_matches_spec n ); "resetting a robot's name gives it a different name" >:: (fun _ctxt -> let r = new_robot () in let n1 = name r in reset r; let n2 = name r in assert_bool ("'" ^ n1 ^ "' was repeated") String.(n1 <> n2) ); "after reset the robot's name still matches the specification" >:: (fun _ctxt -> let r = new_robot () in reset r; let n = name r in assert_matches_spec n ); ] Optionally : make this test pass . There are 26 * 26 * 10 * 10 * 10 = 676,000 possible names . This test generates all possible names , and checks that there are no duplicates . It 's harder to make pass than the other tests , so it is left as optional . To enable it , uncomment the code in the run_test_tt_main line at the bottom of this module . Optionally: make this test pass. There are 26 * 26 * 10 * 10 * 10 = 676,000 possible Robot names. This test generates all possible Robot names, and checks that there are no duplicates. It's harder to make pass than the other tests, so it is left as optional. To enable it, uncomment the code in the run_test_tt_main line at the bottom of this module. *) let unique_name_tests = [ "all possible robot names are distinct" >:: (fun _ctxt -> let rs = Array.init (26 * 26 * 1000) ~f:(fun _ -> new_robot ()) in let empty = Set.empty (module String) in let (repeated, _) = Array.fold rs ~init:(empty, empty) ~f:(fun (repeated, seen) r -> let n = name r in if Set.mem seen n then (Set.add repeated n, seen) else (repeated, Set.add seen n) ) in let first_few_repeats = Array.sub (Set.to_array repeated) ~pos:0 ~len:(min 20 (Set.length repeated)) in let failure_message = "first few repeats: " ^ (String.concat_array first_few_repeats ~sep:",") in assert_bool failure_message (Set.is_empty repeated) ); ] let () =
7ba2a064e5e0face96041b1c4af367eceaa5756864ada663e5a26324d01ca773
lehins/primal
Bench.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE BangPatterns #-} # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -fno - warn - orphans # module Main (main) where import GHC.Exts import Data.Proxy import Data.Typeable import Criterion.Main import Primal.Memory.Bytes import Primal.Memory.Ptr import qualified Data.Primitive.Types as BA import qualified Data.Primitive.ByteArray as BA import Foreign.Storable as S import Foreign.ForeignPtr import GHC.ForeignPtr import Control.DeepSeq instance NFData (ForeignPtr a) where rnf !_ = () main :: IO () main = do let n = 1000000 :: Count a n64 = n :: Count Word64 mb1 <- allocAlignedPinnedMBytes n64 mb2 <- allocAlignedPinnedMBytes n64 b1 <- freezeMBytes mb1 mba <- BA.newAlignedPinnedByteArray (unCountBytes (n :: Count Word64)) 8 ba <- BA.unsafeFreezeByteArray mba Ensure that arrays are equal by filling them with zeros mbaEq1 <- BA.newAlignedPinnedByteArray (unCountBytes (n :: Count Word64)) 8 mbaEq2 <- BA.newAlignedPinnedByteArray (unCountBytes (n :: Count Word64)) 8 BA.setByteArray mbaEq1 0 (unCount n64) (0 :: Word64) BA.setByteArray mbaEq2 0 (unCount n64) (0 :: Word64) defaultMain [ bgroup "ptr" [ env (freezeMBytes mb1) $ \b -> bench "(==) - isSameBytes" $ whnf (isSameBytes b) b , env (freezeMBytes mb1) $ \b -> bench "isSameBytes" $ whnf (isSameBytes b) (relaxPinnedBytes b) , env (freezeMBytes mb1) $ \b -> bench "isSamePinnedBytes" $ whnf (isSamePinnedBytes b) b , bench "(==) - sameByteArray (unexported)" $ whnf (ba ==) ba , bench "isSameMBytes" $ whnf (isSameMBytes mb1) mb1 , bench "sameMutableByteArray" $ whnf (BA.sameMutableByteArray mba) mba ] , bgroup "set" [ bgroup "0" [ setBytesBench mb1 mb2 mba 0 (n * 8 :: Count Word8) , setBytesBench mb1 mb2 mba 0 (n * 4 :: Count Word16) , setBytesBench mb1 mb2 mba 0 (n * 2 :: Count Word32) , setBytesBench mb1 mb2 mba 0 (n :: Count Word64) , setBytesBench mb1 mb2 mba 0 (n * 2 :: Count Float) , setBytesBench mb1 mb2 mba 0 (n :: Count Double) , bench "setMBytes/Bool" $ nfIO (setMBytes mb1 0 (n * 8 :: Count Bool) False) ] , bgroup "regular" [ setBytesBench mb1 mb2 mba 123 (n * 8 :: Count Word8) , setBytesBench mb1 mb2 mba 123 (n * 4 :: Count Word16) , setBytesBench mb1 mb2 mba 123 (n * 2 :: Count Word32) , setBytesBench mb1 mb2 mba 123 (n :: Count Word64) , setBytesBench mb1 mb2 mba 123 (n * 2 :: Count Float) , setBytesBench mb1 mb2 mba 123 (n :: Count Double) , bench "setMBytes/Bool" $ nfIO (setMBytes mb1 0 (n * 8 :: Count Bool) True) ] , bgroup "symmetric" [ setBytesBench mb1 mb2 mba maxBound (n * 8 :: Count Word8) , setBytesBench mb1 mb2 mba maxBound (n * 4 :: Count Word16) , setBytesBench mb1 mb2 mba maxBound (n * 2 :: Count Word32) , setBytesBench mb1 mb2 mba maxBound (n :: Count Word64) ] ] , bgroup "access" [ bgroup "index" [ benchIndex (Proxy :: Proxy Word8) b1 ba , benchIndex (Proxy :: Proxy Word16) b1 ba , benchIndex (Proxy :: Proxy Word32) b1 ba , benchIndex (Proxy :: Proxy Word64) b1 ba , benchIndex (Proxy :: Proxy Char) b1 ba , bgroup "Bool" [bench "Bytes" $ whnf (indexOffBytes b1) (Off 125 :: Off Bool)] ] , bgroup "read" [ benchRead (Proxy :: Proxy Word8) mb1 mba , benchRead (Proxy :: Proxy Word16) mb1 mba , benchRead (Proxy :: Proxy Word32) mb1 mba , benchRead (Proxy :: Proxy Word64) mb1 mba , benchRead (Proxy :: Proxy Char) mb1 mba , bgroup TODO : try out FFI [bench "Bytes" $ whnfIO (readOffMBytes mb1 (Off 125 :: Off Bool))] ] , bgroup "peek" [ env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Word8) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Word16) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Word32) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Word64) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Char) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Bool) mb1) ] ] ] benchIndex :: forall a p. (Typeable a, Unbox a, BA.Prim a) => Proxy a -> Bytes p -> BA.ByteArray -> Benchmark benchIndex px b ba = bgroup (showsType px "") [ bench "Bytes" $ whnf (indexOffBytes b) (Off i :: Off a) , bench "ByteArray" $ whnf (BA.indexByteArray ba :: Int -> a) i ] where i = 100 benchRead :: forall a p. (Typeable a, Unbox a, BA.Prim a) => Proxy a -> MBytes p RealWorld -> BA.MutableByteArray RealWorld -> Benchmark benchRead px mb mba = bgroup (showsType px "") [ bench "Bytes" $ whnfIO (readOffMBytes mb (Off i :: Off a)) , bench "ByteArray" $ whnfIO (BA.readByteArray mba i :: IO a) ] where i = 100 benchPeek :: forall a. (Typeable a, Unbox a, S.Storable a) => Proxy a -> MBytes 'Pin RealWorld -> ForeignPtr a -> Benchmark benchPeek px mb fptr = bgroup (showsType px "") [ bench "Bytes" $ whnfIO $ withPtrMBytes mb (readPtr :: Ptr a -> IO a) , bench "ForeignPtr" $ whnfIO $ withForeignPtr fptr S.peek ] setBytesBench :: forall a . (Typeable a, BA.Prim a, Unbox a) => MBytes 'Pin RealWorld -> MBytes 'Pin RealWorld -> BA.MutableByteArray RealWorld -> a -> Count a -> Benchmark setBytesBench mb1 mb2 mba a c@(Count n) = bgroup (showsType (Proxy :: Proxy a) "") [ bench "setMBytes" $ nfIO (setMBytes mb1 0 c a) , bench "setOffPtr" $ nfIO (withPtrMBytes mb2 $ \ ptr -> setOffPtr ptr 0 c a :: IO ()) , bench "setByteArray" $ nfIO (BA.setByteArray mba 0 n a) ]
null
https://raw.githubusercontent.com/lehins/primal/c620bfd4f2a6475f1c12183fbe8138cf29ab1dad/primal-memory/bench/Bench.hs
haskell
# LANGUAGE BangPatterns #
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -fno - warn - orphans # module Main (main) where import GHC.Exts import Data.Proxy import Data.Typeable import Criterion.Main import Primal.Memory.Bytes import Primal.Memory.Ptr import qualified Data.Primitive.Types as BA import qualified Data.Primitive.ByteArray as BA import Foreign.Storable as S import Foreign.ForeignPtr import GHC.ForeignPtr import Control.DeepSeq instance NFData (ForeignPtr a) where rnf !_ = () main :: IO () main = do let n = 1000000 :: Count a n64 = n :: Count Word64 mb1 <- allocAlignedPinnedMBytes n64 mb2 <- allocAlignedPinnedMBytes n64 b1 <- freezeMBytes mb1 mba <- BA.newAlignedPinnedByteArray (unCountBytes (n :: Count Word64)) 8 ba <- BA.unsafeFreezeByteArray mba Ensure that arrays are equal by filling them with zeros mbaEq1 <- BA.newAlignedPinnedByteArray (unCountBytes (n :: Count Word64)) 8 mbaEq2 <- BA.newAlignedPinnedByteArray (unCountBytes (n :: Count Word64)) 8 BA.setByteArray mbaEq1 0 (unCount n64) (0 :: Word64) BA.setByteArray mbaEq2 0 (unCount n64) (0 :: Word64) defaultMain [ bgroup "ptr" [ env (freezeMBytes mb1) $ \b -> bench "(==) - isSameBytes" $ whnf (isSameBytes b) b , env (freezeMBytes mb1) $ \b -> bench "isSameBytes" $ whnf (isSameBytes b) (relaxPinnedBytes b) , env (freezeMBytes mb1) $ \b -> bench "isSamePinnedBytes" $ whnf (isSamePinnedBytes b) b , bench "(==) - sameByteArray (unexported)" $ whnf (ba ==) ba , bench "isSameMBytes" $ whnf (isSameMBytes mb1) mb1 , bench "sameMutableByteArray" $ whnf (BA.sameMutableByteArray mba) mba ] , bgroup "set" [ bgroup "0" [ setBytesBench mb1 mb2 mba 0 (n * 8 :: Count Word8) , setBytesBench mb1 mb2 mba 0 (n * 4 :: Count Word16) , setBytesBench mb1 mb2 mba 0 (n * 2 :: Count Word32) , setBytesBench mb1 mb2 mba 0 (n :: Count Word64) , setBytesBench mb1 mb2 mba 0 (n * 2 :: Count Float) , setBytesBench mb1 mb2 mba 0 (n :: Count Double) , bench "setMBytes/Bool" $ nfIO (setMBytes mb1 0 (n * 8 :: Count Bool) False) ] , bgroup "regular" [ setBytesBench mb1 mb2 mba 123 (n * 8 :: Count Word8) , setBytesBench mb1 mb2 mba 123 (n * 4 :: Count Word16) , setBytesBench mb1 mb2 mba 123 (n * 2 :: Count Word32) , setBytesBench mb1 mb2 mba 123 (n :: Count Word64) , setBytesBench mb1 mb2 mba 123 (n * 2 :: Count Float) , setBytesBench mb1 mb2 mba 123 (n :: Count Double) , bench "setMBytes/Bool" $ nfIO (setMBytes mb1 0 (n * 8 :: Count Bool) True) ] , bgroup "symmetric" [ setBytesBench mb1 mb2 mba maxBound (n * 8 :: Count Word8) , setBytesBench mb1 mb2 mba maxBound (n * 4 :: Count Word16) , setBytesBench mb1 mb2 mba maxBound (n * 2 :: Count Word32) , setBytesBench mb1 mb2 mba maxBound (n :: Count Word64) ] ] , bgroup "access" [ bgroup "index" [ benchIndex (Proxy :: Proxy Word8) b1 ba , benchIndex (Proxy :: Proxy Word16) b1 ba , benchIndex (Proxy :: Proxy Word32) b1 ba , benchIndex (Proxy :: Proxy Word64) b1 ba , benchIndex (Proxy :: Proxy Char) b1 ba , bgroup "Bool" [bench "Bytes" $ whnf (indexOffBytes b1) (Off 125 :: Off Bool)] ] , bgroup "read" [ benchRead (Proxy :: Proxy Word8) mb1 mba , benchRead (Proxy :: Proxy Word16) mb1 mba , benchRead (Proxy :: Proxy Word32) mb1 mba , benchRead (Proxy :: Proxy Word64) mb1 mba , benchRead (Proxy :: Proxy Char) mb1 mba , bgroup TODO : try out FFI [bench "Bytes" $ whnfIO (readOffMBytes mb1 (Off 125 :: Off Bool))] ] , bgroup "peek" [ env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Word8) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Word16) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Word32) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Word64) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Char) mb1) , env mallocPlainForeignPtr (benchPeek (Proxy :: Proxy Bool) mb1) ] ] ] benchIndex :: forall a p. (Typeable a, Unbox a, BA.Prim a) => Proxy a -> Bytes p -> BA.ByteArray -> Benchmark benchIndex px b ba = bgroup (showsType px "") [ bench "Bytes" $ whnf (indexOffBytes b) (Off i :: Off a) , bench "ByteArray" $ whnf (BA.indexByteArray ba :: Int -> a) i ] where i = 100 benchRead :: forall a p. (Typeable a, Unbox a, BA.Prim a) => Proxy a -> MBytes p RealWorld -> BA.MutableByteArray RealWorld -> Benchmark benchRead px mb mba = bgroup (showsType px "") [ bench "Bytes" $ whnfIO (readOffMBytes mb (Off i :: Off a)) , bench "ByteArray" $ whnfIO (BA.readByteArray mba i :: IO a) ] where i = 100 benchPeek :: forall a. (Typeable a, Unbox a, S.Storable a) => Proxy a -> MBytes 'Pin RealWorld -> ForeignPtr a -> Benchmark benchPeek px mb fptr = bgroup (showsType px "") [ bench "Bytes" $ whnfIO $ withPtrMBytes mb (readPtr :: Ptr a -> IO a) , bench "ForeignPtr" $ whnfIO $ withForeignPtr fptr S.peek ] setBytesBench :: forall a . (Typeable a, BA.Prim a, Unbox a) => MBytes 'Pin RealWorld -> MBytes 'Pin RealWorld -> BA.MutableByteArray RealWorld -> a -> Count a -> Benchmark setBytesBench mb1 mb2 mba a c@(Count n) = bgroup (showsType (Proxy :: Proxy a) "") [ bench "setMBytes" $ nfIO (setMBytes mb1 0 c a) , bench "setOffPtr" $ nfIO (withPtrMBytes mb2 $ \ ptr -> setOffPtr ptr 0 c a :: IO ()) , bench "setByteArray" $ nfIO (BA.setByteArray mba 0 n a) ]
ca4c7517f2cc75ebbb5e658a8cd21a190433c3f8bee613eac5e1780ecaa90ec5
Vonmo/eapa
eapa_int_SUITE.erl
-module(eapa_int_SUITE). -compile(export_all). -import(ct_helper, [config/2]). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). all() -> [ {group, int} ]. groups() -> [ {int, [parallel, shuffle], [float_to_bigint, add, add_prec1, add_prec2, sub, sub_prec1, sub_prec2, mul, mul_prec1, mul_prec2, divp, divp_prec1, divp_prec2, min, min_prec1, min_prec2, max, max_prec1, max_prec2, lt, lt_prec1, lt_prec2, lte, lte_prec1, lte_prec2, gt, gt_prec1, gt_prec2, gte, gte_prec1, gte_prec2, big, big_negative]} ]. %% ============================================================================= %% init %% ============================================================================= init_per_group(_Group, Config) -> ok = application:load(eapa), {ok, _} = application:ensure_all_started(eapa, temporary), [{init, true} | Config]. %% ============================================================================= %% end %% ============================================================================= end_per_group(_Group, _Config) -> ok = application:stop(eapa), ok = application:unload(eapa), ok. %% ============================================================================= %% group: int %% ============================================================================= float_to_bigint(_) -> X = eapa_int:with_val(6, <<"1280001.10345">>), <<"1280001.103">> = eapa_int:to_float(3, X), <<"1280001.103450">> = eapa_int:to_float(6, X), ok. add(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), Sum = eapa_int:add(X1, X2), <<"0.055673">> = eapa_int:to_float(6, Sum), ok. add_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), Sum = eapa_int:add(X1, X2), <<"0.055673">> = eapa_int:to_float(6, Sum), ok. add_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), Sum = eapa_int:add(X1, X2), <<"0.055673">> = eapa_int:to_float(6, Sum), ok. sub(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:sub(X1, X2), <<"0.055427">> = eapa_int:to_float(6, R), ok. sub_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:sub(X1, X2), <<"0.055427">> = eapa_int:to_float(6, R), ok. sub_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:sub(X1, X2), <<"0.055427">> = eapa_int:to_float(6, R), ok. mul(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:mul(X1, X2), <<"0.000006">> = eapa_int:to_float(6, R), ok. mul_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:mul(X1, X2), <<"0.00000683">> = eapa_int:to_float(8, R), ok. mul_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:mul(X1, X2), <<"0.00000683">> = eapa_int:to_float(8, R), ok. divp(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:divp(X1, X2), <<"451.626016">> = eapa_int:to_float(6, R), ok. divp_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:divp(X1, X2), <<"451.62601626">> = eapa_int:to_float(8, R), ok. divp_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:divp(X1, X2), <<"451.62601626">> = eapa_int:to_float(8, R), ok. min(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:min(X1, X2), <<"0.000123">> = eapa_int:to_float(6, R), ok. min_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:min(X1, X2), <<"0.000123">> = eapa_int:to_float(6, R), ok. min_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:min(X1, X2), <<"0.000123">> = eapa_int:to_float(6, R), ok. max(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:max(X1, X2), <<"0.055550">> = eapa_int:to_float(6, R), ok. max_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:max(X1, X2), <<"0.055550">> = eapa_int:to_float(6, R), ok. max_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:max(X1, X2), <<"0.055550">> = eapa_int:to_float(6, R), ok. lt(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), false = eapa_int:lt(X1, X2), true = eapa_int:lt(X2, X1), ok. lt_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), false = eapa_int:lt(X1, X2), true = eapa_int:lt(X2, X1), ok. lt_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), false = eapa_int:lt(X1, X2), true = eapa_int:lt(X2, X1), ok. lte(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), false = eapa_int:lte(X1, X2), true = eapa_int:lte(X2, X1), ok. lte_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), false = eapa_int:lte(X1, X2), true = eapa_int:lte(X2, X1), ok. lte_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), false = eapa_int:lte(X1, X2), true = eapa_int:lte(X2, X1), ok. gt(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), true = eapa_int:gt(X1, X2), false = eapa_int:gt(X2, X1), ok. gt_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), true = eapa_int:gt(X1, X2), false = eapa_int:gt(X2, X1), ok. gt_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), true = eapa_int:gt(X1, X2), false = eapa_int:gt(X2, X1), ok. gte(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), true = eapa_int:gte(X1, X2), false = eapa_int:gte(X2, X1), ok. gte_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), true = eapa_int:gte(X1, X2), false = eapa_int:gte(X2, X1), ok. gte_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), true = eapa_int:gte(X1, X2), false = eapa_int:gte(X2, X1), ok. big(_) -> X = <<"2147483648.2147483647">>, C = eapa_int:with_val(10, X), X = eapa_int:to_float(C). big_negative(_) -> X = <<"-2147483648.2147483647">>, C = eapa_int:with_val(10, X), X = eapa_int:to_float(C).
null
https://raw.githubusercontent.com/Vonmo/eapa/7c577851e3598c8c524999b89c89f9267e769e24/test/eapa_int_SUITE.erl
erlang
============================================================================= init ============================================================================= ============================================================================= end ============================================================================= ============================================================================= group: int =============================================================================
-module(eapa_int_SUITE). -compile(export_all). -import(ct_helper, [config/2]). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). all() -> [ {group, int} ]. groups() -> [ {int, [parallel, shuffle], [float_to_bigint, add, add_prec1, add_prec2, sub, sub_prec1, sub_prec2, mul, mul_prec1, mul_prec2, divp, divp_prec1, divp_prec2, min, min_prec1, min_prec2, max, max_prec1, max_prec2, lt, lt_prec1, lt_prec2, lte, lte_prec1, lte_prec2, gt, gt_prec1, gt_prec2, gte, gte_prec1, gte_prec2, big, big_negative]} ]. init_per_group(_Group, Config) -> ok = application:load(eapa), {ok, _} = application:ensure_all_started(eapa, temporary), [{init, true} | Config]. end_per_group(_Group, _Config) -> ok = application:stop(eapa), ok = application:unload(eapa), ok. float_to_bigint(_) -> X = eapa_int:with_val(6, <<"1280001.10345">>), <<"1280001.103">> = eapa_int:to_float(3, X), <<"1280001.103450">> = eapa_int:to_float(6, X), ok. add(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), Sum = eapa_int:add(X1, X2), <<"0.055673">> = eapa_int:to_float(6, Sum), ok. add_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), Sum = eapa_int:add(X1, X2), <<"0.055673">> = eapa_int:to_float(6, Sum), ok. add_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), Sum = eapa_int:add(X1, X2), <<"0.055673">> = eapa_int:to_float(6, Sum), ok. sub(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:sub(X1, X2), <<"0.055427">> = eapa_int:to_float(6, R), ok. sub_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:sub(X1, X2), <<"0.055427">> = eapa_int:to_float(6, R), ok. sub_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:sub(X1, X2), <<"0.055427">> = eapa_int:to_float(6, R), ok. mul(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:mul(X1, X2), <<"0.000006">> = eapa_int:to_float(6, R), ok. mul_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:mul(X1, X2), <<"0.00000683">> = eapa_int:to_float(8, R), ok. mul_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:mul(X1, X2), <<"0.00000683">> = eapa_int:to_float(8, R), ok. divp(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:divp(X1, X2), <<"451.626016">> = eapa_int:to_float(6, R), ok. divp_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:divp(X1, X2), <<"451.62601626">> = eapa_int:to_float(8, R), ok. divp_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:divp(X1, X2), <<"451.62601626">> = eapa_int:to_float(8, R), ok. min(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:min(X1, X2), <<"0.000123">> = eapa_int:to_float(6, R), ok. min_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:min(X1, X2), <<"0.000123">> = eapa_int:to_float(6, R), ok. min_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:min(X1, X2), <<"0.000123">> = eapa_int:to_float(6, R), ok. max(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:max(X1, X2), <<"0.055550">> = eapa_int:to_float(6, R), ok. max_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), R = eapa_int:max(X1, X2), <<"0.055550">> = eapa_int:to_float(6, R), ok. max_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), R = eapa_int:max(X1, X2), <<"0.055550">> = eapa_int:to_float(6, R), ok. lt(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), false = eapa_int:lt(X1, X2), true = eapa_int:lt(X2, X1), ok. lt_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), false = eapa_int:lt(X1, X2), true = eapa_int:lt(X2, X1), ok. lt_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), false = eapa_int:lt(X1, X2), true = eapa_int:lt(X2, X1), ok. lte(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), false = eapa_int:lte(X1, X2), true = eapa_int:lte(X2, X1), ok. lte_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), false = eapa_int:lte(X1, X2), true = eapa_int:lte(X2, X1), ok. lte_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), false = eapa_int:lte(X1, X2), true = eapa_int:lte(X2, X1), ok. gt(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), true = eapa_int:gt(X1, X2), false = eapa_int:gt(X2, X1), ok. gt_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), true = eapa_int:gt(X1, X2), false = eapa_int:gt(X2, X1), ok. gt_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), true = eapa_int:gt(X1, X2), false = eapa_int:gt(X2, X1), ok. gte(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), true = eapa_int:gte(X1, X2), false = eapa_int:gte(X2, X1), ok. gte_prec1(_) -> X1 = eapa_int:with_val(12, <<"0.05555">>), X2 = eapa_int:with_val(6, <<"0.000123">>), true = eapa_int:gte(X1, X2), false = eapa_int:gte(X2, X1), ok. gte_prec2(_) -> X1 = eapa_int:with_val(6, <<"0.05555">>), X2 = eapa_int:with_val(12, <<"0.000123">>), true = eapa_int:gte(X1, X2), false = eapa_int:gte(X2, X1), ok. big(_) -> X = <<"2147483648.2147483647">>, C = eapa_int:with_val(10, X), X = eapa_int:to_float(C). big_negative(_) -> X = <<"-2147483648.2147483647">>, C = eapa_int:with_val(10, X), X = eapa_int:to_float(C).
7f071a05793150ee9f6d6b7e5f72239a415c03785410a21adae52e720073a93e
ekmett/algebra
Euclidean.hs
module Numeric.Domain.Euclidean (Euclidean(..), euclid, prs, chineseRemainder) where import Numeric.Additive.Group import Numeric.Algebra.Class import Numeric.Algebra.Unital import Numeric.Decidable.Zero import Numeric.Domain.Internal import Prelude (otherwise) import qualified Prelude as P prs :: Euclidean r => r -> r -> [(r, r, r)] prs f g = step [(g, zero, one), (f, one, zero)] where step acc@((r',s',t'):(r,s,t):_) | isZero r' = P.tail acc | otherwise = let q = r `quot` r' s'' = (s - q * s') t'' = (t - q * t') in step ((r - q * r', s'', t'') : acc) step _ = P.error "cannot happen!" chineseRemainder :: Euclidean r ^ List of @(m_i , v_i)@ ^ @f@ with = @v_i@ ( mod @v_i@ ) chineseRemainder mvs = let (ms, _) = P.unzip mvs m = product ms in sum [((vi*s) `rem` mi)*n | (mi, vi) <- mvs , let n = m `quot` mi , let (_, s, _) : _ = euclid n mi ]
null
https://raw.githubusercontent.com/ekmett/algebra/12dd33e848f406dd53d19b69b4f14c93ba6e352b/src/Numeric/Domain/Euclidean.hs
haskell
module Numeric.Domain.Euclidean (Euclidean(..), euclid, prs, chineseRemainder) where import Numeric.Additive.Group import Numeric.Algebra.Class import Numeric.Algebra.Unital import Numeric.Decidable.Zero import Numeric.Domain.Internal import Prelude (otherwise) import qualified Prelude as P prs :: Euclidean r => r -> r -> [(r, r, r)] prs f g = step [(g, zero, one), (f, one, zero)] where step acc@((r',s',t'):(r,s,t):_) | isZero r' = P.tail acc | otherwise = let q = r `quot` r' s'' = (s - q * s') t'' = (t - q * t') in step ((r - q * r', s'', t'') : acc) step _ = P.error "cannot happen!" chineseRemainder :: Euclidean r ^ List of @(m_i , v_i)@ ^ @f@ with = @v_i@ ( mod @v_i@ ) chineseRemainder mvs = let (ms, _) = P.unzip mvs m = product ms in sum [((vi*s) `rem` mi)*n | (mi, vi) <- mvs , let n = m `quot` mi , let (_, s, _) : _ = euclid n mi ]
54aa537501b0bb97d6e371d51077299da936ebfb058c640416b8a9df422ce0d4
RyanGlScott/text-show-instances
PosixSpec.hs
# LANGUAGE CPP # | Module : Spec . System . PosixSpec Copyright : ( C ) 2014 - 2017 License : BSD - style ( see the file LICENSE ) Maintainer : Stability : Provisional Portability : GHC @hspec@ tests for data types in the @unix@ library . Module: Spec.System.PosixSpec Copyright: (C) 2014-2017 Ryan Scott License: BSD-style (see the file LICENSE) Maintainer: Ryan Scott Stability: Provisional Portability: GHC @hspec@ tests for data types in the @unix@ library. -} module Spec.System.PosixSpec (main, spec) where import Prelude () import Prelude.Compat import Test.Hspec (Spec, hspec, parallel) #if !defined(mingw32_HOST_OS) import Data.Proxy (Proxy(..)) import Instances.System.Posix () import Spec.Utils (matchesTextShowSpec) import System.Posix.DynamicLinker (RTLDFlags, DL) import System.Posix.Process (ProcessStatus) # if MIN_VERSION_unix(2,8,0) import System.Posix.User.ByteString # else import System.Posix.User # endif (GroupEntry, UserEntry) import Test.Hspec (describe) import TextShow.System.Posix () #endif main :: IO () main = hspec spec spec :: Spec spec = parallel $ do #if !defined(mingw32_HOST_OS) describe "RTLDFlags" $ matchesTextShowSpec (Proxy :: Proxy RTLDFlags) describe "DL" $ matchesTextShowSpec (Proxy :: Proxy DL) describe "ProcessStatus" $ matchesTextShowSpec (Proxy :: Proxy ProcessStatus) describe "GroupEntry" $ matchesTextShowSpec (Proxy :: Proxy GroupEntry) describe "UserEntry" $ matchesTextShowSpec (Proxy :: Proxy UserEntry) #else pure () #endif
null
https://raw.githubusercontent.com/RyanGlScott/text-show-instances/0b12ef75935eb68b44fc6528ffaba88079df6679/tests/Spec/System/PosixSpec.hs
haskell
# LANGUAGE CPP # | Module : Spec . System . PosixSpec Copyright : ( C ) 2014 - 2017 License : BSD - style ( see the file LICENSE ) Maintainer : Stability : Provisional Portability : GHC @hspec@ tests for data types in the @unix@ library . Module: Spec.System.PosixSpec Copyright: (C) 2014-2017 Ryan Scott License: BSD-style (see the file LICENSE) Maintainer: Ryan Scott Stability: Provisional Portability: GHC @hspec@ tests for data types in the @unix@ library. -} module Spec.System.PosixSpec (main, spec) where import Prelude () import Prelude.Compat import Test.Hspec (Spec, hspec, parallel) #if !defined(mingw32_HOST_OS) import Data.Proxy (Proxy(..)) import Instances.System.Posix () import Spec.Utils (matchesTextShowSpec) import System.Posix.DynamicLinker (RTLDFlags, DL) import System.Posix.Process (ProcessStatus) # if MIN_VERSION_unix(2,8,0) import System.Posix.User.ByteString # else import System.Posix.User # endif (GroupEntry, UserEntry) import Test.Hspec (describe) import TextShow.System.Posix () #endif main :: IO () main = hspec spec spec :: Spec spec = parallel $ do #if !defined(mingw32_HOST_OS) describe "RTLDFlags" $ matchesTextShowSpec (Proxy :: Proxy RTLDFlags) describe "DL" $ matchesTextShowSpec (Proxy :: Proxy DL) describe "ProcessStatus" $ matchesTextShowSpec (Proxy :: Proxy ProcessStatus) describe "GroupEntry" $ matchesTextShowSpec (Proxy :: Proxy GroupEntry) describe "UserEntry" $ matchesTextShowSpec (Proxy :: Proxy UserEntry) #else pure () #endif
bed7374a22ef303ccc5c43781bbb063303cb78ec61433dbbde94543a6b784c2c
sacerdot/MiniErlangBlockchain
miner_act.erl
-module(miner_act). -export([start_M_act/2]). -import(utils, [sleep/1]). %! ---- Behavior di Miner Act ----- compute(PidRoot, PidBlock) -> PidBlock ! {minerReady, self()}, mi metto in attesa di un nuovo set di transazioni da inserire nel blocco receive {createBlock, ID_blocco_prev, Transactions} -> % io:format("-> [~p] Sto minando il BLOCCO: ~p~n",[PidRoot,Transactions]), Solution = proof_of_work:solve({ID_blocco_prev, Transactions}), B = {make_ref(), ID_blocco_prev, Transactions, Solution}, PidBlock ! {miningFinished, B}, compute(PidRoot, PidBlock) end. start_M_act(PidRoot, PidBlock) -> sleep(1), compute(PidRoot, PidBlock).
null
https://raw.githubusercontent.com/sacerdot/MiniErlangBlockchain/46713c579204994a528d2e642c8f7c0670c2a832/CaputoConteducaLazazzera-Node/actors/miner_act.erl
erlang
! ---- Behavior di Miner Act ----- io:format("-> [~p] Sto minando il BLOCCO: ~p~n",[PidRoot,Transactions]),
-module(miner_act). -export([start_M_act/2]). -import(utils, [sleep/1]). compute(PidRoot, PidBlock) -> PidBlock ! {minerReady, self()}, mi metto in attesa di un nuovo set di transazioni da inserire nel blocco receive {createBlock, ID_blocco_prev, Transactions} -> Solution = proof_of_work:solve({ID_blocco_prev, Transactions}), B = {make_ref(), ID_blocco_prev, Transactions, Solution}, PidBlock ! {miningFinished, B}, compute(PidRoot, PidBlock) end. start_M_act(PidRoot, PidBlock) -> sleep(1), compute(PidRoot, PidBlock).
5c37873c601c1f3fc6a5268fbed58695b7678472eb49e2484c562db1e58798e9
spechub/Hets
Sign.hs
{-# LANGUAGE DeriveDataTypeable #-} | Module : ./NeSyPatterns / Sign.hs Description : Signatures for syntax for neural - symbolic patterns Copyright : ( c ) , Uni Magdeburg 2022 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : experimental Portability : portable Definition of signatures for neural - symbolic patterns Module : ./NeSyPatterns/Sign.hs Description : Signatures for syntax for neural-symbolic patterns Copyright : (c) Till Mossakowski, Uni Magdeburg 2022 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : experimental Portability : portable Definition of signatures for neural-symbolic patterns -} module NeSyPatterns.Sign (Sign (..) -- Signatures6 , ResolvedNode(..) , resolved2Node , findNodeId , nesyIdMap , pretty -- pretty printing , isLegalSignature -- is a signature ok? adds an i d to the given Signature , addEdgeToSig -- adds an edge to the given signature , addEdgeToSig' -- adds an edge and its nodes to the given signature , unite -- union of signatures , emptySig -- empty signature , isSubSigOf -- is subsignature? , sigDiff -- Difference of Signatures , sigUnion -- Union for Logic.Logic , nesyIds -- extracts the ids of all nodes of a signature ) where import Data.Data import Data.List as List import qualified Data.Set as Set import qualified Data.Relation as Rel import qualified Data.Map as Map import Common.Id import Common.Result import Common.Doc import Common.DocUtils import Common.SetColimit import Common.IRI import Common.Keywords import NeSyPatterns.AS import NeSyPatterns.Print() import OWL2.AS import OWL2.Pretty data ResolvedNode = ResolvedNode { resolvedOTerm :: IRI, resolvedNeSyId :: IRI, resolvedNodeRange :: Range } deriving (Show, Eq, Ord, Typeable, Data) instance SymbolName ResolvedNode where addString (ResolvedNode t1 t2 r, s) = ResolvedNode t1 (addSuffixToIRI s t2) r instance Pretty ResolvedNode where pretty (ResolvedNode o i r) = pretty $ Node o (Just i) r instance GetRange ResolvedNode where getRange = const nullRange rangeSpan x = case x of ResolvedNode a b c -> joinRanges [rangeSpan a, rangeSpan b, rangeSpan c] | Datatype for propositional Signatures Signatures are graphs over nodes from the abstract syntax Signatures are graphs over nodes from the abstract syntax -} data Sign = Sign { owlClasses :: Set.Set IRI, owlTaxonomy :: Rel.Relation IRI IRI, nodes :: Set.Set ResolvedNode, edges :: Rel.Relation ResolvedNode ResolvedNode, idMap :: Map.Map IRI IRI } deriving (Show, Eq, Ord, Typeable) instance Pretty Sign where pretty = printSign findNodeId :: IRI -> Set.Set ResolvedNode -> Set.Set ResolvedNode findNodeId t = Set.filter (\(ResolvedNode _ t1 _) -> t == t1 ) nesyIds :: Sign -> Set.Set IRI nesyIds = Set.map resolvedNeSyId . nodes nesyIdMap :: Set.Set ResolvedNode -> Map.Map IRI IRI nesyIdMap ns = Map.fromList [(i, o) | ResolvedNode o i _ <- Set.toList ns] resolved2Node :: ResolvedNode -> Node resolved2Node (ResolvedNode t i r) = Node t (Just i) r -- | Builds the owl2 ontology from a signature getOntology :: Sign -> OntologyDocument getOntology s = let decls = Declaration [] . mkEntity Class <$> Set.toList (owlClasses s) subClasses = fmap (\(a,b) -> SubClassOf [] (Expression a) (Expression b)) $ Rel.toList (owlTaxonomy s) subClassAxs = ClassAxiom <$> subClasses axs = decls ++ subClassAxs in emptyOntologyDoc { ontology = emptyOntology { axioms = axs}} | determines whether a signature is isLegalSignature :: Sign -> Bool isLegalSignature s = Rel.dom (edges s) `Set.isSubsetOf` nodes s && Rel.ran (edges s) `Set.isSubsetOf` nodes s | pretty for edge e.g. tuple ( ResolvedNode , ResolvedNode ) printEdge :: (ResolvedNode, ResolvedNode) -> Doc printEdge (node1, node2) = pretty node1 <+> text "->" <+> pretty node2 <> semi ( fsep . punctuate ( text " - > " ) $ map pretty [ node1 , node2 ] ) < > semi -- | pretty printing for Signatures printSign :: Sign -> Doc printSign s = keyword dataS <+> (specBraces . toDocAsMS . getOntology $ s) $+$ (vcat . map printEdge . Rel.toList . edges $ s) $+$ (vcat . map ((<> semi) . pretty) . Set.toList $ (nodes s Set.\\ Set.union (Rel.dom . edges $ s) (Rel.ran . edges $ s))) -- | Adds a node to the signature addToSig :: Sign -> ResolvedNode -> Sign addToSig sig node = sig {nodes = Set.insert node $ nodes sig} -- | Adds an edge to the signature. Nodes are not added. See addEdgeToSig' addEdgeToSig :: Sign -> (ResolvedNode, ResolvedNode) -> Sign addEdgeToSig sig (f, t) = sig {edges = Rel.insert f t $ edges sig} -- | Adds an edge with its nodes to the signature addEdgeToSig' :: Sign -> (ResolvedNode, ResolvedNode) -> Sign addEdgeToSig' sig (f, t) = addToSig (addToSig (sig {edges = Rel.insert f t $ edges sig}) f) t -- | Union of signatures unite :: Sign -> Sign -> Sign unite sig1 sig2 = Sign {owlClasses = Set.union (owlClasses sig1) $ owlClasses sig2, owlTaxonomy = Rel.union (owlTaxonomy sig1) $ owlTaxonomy sig2, nodes = Set.union (nodes sig1) $ nodes sig2, idMap = Map.union (idMap sig1) $ idMap sig2, edges = Rel.union (edges sig1) $ edges sig2} -- | The empty signature emptySig :: Sign emptySig = Sign { owlClasses = Set.empty , owlTaxonomy = Rel.empty , nodes = Set.empty , edges = Rel.empty , idMap = Map.empty} relToSet :: (Ord a, Ord b) => Rel.Relation a b -> Set.Set (a,b) relToSet r = Set.fromList $ Rel.toList r | Determines if is subsignature of sig2 isSubSigOf :: Sign -> Sign -> Bool isSubSigOf sig1 sig2 = owlClasses sig1 `Set.isSubsetOf` owlClasses sig2 && nodes sig1 `Set.isSubsetOf` nodes sig2 && relToSet (edges sig1) `Set.isSubsetOf` relToSet (edges sig2) && relToSet (owlTaxonomy sig1) `Set.isSubsetOf` relToSet (owlTaxonomy sig2) relDiff :: (Ord a, Ord b) => Rel.Relation a b -> Rel.Relation a b -> Rel.Relation a b relDiff r1 r2 = Rel.fromList (l1 List.\\ l2) where l1 = Rel.toList r1 l2 = Rel.toList r2 -- | difference of Signatures sigDiff :: Sign -> Sign -> Sign sigDiff sig1 sig2 = Sign {owlClasses = Set.difference (owlClasses sig1) $ owlClasses sig2, owlTaxonomy = relDiff (owlTaxonomy sig1) $ owlTaxonomy sig2, nodes = Set.difference (nodes sig1) $ nodes sig2, idMap = Map.difference (idMap sig1) $ idMap sig2, edges = relDiff (edges sig1) $ edges sig2} {- | union of Signatures, using Result -} sigUnion :: Sign -> Sign -> Result Sign sigUnion s1 s2 = return $ unite s1 s2
null
https://raw.githubusercontent.com/spechub/Hets/fc26b4947bf52be6baf7819a75d7e7f127e290dd/NeSyPatterns/Sign.hs
haskell
# LANGUAGE DeriveDataTypeable # Signatures6 pretty printing is a signature ok? adds an edge to the given signature adds an edge and its nodes to the given signature union of signatures empty signature is subsignature? Difference of Signatures Union for Logic.Logic extracts the ids of all nodes of a signature | Builds the owl2 ontology from a signature | pretty printing for Signatures | Adds a node to the signature | Adds an edge to the signature. Nodes are not added. See addEdgeToSig' | Adds an edge with its nodes to the signature | Union of signatures | The empty signature | difference of Signatures | union of Signatures, using Result
| Module : ./NeSyPatterns / Sign.hs Description : Signatures for syntax for neural - symbolic patterns Copyright : ( c ) , Uni Magdeburg 2022 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : experimental Portability : portable Definition of signatures for neural - symbolic patterns Module : ./NeSyPatterns/Sign.hs Description : Signatures for syntax for neural-symbolic patterns Copyright : (c) Till Mossakowski, Uni Magdeburg 2022 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : experimental Portability : portable Definition of signatures for neural-symbolic patterns -} module NeSyPatterns.Sign , ResolvedNode(..) , resolved2Node , findNodeId , nesyIdMap adds an i d to the given Signature ) where import Data.Data import Data.List as List import qualified Data.Set as Set import qualified Data.Relation as Rel import qualified Data.Map as Map import Common.Id import Common.Result import Common.Doc import Common.DocUtils import Common.SetColimit import Common.IRI import Common.Keywords import NeSyPatterns.AS import NeSyPatterns.Print() import OWL2.AS import OWL2.Pretty data ResolvedNode = ResolvedNode { resolvedOTerm :: IRI, resolvedNeSyId :: IRI, resolvedNodeRange :: Range } deriving (Show, Eq, Ord, Typeable, Data) instance SymbolName ResolvedNode where addString (ResolvedNode t1 t2 r, s) = ResolvedNode t1 (addSuffixToIRI s t2) r instance Pretty ResolvedNode where pretty (ResolvedNode o i r) = pretty $ Node o (Just i) r instance GetRange ResolvedNode where getRange = const nullRange rangeSpan x = case x of ResolvedNode a b c -> joinRanges [rangeSpan a, rangeSpan b, rangeSpan c] | Datatype for propositional Signatures Signatures are graphs over nodes from the abstract syntax Signatures are graphs over nodes from the abstract syntax -} data Sign = Sign { owlClasses :: Set.Set IRI, owlTaxonomy :: Rel.Relation IRI IRI, nodes :: Set.Set ResolvedNode, edges :: Rel.Relation ResolvedNode ResolvedNode, idMap :: Map.Map IRI IRI } deriving (Show, Eq, Ord, Typeable) instance Pretty Sign where pretty = printSign findNodeId :: IRI -> Set.Set ResolvedNode -> Set.Set ResolvedNode findNodeId t = Set.filter (\(ResolvedNode _ t1 _) -> t == t1 ) nesyIds :: Sign -> Set.Set IRI nesyIds = Set.map resolvedNeSyId . nodes nesyIdMap :: Set.Set ResolvedNode -> Map.Map IRI IRI nesyIdMap ns = Map.fromList [(i, o) | ResolvedNode o i _ <- Set.toList ns] resolved2Node :: ResolvedNode -> Node resolved2Node (ResolvedNode t i r) = Node t (Just i) r getOntology :: Sign -> OntologyDocument getOntology s = let decls = Declaration [] . mkEntity Class <$> Set.toList (owlClasses s) subClasses = fmap (\(a,b) -> SubClassOf [] (Expression a) (Expression b)) $ Rel.toList (owlTaxonomy s) subClassAxs = ClassAxiom <$> subClasses axs = decls ++ subClassAxs in emptyOntologyDoc { ontology = emptyOntology { axioms = axs}} | determines whether a signature is isLegalSignature :: Sign -> Bool isLegalSignature s = Rel.dom (edges s) `Set.isSubsetOf` nodes s && Rel.ran (edges s) `Set.isSubsetOf` nodes s | pretty for edge e.g. tuple ( ResolvedNode , ResolvedNode ) printEdge :: (ResolvedNode, ResolvedNode) -> Doc printEdge (node1, node2) = pretty node1 <+> text "->" <+> pretty node2 <> semi ( fsep . punctuate ( text " - > " ) $ map pretty [ node1 , node2 ] ) < > semi printSign :: Sign -> Doc printSign s = keyword dataS <+> (specBraces . toDocAsMS . getOntology $ s) $+$ (vcat . map printEdge . Rel.toList . edges $ s) $+$ (vcat . map ((<> semi) . pretty) . Set.toList $ (nodes s Set.\\ Set.union (Rel.dom . edges $ s) (Rel.ran . edges $ s))) addToSig :: Sign -> ResolvedNode -> Sign addToSig sig node = sig {nodes = Set.insert node $ nodes sig} addEdgeToSig :: Sign -> (ResolvedNode, ResolvedNode) -> Sign addEdgeToSig sig (f, t) = sig {edges = Rel.insert f t $ edges sig} addEdgeToSig' :: Sign -> (ResolvedNode, ResolvedNode) -> Sign addEdgeToSig' sig (f, t) = addToSig (addToSig (sig {edges = Rel.insert f t $ edges sig}) f) t unite :: Sign -> Sign -> Sign unite sig1 sig2 = Sign {owlClasses = Set.union (owlClasses sig1) $ owlClasses sig2, owlTaxonomy = Rel.union (owlTaxonomy sig1) $ owlTaxonomy sig2, nodes = Set.union (nodes sig1) $ nodes sig2, idMap = Map.union (idMap sig1) $ idMap sig2, edges = Rel.union (edges sig1) $ edges sig2} emptySig :: Sign emptySig = Sign { owlClasses = Set.empty , owlTaxonomy = Rel.empty , nodes = Set.empty , edges = Rel.empty , idMap = Map.empty} relToSet :: (Ord a, Ord b) => Rel.Relation a b -> Set.Set (a,b) relToSet r = Set.fromList $ Rel.toList r | Determines if is subsignature of sig2 isSubSigOf :: Sign -> Sign -> Bool isSubSigOf sig1 sig2 = owlClasses sig1 `Set.isSubsetOf` owlClasses sig2 && nodes sig1 `Set.isSubsetOf` nodes sig2 && relToSet (edges sig1) `Set.isSubsetOf` relToSet (edges sig2) && relToSet (owlTaxonomy sig1) `Set.isSubsetOf` relToSet (owlTaxonomy sig2) relDiff :: (Ord a, Ord b) => Rel.Relation a b -> Rel.Relation a b -> Rel.Relation a b relDiff r1 r2 = Rel.fromList (l1 List.\\ l2) where l1 = Rel.toList r1 l2 = Rel.toList r2 sigDiff :: Sign -> Sign -> Sign sigDiff sig1 sig2 = Sign {owlClasses = Set.difference (owlClasses sig1) $ owlClasses sig2, owlTaxonomy = relDiff (owlTaxonomy sig1) $ owlTaxonomy sig2, nodes = Set.difference (nodes sig1) $ nodes sig2, idMap = Map.difference (idMap sig1) $ idMap sig2, edges = relDiff (edges sig1) $ edges sig2} sigUnion :: Sign -> Sign -> Result Sign sigUnion s1 s2 = return $ unite s1 s2
2e2ae1b924b7ce63e42ba1c7ab9d71737830caae9e7a91c0a722b74b553810fd
UU-ComputerScience/uhc
Word.hs
# LANGUAGE NoImplicitPrelude , CPP # # OPTIONS_GHC -XNoImplicitPrelude # # EXCLUDE_IF_TARGET js # {-# EXCLUDE_IF_TARGET cr #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Word Copyright : ( c ) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : -- Stability : experimental -- Portability : portable -- -- Unsigned integer types. -- ----------------------------------------------------------------------------- module Data.Word ( -- * Unsigned integral types Word, Word8, Word16, Word32, Word64, -- * Notes -- $notes ) where #ifdef __GLASGOW_HASKELL__ import GHC.Word #endif #ifdef __UHC__ import UHC.Word #endif #ifdef __HUGS__ import Hugs.Word #endif #ifdef __NHC__ import NHC.FFI (Word8, Word16, Word32, Word64) import NHC.SizedTypes (Word8, Word16, Word32, Word64) -- instances of Bits type Word = Word32 #endif $ notes * All arithmetic is performed modulo 2^n , where n is the number of bits in the type . One non - obvious consequence of this is that ' Prelude.negate ' should /not/ raise an error on negative arguments . * For coercing between any two integer types , use ' Prelude.fromIntegral ' , which is specialized for all the common cases so should be fast enough . Coercing word types to and from integer types preserves representation , not sign . * It would be very natural to add a type @Natural@ providing an unbounded size unsigned integer , just as ' Prelude . Integer ' provides unbounded size signed integers . We do not do that yet since there is no demand for it . * The rules that hold for ' Prelude . ' instances over a bounded type such as ' Prelude . Int ' ( see the section of the report dealing with arithmetic sequences ) also hold for the ' Prelude . ' instances over the various ' Word ' types defined here . * Right and left shifts by amounts greater than or equal to the width of the type result in a zero result . This is contrary to the behaviour in C , which is undefined ; a common interpretation is to truncate the shift count to the width of the type , for example @1 \<\ < 32 = = 1@ in some C implementations . * All arithmetic is performed modulo 2^n, where n is the number of bits in the type. One non-obvious consequence of this is that 'Prelude.negate' should /not/ raise an error on negative arguments. * For coercing between any two integer types, use 'Prelude.fromIntegral', which is specialized for all the common cases so should be fast enough. Coercing word types to and from integer types preserves representation, not sign. * It would be very natural to add a type @Natural@ providing an unbounded size unsigned integer, just as 'Prelude.Integer' provides unbounded size signed integers. We do not do that yet since there is no demand for it. * The rules that hold for 'Prelude.Enum' instances over a bounded type such as 'Prelude.Int' (see the section of the Haskell report dealing with arithmetic sequences) also hold for the 'Prelude.Enum' instances over the various 'Word' types defined here. * Right and left shifts by amounts greater than or equal to the width of the type result in a zero result. This is contrary to the behaviour in C, which is undefined; a common interpretation is to truncate the shift count to the width of the type, for example @1 \<\< 32 == 1@ in some C implementations. -}
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/ehclib/uhcbase/Data/Word.hs
haskell
# EXCLUDE_IF_TARGET cr # --------------------------------------------------------------------------- | Module : Data.Word License : BSD-style (see the file libraries/base/LICENSE) Maintainer : Stability : experimental Portability : portable Unsigned integer types. --------------------------------------------------------------------------- * Unsigned integral types * Notes $notes instances of Bits
# LANGUAGE NoImplicitPrelude , CPP # # OPTIONS_GHC -XNoImplicitPrelude # # EXCLUDE_IF_TARGET js # Copyright : ( c ) The University of Glasgow 2001 module Data.Word ( Word, Word8, Word16, Word32, Word64, ) where #ifdef __GLASGOW_HASKELL__ import GHC.Word #endif #ifdef __UHC__ import UHC.Word #endif #ifdef __HUGS__ import Hugs.Word #endif #ifdef __NHC__ import NHC.FFI (Word8, Word16, Word32, Word64) type Word = Word32 #endif $ notes * All arithmetic is performed modulo 2^n , where n is the number of bits in the type . One non - obvious consequence of this is that ' Prelude.negate ' should /not/ raise an error on negative arguments . * For coercing between any two integer types , use ' Prelude.fromIntegral ' , which is specialized for all the common cases so should be fast enough . Coercing word types to and from integer types preserves representation , not sign . * It would be very natural to add a type @Natural@ providing an unbounded size unsigned integer , just as ' Prelude . Integer ' provides unbounded size signed integers . We do not do that yet since there is no demand for it . * The rules that hold for ' Prelude . ' instances over a bounded type such as ' Prelude . Int ' ( see the section of the report dealing with arithmetic sequences ) also hold for the ' Prelude . ' instances over the various ' Word ' types defined here . * Right and left shifts by amounts greater than or equal to the width of the type result in a zero result . This is contrary to the behaviour in C , which is undefined ; a common interpretation is to truncate the shift count to the width of the type , for example @1 \<\ < 32 = = 1@ in some C implementations . * All arithmetic is performed modulo 2^n, where n is the number of bits in the type. One non-obvious consequence of this is that 'Prelude.negate' should /not/ raise an error on negative arguments. * For coercing between any two integer types, use 'Prelude.fromIntegral', which is specialized for all the common cases so should be fast enough. Coercing word types to and from integer types preserves representation, not sign. * It would be very natural to add a type @Natural@ providing an unbounded size unsigned integer, just as 'Prelude.Integer' provides unbounded size signed integers. We do not do that yet since there is no demand for it. * The rules that hold for 'Prelude.Enum' instances over a bounded type such as 'Prelude.Int' (see the section of the Haskell report dealing with arithmetic sequences) also hold for the 'Prelude.Enum' instances over the various 'Word' types defined here. * Right and left shifts by amounts greater than or equal to the width of the type result in a zero result. This is contrary to the behaviour in C, which is undefined; a common interpretation is to truncate the shift count to the width of the type, for example @1 \<\< 32 == 1@ in some C implementations. -}
454a3dbe6f7c02405dfe1c66db0c5e6935f88494dfb61cbe2b44bf96966690eb
ulisesmac/Horarios-FC-UNAM
networking.cljs
(ns horarios-fc.networking (:require [re-frame.core :as rf])) (def domain "") (defn http-request! [{:keys [method url on-success on-failure]}] (-> (js/fetch url #js{:method (name method)}) (.then (fn [response] (.text response))) (.then (fn [text] (on-success text) text)) (.catch (fn [error] (on-failure error))))) (rf/reg-fx :http-request http-request!)
null
https://raw.githubusercontent.com/ulisesmac/Horarios-FC-UNAM/dc203e0b424346f8540bbefd99e5d30572be389f/src/horarios_fc/networking.cljs
clojure
(ns horarios-fc.networking (:require [re-frame.core :as rf])) (def domain "") (defn http-request! [{:keys [method url on-success on-failure]}] (-> (js/fetch url #js{:method (name method)}) (.then (fn [response] (.text response))) (.then (fn [text] (on-success text) text)) (.catch (fn [error] (on-failure error))))) (rf/reg-fx :http-request http-request!)
53f2b968165286d64792361123c4e6ac455a6d41631b6453124e827afe686a87
spurious/sagittarius-scheme-mirror
%3a129.scm
(import (except (rnrs) string-titlecase) (srfi :129) (srfi :64)) (test-begin "SRFI 129 titlecase") ;; values are from SRFI-129 sample implementation tests (test-assert (char-title-case? #\x01C5)) (test-assert (char-title-case? #\x1FFC)) (test-assert (not (char-title-case? #\Z))) (test-assert (not (char-title-case? #\z))) (test-equal #\x01C5 (char-titlecase #\x01C4)) (test-equal #\x01C5 (char-titlecase #\x01C6)) (test-equal #\Z (char-titlecase #\Z)) (test-equal #\Z (char-titlecase #\z)) (let () (define Floo "\xFB02;oo") (define Floo-bar "\xFB02;oo bar") (define Baffle "Ba\xFB04;e") (define LJUBLJANA "\x01C7;ub\x01C7;ana") (define Ljubljana "\x01C8;ub\x01C9;ana") (define ljubljana "\x01C9;ub\x01C9;ana") (define-syntax test (syntax-rules () ((_ expect expr) (test-equal expect expect expr)))) (test "\x01C5;" (string-titlecase "\x01C5;")) (test "\x01C5;" (string-titlecase "\x01C4;")) (test "Ss" (string-titlecase "\x00DF;")) (test "Xi\x0307;" (string-titlecase "x\x0130;")) (test "\x1F88;" (string-titlecase "\x1F80;")) (test "Bar Baz" (string-titlecase "bAr baZ")) (test "Floo" (string-titlecase "floo")) (test "Floo" (string-titlecase "FLOO")) (test "Floo" (string-titlecase Floo)) (test "Floo Bar" (string-titlecase"floo bar")) (test "Floo Bar" (string-titlecase "FLOO BAR")) (test "Floo Bar" (string-titlecase Floo-bar)) (test Baffle (string-titlecase Baffle)) (test Ljubljana (string-titlecase LJUBLJANA)) (test Ljubljana (string-titlecase Ljubljana)) (test Ljubljana (string-titlecase ljubljana))) (test-end)
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/tests/srfi/%253a129.scm
scheme
values are from SRFI-129 sample implementation tests
(import (except (rnrs) string-titlecase) (srfi :129) (srfi :64)) (test-begin "SRFI 129 titlecase") (test-assert (char-title-case? #\x01C5)) (test-assert (char-title-case? #\x1FFC)) (test-assert (not (char-title-case? #\Z))) (test-assert (not (char-title-case? #\z))) (test-equal #\x01C5 (char-titlecase #\x01C4)) (test-equal #\x01C5 (char-titlecase #\x01C6)) (test-equal #\Z (char-titlecase #\Z)) (test-equal #\Z (char-titlecase #\z)) (let () (define Floo "\xFB02;oo") (define Floo-bar "\xFB02;oo bar") (define Baffle "Ba\xFB04;e") (define LJUBLJANA "\x01C7;ub\x01C7;ana") (define Ljubljana "\x01C8;ub\x01C9;ana") (define ljubljana "\x01C9;ub\x01C9;ana") (define-syntax test (syntax-rules () ((_ expect expr) (test-equal expect expect expr)))) (test "\x01C5;" (string-titlecase "\x01C5;")) (test "\x01C5;" (string-titlecase "\x01C4;")) (test "Ss" (string-titlecase "\x00DF;")) (test "Xi\x0307;" (string-titlecase "x\x0130;")) (test "\x1F88;" (string-titlecase "\x1F80;")) (test "Bar Baz" (string-titlecase "bAr baZ")) (test "Floo" (string-titlecase "floo")) (test "Floo" (string-titlecase "FLOO")) (test "Floo" (string-titlecase Floo)) (test "Floo Bar" (string-titlecase"floo bar")) (test "Floo Bar" (string-titlecase "FLOO BAR")) (test "Floo Bar" (string-titlecase Floo-bar)) (test Baffle (string-titlecase Baffle)) (test Ljubljana (string-titlecase LJUBLJANA)) (test Ljubljana (string-titlecase Ljubljana)) (test Ljubljana (string-titlecase ljubljana))) (test-end)
3a4dff8a6decadaea7130c48ef4b039d112d8b48c44e53ab2ce3577cd8beff42
bcambel/oss.io
utils.clj
(ns hsm.utils "Utility functions. TODO: - Separate HTTP related helpers into separate namespace - Write proper extensive tests which would make it easier to understand and would be pretty much self documenting." (:require [clojure.java.io :as io] [clojure.string :as str] [taoensso.timbre :as log] [cheshire.core :refer :all] [ring.util.response :as resp] [clj-time.core :as t] [clj-time.format :as f] [clj-time.local :as l] [clj-time.coerce :as c] [clj-kryo.core :as kryo]) (:import [com.google.common.net InternetDomainName] [java.io ByteArrayOutputStream ByteArrayInputStream] [org.postgresql.util PGobject] [com.esotericsoftware.kryo.io Output Input])) (defn pg-json [value] (doto (PGobject.) (.setType "json") (.setValue value))) (defn kryo-round-trip [expr] (let [bos (ByteArrayOutputStream.)] (with-open [out ^Output (kryo/make-output bos)] (kryo/write-object out expr)) (let [bis (ByteArrayInputStream. (.toByteArray bos))] (with-open [in ^Input (kryo/make-input bis)] (kryo/read-object in))))) (defn kryo-out [expr] (let [bos (ByteArrayOutputStream.)] (with-open [out ^Output (kryo/make-output bos)] (kryo/write-object out expr) out))) ; implement a multi-method for different types (declare in?) (declare !nil?) (defn containss? [s x] (.contains x s)) (defn host->pl->lang [host] (condp containss? (str/lower-case host) "pythonhackers.com" "Python" "clojurehackers.com" "Clojure" "erlangarticles.com" "Erlang" "pythonarticles.com" "Python" nil )) (defn pl->lang [platform] (when (!nil? platform ) (condp = (str/lower-case platform) "cpp" "C++" "csharp" "C#" "python" "Python" "clojure" "Clojure" "clj" "Clojure" "php" "PHP" platform))) (defn is-true [val] (condp instance? val java.lang.String (or (in? ["true" "1"] val) (not (in? ["false" "0"] val))) false)) (defn select-values "clojure.core contains select-keys but not select-values." [m ks] (reduce #(if-let [v (m %2)] (conj %1 v) %1) [] ks)) (defn epoch "Returns the millisecond representation the given datetime as epoch" ([d] (c/to-long d)) ([d format] (if (= format :second) (/ (c/to-long d) 1000) (epoch d)))) (defn now->ep "Returns the microsecond representation of epoch of now." [] (epoch (t/now))) (defn body-as-string "In a given request context (or hash-map contains the body key), returns the body if string, else tries to read input string using Java.io and slurp" [ctx] (if-let [body (:body ctx)] (condp instance? body java.lang.String body (slurp (io/reader body))))) (defn mapkeyw [data] (apply merge (map #(hash-map (keyword %) (get data %)) (keys data)))) (def zero (fn[& args] 0)) (def idseq (atom 0)) (def start (hsm.utils/epoch (t/date-time 2014 1 1))) (defn id-generate "Generate a new ID. Very raw right now. TODO: Replace with a proper ID generator. Like Twitter Snowflake or simirlar" [& args] (let [time (-> (- (hsm.utils/now->ep) start) (bit-shift-left 23)) worker (-> 1 (bit-shift-left 10)) sequence (swap! idseq inc)] (if (> sequence 4095) (swap! idseq zero)) (bit-or time worker sequence))) (defn host-of "Finds the host header of the request" [request] (get-in request [:headers "host"])) ;; TODO: must be placed into a config file. (def domains ["pythonhackers.com" "hackersome.com" "sweet.io"]) (defn domain-of [request] (let [domain (InternetDomainName/from (host-of request))] (.parts domain))) (defn ^:private connect-parts [parts] (clojure.string/join "." parts) ) (defn fqdn Parts of domain as vec (fqdn \"www.pythonhackers.com\") => [\"www\" \"pythonhackers\" \"com\"] Adds www. if necessary TODO: Normally www.domain.com is not equal to domain.com but in our scenario, its same. Find a better name!" [request] (let [parts (domain-of request)] (if (= (count parts) 3) (connect-parts parts) (connect-parts (concat ["www"] (vec parts)))))) (defn id-of "Finds the ID of the request. E.g - /link/:id - /post/:id - /user/:id" ([request] (id-of request :id)) ([request kw] (get-in request [:route-params kw]))) (defn body-of "Reads the JSON body of the request" [request] (parse-string (body-as-string request))) (def mime-types {:json "application/json" :html "text/html"}) (defn type-of "Request Type check" [request mode] (or (is-true (get-in request [:params mode])) (= (name mode) (get-in request [:params :format])) (= (get mime-types mode) (get-in request [:headers "accept"])) (= "XMLHttpRequest" (get-in request [:headers "x-requested-with"])))) (defn whois "Temporary user finder.. Returns a static User ID" [request] ; (log/debug (get-in request [:headers "x-auth-token"])) 243975551163827208) (defn common-of [request] (let [host (host-of request) hosted-pl (host->pl->lang host)] {:host host :body (body-of request) :req-id (:req-id request) :id (id-of request) :host-pl hosted-pl :url (:uri request) :platform (or (or (pl->lang (id-of request :platform)) hosted-pl ) "Python") :json? (type-of request :json) :user (whois request) :limit-by (or (Integer/parseInt (or (get-in request [:params :limit]) "100")) 100) })) (defn byte-array->str "Convert byte array into String" [bytes] (apply str (map char bytes))) (defn cutoff [s maxlen] (if (> (count s) maxlen) (str (subs s 0 maxlen) "...") s)) (defn in? "true if seq contains elm" [seq el] (some #(= el %) seq)) (defn hex-to-str "Partition given key by 2. Concats the char that are found in the position" [s] (apply str (map #(char (Integer/parseInt % 16)) (map (fn[x] (apply str x)) (partition 2 s))))) (defn hexify [s] (apply str (map #(format "%02x" (int %)) s))) (defn unhexify [hex] (apply str (map (fn [[x y]] (char (Integer/parseInt (str x y) 16))) (partition 2 hex)))) (defn hexify2 [s] (apply str (map #(format "%02x" %) (.getBytes s "UTF-8")))) (defn unhexify2 [s] (let [bytes (into-array Byte/TYPE (map (fn [[x y]] (unchecked-byte (Integer/parseInt (str x y) 16))) (partition 2 s)))] (String. bytes "UTF-8"))) (defn max-element [v n] (let [size (count v)] (if (> size n) (do (log/info (format "Size: %d reduced to %d" size n)) (subvec v 0 n)) v))) ;; Following functions borrowed+modified slightly from < > ;; (defn !nil? [x] (not (nil? x))) (defn !blank? [x] (not (str/blank? x))) (defn !neg? [x] (not (neg? x))) (defn !neg-int? [x] (and (integer? x) (!neg? x))) (defn nvec? [n x] (and (vector? x) (= (count x) n))) (def vec1? (partial nvec? 1)) (defn vec2? "Vector of 2 or not. Based on (nvec? n)" [x] (nvec? 2 x)) (defn vec3? [x] (nvec? 3 x)) (defn !nil= ([x y] (and (!nil? x) (= x y))) ([x y & more] (and (!nil? x) (apply = x y more)))) (defn vec* [x] (if (vector? x) x (vec x))) (defn set* [x] (if (set? x) x (set x))) (defn !nil-set [x] (disj (set* x) nil)) (defn conj-some [coll ?x] (if (!nil? ?x) (conj coll ?x) coll)) (defn !!nil? [x] (and (!nil? x) (not (empty? x))))
null
https://raw.githubusercontent.com/bcambel/oss.io/cddb8b8ba4610084bc2f3c78c7837cdec87a8c76/src/clj/hsm/utils.clj
clojure
implement a multi-method for different types TODO: must be placed into a config file. (log/debug (get-in request [:headers "x-auth-token"])) Following functions borrowed+modified slightly from
(ns hsm.utils "Utility functions. TODO: - Separate HTTP related helpers into separate namespace - Write proper extensive tests which would make it easier to understand and would be pretty much self documenting." (:require [clojure.java.io :as io] [clojure.string :as str] [taoensso.timbre :as log] [cheshire.core :refer :all] [ring.util.response :as resp] [clj-time.core :as t] [clj-time.format :as f] [clj-time.local :as l] [clj-time.coerce :as c] [clj-kryo.core :as kryo]) (:import [com.google.common.net InternetDomainName] [java.io ByteArrayOutputStream ByteArrayInputStream] [org.postgresql.util PGobject] [com.esotericsoftware.kryo.io Output Input])) (defn pg-json [value] (doto (PGobject.) (.setType "json") (.setValue value))) (defn kryo-round-trip [expr] (let [bos (ByteArrayOutputStream.)] (with-open [out ^Output (kryo/make-output bos)] (kryo/write-object out expr)) (let [bis (ByteArrayInputStream. (.toByteArray bos))] (with-open [in ^Input (kryo/make-input bis)] (kryo/read-object in))))) (defn kryo-out [expr] (let [bos (ByteArrayOutputStream.)] (with-open [out ^Output (kryo/make-output bos)] (kryo/write-object out expr) out))) (declare in?) (declare !nil?) (defn containss? [s x] (.contains x s)) (defn host->pl->lang [host] (condp containss? (str/lower-case host) "pythonhackers.com" "Python" "clojurehackers.com" "Clojure" "erlangarticles.com" "Erlang" "pythonarticles.com" "Python" nil )) (defn pl->lang [platform] (when (!nil? platform ) (condp = (str/lower-case platform) "cpp" "C++" "csharp" "C#" "python" "Python" "clojure" "Clojure" "clj" "Clojure" "php" "PHP" platform))) (defn is-true [val] (condp instance? val java.lang.String (or (in? ["true" "1"] val) (not (in? ["false" "0"] val))) false)) (defn select-values "clojure.core contains select-keys but not select-values." [m ks] (reduce #(if-let [v (m %2)] (conj %1 v) %1) [] ks)) (defn epoch "Returns the millisecond representation the given datetime as epoch" ([d] (c/to-long d)) ([d format] (if (= format :second) (/ (c/to-long d) 1000) (epoch d)))) (defn now->ep "Returns the microsecond representation of epoch of now." [] (epoch (t/now))) (defn body-as-string "In a given request context (or hash-map contains the body key), returns the body if string, else tries to read input string using Java.io and slurp" [ctx] (if-let [body (:body ctx)] (condp instance? body java.lang.String body (slurp (io/reader body))))) (defn mapkeyw [data] (apply merge (map #(hash-map (keyword %) (get data %)) (keys data)))) (def zero (fn[& args] 0)) (def idseq (atom 0)) (def start (hsm.utils/epoch (t/date-time 2014 1 1))) (defn id-generate "Generate a new ID. Very raw right now. TODO: Replace with a proper ID generator. Like Twitter Snowflake or simirlar" [& args] (let [time (-> (- (hsm.utils/now->ep) start) (bit-shift-left 23)) worker (-> 1 (bit-shift-left 10)) sequence (swap! idseq inc)] (if (> sequence 4095) (swap! idseq zero)) (bit-or time worker sequence))) (defn host-of "Finds the host header of the request" [request] (get-in request [:headers "host"])) (def domains ["pythonhackers.com" "hackersome.com" "sweet.io"]) (defn domain-of [request] (let [domain (InternetDomainName/from (host-of request))] (.parts domain))) (defn ^:private connect-parts [parts] (clojure.string/join "." parts) ) (defn fqdn Parts of domain as vec (fqdn \"www.pythonhackers.com\") => [\"www\" \"pythonhackers\" \"com\"] Adds www. if necessary TODO: Normally www.domain.com is not equal to domain.com but in our scenario, its same. Find a better name!" [request] (let [parts (domain-of request)] (if (= (count parts) 3) (connect-parts parts) (connect-parts (concat ["www"] (vec parts)))))) (defn id-of "Finds the ID of the request. E.g - /link/:id - /post/:id - /user/:id" ([request] (id-of request :id)) ([request kw] (get-in request [:route-params kw]))) (defn body-of "Reads the JSON body of the request" [request] (parse-string (body-as-string request))) (def mime-types {:json "application/json" :html "text/html"}) (defn type-of "Request Type check" [request mode] (or (is-true (get-in request [:params mode])) (= (name mode) (get-in request [:params :format])) (= (get mime-types mode) (get-in request [:headers "accept"])) (= "XMLHttpRequest" (get-in request [:headers "x-requested-with"])))) (defn whois "Temporary user finder.. Returns a static User ID" [request] 243975551163827208) (defn common-of [request] (let [host (host-of request) hosted-pl (host->pl->lang host)] {:host host :body (body-of request) :req-id (:req-id request) :id (id-of request) :host-pl hosted-pl :url (:uri request) :platform (or (or (pl->lang (id-of request :platform)) hosted-pl ) "Python") :json? (type-of request :json) :user (whois request) :limit-by (or (Integer/parseInt (or (get-in request [:params :limit]) "100")) 100) })) (defn byte-array->str "Convert byte array into String" [bytes] (apply str (map char bytes))) (defn cutoff [s maxlen] (if (> (count s) maxlen) (str (subs s 0 maxlen) "...") s)) (defn in? "true if seq contains elm" [seq el] (some #(= el %) seq)) (defn hex-to-str "Partition given key by 2. Concats the char that are found in the position" [s] (apply str (map #(char (Integer/parseInt % 16)) (map (fn[x] (apply str x)) (partition 2 s))))) (defn hexify [s] (apply str (map #(format "%02x" (int %)) s))) (defn unhexify [hex] (apply str (map (fn [[x y]] (char (Integer/parseInt (str x y) 16))) (partition 2 hex)))) (defn hexify2 [s] (apply str (map #(format "%02x" %) (.getBytes s "UTF-8")))) (defn unhexify2 [s] (let [bytes (into-array Byte/TYPE (map (fn [[x y]] (unchecked-byte (Integer/parseInt (str x y) 16))) (partition 2 s)))] (String. bytes "UTF-8"))) (defn max-element [v n] (let [size (count v)] (if (> size n) (do (log/info (format "Size: %d reduced to %d" size n)) (subvec v 0 n)) v))) < > (defn !nil? [x] (not (nil? x))) (defn !blank? [x] (not (str/blank? x))) (defn !neg? [x] (not (neg? x))) (defn !neg-int? [x] (and (integer? x) (!neg? x))) (defn nvec? [n x] (and (vector? x) (= (count x) n))) (def vec1? (partial nvec? 1)) (defn vec2? "Vector of 2 or not. Based on (nvec? n)" [x] (nvec? 2 x)) (defn vec3? [x] (nvec? 3 x)) (defn !nil= ([x y] (and (!nil? x) (= x y))) ([x y & more] (and (!nil? x) (apply = x y more)))) (defn vec* [x] (if (vector? x) x (vec x))) (defn set* [x] (if (set? x) x (set x))) (defn !nil-set [x] (disj (set* x) nil)) (defn conj-some [coll ?x] (if (!nil? ?x) (conj coll ?x) coll)) (defn !!nil? [x] (and (!nil? x) (not (empty? x))))
ac076f59e082c0fddea0351b12c48d360632a130c5399c8fb3520024096df79f
abailly/aws-lambda-haskell
Lambda.hs
{-# LANGUAGE OverloadedStrings #-} module AWS.Lambda where import Control.Lens import Control.Monad.Catch import Control.Monad.Trans (liftIO) import Control.Monad.Trans.AWS import Control.Monad.Trans.Resource import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import Network.AWS.Lambda -- | Default role to use for creating function -- -- TODO: parameterize defaultRole :: Text defaultRole = "arn:aws:iam::259394719635:role/lambda" defaultHandler :: Text defaultHandler = "run.handle" createFunctionWithZip :: (MonadResource m, MonadCatch m) => Text -> FilePath -> AWST m FunctionConfiguration createFunctionWithZip fName zipFile = do code <- liftIO $ LBS.readFile zipFile send (createFunction fName NODEJS4_3 defaultRole defaultHandler (set fcZipFile (Just $ LBS.toStrict code) functionCode))
null
https://raw.githubusercontent.com/abailly/aws-lambda-haskell/df9afb7498500c2282515752f905a6e05bba9658/AWS/Lambda.hs
haskell
# LANGUAGE OverloadedStrings # | Default role to use for creating function TODO: parameterize
module AWS.Lambda where import Control.Lens import Control.Monad.Catch import Control.Monad.Trans (liftIO) import Control.Monad.Trans.AWS import Control.Monad.Trans.Resource import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import Network.AWS.Lambda defaultRole :: Text defaultRole = "arn:aws:iam::259394719635:role/lambda" defaultHandler :: Text defaultHandler = "run.handle" createFunctionWithZip :: (MonadResource m, MonadCatch m) => Text -> FilePath -> AWST m FunctionConfiguration createFunctionWithZip fName zipFile = do code <- liftIO $ LBS.readFile zipFile send (createFunction fName NODEJS4_3 defaultRole defaultHandler (set fcZipFile (Just $ LBS.toStrict code) functionCode))
e3629988aaf4c2ed8876c0d50235094bcad231beb313e177f137e4ad31dcefed
samply/blaze
resource_cache_spec.clj
(ns blaze.db.resource-cache-spec (:require [blaze.async.comp-spec] [blaze.db.resource-cache.spec] [blaze.db.resource-store.spec]))
null
https://raw.githubusercontent.com/samply/blaze/e84c106b5ca235600c20ba74fe8a2295eb18f350/modules/db/test/blaze/db/resource_cache_spec.clj
clojure
(ns blaze.db.resource-cache-spec (:require [blaze.async.comp-spec] [blaze.db.resource-cache.spec] [blaze.db.resource-store.spec]))
5450b1668e686c3f2545a062a41237e524a280e1bea37206d49c22a757bc84b8
ntoronto/pict3d
pict3d-combinators.rkt
#lang racket/base (require racket/contract typed/untyped-utils (rename-in "typed-pict3d-combinators.rkt" [bend typed-bend] [bend-smooth typed-bend-smooth] [bend-pict3d typed-bend-pict3d]) "pict3d-struct.rkt" "user-types.rkt") (provide (except-out (all-from-out "typed-pict3d-combinators.rkt") typed-bend typed-bend-pict3d typed-bend-smooth) with-color with-emitted with-material bend) (define/contract untyped-bend (->i ([arg1 (or/c pict3d? real?)] [arg2 (or/c real? interval?)]) ([zivl (arg1) (if (pict3d? arg1) interval? none/c)]) [result (arg1 arg2) (if (pict3d? arg1) pict3d? smooth?)]) (case-lambda [(arg1 arg2) (cond [(and (pict3d? arg1) (real? arg2)) (typed-bend-pict3d arg1 arg2)] [(and (real? arg1) (interval? arg2)) (typed-bend-smooth arg1 arg2)])] [(p angle zivl) (typed-bend-pict3d p angle zivl)])) (define-typed/untyped-identifier bend typed-bend untyped-bend) (define-syntax-rule (with-color c body ...) (parameterize ([current-color c]) body ...)) (define-syntax-rule (with-emitted e body ...) (parameterize ([current-emitted e]) body ...)) (define-syntax-rule (with-material m body ...) (parameterize ([current-material m]) body ...))
null
https://raw.githubusercontent.com/ntoronto/pict3d/09283c9d930c63b6a6a3f2caa43e029222091bdb/pict3d/private/gui/pict3d-combinators.rkt
racket
#lang racket/base (require racket/contract typed/untyped-utils (rename-in "typed-pict3d-combinators.rkt" [bend typed-bend] [bend-smooth typed-bend-smooth] [bend-pict3d typed-bend-pict3d]) "pict3d-struct.rkt" "user-types.rkt") (provide (except-out (all-from-out "typed-pict3d-combinators.rkt") typed-bend typed-bend-pict3d typed-bend-smooth) with-color with-emitted with-material bend) (define/contract untyped-bend (->i ([arg1 (or/c pict3d? real?)] [arg2 (or/c real? interval?)]) ([zivl (arg1) (if (pict3d? arg1) interval? none/c)]) [result (arg1 arg2) (if (pict3d? arg1) pict3d? smooth?)]) (case-lambda [(arg1 arg2) (cond [(and (pict3d? arg1) (real? arg2)) (typed-bend-pict3d arg1 arg2)] [(and (real? arg1) (interval? arg2)) (typed-bend-smooth arg1 arg2)])] [(p angle zivl) (typed-bend-pict3d p angle zivl)])) (define-typed/untyped-identifier bend typed-bend untyped-bend) (define-syntax-rule (with-color c body ...) (parameterize ([current-color c]) body ...)) (define-syntax-rule (with-emitted e body ...) (parameterize ([current-emitted e]) body ...)) (define-syntax-rule (with-material m body ...) (parameterize ([current-material m]) body ...))
c01f613ac546401d81287f96d8da31948a48cd6951194e12ed49279fb29f1085
lspector/Clojush
majority.clj
;; majority.clj an example problem for clojush , a Push / PushGP system written in Clojure , , 2011 . (ns clojush.problems.synthetic.majority (:use [clojush.pushgp.pushgp] [clojush.pushstate] [clojush.random] [clojush.interpreter] [clojure.math.numeric-tower])) ;;;;;;;;;;;; ;; The "majority" problem: have fewer negative complements than respective positive integers ;; (defonce global-problem-size (atom 16)) (defn majority-fitness "Returns a fitness function for the lid problem for specified depth and number of nodes." [individual] (let [f (frequencies (filter number? (flatten (:program individual)))) dfs (map #(if (or (and (contains? f %) (not (contains? f (- %)))) (and (contains? f %) (contains? f (- %)) (>= (- (f %) (f (- %))) 0))) 0 1) (range 1 (inc @global-problem-size)))] (assoc individual :errors dfs))) (defn make-majority-instructions "Make the majority instructions for a given problem size." [problem-size] (list (fn [] (inc (lrand-int problem-size))) (fn [] (- (inc (lrand-int problem-size)))))) (defn majority-pushgp "Run Order with pushgp." [args] (let [size (or (:size args) 16) atom-generators (make-majority-instructions size)] (reset! global-problem-size size) (println "problem-size =" size) (def argmap {:max-points (* 10 4 size) :max-genome-size-in-initial-program (* 10 size) :error-function majority-fitness :atom-generators atom-generators :epigenetic-markers [] :parent-selection :tournament :genetic-operator-probabilities {:alternation 0.5 :uniform-mutation 0.5} :uniform-mutation-constant-tweak-rate 0.0 }))) (majority-pushgp {})
null
https://raw.githubusercontent.com/lspector/Clojush/685b991535607cf942ae1500557171a0739982c3/src/clojush/problems/synthetic/majority.clj
clojure
majority.clj The "majority" problem: have fewer negative complements than respective positive integers
an example problem for clojush , a Push / PushGP system written in Clojure , , 2011 . (ns clojush.problems.synthetic.majority (:use [clojush.pushgp.pushgp] [clojush.pushstate] [clojush.random] [clojush.interpreter] [clojure.math.numeric-tower])) (defonce global-problem-size (atom 16)) (defn majority-fitness "Returns a fitness function for the lid problem for specified depth and number of nodes." [individual] (let [f (frequencies (filter number? (flatten (:program individual)))) dfs (map #(if (or (and (contains? f %) (not (contains? f (- %)))) (and (contains? f %) (contains? f (- %)) (>= (- (f %) (f (- %))) 0))) 0 1) (range 1 (inc @global-problem-size)))] (assoc individual :errors dfs))) (defn make-majority-instructions "Make the majority instructions for a given problem size." [problem-size] (list (fn [] (inc (lrand-int problem-size))) (fn [] (- (inc (lrand-int problem-size)))))) (defn majority-pushgp "Run Order with pushgp." [args] (let [size (or (:size args) 16) atom-generators (make-majority-instructions size)] (reset! global-problem-size size) (println "problem-size =" size) (def argmap {:max-points (* 10 4 size) :max-genome-size-in-initial-program (* 10 size) :error-function majority-fitness :atom-generators atom-generators :epigenetic-markers [] :parent-selection :tournament :genetic-operator-probabilities {:alternation 0.5 :uniform-mutation 0.5} :uniform-mutation-constant-tweak-rate 0.0 }))) (majority-pushgp {})
15c049ffbfb7889c84eb508a9550c722a794aaaa51c4e15f44abafc9990d79fe
dmitryvk/sbcl-win32-threads
alloc.lisp
;;;; allocation VOPs for the PPC This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!VM") ;;;; LIST and LIST* (define-vop (list-or-list*) (:args (things :more t)) (:temporary (:scs (descriptor-reg) :type list) ptr) (:temporary (:scs (descriptor-reg)) temp) (:temporary (:scs (descriptor-reg) :type list :to (:result 0) :target result) res) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:temporary (:scs (non-descriptor-reg)) alloc-temp) (:info num) (:results (result :scs (descriptor-reg))) (:variant-vars star) (:policy :safe) (:node-var node) #!-gencgc (:ignore alloc-temp) (:generator 0 (cond ((zerop num) (move result null-tn)) ((and star (= num 1)) (move result (tn-ref-tn things))) (t (macrolet ((maybe-load (tn) (once-only ((tn tn)) `(sc-case ,tn ((any-reg descriptor-reg zero null) ,tn) (control-stack (load-stack-tn temp ,tn) temp))))) (let* ((dx-p (node-stack-allocate-p node)) (cons-cells (if star (1- num) num)) (alloc (* (pad-data-block cons-size) cons-cells))) (pseudo-atomic (pa-flag) (if dx-p (progn (align-csp res) (inst clrrwi res csp-tn n-lowtag-bits) (inst ori res res list-pointer-lowtag) (inst addi csp-tn csp-tn alloc)) (allocation res alloc list-pointer-lowtag :temp-tn alloc-temp :flag-tn pa-flag)) (move ptr res) (dotimes (i (1- cons-cells)) (storew (maybe-load (tn-ref-tn things)) ptr cons-car-slot list-pointer-lowtag) (setf things (tn-ref-across things)) (inst addi ptr ptr (pad-data-block cons-size)) (storew ptr ptr (- cons-cdr-slot cons-size) list-pointer-lowtag)) (storew (maybe-load (tn-ref-tn things)) ptr cons-car-slot list-pointer-lowtag) (storew (if star (maybe-load (tn-ref-tn (tn-ref-across things))) null-tn) ptr cons-cdr-slot list-pointer-lowtag)) (move result res))))))) (define-vop (list list-or-list*) (:variant nil)) (define-vop (list* list-or-list*) (:variant t)) ;;;; Special purpose inline allocators. (define-vop (allocate-code-object) (:args (boxed-arg :scs (any-reg)) (unboxed-arg :scs (any-reg))) (:results (result :scs (descriptor-reg))) (:temporary (:scs (non-descriptor-reg)) ndescr) (:temporary (:scs (non-descriptor-reg)) size) (:temporary (:scs (any-reg) :from (:argument 0)) boxed) (:temporary (:scs (non-descriptor-reg) :from (:argument 1)) unboxed) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:generator 100 (inst addi boxed boxed-arg (fixnumize (1+ code-trace-table-offset-slot))) (inst clrrwi boxed boxed n-lowtag-bits) (inst srwi unboxed unboxed-arg word-shift) (inst addi unboxed unboxed lowtag-mask) (inst clrrwi unboxed unboxed n-lowtag-bits) (pseudo-atomic (pa-flag) Note : we do n't have to subtract off the 4 that was added by ;; pseudo-atomic, because oring in other-pointer-lowtag just adds ;; it right back. (inst add size boxed unboxed) (allocation result size other-pointer-lowtag :temp-tn ndescr :flag-tn pa-flag) (inst slwi ndescr boxed (- n-widetag-bits word-shift)) (inst ori ndescr ndescr code-header-widetag) (storew ndescr result 0 other-pointer-lowtag) (storew unboxed result code-code-size-slot other-pointer-lowtag) (storew null-tn result code-entry-points-slot other-pointer-lowtag) (storew null-tn result code-debug-info-slot other-pointer-lowtag)))) (define-vop (make-fdefn) (:args (name :scs (descriptor-reg) :to :eval)) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:results (result :scs (descriptor-reg) :from :argument)) (:policy :fast-safe) (:translate make-fdefn) (:generator 37 (with-fixed-allocation (result pa-flag temp fdefn-widetag fdefn-size) (inst lr temp (make-fixup "undefined_tramp" :foreign)) (storew name result fdefn-name-slot other-pointer-lowtag) (storew null-tn result fdefn-fun-slot other-pointer-lowtag) (storew temp result fdefn-raw-addr-slot other-pointer-lowtag)))) (define-vop (make-closure) (:args (function :to :save :scs (descriptor-reg))) (:info length stack-allocate-p) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:results (result :scs (descriptor-reg))) (:generator 10 (let* ((size (+ length closure-info-offset)) (alloc-size (pad-data-block size))) (pseudo-atomic (pa-flag) (if stack-allocate-p (progn (align-csp result) (inst clrrwi. result csp-tn n-lowtag-bits) (inst addi csp-tn csp-tn alloc-size) (inst ori result result fun-pointer-lowtag) (inst lr temp (logior (ash (1- size) n-widetag-bits) closure-header-widetag))) (progn (allocation result (pad-data-block size) fun-pointer-lowtag :temp-tn temp :flag-tn pa-flag) (inst lr temp (logior (ash (1- size) n-widetag-bits) closure-header-widetag)))) (storew temp result 0 fun-pointer-lowtag) (storew function result closure-fun-slot fun-pointer-lowtag))))) ;;; The compiler likes to be able to directly make value cells. ;;; (define-vop (make-value-cell) (:args (value :to :save :scs (descriptor-reg any-reg))) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:info stack-allocate-p) (:ignore stack-allocate-p) (:results (result :scs (descriptor-reg))) (:generator 10 (with-fixed-allocation (result pa-flag temp value-cell-header-widetag value-cell-size) (storew value result value-cell-value-slot other-pointer-lowtag)))) ;;;; Automatic allocators for primitive objects. (define-vop (make-unbound-marker) (:args) (:results (result :scs (any-reg))) (:generator 1 (inst li result unbound-marker-widetag))) (define-vop (make-funcallable-instance-tramp) (:args) (:results (result :scs (any-reg))) (:generator 1 (inst lr result (make-fixup "funcallable_instance_tramp" :foreign)))) (define-vop (fixed-alloc) (:args) (:info name words type lowtag stack-allocate-p) (:ignore name stack-allocate-p) (:results (result :scs (descriptor-reg))) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:generator 4 (with-fixed-allocation (result pa-flag temp type words :lowtag lowtag) ))) (define-vop (var-alloc) (:args (extra :scs (any-reg))) (:arg-types positive-fixnum) (:info name words type lowtag) (:ignore name #!-gencgc temp) (:results (result :scs (descriptor-reg))) (:temporary (:scs (any-reg)) bytes) (:temporary (:scs (non-descriptor-reg)) header) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:generator 6 (inst addi bytes extra (* (1+ words) n-word-bytes)) (inst slwi header bytes (- n-widetag-bits n-fixnum-tag-bits)) (inst addi header header (+ (ash -2 n-widetag-bits) type)) (inst clrrwi bytes bytes n-lowtag-bits) (pseudo-atomic (pa-flag) (allocation result bytes lowtag :temp-tn temp :flag-tn pa-flag) (storew header result 0 lowtag))))
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/ppc/alloc.lisp
lisp
allocation VOPs for the PPC more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. LIST and LIST* Special purpose inline allocators. pseudo-atomic, because oring in other-pointer-lowtag just adds it right back. The compiler likes to be able to directly make value cells. Automatic allocators for primitive objects.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!VM") (define-vop (list-or-list*) (:args (things :more t)) (:temporary (:scs (descriptor-reg) :type list) ptr) (:temporary (:scs (descriptor-reg)) temp) (:temporary (:scs (descriptor-reg) :type list :to (:result 0) :target result) res) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:temporary (:scs (non-descriptor-reg)) alloc-temp) (:info num) (:results (result :scs (descriptor-reg))) (:variant-vars star) (:policy :safe) (:node-var node) #!-gencgc (:ignore alloc-temp) (:generator 0 (cond ((zerop num) (move result null-tn)) ((and star (= num 1)) (move result (tn-ref-tn things))) (t (macrolet ((maybe-load (tn) (once-only ((tn tn)) `(sc-case ,tn ((any-reg descriptor-reg zero null) ,tn) (control-stack (load-stack-tn temp ,tn) temp))))) (let* ((dx-p (node-stack-allocate-p node)) (cons-cells (if star (1- num) num)) (alloc (* (pad-data-block cons-size) cons-cells))) (pseudo-atomic (pa-flag) (if dx-p (progn (align-csp res) (inst clrrwi res csp-tn n-lowtag-bits) (inst ori res res list-pointer-lowtag) (inst addi csp-tn csp-tn alloc)) (allocation res alloc list-pointer-lowtag :temp-tn alloc-temp :flag-tn pa-flag)) (move ptr res) (dotimes (i (1- cons-cells)) (storew (maybe-load (tn-ref-tn things)) ptr cons-car-slot list-pointer-lowtag) (setf things (tn-ref-across things)) (inst addi ptr ptr (pad-data-block cons-size)) (storew ptr ptr (- cons-cdr-slot cons-size) list-pointer-lowtag)) (storew (maybe-load (tn-ref-tn things)) ptr cons-car-slot list-pointer-lowtag) (storew (if star (maybe-load (tn-ref-tn (tn-ref-across things))) null-tn) ptr cons-cdr-slot list-pointer-lowtag)) (move result res))))))) (define-vop (list list-or-list*) (:variant nil)) (define-vop (list* list-or-list*) (:variant t)) (define-vop (allocate-code-object) (:args (boxed-arg :scs (any-reg)) (unboxed-arg :scs (any-reg))) (:results (result :scs (descriptor-reg))) (:temporary (:scs (non-descriptor-reg)) ndescr) (:temporary (:scs (non-descriptor-reg)) size) (:temporary (:scs (any-reg) :from (:argument 0)) boxed) (:temporary (:scs (non-descriptor-reg) :from (:argument 1)) unboxed) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:generator 100 (inst addi boxed boxed-arg (fixnumize (1+ code-trace-table-offset-slot))) (inst clrrwi boxed boxed n-lowtag-bits) (inst srwi unboxed unboxed-arg word-shift) (inst addi unboxed unboxed lowtag-mask) (inst clrrwi unboxed unboxed n-lowtag-bits) (pseudo-atomic (pa-flag) Note : we do n't have to subtract off the 4 that was added by (inst add size boxed unboxed) (allocation result size other-pointer-lowtag :temp-tn ndescr :flag-tn pa-flag) (inst slwi ndescr boxed (- n-widetag-bits word-shift)) (inst ori ndescr ndescr code-header-widetag) (storew ndescr result 0 other-pointer-lowtag) (storew unboxed result code-code-size-slot other-pointer-lowtag) (storew null-tn result code-entry-points-slot other-pointer-lowtag) (storew null-tn result code-debug-info-slot other-pointer-lowtag)))) (define-vop (make-fdefn) (:args (name :scs (descriptor-reg) :to :eval)) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:results (result :scs (descriptor-reg) :from :argument)) (:policy :fast-safe) (:translate make-fdefn) (:generator 37 (with-fixed-allocation (result pa-flag temp fdefn-widetag fdefn-size) (inst lr temp (make-fixup "undefined_tramp" :foreign)) (storew name result fdefn-name-slot other-pointer-lowtag) (storew null-tn result fdefn-fun-slot other-pointer-lowtag) (storew temp result fdefn-raw-addr-slot other-pointer-lowtag)))) (define-vop (make-closure) (:args (function :to :save :scs (descriptor-reg))) (:info length stack-allocate-p) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:results (result :scs (descriptor-reg))) (:generator 10 (let* ((size (+ length closure-info-offset)) (alloc-size (pad-data-block size))) (pseudo-atomic (pa-flag) (if stack-allocate-p (progn (align-csp result) (inst clrrwi. result csp-tn n-lowtag-bits) (inst addi csp-tn csp-tn alloc-size) (inst ori result result fun-pointer-lowtag) (inst lr temp (logior (ash (1- size) n-widetag-bits) closure-header-widetag))) (progn (allocation result (pad-data-block size) fun-pointer-lowtag :temp-tn temp :flag-tn pa-flag) (inst lr temp (logior (ash (1- size) n-widetag-bits) closure-header-widetag)))) (storew temp result 0 fun-pointer-lowtag) (storew function result closure-fun-slot fun-pointer-lowtag))))) (define-vop (make-value-cell) (:args (value :to :save :scs (descriptor-reg any-reg))) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:info stack-allocate-p) (:ignore stack-allocate-p) (:results (result :scs (descriptor-reg))) (:generator 10 (with-fixed-allocation (result pa-flag temp value-cell-header-widetag value-cell-size) (storew value result value-cell-value-slot other-pointer-lowtag)))) (define-vop (make-unbound-marker) (:args) (:results (result :scs (any-reg))) (:generator 1 (inst li result unbound-marker-widetag))) (define-vop (make-funcallable-instance-tramp) (:args) (:results (result :scs (any-reg))) (:generator 1 (inst lr result (make-fixup "funcallable_instance_tramp" :foreign)))) (define-vop (fixed-alloc) (:args) (:info name words type lowtag stack-allocate-p) (:ignore name stack-allocate-p) (:results (result :scs (descriptor-reg))) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:generator 4 (with-fixed-allocation (result pa-flag temp type words :lowtag lowtag) ))) (define-vop (var-alloc) (:args (extra :scs (any-reg))) (:arg-types positive-fixnum) (:info name words type lowtag) (:ignore name #!-gencgc temp) (:results (result :scs (descriptor-reg))) (:temporary (:scs (any-reg)) bytes) (:temporary (:scs (non-descriptor-reg)) header) (:temporary (:scs (non-descriptor-reg)) temp) (:temporary (:sc non-descriptor-reg :offset nl3-offset) pa-flag) (:generator 6 (inst addi bytes extra (* (1+ words) n-word-bytes)) (inst slwi header bytes (- n-widetag-bits n-fixnum-tag-bits)) (inst addi header header (+ (ash -2 n-widetag-bits) type)) (inst clrrwi bytes bytes n-lowtag-bits) (pseudo-atomic (pa-flag) (allocation result bytes lowtag :temp-tn temp :flag-tn pa-flag) (storew header result 0 lowtag))))
98fe5a7eeb7d7d00553f2c6662b15aa7db7571d14a7976f557f50cad1ed482f8
pouriya/cfg
cfg_reader_env.erl
%%% ---------------------------------------------------------------------------- @author < > %%% @hidden %% ----------------------------------------------------------------------------- -module(cfg_reader_env). -behaviour(cfg_reader). -author(''). %% ----------------------------------------------------------------------------- %% Exports: %% 'config_reader' callback: -export([read_config/1]). %% ----------------------------------------------------------------------------- %% 'config_reader' callback: read_config(App) when erlang:is_atom(App) -> {ok, application:get_all_env(App)}; read_config({App, Key}) when erlang:is_atom(App) andalso erlang:is_atom(Key) -> case application:get_env(App, Key) of {ok, _}=Ok -> Ok; _ -> % undefined { error, { env, #{ reason => key_not_found, key => Key, application => App } } } end.
null
https://raw.githubusercontent.com/pouriya/cfg/b03eb73549e2fa11b88f91db73f700d7e6ef4617/src/readers/cfg_reader_env.erl
erlang
---------------------------------------------------------------------------- @hidden ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Exports: 'config_reader' callback: ----------------------------------------------------------------------------- 'config_reader' callback: undefined
@author < > -module(cfg_reader_env). -behaviour(cfg_reader). -author(''). -export([read_config/1]). read_config(App) when erlang:is_atom(App) -> {ok, application:get_all_env(App)}; read_config({App, Key}) when erlang:is_atom(App) andalso erlang:is_atom(Key) -> case application:get_env(App, Key) of {ok, _}=Ok -> Ok; { error, { env, #{ reason => key_not_found, key => Key, application => App } } } end.
d45b0eae857a6f1b64dc67ae1be0ec2d9578757f0c0017d6d8c86409f5825371
Decentralized-Pictures/T4L3NT
block.mli
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Metastate AG < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Protocol open Alpha_context type t = { hash : Block_hash.t; header : Block_header.t; operations : Operation.packed list; context : Tezos_protocol_environment.Context.t; (** Resulting context *) } type block = t val rpc_ctxt : t Environment.RPC_context.simple * Policies to select the next baker : - [ By_round r ] selects the baker at round [ r ] - [ By_account pkh ] selects the first slot for baker [ pkh ] - [ Excluding pkhs ] selects the first baker that does n't belong to ] - [By_round r] selects the baker at round [r] - [By_account pkh] selects the first slot for baker [pkh] - [Excluding pkhs] selects the first baker that doesn't belong to [pkhs] *) type baker_policy = | By_round of int | By_account of public_key_hash | Excluding of public_key_hash list (** The default baking functions below is to use (blocks) [Application] mode. Setting [baking_mode] allows to switch to [Full_construction] mode. *) type baking_mode = Application | Baking * Returns ( account , round , timestamp ) of the next baker given a policy , defaults to By_round 0 . a policy, defaults to By_round 0. *) val get_next_baker : ?policy:baker_policy -> t -> (public_key_hash * int * Time.Protocol.t) tzresult Lwt.t val get_round : block -> Round.t tzresult module Forge : sig val contents : ?proof_of_work_nonce:Bytes.t -> ?seed_nonce_hash:Nonce_hash.t -> ?liquidity_baking_escape_vote:bool -> payload_hash:Block_payload_hash.t -> payload_round:Round.t -> unit -> Block_header.contents type header val classify_operations : packed_operation list -> packed_operation list list (** Forges a correct header following the policy. The header can then be modified and applied with [apply]. *) val forge_header : ?locked_round:Alpha_context.Round.t option -> ?payload_round:Round.t option -> ?policy:baker_policy -> ?timestamp:Timestamp.time -> ?operations:Operation.packed list -> ?liquidity_baking_escape_vote:bool -> t -> header tzresult Lwt.t (** Sets uniquely seed_nonce_hash of a header *) val set_seed_nonce_hash : Nonce_hash.t option -> header -> header (** Sets the baker that will sign the header to an arbitrary pkh *) val set_baker : public_key_hash -> header -> header (** Signs the header with the key of the baker configured in the header. The header can no longer be modified, only applied. *) val sign_header : header -> Block_header.block_header tzresult Lwt.t end val check_constants_consistency : Constants.parametric -> unit tzresult Lwt.t (** [genesis <opts> accounts] : generates an initial block with the given constants [<opts>] and initializes [accounts] with their associated amounts. *) val genesis : ?commitments:Commitment.t list -> ?consensus_threshold:int -> ?min_proposal_quorum:int32 -> ?bootstrap_contracts:Parameters.bootstrap_contract list -> ?level:int32 -> ?cost_per_byte:Tez.t -> ?liquidity_baking_subsidy:Tez.t -> ?endorsing_reward_per_slot:Tez.t -> ?baking_reward_bonus_per_slot:Tez.t -> ?baking_reward_fixed_portion:Tez.t -> ?origination_size:int -> ?blocks_per_cycle:int32 -> (Account.t * Tez.tez) list -> block tzresult Lwt.t val genesis_with_parameters : Parameters.t -> block tzresult Lwt.t (** [alpha_context <opts> accounts] : instantiates an alpha_context with the given constants [<opts>] and initializes [accounts] with their associated amounts. *) val alpha_context : ?commitments:Commitment.t list -> ?min_proposal_quorum:int32 -> (Account.t * Tez.tez) list -> Alpha_context.t tzresult Lwt.t (** [get_application_vstate pred operations] constructs a protocol validation environment for operations in application mode on top of the given block with the given operations. It's a shortcut for [begin_application] *) val get_application_vstate : t -> Protocol.operation list -> validation_state tzresult Lwt.t (** [get_construction_vstate ?policy ?timestamp ?protocol_data pred] constructs a protocol validation environment for operations in construction mode on top of the given block. The mode is full(baking)/partial(mempool) if [protocol_data] given/absent. It's a shortcut for [begin_construction] *) val get_construction_vstate : ?policy:baker_policy -> ?timestamp:Timestamp.time -> ?protocol_data:block_header_data option -> block -> validation_state tzresult Lwt.t (** applies a signed header and its operations to a block and obtains a new block *) val apply : Block_header.block_header -> ?operations:Operation.packed list -> t -> t tzresult Lwt.t (** [bake b] returns a block [b'] which has as predecessor block [b]. Optional parameter [policy] allows to pick the next baker in several ways. This function bundles together [forge_header], [sign_header] and [apply]. These functions should be used instead of bake to craft unusual blocks for testing together with setters for properties of the headers. For examples see seed.ml or double_baking.ml *) val bake : ?baking_mode:baking_mode -> ?payload_round:Round.t option -> ?locked_round:Alpha_context.Round.t option -> ?policy:baker_policy -> ?timestamp:Timestamp.time -> ?operation:Operation.packed -> ?operations:Operation.packed list -> ?liquidity_baking_escape_vote:bool -> t -> t tzresult Lwt.t (** Bakes [n] blocks. *) val bake_n : ?baking_mode:baking_mode -> ?policy:baker_policy -> ?liquidity_baking_escape_vote:bool -> int -> t -> block tzresult Lwt.t (** Version of bake_n that returns a list of all balance updates included in the metadata of baked blocks. **) val bake_n_with_all_balance_updates : ?baking_mode:baking_mode -> ?policy:baker_policy -> ?liquidity_baking_escape_vote:bool -> int -> t -> (block * Alpha_context.Receipt.balance_updates) tzresult Lwt.t (** Version of bake_n that returns a list of all origination results in the metadata of baked blocks. **) val bake_n_with_origination_results : ?baking_mode:baking_mode -> ?policy:baker_policy -> int -> t -> (block * Alpha_context.Kind.origination Apply_results.successful_manager_operation_result list) tzresult Lwt.t * Version of bake_n that returns the liquidity baking escape EMA after [ n ] blocks . * val bake_n_with_liquidity_baking_escape_ema : ?baking_mode:baking_mode -> ?policy:baker_policy -> ?liquidity_baking_escape_vote:bool -> int -> t -> (block * Alpha_context.Liquidity_baking.escape_ema) tzresult Lwt.t val current_cycle : t -> Cycle.t tzresult Lwt.t (** Given a block [b] at level [l] bakes enough blocks to complete a cycle, that is [blocks_per_cycle - (l % blocks_per_cycle)]. *) val bake_until_cycle_end : ?policy:baker_policy -> t -> t tzresult Lwt.t (** Bakes enough blocks to end [n] cycles. *) val bake_until_n_cycle_end : ?policy:baker_policy -> int -> t -> t tzresult Lwt.t (** Bakes enough blocks to reach the cycle. *) val bake_until_cycle : ?policy:baker_policy -> Cycle.t -> t -> t tzresult Lwt.t (** Common util function to create parameters for [initial_context] function *) val prepare_initial_context_params : ?consensus_threshold:int -> ?min_proposal_quorum:int32 -> ?level:int32 -> ?cost_per_byte:Tez.t -> ?liquidity_baking_subsidy:Tez.t -> ?endorsing_reward_per_slot:Tez.t -> ?baking_reward_bonus_per_slot:Tez.t -> ?baking_reward_fixed_portion:Tez.t -> ?origination_size:int -> ?blocks_per_cycle:int32 -> (Account.t * Tez.t) list -> ( Constants.parametric * Block_header.shell_header * Block_hash.t, tztrace ) result Lwt.t
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_012_Psithaca/lib_protocol/test/helpers/block.mli
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Resulting context * The default baking functions below is to use (blocks) [Application] mode. Setting [baking_mode] allows to switch to [Full_construction] mode. * Forges a correct header following the policy. The header can then be modified and applied with [apply]. * Sets uniquely seed_nonce_hash of a header * Sets the baker that will sign the header to an arbitrary pkh * Signs the header with the key of the baker configured in the header. The header can no longer be modified, only applied. * [genesis <opts> accounts] : generates an initial block with the given constants [<opts>] and initializes [accounts] with their associated amounts. * [alpha_context <opts> accounts] : instantiates an alpha_context with the given constants [<opts>] and initializes [accounts] with their associated amounts. * [get_application_vstate pred operations] constructs a protocol validation environment for operations in application mode on top of the given block with the given operations. It's a shortcut for [begin_application] * [get_construction_vstate ?policy ?timestamp ?protocol_data pred] constructs a protocol validation environment for operations in construction mode on top of the given block. The mode is full(baking)/partial(mempool) if [protocol_data] given/absent. It's a shortcut for [begin_construction] * applies a signed header and its operations to a block and obtains a new block * [bake b] returns a block [b'] which has as predecessor block [b]. Optional parameter [policy] allows to pick the next baker in several ways. This function bundles together [forge_header], [sign_header] and [apply]. These functions should be used instead of bake to craft unusual blocks for testing together with setters for properties of the headers. For examples see seed.ml or double_baking.ml * Bakes [n] blocks. * Version of bake_n that returns a list of all balance updates included in the metadata of baked blocks. * * Version of bake_n that returns a list of all origination results in the metadata of baked blocks. * * Given a block [b] at level [l] bakes enough blocks to complete a cycle, that is [blocks_per_cycle - (l % blocks_per_cycle)]. * Bakes enough blocks to end [n] cycles. * Bakes enough blocks to reach the cycle. * Common util function to create parameters for [initial_context] function
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > Copyright ( c ) 2020 Metastate AG < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Protocol open Alpha_context type t = { hash : Block_hash.t; header : Block_header.t; operations : Operation.packed list; } type block = t val rpc_ctxt : t Environment.RPC_context.simple * Policies to select the next baker : - [ By_round r ] selects the baker at round [ r ] - [ By_account pkh ] selects the first slot for baker [ pkh ] - [ Excluding pkhs ] selects the first baker that does n't belong to ] - [By_round r] selects the baker at round [r] - [By_account pkh] selects the first slot for baker [pkh] - [Excluding pkhs] selects the first baker that doesn't belong to [pkhs] *) type baker_policy = | By_round of int | By_account of public_key_hash | Excluding of public_key_hash list type baking_mode = Application | Baking * Returns ( account , round , timestamp ) of the next baker given a policy , defaults to By_round 0 . a policy, defaults to By_round 0. *) val get_next_baker : ?policy:baker_policy -> t -> (public_key_hash * int * Time.Protocol.t) tzresult Lwt.t val get_round : block -> Round.t tzresult module Forge : sig val contents : ?proof_of_work_nonce:Bytes.t -> ?seed_nonce_hash:Nonce_hash.t -> ?liquidity_baking_escape_vote:bool -> payload_hash:Block_payload_hash.t -> payload_round:Round.t -> unit -> Block_header.contents type header val classify_operations : packed_operation list -> packed_operation list list val forge_header : ?locked_round:Alpha_context.Round.t option -> ?payload_round:Round.t option -> ?policy:baker_policy -> ?timestamp:Timestamp.time -> ?operations:Operation.packed list -> ?liquidity_baking_escape_vote:bool -> t -> header tzresult Lwt.t val set_seed_nonce_hash : Nonce_hash.t option -> header -> header val set_baker : public_key_hash -> header -> header val sign_header : header -> Block_header.block_header tzresult Lwt.t end val check_constants_consistency : Constants.parametric -> unit tzresult Lwt.t val genesis : ?commitments:Commitment.t list -> ?consensus_threshold:int -> ?min_proposal_quorum:int32 -> ?bootstrap_contracts:Parameters.bootstrap_contract list -> ?level:int32 -> ?cost_per_byte:Tez.t -> ?liquidity_baking_subsidy:Tez.t -> ?endorsing_reward_per_slot:Tez.t -> ?baking_reward_bonus_per_slot:Tez.t -> ?baking_reward_fixed_portion:Tez.t -> ?origination_size:int -> ?blocks_per_cycle:int32 -> (Account.t * Tez.tez) list -> block tzresult Lwt.t val genesis_with_parameters : Parameters.t -> block tzresult Lwt.t val alpha_context : ?commitments:Commitment.t list -> ?min_proposal_quorum:int32 -> (Account.t * Tez.tez) list -> Alpha_context.t tzresult Lwt.t val get_application_vstate : t -> Protocol.operation list -> validation_state tzresult Lwt.t val get_construction_vstate : ?policy:baker_policy -> ?timestamp:Timestamp.time -> ?protocol_data:block_header_data option -> block -> validation_state tzresult Lwt.t val apply : Block_header.block_header -> ?operations:Operation.packed list -> t -> t tzresult Lwt.t val bake : ?baking_mode:baking_mode -> ?payload_round:Round.t option -> ?locked_round:Alpha_context.Round.t option -> ?policy:baker_policy -> ?timestamp:Timestamp.time -> ?operation:Operation.packed -> ?operations:Operation.packed list -> ?liquidity_baking_escape_vote:bool -> t -> t tzresult Lwt.t val bake_n : ?baking_mode:baking_mode -> ?policy:baker_policy -> ?liquidity_baking_escape_vote:bool -> int -> t -> block tzresult Lwt.t val bake_n_with_all_balance_updates : ?baking_mode:baking_mode -> ?policy:baker_policy -> ?liquidity_baking_escape_vote:bool -> int -> t -> (block * Alpha_context.Receipt.balance_updates) tzresult Lwt.t val bake_n_with_origination_results : ?baking_mode:baking_mode -> ?policy:baker_policy -> int -> t -> (block * Alpha_context.Kind.origination Apply_results.successful_manager_operation_result list) tzresult Lwt.t * Version of bake_n that returns the liquidity baking escape EMA after [ n ] blocks . * val bake_n_with_liquidity_baking_escape_ema : ?baking_mode:baking_mode -> ?policy:baker_policy -> ?liquidity_baking_escape_vote:bool -> int -> t -> (block * Alpha_context.Liquidity_baking.escape_ema) tzresult Lwt.t val current_cycle : t -> Cycle.t tzresult Lwt.t val bake_until_cycle_end : ?policy:baker_policy -> t -> t tzresult Lwt.t val bake_until_n_cycle_end : ?policy:baker_policy -> int -> t -> t tzresult Lwt.t val bake_until_cycle : ?policy:baker_policy -> Cycle.t -> t -> t tzresult Lwt.t val prepare_initial_context_params : ?consensus_threshold:int -> ?min_proposal_quorum:int32 -> ?level:int32 -> ?cost_per_byte:Tez.t -> ?liquidity_baking_subsidy:Tez.t -> ?endorsing_reward_per_slot:Tez.t -> ?baking_reward_bonus_per_slot:Tez.t -> ?baking_reward_fixed_portion:Tez.t -> ?origination_size:int -> ?blocks_per_cycle:int32 -> (Account.t * Tez.t) list -> ( Constants.parametric * Block_header.shell_header * Block_hash.t, tztrace ) result Lwt.t
903f31225e0371737dd17a0786a530bc336593da0f8772edbe3f07ea89fcf89f
airalab/hs-web3
TransactionSpec.hs
{-# LANGUAGE OverloadedStrings #-} module Network.Ethereum.Test.TransactionSpec where import Crypto.Ecdsa.Utils (importKey) import Crypto.Ethereum.Signature (signTransaction) import Data.ByteArray.HexString (HexString) import Network.Ethereum.Api.Types (Call (..)) import Network.Ethereum.Transaction (encodeTransaction) import Test.Hspec spec :: Spec spec = parallel $ describe "Ethereum raw transactions" $ it "can create and sign valid raw transaction" $ do -- using same example as in this blog post: -- /@codetractio/walkthrough-of-an-ethereum-improvement-proposal-eip-6fda3966d171 let testCall = Call Nothing (Just "0x3535353535353535353535353535353535353535") (Just 21000) (Just 20000000000) (Just 1000000000000000000) Nothing (Just 9) key = "4646464646464646464646464646464646464646464646464646464646464646" :: HexString correctSignedTx = "f86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83" signTransaction (encodeTransaction testCall 1) (importKey key) `shouldBe` (correctSignedTx :: HexString)
null
https://raw.githubusercontent.com/airalab/hs-web3/e6719ae384d2371a342f03afa3634921f4a8cd37/packages/ethereum/tests/Network/Ethereum/Test/TransactionSpec.hs
haskell
# LANGUAGE OverloadedStrings # using same example as in this blog post: /@codetractio/walkthrough-of-an-ethereum-improvement-proposal-eip-6fda3966d171
module Network.Ethereum.Test.TransactionSpec where import Crypto.Ecdsa.Utils (importKey) import Crypto.Ethereum.Signature (signTransaction) import Data.ByteArray.HexString (HexString) import Network.Ethereum.Api.Types (Call (..)) import Network.Ethereum.Transaction (encodeTransaction) import Test.Hspec spec :: Spec spec = parallel $ describe "Ethereum raw transactions" $ it "can create and sign valid raw transaction" $ do let testCall = Call Nothing (Just "0x3535353535353535353535353535353535353535") (Just 21000) (Just 20000000000) (Just 1000000000000000000) Nothing (Just 9) key = "4646464646464646464646464646464646464646464646464646464646464646" :: HexString correctSignedTx = "f86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83" signTransaction (encodeTransaction testCall 1) (importKey key) `shouldBe` (correctSignedTx :: HexString)
35c81c86db1266b6e6dfe68e9ee82a3b999753fed8d99a67e35bd2b0f7a1cce5
junjihashimoto/hspec-server
NetworkStatus.hs
module Test.Hspec.Server.NetworkStatus ( NetworkStatus , reachable , host , hostWithPort ) where import System.Exit import Control.Monad.IO.Class import Test.Hspec.Server.Core import Test.Hspec.Server.Util import qualified Data.Set as S type NetworkStatus = S.Set NetworkStatus' data NetworkStatus' = Reachable deriving (Show,Ord,Eq) reachable :: S.Set NetworkStatus' reachable = S.singleton Reachable host :: ServerType dat => String -> ServerExample dat NetworkStatus host hostname = do dat <- getServerData (code,_,_) <- liftIO $ cmd dat "ping" ["-c","1",hostname] [] if code == ExitSuccess then return reachable else return none hostWithPort :: ServerType dat => String -> Int -> ServerExample dat NetworkStatus hostWithPort hostname port = do dat <- getServerData (code,_,_) <- liftIO $ cmd dat "nc" [hostname,show port] [] if code == ExitSuccess then return reachable else return none
null
https://raw.githubusercontent.com/junjihashimoto/hspec-server/473058fa4ca17abbe110d9f273d3c6726d5f1365/Test/Hspec/Server/NetworkStatus.hs
haskell
module Test.Hspec.Server.NetworkStatus ( NetworkStatus , reachable , host , hostWithPort ) where import System.Exit import Control.Monad.IO.Class import Test.Hspec.Server.Core import Test.Hspec.Server.Util import qualified Data.Set as S type NetworkStatus = S.Set NetworkStatus' data NetworkStatus' = Reachable deriving (Show,Ord,Eq) reachable :: S.Set NetworkStatus' reachable = S.singleton Reachable host :: ServerType dat => String -> ServerExample dat NetworkStatus host hostname = do dat <- getServerData (code,_,_) <- liftIO $ cmd dat "ping" ["-c","1",hostname] [] if code == ExitSuccess then return reachable else return none hostWithPort :: ServerType dat => String -> Int -> ServerExample dat NetworkStatus hostWithPort hostname port = do dat <- getServerData (code,_,_) <- liftIO $ cmd dat "nc" [hostname,show port] [] if code == ExitSuccess then return reachable else return none
6429d77b85c2182354a0bc2666faa8f6d44c8ffe6f498b25e4ba05e4adea8164
gas2serra/mcclim-desktop
clim-debugger.lisp
(in-package :desktop-user) (register-application "clim-debugger" 'standard-mcclim-debugger-application :pretty-name "Clim Debugger" :icon nil :menu-p nil :requires-args-p t :home-page "" :git-repo "" :system-name "clim-debugger")
null
https://raw.githubusercontent.com/gas2serra/mcclim-desktop/f85d19c57d76322ae3c05f98ae43bfc8c0d0a554/dot-mcclim-desktop/apps/clim-debugger.lisp
lisp
(in-package :desktop-user) (register-application "clim-debugger" 'standard-mcclim-debugger-application :pretty-name "Clim Debugger" :icon nil :menu-p nil :requires-args-p t :home-page "" :git-repo "" :system-name "clim-debugger")
d5ce72a304f3a15d8ceb76f2c0f171876c5d57e78eeda51bd812d01917228ef2
brownplt/LambdaS5
ljs_eval.ml
open Prelude module S = Ljs_syntax open Format open Ljs open Ljs_values open Ljs_delta open Ljs_pretty open Ljs_pretty_value open Unix open SpiderMonkey open Exprjs_to_ljs open Js_to_exprjs open Str type answer = Answer of S.exp list * value * env list * store let bool b = match b with | true -> True | false -> False let unbool b = match b with | True -> true | False -> false | _ -> failwith ("tried to unbool a non-bool" ^ (pretty_value b)) let interp_error pos message = raise (PrimErr ([], String ("[interp] (" ^ Pos.string_of_pos pos ^ ") " ^ message))) let rec get_prop p store obj field = match obj with | Null -> None | ObjLoc loc -> begin match get_obj store loc with | { proto = pvalue; }, props -> try Some (IdMap.find field props) with Not_found -> get_prop p store pvalue field end | _ -> failwith (interp_error p "get_prop on a non-object. The expression was (get-prop " ^ pretty_value obj ^ " " ^ field ^ ")") let get_obj_attr attrs attr = match attrs, attr with | { proto=proto }, S.Proto -> proto | { extensible=extensible} , S.Extensible -> bool extensible | { code=Some code}, S.Code -> code | { code=None}, S.Code -> Null | { primval=Some primval}, S.Primval -> primval | { primval=None}, S.Primval -> failwith "[interp] Got Primval attr of None" | { klass=klass }, S.Klass -> String klass let rec get_attr store attr obj field = match obj, field with | ObjLoc loc, String s -> let (attrs, props) = get_obj store loc in if (not (IdMap.mem s props)) then undef else begin match (IdMap.find s props), attr with | Data (_, _, config), S.Config | Accessor (_, _, config), S.Config -> bool config | Data (_, enum, _), S.Enum | Accessor (_, enum, _), S.Enum -> bool enum | Data ({ writable = b; }, _, _), S.Writable -> bool b | Data ({ value = v; }, _, _), S.Value -> v | Accessor ({ getter = gv; }, _, _), S.Getter -> gv | Accessor ({ setter = sv; }, _, _), S.Setter -> sv | _ -> interp_error Pos.dummy "bad access of attribute" end | _ -> failwith ("[interp] get-attr didn't get an object and a string.") The goal here is to maintain a few invariants ( implied by 8.12.9 and 8.10.5 ) , while keeping things simple from a semantic standpoint . The errors from 8.12.9 and 8.10.5 can be defined in the environment and enforced that way . The invariants here make it more obvious that the semantics ca n't go wrong . In particular , a property 1 . Has to be either an accessor or a data property , and ; 2 . Ca n't change attributes when Config is false , except for a. Value , which checks , which can change true->false The goal here is to maintain a few invariants (implied by 8.12.9 and 8.10.5), while keeping things simple from a semantic standpoint. The errors from 8.12.9 and 8.10.5 can be defined in the environment and enforced that way. The invariants here make it more obvious that the semantics can't go wrong. In particular, a property 1. Has to be either an accessor or a data property, and; 2. Can't change attributes when Config is false, except for a. Value, which checks Writable b. Writable, which can change true->false *) let rec set_attr (store : store) attr obj field newval = match obj, field with | ObjLoc loc, String f_str -> begin match get_obj store loc with | ({ extensible = ext; } as attrsv, props) -> if not (IdMap.mem f_str props) then if ext then let newprop = match attr with | S.Getter -> Accessor ({ getter = newval; setter = Undefined; }, false, false) | S.Setter -> Accessor ({ getter = Undefined; setter = newval; }, false, false) | S.Value -> Data ({ value = newval; writable = false; }, false, false) | S.Writable -> Data ({ value = Undefined; writable = unbool newval }, false, false) | S.Enum -> Data ({ value = Undefined; writable = false }, unbool newval, true) | S.Config -> Data ({ value = Undefined; writable = false }, true, unbool newval) in let store = set_obj store loc (attrsv, IdMap.add f_str newprop props) in true, store else failwith "[interp] Extending inextensible object ." else 8.12.9 : " If a field is absent , then its value is considered to be false " -- we ensure that fields are present and ( and false , if they would have been absent ) . to be false" -- we ensure that fields are present and (and false, if they would have been absent). *) let newprop = match (IdMap.find f_str props), attr, newval with (* S.Writable true -> false when configurable is false *) | Data ({ writable = true } as d, enum, config), S.Writable, new_w -> Data ({ d with writable = unbool new_w }, enum, config) | Data (d, enum, true), S.Writable, new_w -> Data ({ d with writable = unbool new_w }, enum, true) (* Updating values only checks writable *) | Data ({ writable = true } as d, enum, config), S.Value, v -> Data ({ d with value = v }, enum, config) (* If we had a data property, update it to an accessor *) | Data (d, enum, true), S.Setter, setterv -> Accessor ({ getter = Undefined; setter = setterv }, enum, true) | Data (d, enum, true), S.Getter, getterv -> Accessor ({ getter = getterv; setter = Undefined }, enum, true) (* Accessors can update their getter and setter properties *) | Accessor (a, enum, true), S.Getter, getterv -> Accessor ({ a with getter = getterv }, enum, true) | Accessor (a, enum, true), S.Setter, setterv -> Accessor ({ a with setter = setterv }, enum, true) (* An accessor can be changed into a data property *) | Accessor (a, enum, true), S.Value, v -> Data ({ value = v; writable = false; }, enum, true) | Accessor (a, enum, true), S.Writable, w -> Data ({ value = Undefined; writable = unbool w; }, enum, true) (* enumerable and configurable need configurable=true *) | Data (d, _, true), S.Enum, new_enum -> Data (d, unbool new_enum, true) | Data (d, enum, true), S.Config, new_config -> Data (d, enum, unbool new_config) | Data (d, enum, false), S.Config, False -> Data (d, enum, false) | Accessor (a, enum, true), S.Config, new_config -> Accessor (a, enum, unbool new_config) | Accessor (a, enum, true), S.Enum, new_enum -> Accessor (a, unbool new_enum, true) | Accessor (a, enum, false), S.Config, False -> Accessor (a, enum, false) | _ -> raise (PrimErr ([], String ("[interp] bad property set " ^ (pretty_value obj) ^ " " ^ f_str ^ " " ^ (S.string_of_attr attr) ^ " " ^ (pretty_value newval)))) in begin let store = set_obj store loc (attrsv, IdMap.add f_str newprop props) in true, store end end | _ -> let msg = (sprintf "[interp] set-attr got: %s[%s] not object and string" (pretty_value obj) (pretty_value field)) in raise (PrimErr ([], String msg)) let rec eval desugar exp env (store : store) : (value * store) = let eval exp env store = begin try eval desugar exp env store with | Break (exprs, l, v, s) -> raise (Break (exp::exprs, l, v, s)) | Throw (exprs, v, s) -> raise (Throw (exp::exprs, v, s)) | PrimErr (exprs, v) -> raise (PrimErr (exp::exprs, v)) | Snapshot (exps, v, envs, s) -> raise (Snapshot (exp :: exps, v, env :: envs, s)) | Sys.Break -> raise (PrimErr ([exp], String "s5_eval stopped by user interrupt")) | Stack_overflow -> raise (PrimErr ([exp], String "s5_eval overflowed the Ocaml stack")) end in let rec apply p store func args = match func with | Closure (env, xs, body) -> let alloc_arg argval argname (store, env) = let (new_loc, store) = add_var store argval in let env' = IdMap.add argname new_loc env in (store, env') in if (List.length args) != (List.length xs) then arity_mismatch_err p xs args else let (store, env) = (List.fold_right2 alloc_arg args xs (store, env)) in eval body env store | ObjLoc loc -> begin match get_obj store loc with | ({ code = Some f }, _) -> apply p store f args | _ -> failwith "Applied an object without a code attribute" end | _ -> failwith (interp_error p ("Applied non-function, was actually " ^ pretty_value func)) in match exp with | S.Hint (_, "___takeS5Snapshot", e) -> let (v, store) = eval e env store in raise (Snapshot ([], v, [], store)) | S.Hint (_, _, e) -> eval e env store | S.Undefined _ -> Undefined, store | S.Null _ -> Null, store | S.String (_, s) -> String s, store | S.Num (_, n) -> Num n, store | S.True _ -> True, store | S.False _ -> False, store | S.Id (p, x) -> begin try (get_var store (IdMap.find x env), store) with Not_found -> failwith ("[interp] Unbound identifier: " ^ x ^ " in identifier lookup at " ^ (Pos.string_of_pos p)) end | S.SetBang (p, x, e) -> begin try let loc = IdMap.find x env in let (new_val, store) = eval e env store in let store = set_var store loc new_val in new_val, store with Not_found -> failwith ("[interp] Unbound identifier: " ^ x ^ " in set! at " ^ (Pos.string_of_pos p)) end | S.Object (p, attrs, props) -> let { S.primval = vexp; S.proto = protoexp; S.code = codexp; S.extensible = ext; S.klass = kls; } = attrs in let opt_lift (value, store) = (Some value, store) in let primval, store = match vexp with | Some vexp -> opt_lift (eval vexp env store) | None -> None, store in let proto, store = match protoexp with | Some pexp -> eval pexp env store | None -> Undefined, store in let code, store = match codexp with | Some cexp -> opt_lift (eval cexp env store) | None -> None, store in let attrsv = { code=code; proto=proto; primval=primval; klass=kls; extensible=ext; } in let eval_prop prop store = match prop with | S.Data ({ S.value = vexp; S.writable = w; }, enum, config) -> let vexp, store = eval vexp env store in Data ({ value = vexp; writable = w; }, enum, config), store | S.Accessor ({ S.getter = ge; S.setter = se; }, enum, config) -> let gv, store = eval ge env store in let sv, store = eval se env store in Accessor ({ getter = gv; setter = sv}, enum, config), store in let eval_prop (m, store) (name, prop) = let propv, store = eval_prop prop store in IdMap.add name propv m, store in let propsv, store = fold_left eval_prop (IdMap.empty, store) props in let obj_loc, store = add_obj store (attrsv, propsv) in ObjLoc obj_loc, store 8.12.4 , 8.12.5 | S.SetField (p, obj, f, v, args) -> let (obj_value, store) = eval obj env store in let (f_value, store) = eval f env store in let (v_value, store) = eval v env store in let (args_value, store) = eval args env store in begin match (obj_value, f_value) with | (ObjLoc loc, String s) -> let ({extensible=extensible;} as attrs, props) = get_obj store loc in let prop = get_prop p store obj_value s in let unwritable = (Throw ([], String "unwritable-field", store )) in begin match prop with | Some (Data ({ writable = true; }, enum, config)) -> let (enum, config) = if (IdMap.mem s props) 8.12.5 , step 3 , changing the value of a field else (true, true) in (* 8.12.4, last step where inherited.[[writable]] is true *) let store = set_obj store loc (attrs, IdMap.add s (Data ({ value = v_value; writable = true }, enum, config)) props) in v_value, store | Some (Data _) -> raise unwritable | Some (Accessor ({ setter = Undefined; }, _, _)) -> raise unwritable | Some (Accessor ({ setter = setterv; }, _, _)) -> 8.12.5 , step 5 apply p store setterv [obj_value; args_value] | None -> 8.12.5 , step 6 if extensible then let store = set_obj store loc (attrs, IdMap.add s (Data ({ value = v_value; writable = true; }, true, true)) props) in v_value, store else Undefined, store (* TODO: Check error in case of non-extensible *) end | _ -> failwith ("[interp] Update field didn't get an object and a string" ^ Pos.string_of_pos p ^ " : " ^ (pretty_value obj_value) ^ ", " ^ (pretty_value f_value)) end | S.GetField (p, obj, f, args) -> let (obj_value, store) = eval obj env store in let (f_value, store) = eval f env store in let (args_value, store) = eval args env store in begin match (obj_value, f_value) with | (ObjLoc _, String s) -> let prop = get_prop p store obj_value s in begin match prop with | Some (Data ({value=v;}, _, _)) -> v, store | Some (Accessor ({getter=g;},_,_)) -> if g = Undefined then Undefined, store else apply p store g [obj_value; args_value] | None -> Undefined, store end | _ -> failwith ("[interp] Get field didn't get an object and a string at " ^ Pos.string_of_pos p ^ ". Instead, it got " ^ pretty_value obj_value ^ " and " ^ pretty_value f_value) end | S.DeleteField (p, obj, f) -> let (obj_val, store) = eval obj env store in let (f_val, store) = eval f env store in begin match (obj_val, f_val) with | (ObjLoc loc, String s) -> begin match get_obj store loc with | (attrs, props) -> begin try match IdMap.find s props with | Data (_, _, true) | Accessor (_, _, true) -> let store = set_obj store loc (attrs, IdMap.remove s props) in True, store | _ -> raise (Throw ([], String "unconfigurable-delete", store)) with Not_found -> False, store end end | _ -> failwith ("[interp] Delete field didn't get an object and a string at " ^ Pos.string_of_pos p ^ ". Instead, it got " ^ pretty_value obj_val ^ " and " ^ pretty_value f_val) end | S.GetAttr (p, attr, obj, field) -> let (obj_val, store) = eval obj env store in let (f_val, store) = eval field env store in get_attr store attr obj_val f_val, store | S.SetAttr (p, attr, obj, field, newval) -> let (obj_val, store) = eval obj env store in let (f_val, store) = eval field env store in let (v_val, store) = eval newval env store in let b, store = set_attr store attr obj_val f_val v_val in bool b, store | S.GetObjAttr (p, oattr, obj) -> let (obj_val, store) = eval obj env store in begin match obj_val with | ObjLoc loc -> let (attrs, _) = get_obj store loc in get_obj_attr attrs oattr, store | _ -> failwith ("[interp] GetObjAttr got a non-object: " ^ (pretty_value obj_val)) end | S.SetObjAttr (p, oattr, obj, attre) -> let (obj_val, store) = eval obj env store in let (attrv, store) = eval attre env store in begin match obj_val with | ObjLoc loc -> let (attrs, props) = get_obj store loc in let attrs' = match oattr, attrv with | S.Proto, ObjLoc _ | S.Proto, Null -> { attrs with proto=attrv } | S.Proto, _ -> failwith ("[interp] Update proto failed: " ^ (pretty_value attrv)) | S.Extensible, True -> { attrs with extensible=true } | S.Extensible, False -> { attrs with extensible=false } | S.Extensible, _ -> failwith ("[interp] Update extensible failed: " ^ (pretty_value attrv)) | S.Code, _ -> failwith "[interp] Can't update Code" | S.Primval, v -> { attrs with primval=Some v } | S.Klass, _ -> failwith "[interp] Can't update Klass" in attrv, set_obj store loc (attrs', props) | _ -> failwith ("[interp] SetObjAttr got a non-object: " ^ (pretty_value obj_val)) end | S.OwnFieldNames (p, obj) -> let (obj_val, store) = eval obj env store in begin match obj_val with | ObjLoc loc -> let _, props = get_obj store loc in let add_name n x m = IdMap.add (string_of_int x) (Data ({ value = String n; writable = false; }, false, false)) m in let namelist = IdMap.fold (fun k v l -> (k :: l)) props [] in let props = List.fold_right2 add_name namelist (iota (List.length namelist)) IdMap.empty in let d = (float_of_int (List.length namelist)) in let final_props = IdMap.add "length" (Data ({ value = Num d; writable = false; }, false, false)) props in let (new_obj, store) = add_obj store (d_attrsv, final_props) in ObjLoc new_obj, store | _ -> failwith ("[interp] OwnFieldNames didn't get an object," ^ " got " ^ (pretty_value obj_val) ^ " instead.") end | S.Op1 (p, op, e) -> let (e_val, store) = eval e env store in op1 store op e_val, store | S.Op2 (p, op, e1, e2) -> let (e1_val, store) = eval e1 env store in let (e2_val, store) = eval e2 env store in op2 store op e1_val e2_val, store | S.If (p, c, t, e) -> let (c_val, store) = eval c env store in if (c_val = True) then eval t env store else eval e env store | S.App (p, func, args) -> let (func_value, store) = eval func env store in let (args_values, store) = fold_left (fun (vals, store) e -> let (newval, store) = eval e env store in (newval::vals, store)) ([], store) args in apply p store func_value (List.rev args_values) | S.Seq (p, e1, e2) -> let (_, store) = eval e1 env store in eval e2 env store | S.Let (p, x, e, body) -> let (e_val, store) = eval e env store in let (new_loc, store) = add_var store e_val in eval body (IdMap.add x new_loc env) store | S.Rec (p, x, e, body) -> let (new_loc, store) = add_var store Undefined in let env' = (IdMap.add x new_loc env) in let (ev_val, store) = eval e env' store in eval body env' (set_var store new_loc ev_val) | S.Label (p, l, e) -> begin try eval e env store with Break (t, l', v, store) -> if l = l' then (v, store) else raise (Break (t, l', v, store)) end | S.Break (p, l, e) -> let v, store = eval e env store in raise (Break ([], l, v, store)) | S.TryCatch (p, body, catch) -> begin try eval body env store with Throw (_, v, store) -> let catchv, store = eval catch env store in apply p store catchv [v] end | S.TryFinally (p, body, fin) -> begin try let (v, store) = eval body env store in let (_, store') = eval fin env store in (v, store') with | Throw (t, v, store) -> let (_, store) = eval fin env store in raise (Throw (t, v, store)) | Break (t, l, v, store) -> let (_, store) = eval fin env store in raise (Break (t, l, v, store)) end | S.Throw (p, e) -> let (v, s) = eval e env store in raise (Throw ([], v, s)) | S.Lambda (p, xs, e) -> (* Only close over the variables that the function body might reference. *) let free_vars = S.free_vars e in let filtered_env = IdMap.filter (fun var _ -> IdSet.mem var free_vars) env in Closure (filtered_env, xs, e), store | S.Eval (p, e, bindings) -> let evalstr, store = eval e env store in let bindobj, store = eval bindings env store in begin match evalstr, bindobj with | String s, ObjLoc o -> let expr = desugar s in let env, store = envstore_of_obj p (get_obj store o) store in eval expr env store | String s, _ -> interp_error p "Non-object given to eval() for env" | v, _ -> v, store end and envstore_of_obj p (_, props) store = IdMap.fold (fun id prop (env, store) -> match prop with | Data ({value=v}, _, _) -> let new_loc, store = add_var store v in let env = IdMap.add id new_loc env in env, store | _ -> interp_error p "Non-data value in env_of_obj") props (IdMap.empty, store) and arity_mismatch_err p xs args = interp_error p ("Arity mismatch, supplied " ^ string_of_int (List.length args) ^ " arguments and expected " ^ string_of_int (List.length xs) ^ ". Arg names were: " ^ (List.fold_right (^) (map (fun s -> " " ^ s ^ " ") xs) "") ^ ". Values were: " ^ (List.fold_right (^) (map (fun v -> " " ^ pretty_value v ^ " ") args) "")) let err show_stack trace message = if show_stack then begin eprintf "%s\n" (string_stack_trace trace); eprintf "%s\n" message; failwith "Runtime error" end else eprintf "%s\n" message; failwith "Runtime error" let continue_eval expr desugar print_trace env store = try Sys.catch_break true; let (v, store) = eval desugar expr env store in Answer ([], v, [], store) with | Snapshot (exprs, v, envs, store) -> Answer (exprs, v, envs, store) | Throw (t, v, store) -> let err_msg = match v with | ObjLoc loc -> begin match get_obj store loc with | _, props -> try match IdMap.find "%js-exn" props with | Data ({value=jserr}, _, _) -> string_of_value jserr store | _ -> string_of_value v store with Not_found -> string_of_value v store end | v -> string_of_value v store in err print_trace t (sprintf "Uncaught exception: %s\n" err_msg) | Break (p, l, v, _) -> failwith ("Broke to top of execution, missed label: " ^ l) | PrimErr (t, v) -> err print_trace t (sprintf "Uncaught error: %s\n" (pretty_value v)) let eval_expr expr desugar print_trace = continue_eval expr desugar print_trace IdMap.empty (Store.empty, Store.empty)
null
https://raw.githubusercontent.com/brownplt/LambdaS5/f0bf5c7baf1daa4ead4e398ba7d430bedb7de9cf/src/ljs/ljs_eval.ml
ocaml
S.Writable true -> false when configurable is false Updating values only checks writable If we had a data property, update it to an accessor Accessors can update their getter and setter properties An accessor can be changed into a data property enumerable and configurable need configurable=true 8.12.4, last step where inherited.[[writable]] is true TODO: Check error in case of non-extensible Only close over the variables that the function body might reference.
open Prelude module S = Ljs_syntax open Format open Ljs open Ljs_values open Ljs_delta open Ljs_pretty open Ljs_pretty_value open Unix open SpiderMonkey open Exprjs_to_ljs open Js_to_exprjs open Str type answer = Answer of S.exp list * value * env list * store let bool b = match b with | true -> True | false -> False let unbool b = match b with | True -> true | False -> false | _ -> failwith ("tried to unbool a non-bool" ^ (pretty_value b)) let interp_error pos message = raise (PrimErr ([], String ("[interp] (" ^ Pos.string_of_pos pos ^ ") " ^ message))) let rec get_prop p store obj field = match obj with | Null -> None | ObjLoc loc -> begin match get_obj store loc with | { proto = pvalue; }, props -> try Some (IdMap.find field props) with Not_found -> get_prop p store pvalue field end | _ -> failwith (interp_error p "get_prop on a non-object. The expression was (get-prop " ^ pretty_value obj ^ " " ^ field ^ ")") let get_obj_attr attrs attr = match attrs, attr with | { proto=proto }, S.Proto -> proto | { extensible=extensible} , S.Extensible -> bool extensible | { code=Some code}, S.Code -> code | { code=None}, S.Code -> Null | { primval=Some primval}, S.Primval -> primval | { primval=None}, S.Primval -> failwith "[interp] Got Primval attr of None" | { klass=klass }, S.Klass -> String klass let rec get_attr store attr obj field = match obj, field with | ObjLoc loc, String s -> let (attrs, props) = get_obj store loc in if (not (IdMap.mem s props)) then undef else begin match (IdMap.find s props), attr with | Data (_, _, config), S.Config | Accessor (_, _, config), S.Config -> bool config | Data (_, enum, _), S.Enum | Accessor (_, enum, _), S.Enum -> bool enum | Data ({ writable = b; }, _, _), S.Writable -> bool b | Data ({ value = v; }, _, _), S.Value -> v | Accessor ({ getter = gv; }, _, _), S.Getter -> gv | Accessor ({ setter = sv; }, _, _), S.Setter -> sv | _ -> interp_error Pos.dummy "bad access of attribute" end | _ -> failwith ("[interp] get-attr didn't get an object and a string.") The goal here is to maintain a few invariants ( implied by 8.12.9 and 8.10.5 ) , while keeping things simple from a semantic standpoint . The errors from 8.12.9 and 8.10.5 can be defined in the environment and enforced that way . The invariants here make it more obvious that the semantics ca n't go wrong . In particular , a property 1 . Has to be either an accessor or a data property , and ; 2 . Ca n't change attributes when Config is false , except for a. Value , which checks , which can change true->false The goal here is to maintain a few invariants (implied by 8.12.9 and 8.10.5), while keeping things simple from a semantic standpoint. The errors from 8.12.9 and 8.10.5 can be defined in the environment and enforced that way. The invariants here make it more obvious that the semantics can't go wrong. In particular, a property 1. Has to be either an accessor or a data property, and; 2. Can't change attributes when Config is false, except for a. Value, which checks Writable b. Writable, which can change true->false *) let rec set_attr (store : store) attr obj field newval = match obj, field with | ObjLoc loc, String f_str -> begin match get_obj store loc with | ({ extensible = ext; } as attrsv, props) -> if not (IdMap.mem f_str props) then if ext then let newprop = match attr with | S.Getter -> Accessor ({ getter = newval; setter = Undefined; }, false, false) | S.Setter -> Accessor ({ getter = Undefined; setter = newval; }, false, false) | S.Value -> Data ({ value = newval; writable = false; }, false, false) | S.Writable -> Data ({ value = Undefined; writable = unbool newval }, false, false) | S.Enum -> Data ({ value = Undefined; writable = false }, unbool newval, true) | S.Config -> Data ({ value = Undefined; writable = false }, true, unbool newval) in let store = set_obj store loc (attrsv, IdMap.add f_str newprop props) in true, store else failwith "[interp] Extending inextensible object ." else 8.12.9 : " If a field is absent , then its value is considered to be false " -- we ensure that fields are present and ( and false , if they would have been absent ) . to be false" -- we ensure that fields are present and (and false, if they would have been absent). *) let newprop = match (IdMap.find f_str props), attr, newval with | Data ({ writable = true } as d, enum, config), S.Writable, new_w -> Data ({ d with writable = unbool new_w }, enum, config) | Data (d, enum, true), S.Writable, new_w -> Data ({ d with writable = unbool new_w }, enum, true) | Data ({ writable = true } as d, enum, config), S.Value, v -> Data ({ d with value = v }, enum, config) | Data (d, enum, true), S.Setter, setterv -> Accessor ({ getter = Undefined; setter = setterv }, enum, true) | Data (d, enum, true), S.Getter, getterv -> Accessor ({ getter = getterv; setter = Undefined }, enum, true) | Accessor (a, enum, true), S.Getter, getterv -> Accessor ({ a with getter = getterv }, enum, true) | Accessor (a, enum, true), S.Setter, setterv -> Accessor ({ a with setter = setterv }, enum, true) | Accessor (a, enum, true), S.Value, v -> Data ({ value = v; writable = false; }, enum, true) | Accessor (a, enum, true), S.Writable, w -> Data ({ value = Undefined; writable = unbool w; }, enum, true) | Data (d, _, true), S.Enum, new_enum -> Data (d, unbool new_enum, true) | Data (d, enum, true), S.Config, new_config -> Data (d, enum, unbool new_config) | Data (d, enum, false), S.Config, False -> Data (d, enum, false) | Accessor (a, enum, true), S.Config, new_config -> Accessor (a, enum, unbool new_config) | Accessor (a, enum, true), S.Enum, new_enum -> Accessor (a, unbool new_enum, true) | Accessor (a, enum, false), S.Config, False -> Accessor (a, enum, false) | _ -> raise (PrimErr ([], String ("[interp] bad property set " ^ (pretty_value obj) ^ " " ^ f_str ^ " " ^ (S.string_of_attr attr) ^ " " ^ (pretty_value newval)))) in begin let store = set_obj store loc (attrsv, IdMap.add f_str newprop props) in true, store end end | _ -> let msg = (sprintf "[interp] set-attr got: %s[%s] not object and string" (pretty_value obj) (pretty_value field)) in raise (PrimErr ([], String msg)) let rec eval desugar exp env (store : store) : (value * store) = let eval exp env store = begin try eval desugar exp env store with | Break (exprs, l, v, s) -> raise (Break (exp::exprs, l, v, s)) | Throw (exprs, v, s) -> raise (Throw (exp::exprs, v, s)) | PrimErr (exprs, v) -> raise (PrimErr (exp::exprs, v)) | Snapshot (exps, v, envs, s) -> raise (Snapshot (exp :: exps, v, env :: envs, s)) | Sys.Break -> raise (PrimErr ([exp], String "s5_eval stopped by user interrupt")) | Stack_overflow -> raise (PrimErr ([exp], String "s5_eval overflowed the Ocaml stack")) end in let rec apply p store func args = match func with | Closure (env, xs, body) -> let alloc_arg argval argname (store, env) = let (new_loc, store) = add_var store argval in let env' = IdMap.add argname new_loc env in (store, env') in if (List.length args) != (List.length xs) then arity_mismatch_err p xs args else let (store, env) = (List.fold_right2 alloc_arg args xs (store, env)) in eval body env store | ObjLoc loc -> begin match get_obj store loc with | ({ code = Some f }, _) -> apply p store f args | _ -> failwith "Applied an object without a code attribute" end | _ -> failwith (interp_error p ("Applied non-function, was actually " ^ pretty_value func)) in match exp with | S.Hint (_, "___takeS5Snapshot", e) -> let (v, store) = eval e env store in raise (Snapshot ([], v, [], store)) | S.Hint (_, _, e) -> eval e env store | S.Undefined _ -> Undefined, store | S.Null _ -> Null, store | S.String (_, s) -> String s, store | S.Num (_, n) -> Num n, store | S.True _ -> True, store | S.False _ -> False, store | S.Id (p, x) -> begin try (get_var store (IdMap.find x env), store) with Not_found -> failwith ("[interp] Unbound identifier: " ^ x ^ " in identifier lookup at " ^ (Pos.string_of_pos p)) end | S.SetBang (p, x, e) -> begin try let loc = IdMap.find x env in let (new_val, store) = eval e env store in let store = set_var store loc new_val in new_val, store with Not_found -> failwith ("[interp] Unbound identifier: " ^ x ^ " in set! at " ^ (Pos.string_of_pos p)) end | S.Object (p, attrs, props) -> let { S.primval = vexp; S.proto = protoexp; S.code = codexp; S.extensible = ext; S.klass = kls; } = attrs in let opt_lift (value, store) = (Some value, store) in let primval, store = match vexp with | Some vexp -> opt_lift (eval vexp env store) | None -> None, store in let proto, store = match protoexp with | Some pexp -> eval pexp env store | None -> Undefined, store in let code, store = match codexp with | Some cexp -> opt_lift (eval cexp env store) | None -> None, store in let attrsv = { code=code; proto=proto; primval=primval; klass=kls; extensible=ext; } in let eval_prop prop store = match prop with | S.Data ({ S.value = vexp; S.writable = w; }, enum, config) -> let vexp, store = eval vexp env store in Data ({ value = vexp; writable = w; }, enum, config), store | S.Accessor ({ S.getter = ge; S.setter = se; }, enum, config) -> let gv, store = eval ge env store in let sv, store = eval se env store in Accessor ({ getter = gv; setter = sv}, enum, config), store in let eval_prop (m, store) (name, prop) = let propv, store = eval_prop prop store in IdMap.add name propv m, store in let propsv, store = fold_left eval_prop (IdMap.empty, store) props in let obj_loc, store = add_obj store (attrsv, propsv) in ObjLoc obj_loc, store 8.12.4 , 8.12.5 | S.SetField (p, obj, f, v, args) -> let (obj_value, store) = eval obj env store in let (f_value, store) = eval f env store in let (v_value, store) = eval v env store in let (args_value, store) = eval args env store in begin match (obj_value, f_value) with | (ObjLoc loc, String s) -> let ({extensible=extensible;} as attrs, props) = get_obj store loc in let prop = get_prop p store obj_value s in let unwritable = (Throw ([], String "unwritable-field", store )) in begin match prop with | Some (Data ({ writable = true; }, enum, config)) -> let (enum, config) = if (IdMap.mem s props) 8.12.5 , step 3 , changing the value of a field let store = set_obj store loc (attrs, IdMap.add s (Data ({ value = v_value; writable = true }, enum, config)) props) in v_value, store | Some (Data _) -> raise unwritable | Some (Accessor ({ setter = Undefined; }, _, _)) -> raise unwritable | Some (Accessor ({ setter = setterv; }, _, _)) -> 8.12.5 , step 5 apply p store setterv [obj_value; args_value] | None -> 8.12.5 , step 6 if extensible then let store = set_obj store loc (attrs, IdMap.add s (Data ({ value = v_value; writable = true; }, true, true)) props) in v_value, store else end | _ -> failwith ("[interp] Update field didn't get an object and a string" ^ Pos.string_of_pos p ^ " : " ^ (pretty_value obj_value) ^ ", " ^ (pretty_value f_value)) end | S.GetField (p, obj, f, args) -> let (obj_value, store) = eval obj env store in let (f_value, store) = eval f env store in let (args_value, store) = eval args env store in begin match (obj_value, f_value) with | (ObjLoc _, String s) -> let prop = get_prop p store obj_value s in begin match prop with | Some (Data ({value=v;}, _, _)) -> v, store | Some (Accessor ({getter=g;},_,_)) -> if g = Undefined then Undefined, store else apply p store g [obj_value; args_value] | None -> Undefined, store end | _ -> failwith ("[interp] Get field didn't get an object and a string at " ^ Pos.string_of_pos p ^ ". Instead, it got " ^ pretty_value obj_value ^ " and " ^ pretty_value f_value) end | S.DeleteField (p, obj, f) -> let (obj_val, store) = eval obj env store in let (f_val, store) = eval f env store in begin match (obj_val, f_val) with | (ObjLoc loc, String s) -> begin match get_obj store loc with | (attrs, props) -> begin try match IdMap.find s props with | Data (_, _, true) | Accessor (_, _, true) -> let store = set_obj store loc (attrs, IdMap.remove s props) in True, store | _ -> raise (Throw ([], String "unconfigurable-delete", store)) with Not_found -> False, store end end | _ -> failwith ("[interp] Delete field didn't get an object and a string at " ^ Pos.string_of_pos p ^ ". Instead, it got " ^ pretty_value obj_val ^ " and " ^ pretty_value f_val) end | S.GetAttr (p, attr, obj, field) -> let (obj_val, store) = eval obj env store in let (f_val, store) = eval field env store in get_attr store attr obj_val f_val, store | S.SetAttr (p, attr, obj, field, newval) -> let (obj_val, store) = eval obj env store in let (f_val, store) = eval field env store in let (v_val, store) = eval newval env store in let b, store = set_attr store attr obj_val f_val v_val in bool b, store | S.GetObjAttr (p, oattr, obj) -> let (obj_val, store) = eval obj env store in begin match obj_val with | ObjLoc loc -> let (attrs, _) = get_obj store loc in get_obj_attr attrs oattr, store | _ -> failwith ("[interp] GetObjAttr got a non-object: " ^ (pretty_value obj_val)) end | S.SetObjAttr (p, oattr, obj, attre) -> let (obj_val, store) = eval obj env store in let (attrv, store) = eval attre env store in begin match obj_val with | ObjLoc loc -> let (attrs, props) = get_obj store loc in let attrs' = match oattr, attrv with | S.Proto, ObjLoc _ | S.Proto, Null -> { attrs with proto=attrv } | S.Proto, _ -> failwith ("[interp] Update proto failed: " ^ (pretty_value attrv)) | S.Extensible, True -> { attrs with extensible=true } | S.Extensible, False -> { attrs with extensible=false } | S.Extensible, _ -> failwith ("[interp] Update extensible failed: " ^ (pretty_value attrv)) | S.Code, _ -> failwith "[interp] Can't update Code" | S.Primval, v -> { attrs with primval=Some v } | S.Klass, _ -> failwith "[interp] Can't update Klass" in attrv, set_obj store loc (attrs', props) | _ -> failwith ("[interp] SetObjAttr got a non-object: " ^ (pretty_value obj_val)) end | S.OwnFieldNames (p, obj) -> let (obj_val, store) = eval obj env store in begin match obj_val with | ObjLoc loc -> let _, props = get_obj store loc in let add_name n x m = IdMap.add (string_of_int x) (Data ({ value = String n; writable = false; }, false, false)) m in let namelist = IdMap.fold (fun k v l -> (k :: l)) props [] in let props = List.fold_right2 add_name namelist (iota (List.length namelist)) IdMap.empty in let d = (float_of_int (List.length namelist)) in let final_props = IdMap.add "length" (Data ({ value = Num d; writable = false; }, false, false)) props in let (new_obj, store) = add_obj store (d_attrsv, final_props) in ObjLoc new_obj, store | _ -> failwith ("[interp] OwnFieldNames didn't get an object," ^ " got " ^ (pretty_value obj_val) ^ " instead.") end | S.Op1 (p, op, e) -> let (e_val, store) = eval e env store in op1 store op e_val, store | S.Op2 (p, op, e1, e2) -> let (e1_val, store) = eval e1 env store in let (e2_val, store) = eval e2 env store in op2 store op e1_val e2_val, store | S.If (p, c, t, e) -> let (c_val, store) = eval c env store in if (c_val = True) then eval t env store else eval e env store | S.App (p, func, args) -> let (func_value, store) = eval func env store in let (args_values, store) = fold_left (fun (vals, store) e -> let (newval, store) = eval e env store in (newval::vals, store)) ([], store) args in apply p store func_value (List.rev args_values) | S.Seq (p, e1, e2) -> let (_, store) = eval e1 env store in eval e2 env store | S.Let (p, x, e, body) -> let (e_val, store) = eval e env store in let (new_loc, store) = add_var store e_val in eval body (IdMap.add x new_loc env) store | S.Rec (p, x, e, body) -> let (new_loc, store) = add_var store Undefined in let env' = (IdMap.add x new_loc env) in let (ev_val, store) = eval e env' store in eval body env' (set_var store new_loc ev_val) | S.Label (p, l, e) -> begin try eval e env store with Break (t, l', v, store) -> if l = l' then (v, store) else raise (Break (t, l', v, store)) end | S.Break (p, l, e) -> let v, store = eval e env store in raise (Break ([], l, v, store)) | S.TryCatch (p, body, catch) -> begin try eval body env store with Throw (_, v, store) -> let catchv, store = eval catch env store in apply p store catchv [v] end | S.TryFinally (p, body, fin) -> begin try let (v, store) = eval body env store in let (_, store') = eval fin env store in (v, store') with | Throw (t, v, store) -> let (_, store) = eval fin env store in raise (Throw (t, v, store)) | Break (t, l, v, store) -> let (_, store) = eval fin env store in raise (Break (t, l, v, store)) end | S.Throw (p, e) -> let (v, s) = eval e env store in raise (Throw ([], v, s)) | S.Lambda (p, xs, e) -> let free_vars = S.free_vars e in let filtered_env = IdMap.filter (fun var _ -> IdSet.mem var free_vars) env in Closure (filtered_env, xs, e), store | S.Eval (p, e, bindings) -> let evalstr, store = eval e env store in let bindobj, store = eval bindings env store in begin match evalstr, bindobj with | String s, ObjLoc o -> let expr = desugar s in let env, store = envstore_of_obj p (get_obj store o) store in eval expr env store | String s, _ -> interp_error p "Non-object given to eval() for env" | v, _ -> v, store end and envstore_of_obj p (_, props) store = IdMap.fold (fun id prop (env, store) -> match prop with | Data ({value=v}, _, _) -> let new_loc, store = add_var store v in let env = IdMap.add id new_loc env in env, store | _ -> interp_error p "Non-data value in env_of_obj") props (IdMap.empty, store) and arity_mismatch_err p xs args = interp_error p ("Arity mismatch, supplied " ^ string_of_int (List.length args) ^ " arguments and expected " ^ string_of_int (List.length xs) ^ ". Arg names were: " ^ (List.fold_right (^) (map (fun s -> " " ^ s ^ " ") xs) "") ^ ". Values were: " ^ (List.fold_right (^) (map (fun v -> " " ^ pretty_value v ^ " ") args) "")) let err show_stack trace message = if show_stack then begin eprintf "%s\n" (string_stack_trace trace); eprintf "%s\n" message; failwith "Runtime error" end else eprintf "%s\n" message; failwith "Runtime error" let continue_eval expr desugar print_trace env store = try Sys.catch_break true; let (v, store) = eval desugar expr env store in Answer ([], v, [], store) with | Snapshot (exprs, v, envs, store) -> Answer (exprs, v, envs, store) | Throw (t, v, store) -> let err_msg = match v with | ObjLoc loc -> begin match get_obj store loc with | _, props -> try match IdMap.find "%js-exn" props with | Data ({value=jserr}, _, _) -> string_of_value jserr store | _ -> string_of_value v store with Not_found -> string_of_value v store end | v -> string_of_value v store in err print_trace t (sprintf "Uncaught exception: %s\n" err_msg) | Break (p, l, v, _) -> failwith ("Broke to top of execution, missed label: " ^ l) | PrimErr (t, v) -> err print_trace t (sprintf "Uncaught error: %s\n" (pretty_value v)) let eval_expr expr desugar print_trace = continue_eval expr desugar print_trace IdMap.empty (Store.empty, Store.empty)
5ea65e72a0100e64be30a38b7cf89fa51cbcfca228648944f39e33571520961d
melange-re/melange
int32.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) Module [ Int32 ] : 32 - bit integers external neg : int32 -> int32 = "%int32_neg" external add : int32 -> int32 -> int32 = "%int32_add" external sub : int32 -> int32 -> int32 = "%int32_sub" external mul : int32 -> int32 -> int32 = "%int32_mul" external div : int32 -> int32 -> int32 = "%int32_div" external rem : int32 -> int32 -> int32 = "%int32_mod" external logand : int32 -> int32 -> int32 = "%int32_and" external logor : int32 -> int32 -> int32 = "%int32_or" external logxor : int32 -> int32 -> int32 = "%int32_xor" external shift_left : int32 -> int -> int32 = "%int32_lsl" external shift_right : int32 -> int -> int32 = "%int32_asr" external shift_right_logical : int32 -> int -> int32 = "%int32_lsr" external of_int : int -> int32 = "%int32_of_int" external to_int : int32 -> int = "%int32_to_int" external of_float : float -> int32 = "caml_int32_of_float" "caml_int32_of_float_unboxed" [@@unboxed] [@@noalloc] external to_float : int32 -> float = "caml_int32_to_float" "caml_int32_to_float_unboxed" [@@unboxed] [@@noalloc] external bits_of_float : float -> int32 = "caml_int32_bits_of_float" "caml_int32_bits_of_float_unboxed" [@@unboxed] [@@noalloc] external float_of_bits : int32 -> float = "caml_int32_float_of_bits" "caml_int32_float_of_bits_unboxed" [@@unboxed] [@@noalloc] let zero = 0l let one = 1l let minus_one = -1l let succ n = add n 1l let pred n = sub n 1l let abs n = if n >= 0l then n else neg n let min_int = 0x80000000l let max_int = 0x7FFFFFFFl let lognot n = logxor n (-1l) let unsigned_to_int = match Sys.word_size with | 32 -> let max_int = of_int Stdlib.max_int in fun n -> if compare zero n <= 0 && compare n max_int <= 0 then Some (to_int n) else None | 64 -> So that it compiles in 32 - bit let mask = 0xFFFF lsl 16 lor 0xFFFF in fun n -> Some (to_int n land mask) | _ -> assert false external format : string -> int32 -> string = "caml_int32_format" let to_string n = format "%d" n external of_string : string -> int32 = "caml_int32_of_string" let of_string_opt s = (* TODO: expose a non-raising primitive directly. *) try Some (of_string s) with Failure _ -> None type t = int32 let compare (x: t) (y: t) = Stdlib.compare x y let equal (x: t) (y: t) = compare x y = 0 let unsigned_compare n m = compare (sub n min_int) (sub m min_int) let min x y : t = if x <= y then x else y let max x y : t = if x >= y then x else y Unsigned division from signed division of the same bitness . See , ( 2013 ) . Hacker 's Delight ( 2 ed . ) , Sec 9 - 3 . bitness. See Warren Jr., Henry S. (2013). Hacker's Delight (2 ed.), Sec 9-3. *) let unsigned_div n d = if d < zero then if unsigned_compare n d < 0 then zero else one else let q = shift_left (div (shift_right_logical n 1) d) 1 in let r = sub n (mul q d) in if unsigned_compare r d >= 0 then succ q else q let unsigned_rem n d = sub n (mul (unsigned_div n d) d)
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/stdlib-412/stdlib_modules/int32.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ TODO: expose a non-raising primitive directly.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the Module [ Int32 ] : 32 - bit integers external neg : int32 -> int32 = "%int32_neg" external add : int32 -> int32 -> int32 = "%int32_add" external sub : int32 -> int32 -> int32 = "%int32_sub" external mul : int32 -> int32 -> int32 = "%int32_mul" external div : int32 -> int32 -> int32 = "%int32_div" external rem : int32 -> int32 -> int32 = "%int32_mod" external logand : int32 -> int32 -> int32 = "%int32_and" external logor : int32 -> int32 -> int32 = "%int32_or" external logxor : int32 -> int32 -> int32 = "%int32_xor" external shift_left : int32 -> int -> int32 = "%int32_lsl" external shift_right : int32 -> int -> int32 = "%int32_asr" external shift_right_logical : int32 -> int -> int32 = "%int32_lsr" external of_int : int -> int32 = "%int32_of_int" external to_int : int32 -> int = "%int32_to_int" external of_float : float -> int32 = "caml_int32_of_float" "caml_int32_of_float_unboxed" [@@unboxed] [@@noalloc] external to_float : int32 -> float = "caml_int32_to_float" "caml_int32_to_float_unboxed" [@@unboxed] [@@noalloc] external bits_of_float : float -> int32 = "caml_int32_bits_of_float" "caml_int32_bits_of_float_unboxed" [@@unboxed] [@@noalloc] external float_of_bits : int32 -> float = "caml_int32_float_of_bits" "caml_int32_float_of_bits_unboxed" [@@unboxed] [@@noalloc] let zero = 0l let one = 1l let minus_one = -1l let succ n = add n 1l let pred n = sub n 1l let abs n = if n >= 0l then n else neg n let min_int = 0x80000000l let max_int = 0x7FFFFFFFl let lognot n = logxor n (-1l) let unsigned_to_int = match Sys.word_size with | 32 -> let max_int = of_int Stdlib.max_int in fun n -> if compare zero n <= 0 && compare n max_int <= 0 then Some (to_int n) else None | 64 -> So that it compiles in 32 - bit let mask = 0xFFFF lsl 16 lor 0xFFFF in fun n -> Some (to_int n land mask) | _ -> assert false external format : string -> int32 -> string = "caml_int32_format" let to_string n = format "%d" n external of_string : string -> int32 = "caml_int32_of_string" let of_string_opt s = try Some (of_string s) with Failure _ -> None type t = int32 let compare (x: t) (y: t) = Stdlib.compare x y let equal (x: t) (y: t) = compare x y = 0 let unsigned_compare n m = compare (sub n min_int) (sub m min_int) let min x y : t = if x <= y then x else y let max x y : t = if x >= y then x else y Unsigned division from signed division of the same bitness . See , ( 2013 ) . Hacker 's Delight ( 2 ed . ) , Sec 9 - 3 . bitness. See Warren Jr., Henry S. (2013). Hacker's Delight (2 ed.), Sec 9-3. *) let unsigned_div n d = if d < zero then if unsigned_compare n d < 0 then zero else one else let q = shift_left (div (shift_right_logical n 1) d) 1 in let r = sub n (mul q d) in if unsigned_compare r d >= 0 then succ q else q let unsigned_rem n d = sub n (mul (unsigned_div n d) d)
1df16f472ec9cfe979f861c0e9c803cb8c5aae7834902a164f078c16306352b9
SnootyMonkey/posthere.io
results.clj
(ns posthere.results "Show the saved requests for a particular URL UUID." (:require [clojure.string :as s] [net.cgrand.enlive-html :as enl :refer (content html-snippet deftemplate)] [ring.util.response :refer (response header)] [cheshire.core :refer (generate-string)] [posthere.examples :as examples] [posthere.static-templating :as st :refer (partial-content add-key remove-js)])) (deftemplate results-page st/layout [results uuid] use Enlive to combine the layout and the page partial into a HTMl page [:#page-partial-container] (content (html-snippet (partial-content "results"))) [:#doorbell-io-app-key] (add-key st/doorbell-io-app-key) ;; insert the config'd doorbell.io app key remove the doorbell.io JS if there 's no app key insert the config'd Google Analytics tracking code remove the Google Analytics JS if there 's no tracking code ;; unhide the results div if we DO have some results [:#results] (if-not (empty? results) (enl/remove-attr :style)) ;; unhide the API hints div if we DO have some results and it's not the examples [:#api] (if-not (or (empty? results) (= (str "/" uuid) examples/example-url)) (enl/remove-attr :style)) ;; keep the empty-results div only if we DON'T have any results [:#empty-results] (if (empty? results) (enl/append "")) ; append a blank string (do nothing), otherwise returning nil wipes it out add a JavaScript array with the POST results for this UUID from redis ( or an empty array if there are none ) [:#data] (if (empty? results) (enl/html-content "<script type='text/javascript'>var resultData = []; </script>") (enl/html-content (str "<script type='text/javascript'>var resultData = " (generate-string results) "</script>"))) replace the placeholder UUID in the HTML template with our actual UUID [:.uuid-value] (enl/html-content (str uuid))) (defn results-view "Create our HTML page for results using the results HTML template and enlive." [results uuid headers] (if (or (= (get headers "accept") "application/json") ; http-kit in development is lower-case (= (get headers "Accept") "application/json")) ; nginx-clojure in production is camel-case ;; Asked for JSON (header (response (generate-string results)) "content-type" "application/json") ;; Everything else gets HTML (s/join (results-page results uuid))))
null
https://raw.githubusercontent.com/SnootyMonkey/posthere.io/698b46c917d7f74a5fb06c13beae49ded1ca1705/src/posthere/results.clj
clojure
insert the config'd doorbell.io app key unhide the results div if we DO have some results unhide the API hints div if we DO have some results and it's not the examples keep the empty-results div only if we DON'T have any results append a blank string (do nothing), otherwise returning nil wipes it out http-kit in development is lower-case nginx-clojure in production is camel-case Asked for JSON Everything else gets HTML
(ns posthere.results "Show the saved requests for a particular URL UUID." (:require [clojure.string :as s] [net.cgrand.enlive-html :as enl :refer (content html-snippet deftemplate)] [ring.util.response :refer (response header)] [cheshire.core :refer (generate-string)] [posthere.examples :as examples] [posthere.static-templating :as st :refer (partial-content add-key remove-js)])) (deftemplate results-page st/layout [results uuid] use Enlive to combine the layout and the page partial into a HTMl page [:#page-partial-container] (content (html-snippet (partial-content "results"))) remove the doorbell.io JS if there 's no app key insert the config'd Google Analytics tracking code remove the Google Analytics JS if there 's no tracking code [:#results] (if-not (empty? results) (enl/remove-attr :style)) [:#api] (if-not (or (empty? results) (= (str "/" uuid) examples/example-url)) (enl/remove-attr :style)) [:#empty-results] (if (empty? results) add a JavaScript array with the POST results for this UUID from redis ( or an empty array if there are none ) [:#data] (if (empty? results) (enl/html-content "<script type='text/javascript'>var resultData = []; </script>") (enl/html-content (str "<script type='text/javascript'>var resultData = " (generate-string results) "</script>"))) replace the placeholder UUID in the HTML template with our actual UUID [:.uuid-value] (enl/html-content (str uuid))) (defn results-view "Create our HTML page for results using the results HTML template and enlive." [results uuid headers] (if (or (header (response (generate-string results)) "content-type" "application/json") (s/join (results-page results uuid))))
7bc70962938e1a15aa95378fe2a652ec2c57ec938882ed4a55949df98c5c8e5d
maybevoid/casimir
Free.hs
module Casimir.Free ( EffCoOp (..) , FreeOps (..) , CoOpHandler (..) , FreeEff (..) , FreeHandler (..) , NoCoOp , UnionCoOp (..) , ChurchMonad (..) , FreeMonad (..) , GenericCoOpHandler (..) , ContextualHandler (..) , freeLiftEff , coopHandlerToPipeline , genericCoOpHandlerToPipeline , contextualHandlerToPipeline , withCoOpHandler , withCoOpHandlerAndOps , withContextualCoOpHandler ) where import Casimir.Free.CoOp import Casimir.Free.NoOp import Casimir.Free.Union import Casimir.Free.FreeOps import Casimir.Free.FreeEff import Casimir.Free.Handler import Casimir.Free.Pipeline import Casimir.Free.Monad.Church (ChurchMonad (..)) import Casimir.Free.Monad.Free (FreeMonad (..))
null
https://raw.githubusercontent.com/maybevoid/casimir/ebbfa403739d6f258e6ac6793549006a0e8bff42/casimir/src/lib/Casimir/Free.hs
haskell
module Casimir.Free ( EffCoOp (..) , FreeOps (..) , CoOpHandler (..) , FreeEff (..) , FreeHandler (..) , NoCoOp , UnionCoOp (..) , ChurchMonad (..) , FreeMonad (..) , GenericCoOpHandler (..) , ContextualHandler (..) , freeLiftEff , coopHandlerToPipeline , genericCoOpHandlerToPipeline , contextualHandlerToPipeline , withCoOpHandler , withCoOpHandlerAndOps , withContextualCoOpHandler ) where import Casimir.Free.CoOp import Casimir.Free.NoOp import Casimir.Free.Union import Casimir.Free.FreeOps import Casimir.Free.FreeEff import Casimir.Free.Handler import Casimir.Free.Pipeline import Casimir.Free.Monad.Church (ChurchMonad (..)) import Casimir.Free.Monad.Free (FreeMonad (..))
4ad8cd3adf06e981a2838932d85ef9cbc7cdc41ea4b87ea989bcf0b7ab16870c
zchn/ethereum-analyzer
Foreach.hs
module Ethereum.Analyzer.Solidity.Foreach ( statementsOf , expressionsOf ) where import Protolude import Data.List (concatMap) import Ethereum.Analyzer.Solidity.Simple statementsOf :: Contract -> [Statement] statementsOf = _sOf class HasStatements a where _sOf :: a -> [Statement] instance HasStatements Contract where _sOf Contract {cFunctions = funs} = concatMap _sOf funs instance HasStatements FunDefinition where _sOf FunDefinition {fBody = stmts} = concatMap _sOf stmts instance HasStatements Statement where _sOf s@(StIf _ thenSts elseSts) = [s] <> concatMap _sOf thenSts <> concatMap _sOf elseSts _sOf s@(StLoop bodySts) = [s] <> concatMap _sOf bodySts _sOf s = [s] expressionsOf :: Contract -> [Expression] expressionsOf c = concatMap _eOf $ statementsOf c _eOf :: Statement -> [Expression] _eOf (StLocalVarDecl _) = [] _eOf (StAssign _ e) = [e] _eOf StIf {} = [] _eOf (StLoop _) = [] _eOf StBreak = [] _eOf StContinue = [] _eOf (StReturn _) = [] _eOf (StDelete _) = [] _eOf (StTodo _) = [] _eOf StThrow = []
null
https://raw.githubusercontent.com/zchn/ethereum-analyzer/f2a60d8b451358971f1e3b1a61658f5741c4c099/ethereum-analyzer/src/Ethereum/Analyzer/Solidity/Foreach.hs
haskell
module Ethereum.Analyzer.Solidity.Foreach ( statementsOf , expressionsOf ) where import Protolude import Data.List (concatMap) import Ethereum.Analyzer.Solidity.Simple statementsOf :: Contract -> [Statement] statementsOf = _sOf class HasStatements a where _sOf :: a -> [Statement] instance HasStatements Contract where _sOf Contract {cFunctions = funs} = concatMap _sOf funs instance HasStatements FunDefinition where _sOf FunDefinition {fBody = stmts} = concatMap _sOf stmts instance HasStatements Statement where _sOf s@(StIf _ thenSts elseSts) = [s] <> concatMap _sOf thenSts <> concatMap _sOf elseSts _sOf s@(StLoop bodySts) = [s] <> concatMap _sOf bodySts _sOf s = [s] expressionsOf :: Contract -> [Expression] expressionsOf c = concatMap _eOf $ statementsOf c _eOf :: Statement -> [Expression] _eOf (StLocalVarDecl _) = [] _eOf (StAssign _ e) = [e] _eOf StIf {} = [] _eOf (StLoop _) = [] _eOf StBreak = [] _eOf StContinue = [] _eOf (StReturn _) = [] _eOf (StDelete _) = [] _eOf (StTodo _) = [] _eOf StThrow = []
9f180c8a3d38025cf92985cc141ca4cfc5b5eaf335c047108d07d9475dd21fcc
ocaml-gospel/gospel
redundant2.mli
type t = A | B of t val f : t -> int (*@ y = f x ensures match x with | A -> false | B (B _) -> false | B (B A) -> false | _ -> true *) { gospel_expected| [ 125 ] File " redundant2.mli " , line 5 , characters 12 - 103 : 5 | ............ match x with 6 | | A - > false 7 | | B ( B _ ) - > false 8 | | B ( B A ) - > false 9 | | _ - > true ... Error : The pattern - matching is redundant . Here is a case that is unused : B B A. |gospel_expected } [125] File "redundant2.mli", line 5, characters 12-103: 5 | ............match x with 6 | | A -> false 7 | | B (B _) -> false 8 | | B (B A) -> false 9 | | _ -> true... Error: The pattern-matching is redundant. Here is a case that is unused: B B A. |gospel_expected} *)
null
https://raw.githubusercontent.com/ocaml-gospel/gospel/79841c510baeb396d9a695ae33b290899188380b/test/patterns/negative/redundant2.mli
ocaml
@ y = f x ensures match x with | A -> false | B (B _) -> false | B (B A) -> false | _ -> true
type t = A | B of t val f : t -> int { gospel_expected| [ 125 ] File " redundant2.mli " , line 5 , characters 12 - 103 : 5 | ............ match x with 6 | | A - > false 7 | | B ( B _ ) - > false 8 | | B ( B A ) - > false 9 | | _ - > true ... Error : The pattern - matching is redundant . Here is a case that is unused : B B A. |gospel_expected } [125] File "redundant2.mli", line 5, characters 12-103: 5 | ............match x with 6 | | A -> false 7 | | B (B _) -> false 8 | | B (B A) -> false 9 | | _ -> true... Error: The pattern-matching is redundant. Here is a case that is unused: B B A. |gospel_expected} *)
ae40fa9adb5ec59379e57d0a0504f9378eae8ab9d419cb2821f374bb0a701133
lukaszcz/coinduction
cStmt.ml
(* Statement translation -- implementation *) Read first : #inductive-definitions , kernel / entries.ml , kernel / constr.mli #inductive-definitions, kernel/entries.ml, kernel/constr.mli *) open CUtils open CPred open Names type coarg = ATerm of EConstr.t | AEx of int (* a variable bound by an existential -- Rel index *) type stmt = SProd of Name.t Context.binder_annot * EConstr.t (* type *) * stmt (* body *) | SPred of int (* copred index 0-based *) * copred * coarg list | SAnd (* and-like inductive type *) of inductive * stmt list | SEx (* exists-like inductive type *) of inductive * Name.t Context.binder_annot (* variable name *) * stmt (* type *) * stmt (* body *) let map_fold_stmt (f : int -> 'a -> stmt -> 'a * stmt) acc stmt = let rec hlp n acc stmt = match stmt with | SProd(na, ty, body) -> let (acc2, body2) = hlp (n + 1) acc body in f n acc2 (SProd(na, ty, body2)) | SPred _ -> f n acc stmt | SAnd (ind, args) -> let (acc2, args2) = List.fold_right begin fun x (acc, args2) -> let (acc2, x2) = hlp n acc x in (acc2, x2 :: args2) end args (acc, []) in f n acc2 (SAnd (ind, args2)) | SEx (ind, na, ty, body) -> let (acc, ty2) = hlp n acc ty in let (acc, body2) = hlp (n + 1) acc body in f n acc (SEx (ind, na, ty2, body2)) in hlp 0 acc stmt let map_stmt (f : int -> stmt -> stmt) stmt = snd (map_fold_stmt (fun n () x -> ((), f n x)) () stmt) let fold_stmt (f : int -> 'a -> stmt -> 'a) acc stmt = fst (map_fold_stmt (fun n acc x -> (f n acc x, x)) acc stmt) let stmt_to_constr (f : int -> int -> copred -> coarg list -> EConstr.t) = let open EConstr in let rec hlp n stmt = match stmt with | SProd(na, ty, body) -> mkProd (na, ty, hlp (n + 1) body) | SPred(p, cop, coargs) -> f n p cop coargs | SAnd (ind, args) -> mkApp(mkInd ind, Array.of_list (List.map (hlp n) args)) | SEx (ind, na, ty, body) -> let ty2 = hlp n ty in let body2 = hlp (n + 1) body in mkApp(mkInd ind, [| ty2; mkLambda(na, ty2, body2) |]) in hlp 0 let get_copreds s = let rec hlp s acc = match s with | SProd(na, ty, body) -> hlp body acc | SPred(p, cop, coargs) -> (p, cop) :: acc | SAnd (ind, args) -> List.fold_left (fun acc x -> hlp x acc) acc args | SEx (ind, na, ty, body) -> hlp body (hlp ty acc) in List.rev (hlp s []) let translate_coargs ectx evd args = let open Constr in let open EConstr in List.map begin fun x -> match kind evd x with | Rel i when fst (List.nth ectx (i - 1)) <> "" -> AEx i | _ -> ATerm x (* TODO: check if existential variables do not occur in `x' *) end args let make_stmt evd t = let get_ex_arg_indname evd ty = let open Constr in let open EConstr in match kind evd ty with | App (t, args) -> begin match kind evd t with | Ind (ind, _) when is_coinductive ind -> get_ind_name ind | _ -> failwith ("unsupported coinductive statement: " ^ "the type of an existential variable should be coinductive") end | Ind (ind, _) when is_coinductive ind -> get_ind_name ind | _ -> failwith ("unsupported coinductive statement: " ^ "the type of an existential variable should be coinductive") in let open Constr in let open EConstr in p - the number of " to the left " let rec hlp evd p ectx t = match kind evd t with | Prod (na, ty, c) -> let (evd, a, x) = hlp evd p (("", 0) :: ectx) c in (evd, a, SProd (na, ty, x)) | Ind (ind, u) when is_coinductive ind -> let (evd, cop) = translate_coinductive evd ind [] [] in (evd, p + 1, SPred (p, cop, [])) | App (f, args) -> begin match kind evd f with | Ind (ind, u) when is_coinductive ind -> let coargs = translate_coargs ectx evd (Array.to_list args) in let ex_args = List.map (function ATerm _ -> "" | AEx i -> fst (List.nth ectx (i - 1))) coargs in let ex_arg_idxs = List.filter (fun i -> i >= 0) (List.map (function ATerm _ -> -1 | AEx i -> snd (List.nth ectx (i - 1))) coargs) in let (evd, cop) = translate_coinductive evd ind ex_args ex_arg_idxs in (evd, p + 1, SPred (p, cop, coargs)) | Ind (ind, u) when is_and_like ind && Array.length args = get_ind_nparams ind -> let (evd, p', rargs') = List.fold_left begin fun (evd, p, acc) x -> let (evd, a, y) = hlp evd p ectx x in (evd, a, y :: acc) end (evd, p, []) (Array.to_list args) in (evd, p', SAnd (ind, List.rev rargs')) | Ind (ind, u) when is_exists_like ind -> begin match args with | [| ty; pred |] -> begin match kind evd pred with | Lambda(na, _, body) -> begin let (evd, p1, cp) = hlp evd p ectx ty in match cp with | SPred (_, cop, _) -> begin CPeek.declare_peek evd cop.cop_name; let (evd, p2, x) = hlp evd p1 ((get_ex_arg_indname evd ty, p) :: ectx) body in (evd, p2, SEx (ind, na, cp, x)) end | _ -> failwith "unsupported coinductive statement (1)" end | _ -> failwith "unsupported coinductive statement (2)" end | _ -> failwith "unsupported coinductive statement (3)" end | _ -> failwith "unsupported coinductive statement (4)" end | _ -> failwith "unsupported coinductive statement (5)" in let (evd, _, s) = hlp evd 0 [] t in (evd, s) (* m - the total number of coinductive predicates (= the number of red parameters) *) (* n - the number of non-ex binders up *) (* p - the index of the current cop (0-indexed) *) let make_ch_red_cop m n p cop coargs = let open EConstr in let args = List.map begin function | ATerm t -> t | AEx i -> failwith "AEx" end coargs in mkApp (mkRel (n + m + m + m), Array.of_list args) let fix_rels evd n = let open Constr in let open EConstr in map_constr begin fun k t -> match kind evd t with | Rel i when i >= k + n + 1 -> mkRel (i - 1) | _ -> t end evd (* m - the total number of coinductive predicates (= the number of red parameters) *) (* n - the number of non-ex binders up *) let fix_stmt_rels evd m n p s = let open EConstr in map_stmt begin fun k x -> match x with | SProd (na, ty, body) -> SProd (na, fix_rels evd k ty, body) | SPred (idx, cop, coargs) -> SPred (idx, cop, List.map begin function | ATerm t -> ATerm (fix_rels evd k t) | AEx i when i = k + 1 -> let args = List.rev (List.map mkRel (range (k + 1) (k + n + 1))) in ATerm (mkApp (mkRel (k + n + idx - p), Array.of_list args)) | x -> x end coargs) | _ -> x end s (* m - the total number of coinductive predicates (= the number of red parameters) *) let make_coind_hyps evd m s = let open EConstr in (* n - the number of non-ex binders up *) let rec hlp n s = match s with | SProd (na, ty, body) -> List.map (fun x -> mkProd (na, ty, x)) (hlp (n + 1) body) | SPred (p, cop, coargs) -> [make_ch_red_cop m n p cop coargs] | SAnd (ind, args) -> List.concat (List.map (hlp n) args) | SEx (ind, na, ty, body) -> begin match ty with | SPred (p, _, _) -> hlp n ty @ hlp n (fix_stmt_rels evd m n p body) | _ -> failwith "SEx" end in hlp 0 s let make_red k = stmt_to_constr begin fun n p cop coargs -> let open EConstr in let args = List.map begin function | ATerm t -> t | AEx i -> mkRel i end coargs in mkApp (mkRel (n + k - p), Array.of_list args) end let make_green_cop k p cop args = let open EConstr in let args = List.map (fun idx -> mkRel (k - idx)) cop.cop_ex_arg_idxs @ [ mkRel (k - p) ] @ args in mkApp (get_constr (get_green_name cop cop.cop_name), Array.of_list args) let make_green k = stmt_to_constr begin fun n p cop coargs -> let open EConstr in make_green_cop (n + k) p cop (List.map begin function | ATerm t -> t | AEx i -> mkRel i end coargs) end let get_red_type evd p cop = let open Constr in let open EConstr in let rec hlp k lst idxs t = match lst with | head :: tail -> begin match kind evd t with | Prod (na, ty, body) -> if head <> "" then begin mkProd (na, fix_ex_arg_e_red evd (k + p - List.hd idxs) ty, hlp (k + 1) tail (List.tl idxs) body) end else mkProd (na, ty, hlp (k + 1) tail idxs body) | _ -> failwith "unsupported coinductive type" end | [] -> t in hlp 0 cop.cop_ex_args cop.cop_ex_arg_idxs cop.cop_type let fix_ex_arg_inj_args evd p cop m k typeargs args2 = let rec hlp n lst ex_args tyargs idxs = match lst, ex_args, tyargs with | h :: t1, arg :: t2, ty :: t3 -> if arg <> "" then let i = k + 1 + p - List.hd idxs in let open Constr in let open EConstr in let h2 = match kind evd ty with | Ind (_) -> mkApp (mkRel i, [| h |]) | App (_, args) -> let args' = Array.map begin fun x -> map_constr begin fun l y -> match kind evd y with | Rel j when j > l -> mkRel (j + k - n + 1) | _ -> y end evd x end args in mkApp (mkRel i, Array.append args' [| h |]) | _ -> failwith "unsupported coinductive type (2)" in h2 :: hlp (n + 1) t1 t2 t3 (List.tl idxs) else h :: hlp (n + 1) t1 t2 t3 idxs | _ -> lst in hlp 0 args2 cop.cop_ex_args (List.map snd typeargs) cop.cop_ex_arg_idxs let fix_injg_typeargs evd k copreds cop typeargs = let rec hlp n ex_args tyargs idxs = match ex_args, tyargs with | arg :: t1, ty :: t2 -> if arg <> "" then let p2 = List.hd idxs in let cop2 = List.nth copreds p2 in let open Constr in let open EConstr in let ty2 = match kind evd ty with | Ind (_) -> make_green_cop (k + n) p2 cop2 [] | App (_, args) -> make_green_cop (k + n) p2 cop2 (Array.to_list args) | _ -> failwith "unsupported coinductive type (2)" in ty2 :: hlp (n + 1) t1 t2 (List.tl idxs) else ty :: hlp (n + 1) t1 t2 idxs | _ -> [] in List.combine (List.map fst typeargs) (hlp 0 cop.cop_ex_args (List.map snd typeargs) cop.cop_ex_arg_idxs) let translate_statement evd t = let open EConstr in let fix_ctx = List.map (fun (x, y) -> (Context.make_annot (Name.mk_name (string_to_id x)) Sorts.Relevant, y)) in let (evd, stmt) = make_stmt evd t in let copreds = get_copreds stmt in let m = List.length copreds in let red_copred_decls = List.map begin fun (p, cop) -> (get_red_name cop cop.cop_name, get_red_type evd p cop) end copreds in let injections = List.map begin fun (p, cop) -> let typeargs = get_inductive_typeargs evd (get_inductive cop.cop_name) in let k = List.length typeargs in let args1 = Array.of_list (List.rev (List.map mkRel (range 1 (k + 1)))) in let args2_l = List.rev (List.map mkRel (range 2 (k + 2))) in let args2 = Array.of_list (fix_ex_arg_inj_args evd p cop m k typeargs args2_l) in (get_red_name cop cop.cop_name ^ "__inj", close mkProd typeargs (mkProd (Context.make_annot Name.Anonymous Sorts.Relevant, mkApp (get_constr cop.cop_name, args1), mkApp (mkRel (k + 1 + m), args2)))) end copreds in let injections2 = List.map begin fun (p, cop) -> let typeargs0 = get_inductive_typeargs evd (get_inductive cop.cop_name) in let typeargs = fix_injg_typeargs evd (2 * m + p) (List.map snd copreds) cop typeargs0 in let k = List.length typeargs in let args1_l = List.rev (List.map mkRel (range 1 (k + 1))) in let args2_l = List.rev (List.map mkRel (range 2 (k + 2))) in let args2 = Array.of_list (fix_ex_arg_inj_args evd p cop m k typeargs0 args2_l) in (get_red_name cop cop.cop_name ^ "__injg", close mkProd typeargs (mkProd (Context.make_annot Name.Anonymous Sorts.Relevant, make_green_cop (m + m + k + p) p cop args1_l, mkApp (mkRel (k + 1 + m + m), args2)))) end copreds in let result = close mkProd (fix_ctx red_copred_decls) (close mkProd (fix_ctx injections) (close mkProd (fix_ctx injections2) (mkProd (Context.make_annot Name.Anonymous Sorts.Relevant, make_red (m + m + m) stmt, make_green (m + m + m + 1) stmt)))) in let cohyps = make_coind_hyps evd m stmt in (evd, stmt, cohyps, result)
null
https://raw.githubusercontent.com/lukaszcz/coinduction/b7437fe155a45f93042a5788dc62512534172dcd/src/cStmt.ml
ocaml
Statement translation -- implementation a variable bound by an existential -- Rel index type body copred index 0-based and-like inductive type exists-like inductive type variable name type body TODO: check if existential variables do not occur in `x' m - the total number of coinductive predicates (= the number of red parameters) n - the number of non-ex binders up p - the index of the current cop (0-indexed) m - the total number of coinductive predicates (= the number of red parameters) n - the number of non-ex binders up m - the total number of coinductive predicates (= the number of red parameters) n - the number of non-ex binders up
Read first : #inductive-definitions , kernel / entries.ml , kernel / constr.mli #inductive-definitions, kernel/entries.ml, kernel/constr.mli *) open CUtils open CPred open Names type coarg = ATerm of EConstr.t type stmt = let map_fold_stmt (f : int -> 'a -> stmt -> 'a * stmt) acc stmt = let rec hlp n acc stmt = match stmt with | SProd(na, ty, body) -> let (acc2, body2) = hlp (n + 1) acc body in f n acc2 (SProd(na, ty, body2)) | SPred _ -> f n acc stmt | SAnd (ind, args) -> let (acc2, args2) = List.fold_right begin fun x (acc, args2) -> let (acc2, x2) = hlp n acc x in (acc2, x2 :: args2) end args (acc, []) in f n acc2 (SAnd (ind, args2)) | SEx (ind, na, ty, body) -> let (acc, ty2) = hlp n acc ty in let (acc, body2) = hlp (n + 1) acc body in f n acc (SEx (ind, na, ty2, body2)) in hlp 0 acc stmt let map_stmt (f : int -> stmt -> stmt) stmt = snd (map_fold_stmt (fun n () x -> ((), f n x)) () stmt) let fold_stmt (f : int -> 'a -> stmt -> 'a) acc stmt = fst (map_fold_stmt (fun n acc x -> (f n acc x, x)) acc stmt) let stmt_to_constr (f : int -> int -> copred -> coarg list -> EConstr.t) = let open EConstr in let rec hlp n stmt = match stmt with | SProd(na, ty, body) -> mkProd (na, ty, hlp (n + 1) body) | SPred(p, cop, coargs) -> f n p cop coargs | SAnd (ind, args) -> mkApp(mkInd ind, Array.of_list (List.map (hlp n) args)) | SEx (ind, na, ty, body) -> let ty2 = hlp n ty in let body2 = hlp (n + 1) body in mkApp(mkInd ind, [| ty2; mkLambda(na, ty2, body2) |]) in hlp 0 let get_copreds s = let rec hlp s acc = match s with | SProd(na, ty, body) -> hlp body acc | SPred(p, cop, coargs) -> (p, cop) :: acc | SAnd (ind, args) -> List.fold_left (fun acc x -> hlp x acc) acc args | SEx (ind, na, ty, body) -> hlp body (hlp ty acc) in List.rev (hlp s []) let translate_coargs ectx evd args = let open Constr in let open EConstr in List.map begin fun x -> match kind evd x with | Rel i when fst (List.nth ectx (i - 1)) <> "" -> AEx i end args let make_stmt evd t = let get_ex_arg_indname evd ty = let open Constr in let open EConstr in match kind evd ty with | App (t, args) -> begin match kind evd t with | Ind (ind, _) when is_coinductive ind -> get_ind_name ind | _ -> failwith ("unsupported coinductive statement: " ^ "the type of an existential variable should be coinductive") end | Ind (ind, _) when is_coinductive ind -> get_ind_name ind | _ -> failwith ("unsupported coinductive statement: " ^ "the type of an existential variable should be coinductive") in let open Constr in let open EConstr in p - the number of " to the left " let rec hlp evd p ectx t = match kind evd t with | Prod (na, ty, c) -> let (evd, a, x) = hlp evd p (("", 0) :: ectx) c in (evd, a, SProd (na, ty, x)) | Ind (ind, u) when is_coinductive ind -> let (evd, cop) = translate_coinductive evd ind [] [] in (evd, p + 1, SPred (p, cop, [])) | App (f, args) -> begin match kind evd f with | Ind (ind, u) when is_coinductive ind -> let coargs = translate_coargs ectx evd (Array.to_list args) in let ex_args = List.map (function ATerm _ -> "" | AEx i -> fst (List.nth ectx (i - 1))) coargs in let ex_arg_idxs = List.filter (fun i -> i >= 0) (List.map (function ATerm _ -> -1 | AEx i -> snd (List.nth ectx (i - 1))) coargs) in let (evd, cop) = translate_coinductive evd ind ex_args ex_arg_idxs in (evd, p + 1, SPred (p, cop, coargs)) | Ind (ind, u) when is_and_like ind && Array.length args = get_ind_nparams ind -> let (evd, p', rargs') = List.fold_left begin fun (evd, p, acc) x -> let (evd, a, y) = hlp evd p ectx x in (evd, a, y :: acc) end (evd, p, []) (Array.to_list args) in (evd, p', SAnd (ind, List.rev rargs')) | Ind (ind, u) when is_exists_like ind -> begin match args with | [| ty; pred |] -> begin match kind evd pred with | Lambda(na, _, body) -> begin let (evd, p1, cp) = hlp evd p ectx ty in match cp with | SPred (_, cop, _) -> begin CPeek.declare_peek evd cop.cop_name; let (evd, p2, x) = hlp evd p1 ((get_ex_arg_indname evd ty, p) :: ectx) body in (evd, p2, SEx (ind, na, cp, x)) end | _ -> failwith "unsupported coinductive statement (1)" end | _ -> failwith "unsupported coinductive statement (2)" end | _ -> failwith "unsupported coinductive statement (3)" end | _ -> failwith "unsupported coinductive statement (4)" end | _ -> failwith "unsupported coinductive statement (5)" in let (evd, _, s) = hlp evd 0 [] t in (evd, s) let make_ch_red_cop m n p cop coargs = let open EConstr in let args = List.map begin function | ATerm t -> t | AEx i -> failwith "AEx" end coargs in mkApp (mkRel (n + m + m + m), Array.of_list args) let fix_rels evd n = let open Constr in let open EConstr in map_constr begin fun k t -> match kind evd t with | Rel i when i >= k + n + 1 -> mkRel (i - 1) | _ -> t end evd let fix_stmt_rels evd m n p s = let open EConstr in map_stmt begin fun k x -> match x with | SProd (na, ty, body) -> SProd (na, fix_rels evd k ty, body) | SPred (idx, cop, coargs) -> SPred (idx, cop, List.map begin function | ATerm t -> ATerm (fix_rels evd k t) | AEx i when i = k + 1 -> let args = List.rev (List.map mkRel (range (k + 1) (k + n + 1))) in ATerm (mkApp (mkRel (k + n + idx - p), Array.of_list args)) | x -> x end coargs) | _ -> x end s let make_coind_hyps evd m s = let open EConstr in let rec hlp n s = match s with | SProd (na, ty, body) -> List.map (fun x -> mkProd (na, ty, x)) (hlp (n + 1) body) | SPred (p, cop, coargs) -> [make_ch_red_cop m n p cop coargs] | SAnd (ind, args) -> List.concat (List.map (hlp n) args) | SEx (ind, na, ty, body) -> begin match ty with | SPred (p, _, _) -> hlp n ty @ hlp n (fix_stmt_rels evd m n p body) | _ -> failwith "SEx" end in hlp 0 s let make_red k = stmt_to_constr begin fun n p cop coargs -> let open EConstr in let args = List.map begin function | ATerm t -> t | AEx i -> mkRel i end coargs in mkApp (mkRel (n + k - p), Array.of_list args) end let make_green_cop k p cop args = let open EConstr in let args = List.map (fun idx -> mkRel (k - idx)) cop.cop_ex_arg_idxs @ [ mkRel (k - p) ] @ args in mkApp (get_constr (get_green_name cop cop.cop_name), Array.of_list args) let make_green k = stmt_to_constr begin fun n p cop coargs -> let open EConstr in make_green_cop (n + k) p cop (List.map begin function | ATerm t -> t | AEx i -> mkRel i end coargs) end let get_red_type evd p cop = let open Constr in let open EConstr in let rec hlp k lst idxs t = match lst with | head :: tail -> begin match kind evd t with | Prod (na, ty, body) -> if head <> "" then begin mkProd (na, fix_ex_arg_e_red evd (k + p - List.hd idxs) ty, hlp (k + 1) tail (List.tl idxs) body) end else mkProd (na, ty, hlp (k + 1) tail idxs body) | _ -> failwith "unsupported coinductive type" end | [] -> t in hlp 0 cop.cop_ex_args cop.cop_ex_arg_idxs cop.cop_type let fix_ex_arg_inj_args evd p cop m k typeargs args2 = let rec hlp n lst ex_args tyargs idxs = match lst, ex_args, tyargs with | h :: t1, arg :: t2, ty :: t3 -> if arg <> "" then let i = k + 1 + p - List.hd idxs in let open Constr in let open EConstr in let h2 = match kind evd ty with | Ind (_) -> mkApp (mkRel i, [| h |]) | App (_, args) -> let args' = Array.map begin fun x -> map_constr begin fun l y -> match kind evd y with | Rel j when j > l -> mkRel (j + k - n + 1) | _ -> y end evd x end args in mkApp (mkRel i, Array.append args' [| h |]) | _ -> failwith "unsupported coinductive type (2)" in h2 :: hlp (n + 1) t1 t2 t3 (List.tl idxs) else h :: hlp (n + 1) t1 t2 t3 idxs | _ -> lst in hlp 0 args2 cop.cop_ex_args (List.map snd typeargs) cop.cop_ex_arg_idxs let fix_injg_typeargs evd k copreds cop typeargs = let rec hlp n ex_args tyargs idxs = match ex_args, tyargs with | arg :: t1, ty :: t2 -> if arg <> "" then let p2 = List.hd idxs in let cop2 = List.nth copreds p2 in let open Constr in let open EConstr in let ty2 = match kind evd ty with | Ind (_) -> make_green_cop (k + n) p2 cop2 [] | App (_, args) -> make_green_cop (k + n) p2 cop2 (Array.to_list args) | _ -> failwith "unsupported coinductive type (2)" in ty2 :: hlp (n + 1) t1 t2 (List.tl idxs) else ty :: hlp (n + 1) t1 t2 idxs | _ -> [] in List.combine (List.map fst typeargs) (hlp 0 cop.cop_ex_args (List.map snd typeargs) cop.cop_ex_arg_idxs) let translate_statement evd t = let open EConstr in let fix_ctx = List.map (fun (x, y) -> (Context.make_annot (Name.mk_name (string_to_id x)) Sorts.Relevant, y)) in let (evd, stmt) = make_stmt evd t in let copreds = get_copreds stmt in let m = List.length copreds in let red_copred_decls = List.map begin fun (p, cop) -> (get_red_name cop cop.cop_name, get_red_type evd p cop) end copreds in let injections = List.map begin fun (p, cop) -> let typeargs = get_inductive_typeargs evd (get_inductive cop.cop_name) in let k = List.length typeargs in let args1 = Array.of_list (List.rev (List.map mkRel (range 1 (k + 1)))) in let args2_l = List.rev (List.map mkRel (range 2 (k + 2))) in let args2 = Array.of_list (fix_ex_arg_inj_args evd p cop m k typeargs args2_l) in (get_red_name cop cop.cop_name ^ "__inj", close mkProd typeargs (mkProd (Context.make_annot Name.Anonymous Sorts.Relevant, mkApp (get_constr cop.cop_name, args1), mkApp (mkRel (k + 1 + m), args2)))) end copreds in let injections2 = List.map begin fun (p, cop) -> let typeargs0 = get_inductive_typeargs evd (get_inductive cop.cop_name) in let typeargs = fix_injg_typeargs evd (2 * m + p) (List.map snd copreds) cop typeargs0 in let k = List.length typeargs in let args1_l = List.rev (List.map mkRel (range 1 (k + 1))) in let args2_l = List.rev (List.map mkRel (range 2 (k + 2))) in let args2 = Array.of_list (fix_ex_arg_inj_args evd p cop m k typeargs0 args2_l) in (get_red_name cop cop.cop_name ^ "__injg", close mkProd typeargs (mkProd (Context.make_annot Name.Anonymous Sorts.Relevant, make_green_cop (m + m + k + p) p cop args1_l, mkApp (mkRel (k + 1 + m + m), args2)))) end copreds in let result = close mkProd (fix_ctx red_copred_decls) (close mkProd (fix_ctx injections) (close mkProd (fix_ctx injections2) (mkProd (Context.make_annot Name.Anonymous Sorts.Relevant, make_red (m + m + m) stmt, make_green (m + m + m + 1) stmt)))) in let cohyps = make_coind_hyps evd m stmt in (evd, stmt, cohyps, result)
59b09bc4b8f7f26bcffa5c2f5c6a0fc02fcc09fbf4a0504ce7f7cddcde1d9841
serokell/log-warper
Wlog.hs
-- | -- Module : System.Wlog Copyright : ( c ) , 2016 -- License : GPL-3 (see the file LICENSE) Maintainer : > -- Stability : experimental Portability : POSIX , GHC -- -- Logging functionality. This module is wrapper over -- < hslogger>, -- which allows to keep logger name in monadic context. -- Messages are colored depending on used serverity. module System.Wlog ( module System.Wlog.CanLog , module System.Wlog.Concurrent , module System.Wlog.Exception , module System.Wlog.FileUtils , module System.Wlog.HasLoggerName , module System.Wlog.IOLogger , module System.Wlog.Launcher , module System.Wlog.LoggerConfig , module System.Wlog.LoggerName , module System.Wlog.LoggerNameBox , module System.Wlog.LogHandler.Roller , module System.Wlog.LogHandler.Simple , module System.Wlog.PureLogging , module System.Wlog.Severity , module System.Wlog.Terminal ) where import System.Wlog.CanLog import System.Wlog.Concurrent import System.Wlog.Exception import System.Wlog.FileUtils import System.Wlog.HasLoggerName import System.Wlog.IOLogger import System.Wlog.Launcher import System.Wlog.LoggerConfig import System.Wlog.LoggerName import System.Wlog.LoggerNameBox import System.Wlog.LogHandler.Roller import System.Wlog.LogHandler.Simple import System.Wlog.PureLogging import System.Wlog.Severity import System.Wlog.Terminal
null
https://raw.githubusercontent.com/serokell/log-warper/a6dd74a1085e8c6d94a4aefc2a036efe30f6cde5/src/System/Wlog.hs
haskell
| Module : System.Wlog License : GPL-3 (see the file LICENSE) Stability : experimental Logging functionality. This module is wrapper over < hslogger>, which allows to keep logger name in monadic context. Messages are colored depending on used serverity.
Copyright : ( c ) , 2016 Maintainer : > Portability : POSIX , GHC module System.Wlog ( module System.Wlog.CanLog , module System.Wlog.Concurrent , module System.Wlog.Exception , module System.Wlog.FileUtils , module System.Wlog.HasLoggerName , module System.Wlog.IOLogger , module System.Wlog.Launcher , module System.Wlog.LoggerConfig , module System.Wlog.LoggerName , module System.Wlog.LoggerNameBox , module System.Wlog.LogHandler.Roller , module System.Wlog.LogHandler.Simple , module System.Wlog.PureLogging , module System.Wlog.Severity , module System.Wlog.Terminal ) where import System.Wlog.CanLog import System.Wlog.Concurrent import System.Wlog.Exception import System.Wlog.FileUtils import System.Wlog.HasLoggerName import System.Wlog.IOLogger import System.Wlog.Launcher import System.Wlog.LoggerConfig import System.Wlog.LoggerName import System.Wlog.LoggerNameBox import System.Wlog.LogHandler.Roller import System.Wlog.LogHandler.Simple import System.Wlog.PureLogging import System.Wlog.Severity import System.Wlog.Terminal
142047ab1d4cd33b886adeea0462370125637339cc70214f7516ccad4e73d10a
ocaml/obi
gitlab.ml
Copyright ( c ) 2018 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) module L = Dockerfile_linux module D = Dockerfile_distro module C = Dockerfile_cmd module G = Dockerfile_gen module O = Dockerfile_opam module OV = Ocaml_version open Rresult open R.Infix type copts = {staging_hub_id: string; prod_hub_id: string; results_dir: Fpath.t} let copts staging_hub_id prod_hub_id results_dir = {staging_hub_id; prod_hub_id; results_dir} let arches = OV.arches type build_t = {ov: Ocaml_version.t; distro: D.t} let docs {prod_hub_id; _} = let distros ds = List.map (fun distro -> let name = D.human_readable_string_of_distro distro in let tag = D.tag_of_distro distro in let arches = String.concat " " (List.map OV.string_of_arch (D.distro_arches OV.Releases.latest distro)) in Fmt.strf "| %s | `%s` | %s | `docker run %s:%s`" name tag arches prod_hub_id tag ) ds |> String.concat "\n" in let latest_distros = distros D.latest_distros in let active_distros = distros (D.active_distros `X86_64) in let dev_versions_of_ocaml = String.concat " " (List.map OV.to_string OV.Releases.dev) in let intro = Fmt.strf {|# OCaml Container Infrastructure This repository contains a set of [Docker]() container definitions for various combination of [OCaml]() and the [opam]() package manager. The containers come preinstalled with an opam2 environment, and are particularly suitable for use with continuous integration systems such as [Travis CI](-ci.org). All the containers are hosted on the [Docker Hub ocaml/opam2]() repository. Using it is as simple as: ``` docker pull %s docker run -it %s bash ``` This will get you an interactive development environment (including on [Docker for Mac](-mac)). You can grab a specific OS distribution and test out external dependencies as well: ``` docker run %s:ubuntu opam depext -i cohttp-lwt-unix tls ``` There are a number of different variants available that are regularly rebuilt on the ocaml.org infrastructure and pushed to the [Docker Hub](). Each of the containers contains the Dockerfile used to build it in `/Dockerfile` within the container image. Using The Defaults ================== The `%s` Docker remote has a default `latest` tag that provides the %s Linux distribution with the latest release of the OCaml compiler (%s). The [opam-depext](-depext) plugin can be used to install external system libraries in a distro-portable way. The default user is `opam` in the `/home/opam` directory, with a copy of the [opam-repository](-repository) checked out in `/home/opam/opam-repository`. You can supply your own source code by volume mounting it anywhere in the container, but bear in mind that it should be owned by the `opam` user (uid `1000` in all distributions). Selecting a Specific Compiler ============================= The default container comes with the latest compiler activated, but also a number of other switches for older revisions of OCaml. You can switch to these to test compatibility in CI by iterating through older revisions. For example: ``` $ docker run %s opam switch switch compiler description 4.02 ocaml-base-compiler.4.02.3 4.02 4.03 ocaml-base-compiler.4.03.0 4.03 4.04 ocaml-base-compiler.4.04.2 4.04 4.05 ocaml-base-compiler.4.05.0 4.05 -> 4.06 ocaml-base-compiler.4.06.1 4.06 ``` Note that the name of the switch drops the minor patch release (e.g. `4.06` _vs_ `4.06.1`), since you should always be using the latest patch revision of the compiler. Accessing Compiler Variants =========================== Modern versions of OCaml also feature a number of variants, such as the experimental flambda inliner or [AFL fuzzing](/) support. These are also conveniently available using the `<VERSION>` tag. For example: ``` $ docker run %s:4.06 opam switch switch compiler description -> 4.06 ocaml-base-compiler.4.06.1 4.06 4.06+afl ocaml-variants.4.06.1+afl 4.06+afl 4.06+default-unsafe-string ocaml-variants.4.06.1+default-unsafe-string 4.06+default-unsafe-string 4.06+flambda ocaml-variants.4.06.1+flambda 4.06+flambda 4.06+force-safe-string ocaml-variants.4.06.1+force-safe-string 4.06+force-safe-string ``` In this case, the `4.06` container has the latest patch release (4.06.1) activated by default, but the other variant compilers are available easily via `opam switch` without having to compile them yourself. Using this more specific tag also helps you pin the version of OCaml that your CI system will be testing with, as the default `latest` tag will be regularly upgraded to keep up with upstream OCaml releases. Selecting Linux Distributions ============================= There are also tags available to select other Linux distributions, which is useful to validate and test the behaviour of your package in CI. Distribution | Tag | Architectures | Command ------------ | --- | ------------- | ------- %s The tags above are for the latest version of the distribution, and are upgraded to the latest upstream stable releases. You can also select a specific version number in the tag name to obtain a particular OS release. However, these will eventually time out once they are out of their support window, so try to use the version-free aliases described earlier unless you really know that you want a specific release. When a specific release does time out, the container will be replaced by one that always displays an error message requesting you to upgrade your CI script. Distribution | Tag | Architectures | Command ------------ | --- | ------------- | ------- %s Multi-architecture Containers ============================= The observant reader will notice that the distributions listed above have more than one architecture. We are building an increasing number of packages on non-x86 containers, starting with ARM64 and soon to include PPC64. Using the multiarch images is simple, as the correct one will be selected depending on your host architecture. The images are built using [docker manifest](/). Development Versions of the Compiler ==================================== You can also access development versions of the OCaml compiler (currently %s) that have not yet been released. These are rebuilt around once a day, so you may lag a few commits behind the main master branch. You can reference it via the version `v4.08` tag as with other compilers, but please do bear in mind that this is a development version and so subject to more breakage than a stable release. ``` $ docker run -it ocaml/opam2:v4.08 switch switch compiler description -> 4.08 ocaml-variants.4.08.0+trunk 4.08 4.08+trunk+afl ocaml-variants.4.08.0+trunk+afl 4.08+trunk+afl 4.08+trunk+flambda ocaml-variants.4.08.0+trunk+flambda 4.08+trunk+flambda $ docker run -it ocaml/opam2:v4.08 ocaml --version The OCaml toplevel, version 4.08.0+dev7-2018-11-10 ``` Just the Binaries Please ======================== All of the OCaml containers here are built over a smaller container that just installs the `opam` binary first, without having an OCaml compiler installed. Sometimes for advanced uses, you may want to initialise your own opam environment. In this case, you can access the base container directly via the `<DISTRO>-opam` tag (e.g. `debian-9-opam`). Bear in mind that this base image will be deleted in the future when the distribution goes out of support, so please only use these low-level opam containers if one of the options listed above isn't sufficient for your usecase. There are a large number of distribution and OCaml version combinations that are regularly built that are not mentioned here. For the advanced user who needs a specific combination, the full current list can be found on the [Docker Hub](). However, please try to use the shorter aliases rather than these explicit versions if you can, since then your builds will not error as the upstream versions advance. Package Sandboxing ================== The Docker containers install opam2's [Bubblewrap]() tool that is used for sandboxing builds. However, due to the way that Linux sandboxing works, this may not work with all Docker installations since unprivileged containers cannot create new Linux namespaces on some installations. Thus, sandboxing is disabled by default in the containers that have opam initialised. If you can run containers with `docker run --privileged`, then you can enable opam sandboxing within the container by running `opam-sandbox-enable` within the container. This will ensure that every package is restricted to only writing within `~/.opam` and is the recommended way of doing testing. Questions and Feedback ====================== We are constantly improving and maintaining this infrastructure, so please get in touch with Anil Madhavapeddy `<>` if you have any questions or requests for improvement. Note that until opam 2.0 is released, this infrastructure is considered to be in a beta stage and subject to change. This is all possible thanks to generous infrastructure contributions from [Packet.net](), [IBM](), [Azure](-gb/) and [Rackspace](), as well as a dedicated machine cluster funded by [Jane Street](). The Docker Hub also provides a huge amount of storage space for our containers. We use hundreds of build agents running on [GitLab]() in order to regularly generate the large volume of updates that this infrastructure needs, including the multiarch builds. |} prod_hub_id prod_hub_id prod_hub_id prod_hub_id (D.human_readable_string_of_distro D.master_distro) OV.(to_string Releases.latest) prod_hub_id prod_hub_id latest_distros active_distros dev_versions_of_ocaml in intro let assoc_hashtbl l = let h = Hashtbl.create 7 in List.iter (fun (k, v) -> match Hashtbl.find h k with | _, a -> Hashtbl.replace h k (None, v :: a) | exception Not_found -> Hashtbl.add h k (None, [v]) ) l ; h let docker_build_and_push_cmds ~distro ~arch ~tag prefix = let file = Fmt.strf "%s-%s/Dockerfile.%s" prefix arch distro in `A [ `String "docker login -u $DOCKER_HUB_USER -p $DOCKER_HUB_PASSWORD" ; `String (Fmt.strf "echo >> %s" file) ; `String (Fmt.strf "echo ADD %s /Dockerfile >> %s" file file) ; `String (Fmt.strf "docker build --no-cache --force-rm --rm --pull -t %s -f %s ." tag file) ; `String (Fmt.strf "docker push %s" tag) ; `String (Fmt.strf "docker rmi %s" tag) ] let gen_multiarch ~staging_hub_id ~prod_hub_id h suffix name = Hashtbl.fold (fun f (tag, arches) acc -> let tags = List.map (fun arch -> Fmt.strf "%s:%s%s-linux-%s" staging_hub_id f suffix (OV.string_of_arch arch) ) arches in let l = String.concat " " tags in let pulls = List.map (fun t -> `String (Fmt.strf "docker pull %s" t)) tags in let tag = match tag with None -> Fmt.strf "%s%s" f suffix | Some t -> t in let annotates = List.map2 (fun atag arch -> let flags = match arch with | `Aarch32 -> "--arch arm --variant v7" | `I386 -> "--arch 386" | `Aarch64 -> "--arch arm64 --variant v8" | `X86_64 -> "--arch amd64" | `Ppc64le -> "--arch ppc64le" in `String (Fmt.strf "docker manifest annotate %s:%s %s %s" prod_hub_id tag atag flags) ) tags arches in let script = `A ( [`String "docker login -u $DOCKER_HUB_USER -p $DOCKER_HUB_PASSWORD"] @ pulls @ [ `String (Fmt.strf "docker manifest push -p %s:%s || true" prod_hub_id tag) ; `String (Fmt.strf "docker manifest create %s:%s %s" prod_hub_id tag l) ] @ annotates @ [ `String (Fmt.strf "docker manifest inspect %s:%s" prod_hub_id tag) ; `String (Fmt.strf "docker manifest push -p %s:%s" prod_hub_id tag) ] ) in let cmds : Yaml.value = `O [ ("stage", `String (Fmt.strf "%s-multiarch" name)) ; ("retry", `String "2") ; ("except", `A [`String "pushes"]) ; ("tags", `A [`String "shell"; `String "amd64"]) ; ("script", script) ] in let jobname = match tag.[0] with '0' .. '9' -> "v" ^ tag | _ -> tag in (jobname, cmds) :: acc ) h [] let gen_ocaml ({staging_hub_id; prod_hub_id; results_dir; _} as opts) () = ignore (Bos.OS.Dir.create ~path:true results_dir) ; let ocaml_dockerfiles = List.map (fun arch -> let prefix = Fmt.strf "ocaml-%s" (OV.string_of_arch arch) in let results_dir = Fpath.(results_dir / prefix) in ignore (Bos.OS.Dir.create ~path:true results_dir) ; let all_compilers = D.active_distros arch |> List.map (O.all_ocaml_compilers prod_hub_id arch) in let each_compiler = D.active_tier1_distros arch |> List.map (O.separate_ocaml_compilers prod_hub_id arch) |> List.flatten in let dfiles = all_compilers @ each_compiler in ignore (G.generate_dockerfiles ~crunch:true results_dir dfiles) ; List.map (fun (f, _) -> (f, arch)) dfiles ) arches |> List.flatten in let ocaml_arch_builds = List.map (fun (f, arch) -> let arch = OV.string_of_arch arch in let label = Fmt.strf "%s-linux-%s" f arch in let tag = Fmt.strf "%s:%s" staging_hub_id label in let cmds = `O [ ("stage", `String "ocaml-builds") ; ("retry", `String "2") ; ("except", `A [`String "pushes"]) ; ("tags", `A [`String "shell"; `String (match arch with "i386" -> "amd64" | "arm32v7" -> "arm64" | _ -> arch) ]) ; ( "script" , docker_build_and_push_cmds ~distro:f ~arch ~tag "ocaml" ) ] in (label, cmds) ) ocaml_dockerfiles in let ocaml_dockerfiles_by_arch = assoc_hashtbl ocaml_dockerfiles in let ocaml_multiarch_dockerfiles = gen_multiarch ~staging_hub_id ~prod_hub_id ocaml_dockerfiles_by_arch "" "ocaml" in (* Generate aliases for OCaml releases and distros *) let distro_alias_multiarch = let distro_aliases = Hashtbl.create 7 in List.iter (fun ldistro -> let distro = D.resolve_alias ldistro in let f = D.tag_of_distro distro in let tag = D.tag_of_distro ldistro in let arches = try snd (Hashtbl.find ocaml_dockerfiles_by_arch f) with Not_found -> [] in Hashtbl.add distro_aliases f (Some tag, arches) ; Add an alias for " latest " for Debian Stable too if ldistro = `Debian `Stable then Hashtbl.add distro_aliases f (Some "latest", arches) ) D.latest_distros ; gen_multiarch ~staging_hub_id ~prod_hub_id distro_aliases "" "alias" in let ocaml_alias_multiarch = let ocaml_aliases = Hashtbl.create 7 in List.iter (fun ov -> let ov = OV.with_patch ov None in let distro = D.resolve_alias (`Debian `Stable) in let f = Fmt.strf "%s-ocaml-%s" (D.tag_of_distro distro) (OV.to_string ov) in let arches = try snd (Hashtbl.find ocaml_dockerfiles_by_arch f) with Not_found -> [] in let tag = OV.to_string ov in Hashtbl.add ocaml_aliases f (Some tag, arches) ) OV.Releases.recent_with_dev ; gen_multiarch ~staging_hub_id ~prod_hub_id ocaml_aliases "" "alias" in let yml = `O ( ocaml_arch_builds @ ocaml_multiarch_dockerfiles @ distro_alias_multiarch @ ocaml_alias_multiarch ) |> Yaml.to_string_exn ~len:256000 in Bos.OS.File.write Fpath.(results_dir / "ocaml-builds.yml") yml >>= fun () -> Bos.OS.File.write Fpath.(results_dir / "README.md") (docs opts) let gen_opam ({staging_hub_id; prod_hub_id; results_dir; _} as opts) () = ignore (Bos.OS.Dir.create ~path:true results_dir) ; let opam_dockerfiles = List.map (fun arch -> let prefix = Fmt.strf "opam-%s" (OV.string_of_arch arch) in let results_dir = Fpath.(results_dir / prefix) in ignore (Bos.OS.Dir.create ~path:true results_dir) ; let distros = List.filter (D.distro_supported_on arch OV.Releases.latest) (D.active_distros arch) in let open Dockerfile in let dfiles = List.map (fun distro -> O.gen_opam2_distro ~arch distro) distros in ignore (G.generate_dockerfiles ~crunch:true results_dir dfiles) ; List.map (fun (f, _) -> (f, arch)) dfiles ) arches |> List.flatten in let opam_arch_builds = List.map (fun (f, arch) -> let arch = OV.string_of_arch arch in let tag = Fmt.strf "%s:%s-opam-linux-%s" staging_hub_id f arch in let label = Fmt.strf "%s-opam-linux-%s" f arch in let cmds = `O [ ("stage", `String "opam-builds") ; ("retry", `String "2") ; ("except", `A [`String "pushes"]) ; ("tags", `A [`String "shell"; `String (match arch with "i386" -> "amd64" | "arm32v7" -> "arm64" | _ -> arch)]) ; ("script", docker_build_and_push_cmds ~distro:f ~arch ~tag "opam") ] in (label, cmds) ) opam_dockerfiles in let opam_dockerfiles_by_arch = assoc_hashtbl opam_dockerfiles in let opam_multiarch_dockerfiles = gen_multiarch ~staging_hub_id ~prod_hub_id opam_dockerfiles_by_arch "-opam" "opam" in let yml = `O (opam_arch_builds @ opam_multiarch_dockerfiles) |> Yaml.to_string_exn ~len:256000 in Bos.OS.File.write Fpath.(results_dir / "opam-builds.yml") yml >>= fun () -> Bos.OS.File.write Fpath.(results_dir / "README.md") (docs opts) let pkg_version pkg = let open Astring in match String.cut ~sep:"." pkg with | None -> Error (`Msg "invalid pkg") | Some (pkg, ver) -> Ok (pkg, ver) open Cmdliner let setup_logs = C.setup_logs () let fpath = Arg.conv ~docv:"PATH" (Fpath.of_string, Fpath.pp) let arch = let doc = "CPU architecture to perform build on" in let term = Arg.enum [("i386", `I386); ("amd64", `X86_64); ("arm64", `Aarch64); ("ppc64le", `Ppc64le)] in Arg.(value & opt term `X86_64 & info ["arch"] ~docv:"ARCH" ~doc) let opam_repo_rev = let doc = "opam repo git rev" in let open Arg in required & opt (some string) None & info ["opam-repo-rev"] ~docv:"OPAM_REPO_REV" ~doc let copts_t = let docs = Manpage.s_common_options in let staging_hub_id = let doc = "Docker Hub user/repo to push to for staging builds" in let open Arg in value & opt string "ocaml/opam2-staging" & info ["staging-hub-id"] ~docv:"STAGING_HUB_ID" ~doc ~docs in let prod_hub_id = let doc = "Docker Hub user/repo to push to for production multiarch builds" in let open Arg in value & opt string "ocaml/opam2" & info ["prod-hub-id"] ~docv:"PROD_HUB_ID" ~doc ~docs in let results_dir = let doc = "Directory in which to store bulk build results" in let open Arg in value & opt fpath (Fpath.v "_results") & info ["o"; "results-dir"] ~docv:"RESULTS_DIR" ~doc ~docs in Term.(const copts $ staging_hub_id $ prod_hub_id $ results_dir) let buildv ov distro = Ocaml_version.of_string_exn ov |> fun ov -> let distro = match D.distro_of_tag distro with | None -> failwith "unknown distro" | Some distro -> distro in {ov; distro} let build_t = let ocaml_version = let doc = "ocaml version to build" in let env = Arg.env_var "OCAML_VERSION" ~doc in let open Arg in value & opt string "4.06.1" & info ["ocaml-version"] ~docv:"OCAML_VERSION" ~env ~doc in let distro = let doc = "distro to build" in let env = Arg.env_var "DISTRO" ~doc in let open Arg in value & opt string "debian-9" & info ["distro"] ~env ~docv:"DISTRO" ~doc in Term.(const buildv $ ocaml_version $ distro) let opam_cmd = let doc = "generate, build and push base opam container images" in let exits = Term.default_exits in let man = [ `S Manpage.s_description ; `P "Generate and build base $(b,opam) container images." ] in ( Term.(term_result (const gen_opam $ copts_t $ setup_logs)) , Term.info "opam" ~doc ~sdocs:Manpage.s_common_options ~exits ~man ) let ocaml_cmd = let doc = "generate, build and push base ocaml container images" in let exits = Term.default_exits in let man = [ `S Manpage.s_description ; `P "Generate and build base $(b,ocaml) container images." ] in ( Term.(term_result (const gen_ocaml $ copts_t $ setup_logs)) , Term.info "ocaml" ~doc ~sdocs:Manpage.s_common_options ~exits ~man ) let default_cmd = let doc = "build and push opam and OCaml multiarch container images" in let sdocs = Manpage.s_common_options in ( Term.(ret (const (fun _ -> `Help (`Pager, None)) $ pure ())) , Term.info "obi-git" ~version:"%%VERSION%%" ~doc ~sdocs ) let cmds = [opam_cmd; ocaml_cmd] let () = Term.(exit @@ eval_choice default_cmd cmds)
null
https://raw.githubusercontent.com/ocaml/obi/68a93c27a2076dfa0e1634a4da16826ddc47455d/src/obi-gitlab/gitlab.ml
ocaml
Generate aliases for OCaml releases and distros
Copyright ( c ) 2018 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *) module L = Dockerfile_linux module D = Dockerfile_distro module C = Dockerfile_cmd module G = Dockerfile_gen module O = Dockerfile_opam module OV = Ocaml_version open Rresult open R.Infix type copts = {staging_hub_id: string; prod_hub_id: string; results_dir: Fpath.t} let copts staging_hub_id prod_hub_id results_dir = {staging_hub_id; prod_hub_id; results_dir} let arches = OV.arches type build_t = {ov: Ocaml_version.t; distro: D.t} let docs {prod_hub_id; _} = let distros ds = List.map (fun distro -> let name = D.human_readable_string_of_distro distro in let tag = D.tag_of_distro distro in let arches = String.concat " " (List.map OV.string_of_arch (D.distro_arches OV.Releases.latest distro)) in Fmt.strf "| %s | `%s` | %s | `docker run %s:%s`" name tag arches prod_hub_id tag ) ds |> String.concat "\n" in let latest_distros = distros D.latest_distros in let active_distros = distros (D.active_distros `X86_64) in let dev_versions_of_ocaml = String.concat " " (List.map OV.to_string OV.Releases.dev) in let intro = Fmt.strf {|# OCaml Container Infrastructure This repository contains a set of [Docker]() container definitions for various combination of [OCaml]() and the [opam]() package manager. The containers come preinstalled with an opam2 environment, and are particularly suitable for use with continuous integration systems such as [Travis CI](-ci.org). All the containers are hosted on the [Docker Hub ocaml/opam2]() repository. Using it is as simple as: ``` docker pull %s docker run -it %s bash ``` This will get you an interactive development environment (including on [Docker for Mac](-mac)). You can grab a specific OS distribution and test out external dependencies as well: ``` docker run %s:ubuntu opam depext -i cohttp-lwt-unix tls ``` There are a number of different variants available that are regularly rebuilt on the ocaml.org infrastructure and pushed to the [Docker Hub](). Each of the containers contains the Dockerfile used to build it in `/Dockerfile` within the container image. Using The Defaults ================== The `%s` Docker remote has a default `latest` tag that provides the %s Linux distribution with the latest release of the OCaml compiler (%s). The [opam-depext](-depext) plugin can be used to install external system libraries in a distro-portable way. The default user is `opam` in the `/home/opam` directory, with a copy of the [opam-repository](-repository) checked out in `/home/opam/opam-repository`. You can supply your own source code by volume mounting it anywhere in the container, but bear in mind that it should be owned by the `opam` user (uid `1000` in all distributions). Selecting a Specific Compiler ============================= The default container comes with the latest compiler activated, but also a number of other switches for older revisions of OCaml. You can switch to these to test compatibility in CI by iterating through older revisions. For example: ``` $ docker run %s opam switch switch compiler description 4.02 ocaml-base-compiler.4.02.3 4.02 4.03 ocaml-base-compiler.4.03.0 4.03 4.04 ocaml-base-compiler.4.04.2 4.04 4.05 ocaml-base-compiler.4.05.0 4.05 -> 4.06 ocaml-base-compiler.4.06.1 4.06 ``` Note that the name of the switch drops the minor patch release (e.g. `4.06` _vs_ `4.06.1`), since you should always be using the latest patch revision of the compiler. Accessing Compiler Variants =========================== Modern versions of OCaml also feature a number of variants, such as the experimental flambda inliner or [AFL fuzzing](/) support. These are also conveniently available using the `<VERSION>` tag. For example: ``` $ docker run %s:4.06 opam switch switch compiler description -> 4.06 ocaml-base-compiler.4.06.1 4.06 4.06+afl ocaml-variants.4.06.1+afl 4.06+afl 4.06+default-unsafe-string ocaml-variants.4.06.1+default-unsafe-string 4.06+default-unsafe-string 4.06+flambda ocaml-variants.4.06.1+flambda 4.06+flambda 4.06+force-safe-string ocaml-variants.4.06.1+force-safe-string 4.06+force-safe-string ``` In this case, the `4.06` container has the latest patch release (4.06.1) activated by default, but the other variant compilers are available easily via `opam switch` without having to compile them yourself. Using this more specific tag also helps you pin the version of OCaml that your CI system will be testing with, as the default `latest` tag will be regularly upgraded to keep up with upstream OCaml releases. Selecting Linux Distributions ============================= There are also tags available to select other Linux distributions, which is useful to validate and test the behaviour of your package in CI. Distribution | Tag | Architectures | Command ------------ | --- | ------------- | ------- %s The tags above are for the latest version of the distribution, and are upgraded to the latest upstream stable releases. You can also select a specific version number in the tag name to obtain a particular OS release. However, these will eventually time out once they are out of their support window, so try to use the version-free aliases described earlier unless you really know that you want a specific release. When a specific release does time out, the container will be replaced by one that always displays an error message requesting you to upgrade your CI script. Distribution | Tag | Architectures | Command ------------ | --- | ------------- | ------- %s Multi-architecture Containers ============================= The observant reader will notice that the distributions listed above have more than one architecture. We are building an increasing number of packages on non-x86 containers, starting with ARM64 and soon to include PPC64. Using the multiarch images is simple, as the correct one will be selected depending on your host architecture. The images are built using [docker manifest](/). Development Versions of the Compiler ==================================== You can also access development versions of the OCaml compiler (currently %s) that have not yet been released. These are rebuilt around once a day, so you may lag a few commits behind the main master branch. You can reference it via the version `v4.08` tag as with other compilers, but please do bear in mind that this is a development version and so subject to more breakage than a stable release. ``` $ docker run -it ocaml/opam2:v4.08 switch switch compiler description -> 4.08 ocaml-variants.4.08.0+trunk 4.08 4.08+trunk+afl ocaml-variants.4.08.0+trunk+afl 4.08+trunk+afl 4.08+trunk+flambda ocaml-variants.4.08.0+trunk+flambda 4.08+trunk+flambda $ docker run -it ocaml/opam2:v4.08 ocaml --version The OCaml toplevel, version 4.08.0+dev7-2018-11-10 ``` Just the Binaries Please ======================== All of the OCaml containers here are built over a smaller container that just installs the `opam` binary first, without having an OCaml compiler installed. Sometimes for advanced uses, you may want to initialise your own opam environment. In this case, you can access the base container directly via the `<DISTRO>-opam` tag (e.g. `debian-9-opam`). Bear in mind that this base image will be deleted in the future when the distribution goes out of support, so please only use these low-level opam containers if one of the options listed above isn't sufficient for your usecase. There are a large number of distribution and OCaml version combinations that are regularly built that are not mentioned here. For the advanced user who needs a specific combination, the full current list can be found on the [Docker Hub](). However, please try to use the shorter aliases rather than these explicit versions if you can, since then your builds will not error as the upstream versions advance. Package Sandboxing ================== The Docker containers install opam2's [Bubblewrap]() tool that is used for sandboxing builds. However, due to the way that Linux sandboxing works, this may not work with all Docker installations since unprivileged containers cannot create new Linux namespaces on some installations. Thus, sandboxing is disabled by default in the containers that have opam initialised. If you can run containers with `docker run --privileged`, then you can enable opam sandboxing within the container by running `opam-sandbox-enable` within the container. This will ensure that every package is restricted to only writing within `~/.opam` and is the recommended way of doing testing. Questions and Feedback ====================== We are constantly improving and maintaining this infrastructure, so please get in touch with Anil Madhavapeddy `<>` if you have any questions or requests for improvement. Note that until opam 2.0 is released, this infrastructure is considered to be in a beta stage and subject to change. This is all possible thanks to generous infrastructure contributions from [Packet.net](), [IBM](), [Azure](-gb/) and [Rackspace](), as well as a dedicated machine cluster funded by [Jane Street](). The Docker Hub also provides a huge amount of storage space for our containers. We use hundreds of build agents running on [GitLab]() in order to regularly generate the large volume of updates that this infrastructure needs, including the multiarch builds. |} prod_hub_id prod_hub_id prod_hub_id prod_hub_id (D.human_readable_string_of_distro D.master_distro) OV.(to_string Releases.latest) prod_hub_id prod_hub_id latest_distros active_distros dev_versions_of_ocaml in intro let assoc_hashtbl l = let h = Hashtbl.create 7 in List.iter (fun (k, v) -> match Hashtbl.find h k with | _, a -> Hashtbl.replace h k (None, v :: a) | exception Not_found -> Hashtbl.add h k (None, [v]) ) l ; h let docker_build_and_push_cmds ~distro ~arch ~tag prefix = let file = Fmt.strf "%s-%s/Dockerfile.%s" prefix arch distro in `A [ `String "docker login -u $DOCKER_HUB_USER -p $DOCKER_HUB_PASSWORD" ; `String (Fmt.strf "echo >> %s" file) ; `String (Fmt.strf "echo ADD %s /Dockerfile >> %s" file file) ; `String (Fmt.strf "docker build --no-cache --force-rm --rm --pull -t %s -f %s ." tag file) ; `String (Fmt.strf "docker push %s" tag) ; `String (Fmt.strf "docker rmi %s" tag) ] let gen_multiarch ~staging_hub_id ~prod_hub_id h suffix name = Hashtbl.fold (fun f (tag, arches) acc -> let tags = List.map (fun arch -> Fmt.strf "%s:%s%s-linux-%s" staging_hub_id f suffix (OV.string_of_arch arch) ) arches in let l = String.concat " " tags in let pulls = List.map (fun t -> `String (Fmt.strf "docker pull %s" t)) tags in let tag = match tag with None -> Fmt.strf "%s%s" f suffix | Some t -> t in let annotates = List.map2 (fun atag arch -> let flags = match arch with | `Aarch32 -> "--arch arm --variant v7" | `I386 -> "--arch 386" | `Aarch64 -> "--arch arm64 --variant v8" | `X86_64 -> "--arch amd64" | `Ppc64le -> "--arch ppc64le" in `String (Fmt.strf "docker manifest annotate %s:%s %s %s" prod_hub_id tag atag flags) ) tags arches in let script = `A ( [`String "docker login -u $DOCKER_HUB_USER -p $DOCKER_HUB_PASSWORD"] @ pulls @ [ `String (Fmt.strf "docker manifest push -p %s:%s || true" prod_hub_id tag) ; `String (Fmt.strf "docker manifest create %s:%s %s" prod_hub_id tag l) ] @ annotates @ [ `String (Fmt.strf "docker manifest inspect %s:%s" prod_hub_id tag) ; `String (Fmt.strf "docker manifest push -p %s:%s" prod_hub_id tag) ] ) in let cmds : Yaml.value = `O [ ("stage", `String (Fmt.strf "%s-multiarch" name)) ; ("retry", `String "2") ; ("except", `A [`String "pushes"]) ; ("tags", `A [`String "shell"; `String "amd64"]) ; ("script", script) ] in let jobname = match tag.[0] with '0' .. '9' -> "v" ^ tag | _ -> tag in (jobname, cmds) :: acc ) h [] let gen_ocaml ({staging_hub_id; prod_hub_id; results_dir; _} as opts) () = ignore (Bos.OS.Dir.create ~path:true results_dir) ; let ocaml_dockerfiles = List.map (fun arch -> let prefix = Fmt.strf "ocaml-%s" (OV.string_of_arch arch) in let results_dir = Fpath.(results_dir / prefix) in ignore (Bos.OS.Dir.create ~path:true results_dir) ; let all_compilers = D.active_distros arch |> List.map (O.all_ocaml_compilers prod_hub_id arch) in let each_compiler = D.active_tier1_distros arch |> List.map (O.separate_ocaml_compilers prod_hub_id arch) |> List.flatten in let dfiles = all_compilers @ each_compiler in ignore (G.generate_dockerfiles ~crunch:true results_dir dfiles) ; List.map (fun (f, _) -> (f, arch)) dfiles ) arches |> List.flatten in let ocaml_arch_builds = List.map (fun (f, arch) -> let arch = OV.string_of_arch arch in let label = Fmt.strf "%s-linux-%s" f arch in let tag = Fmt.strf "%s:%s" staging_hub_id label in let cmds = `O [ ("stage", `String "ocaml-builds") ; ("retry", `String "2") ; ("except", `A [`String "pushes"]) ; ("tags", `A [`String "shell"; `String (match arch with "i386" -> "amd64" | "arm32v7" -> "arm64" | _ -> arch) ]) ; ( "script" , docker_build_and_push_cmds ~distro:f ~arch ~tag "ocaml" ) ] in (label, cmds) ) ocaml_dockerfiles in let ocaml_dockerfiles_by_arch = assoc_hashtbl ocaml_dockerfiles in let ocaml_multiarch_dockerfiles = gen_multiarch ~staging_hub_id ~prod_hub_id ocaml_dockerfiles_by_arch "" "ocaml" in let distro_alias_multiarch = let distro_aliases = Hashtbl.create 7 in List.iter (fun ldistro -> let distro = D.resolve_alias ldistro in let f = D.tag_of_distro distro in let tag = D.tag_of_distro ldistro in let arches = try snd (Hashtbl.find ocaml_dockerfiles_by_arch f) with Not_found -> [] in Hashtbl.add distro_aliases f (Some tag, arches) ; Add an alias for " latest " for Debian Stable too if ldistro = `Debian `Stable then Hashtbl.add distro_aliases f (Some "latest", arches) ) D.latest_distros ; gen_multiarch ~staging_hub_id ~prod_hub_id distro_aliases "" "alias" in let ocaml_alias_multiarch = let ocaml_aliases = Hashtbl.create 7 in List.iter (fun ov -> let ov = OV.with_patch ov None in let distro = D.resolve_alias (`Debian `Stable) in let f = Fmt.strf "%s-ocaml-%s" (D.tag_of_distro distro) (OV.to_string ov) in let arches = try snd (Hashtbl.find ocaml_dockerfiles_by_arch f) with Not_found -> [] in let tag = OV.to_string ov in Hashtbl.add ocaml_aliases f (Some tag, arches) ) OV.Releases.recent_with_dev ; gen_multiarch ~staging_hub_id ~prod_hub_id ocaml_aliases "" "alias" in let yml = `O ( ocaml_arch_builds @ ocaml_multiarch_dockerfiles @ distro_alias_multiarch @ ocaml_alias_multiarch ) |> Yaml.to_string_exn ~len:256000 in Bos.OS.File.write Fpath.(results_dir / "ocaml-builds.yml") yml >>= fun () -> Bos.OS.File.write Fpath.(results_dir / "README.md") (docs opts) let gen_opam ({staging_hub_id; prod_hub_id; results_dir; _} as opts) () = ignore (Bos.OS.Dir.create ~path:true results_dir) ; let opam_dockerfiles = List.map (fun arch -> let prefix = Fmt.strf "opam-%s" (OV.string_of_arch arch) in let results_dir = Fpath.(results_dir / prefix) in ignore (Bos.OS.Dir.create ~path:true results_dir) ; let distros = List.filter (D.distro_supported_on arch OV.Releases.latest) (D.active_distros arch) in let open Dockerfile in let dfiles = List.map (fun distro -> O.gen_opam2_distro ~arch distro) distros in ignore (G.generate_dockerfiles ~crunch:true results_dir dfiles) ; List.map (fun (f, _) -> (f, arch)) dfiles ) arches |> List.flatten in let opam_arch_builds = List.map (fun (f, arch) -> let arch = OV.string_of_arch arch in let tag = Fmt.strf "%s:%s-opam-linux-%s" staging_hub_id f arch in let label = Fmt.strf "%s-opam-linux-%s" f arch in let cmds = `O [ ("stage", `String "opam-builds") ; ("retry", `String "2") ; ("except", `A [`String "pushes"]) ; ("tags", `A [`String "shell"; `String (match arch with "i386" -> "amd64" | "arm32v7" -> "arm64" | _ -> arch)]) ; ("script", docker_build_and_push_cmds ~distro:f ~arch ~tag "opam") ] in (label, cmds) ) opam_dockerfiles in let opam_dockerfiles_by_arch = assoc_hashtbl opam_dockerfiles in let opam_multiarch_dockerfiles = gen_multiarch ~staging_hub_id ~prod_hub_id opam_dockerfiles_by_arch "-opam" "opam" in let yml = `O (opam_arch_builds @ opam_multiarch_dockerfiles) |> Yaml.to_string_exn ~len:256000 in Bos.OS.File.write Fpath.(results_dir / "opam-builds.yml") yml >>= fun () -> Bos.OS.File.write Fpath.(results_dir / "README.md") (docs opts) let pkg_version pkg = let open Astring in match String.cut ~sep:"." pkg with | None -> Error (`Msg "invalid pkg") | Some (pkg, ver) -> Ok (pkg, ver) open Cmdliner let setup_logs = C.setup_logs () let fpath = Arg.conv ~docv:"PATH" (Fpath.of_string, Fpath.pp) let arch = let doc = "CPU architecture to perform build on" in let term = Arg.enum [("i386", `I386); ("amd64", `X86_64); ("arm64", `Aarch64); ("ppc64le", `Ppc64le)] in Arg.(value & opt term `X86_64 & info ["arch"] ~docv:"ARCH" ~doc) let opam_repo_rev = let doc = "opam repo git rev" in let open Arg in required & opt (some string) None & info ["opam-repo-rev"] ~docv:"OPAM_REPO_REV" ~doc let copts_t = let docs = Manpage.s_common_options in let staging_hub_id = let doc = "Docker Hub user/repo to push to for staging builds" in let open Arg in value & opt string "ocaml/opam2-staging" & info ["staging-hub-id"] ~docv:"STAGING_HUB_ID" ~doc ~docs in let prod_hub_id = let doc = "Docker Hub user/repo to push to for production multiarch builds" in let open Arg in value & opt string "ocaml/opam2" & info ["prod-hub-id"] ~docv:"PROD_HUB_ID" ~doc ~docs in let results_dir = let doc = "Directory in which to store bulk build results" in let open Arg in value & opt fpath (Fpath.v "_results") & info ["o"; "results-dir"] ~docv:"RESULTS_DIR" ~doc ~docs in Term.(const copts $ staging_hub_id $ prod_hub_id $ results_dir) let buildv ov distro = Ocaml_version.of_string_exn ov |> fun ov -> let distro = match D.distro_of_tag distro with | None -> failwith "unknown distro" | Some distro -> distro in {ov; distro} let build_t = let ocaml_version = let doc = "ocaml version to build" in let env = Arg.env_var "OCAML_VERSION" ~doc in let open Arg in value & opt string "4.06.1" & info ["ocaml-version"] ~docv:"OCAML_VERSION" ~env ~doc in let distro = let doc = "distro to build" in let env = Arg.env_var "DISTRO" ~doc in let open Arg in value & opt string "debian-9" & info ["distro"] ~env ~docv:"DISTRO" ~doc in Term.(const buildv $ ocaml_version $ distro) let opam_cmd = let doc = "generate, build and push base opam container images" in let exits = Term.default_exits in let man = [ `S Manpage.s_description ; `P "Generate and build base $(b,opam) container images." ] in ( Term.(term_result (const gen_opam $ copts_t $ setup_logs)) , Term.info "opam" ~doc ~sdocs:Manpage.s_common_options ~exits ~man ) let ocaml_cmd = let doc = "generate, build and push base ocaml container images" in let exits = Term.default_exits in let man = [ `S Manpage.s_description ; `P "Generate and build base $(b,ocaml) container images." ] in ( Term.(term_result (const gen_ocaml $ copts_t $ setup_logs)) , Term.info "ocaml" ~doc ~sdocs:Manpage.s_common_options ~exits ~man ) let default_cmd = let doc = "build and push opam and OCaml multiarch container images" in let sdocs = Manpage.s_common_options in ( Term.(ret (const (fun _ -> `Help (`Pager, None)) $ pure ())) , Term.info "obi-git" ~version:"%%VERSION%%" ~doc ~sdocs ) let cmds = [opam_cmd; ocaml_cmd] let () = Term.(exit @@ eval_choice default_cmd cmds)
114f2a932731cabd4091a49dbdbf738317f6aaa5f3d021beb34ddc2e14d6e459
kadena-io/digraph
Test.hs
# LANGUAGE CPP # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # -- | -- Module: Data.DiGraph.Test Copyright : Copyright © 2019 - 2020 Kadena LLC . License : MIT Maintainer : < > -- Stability: experimental -- module Data.DiGraph.Test ( -- * Test Properties properties ) where import Data.Bifunctor import Data.Hashable import Numeric.Natural import Test.QuickCheck -- internal modules import Data.DiGraph -- -------------------------------------------------------------------------- -- -- Test Properties prefixProperties :: String -> [(String, Property)] -> [(String, Property)] prefixProperties p = fmap $ first (p <>) properties_undirected :: Eq a => Hashable a => DiGraph a -> [(String, Property)] properties_undirected g = [ ("isDiGraph", property $ isDiGraph g) , ("isIrreflexive", property $ isIrreflexive g) , ("isSymmetric", property $ isSymmetric g) ] properties_directed :: Eq a => Hashable a => DiGraph a -> [(String, Property)] properties_directed = filter ((/=) "isSymmetric" . fst) . properties_undirected properties_emptyGraph :: Natural -> [(String, Property)] properties_emptyGraph n = prefixProperties ("emptyGraph of order " <> show n <> ": ") $ ("order == " <> show n, order g === n) : ("size == 0", size g === 0) : properties_undirected g where g = emptyGraph n properties_singletonGraph :: [(String, Property)] properties_singletonGraph = prefixProperties "singletonGraph: " $ ("order == 1", order g === 1) : ("size == 0", symSize g === 0) : ("outDegree == 0", maxOutDegree g === 0) : ("isRegular", property $ isRegular g) : ("diameter == 0", diameter g === Just 0) : properties_undirected g where g = singleton properties_petersonGraph :: [(String, Property)] properties_petersonGraph = prefixProperties "petersonGraph: " $ ("order == 10", order g === 10) : ("size == 15", symSize g === 15) : ("outDegree == 3", maxOutDegree g === 3) : ("isRegular", property $ isRegular g) : ("diameter == 2", diameter g === Just 2) : properties_undirected g where g = petersonGraph properties_twentyChainGraph :: [(String, Property)] properties_twentyChainGraph = prefixProperties "twentyChainGraph: " $ ("order == 20", order g === 20) : ("size == 30", symSize g === 30) : ("outDegree == 3", maxOutDegree g === 3) : ("isRegular", property $ isRegular g) : ("diameter == 3", diameter g === Just 3) : properties_undirected g where g = twentyChainGraph properties_hoffmanSingletonGraph :: [(String, Property)] properties_hoffmanSingletonGraph = prefixProperties "HoffmanSingletonGraph: " $ ("order == 50", order g === 50) : ("size == 175", symSize g === 175) : ("outDegree == 7", maxOutDegree g === 7) : ("isRegular", property $ isRegular g) : ("diameter == 2", diameter g === Just 2) : properties_undirected g where g = hoffmanSingleton properties_pentagon :: [(String,Property)] properties_pentagon = prefixProperties "Pentagon: " $ ("order == 5",order g === 5) : ("size == 5",symSize g === 5) : ("outDegree == 1",maxOutDegree g === 1) : ("isRegular", property $ isRegular g) : ("diameter == 4", diameter g === Just 4) : properties_directed g where g = pentagon properties_ascendingCube :: [(String,Property)] properties_ascendingCube = prefixProperties "Ascending Cube: " $ ("order == 8",order g === 8) : ("size == 12",symSize g === 12) : ("outDegree == 3",maxOutDegree g === 3) : ("isIrRegular", property $ not $ isRegular g) : ("diameter == Nothing", diameter g === Nothing) : properties_directed g where g = ascendingCube -- | Test Properties. -- properties :: [(String, Property)] properties = (concat :: [[(String, Property)]] -> [(String, Property)]) [ properties_emptyGraph 0 , properties_emptyGraph 2 , properties_singletonGraph , properties_petersonGraph , properties_twentyChainGraph , properties_hoffmanSingletonGraph , properties_pentagon , properties_ascendingCube ]
null
https://raw.githubusercontent.com/kadena-io/digraph/c31c35d0270b8da16815cb7e6f5a09e3fc012bd8/test/Data/DiGraph/Test.hs
haskell
# LANGUAGE OverloadedStrings # | Module: Data.DiGraph.Test Stability: experimental * Test Properties internal modules -------------------------------------------------------------------------- -- Test Properties | Test Properties.
# LANGUAGE CPP # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # Copyright : Copyright © 2019 - 2020 Kadena LLC . License : MIT Maintainer : < > module Data.DiGraph.Test ( properties ) where import Data.Bifunctor import Data.Hashable import Numeric.Natural import Test.QuickCheck import Data.DiGraph prefixProperties :: String -> [(String, Property)] -> [(String, Property)] prefixProperties p = fmap $ first (p <>) properties_undirected :: Eq a => Hashable a => DiGraph a -> [(String, Property)] properties_undirected g = [ ("isDiGraph", property $ isDiGraph g) , ("isIrreflexive", property $ isIrreflexive g) , ("isSymmetric", property $ isSymmetric g) ] properties_directed :: Eq a => Hashable a => DiGraph a -> [(String, Property)] properties_directed = filter ((/=) "isSymmetric" . fst) . properties_undirected properties_emptyGraph :: Natural -> [(String, Property)] properties_emptyGraph n = prefixProperties ("emptyGraph of order " <> show n <> ": ") $ ("order == " <> show n, order g === n) : ("size == 0", size g === 0) : properties_undirected g where g = emptyGraph n properties_singletonGraph :: [(String, Property)] properties_singletonGraph = prefixProperties "singletonGraph: " $ ("order == 1", order g === 1) : ("size == 0", symSize g === 0) : ("outDegree == 0", maxOutDegree g === 0) : ("isRegular", property $ isRegular g) : ("diameter == 0", diameter g === Just 0) : properties_undirected g where g = singleton properties_petersonGraph :: [(String, Property)] properties_petersonGraph = prefixProperties "petersonGraph: " $ ("order == 10", order g === 10) : ("size == 15", symSize g === 15) : ("outDegree == 3", maxOutDegree g === 3) : ("isRegular", property $ isRegular g) : ("diameter == 2", diameter g === Just 2) : properties_undirected g where g = petersonGraph properties_twentyChainGraph :: [(String, Property)] properties_twentyChainGraph = prefixProperties "twentyChainGraph: " $ ("order == 20", order g === 20) : ("size == 30", symSize g === 30) : ("outDegree == 3", maxOutDegree g === 3) : ("isRegular", property $ isRegular g) : ("diameter == 3", diameter g === Just 3) : properties_undirected g where g = twentyChainGraph properties_hoffmanSingletonGraph :: [(String, Property)] properties_hoffmanSingletonGraph = prefixProperties "HoffmanSingletonGraph: " $ ("order == 50", order g === 50) : ("size == 175", symSize g === 175) : ("outDegree == 7", maxOutDegree g === 7) : ("isRegular", property $ isRegular g) : ("diameter == 2", diameter g === Just 2) : properties_undirected g where g = hoffmanSingleton properties_pentagon :: [(String,Property)] properties_pentagon = prefixProperties "Pentagon: " $ ("order == 5",order g === 5) : ("size == 5",symSize g === 5) : ("outDegree == 1",maxOutDegree g === 1) : ("isRegular", property $ isRegular g) : ("diameter == 4", diameter g === Just 4) : properties_directed g where g = pentagon properties_ascendingCube :: [(String,Property)] properties_ascendingCube = prefixProperties "Ascending Cube: " $ ("order == 8",order g === 8) : ("size == 12",symSize g === 12) : ("outDegree == 3",maxOutDegree g === 3) : ("isIrRegular", property $ not $ isRegular g) : ("diameter == Nothing", diameter g === Nothing) : properties_directed g where g = ascendingCube properties :: [(String, Property)] properties = (concat :: [[(String, Property)]] -> [(String, Property)]) [ properties_emptyGraph 0 , properties_emptyGraph 2 , properties_singletonGraph , properties_petersonGraph , properties_twentyChainGraph , properties_hoffmanSingletonGraph , properties_pentagon , properties_ascendingCube ]
b1756b7b68fe276efc6c9f3818f180d399e5e7a67863bdfc52e1721328cf661a
metaocaml/ber-metaocaml
t01bad.ml
TEST flags = " -w a " ocamlc_byte_exit_status = " 2 " * setup - ocamlc.byte - build - env * * ocamlc.byte * * * check - ocamlc.byte - output flags = " -w a " ocamlc_byte_exit_status = "2" * setup-ocamlc.byte-build-env ** ocamlc.byte *** check-ocamlc.byte-output *) (* Bad (t = t) *) module rec A : sig type t = A.t end = struct type t = A.t end;;
null
https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-recmod/t01bad.ml
ocaml
Bad (t = t)
TEST flags = " -w a " ocamlc_byte_exit_status = " 2 " * setup - ocamlc.byte - build - env * * ocamlc.byte * * * check - ocamlc.byte - output flags = " -w a " ocamlc_byte_exit_status = "2" * setup-ocamlc.byte-build-env ** ocamlc.byte *** check-ocamlc.byte-output *) module rec A : sig type t = A.t end = struct type t = A.t end;;
12438cf38f7ebef0a27c176ede83ac2f30ec9f1809c6a16360d2874bade85464
codecov/codecov-racket
codecov.rkt
#lang racket/base (provide generate-codecov-coverage) (require "private/codecov.rkt")
null
https://raw.githubusercontent.com/codecov/codecov-racket/50388b36071d54b2beffc0cfd8ad17cad940f7a8/cover/codecov.rkt
racket
#lang racket/base (provide generate-codecov-coverage) (require "private/codecov.rkt")
81a52b4d26a0aacac6dc07280a957ea5366a3c409ccb41c9b91766e76b106e72
clojure/core.typed
check_below.clj
Copyright ( c ) , contributors . ;; 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 clojure.core.typed.checker.check-below (:require [clojure.core.typed :as t] [clojure.core.typed.checker.type-rep :as r] [clojure.core.typed.checker.type-ctors :as c] [clojure.core.typed.checker.filter-rep :as fl] [clojure.core.typed.checker.filter-ops :as fo] [clojure.core.typed.checker.object-rep :as obj] [clojure.core.typed.checker.jvm.subtype :as sub] [clojure.core.typed.checker.cs-gen :as cgen] [clojure.core.typed.checker.check.utils :as cu] [clojure.core.typed.util-vars :as vs] [clojure.core.typed.errors :as err] [clojure.core.typed.checker.experimental.infer-vars :as infer-vars])) ;; returns true when f1 <: f2 (defn simple-filter-better? [f1 f2] {:pre [(fl/Filter? f1) (fl/Filter? f2)]} (cond (fl/NoFilter? f2) true (fl/NoFilter? f1) false :else (sub/subtype-filter? f1 f2))) (defn subtype? [t1 t2] (let [s (sub/subtype? t1 t2)] (when (r/Unchecked? t1) (when-some [vsym (:vsym t1)] (infer-vars/add-inferred-type (cu/expr-ns vs/*current-expr*) vsym t2))) s)) apply f1 to the current environment , and if the type filter ;; is boring enough it will reflect in the updated type environment ( defn can - extract - in ? [ env f1 f2 ] ; (cond ( fl / TypeFilter ? f2 ) ( let [ good ? ( atom true ) ; new-env (update/env+ env [f1] good?)] ; (boolean ; (when @good? ; ))) ;; check-below : (/\ (Result Type -> Result) ;; (Result Result -> Result) ;; (Type Result -> Type) ;; (Type Type -> Type)) ;check that arg type tr1 is under expected (defn check-below [tr1 expected] {:pre [((some-fn r/TCResult? r/Type?) tr1) ((some-fn r/TCResult? r/Type?) expected)] :post [(cond (r/TCResult? tr1) (r/TCResult? %) (r/Type? tr1) (r/Type? %))]} (letfn [;; returns true when f1 <: f2 (filter-better? [{f1+ :then f1- :else :as f1} {f2+ :then f2- :else :as f2}] {:pre [(fl/FilterSet? f1) (fl/FilterSet? f2)] :post [(boolean? %)]} (cond (= f1 f2) true :else (let [f+-better? (simple-filter-better? f1+ f2+) f--better? (simple-filter-better? f1- f2-)] (and f+-better? f--better?)))) ;; returns true when o1 <: o2 (object-better? [o1 o2] {:pre [(obj/RObject? o1) (obj/RObject? o2)] :post [(boolean? %)]} (cond (= o1 o2) true ((some-fn obj/NoObject? obj/EmptyObject?) o2) true :else false)) ;; returns true when f1 <: f2 (flow-better? [{flow1 :normal :as f1} {flow2 :normal :as f2}] {:pre [((every-pred r/FlowSet?) f1 f2)] :post [(boolean? %)]} (cond (= flow1 flow2) true (fl/NoFilter? flow2) true (sub/subtype-filter? flow1 flow2) true :else false)) (choose-result-type [t1 t2] {:pre [(r/Type? t1) (r/Type? t2)] :post [(r/Type? %)]} #_ (prn "choose-result-type" t1 t2 (r/infer-any? t1) (r/infer-any? t2)) (cond (r/infer-any? t2) t1 (and (r/FnIntersection? t2) (= 1 (count (:types t2))) (r/infer-any? (-> t2 :types first :rng :t))) (let [rng-t (cgen/unify-or-nil {:fresh [x] :out x} t1 (r/make-FnIntersection (r/make-Function (-> t2 :types first :dom) x)))] (prn "rng-t" rng-t) (if rng-t (assoc-in t2 [:types 0 :rng :t] rng-t) t2)) :else t2)) (choose-result-filter [f1 f2] {:pre [(fl/Filter? f1) (fl/Filter? f2)] :post [(fl/Filter? %)]} ;(prn "check-below choose-result-filter" ; f1 f2 ; (fl/infer-top? f1) ; (fl/infer-top? f2)) (cond (and (fl/infer-top? f2) (not (fl/NoFilter? f1))) f1 :else f2)) (construct-ret [tr1 expected] {:pre [((every-pred r/TCResult?) tr1 expected)] :post [(r/TCResult? %)]} (r/ret (choose-result-type (r/ret-t tr1) (r/ret-t expected)) (let [exp-f (r/ret-f expected) tr-f (r/ret-f tr1)] ;(prn "check-below exp-f" exp-f) ;(prn "check-below tr-f" tr-f) (fo/-FS (choose-result-filter (:then tr-f) (:then exp-f)) (choose-result-filter (:else tr-f) (:else exp-f)))) (let [exp-o (r/ret-o expected) tr-o (r/ret-o tr1)] (if (obj/NoObject? exp-o) tr-o exp-o)) (let [exp-flow (r/ret-flow expected) tr-flow (r/ret-flow tr1)] ;(prn "choose flow" tr-flow exp-flow (fl/infer-top? (:normal exp-flow))) (cond ((some-fn fl/infer-top? fl/NoFilter?) (:normal exp-flow)) tr-flow :else exp-flow))))] ;tr1 = arg ;expected = dom (cond (and (r/TCResult? tr1) (r/TCResult? expected)) (let [{t1 :t f1 :fl o1 :o flow1 :flow} tr1 {t2 :t f2 :fl o2 :o flow2 :flow} expected] (cond (not (subtype? t1 t2)) (cu/expected-error t1 expected) :else (let [better-fs? (filter-better? f1 f2) _ ( prn " better - fs ? " better - fs ? ) better-obj? (object-better? o1 o2) better-flow? (flow-better? flow1 flow2) ;_ (prn "better-flow?" better-flow? flow1 flow2) ] (cond (not better-flow?) (err/tc-delayed-error (str "Expected result with flow filter " (pr-str flow2) ", got flow filter " (pr-str flow1)) :expected expected) (and (not better-fs?) better-obj?) (err/tc-delayed-error (str "Expected result with filter " (pr-str f2) ", got filter " (pr-str f1)) :expected expected) (and better-fs? (not better-obj?)) (err/tc-delayed-error (str "Expected result with object " (pr-str o2) ", got object " (pr-str o1)) :expected expected) (and (not better-fs?) (not better-obj?)) (err/tc-delayed-error (str "Expected result with object " (pr-str o2) ", got object" o1 " and filter " (pr-str f2) " got filter " (pr-str f1))) :expected expected))) (construct-ret tr1 expected)) (and (r/TCResult? tr1) (r/Type? expected)) (let [{t1 :t f :fl o :o} tr1 t2 expected] (when-not (subtype? t1 t2) (cu/expected-error t1 (r/ret t2))) (r/ret (choose-result-type t1 t2) f o)) (and (r/Type? tr1) (r/TCResult? expected)) (let [t1 tr1 {t2 :t f :fl o :o} expected] (if (subtype? t1 t2) (err/tc-delayed-error (str "Expected result with filter " (pr-str f) " and object " (pr-str o) ", got trivial filter and empty object.")) (cu/expected-error t1 expected)) t1) (and (r/Type? tr1) (r/Type? expected)) (let [t1 tr1 t2 expected] (when-not (subtype? t1 t2) (cu/expected-error t1 (r/ret t2))) (choose-result-type t1 t2)) :else (let [a tr1 b expected] (err/int-error (str "Unexpected input for check-below " a b)))))) (defn maybe-check-below [tr1 expected] {:pre [(r/TCResult? tr1) ((some-fn nil? r/TCResult?) expected)] :post [(r/TCResult? %)]} (if expected (check-below tr1 expected) tr1))
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/src/clojure/core/typed/checker/check_below.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. returns true when f1 <: f2 is boring enough it will reflect in the updated type environment (cond new-env (update/env+ env [f1] good?)] (boolean (when @good? ))) check-below : (/\ (Result Type -> Result) (Result Result -> Result) (Type Result -> Type) (Type Type -> Type)) check that arg type tr1 is under expected returns true when f1 <: f2 returns true when o1 <: o2 returns true when f1 <: f2 (prn "check-below choose-result-filter" f1 f2 (fl/infer-top? f1) (fl/infer-top? f2)) (prn "check-below exp-f" exp-f) (prn "check-below tr-f" tr-f) (prn "choose flow" tr-flow exp-flow (fl/infer-top? (:normal exp-flow))) tr1 = arg expected = dom _ (prn "better-flow?" better-flow? flow1 flow2)
Copyright ( c ) , contributors . (ns clojure.core.typed.checker.check-below (:require [clojure.core.typed :as t] [clojure.core.typed.checker.type-rep :as r] [clojure.core.typed.checker.type-ctors :as c] [clojure.core.typed.checker.filter-rep :as fl] [clojure.core.typed.checker.filter-ops :as fo] [clojure.core.typed.checker.object-rep :as obj] [clojure.core.typed.checker.jvm.subtype :as sub] [clojure.core.typed.checker.cs-gen :as cgen] [clojure.core.typed.checker.check.utils :as cu] [clojure.core.typed.util-vars :as vs] [clojure.core.typed.errors :as err] [clojure.core.typed.checker.experimental.infer-vars :as infer-vars])) (defn simple-filter-better? [f1 f2] {:pre [(fl/Filter? f1) (fl/Filter? f2)]} (cond (fl/NoFilter? f2) true (fl/NoFilter? f1) false :else (sub/subtype-filter? f1 f2))) (defn subtype? [t1 t2] (let [s (sub/subtype? t1 t2)] (when (r/Unchecked? t1) (when-some [vsym (:vsym t1)] (infer-vars/add-inferred-type (cu/expr-ns vs/*current-expr*) vsym t2))) s)) apply f1 to the current environment , and if the type filter ( defn can - extract - in ? [ env f1 f2 ] ( fl / TypeFilter ? f2 ) ( let [ good ? ( atom true ) (defn check-below [tr1 expected] {:pre [((some-fn r/TCResult? r/Type?) tr1) ((some-fn r/TCResult? r/Type?) expected)] :post [(cond (r/TCResult? tr1) (r/TCResult? %) (r/Type? tr1) (r/Type? %))]} (filter-better? [{f1+ :then f1- :else :as f1} {f2+ :then f2- :else :as f2}] {:pre [(fl/FilterSet? f1) (fl/FilterSet? f2)] :post [(boolean? %)]} (cond (= f1 f2) true :else (let [f+-better? (simple-filter-better? f1+ f2+) f--better? (simple-filter-better? f1- f2-)] (and f+-better? f--better?)))) (object-better? [o1 o2] {:pre [(obj/RObject? o1) (obj/RObject? o2)] :post [(boolean? %)]} (cond (= o1 o2) true ((some-fn obj/NoObject? obj/EmptyObject?) o2) true :else false)) (flow-better? [{flow1 :normal :as f1} {flow2 :normal :as f2}] {:pre [((every-pred r/FlowSet?) f1 f2)] :post [(boolean? %)]} (cond (= flow1 flow2) true (fl/NoFilter? flow2) true (sub/subtype-filter? flow1 flow2) true :else false)) (choose-result-type [t1 t2] {:pre [(r/Type? t1) (r/Type? t2)] :post [(r/Type? %)]} #_ (prn "choose-result-type" t1 t2 (r/infer-any? t1) (r/infer-any? t2)) (cond (r/infer-any? t2) t1 (and (r/FnIntersection? t2) (= 1 (count (:types t2))) (r/infer-any? (-> t2 :types first :rng :t))) (let [rng-t (cgen/unify-or-nil {:fresh [x] :out x} t1 (r/make-FnIntersection (r/make-Function (-> t2 :types first :dom) x)))] (prn "rng-t" rng-t) (if rng-t (assoc-in t2 [:types 0 :rng :t] rng-t) t2)) :else t2)) (choose-result-filter [f1 f2] {:pre [(fl/Filter? f1) (fl/Filter? f2)] :post [(fl/Filter? %)]} (cond (and (fl/infer-top? f2) (not (fl/NoFilter? f1))) f1 :else f2)) (construct-ret [tr1 expected] {:pre [((every-pred r/TCResult?) tr1 expected)] :post [(r/TCResult? %)]} (r/ret (choose-result-type (r/ret-t tr1) (r/ret-t expected)) (let [exp-f (r/ret-f expected) tr-f (r/ret-f tr1)] (fo/-FS (choose-result-filter (:then tr-f) (:then exp-f)) (choose-result-filter (:else tr-f) (:else exp-f)))) (let [exp-o (r/ret-o expected) tr-o (r/ret-o tr1)] (if (obj/NoObject? exp-o) tr-o exp-o)) (let [exp-flow (r/ret-flow expected) tr-flow (r/ret-flow tr1)] (cond ((some-fn fl/infer-top? fl/NoFilter?) (:normal exp-flow)) tr-flow :else exp-flow))))] (cond (and (r/TCResult? tr1) (r/TCResult? expected)) (let [{t1 :t f1 :fl o1 :o flow1 :flow} tr1 {t2 :t f2 :fl o2 :o flow2 :flow} expected] (cond (not (subtype? t1 t2)) (cu/expected-error t1 expected) :else (let [better-fs? (filter-better? f1 f2) _ ( prn " better - fs ? " better - fs ? ) better-obj? (object-better? o1 o2) better-flow? (flow-better? flow1 flow2) ] (cond (not better-flow?) (err/tc-delayed-error (str "Expected result with flow filter " (pr-str flow2) ", got flow filter " (pr-str flow1)) :expected expected) (and (not better-fs?) better-obj?) (err/tc-delayed-error (str "Expected result with filter " (pr-str f2) ", got filter " (pr-str f1)) :expected expected) (and better-fs? (not better-obj?)) (err/tc-delayed-error (str "Expected result with object " (pr-str o2) ", got object " (pr-str o1)) :expected expected) (and (not better-fs?) (not better-obj?)) (err/tc-delayed-error (str "Expected result with object " (pr-str o2) ", got object" o1 " and filter " (pr-str f2) " got filter " (pr-str f1))) :expected expected))) (construct-ret tr1 expected)) (and (r/TCResult? tr1) (r/Type? expected)) (let [{t1 :t f :fl o :o} tr1 t2 expected] (when-not (subtype? t1 t2) (cu/expected-error t1 (r/ret t2))) (r/ret (choose-result-type t1 t2) f o)) (and (r/Type? tr1) (r/TCResult? expected)) (let [t1 tr1 {t2 :t f :fl o :o} expected] (if (subtype? t1 t2) (err/tc-delayed-error (str "Expected result with filter " (pr-str f) " and object " (pr-str o) ", got trivial filter and empty object.")) (cu/expected-error t1 expected)) t1) (and (r/Type? tr1) (r/Type? expected)) (let [t1 tr1 t2 expected] (when-not (subtype? t1 t2) (cu/expected-error t1 (r/ret t2))) (choose-result-type t1 t2)) :else (let [a tr1 b expected] (err/int-error (str "Unexpected input for check-below " a b)))))) (defn maybe-check-below [tr1 expected] {:pre [(r/TCResult? tr1) ((some-fn nil? r/TCResult?) expected)] :post [(r/TCResult? %)]} (if expected (check-below tr1 expected) tr1))
e60bc8277e71476040a9ffdc98dd26526b0eed5b35f4078c4c21655527cb7b2d
BumblebeeBat/FlyingFox
serve.erl
-module(serve). -export([start/0, start/1, pw/0, pw/1]). start() -> start(port:check()). start(Port) -> io:fwrite("start server\n"), D_internal = [ {'_', [ {"/:file", main_handler, []}, {"/", internal_handler, []} ]} ], D = [ {'_', [ {"/:file", external_handler, []}, {"/", handler, []} ]} ], Dispatch_internal = cowboy_router:compile(D_internal), Dispatch = cowboy_router:compile(D), K_internal = [ {env, [{dispatch, Dispatch_internal}]} ], K = [ {env, [{dispatch, Dispatch}]} ], { ok , _ } = cowboy : start_http(http_internal , 100 , [ { ip , { 127,0,0,1}},{port , Port+1 } ] , K_internal ) , {ok, _} = cowboy:start_http(http_internal, 100, [{ip, {0,0,0,0}},{port, Port+1}], K_internal), {ok, _} = cowboy:start_http(http, 100, [{ip, {0,0,0,0}},{port, Port}], K). pw() -> start(port:check()). pw(X) -> port:change(X), pw().
null
https://raw.githubusercontent.com/BumblebeeBat/FlyingFox/0fa039cd2394b08b1a85559f9392086c6be47fa6/src/networking/serve.erl
erlang
-module(serve). -export([start/0, start/1, pw/0, pw/1]). start() -> start(port:check()). start(Port) -> io:fwrite("start server\n"), D_internal = [ {'_', [ {"/:file", main_handler, []}, {"/", internal_handler, []} ]} ], D = [ {'_', [ {"/:file", external_handler, []}, {"/", handler, []} ]} ], Dispatch_internal = cowboy_router:compile(D_internal), Dispatch = cowboy_router:compile(D), K_internal = [ {env, [{dispatch, Dispatch_internal}]} ], K = [ {env, [{dispatch, Dispatch}]} ], { ok , _ } = cowboy : start_http(http_internal , 100 , [ { ip , { 127,0,0,1}},{port , Port+1 } ] , K_internal ) , {ok, _} = cowboy:start_http(http_internal, 100, [{ip, {0,0,0,0}},{port, Port+1}], K_internal), {ok, _} = cowboy:start_http(http, 100, [{ip, {0,0,0,0}},{port, Port}], K). pw() -> start(port:check()). pw(X) -> port:change(X), pw().
e7a898f9f21196dddbe2c39f0b564fa0e7b02abb1853790b107b35863f66fbf7
dongcarl/guix
cpan.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 < > Copyright © 2016 < > Copyright © 2020 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (test-cpan) #:use-module (guix import cpan) #:use-module (guix base32) #:use-module (gcrypt hash) #:use-module (guix tests http) #:use-module (guix grafts) #:use-module (srfi srfi-64) #:use-module (web client) #:use-module (ice-9 match)) ;; Globally disable grafts because they can trigger early builds. (%graft? #f) (define test-json "{ \"metadata\" : { \"name\" : \"Foo-Bar\", \"version\" : \"0.1\" } \"name\" : \"Foo-Bar-0.1\", \"distribution\" : \"Foo-Bar\", \"license\" : [ \"perl_5\" ], \"dependency\": [ { \"relationship\": \"requires\", \"phase\": \"runtime\", \"version\": \"1.05\", \"module\": \"Test::Script\" } ], \"abstract\" : \"Fizzle Fuzz\", \"download_url\" : \"-Bar-0.1.tar.gz\", \"author\" : \"Guix\", \"version\" : \"0.1\" }") (define test-source "foobar") ;; Avoid collisions with other tests. (%http-server-port 10400) (test-begin "cpan") (test-assert "cpan->guix-package" ;; Replace network resources with sample data. (with-http-server `((200 ,test-json) (200 ,test-source) (200 "{ \"distribution\" : \"Test-Script\" }")) (parameterize ((%metacpan-base-url (%local-url)) (current-http-proxy (%local-url))) (match (cpan->guix-package "Foo::Bar") (('package ('name "perl-foo-bar") ('version "0.1") ('source ('origin ('method 'url-fetch) ('uri ('string-append "-Bar-" 'version ".tar.gz")) ('sha256 ('base32 (? string? hash))))) ('build-system 'perl-build-system) ('propagated-inputs ('quasiquote (("perl-test-script" ('unquote 'perl-test-script))))) ('home-page "-Bar") ('synopsis "Fizzle Fuzz") ('description 'fill-in-yourself!) ('license 'perl-license)) (string=? (bytevector->nix-base32-string (call-with-input-string test-source port-sha256)) hash)) (x (pk 'fail x #f)))))) (test-equal "metacpan-url->mirror-url, http" "mirror-Bar-0.1.tar.gz" (metacpan-url->mirror-url "-Bar-0.1.tar.gz")) (test-equal "metacpan-url->mirror-url, https" "mirror-Bar-0.1.tar.gz" (metacpan-url->mirror-url "-Bar-0.1.tar.gz")) (test-end "cpan")
null
https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/tests/cpan.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Globally disable grafts because they can trigger early builds. Avoid collisions with other tests. Replace network resources with sample data.
Copyright © 2015 < > Copyright © 2016 < > Copyright © 2020 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (test-cpan) #:use-module (guix import cpan) #:use-module (guix base32) #:use-module (gcrypt hash) #:use-module (guix tests http) #:use-module (guix grafts) #:use-module (srfi srfi-64) #:use-module (web client) #:use-module (ice-9 match)) (%graft? #f) (define test-json "{ \"metadata\" : { \"name\" : \"Foo-Bar\", \"version\" : \"0.1\" } \"name\" : \"Foo-Bar-0.1\", \"distribution\" : \"Foo-Bar\", \"license\" : [ \"perl_5\" ], \"dependency\": [ { \"relationship\": \"requires\", \"phase\": \"runtime\", \"version\": \"1.05\", \"module\": \"Test::Script\" } ], \"abstract\" : \"Fizzle Fuzz\", \"download_url\" : \"-Bar-0.1.tar.gz\", \"author\" : \"Guix\", \"version\" : \"0.1\" }") (define test-source "foobar") (%http-server-port 10400) (test-begin "cpan") (test-assert "cpan->guix-package" (with-http-server `((200 ,test-json) (200 ,test-source) (200 "{ \"distribution\" : \"Test-Script\" }")) (parameterize ((%metacpan-base-url (%local-url)) (current-http-proxy (%local-url))) (match (cpan->guix-package "Foo::Bar") (('package ('name "perl-foo-bar") ('version "0.1") ('source ('origin ('method 'url-fetch) ('uri ('string-append "-Bar-" 'version ".tar.gz")) ('sha256 ('base32 (? string? hash))))) ('build-system 'perl-build-system) ('propagated-inputs ('quasiquote (("perl-test-script" ('unquote 'perl-test-script))))) ('home-page "-Bar") ('synopsis "Fizzle Fuzz") ('description 'fill-in-yourself!) ('license 'perl-license)) (string=? (bytevector->nix-base32-string (call-with-input-string test-source port-sha256)) hash)) (x (pk 'fail x #f)))))) (test-equal "metacpan-url->mirror-url, http" "mirror-Bar-0.1.tar.gz" (metacpan-url->mirror-url "-Bar-0.1.tar.gz")) (test-equal "metacpan-url->mirror-url, https" "mirror-Bar-0.1.tar.gz" (metacpan-url->mirror-url "-Bar-0.1.tar.gz")) (test-end "cpan")
7cb0159f955477e445b9c6c5c2337d6da8838fcfab59cee08172d25e2a155153
MaskRay/99-problems-ocaml
20.ml
let rec remove_at xs n = match xs with | [] -> [] | h::t -> if n == 1 then t else h :: remove_at t (n-1)
null
https://raw.githubusercontent.com/MaskRay/99-problems-ocaml/652604f13ba7a73eee06d359b4db549b49ec9bb3/11-20/20.ml
ocaml
let rec remove_at xs n = match xs with | [] -> [] | h::t -> if n == 1 then t else h :: remove_at t (n-1)
6047387227457132a844ed0b70b420fa9b8cd79f406baac8f91b04f491d88f1f
basho/riak_cs
riak_cs_stats.erl
%% --------------------------------------------------------------------- %% Copyright ( c ) 2007 - 2015 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% --------------------------------------------------------------------- -module(riak_cs_stats). %% API -export([ inflow/1, update_with_start/3, update_with_start/2, update_error_with_start/2, update/2, countup/1, report_json/0, report_pretty_json/0, get_stats/0]). %% Lower level API, mainly for debugging or investigation from shell -export([report_exometer_item/3, report_pool/0, report_pool/1, report_mochiweb/0, report_memory/0, report_system/0, system_monitor_count/0, system_version/0, system_architecture/0]). -export([init/0]). -type key() :: [atom()]. -export_type([key/0]). -type ok_error_res() :: ok | {ok, _} | {error, _}. -spec duration_metrics() -> [key()]. duration_metrics() -> [ [service, get], [bucket, put], [bucket, head], [bucket, delete], [bucket_acl, get], [bucket_acl, put], [bucket_policy, get], [bucket_policy, put], [bucket_policy, delete], [bucket_location, get], [bucket_versioning, get], [bucket_request_payment, get], [list_uploads, get], [multiple_delete, post], [list_objects, get], [object, get], [object, put], [object, put_copy], [object, head], [object, delete], [object_acl, get], [object_acl, put], [multipart, post], % Initiate [multipart_upload, put], % Upload Part [multipart_upload, put_copy], % Upload Part (Copy) [multipart_upload, post], % Complete [multipart_upload, delete], % Abort [multipart_upload, get], % List Parts [velvet, create_user], [velvet, update_user], [velvet, create_bucket], [velvet, delete_bucket], [velvet, set_bucket_acl], [velvet, set_bucket_policy], [velvet, delete_bucket_policy], Riak PB client , per key operations [riakc, ping], [riakc, get_cs_bucket], [riakc, get_cs_user_strong], [riakc, get_cs_user], [riakc, put_cs_user], [riakc, get_manifest], [riakc, put_manifest], [riakc, delete_manifest], [riakc, get_block_n_one], [riakc, get_block_n_all], [riakc, get_block_remote], [riakc, get_block_legacy], [riakc, get_block_legacy_remote], [riakc, put_block], [riakc, put_block_resolved], [riakc, head_block], [riakc, delete_block_constrained], [riakc, delete_block_secondary], [riakc, get_gc_manifest_set], [riakc, put_gc_manifest_set], [riakc, delete_gc_manifest_set], [riakc, get_access], [riakc, put_access], [riakc, get_storage], [riakc, put_storage], %% Riak PB client, coverage operations [riakc, fold_manifest_objs], [riakc, mapred_storage], [riakc, list_all_user_keys], [riakc, list_all_bucket_keys], [riakc, list_all_manifest_keys], [riakc, list_users_receive_chunk], [riakc, get_uploads_by_index], [riakc, get_user_by_index], [riakc, get_gc_keys_by_index], [riakc, get_cs_buckets_by_index], Riak PB client , misc [riakc, get_clusterid] ]. counting_metrics() -> [ %% Almost deprecated [manifest, siblings_bp_sleep] ]. duration_subkeys() -> [{[in], spiral}, {[out], spiral}, {[time], histogram}, {[out, error], spiral}, {[time, error], histogram}]. counting_subkeys() -> [{[], spiral}]. %% ==================================================================== %% API %% ==================================================================== -spec inflow(key()) -> ok. inflow(Key) -> safe_update([riak_cs, in | Key], 1). -spec update_with_start(key(), erlang:timestamp(), ok_error_res()) -> ok. update_with_start(Key, StartTime, ok) -> update_with_start(Key, StartTime); update_with_start(Key, StartTime, {ok, _}) -> update_with_start(Key, StartTime); update_with_start(Key, StartTime, {error, _}) -> update_error_with_start(Key, StartTime). -spec update_with_start(key(), erlang:timestamp()) -> ok. update_with_start(Key, StartTime) -> update(Key, timer:now_diff(os:timestamp(), StartTime)). -spec update_error_with_start(key(), erlang:timestamp()) -> ok. update_error_with_start(Key, StartTime) -> update([error | Key], timer:now_diff(os:timestamp(), StartTime)). -spec countup(key()) -> ok. countup(Key) -> safe_update([riak_cs | Key], 1). -spec report_json() -> string(). report_json() -> lists:flatten(mochijson2:encode({struct, get_stats()})). -spec report_pretty_json() -> string(). report_pretty_json() -> lists:flatten(riak_cs_utils:json_pp_print(report_json())). -spec get_stats() -> proplists:proplist(). get_stats() -> DurationStats = [report_exometer_item(Key, SubKey, ExometerType) || Key <- duration_metrics(), {SubKey, ExometerType} <- duration_subkeys()], CountingStats = [report_exometer_item(Key, SubKey, ExometerType) || Key <- counting_metrics(), {SubKey, ExometerType} <- counting_subkeys()], lists:flatten([DurationStats, CountingStats, report_pool(), report_mochiweb(), report_memory(), report_system()]). %% ==================================================================== Internal %% ==================================================================== init() -> _ = [init_duration_item(I) || I <- duration_metrics()], _ = [init_counting_item(I) || I <- counting_metrics()], ok. init_duration_item(Key) -> [ok = exometer:re_register([riak_cs | SubKey ++ Key], ExometerType, []) || {SubKey, ExometerType} <- duration_subkeys()]. init_counting_item(Key) -> [ok = exometer:re_register([riak_cs | SubKey ++ Key], ExometerType, []) || {SubKey, ExometerType} <- counting_subkeys()]. -spec update(key(), integer()) -> ok. update(Key, ElapsedUs) -> safe_update([riak_cs, out | Key], 1), safe_update([riak_cs, time | Key], ElapsedUs). safe_update(ExometerKey, Arg) -> case exometer:update(ExometerKey, Arg) of ok -> ok; {error, Reason} -> lager:warning("Stats update for key ~p error: ~p", [ExometerKey, Reason]), ok end. -spec report_exometer_item(key(), [atom()], exometer:type()) -> [{atom(), integer()}]. report_exometer_item(Key, SubKey, ExometerType) -> AtomKeys = [metric_to_atom(Key ++ SubKey, Suffix) || Suffix <- suffixes(ExometerType)], {ok, Values} = exometer:get_value([riak_cs | SubKey ++ Key], datapoints(ExometerType)), [{AtomKey, Value} || {AtomKey, {_DP, Value}} <- lists:zip(AtomKeys, Values)]. datapoints(histogram) -> [mean, median, 95, 99, max]; datapoints(spiral) -> [one, count]. suffixes(histogram) -> ["mean", "median", "95", "99", "100"]; suffixes(spiral) -> ["one", "total"]. -spec report_pool() -> [[{atom(), integer()}]]. report_pool() -> Pools = [request_pool, bucket_list_pool | riak_cs_riak_client:pbc_pools()], [report_pool(Pool) || Pool <- Pools]. -spec report_pool(atom()) -> [{atom(), integer()}]. report_pool(Pool) -> {_PoolState, PoolWorkers, PoolOverflow, PoolSize} = poolboy:status(Pool), [{metric_to_atom([Pool], "workers"), PoolWorkers}, {metric_to_atom([Pool], "overflow"), PoolOverflow}, {metric_to_atom([Pool], "size"), PoolSize}]. -spec report_mochiweb() -> [[{atom(), integer()}]]. report_mochiweb() -> MochiIds = [object_web, admin_web], [report_mochiweb(Id) || Id <- MochiIds]. report_mochiweb(Id) -> Children = supervisor:which_children(riak_cs_sup), case lists:keyfind(Id, 1, Children) of false -> []; {_, Pid, _, _} -> report_mochiweb(Id, Pid) end. report_mochiweb(Id, Pid) -> [{metric_to_atom([Id], PropKey), gen_server:call(Pid, {get, PropKey})} || PropKey <- [active_sockets, waiting_acceptors, port]]. -spec report_memory() -> [{atom(), integer()}]. report_memory() -> lists:map(fun({K, V}) -> {metric_to_atom([memory], K), V} end, erlang:memory()). -spec report_system() -> [{atom(), integer()}]. report_system() -> [{nodename, erlang:node()}, {connected_nodes, erlang:nodes()}, {sys_driver_version, list_to_binary(erlang:system_info(driver_version))}, {sys_heap_type, erlang:system_info(heap_type)}, {sys_logical_processors, erlang:system_info(logical_processors)}, {sys_monitor_count, system_monitor_count()}, {sys_otp_release, list_to_binary(erlang:system_info(otp_release))}, {sys_port_count, erlang:system_info(port_count)}, {sys_process_count, erlang:system_info(process_count)}, {sys_smp_support, erlang:system_info(smp_support)}, {sys_system_version, system_version()}, {sys_system_architecture, system_architecture()}, {sys_threads_enabled, erlang:system_info(threads)}, {sys_thread_pool_size, erlang:system_info(thread_pool_size)}, {sys_wordsize, erlang:system_info(wordsize)}]. system_monitor_count() -> lists:foldl(fun(Pid, Count) -> case erlang:process_info(Pid, monitors) of {monitors, Mons} -> Count + length(Mons); _ -> Count end end, 0, processes()). system_version() -> list_to_binary(string:strip(erlang:system_info(system_version), right, $\n)). system_architecture() -> list_to_binary(erlang:system_info(system_architecture)). metric_to_atom(Key, Suffix) when is_atom(Suffix) -> metric_to_atom(Key, atom_to_list(Suffix)); metric_to_atom(Key, Suffix) -> StringKey = string:join([atom_to_list(Token) || Token <- Key], "_"), list_to_atom(lists:flatten([StringKey, $_, Suffix])). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). stats_test_() -> Apps = [setup, compiler, syntax_tools, goldrush, lager, exometer_core], {setup, fun() -> application:set_env(lager, handlers, []), [catch (application:start(App)) || App <- Apps], ok = init() end, fun(_) -> [ok = application:stop(App) || App <- Apps] end, [{inparallel, [fun() -> inflow(Key), update(Key, 16#deadbeef), update([error | Key], 16#deadbeef) end || Key <- duration_metrics()]}, {inparallel, [fun() -> countup(Key) end || Key <- counting_metrics()]}, fun() -> [begin Report = [N || {_, N} <- report_exometer_item(Key, SubKey, ExometerType)], case ExometerType of spiral -> ?assertEqual([1, 1], Report); histogram -> ?assertEqual( [16#deadbeef, 16#deadbeef, 16#deadbeef, 16#deadbeef, 16#deadbeef], Report) end end || Key <- duration_metrics(), {SubKey, ExometerType} <- duration_subkeys()], [begin Report = [N || {_, N} <- report_exometer_item(Key, SubKey, ExometerType)], case ExometerType of spiral -> ?assertEqual([1, 1], Report) end end || Key <- counting_metrics(), {SubKey, ExometerType} <- counting_subkeys()] end]}. -endif.
null
https://raw.githubusercontent.com/basho/riak_cs/c0c1012d1c9c691c74c8c5d9f69d388f5047bcd2/src/riak_cs_stats.erl
erlang
--------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------- API Lower level API, mainly for debugging or investigation from shell Initiate Upload Part Upload Part (Copy) Complete Abort List Parts Riak PB client, coverage operations Almost deprecated ==================================================================== API ==================================================================== ==================================================================== ====================================================================
Copyright ( c ) 2007 - 2015 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(riak_cs_stats). -export([ inflow/1, update_with_start/3, update_with_start/2, update_error_with_start/2, update/2, countup/1, report_json/0, report_pretty_json/0, get_stats/0]). -export([report_exometer_item/3, report_pool/0, report_pool/1, report_mochiweb/0, report_memory/0, report_system/0, system_monitor_count/0, system_version/0, system_architecture/0]). -export([init/0]). -type key() :: [atom()]. -export_type([key/0]). -type ok_error_res() :: ok | {ok, _} | {error, _}. -spec duration_metrics() -> [key()]. duration_metrics() -> [ [service, get], [bucket, put], [bucket, head], [bucket, delete], [bucket_acl, get], [bucket_acl, put], [bucket_policy, get], [bucket_policy, put], [bucket_policy, delete], [bucket_location, get], [bucket_versioning, get], [bucket_request_payment, get], [list_uploads, get], [multiple_delete, post], [list_objects, get], [object, get], [object, put], [object, put_copy], [object, head], [object, delete], [object_acl, get], [object_acl, put], [velvet, create_user], [velvet, update_user], [velvet, create_bucket], [velvet, delete_bucket], [velvet, set_bucket_acl], [velvet, set_bucket_policy], [velvet, delete_bucket_policy], Riak PB client , per key operations [riakc, ping], [riakc, get_cs_bucket], [riakc, get_cs_user_strong], [riakc, get_cs_user], [riakc, put_cs_user], [riakc, get_manifest], [riakc, put_manifest], [riakc, delete_manifest], [riakc, get_block_n_one], [riakc, get_block_n_all], [riakc, get_block_remote], [riakc, get_block_legacy], [riakc, get_block_legacy_remote], [riakc, put_block], [riakc, put_block_resolved], [riakc, head_block], [riakc, delete_block_constrained], [riakc, delete_block_secondary], [riakc, get_gc_manifest_set], [riakc, put_gc_manifest_set], [riakc, delete_gc_manifest_set], [riakc, get_access], [riakc, put_access], [riakc, get_storage], [riakc, put_storage], [riakc, fold_manifest_objs], [riakc, mapred_storage], [riakc, list_all_user_keys], [riakc, list_all_bucket_keys], [riakc, list_all_manifest_keys], [riakc, list_users_receive_chunk], [riakc, get_uploads_by_index], [riakc, get_user_by_index], [riakc, get_gc_keys_by_index], [riakc, get_cs_buckets_by_index], Riak PB client , misc [riakc, get_clusterid] ]. counting_metrics() -> [ [manifest, siblings_bp_sleep] ]. duration_subkeys() -> [{[in], spiral}, {[out], spiral}, {[time], histogram}, {[out, error], spiral}, {[time, error], histogram}]. counting_subkeys() -> [{[], spiral}]. -spec inflow(key()) -> ok. inflow(Key) -> safe_update([riak_cs, in | Key], 1). -spec update_with_start(key(), erlang:timestamp(), ok_error_res()) -> ok. update_with_start(Key, StartTime, ok) -> update_with_start(Key, StartTime); update_with_start(Key, StartTime, {ok, _}) -> update_with_start(Key, StartTime); update_with_start(Key, StartTime, {error, _}) -> update_error_with_start(Key, StartTime). -spec update_with_start(key(), erlang:timestamp()) -> ok. update_with_start(Key, StartTime) -> update(Key, timer:now_diff(os:timestamp(), StartTime)). -spec update_error_with_start(key(), erlang:timestamp()) -> ok. update_error_with_start(Key, StartTime) -> update([error | Key], timer:now_diff(os:timestamp(), StartTime)). -spec countup(key()) -> ok. countup(Key) -> safe_update([riak_cs | Key], 1). -spec report_json() -> string(). report_json() -> lists:flatten(mochijson2:encode({struct, get_stats()})). -spec report_pretty_json() -> string(). report_pretty_json() -> lists:flatten(riak_cs_utils:json_pp_print(report_json())). -spec get_stats() -> proplists:proplist(). get_stats() -> DurationStats = [report_exometer_item(Key, SubKey, ExometerType) || Key <- duration_metrics(), {SubKey, ExometerType} <- duration_subkeys()], CountingStats = [report_exometer_item(Key, SubKey, ExometerType) || Key <- counting_metrics(), {SubKey, ExometerType} <- counting_subkeys()], lists:flatten([DurationStats, CountingStats, report_pool(), report_mochiweb(), report_memory(), report_system()]). Internal init() -> _ = [init_duration_item(I) || I <- duration_metrics()], _ = [init_counting_item(I) || I <- counting_metrics()], ok. init_duration_item(Key) -> [ok = exometer:re_register([riak_cs | SubKey ++ Key], ExometerType, []) || {SubKey, ExometerType} <- duration_subkeys()]. init_counting_item(Key) -> [ok = exometer:re_register([riak_cs | SubKey ++ Key], ExometerType, []) || {SubKey, ExometerType} <- counting_subkeys()]. -spec update(key(), integer()) -> ok. update(Key, ElapsedUs) -> safe_update([riak_cs, out | Key], 1), safe_update([riak_cs, time | Key], ElapsedUs). safe_update(ExometerKey, Arg) -> case exometer:update(ExometerKey, Arg) of ok -> ok; {error, Reason} -> lager:warning("Stats update for key ~p error: ~p", [ExometerKey, Reason]), ok end. -spec report_exometer_item(key(), [atom()], exometer:type()) -> [{atom(), integer()}]. report_exometer_item(Key, SubKey, ExometerType) -> AtomKeys = [metric_to_atom(Key ++ SubKey, Suffix) || Suffix <- suffixes(ExometerType)], {ok, Values} = exometer:get_value([riak_cs | SubKey ++ Key], datapoints(ExometerType)), [{AtomKey, Value} || {AtomKey, {_DP, Value}} <- lists:zip(AtomKeys, Values)]. datapoints(histogram) -> [mean, median, 95, 99, max]; datapoints(spiral) -> [one, count]. suffixes(histogram) -> ["mean", "median", "95", "99", "100"]; suffixes(spiral) -> ["one", "total"]. -spec report_pool() -> [[{atom(), integer()}]]. report_pool() -> Pools = [request_pool, bucket_list_pool | riak_cs_riak_client:pbc_pools()], [report_pool(Pool) || Pool <- Pools]. -spec report_pool(atom()) -> [{atom(), integer()}]. report_pool(Pool) -> {_PoolState, PoolWorkers, PoolOverflow, PoolSize} = poolboy:status(Pool), [{metric_to_atom([Pool], "workers"), PoolWorkers}, {metric_to_atom([Pool], "overflow"), PoolOverflow}, {metric_to_atom([Pool], "size"), PoolSize}]. -spec report_mochiweb() -> [[{atom(), integer()}]]. report_mochiweb() -> MochiIds = [object_web, admin_web], [report_mochiweb(Id) || Id <- MochiIds]. report_mochiweb(Id) -> Children = supervisor:which_children(riak_cs_sup), case lists:keyfind(Id, 1, Children) of false -> []; {_, Pid, _, _} -> report_mochiweb(Id, Pid) end. report_mochiweb(Id, Pid) -> [{metric_to_atom([Id], PropKey), gen_server:call(Pid, {get, PropKey})} || PropKey <- [active_sockets, waiting_acceptors, port]]. -spec report_memory() -> [{atom(), integer()}]. report_memory() -> lists:map(fun({K, V}) -> {metric_to_atom([memory], K), V} end, erlang:memory()). -spec report_system() -> [{atom(), integer()}]. report_system() -> [{nodename, erlang:node()}, {connected_nodes, erlang:nodes()}, {sys_driver_version, list_to_binary(erlang:system_info(driver_version))}, {sys_heap_type, erlang:system_info(heap_type)}, {sys_logical_processors, erlang:system_info(logical_processors)}, {sys_monitor_count, system_monitor_count()}, {sys_otp_release, list_to_binary(erlang:system_info(otp_release))}, {sys_port_count, erlang:system_info(port_count)}, {sys_process_count, erlang:system_info(process_count)}, {sys_smp_support, erlang:system_info(smp_support)}, {sys_system_version, system_version()}, {sys_system_architecture, system_architecture()}, {sys_threads_enabled, erlang:system_info(threads)}, {sys_thread_pool_size, erlang:system_info(thread_pool_size)}, {sys_wordsize, erlang:system_info(wordsize)}]. system_monitor_count() -> lists:foldl(fun(Pid, Count) -> case erlang:process_info(Pid, monitors) of {monitors, Mons} -> Count + length(Mons); _ -> Count end end, 0, processes()). system_version() -> list_to_binary(string:strip(erlang:system_info(system_version), right, $\n)). system_architecture() -> list_to_binary(erlang:system_info(system_architecture)). metric_to_atom(Key, Suffix) when is_atom(Suffix) -> metric_to_atom(Key, atom_to_list(Suffix)); metric_to_atom(Key, Suffix) -> StringKey = string:join([atom_to_list(Token) || Token <- Key], "_"), list_to_atom(lists:flatten([StringKey, $_, Suffix])). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). stats_test_() -> Apps = [setup, compiler, syntax_tools, goldrush, lager, exometer_core], {setup, fun() -> application:set_env(lager, handlers, []), [catch (application:start(App)) || App <- Apps], ok = init() end, fun(_) -> [ok = application:stop(App) || App <- Apps] end, [{inparallel, [fun() -> inflow(Key), update(Key, 16#deadbeef), update([error | Key], 16#deadbeef) end || Key <- duration_metrics()]}, {inparallel, [fun() -> countup(Key) end || Key <- counting_metrics()]}, fun() -> [begin Report = [N || {_, N} <- report_exometer_item(Key, SubKey, ExometerType)], case ExometerType of spiral -> ?assertEqual([1, 1], Report); histogram -> ?assertEqual( [16#deadbeef, 16#deadbeef, 16#deadbeef, 16#deadbeef, 16#deadbeef], Report) end end || Key <- duration_metrics(), {SubKey, ExometerType} <- duration_subkeys()], [begin Report = [N || {_, N} <- report_exometer_item(Key, SubKey, ExometerType)], case ExometerType of spiral -> ?assertEqual([1, 1], Report) end end || Key <- counting_metrics(), {SubKey, ExometerType} <- counting_subkeys()] end]}. -endif.
aab551903280f9d71eb5f0e1a3965ceef9481f3c2bd2bd073a4b11690c825696
kcsongor/typelevel-prelude
Reader.hs
module Type.Control.Monad.Reader ( Reader(..) , RunReader ) where import Type.Prelude data Reader r a = MkReader (r ~> a) type family RunReader (f :: Reader r a) :: r ~> a where RunReader ('MkReader f) = f instance Functor (Reader r) where type instance Fmap f ('MkReader g) = 'MkReader (f . g) instance Applicative (Reader r) where type instance Pure x = 'MkReader (Const x) type instance 'MkReader f <*> 'MkReader x = 'MkReader (S f x) type family ReaderBindImpl (m :: r ~> a) (k :: a ~> Reader r b) (s :: r) where ReaderBindImpl m k s = RunReader (k (m s)) s instance Monad (Reader r) where type instance 'MkReader m >>= k = 'MkReader (ReaderBindImpl m k)
null
https://raw.githubusercontent.com/kcsongor/typelevel-prelude/ed16e52c4547e9d3e9611403228d586f6d03ef55/src/Type/Control/Monad/Reader.hs
haskell
module Type.Control.Monad.Reader ( Reader(..) , RunReader ) where import Type.Prelude data Reader r a = MkReader (r ~> a) type family RunReader (f :: Reader r a) :: r ~> a where RunReader ('MkReader f) = f instance Functor (Reader r) where type instance Fmap f ('MkReader g) = 'MkReader (f . g) instance Applicative (Reader r) where type instance Pure x = 'MkReader (Const x) type instance 'MkReader f <*> 'MkReader x = 'MkReader (S f x) type family ReaderBindImpl (m :: r ~> a) (k :: a ~> Reader r b) (s :: r) where ReaderBindImpl m k s = RunReader (k (m s)) s instance Monad (Reader r) where type instance 'MkReader m >>= k = 'MkReader (ReaderBindImpl m k)
d69481ac32bcd268354c9a112855c8d959ecbfd36216e99023340c47d79eff28
RedPRL/kado
Graph.ml
module type Vertex = sig type t val compare : t -> t -> int val initial : t (* if you pretent the graph is a category *) val terminal : t end module type S = sig type key type t val empty : t val test : key -> key -> t -> bool val union : key -> key -> t -> t val test_and_union : key -> key -> t -> bool * t val merge : t -> t -> t end module Make (V : Vertex) : S with type key = V.t = struct module M = Map.Make (V) module S = Set.Make (V) type vertex = V.t type key = vertex let (=) v1 v2 = V.compare v1 v2 = 0 type t = { reachable : S.t M.t; (* a map from vertices to their reachable vertices *) the reduced graph exclding ( v , 1 ) } let empty : t = { reachable = M.of_seq @@ List.to_seq [V.initial, S.of_list [V.initial; V.terminal]; V.terminal, S.singleton V.terminal]; reduced = M.of_seq @@ List.to_seq [V.initial, []; V.terminal, []] } let mem_vertex (v : vertex) (g : t) : bool = M.mem v g.reachable let touch_vertex (v : vertex) (g : t) : t = if mem_vertex v g then g else { reachable = M.add v (S.add v (M.find V.terminal g.reachable)) @@ M.map (fun s -> if S.mem V.initial s then S.add v s else s) @@ g.reachable; reduced = as an optimization , there 's no need to the add edge ( v , 1 ) because 1 is always reachable . M.update V.initial (fun l -> Some (v :: Option.get l)) @@ M.add v [] @@ g.reduced } let raw_test (u : vertex) (v : vertex) (g : t) = S.mem v (M.find u g.reachable) let test (u : vertex) (v : vertex) (g : t) = match mem_vertex u g, mem_vertex v g with | true, true -> raw_test u v g | true, false -> raw_test u V.initial g | false, true -> raw_test V.terminal v g | false, false -> u = v || raw_test V.terminal V.initial g let union (u : vertex) (v : vertex) (g : t) = if test u v g then g else let g = touch_vertex v @@ touch_vertex u g in let rec meld i rx = let f rx j = if S.mem j rx then rx else meld j (S.add j rx) in List.fold_left f rx (M.find i g.reduced) in { reduced = M.update u (fun l -> Some (v :: Option.get l)) g.reduced; reachable = g.reachable |> M.map @@ fun rx -> if S.mem u rx && not (S.mem v rx) then meld v @@ S.add v rx else rx } let test_and_union (u : vertex) (v : vertex) (g : t) = test u v g, union u v g let merge (g1 : t) (g2 : t) = M.fold (fun u -> List.fold_right (union u)) g1.reduced g2 end
null
https://raw.githubusercontent.com/RedPRL/kado/f18418bcd0123ce906cb513b18f4cd282ff14b8e/src/Graph.ml
ocaml
if you pretent the graph is a category a map from vertices to their reachable vertices
module type Vertex = sig type t val compare : t -> t -> int val terminal : t end module type S = sig type key type t val empty : t val test : key -> key -> t -> bool val union : key -> key -> t -> t val test_and_union : key -> key -> t -> bool * t val merge : t -> t -> t end module Make (V : Vertex) : S with type key = V.t = struct module M = Map.Make (V) module S = Set.Make (V) type vertex = V.t type key = vertex let (=) v1 v2 = V.compare v1 v2 = 0 type t = the reduced graph exclding ( v , 1 ) } let empty : t = { reachable = M.of_seq @@ List.to_seq [V.initial, S.of_list [V.initial; V.terminal]; V.terminal, S.singleton V.terminal]; reduced = M.of_seq @@ List.to_seq [V.initial, []; V.terminal, []] } let mem_vertex (v : vertex) (g : t) : bool = M.mem v g.reachable let touch_vertex (v : vertex) (g : t) : t = if mem_vertex v g then g else { reachable = M.add v (S.add v (M.find V.terminal g.reachable)) @@ M.map (fun s -> if S.mem V.initial s then S.add v s else s) @@ g.reachable; reduced = as an optimization , there 's no need to the add edge ( v , 1 ) because 1 is always reachable . M.update V.initial (fun l -> Some (v :: Option.get l)) @@ M.add v [] @@ g.reduced } let raw_test (u : vertex) (v : vertex) (g : t) = S.mem v (M.find u g.reachable) let test (u : vertex) (v : vertex) (g : t) = match mem_vertex u g, mem_vertex v g with | true, true -> raw_test u v g | true, false -> raw_test u V.initial g | false, true -> raw_test V.terminal v g | false, false -> u = v || raw_test V.terminal V.initial g let union (u : vertex) (v : vertex) (g : t) = if test u v g then g else let g = touch_vertex v @@ touch_vertex u g in let rec meld i rx = let f rx j = if S.mem j rx then rx else meld j (S.add j rx) in List.fold_left f rx (M.find i g.reduced) in { reduced = M.update u (fun l -> Some (v :: Option.get l)) g.reduced; reachable = g.reachable |> M.map @@ fun rx -> if S.mem u rx && not (S.mem v rx) then meld v @@ S.add v rx else rx } let test_and_union (u : vertex) (v : vertex) (g : t) = test u v g, union u v g let merge (g1 : t) (g2 : t) = M.fold (fun u -> List.fold_right (union u)) g1.reduced g2 end
4e29b98a85bf64adfe60d4f954302c45eb47109d8cfd0f02f617f475ebca6821
fukamachi/lack
dbi.lisp
(in-package :cl-user) (defpackage t.lack.session.store.dbi (:use :cl :lack :lack.test :lack.session.store.dbi :dbi :prove)) (in-package :t.lack.session.store.dbi) (plan 4) (defvar *test-db* (asdf:system-relative-pathname :lack "data/test.db")) (when (probe-file *test-db*) (delete-file *test-db*)) (defparameter *conn* (dbi:connect :sqlite3 :database-name *test-db*)) (dbi:do-sql *conn* "CREATE TABLE sessions (id CHAR(72) PRIMARY KEY, session_data TEXT)") (subtest "session middleware" (let ((app (builder (:session :store (make-dbi-store :connector (lambda () *conn*))) (lambda (env) (unless (gethash :counter (getf env :lack.session)) (setf (gethash :counter (getf env :lack.session)) 0)) `(200 (:content-type "text/plain") (,(format nil "Hello, you've been here for ~Ath times!" (incf (gethash :counter (getf env :lack.session))))))))) session) (diag "1st request") (destructuring-bind (status headers body) (funcall app (generate-env "/")) (is status 200) (setf session (parse-lack-session headers)) (ok session) (is body '("Hello, you've been here for 1th times!"))) (diag "2nd request") (destructuring-bind (status headers body) (funcall app (generate-env "/" :cookies `(("lack.session" . ,session)))) (declare (ignore headers)) (is status 200) (is body '("Hello, you've been here for 2th times!"))))) (subtest "utf-8 session data" (let ((app (builder (:session :store (make-dbi-store :connector (lambda () *conn*))) (lambda (env) (unless (gethash :user (getf env :lack.session)) (setf (gethash :user (getf env :lack.session)) "深町英太郎")) (unless (gethash :counter (getf env :lack.session)) (setf (gethash :counter (getf env :lack.session)) 0)) `(200 (:content-type "text/plain") (,(format nil "Hello, ~A! You've been here for ~Ath times!" (gethash :user (getf env :lack.session)) (incf (gethash :counter (getf env :lack.session))))))))) session) (destructuring-bind (status headers body) (funcall app (generate-env "/")) (is status 200) (setf session (parse-lack-session headers)) (ok session) (is body '("Hello, 深町英太郎! You've been here for 1th times!"))) (destructuring-bind (status headers body) (funcall app (generate-env "/" :cookies `(("lack.session" . ,session)))) (declare (ignore headers)) (is status 200) (is body '("Hello, 深町英太郎! You've been here for 2th times!"))))) (let ((session (dbi:fetch (dbi:execute (dbi:prepare *conn* "SELECT COUNT(*) AS count FROM sessions"))))) (is (getf session :|count|) 2 "'sessions' has two records")) (dbi:disconnect *conn*) (delete-file *test-db*) (setf *conn* (dbi:connect :sqlite3 :database-name *test-db*)) ;; ;; record-timestamps t (dbi:do-sql *conn* "CREATE TABLE sessions (id CHAR(72) PRIMARY KEY, session_data TEXT, created_at DATETIME, updated_at DATETIME)") (subtest "session middleware" (let ((app (builder (:session :store (make-dbi-store :connector (lambda () *conn*) :record-timestamps t)) (lambda (env) (unless (gethash :counter (getf env :lack.session)) (setf (gethash :counter (getf env :lack.session)) 0)) `(200 (:content-type "text/plain") (,(format nil "Hello, you've been here for ~Ath times!" (incf (gethash :counter (getf env :lack.session))))))))) session now) (diag "1st request") (destructuring-bind (status headers body) (funcall app (generate-env "/")) (is status 200) (setf session (parse-lack-session headers)) (ok session) (is body '("Hello, you've been here for 1th times!"))) (let ((records (dbi:fetch-all (dbi:execute (dbi:prepare *conn* "SELECT * FROM sessions"))))) (is (length records) 1) (is (getf (first records) :|id|) session) (setf now (getf (first records) :|created_at|)) (is (getf (first records) :|updated_at|) now)) (sleep 2) (diag "2nd request") (destructuring-bind (status headers body) (funcall app (generate-env "/" :cookies `(("lack.session" . ,session)))) (declare (ignore headers)) (is status 200) (is body '("Hello, you've been here for 2th times!"))) (let ((records (dbi:fetch-all (dbi:execute (dbi:prepare *conn* "SELECT * FROM sessions"))))) (is (length records) 1) (is (getf (first records) :|id|) session) (is (getf (first records) :|created_at|) now) (isnt (getf (first records) :|updated_at|) now)))) (dbi:disconnect *conn*) (finalize)
null
https://raw.githubusercontent.com/fukamachi/lack/1f155216aeea36291b325c519f041e469262a399/t/session/store/dbi.lisp
lisp
record-timestamps t
(in-package :cl-user) (defpackage t.lack.session.store.dbi (:use :cl :lack :lack.test :lack.session.store.dbi :dbi :prove)) (in-package :t.lack.session.store.dbi) (plan 4) (defvar *test-db* (asdf:system-relative-pathname :lack "data/test.db")) (when (probe-file *test-db*) (delete-file *test-db*)) (defparameter *conn* (dbi:connect :sqlite3 :database-name *test-db*)) (dbi:do-sql *conn* "CREATE TABLE sessions (id CHAR(72) PRIMARY KEY, session_data TEXT)") (subtest "session middleware" (let ((app (builder (:session :store (make-dbi-store :connector (lambda () *conn*))) (lambda (env) (unless (gethash :counter (getf env :lack.session)) (setf (gethash :counter (getf env :lack.session)) 0)) `(200 (:content-type "text/plain") (,(format nil "Hello, you've been here for ~Ath times!" (incf (gethash :counter (getf env :lack.session))))))))) session) (diag "1st request") (destructuring-bind (status headers body) (funcall app (generate-env "/")) (is status 200) (setf session (parse-lack-session headers)) (ok session) (is body '("Hello, you've been here for 1th times!"))) (diag "2nd request") (destructuring-bind (status headers body) (funcall app (generate-env "/" :cookies `(("lack.session" . ,session)))) (declare (ignore headers)) (is status 200) (is body '("Hello, you've been here for 2th times!"))))) (subtest "utf-8 session data" (let ((app (builder (:session :store (make-dbi-store :connector (lambda () *conn*))) (lambda (env) (unless (gethash :user (getf env :lack.session)) (setf (gethash :user (getf env :lack.session)) "深町英太郎")) (unless (gethash :counter (getf env :lack.session)) (setf (gethash :counter (getf env :lack.session)) 0)) `(200 (:content-type "text/plain") (,(format nil "Hello, ~A! You've been here for ~Ath times!" (gethash :user (getf env :lack.session)) (incf (gethash :counter (getf env :lack.session))))))))) session) (destructuring-bind (status headers body) (funcall app (generate-env "/")) (is status 200) (setf session (parse-lack-session headers)) (ok session) (is body '("Hello, 深町英太郎! You've been here for 1th times!"))) (destructuring-bind (status headers body) (funcall app (generate-env "/" :cookies `(("lack.session" . ,session)))) (declare (ignore headers)) (is status 200) (is body '("Hello, 深町英太郎! You've been here for 2th times!"))))) (let ((session (dbi:fetch (dbi:execute (dbi:prepare *conn* "SELECT COUNT(*) AS count FROM sessions"))))) (is (getf session :|count|) 2 "'sessions' has two records")) (dbi:disconnect *conn*) (delete-file *test-db*) (setf *conn* (dbi:connect :sqlite3 :database-name *test-db*)) (dbi:do-sql *conn* "CREATE TABLE sessions (id CHAR(72) PRIMARY KEY, session_data TEXT, created_at DATETIME, updated_at DATETIME)") (subtest "session middleware" (let ((app (builder (:session :store (make-dbi-store :connector (lambda () *conn*) :record-timestamps t)) (lambda (env) (unless (gethash :counter (getf env :lack.session)) (setf (gethash :counter (getf env :lack.session)) 0)) `(200 (:content-type "text/plain") (,(format nil "Hello, you've been here for ~Ath times!" (incf (gethash :counter (getf env :lack.session))))))))) session now) (diag "1st request") (destructuring-bind (status headers body) (funcall app (generate-env "/")) (is status 200) (setf session (parse-lack-session headers)) (ok session) (is body '("Hello, you've been here for 1th times!"))) (let ((records (dbi:fetch-all (dbi:execute (dbi:prepare *conn* "SELECT * FROM sessions"))))) (is (length records) 1) (is (getf (first records) :|id|) session) (setf now (getf (first records) :|created_at|)) (is (getf (first records) :|updated_at|) now)) (sleep 2) (diag "2nd request") (destructuring-bind (status headers body) (funcall app (generate-env "/" :cookies `(("lack.session" . ,session)))) (declare (ignore headers)) (is status 200) (is body '("Hello, you've been here for 2th times!"))) (let ((records (dbi:fetch-all (dbi:execute (dbi:prepare *conn* "SELECT * FROM sessions"))))) (is (length records) 1) (is (getf (first records) :|id|) session) (is (getf (first records) :|created_at|) now) (isnt (getf (first records) :|updated_at|) now)))) (dbi:disconnect *conn*) (finalize)
5c909f3f5cb13fa38570b0a67d725a891c69f70eba24abf36c182d4ef018b30e
jeapostrophe/mode-lambda
main.rkt
#lang racket/base (require racket/match racket/contract/base (except-in ffi/unsafe ->) file/gunzip racket/file mode-lambda/color "core.rkt") (define (sprite-idx csd spr) (hash-ref (compiled-sprite-db-spr->idx csd) spr #f)) (define (palette-idx csd pal) (hash-ref (compiled-sprite-db-pal->idx csd) pal #f)) (define (sprite-width csd idx) (match-define (vector w h tx ty) (vector-ref (compiled-sprite-db-idx->w*h*tx*ty csd) idx)) w) (define (sprite-height csd idx) (match-define (vector w h tx ty) (vector-ref (compiled-sprite-db-idx->w*h*tx*ty csd) idx)) h) (define (read/bytes/gunzip bs) (define-values (read-v write-v-bs) (make-pipe)) (define read-v-bs/gz (open-input-bytes bs)) (gunzip-through-ports read-v-bs/gz write-v-bs) (close-output-port write-v-bs) (read read-v)) (define (load-csd/bs bs) (match-define (vector 1 spr->idx idx->w*h*tx*ty pal->idx atlas-bs atlas-size pal-bs pal-size) (read/bytes/gunzip bs)) (compiled-sprite-db atlas-size atlas-bs spr->idx idx->w*h*tx*ty pal-size pal-bs pal->idx)) (define (load-csd p) (load-csd/bs (file->bytes (build-path p "csd.rktd.gz")))) (define (sprite cx cy spr-idx #:layer [layer 0] #:r [r 0] #:g [g 0] #:b [b 0] #:a [a 1.0] #:pal-idx [pal-idx 0] #:m [m 1.0] #:mx [mx m] #:my [my m] #:theta [theta 0.0]) (make-sprite-data cx cy mx my theta a spr-idx pal-idx layer r g b)) (define (layer cx cy #:hw [hw +inf.0] #:hh [hh +inf.0] #:wrap-x? [wrap-x? #f] #:wrap-y? [wrap-y? #f] #:mx [mx 1.0] #:my [my 1.0] #:theta [theta 0.0] #:mode7 [mode7-coeff 0.0] #:horizon [horizon 0.0] #:fov [fov 1.0]) (make-layer-data cx cy hw hh mx my theta mode7-coeff horizon fov wrap-x? wrap-y?)) (provide (contract-out [PALETTE-DEPTH exact-nonnegative-integer?] [compiled-sprite-db? (-> any/c boolean?)] [load-csd/bs (-> bytes? compiled-sprite-db?)] [load-csd (-> path-string? compiled-sprite-db?)] [sprite-idx (-> compiled-sprite-db? symbol? (or/c #f ushort?))] [palette-idx (-> compiled-sprite-db? symbol? (or/c #f ushort?))] [sprite-width (-> compiled-sprite-db? ushort? ushort?)] [sprite-height (-> compiled-sprite-db? ushort? ushort?)] [sprite (->* (flonum? flonum? ushort?) (#:layer layer/c #:r byte? #:g byte? #:b byte? #:a flonum? #:pal-idx ushort? #:m flonum? #:mx flonum? #:my flonum? #:theta flonum?) sprite-data?)] [sprite-data? (-> any/c boolean?)] [sprite-data-dx (-> sprite-data? flonum?)] [sprite-data-dy (-> sprite-data? flonum?)] [sprite-data-mx (-> sprite-data? flonum?)] [sprite-data-my (-> sprite-data? flonum?)] [sprite-data-spr (-> sprite-data? ushort?)] [sprite-data-layer (-> sprite-data? byte?)] [layer (->* (flonum? flonum?) (#:hw flonum? #:hh flonum? #:wrap-x? boolean? #:wrap-y? boolean? #:mx flonum? #:my flonum? #:theta flonum? #:mode7 flonum? #:horizon flonum? #:fov flonum?) layer-data?)]))
null
https://raw.githubusercontent.com/jeapostrophe/mode-lambda/64b5ae81f457ded7664458cd9935ce7d3ebfc449/mode-lambda/main.rkt
racket
#lang racket/base (require racket/match racket/contract/base (except-in ffi/unsafe ->) file/gunzip racket/file mode-lambda/color "core.rkt") (define (sprite-idx csd spr) (hash-ref (compiled-sprite-db-spr->idx csd) spr #f)) (define (palette-idx csd pal) (hash-ref (compiled-sprite-db-pal->idx csd) pal #f)) (define (sprite-width csd idx) (match-define (vector w h tx ty) (vector-ref (compiled-sprite-db-idx->w*h*tx*ty csd) idx)) w) (define (sprite-height csd idx) (match-define (vector w h tx ty) (vector-ref (compiled-sprite-db-idx->w*h*tx*ty csd) idx)) h) (define (read/bytes/gunzip bs) (define-values (read-v write-v-bs) (make-pipe)) (define read-v-bs/gz (open-input-bytes bs)) (gunzip-through-ports read-v-bs/gz write-v-bs) (close-output-port write-v-bs) (read read-v)) (define (load-csd/bs bs) (match-define (vector 1 spr->idx idx->w*h*tx*ty pal->idx atlas-bs atlas-size pal-bs pal-size) (read/bytes/gunzip bs)) (compiled-sprite-db atlas-size atlas-bs spr->idx idx->w*h*tx*ty pal-size pal-bs pal->idx)) (define (load-csd p) (load-csd/bs (file->bytes (build-path p "csd.rktd.gz")))) (define (sprite cx cy spr-idx #:layer [layer 0] #:r [r 0] #:g [g 0] #:b [b 0] #:a [a 1.0] #:pal-idx [pal-idx 0] #:m [m 1.0] #:mx [mx m] #:my [my m] #:theta [theta 0.0]) (make-sprite-data cx cy mx my theta a spr-idx pal-idx layer r g b)) (define (layer cx cy #:hw [hw +inf.0] #:hh [hh +inf.0] #:wrap-x? [wrap-x? #f] #:wrap-y? [wrap-y? #f] #:mx [mx 1.0] #:my [my 1.0] #:theta [theta 0.0] #:mode7 [mode7-coeff 0.0] #:horizon [horizon 0.0] #:fov [fov 1.0]) (make-layer-data cx cy hw hh mx my theta mode7-coeff horizon fov wrap-x? wrap-y?)) (provide (contract-out [PALETTE-DEPTH exact-nonnegative-integer?] [compiled-sprite-db? (-> any/c boolean?)] [load-csd/bs (-> bytes? compiled-sprite-db?)] [load-csd (-> path-string? compiled-sprite-db?)] [sprite-idx (-> compiled-sprite-db? symbol? (or/c #f ushort?))] [palette-idx (-> compiled-sprite-db? symbol? (or/c #f ushort?))] [sprite-width (-> compiled-sprite-db? ushort? ushort?)] [sprite-height (-> compiled-sprite-db? ushort? ushort?)] [sprite (->* (flonum? flonum? ushort?) (#:layer layer/c #:r byte? #:g byte? #:b byte? #:a flonum? #:pal-idx ushort? #:m flonum? #:mx flonum? #:my flonum? #:theta flonum?) sprite-data?)] [sprite-data? (-> any/c boolean?)] [sprite-data-dx (-> sprite-data? flonum?)] [sprite-data-dy (-> sprite-data? flonum?)] [sprite-data-mx (-> sprite-data? flonum?)] [sprite-data-my (-> sprite-data? flonum?)] [sprite-data-spr (-> sprite-data? ushort?)] [sprite-data-layer (-> sprite-data? byte?)] [layer (->* (flonum? flonum?) (#:hw flonum? #:hh flonum? #:wrap-x? boolean? #:wrap-y? boolean? #:mx flonum? #:my flonum? #:theta flonum? #:mode7 flonum? #:horizon flonum? #:fov flonum?) layer-data?)]))
ecc4cfef17cf4a912a891425cfb38f529e8a9587551749170eec04882567e7f1
haskell-works/hw-koans
Eq.hs
module Koan.Eq where import Prelude hiding (elem, filter) enrolled :: Bool enrolled = False -- Introduction to generics filterInt :: (Int -> Bool) -> [Int] -> [Int] filterInt p (x:xs) = if p x then x:filterInt p xs else filterInt p xs filterInt _ [] = [] filterChar :: (Char -> Bool) -> [Char] -> [Char] filterChar p (x:xs) = if p x then x:filterChar p xs else filterChar p xs filterChar _ [] = [] filter :: (a -> Bool) -> [a] -> [a] filter p (x:xs) = if p x then x:filter p xs else filter p xs filter _ [] = [] -- Using the Eq typeclass elemInt :: Int -> [Int] -> Bool elemInt i (x:xs) = if i == x then True else elemInt i xs elemInt _ [] = False elem :: Eq a => a -> [a] -> Bool elem i (x:xs) = if i == x then True else elem i xs elem _ [] = False nub :: Eq a => [a] -> [a] nub xs = go xs [] where go (y:ys) rs = if y `elem` rs then go ys rs else go ys (y:rs) go [] rs = reverse rs isPrefixOf :: Eq a => [a] -> [a] -> Bool isPrefixOf [] _ = True isPrefixOf _ [] = False isPrefixOf (x:xs) (y:ys) = x == y && isPrefixOf xs ys elemIndex :: Eq a => a -> [a] -> Maybe Int elemIndex e = go 0 where go n (x:xs) = if x == e then Just n else go (n + 1) xs go _ [] = Nothing
null
https://raw.githubusercontent.com/haskell-works/hw-koans/a807e72513d91ddf1c8aa445371b94bb169f22fd/solution/Koan/Eq.hs
haskell
Introduction to generics Using the Eq typeclass
module Koan.Eq where import Prelude hiding (elem, filter) enrolled :: Bool enrolled = False filterInt :: (Int -> Bool) -> [Int] -> [Int] filterInt p (x:xs) = if p x then x:filterInt p xs else filterInt p xs filterInt _ [] = [] filterChar :: (Char -> Bool) -> [Char] -> [Char] filterChar p (x:xs) = if p x then x:filterChar p xs else filterChar p xs filterChar _ [] = [] filter :: (a -> Bool) -> [a] -> [a] filter p (x:xs) = if p x then x:filter p xs else filter p xs filter _ [] = [] elemInt :: Int -> [Int] -> Bool elemInt i (x:xs) = if i == x then True else elemInt i xs elemInt _ [] = False elem :: Eq a => a -> [a] -> Bool elem i (x:xs) = if i == x then True else elem i xs elem _ [] = False nub :: Eq a => [a] -> [a] nub xs = go xs [] where go (y:ys) rs = if y `elem` rs then go ys rs else go ys (y:rs) go [] rs = reverse rs isPrefixOf :: Eq a => [a] -> [a] -> Bool isPrefixOf [] _ = True isPrefixOf _ [] = False isPrefixOf (x:xs) (y:ys) = x == y && isPrefixOf xs ys elemIndex :: Eq a => a -> [a] -> Maybe Int elemIndex e = go 0 where go n (x:xs) = if x == e then Just n else go (n + 1) xs go _ [] = Nothing
65de57c8c4db66d4b6fddf0dd46f0acdbafa571f3a6b78db5d154640a45a97aa
haskell-mafia/mismi
Arbitrary.hs
# LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - orphans # module Test.Mismi.Kernel.Arbitrary where import Mismi.Kernel.Data import Test.QuickCheck import Test.QuickCheck.Instances () instance Arbitrary MismiRegion where arbitrary = arbitraryBoundedEnum
null
https://raw.githubusercontent.com/haskell-mafia/mismi/f6df07a52c6c8b1cf195b58d20ef109e390be014/mismi-kernel/test/Test/Mismi/Kernel/Arbitrary.hs
haskell
# LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - orphans # module Test.Mismi.Kernel.Arbitrary where import Mismi.Kernel.Data import Test.QuickCheck import Test.QuickCheck.Instances () instance Arbitrary MismiRegion where arbitrary = arbitraryBoundedEnum
00ded890a38e18902e29c3e744ccd9ef5a77ba2594a44a73cb98da3883b5b13f
mfoemmel/erlang-otp
wxGauge.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT %% @doc See external documentation: <a href="">wxGauge</a>. %% <p>This class is derived (and can use functions) from: %% <br />{@link wxControl} %% <br />{@link wxWindow} %% <br />{@link wxEvtHandler} %% </p> %% @type wxGauge(). An object reference, The representation is internal %% and can be changed without notice. It can't be used for comparsion %% stored on disc or distributed for use on other nodes. -module(wxGauge). -include("wxe.hrl"). -export([create/4,create/5,destroy/1,getBezelFace/1,getRange/1,getShadowWidth/1, getValue/1,isVertical/1,new/0,new/3,new/4,pulse/1,setBezelFace/2,setRange/2, setShadowWidth/2,setValue/2]). %% inherited exports -export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1, centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2, clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2, connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1, getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1, getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1, getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1, getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2, getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2, getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1, getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1, hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1, isExposed/2,isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1, layout/1,lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2, move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1, navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2, setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2, setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2, setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6, setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3, setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3, setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3, setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4, setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1, show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1, update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). %% @hidden parent_class(wxControl) -> true; parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). ( ) - > wxGauge ( ) %% @doc See <a href="#wxgaugewxgauge">external documentation</a>. new() -> wxe_util:construct(?wxGauge_new_0, <<>>). ( Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , ( ) ) - > wxGauge ( ) @equiv new(Parent , Id , Range , [ ] ) new(Parent,Id,Range) when is_record(Parent, wx_ref),is_integer(Id),is_integer(Range) -> new(Parent,Id,Range, []). ( Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , ( ) , [ Option ] ) - > wxGauge ( ) %% Option = {pos, {X::integer(),Y::integer()}} | {size, {W::integer(),H::integer()}} | {style, integer()} | {validator, wx:wx()} %% @doc See <a href="#wxgaugewxgauge">external documentation</a>. new(#wx_ref{type=ParentT,ref=ParentRef},Id,Range, Options) when is_integer(Id),is_integer(Range),is_list(Options) -> ?CLASS(ParentT,wxWindow), MOpts = fun({pos, {PosX,PosY}}, Acc) -> [<<1:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc]; ({size, {SizeW,SizeH}}, Acc) -> [<<2:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc]; ({style, Style}, Acc) -> [<<3:32/?UI,Style:32/?UI>>|Acc]; ({validator, #wx_ref{type=ValidatorT,ref=ValidatorRef}}, Acc) -> ?CLASS(ValidatorT,wx),[<<4:32/?UI,ValidatorRef:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:construct(?wxGauge_new_4, <<ParentRef:32/?UI,Id:32/?UI,Range:32/?UI, 0:32,BinOpt/binary>>). ( This::wxGauge ( ) , Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , ( ) ) - > bool ( ) %% @equiv create(This,Parent,Id,Range, []) create(This,Parent,Id,Range) when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id),is_integer(Range) -> create(This,Parent,Id,Range, []). ( This::wxGauge ( ) , Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , ( ) , [ Option ] ) - > bool ( ) %% Option = {pos, {X::integer(),Y::integer()}} | {size, {W::integer(),H::integer()}} | {style, integer()} | {validator, wx:wx()} %% @doc See <a href="#wxgaugecreate">external documentation</a>. create(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},Id,Range, Options) when is_integer(Id),is_integer(Range),is_list(Options) -> ?CLASS(ThisT,wxGauge), ?CLASS(ParentT,wxWindow), MOpts = fun({pos, {PosX,PosY}}, Acc) -> [<<1:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc]; ({size, {SizeW,SizeH}}, Acc) -> [<<2:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc]; ({style, Style}, Acc) -> [<<3:32/?UI,Style:32/?UI>>|Acc]; ({validator, #wx_ref{type=ValidatorT,ref=ValidatorRef}}, Acc) -> ?CLASS(ValidatorT,wx),[<<4:32/?UI,ValidatorRef:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:call(?wxGauge_Create, <<ThisRef:32/?UI,ParentRef:32/?UI,Id:32/?UI,Range:32/?UI, BinOpt/binary>>). ( This::wxGauge ( ) ) - > integer ( ) %% @doc See <a href="#wxgaugegetbezelface">external documentation</a>. getBezelFace(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_GetBezelFace, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > integer ( ) %% @doc See <a href="#wxgaugegetrange">external documentation</a>. getRange(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_GetRange, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > integer ( ) %% @doc See <a href="#wxgaugegetshadowwidth">external documentation</a>. getShadowWidth(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_GetShadowWidth, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > integer ( ) %% @doc See <a href="#wxgaugegetvalue">external documentation</a>. getValue(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_GetValue, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > bool ( ) %% @doc See <a href="#wxgaugeisvertical">external documentation</a>. isVertical(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_IsVertical, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) , W::integer ( ) ) - > ok %% @doc See <a href="#wxgaugesetbezelface">external documentation</a>. setBezelFace(#wx_ref{type=ThisT,ref=ThisRef},W) when is_integer(W) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_SetBezelFace, <<ThisRef:32/?UI,W:32/?UI>>). ( This::wxGauge ( ) , ( ) ) - > ok %% @doc See <a href="#wxgaugesetrange">external documentation</a>. setRange(#wx_ref{type=ThisT,ref=ThisRef},R) when is_integer(R) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_SetRange, <<ThisRef:32/?UI,R:32/?UI>>). ( This::wxGauge ( ) , W::integer ( ) ) - > ok %% @doc See <a href="#wxgaugesetshadowwidth">external documentation</a>. setShadowWidth(#wx_ref{type=ThisT,ref=ThisRef},W) when is_integer(W) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_SetShadowWidth, <<ThisRef:32/?UI,W:32/?UI>>). ( This::wxGauge ( ) , Pos::integer ( ) ) - > ok %% @doc See <a href="#wxgaugesetvalue">external documentation</a>. setValue(#wx_ref{type=ThisT,ref=ThisRef},Pos) when is_integer(Pos) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_SetValue, <<ThisRef:32/?UI,Pos:32/?UI>>). ( This::wxGauge ( ) ) - > ok %% @doc See <a href="#wxgaugepulse">external documentation</a>. pulse(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_Pulse, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > ok %% @doc Destroys this object, do not use object again destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxGauge), wxe_util:destroy(?DESTROY_OBJECT,Obj), ok. %% From wxControl %% @hidden setLabel(This,Label) -> wxControl:setLabel(This,Label). %% @hidden getLabel(This) -> wxControl:getLabel(This). %% From wxWindow %% @hidden warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). %% @hidden validate(This) -> wxWindow:validate(This). %% @hidden updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). %% @hidden updateWindowUI(This) -> wxWindow:updateWindowUI(This). %% @hidden update(This) -> wxWindow:update(This). %% @hidden transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). %% @hidden transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). %% @hidden thaw(This) -> wxWindow:thaw(This). %% @hidden show(This, Options) -> wxWindow:show(This, Options). %% @hidden show(This) -> wxWindow:show(This). %% @hidden shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). %% @hidden setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). %% @hidden setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). %% @hidden setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). %% @hidden setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options). %% @hidden setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH). %% @hidden setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize). %% @hidden setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y). %% @hidden setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). %% @hidden setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip). %% @hidden setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme). %% @hidden setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). %% @hidden setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). %% @hidden setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). %% @hidden setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). %% @hidden setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). %% @hidden setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). %% @hidden setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). %% @hidden setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). %% @hidden setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). %% @hidden setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). %% @hidden setSize(This,Rect) -> wxWindow:setSize(This,Rect). %% @hidden setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options). %% @hidden setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos). %% @hidden setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options). %% @hidden setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range). %% @hidden setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). %% @hidden setName(This,Name) -> wxWindow:setName(This,Name). %% @hidden setId(This,Winid) -> wxWindow:setId(This,Winid). %% @hidden setHelpText(This,Text) -> wxWindow:setHelpText(This,Text). %% @hidden setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). %% @hidden setFont(This,Font) -> wxWindow:setFont(This,Font). %% @hidden setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). %% @hidden setFocus(This) -> wxWindow:setFocus(This). %% @hidden setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). %% @hidden setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget). %% @hidden setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). %% @hidden setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). %% @hidden setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). %% @hidden setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize). %% @hidden setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize). %% @hidden setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). %% @hidden setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). %% @hidden setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). %% @hidden setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). %% @hidden setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). %% @hidden setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). %% @hidden setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). %% @hidden setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). %% @hidden setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). %% @hidden scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). %% @hidden scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). %% @hidden scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). %% @hidden scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). %% @hidden screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). %% @hidden screenToClient(This) -> wxWindow:screenToClient(This). %% @hidden reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). %% @hidden removeChild(This,Child) -> wxWindow:removeChild(This,Child). %% @hidden releaseMouse(This) -> wxWindow:releaseMouse(This). %% @hidden refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). %% @hidden refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). %% @hidden refresh(This, Options) -> wxWindow:refresh(This, Options). %% @hidden refresh(This) -> wxWindow:refresh(This). %% @hidden raise(This) -> wxWindow:raise(This). %% @hidden popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). %% @hidden popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). %% @hidden popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). %% @hidden popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options). %% @hidden popEventHandler(This) -> wxWindow:popEventHandler(This). %% @hidden pageUp(This) -> wxWindow:pageUp(This). %% @hidden pageDown(This) -> wxWindow:pageDown(This). %% @hidden navigate(This, Options) -> wxWindow:navigate(This, Options). %% @hidden navigate(This) -> wxWindow:navigate(This). %% @hidden moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). %% @hidden moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). %% @hidden move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). %% @hidden move(This,X,Y) -> wxWindow:move(This,X,Y). %% @hidden move(This,Pt) -> wxWindow:move(This,Pt). %% @hidden makeModal(This, Options) -> wxWindow:makeModal(This, Options). %% @hidden makeModal(This) -> wxWindow:makeModal(This). %% @hidden lower(This) -> wxWindow:lower(This). %% @hidden lineUp(This) -> wxWindow:lineUp(This). %% @hidden lineDown(This) -> wxWindow:lineDown(This). %% @hidden layout(This) -> wxWindow:layout(This). %% @hidden isTopLevel(This) -> wxWindow:isTopLevel(This). %% @hidden isShown(This) -> wxWindow:isShown(This). %% @hidden isRetained(This) -> wxWindow:isRetained(This). %% @hidden isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). %% @hidden isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). %% @hidden isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). %% @hidden isEnabled(This) -> wxWindow:isEnabled(This). %% @hidden invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). %% @hidden initDialog(This) -> wxWindow:initDialog(This). %% @hidden inheritAttributes(This) -> wxWindow:inheritAttributes(This). %% @hidden hide(This) -> wxWindow:hide(This). %% @hidden hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). %% @hidden hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). %% @hidden hasCapture(This) -> wxWindow:hasCapture(This). %% @hidden getWindowVariant(This) -> wxWindow:getWindowVariant(This). %% @hidden getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). %% @hidden getVirtualSize(This) -> wxWindow:getVirtualSize(This). %% @hidden getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). %% @hidden getToolTip(This) -> wxWindow:getToolTip(This). %% @hidden getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). %% @hidden getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). %% @hidden getSizer(This) -> wxWindow:getSizer(This). %% @hidden getSize(This) -> wxWindow:getSize(This). %% @hidden getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient). %% @hidden getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient). %% @hidden getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient). %% @hidden getScreenRect(This) -> wxWindow:getScreenRect(This). %% @hidden getScreenPosition(This) -> wxWindow:getScreenPosition(This). %% @hidden getRect(This) -> wxWindow:getRect(This). %% @hidden getPosition(This) -> wxWindow:getPosition(This). %% @hidden getParent(This) -> wxWindow:getParent(This). %% @hidden getName(This) -> wxWindow:getName(This). %% @hidden getMinSize(This) -> wxWindow:getMinSize(This). %% @hidden getMaxSize(This) -> wxWindow:getMaxSize(This). %% @hidden getId(This) -> wxWindow:getId(This). %% @hidden getHelpText(This) -> wxWindow:getHelpText(This). %% @hidden getHandle(This) -> wxWindow:getHandle(This). %% @hidden getGrandParent(This) -> wxWindow:getGrandParent(This). %% @hidden getForegroundColour(This) -> wxWindow:getForegroundColour(This). %% @hidden getFont(This) -> wxWindow:getFont(This). %% @hidden getExtraStyle(This) -> wxWindow:getExtraStyle(This). %% @hidden getEventHandler(This) -> wxWindow:getEventHandler(This). %% @hidden getDropTarget(This) -> wxWindow:getDropTarget(This). %% @hidden getCursor(This) -> wxWindow:getCursor(This). %% @hidden getContainingSizer(This) -> wxWindow:getContainingSizer(This). %% @hidden getClientSize(This) -> wxWindow:getClientSize(This). %% @hidden getChildren(This) -> wxWindow:getChildren(This). %% @hidden getCharWidth(This) -> wxWindow:getCharWidth(This). %% @hidden getCharHeight(This) -> wxWindow:getCharHeight(This). %% @hidden getCaret(This) -> wxWindow:getCaret(This). %% @hidden getBestSize(This) -> wxWindow:getBestSize(This). %% @hidden getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). %% @hidden getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). %% @hidden getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). %% @hidden freeze(This) -> wxWindow:freeze(This). %% @hidden fitInside(This) -> wxWindow:fitInside(This). %% @hidden fit(This) -> wxWindow:fit(This). %% @hidden findWindow(This,Winid) -> wxWindow:findWindow(This,Winid). %% @hidden enable(This, Options) -> wxWindow:enable(This, Options). %% @hidden enable(This) -> wxWindow:enable(This). %% @hidden disable(This) -> wxWindow:disable(This). %% @hidden destroyChildren(This) -> wxWindow:destroyChildren(This). %% @hidden convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). %% @hidden convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). %% @hidden close(This, Options) -> wxWindow:close(This, Options). %% @hidden close(This) -> wxWindow:close(This). %% @hidden clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). %% @hidden clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). %% @hidden clearBackground(This) -> wxWindow:clearBackground(This). %% @hidden centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). %% @hidden centreOnParent(This) -> wxWindow:centreOnParent(This). %% @hidden centre(This, Options) -> wxWindow:centre(This, Options). %% @hidden centre(This) -> wxWindow:centre(This). %% @hidden centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). %% @hidden centerOnParent(This) -> wxWindow:centerOnParent(This). %% @hidden center(This, Options) -> wxWindow:center(This, Options). %% @hidden center(This) -> wxWindow:center(This). %% @hidden captureMouse(This) -> wxWindow:captureMouse(This). %% @hidden cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). %% From wxEvtHandler %% @hidden disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). %% @hidden disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). %% @hidden disconnect(This) -> wxEvtHandler:disconnect(This). %% @hidden connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). %% @hidden connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxGauge.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT @doc See external documentation: <a href="">wxGauge</a>. <p>This class is derived (and can use functions) from: <br />{@link wxControl} <br />{@link wxWindow} <br />{@link wxEvtHandler} </p> @type wxGauge(). An object reference, The representation is internal and can be changed without notice. It can't be used for comparsion stored on disc or distributed for use on other nodes. inherited exports @hidden @doc See <a href="#wxgaugewxgauge">external documentation</a>. Option = {pos, {X::integer(),Y::integer()}} | {size, {W::integer(),H::integer()}} | {style, integer()} | {validator, wx:wx()} @doc See <a href="#wxgaugewxgauge">external documentation</a>. @equiv create(This,Parent,Id,Range, []) Option = {pos, {X::integer(),Y::integer()}} | {size, {W::integer(),H::integer()}} | {style, integer()} | {validator, wx:wx()} @doc See <a href="#wxgaugecreate">external documentation</a>. @doc See <a href="#wxgaugegetbezelface">external documentation</a>. @doc See <a href="#wxgaugegetrange">external documentation</a>. @doc See <a href="#wxgaugegetshadowwidth">external documentation</a>. @doc See <a href="#wxgaugegetvalue">external documentation</a>. @doc See <a href="#wxgaugeisvertical">external documentation</a>. @doc See <a href="#wxgaugesetbezelface">external documentation</a>. @doc See <a href="#wxgaugesetrange">external documentation</a>. @doc See <a href="#wxgaugesetshadowwidth">external documentation</a>. @doc See <a href="#wxgaugesetvalue">external documentation</a>. @doc See <a href="#wxgaugepulse">external documentation</a>. @doc Destroys this object, do not use object again From wxControl @hidden @hidden From wxWindow @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden From wxEvtHandler @hidden @hidden @hidden @hidden @hidden
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(wxGauge). -include("wxe.hrl"). -export([create/4,create/5,destroy/1,getBezelFace/1,getRange/1,getShadowWidth/1, getValue/1,isVertical/1,new/0,new/3,new/4,pulse/1,setBezelFace/2,setRange/2, setShadowWidth/2,setValue/2]). -export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1, centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2, clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2, connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1, getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1, getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1, getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1, getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2, getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2, getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1, getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1, hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1, isExposed/2,isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1, layout/1,lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2, move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1, navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2, setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2, setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2, setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6, setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3, setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3, setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3, setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4, setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1, show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1, update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). parent_class(wxControl) -> true; parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). ( ) - > wxGauge ( ) new() -> wxe_util:construct(?wxGauge_new_0, <<>>). ( Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , ( ) ) - > wxGauge ( ) @equiv new(Parent , Id , Range , [ ] ) new(Parent,Id,Range) when is_record(Parent, wx_ref),is_integer(Id),is_integer(Range) -> new(Parent,Id,Range, []). ( Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , ( ) , [ Option ] ) - > wxGauge ( ) new(#wx_ref{type=ParentT,ref=ParentRef},Id,Range, Options) when is_integer(Id),is_integer(Range),is_list(Options) -> ?CLASS(ParentT,wxWindow), MOpts = fun({pos, {PosX,PosY}}, Acc) -> [<<1:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc]; ({size, {SizeW,SizeH}}, Acc) -> [<<2:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc]; ({style, Style}, Acc) -> [<<3:32/?UI,Style:32/?UI>>|Acc]; ({validator, #wx_ref{type=ValidatorT,ref=ValidatorRef}}, Acc) -> ?CLASS(ValidatorT,wx),[<<4:32/?UI,ValidatorRef:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:construct(?wxGauge_new_4, <<ParentRef:32/?UI,Id:32/?UI,Range:32/?UI, 0:32,BinOpt/binary>>). ( This::wxGauge ( ) , Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , ( ) ) - > bool ( ) create(This,Parent,Id,Range) when is_record(This, wx_ref),is_record(Parent, wx_ref),is_integer(Id),is_integer(Range) -> create(This,Parent,Id,Range, []). ( This::wxGauge ( ) , Parent::wxWindow : wxWindow ( ) , Id::integer ( ) , ( ) , [ Option ] ) - > bool ( ) create(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef},Id,Range, Options) when is_integer(Id),is_integer(Range),is_list(Options) -> ?CLASS(ThisT,wxGauge), ?CLASS(ParentT,wxWindow), MOpts = fun({pos, {PosX,PosY}}, Acc) -> [<<1:32/?UI,PosX:32/?UI,PosY:32/?UI,0:32>>|Acc]; ({size, {SizeW,SizeH}}, Acc) -> [<<2:32/?UI,SizeW:32/?UI,SizeH:32/?UI,0:32>>|Acc]; ({style, Style}, Acc) -> [<<3:32/?UI,Style:32/?UI>>|Acc]; ({validator, #wx_ref{type=ValidatorT,ref=ValidatorRef}}, Acc) -> ?CLASS(ValidatorT,wx),[<<4:32/?UI,ValidatorRef:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:call(?wxGauge_Create, <<ThisRef:32/?UI,ParentRef:32/?UI,Id:32/?UI,Range:32/?UI, BinOpt/binary>>). ( This::wxGauge ( ) ) - > integer ( ) getBezelFace(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_GetBezelFace, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > integer ( ) getRange(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_GetRange, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > integer ( ) getShadowWidth(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_GetShadowWidth, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > integer ( ) getValue(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_GetValue, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > bool ( ) isVertical(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:call(?wxGauge_IsVertical, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) , W::integer ( ) ) - > ok setBezelFace(#wx_ref{type=ThisT,ref=ThisRef},W) when is_integer(W) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_SetBezelFace, <<ThisRef:32/?UI,W:32/?UI>>). ( This::wxGauge ( ) , ( ) ) - > ok setRange(#wx_ref{type=ThisT,ref=ThisRef},R) when is_integer(R) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_SetRange, <<ThisRef:32/?UI,R:32/?UI>>). ( This::wxGauge ( ) , W::integer ( ) ) - > ok setShadowWidth(#wx_ref{type=ThisT,ref=ThisRef},W) when is_integer(W) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_SetShadowWidth, <<ThisRef:32/?UI,W:32/?UI>>). ( This::wxGauge ( ) , Pos::integer ( ) ) - > ok setValue(#wx_ref{type=ThisT,ref=ThisRef},Pos) when is_integer(Pos) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_SetValue, <<ThisRef:32/?UI,Pos:32/?UI>>). ( This::wxGauge ( ) ) - > ok pulse(#wx_ref{type=ThisT,ref=ThisRef}) -> ?CLASS(ThisT,wxGauge), wxe_util:cast(?wxGauge_Pulse, <<ThisRef:32/?UI>>). ( This::wxGauge ( ) ) - > ok destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxGauge), wxe_util:destroy(?DESTROY_OBJECT,Obj), ok. setLabel(This,Label) -> wxControl:setLabel(This,Label). getLabel(This) -> wxControl:getLabel(This). warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). validate(This) -> wxWindow:validate(This). updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). updateWindowUI(This) -> wxWindow:updateWindowUI(This). update(This) -> wxWindow:update(This). transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). thaw(This) -> wxWindow:thaw(This). show(This, Options) -> wxWindow:show(This, Options). show(This) -> wxWindow:show(This). shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options). setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH). setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize). setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y). setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip). setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme). setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). setSize(This,Rect) -> wxWindow:setSize(This,Rect). setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options). setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos). setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options). setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range). setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). setName(This,Name) -> wxWindow:setName(This,Name). setId(This,Winid) -> wxWindow:setId(This,Winid). setHelpText(This,Text) -> wxWindow:setHelpText(This,Text). setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). setFont(This,Font) -> wxWindow:setFont(This,Font). setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). setFocus(This) -> wxWindow:setFocus(This). setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget). setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize). setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize). setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). screenToClient(This) -> wxWindow:screenToClient(This). reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). removeChild(This,Child) -> wxWindow:removeChild(This,Child). releaseMouse(This) -> wxWindow:releaseMouse(This). refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). refresh(This, Options) -> wxWindow:refresh(This, Options). refresh(This) -> wxWindow:refresh(This). raise(This) -> wxWindow:raise(This). popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options). popEventHandler(This) -> wxWindow:popEventHandler(This). pageUp(This) -> wxWindow:pageUp(This). pageDown(This) -> wxWindow:pageDown(This). navigate(This, Options) -> wxWindow:navigate(This, Options). navigate(This) -> wxWindow:navigate(This). moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). move(This,X,Y) -> wxWindow:move(This,X,Y). move(This,Pt) -> wxWindow:move(This,Pt). makeModal(This, Options) -> wxWindow:makeModal(This, Options). makeModal(This) -> wxWindow:makeModal(This). lower(This) -> wxWindow:lower(This). lineUp(This) -> wxWindow:lineUp(This). lineDown(This) -> wxWindow:lineDown(This). layout(This) -> wxWindow:layout(This). isTopLevel(This) -> wxWindow:isTopLevel(This). isShown(This) -> wxWindow:isShown(This). isRetained(This) -> wxWindow:isRetained(This). isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). isEnabled(This) -> wxWindow:isEnabled(This). invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). initDialog(This) -> wxWindow:initDialog(This). inheritAttributes(This) -> wxWindow:inheritAttributes(This). hide(This) -> wxWindow:hide(This). hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). hasCapture(This) -> wxWindow:hasCapture(This). getWindowVariant(This) -> wxWindow:getWindowVariant(This). getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). getVirtualSize(This) -> wxWindow:getVirtualSize(This). getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). getToolTip(This) -> wxWindow:getToolTip(This). getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). getSizer(This) -> wxWindow:getSizer(This). getSize(This) -> wxWindow:getSize(This). getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient). getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient). getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient). getScreenRect(This) -> wxWindow:getScreenRect(This). getScreenPosition(This) -> wxWindow:getScreenPosition(This). getRect(This) -> wxWindow:getRect(This). getPosition(This) -> wxWindow:getPosition(This). getParent(This) -> wxWindow:getParent(This). getName(This) -> wxWindow:getName(This). getMinSize(This) -> wxWindow:getMinSize(This). getMaxSize(This) -> wxWindow:getMaxSize(This). getId(This) -> wxWindow:getId(This). getHelpText(This) -> wxWindow:getHelpText(This). getHandle(This) -> wxWindow:getHandle(This). getGrandParent(This) -> wxWindow:getGrandParent(This). getForegroundColour(This) -> wxWindow:getForegroundColour(This). getFont(This) -> wxWindow:getFont(This). getExtraStyle(This) -> wxWindow:getExtraStyle(This). getEventHandler(This) -> wxWindow:getEventHandler(This). getDropTarget(This) -> wxWindow:getDropTarget(This). getCursor(This) -> wxWindow:getCursor(This). getContainingSizer(This) -> wxWindow:getContainingSizer(This). getClientSize(This) -> wxWindow:getClientSize(This). getChildren(This) -> wxWindow:getChildren(This). getCharWidth(This) -> wxWindow:getCharWidth(This). getCharHeight(This) -> wxWindow:getCharHeight(This). getCaret(This) -> wxWindow:getCaret(This). getBestSize(This) -> wxWindow:getBestSize(This). getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). freeze(This) -> wxWindow:freeze(This). fitInside(This) -> wxWindow:fitInside(This). fit(This) -> wxWindow:fit(This). findWindow(This,Winid) -> wxWindow:findWindow(This,Winid). enable(This, Options) -> wxWindow:enable(This, Options). enable(This) -> wxWindow:enable(This). disable(This) -> wxWindow:disable(This). destroyChildren(This) -> wxWindow:destroyChildren(This). convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). close(This, Options) -> wxWindow:close(This, Options). close(This) -> wxWindow:close(This). clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). clearBackground(This) -> wxWindow:clearBackground(This). centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). centreOnParent(This) -> wxWindow:centreOnParent(This). centre(This, Options) -> wxWindow:centre(This, Options). centre(This) -> wxWindow:centre(This). centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). centerOnParent(This) -> wxWindow:centerOnParent(This). center(This, Options) -> wxWindow:center(This, Options). center(This) -> wxWindow:center(This). captureMouse(This) -> wxWindow:captureMouse(This). cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). disconnect(This) -> wxEvtHandler:disconnect(This). connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
156a52e67f5f2886d017f3bc395ea12dcfcbe8902edf48595b8e7bace2d190e8
vdaas/vald-client-clj
stream_get_object.clj
(ns vald-client-clj.command.stream-get-object (:require [clojure.tools.cli :as cli] [clojure.string :as string] [clojure.edn :as edn] [vald-client-clj.core :as vald] [vald-client-clj.util :as util])) (def cli-options [["-h" "--help" :id :help?] ["-j" "--json" "read and write as json" :id :json?] [nil "--elapsed-time" "show elapsed time the request took" :id :elapsed-time?] ["-t" "--threads THREADS" "Number of threads" :id :threads :default 1 :parse-fn #(Integer/parseInt %) :validate [pos? "Must be positive number"]]]) (defn usage [summary] (->> ["Usage: valdcli [OPTIONS] stream-get-object [SUBOPTIONS] IDs" "" "Get object info of multiple IDs." "" "Sub Options:" summary ""] (string/join "\n"))) (defn run [client args] (let [parsed-result (cli/parse-opts args cli-options) {:keys [options summary arguments]} parsed-result {:keys [help? json? elapsed-time? threads]} options read-string (if json? util/read-json edn/read-string) writer (if json? (comp println util/->json) (comp println util/->edn))] (if help? (-> summary (usage) (println)) (let [ids (-> (or (first arguments) (util/read-from-stdin)) (read-string)) idss (partition-all (/ (count ids) threads) ids) f (fn [ids] (-> client (vald/stream-get-object writer ids) (deref))) res (->> (if elapsed-time? (time (doall (pmap f idss))) (doall (pmap f idss))) (apply merge-with (fn [x y] (if (and (number? x) (number? y)) (+ x y) x))))] (when (:error res) (throw (:error res)))))))
null
https://raw.githubusercontent.com/vdaas/vald-client-clj/a26bfb6229bd2582d282023beee7f4dc2fabea46/cmd/vald_client_clj/command/stream_get_object.clj
clojure
(ns vald-client-clj.command.stream-get-object (:require [clojure.tools.cli :as cli] [clojure.string :as string] [clojure.edn :as edn] [vald-client-clj.core :as vald] [vald-client-clj.util :as util])) (def cli-options [["-h" "--help" :id :help?] ["-j" "--json" "read and write as json" :id :json?] [nil "--elapsed-time" "show elapsed time the request took" :id :elapsed-time?] ["-t" "--threads THREADS" "Number of threads" :id :threads :default 1 :parse-fn #(Integer/parseInt %) :validate [pos? "Must be positive number"]]]) (defn usage [summary] (->> ["Usage: valdcli [OPTIONS] stream-get-object [SUBOPTIONS] IDs" "" "Get object info of multiple IDs." "" "Sub Options:" summary ""] (string/join "\n"))) (defn run [client args] (let [parsed-result (cli/parse-opts args cli-options) {:keys [options summary arguments]} parsed-result {:keys [help? json? elapsed-time? threads]} options read-string (if json? util/read-json edn/read-string) writer (if json? (comp println util/->json) (comp println util/->edn))] (if help? (-> summary (usage) (println)) (let [ids (-> (or (first arguments) (util/read-from-stdin)) (read-string)) idss (partition-all (/ (count ids) threads) ids) f (fn [ids] (-> client (vald/stream-get-object writer ids) (deref))) res (->> (if elapsed-time? (time (doall (pmap f idss))) (doall (pmap f idss))) (apply merge-with (fn [x y] (if (and (number? x) (number? y)) (+ x y) x))))] (when (:error res) (throw (:error res)))))))
e03fe1e85e6921980a84c3728aac1db98fece99b1c6a839876e82bce8d6e14a8
ptal/AbSolute
sat_interpretation.mli
Copyright 2019 This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 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 Lesser General Public License for more details . This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 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 Lesser General Public License for more details. *) open Typing.Tast open Domains.Interpretation module type Sat_interpretation_sig = sig type rconstraint = Minisatml.Types.Lit.lit Minisatml.Vec.t include module type of (Interpretation_ground( struct type var_id=Minisatml.Solver.var end)) val exact_interpretation: bool * Create a set of clauses from a formula . The formula is rewritten into CNF . The formula is rewritten into CNF. *) val interpret: t -> approx_kind -> tformula -> t * rconstraint list (** See [Interpretation.to_tqformula] *) val to_qformula: t -> rconstraint list -> tqformula end module Sat_interpretation: Sat_interpretation_sig
null
https://raw.githubusercontent.com/ptal/AbSolute/469159d87e3a717499573c1e187e5cfa1b569829/src/domains/sat/sat_interpretation.mli
ocaml
* See [Interpretation.to_tqformula]
Copyright 2019 This program is free software ; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 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 Lesser General Public License for more details . This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 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 Lesser General Public License for more details. *) open Typing.Tast open Domains.Interpretation module type Sat_interpretation_sig = sig type rconstraint = Minisatml.Types.Lit.lit Minisatml.Vec.t include module type of (Interpretation_ground( struct type var_id=Minisatml.Solver.var end)) val exact_interpretation: bool * Create a set of clauses from a formula . The formula is rewritten into CNF . The formula is rewritten into CNF. *) val interpret: t -> approx_kind -> tformula -> t * rconstraint list val to_qformula: t -> rconstraint list -> tqformula end module Sat_interpretation: Sat_interpretation_sig
e54465d117326b0be282f34a2b385ab5be86c492a21e53c019f5c8203c4c731d
inhabitedtype/ocaml-aws
deregisterManagedInstance.ml
open Types open Aws type input = DeregisterManagedInstanceRequest.t type output = unit type error = Errors_internal.t let service = "ssm" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2014-11-06" ]; "Action", [ "DeregisterManagedInstance" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (DeregisterManagedInstanceRequest.to_query req))))) in `POST, uri, [] let of_http body = `Ok () let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/3bc554af7ae7ef9e2dcea44a1b72c9e687435fa9/libraries/ssm/lib/deregisterManagedInstance.ml
ocaml
open Types open Aws type input = DeregisterManagedInstanceRequest.t type output = unit type error = Errors_internal.t let service = "ssm" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2014-11-06" ]; "Action", [ "DeregisterManagedInstance" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (DeregisterManagedInstanceRequest.to_query req))))) in `POST, uri, [] let of_http body = `Ok () let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
e8aed99abf230c41d3d4a89fe707fdd7db1ee3c99fd6b0ac7f928bb1016f3aec
mrkkrp/ghc-syntax-highlighter
Forall.hs
x :: forall a. a x = undefined
null
https://raw.githubusercontent.com/mrkkrp/ghc-syntax-highlighter/201eebf10b96f1c382669c69cc1a1cefb07cc897/data/Forall.hs
haskell
x :: forall a. a x = undefined
c4241c20b45d59342d12d455e74c87eb7dd0020c47a191ced5514b8dcc89eecb
Element84/clj-gdal
repl-session.clj
(gdal/init) (def data-dir "test/data/l8") (def scene-id "LC80290302015263LGN00") (def tiff-file (format "%s/%s/%s_B2.TIF" data-dir scene-id scene-id)) (def tiff-data (gdal/open tiff-file)) (dataset/get-size tiff-data) (dataset/count-bands tiff-data) (def band-data (dataset/get-band tiff-data 1)) (band/get-checksum band-data) (def proj-data (dataset/get-projection tiff-data)) (proj/get-name proj-data) (proj/get-ids proj-data) (:code-space (proj/get-id proj-data)) (:code (proj/get-id proj-data)) (proj/get-datum proj-data) (proj/get-datum-name proj-data) (proj/get-ellipsoid proj-data) (proj/get-ellipsoid-name proj-data) (proj/get-eccentricity proj-data) (proj/get-prime-meridian proj-data) (proj/get-bw-params proj-data) (proj/get-coord-system proj-data) (proj/get-coord-name proj-data) (proj/get-coord-dim proj-data) (proj/get-axes proj-data) (proj/get-axis proj-data 1) (proj/get-axis-name proj-data 1) (proj/get-axis-unit proj-data 1)
null
https://raw.githubusercontent.com/Element84/clj-gdal/7e3ded6935d8b06c49e90be911ca9648b5a84205/examples/repl-session.clj
clojure
(gdal/init) (def data-dir "test/data/l8") (def scene-id "LC80290302015263LGN00") (def tiff-file (format "%s/%s/%s_B2.TIF" data-dir scene-id scene-id)) (def tiff-data (gdal/open tiff-file)) (dataset/get-size tiff-data) (dataset/count-bands tiff-data) (def band-data (dataset/get-band tiff-data 1)) (band/get-checksum band-data) (def proj-data (dataset/get-projection tiff-data)) (proj/get-name proj-data) (proj/get-ids proj-data) (:code-space (proj/get-id proj-data)) (:code (proj/get-id proj-data)) (proj/get-datum proj-data) (proj/get-datum-name proj-data) (proj/get-ellipsoid proj-data) (proj/get-ellipsoid-name proj-data) (proj/get-eccentricity proj-data) (proj/get-prime-meridian proj-data) (proj/get-bw-params proj-data) (proj/get-coord-system proj-data) (proj/get-coord-name proj-data) (proj/get-coord-dim proj-data) (proj/get-axes proj-data) (proj/get-axis proj-data 1) (proj/get-axis-name proj-data 1) (proj/get-axis-unit proj-data 1)