_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
5cc792b3ebcd59a5809b04451c77551863faec13c588d9150c29f1f1a57332c3
grasswire/chat-app
CommonSpec.hs
module Handler.CommonSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "health check" $ do it "gives a 200" $ do get HealthCheckR statusIs 200
null
https://raw.githubusercontent.com/grasswire/chat-app/a8ae4e782cacd902d7ec9c68c40a939cc5cabb0a/backend/test/Handler/CommonSpec.hs
haskell
module Handler.CommonSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "health check" $ do it "gives a 200" $ do get HealthCheckR statusIs 200
ff2973253934da4844c67633c9eefb12be5c5220eb38ac153c22f88ee20cf2a8
clojure-interop/google-cloud-clients
SecurityCenterClient$ListFindingsPage.clj
(ns com.google.cloud.securitycenter.v1.SecurityCenterClient$ListFindingsPage (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.securitycenter.v1 SecurityCenterClient$ListFindingsPage])) (defn create-page-async "context - `com.google.api.gax.rpc.PageContext` future-response - `com.google.api.core.ApiFuture` returns: `com.google.api.core.ApiFuture<com.google.cloud.securitycenter.v1.SecurityCenterClient$ListFindingsPage>`" (^com.google.api.core.ApiFuture [^SecurityCenterClient$ListFindingsPage this ^com.google.api.gax.rpc.PageContext context ^com.google.api.core.ApiFuture future-response] (-> this (.createPageAsync context future-response))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.securitycenter/src/com/google/cloud/securitycenter/v1/SecurityCenterClient%24ListFindingsPage.clj
clojure
(ns com.google.cloud.securitycenter.v1.SecurityCenterClient$ListFindingsPage (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.securitycenter.v1 SecurityCenterClient$ListFindingsPage])) (defn create-page-async "context - `com.google.api.gax.rpc.PageContext` future-response - `com.google.api.core.ApiFuture` returns: `com.google.api.core.ApiFuture<com.google.cloud.securitycenter.v1.SecurityCenterClient$ListFindingsPage>`" (^com.google.api.core.ApiFuture [^SecurityCenterClient$ListFindingsPage this ^com.google.api.gax.rpc.PageContext context ^com.google.api.core.ApiFuture future-response] (-> this (.createPageAsync context future-response))))
17971e221e3ab873d85d029c8e4336a42a67610ef46e4c265deba2cabbec89bc
ucsd-progsys/liquidhaskell
CyclicTypeAlias0.hs
@ LIQUID " --expect - error - containing = Cyclic type alias definition for ` CyclicA1 ` " @ module CyclicTypeAlias0 () where @ type CyclicA1 = CyclicA2 @ @ type CyclicA2 = CyclicA1 @
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/errors/CyclicTypeAlias0.hs
haskell
@ LIQUID " --expect - error - containing = Cyclic type alias definition for ` CyclicA1 ` " @ module CyclicTypeAlias0 () where @ type CyclicA1 = CyclicA2 @ @ type CyclicA2 = CyclicA1 @
c8853bb5b653bc220b803e44b6fd850780597b923b03165f2280d8297f6240c8
compiling-to-categories/concat
FFT.hs
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # {-# LANGUAGE GADTs #-} # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE ParallelListComp #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE TypeApplications # {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE UndecidableInstances # -- experiment -- {-# LANGUAGE PartialTypeSignatures #-} # OPTIONS_GHC -Wall # { - # OPTIONS_GHC -fno - warn - unused - imports # - } -- TEMP -- #define TESTING #ifdef TESTING # OPTIONS_GHC -fno - warn - unused - binds # #endif # define ---------------------------------------------------------------------- -- | Generic FFT ---------------------------------------------------------------------- module ConCat.FFT ( dft, FFT(..), DFTTy, genericFft, GFFT -- -- Temporary while debugging , twiddle, twiddles, omega, cis , o8sq ) where import Prelude hiding (zipWith) import Data.Complex import Control . Applicative ( liftA2 ) import GHC.Generics hiding (C,S) import Data.Key (Zip(..)) import Data.Pointed #ifdef TESTING import Data.Foldable (toList) import Test . QuickCheck ( quickCheck ) import Test.QuickCheck.All (quickCheckAll) import ShapedTypes.ApproxEq #endif import ConCat.Misc (Unop,transpose,C,inGeneric1,inComp) import ConCat.Sized import ConCat.Scan (LScan,lproducts) import ConCat.Pair import ConCat.Free.LinearRow (($*)) {-------------------------------------------------------------------- DFT --------------------------------------------------------------------} type AS h = (Pointed h, Zip h, LScan h) type ASZ h = (AS h, Sized h) -- To resolve: Zip vs Applicative. traverse/transpose needs Applicative. dft :: forall f a. (ASZ f, Foldable f, RealFloat a) => Unop (f (Complex a)) dft xs = omegas (size @f) $* xs # INLINE dft # omegas :: (AS f, AS g, RealFloat a) => Int -> g (f (Complex a)) omegas = fmap powers . powers . omega -- omegas n = powers <$> powers (omega n) omegas n = powers < $ > powers ( exp ( - i * 2 * pi / fromIntegral n ) ) # INLINE omegas # omegas' :: forall f g a. (ASZ f, ASZ g, RealFloat a) => g (f (Complex a)) omegas' = fmap powers (powers (cis (- 2 * pi / fromIntegral (size @(g :.: f))))) i : : a = > Complex a i = 0 : + 1 omega :: RealFloat a => Int -> Complex a omega n = cis (- 2 * pi / fromIntegral n) -- omega n = exp (0 :+ (- 2 * pi / fromIntegral n)) -- omega n = exp (- 2 * (0:+1) * pi / fromIntegral n) # INLINE omega # ------------------------------------------------------------------- FFT ------------------------------------------------------------------- FFT --------------------------------------------------------------------} type DFTTy f = forall a. RealFloat a => f (Complex a) -> FFO f (Complex a) class FFT f where type FFO f :: * -> * fft :: DFTTy f default fft : : ( Generic1 f , Generic1 ( FFO f ) , FFT ( Rep1 f ) , FFO ( Rep1 f ) ~ Rep1 ( FFO f ) ) = > DFTTy f -- fft = genericFft -- Temporary hack to avoid newtype-like representation. fftDummy :: f a fftDummy = undefined -- TODO: Eliminate FFO, in favor of fft :: Unop (f (Complex a)). -- Use dft as spec. twiddle :: forall g f a. (ASZ g, ASZ f, RealFloat a) => Unop (g (f (Complex a))) -- twiddle = (zipWith.zipWith) (*) twiddles twiddle = (zipWith.zipWith) (*) omegas' twiddle = ( zipWith.zipWith ) ( * ) ( ( size @(g : . : f ) ) ) # INLINE twiddle # twiddles :: forall g f a. (ASZ g, ASZ f, RealFloat a) => g (f (Complex a)) twiddles = omegas (size @(g :.: f)) # INLINE twiddles # o8sq :: C o8sq = omega (8 :: Int) ^ (2 :: Int) Powers of x , starting x^0 . Uses ' LScan ' for log parallel time powers :: (LScan f, Pointed f, Num a) => a -> f a powers = fst . lproducts . point # INLINE powers # -- TODO: Consolidate with powers in TreeTest and rename sensibly. Maybe use -- "In" and "Ex" suffixes to distinguish inclusive and exclusive cases. {-------------------------------------------------------------------- Generic support --------------------------------------------------------------------} instance FFT Par1 where type FFO Par1 = Par1 fft = id #if 0 inTranspose :: (Traversable f', Traversable g, Applicative g', Applicative f) => (f (g a) -> f' (g' a)) -> g (f a) -> g' (f' a) inTranspose = transpose <-- transpose ffts' :: ( FFT g, Traversable f, Traversable g , Applicative (FFO g), Applicative f, RealFloat a) => g (f (Complex a)) -> FFO g (f (Complex a)) ffts' = transpose . fmap fft . transpose #endif #if 0 transpose :: g (f C) -> f (g C) fmap fft :: f (g C) -> f (FFO g C) transpose :: f (FFO g C) -> FFO g (f C) #endif instance ( Zip f, Traversable f , Traversable g , Applicative f, Applicative (FFO f), Applicative (FFO g), Zip (FFO g) , Pointed f, Traversable (FFO g), Pointed (FFO g) , FFT f, FFT g, LScan f, LScan (FFO g), Sized f, Sized (FFO g) ) => FFT (g :.: f) where type FFO (g :.: f) = FFO f :.: FFO g fft = inComp (traverse fft . twiddle . traverse fft . transpose) fft = inComp ( ffts ' . transpose . twiddle . ' ) # INLINE fft # #if 0 fft = Comp1 . transpose . fmap fft . twiddle . transpose . fmap fft . transpose . unComp1 fft = Comp1 . traverse fft . twiddle . traverse fft . transpose . unComp1 -- Types in fft for (g :. f): unComp1 :: (g :. f) a -> g (f a) transpose :: g (f a) -> f (g a) fmap fft :: f (g a) -> f (g' a) transpose :: f (g' a) -> g' (f a) twiddle :: g' (f a) -> g' (f a) fmap fft :: g' (f a) -> g' (f' a) transpose :: g' (f' a) -> f' (g' a) Comp1 :: f' (g' a) -> (f' :. g') a #endif #if 0 fft = inComp ( ffts ' . transpose . twiddle . ' ) ffts' :: g (f C) -> FFO g (f C) twiddle :: FFO g (f C) -> FFO g (f C) transpose :: FFO g (f C) -> f (FFO g C) ffts' :: f (FFO g C) -> FFO f (FFO g C) #endif -- -- Generalization of 'dft' to traversables. Note that liftA2 should -- -- work zippily (unlike with lists). dftT : : forall f a. ( ASZ f , , RealFloat a ) -- => Unop (f (Complex a)) -- dftT xs = out <$> indices -- where out k = sum ( liftA2 ( \ n x - > x * ok^n ) indices xs ) where ok = om ^ k -- indices = fst iota :: f Int = omega ( size @f ) -- {-# INLINE dftT #-} -- | Generic FFT genericFft :: ( Generic1 f, Generic1 (FFO f) , FFT (Rep1 f), FFO (Rep1 f) ~ Rep1 (FFO f) ) => DFTTy f genericFft = inGeneric1 fft type GFFT f = (Generic1 f, Generic1 (FFO f), FFT (Rep1 f), FFO (Rep1 f) ~ Rep1 (FFO f)) #define GenericFFT(f,g) instance GFFT (f) => FFT (f) where { type FFO (f) = (g); fft = genericFft } # define GenericFFT(f , ) instance ( f ) = > FFT ( f ) where { type FFO ( f ) = g ; INLINE } -- TODO: Replace Applicative with Zippable. Ca n't , because needs Applicative . Perhaps dftT is n't very useful . Its result and argument types match , unlike fft . {-------------------------------------------------------------------- Specialized FFT instances. --------------------------------------------------------------------} -- I put the specific instances here in order to avoid an import loop between the LPow and RPow modules . I 'd still like to find an elegant FFT that maps f to f , and then move the instances to RPow and LPow . -- Radix 2 butterfly instance FFT Pair where type FFO Pair = Pair -- bogus "non-exhaustive" warning in ghc 8.0.2 -- fft (a :# b) = (a + b) :# (a - b) fft = \ (a :# b) -> (a + b) :# (a - b) -- fft = dft # INLINE fft # #ifdef TESTING #if 0 twiddles :: (ASZ g, ASZ f, RealFloat a) => g (f (Complex a)) as :: f C (<.> as) :: f C -> C twiddles :: f (f C) (<.> as) <$> twiddles :: f C #endif -- -- Binary dot product infixl 7 < . > ( < . > ) : : ( Foldable f , Applicative f , a ) = > f a - > f a - > a -- u <.> v = sum (liftA2 (*) u v) ------------------------------------------------------------------- Simple , quadratic DFT ( for specification & testing ) ------------------------------------------------------------------- Simple, quadratic DFT (for specification & testing) --------------------------------------------------------------------} Adapted from 's definition dftL :: RealFloat a => Unop [Complex a] dftL xs = [ sum [ x * ok^n | x <- xs | n <- [0 :: Int ..] ] | k <- [0 .. length xs - 1], let ok = om ^ k ] where om = omega (length xs) {-------------------------------------------------------------------- Tests --------------------------------------------------------------------} > powers 2 : : B ( B ( L ( ( 1 : # 2 ) : # ( 4 : # 8) ) ) ) > powers 2 : : B ( B ( B ( L ( ( ( 1 : # 2 ) : # ( 4 : # 8) ) : # ( ( 16 : # 32 ) : # ( 64 : # 128 ) ) ) ) ) ) fftl :: (FFT f, Foldable (FFO f), RealFloat a) => f (Complex a) -> [Complex a] fftl = toList . fft type LTree = L.Pow Pair type RTree = R.Pow Pair type LC n = LTree n C type RC n = RTree n C p1 :: Pair C p1 = 1 :# 0 tw1 :: LTree N1 (Pair C) tw1 = twiddles tw2 :: RTree N2 (Pair C) tw2 = twiddles tw3 :: RTree N2 (RTree N2 C) tw3 = twiddles tw3' :: [[C]] tw3' = toList (toList <$> tw3) Adapted from 's testing test : : ( FFT f , Foldable f , Foldable ( FFO f ) ) = > f C - > IO ( ) -- test fx = -- do ps "\nTesting input" xs -- ps "Expected output" (dftL xs) -- ps "Actual output " (toList (fft fx)) -- where ps label z = ( label + + " : " + + show z ) #if 0 t0 :: LC N0 t0 = L.fromList [1] t1 :: LC N1 t1 = L.fromList [1, 0] t2s :: [LC N2] t2s = L.fromList <$> Delta , [1, 1, 1, 1] -- Constant , [1, 0, -1, 0] -- Fundamental , [0, 1, 0, -1] -- Fundamental w/ 90-deg. phase lag ] tests :: IO () tests = do test p1 test t0 test t1 mapM_ test t2s #endif infix 4 === (===) :: Eq b => (a -> b) -> (a -> b) -> a -> Bool (f === g) x = f x == g x infix 4 =~= (=~=) :: ApproxEq b => (a -> b) -> (a -> b) -> a -> Bool (f =~= g) x = f x =~ g x fftIsDftL :: (FFT f, Foldable f, Foldable (FFO f), RealFloat a, ApproxEq a) => f (Complex a) -> Bool fftIsDftL = toList . fft =~= dftL . toList dftTIsDftL :: (ASZ f, Traversable f, RealFloat a, ApproxEq a) => f (Complex a) -> Bool dftTIsDftL = toList . dftT =~= dftL . toList dftIsDftL :: (ASZ f, Foldable f, RealFloat a, ApproxEq a) => f (Complex a) -> Bool dftIsDftL = toList . dft =~= dftL . toList -- -- TEMP: dftDft : : ( ASZ f , , RealFloat a , ApproxEq a ) = > -- f (Complex a) -> ([Complex a], [Complex a]) dftDft xs = ( toList . dft $ xs , dftL . toList $ xs ) {-------------------------------------------------------------------- Properties to test --------------------------------------------------------------------} transposeTwiddleCommutes :: (ASZ g, Traversable g, ASZ f, (ApproxEq (f (g C)))) => g (f C) -> Bool transposeTwiddleCommutes = twiddle . transpose =~= transpose . twiddle prop_transposeTwiddle_L3P :: LTree N3 (Pair C) -> Bool prop_transposeTwiddle_L3P = transposeTwiddleCommutes prop_transposeTwiddle_R3P :: RTree N3 (Pair C) -> Bool prop_transposeTwiddle_R3P = transposeTwiddleCommutes -- dft tests fail. Hm! prop_dft_R3 : : Bool -- prop_dft_R3 = dftIsDftL prop_dft_L3 : : Bool -- prop_dft_L3 = dftIsDftL prop_dftT_p :: Pair C -> Bool prop_dftT_p = dftTIsDftL prop_dftT_L3 :: LTree N3 C -> Bool prop_dftT_L3 = dftTIsDftL prop_dftT_R3 :: RTree N3 C -> Bool prop_dftT_R3 = dftTIsDftL prop_fft_p :: Pair C -> Bool prop_fft_p = fftIsDftL prop_fft_L1 :: LTree N1 C -> Bool prop_fft_L1 = fftIsDftL prop_fft_L2 :: LTree N2 C -> Bool prop_fft_L2 = fftIsDftL prop_fft_L3 :: LTree N3 C -> Bool prop_fft_L3 = fftIsDftL prop_fft_L4 :: LTree N4 C -> Bool prop_fft_L4 = fftIsDftL prop_fft_R1 :: RTree N1 C -> Bool prop_fft_R1 = fftIsDftL prop_fft_R2 :: RTree N2 C -> Bool prop_fft_R2 = fftIsDftL prop_fft_R3 :: RTree N3 C -> Bool prop_fft_R3 = fftIsDftL prop_fft_R4 :: RTree N4 C -> Bool prop_fft_R4 = fftIsDftL -- TH oddity return [] runTests :: IO Bool runTests = $quickCheckAll -- end of tests #endif
null
https://raw.githubusercontent.com/compiling-to-categories/concat/49e554856576245f583dfd2484e5f7c19f688028/examples/src/ConCat/FFT.hs
haskell
# LANGUAGE CPP # # LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE DefaultSignatures # # LANGUAGE FlexibleContexts # # LANGUAGE GADTs # # LANGUAGE ParallelListComp # # LANGUAGE PartialTypeSignatures # # LANGUAGE PatternGuards # # LANGUAGE Rank2Types # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeOperators # # LANGUAGE TypeFamilies # # LANGUAGE TypeSynonymInstances # experiment {-# LANGUAGE PartialTypeSignatures #-} TEMP #define TESTING -------------------------------------------------------------------- | Generic FFT -------------------------------------------------------------------- -- Temporary while debugging ------------------------------------------------------------------- DFT ------------------------------------------------------------------- To resolve: Zip vs Applicative. traverse/transpose needs Applicative. omegas n = powers <$> powers (omega n) omega n = exp (0 :+ (- 2 * pi / fromIntegral n)) omega n = exp (- 2 * (0:+1) * pi / fromIntegral n) ----------------------------------------------------------------- ----------------------------------------------------------------- ------------------------------------------------------------------} fft = genericFft Temporary hack to avoid newtype-like representation. TODO: Eliminate FFO, in favor of fft :: Unop (f (Complex a)). Use dft as spec. twiddle = (zipWith.zipWith) (*) twiddles TODO: Consolidate with powers in TreeTest and rename sensibly. Maybe use "In" and "Ex" suffixes to distinguish inclusive and exclusive cases. ------------------------------------------------------------------- Generic support ------------------------------------------------------------------- transpose Types in fft for (g :. f): -- Generalization of 'dft' to traversables. Note that liftA2 should -- work zippily (unlike with lists). => Unop (f (Complex a)) dftT xs = out <$> indices where indices = fst iota :: f Int {-# INLINE dftT #-} | Generic FFT TODO: Replace Applicative with Zippable. ------------------------------------------------------------------- Specialized FFT instances. ------------------------------------------------------------------- I put the specific instances here in order to avoid an import loop between Radix 2 butterfly bogus "non-exhaustive" warning in ghc 8.0.2 fft (a :# b) = (a + b) :# (a - b) fft = dft -- Binary dot product u <.> v = sum (liftA2 (*) u v) ----------------------------------------------------------------- ----------------------------------------------------------------- ------------------------------------------------------------------} ------------------------------------------------------------------- Tests ------------------------------------------------------------------- test fx = do ps "\nTesting input" xs ps "Expected output" (dftL xs) ps "Actual output " (toList (fft fx)) where Constant Fundamental Fundamental w/ 90-deg. phase lag -- TEMP: f (Complex a) -> ([Complex a], [Complex a]) ------------------------------------------------------------------- Properties to test ------------------------------------------------------------------- dft tests fail. Hm! prop_dft_R3 = dftIsDftL prop_dft_L3 = dftIsDftL TH oddity end of tests
# LANGUAGE FlexibleInstances # # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TypeApplications # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -Wall # #ifdef TESTING # OPTIONS_GHC -fno - warn - unused - binds # #endif # define module ConCat.FFT ( dft, FFT(..), DFTTy, genericFft, GFFT , twiddle, twiddles, omega, cis , o8sq ) where import Prelude hiding (zipWith) import Data.Complex import Control . Applicative ( liftA2 ) import GHC.Generics hiding (C,S) import Data.Key (Zip(..)) import Data.Pointed #ifdef TESTING import Data.Foldable (toList) import Test . QuickCheck ( quickCheck ) import Test.QuickCheck.All (quickCheckAll) import ShapedTypes.ApproxEq #endif import ConCat.Misc (Unop,transpose,C,inGeneric1,inComp) import ConCat.Sized import ConCat.Scan (LScan,lproducts) import ConCat.Pair import ConCat.Free.LinearRow (($*)) type AS h = (Pointed h, Zip h, LScan h) type ASZ h = (AS h, Sized h) dft :: forall f a. (ASZ f, Foldable f, RealFloat a) => Unop (f (Complex a)) dft xs = omegas (size @f) $* xs # INLINE dft # omegas :: (AS f, AS g, RealFloat a) => Int -> g (f (Complex a)) omegas = fmap powers . powers . omega omegas n = powers < $ > powers ( exp ( - i * 2 * pi / fromIntegral n ) ) # INLINE omegas # omegas' :: forall f g a. (ASZ f, ASZ g, RealFloat a) => g (f (Complex a)) omegas' = fmap powers (powers (cis (- 2 * pi / fromIntegral (size @(g :.: f))))) i : : a = > Complex a i = 0 : + 1 omega :: RealFloat a => Int -> Complex a omega n = cis (- 2 * pi / fromIntegral n) # INLINE omega # FFT FFT type DFTTy f = forall a. RealFloat a => f (Complex a) -> FFO f (Complex a) class FFT f where type FFO f :: * -> * fft :: DFTTy f default fft : : ( Generic1 f , Generic1 ( FFO f ) , FFT ( Rep1 f ) , FFO ( Rep1 f ) ~ Rep1 ( FFO f ) ) = > DFTTy f fftDummy :: f a fftDummy = undefined twiddle :: forall g f a. (ASZ g, ASZ f, RealFloat a) => Unop (g (f (Complex a))) twiddle = (zipWith.zipWith) (*) omegas' twiddle = ( zipWith.zipWith ) ( * ) ( ( size @(g : . : f ) ) ) # INLINE twiddle # twiddles :: forall g f a. (ASZ g, ASZ f, RealFloat a) => g (f (Complex a)) twiddles = omegas (size @(g :.: f)) # INLINE twiddles # o8sq :: C o8sq = omega (8 :: Int) ^ (2 :: Int) Powers of x , starting x^0 . Uses ' LScan ' for log parallel time powers :: (LScan f, Pointed f, Num a) => a -> f a powers = fst . lproducts . point # INLINE powers # instance FFT Par1 where type FFO Par1 = Par1 fft = id #if 0 inTranspose :: (Traversable f', Traversable g, Applicative g', Applicative f) => (f (g a) -> f' (g' a)) -> g (f a) -> g' (f' a) ffts' :: ( FFT g, Traversable f, Traversable g , Applicative (FFO g), Applicative f, RealFloat a) => g (f (Complex a)) -> FFO g (f (Complex a)) ffts' = transpose . fmap fft . transpose #endif #if 0 transpose :: g (f C) -> f (g C) fmap fft :: f (g C) -> f (FFO g C) transpose :: f (FFO g C) -> FFO g (f C) #endif instance ( Zip f, Traversable f , Traversable g , Applicative f, Applicative (FFO f), Applicative (FFO g), Zip (FFO g) , Pointed f, Traversable (FFO g), Pointed (FFO g) , FFT f, FFT g, LScan f, LScan (FFO g), Sized f, Sized (FFO g) ) => FFT (g :.: f) where type FFO (g :.: f) = FFO f :.: FFO g fft = inComp (traverse fft . twiddle . traverse fft . transpose) fft = inComp ( ffts ' . transpose . twiddle . ' ) # INLINE fft # #if 0 fft = Comp1 . transpose . fmap fft . twiddle . transpose . fmap fft . transpose . unComp1 fft = Comp1 . traverse fft . twiddle . traverse fft . transpose . unComp1 unComp1 :: (g :. f) a -> g (f a) transpose :: g (f a) -> f (g a) fmap fft :: f (g a) -> f (g' a) transpose :: f (g' a) -> g' (f a) twiddle :: g' (f a) -> g' (f a) fmap fft :: g' (f a) -> g' (f' a) transpose :: g' (f' a) -> f' (g' a) Comp1 :: f' (g' a) -> (f' :. g') a #endif #if 0 fft = inComp ( ffts ' . transpose . twiddle . ' ) ffts' :: g (f C) -> FFO g (f C) twiddle :: FFO g (f C) -> FFO g (f C) transpose :: FFO g (f C) -> f (FFO g C) ffts' :: f (FFO g C) -> FFO f (FFO g C) #endif dftT : : forall f a. ( ASZ f , , RealFloat a ) out k = sum ( liftA2 ( \ n x - > x * ok^n ) indices xs ) where ok = om ^ k = omega ( size @f ) genericFft :: ( Generic1 f, Generic1 (FFO f) , FFT (Rep1 f), FFO (Rep1 f) ~ Rep1 (FFO f) ) => DFTTy f genericFft = inGeneric1 fft type GFFT f = (Generic1 f, Generic1 (FFO f), FFT (Rep1 f), FFO (Rep1 f) ~ Rep1 (FFO f)) #define GenericFFT(f,g) instance GFFT (f) => FFT (f) where { type FFO (f) = (g); fft = genericFft } # define GenericFFT(f , ) instance ( f ) = > FFT ( f ) where { type FFO ( f ) = g ; INLINE } Ca n't , because needs Applicative . Perhaps dftT is n't very useful . Its result and argument types match , unlike fft . the LPow and RPow modules . I 'd still like to find an elegant FFT that maps f to f , and then move the instances to RPow and LPow . instance FFT Pair where type FFO Pair = Pair fft = \ (a :# b) -> (a + b) :# (a - b) # INLINE fft # #ifdef TESTING #if 0 twiddles :: (ASZ g, ASZ f, RealFloat a) => g (f (Complex a)) as :: f C (<.> as) :: f C -> C twiddles :: f (f C) (<.> as) <$> twiddles :: f C #endif infixl 7 < . > ( < . > ) : : ( Foldable f , Applicative f , a ) = > f a - > f a - > a Simple , quadratic DFT ( for specification & testing ) Simple, quadratic DFT (for specification & testing) Adapted from 's definition dftL :: RealFloat a => Unop [Complex a] dftL xs = [ sum [ x * ok^n | x <- xs | n <- [0 :: Int ..] ] | k <- [0 .. length xs - 1], let ok = om ^ k ] where om = omega (length xs) > powers 2 : : B ( B ( L ( ( 1 : # 2 ) : # ( 4 : # 8) ) ) ) > powers 2 : : B ( B ( B ( L ( ( ( 1 : # 2 ) : # ( 4 : # 8) ) : # ( ( 16 : # 32 ) : # ( 64 : # 128 ) ) ) ) ) ) fftl :: (FFT f, Foldable (FFO f), RealFloat a) => f (Complex a) -> [Complex a] fftl = toList . fft type LTree = L.Pow Pair type RTree = R.Pow Pair type LC n = LTree n C type RC n = RTree n C p1 :: Pair C p1 = 1 :# 0 tw1 :: LTree N1 (Pair C) tw1 = twiddles tw2 :: RTree N2 (Pair C) tw2 = twiddles tw3 :: RTree N2 (RTree N2 C) tw3 = twiddles tw3' :: [[C]] tw3' = toList (toList <$> tw3) Adapted from 's testing test : : ( FFT f , Foldable f , Foldable ( FFO f ) ) = > f C - > IO ( ) ps label z = ( label + + " : " + + show z ) #if 0 t0 :: LC N0 t0 = L.fromList [1] t1 :: LC N1 t1 = L.fromList [1, 0] t2s :: [LC N2] t2s = L.fromList <$> Delta ] tests :: IO () tests = do test p1 test t0 test t1 mapM_ test t2s #endif infix 4 === (===) :: Eq b => (a -> b) -> (a -> b) -> a -> Bool (f === g) x = f x == g x infix 4 =~= (=~=) :: ApproxEq b => (a -> b) -> (a -> b) -> a -> Bool (f =~= g) x = f x =~ g x fftIsDftL :: (FFT f, Foldable f, Foldable (FFO f), RealFloat a, ApproxEq a) => f (Complex a) -> Bool fftIsDftL = toList . fft =~= dftL . toList dftTIsDftL :: (ASZ f, Traversable f, RealFloat a, ApproxEq a) => f (Complex a) -> Bool dftTIsDftL = toList . dftT =~= dftL . toList dftIsDftL :: (ASZ f, Foldable f, RealFloat a, ApproxEq a) => f (Complex a) -> Bool dftIsDftL = toList . dft =~= dftL . toList dftDft : : ( ASZ f , , RealFloat a , ApproxEq a ) = > dftDft xs = ( toList . dft $ xs , dftL . toList $ xs ) transposeTwiddleCommutes :: (ASZ g, Traversable g, ASZ f, (ApproxEq (f (g C)))) => g (f C) -> Bool transposeTwiddleCommutes = twiddle . transpose =~= transpose . twiddle prop_transposeTwiddle_L3P :: LTree N3 (Pair C) -> Bool prop_transposeTwiddle_L3P = transposeTwiddleCommutes prop_transposeTwiddle_R3P :: RTree N3 (Pair C) -> Bool prop_transposeTwiddle_R3P = transposeTwiddleCommutes prop_dft_R3 : : Bool prop_dft_L3 : : Bool prop_dftT_p :: Pair C -> Bool prop_dftT_p = dftTIsDftL prop_dftT_L3 :: LTree N3 C -> Bool prop_dftT_L3 = dftTIsDftL prop_dftT_R3 :: RTree N3 C -> Bool prop_dftT_R3 = dftTIsDftL prop_fft_p :: Pair C -> Bool prop_fft_p = fftIsDftL prop_fft_L1 :: LTree N1 C -> Bool prop_fft_L1 = fftIsDftL prop_fft_L2 :: LTree N2 C -> Bool prop_fft_L2 = fftIsDftL prop_fft_L3 :: LTree N3 C -> Bool prop_fft_L3 = fftIsDftL prop_fft_L4 :: LTree N4 C -> Bool prop_fft_L4 = fftIsDftL prop_fft_R1 :: RTree N1 C -> Bool prop_fft_R1 = fftIsDftL prop_fft_R2 :: RTree N2 C -> Bool prop_fft_R2 = fftIsDftL prop_fft_R3 :: RTree N3 C -> Bool prop_fft_R3 = fftIsDftL prop_fft_R4 :: RTree N4 C -> Bool prop_fft_R4 = fftIsDftL return [] runTests :: IO Bool runTests = $quickCheckAll #endif
b025a0c73778d52c7284de7e3fa2bbce688124fc7667809a92586d3329696d42
haskell/fgl
GVD.hs
( c ) 2000 - 2005 by [ see file COPYRIGHT ] -- | Graph Voronoi Diagram -- -- These functions can be used to create a /shortest path forest/ -- where the roots are specified. module Data.Graph.Inductive.Query.GVD ( Voronoi,LRTree, gvdIn,gvdOut, voronoiSet,nearestNode,nearestDist,nearestPath, -- vd,nn,ns, vdO , nnO , nsO ) where import Data.List (nub) import Data.Maybe (listToMaybe) import qualified Data.Graph.Inductive.Internal.Heap as H import Data.Graph.Inductive.Basic import Data.Graph.Inductive.Graph import Data.Graph.Inductive.Internal.RootPath import Data.Graph.Inductive.Query.SP (dijkstra) -- | Representation of a shortest path forest. type Voronoi a = LRTree a -- | Produce a shortest path forest (the roots of which are those nodes specified ) from nodes in the graph /to/ one of the root -- nodes (if possible). gvdIn :: (DynGraph gr, Real b) => [Node] -> gr a b -> Voronoi b gvdIn vs g = gvdOut vs (grev g) -- | Produce a shortest path forest (the roots of which are those nodes specified ) from nodes in the graph /from/ one of the root -- nodes (if possible). gvdOut :: (Graph gr, Real b) => [Node] -> gr a b -> Voronoi b gvdOut vs = dijkstra (H.build (zip (repeat 0) (map (\v->LP [(v,0)]) vs))) -- | Return the nodes reachable to/from (depending on how the ' ' was constructed ) from the specified root node ( if the -- specified node is not one of the root nodes of the shortest path -- forest, an empty list will be returned). voronoiSet :: Node -> Voronoi b -> [Node] voronoiSet v = nub . concat . filter (\p->last p==v) . map (map fst . unLPath) | Try to construct a path to / from a specified node to one of the -- root nodes of the shortest path forest. maybePath :: Node -> Voronoi b -> Maybe (LPath b) maybePath v = listToMaybe . filter ((v==) . fst . head . unLPath) | Try to determine the nearest root node to the one specified in the -- shortest path forest. nearestNode :: Node -> Voronoi b -> Maybe Node nearestNode v = fmap (fst . last . unLPath) . maybePath v -- | The distance to the 'nearestNode' (if there is one) in the -- shortest path forest. nearestDist :: Node -> Voronoi b -> Maybe b nearestDist v = fmap (snd . head . unLPath) . maybePath v | Try to construct a path to / from a specified node to one of the -- root nodes of the shortest path forest. nearestPath :: Node -> Voronoi b -> Maybe Path nearestPath v = fmap (map fst . unLPath) . maybePath v vd = gvdIn [ 4,5 ] vor vdO = gvdOut [ 4,5 ] vor nn = map ( flip nearestNode vd ) [ 1 .. 8 ] nnO = map ( flip nearestNode vdO ) [ 1 .. 8 ] ns = map ( flip voronoiSet vd ) [ 1 .. 8 ] nsO = map ( flip voronoiSet vdO ) [ 1 .. 8 ]
null
https://raw.githubusercontent.com/haskell/fgl/86dc04d2ae9ca73a0923bdc8d78b53bf2f2876c8/Data/Graph/Inductive/Query/GVD.hs
haskell
| Graph Voronoi Diagram These functions can be used to create a /shortest path forest/ where the roots are specified. vd,nn,ns, | Representation of a shortest path forest. | Produce a shortest path forest (the roots of which are those nodes (if possible). | Produce a shortest path forest (the roots of which are those nodes (if possible). | Return the nodes reachable to/from (depending on how the specified node is not one of the root nodes of the shortest path forest, an empty list will be returned). root nodes of the shortest path forest. shortest path forest. | The distance to the 'nearestNode' (if there is one) in the shortest path forest. root nodes of the shortest path forest.
( c ) 2000 - 2005 by [ see file COPYRIGHT ] module Data.Graph.Inductive.Query.GVD ( Voronoi,LRTree, gvdIn,gvdOut, voronoiSet,nearestNode,nearestDist,nearestPath, vdO , nnO , nsO ) where import Data.List (nub) import Data.Maybe (listToMaybe) import qualified Data.Graph.Inductive.Internal.Heap as H import Data.Graph.Inductive.Basic import Data.Graph.Inductive.Graph import Data.Graph.Inductive.Internal.RootPath import Data.Graph.Inductive.Query.SP (dijkstra) type Voronoi a = LRTree a nodes specified ) from nodes in the graph /to/ one of the root gvdIn :: (DynGraph gr, Real b) => [Node] -> gr a b -> Voronoi b gvdIn vs g = gvdOut vs (grev g) nodes specified ) from nodes in the graph /from/ one of the root gvdOut :: (Graph gr, Real b) => [Node] -> gr a b -> Voronoi b gvdOut vs = dijkstra (H.build (zip (repeat 0) (map (\v->LP [(v,0)]) vs))) ' ' was constructed ) from the specified root node ( if the voronoiSet :: Node -> Voronoi b -> [Node] voronoiSet v = nub . concat . filter (\p->last p==v) . map (map fst . unLPath) | Try to construct a path to / from a specified node to one of the maybePath :: Node -> Voronoi b -> Maybe (LPath b) maybePath v = listToMaybe . filter ((v==) . fst . head . unLPath) | Try to determine the nearest root node to the one specified in the nearestNode :: Node -> Voronoi b -> Maybe Node nearestNode v = fmap (fst . last . unLPath) . maybePath v nearestDist :: Node -> Voronoi b -> Maybe b nearestDist v = fmap (snd . head . unLPath) . maybePath v | Try to construct a path to / from a specified node to one of the nearestPath :: Node -> Voronoi b -> Maybe Path nearestPath v = fmap (map fst . unLPath) . maybePath v vd = gvdIn [ 4,5 ] vor vdO = gvdOut [ 4,5 ] vor nn = map ( flip nearestNode vd ) [ 1 .. 8 ] nnO = map ( flip nearestNode vdO ) [ 1 .. 8 ] ns = map ( flip voronoiSet vd ) [ 1 .. 8 ] nsO = map ( flip voronoiSet vdO ) [ 1 .. 8 ]
f9402fcebc09d4f1a83802dbb7c0f8d133495743b61c70c7258cb5e72adf768a
anik545/OwlPPL
test_evaluation.ml
(* Module to test the evaluation module - hypothesis tests and kl divergence *) open Ppl open Core open Core *) let test_kl_discrete () = () let test_kl_continuous () = () let test_ks () = () let test_chisq () = () let tests : unit Alcotest.test list = [ ("discrete kl-div", [ ("", `Quick, test_kl_continuous) ]); ("continuous kl-div", [ ("", `Quick, test_kl_discrete) ]); ("ks test statistic", [ ("", `Quick, test_ks) ]); ("chi-sq test statistic", [ ("", `Quick, test_kl_discrete) ]); ]
null
https://raw.githubusercontent.com/anik545/OwlPPL/ad650219769d5f32564cc771d63c9a52289043a5/ppl/test/unit_tests/test_evaluation.ml
ocaml
Module to test the evaluation module - hypothesis tests and kl divergence
open Ppl open Core open Core *) let test_kl_discrete () = () let test_kl_continuous () = () let test_ks () = () let test_chisq () = () let tests : unit Alcotest.test list = [ ("discrete kl-div", [ ("", `Quick, test_kl_continuous) ]); ("continuous kl-div", [ ("", `Quick, test_kl_discrete) ]); ("ks test statistic", [ ("", `Quick, test_ks) ]); ("chi-sq test statistic", [ ("", `Quick, test_kl_discrete) ]); ]
56959f89bf5a8ea81b1b67c8a338c093989cd881a7a614475fe09daf69120ac4
synduce/Synduce
exists_equal_elems.ml
* @synduce -s 2 -NB --no - lifting --se2gis type two_list = TwoLists of list * list and list = | Elt of int | Cons of int * list (* Invariant: sorted in decreasing order. *) let rec is_sorted = function | TwoLists (x, y) -> is_sorted_l x && is_sorted_l y and is_sorted_l = function | Elt x -> true | Cons (hd, tl) -> aux hd tl and aux prev = function | Elt x -> prev >= x | Cons (hd, tl) -> prev >= hd && aux hd tl ;; (* Reference function in quadratic time. *) let rec is_intersection_nonempty = function | TwoLists (x, y) -> seek_common_elt x y and seek_common_elt y = function | Elt a -> find a y | Cons (hd, tl) -> find hd y || is_intersection_nonempty (TwoLists (tl, y)) and find a = function | Elt b -> b = a | Cons (hd, tl) -> hd = a || find a tl ;; Target assumes that lsits are sorted and takes advantage of it . let rec target = function | TwoLists (x, y) -> seek x y [@@requires is_sorted] and seek y = function | Elt a -> find2 a y | Cons (hd, tl) -> aux hd tl y and aux a l = function | Elt b -> a = b | Cons (b, l2) -> if a < b then target (TwoLists (Cons (b, l2), l)) else target (TwoLists (l2, Cons (a, l))) and find2 a = function | Elt b -> [%synt base_case] | Cons (hd, tl) -> if a > hd then [%synt fstop] else [%synt fcontinue] ;; assert (target = is_intersection_nonempty)
null
https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/sortedlist/exists_equal_elems.ml
ocaml
Invariant: sorted in decreasing order. Reference function in quadratic time.
* @synduce -s 2 -NB --no - lifting --se2gis type two_list = TwoLists of list * list and list = | Elt of int | Cons of int * list let rec is_sorted = function | TwoLists (x, y) -> is_sorted_l x && is_sorted_l y and is_sorted_l = function | Elt x -> true | Cons (hd, tl) -> aux hd tl and aux prev = function | Elt x -> prev >= x | Cons (hd, tl) -> prev >= hd && aux hd tl ;; let rec is_intersection_nonempty = function | TwoLists (x, y) -> seek_common_elt x y and seek_common_elt y = function | Elt a -> find a y | Cons (hd, tl) -> find hd y || is_intersection_nonempty (TwoLists (tl, y)) and find a = function | Elt b -> b = a | Cons (hd, tl) -> hd = a || find a tl ;; Target assumes that lsits are sorted and takes advantage of it . let rec target = function | TwoLists (x, y) -> seek x y [@@requires is_sorted] and seek y = function | Elt a -> find2 a y | Cons (hd, tl) -> aux hd tl y and aux a l = function | Elt b -> a = b | Cons (b, l2) -> if a < b then target (TwoLists (Cons (b, l2), l)) else target (TwoLists (l2, Cons (a, l))) and find2 a = function | Elt b -> [%synt base_case] | Cons (hd, tl) -> if a > hd then [%synt fstop] else [%synt fcontinue] ;; assert (target = is_intersection_nonempty)
ed3e4aaedeb53db8e61427397f143b839e3cb3b28aff9b28ec63fa91d96899fc
ashleylwatson/HaskellsCastle
Player.hs
# LANGUAGE TemplateHaskell # module Player ( Player(..), -- Character Storage [Room] plch,rooms, remOptOnRoom, -- Location -> Room -> Room RoomOption - > Room - > Room RoomOption - > Room - > Room remOpt, -- Location -> Player -> Player RoomOption - > Player - > Player RoomOption - > Player - > Player ) where import CharacUtil import SelectSystem import Battle import Rooms import Control.Lens import Control.Monad import Data.List data Player = P {_plch :: Character ,_rooms :: [Room]} deriving (Show, Read) makeLenses ''Player instance Mortal Player where name = plch . characterName hp = plch . characterHp xp = plch . characterXp belt = plch . characterBelt remOptOnRoom :: Location -> Room -> Room remOptOnRoom location [] = [] remOptOnRoom location (o:os) | location == view loc o = os | otherwise = o : remOptOnRoom location os addOptOnRoom :: RoomOption -> Room -> Room addOptOnRoom option room = sortOn (view loc) $ option : room replOptOnRoom :: RoomOption -> Room -> Room replOptOnRoom option = addOptOnRoom option . remOptOnRoom (option ^. loc) remOpt :: Location -> Player -> Player remOpt = over rooms . (inject . remOptOnRoom <*> view roomNum) addOpt :: RoomOption -> Player -> Player addOpt = over rooms . (inject . addOptOnRoom <*> view (loc . roomNum)) replOpt :: RoomOption -> Player -> Player replOpt option = addOpt option . remOpt (option ^. loc)
null
https://raw.githubusercontent.com/ashleylwatson/HaskellsCastle/26e35a2beacfb317733900946572111d6feac0a7/src/Player.hs
haskell
Character Storage [Room] Location -> Room -> Room Location -> Player -> Player
# LANGUAGE TemplateHaskell # module Player ( plch,rooms, RoomOption - > Room - > Room RoomOption - > Room - > Room RoomOption - > Player - > Player RoomOption - > Player - > Player ) where import CharacUtil import SelectSystem import Battle import Rooms import Control.Lens import Control.Monad import Data.List data Player = P {_plch :: Character ,_rooms :: [Room]} deriving (Show, Read) makeLenses ''Player instance Mortal Player where name = plch . characterName hp = plch . characterHp xp = plch . characterXp belt = plch . characterBelt remOptOnRoom :: Location -> Room -> Room remOptOnRoom location [] = [] remOptOnRoom location (o:os) | location == view loc o = os | otherwise = o : remOptOnRoom location os addOptOnRoom :: RoomOption -> Room -> Room addOptOnRoom option room = sortOn (view loc) $ option : room replOptOnRoom :: RoomOption -> Room -> Room replOptOnRoom option = addOptOnRoom option . remOptOnRoom (option ^. loc) remOpt :: Location -> Player -> Player remOpt = over rooms . (inject . remOptOnRoom <*> view roomNum) addOpt :: RoomOption -> Player -> Player addOpt = over rooms . (inject . addOptOnRoom <*> view (loc . roomNum)) replOpt :: RoomOption -> Player -> Player replOpt option = addOpt option . remOpt (option ^. loc)
ec8358586ab66aa5fcdb6a3f1eeca4ac4666f09b434434d5b2975788d5d2d33d
incoherentsoftware/defect-process
Data.hs
module Enemy.All.Bomb.Data ( BombEnemyData(..) , mkBombEnemyData , isExplodeTimerActive ) where import Control.Monad.IO.Class (MonadIO) import Data.Maybe (isJust) import Configs import Configs.All.Enemy import Enemy.All.Bomb.AttackDescriptions import Enemy.All.Bomb.Behavior import Enemy.All.Bomb.Sprites import FileCache import Util import Window.Graphics data BombEnemyData = BombEnemyData { _behavior :: BombEnemyBehavior , _prevBehavior :: BombEnemyBehavior , _explodeTimerTtl :: Maybe Secs , _sprites :: EnemySprites , _attackDescs :: EnemyAttackDescriptions , _config :: EnemyConfig } mkBombEnemyData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => m BombEnemyData mkBombEnemyData = do sprs <- mkEnemySprites atkDescs <- mkEnemyAttackDescs cfg <- _enemy <$> readConfigs return $ BombEnemyData { _behavior = SpawnBehavior , _prevBehavior = SpawnBehavior , _explodeTimerTtl = Nothing , _sprites = sprs , _attackDescs = atkDescs , _config = cfg } isExplodeTimerActive :: BombEnemyData -> Bool isExplodeTimerActive = isJust . _explodeTimerTtl
null
https://raw.githubusercontent.com/incoherentsoftware/defect-process/8797aad1d93bff5aadd7226c39a48f45cf76746e/src/Enemy/All/Bomb/Data.hs
haskell
module Enemy.All.Bomb.Data ( BombEnemyData(..) , mkBombEnemyData , isExplodeTimerActive ) where import Control.Monad.IO.Class (MonadIO) import Data.Maybe (isJust) import Configs import Configs.All.Enemy import Enemy.All.Bomb.AttackDescriptions import Enemy.All.Bomb.Behavior import Enemy.All.Bomb.Sprites import FileCache import Util import Window.Graphics data BombEnemyData = BombEnemyData { _behavior :: BombEnemyBehavior , _prevBehavior :: BombEnemyBehavior , _explodeTimerTtl :: Maybe Secs , _sprites :: EnemySprites , _attackDescs :: EnemyAttackDescriptions , _config :: EnemyConfig } mkBombEnemyData :: (ConfigsRead m, FileCache m, GraphicsRead m, MonadIO m) => m BombEnemyData mkBombEnemyData = do sprs <- mkEnemySprites atkDescs <- mkEnemyAttackDescs cfg <- _enemy <$> readConfigs return $ BombEnemyData { _behavior = SpawnBehavior , _prevBehavior = SpawnBehavior , _explodeTimerTtl = Nothing , _sprites = sprs , _attackDescs = atkDescs , _config = cfg } isExplodeTimerActive :: BombEnemyData -> Bool isExplodeTimerActive = isJust . _explodeTimerTtl
aefd79e6da4ce962a3dc051bb5afd425e5b636485560454cae13212884ee9650
cedlemo/OCaml-Notty-introduction
common_lwt.ml
open Notty open Lwt.Infix include Common module T = Notty_lwt.Term let simpleterm_lwt ~imgf ~f ~s = let term = T.create () in let imgf (w, h) s = I.(string A.(fg lightblack) "[ESC quits.]" <-> imgf (w, h - 1) s) in let step e s = match e with | `Key (`Escape, []) | `Key (`Uchar 67, [`Ctrl]) -> T.release term >|= fun () -> s | `Resize dim -> T.image term (imgf dim s) >|= fun () -> s | #Unescape.event as e -> match f s e with | Some s -> T.image term (imgf (T.size term) s) >|= fun () -> s | None -> T.release term >|= fun () -> s in ( T.image term (imgf (T.size term) s) >>= fun () -> Lwt_stream.fold_s step (T.events term) s ) |> Lwt_main.run |> ignore let timer = function | None -> Lwt.wait () |> fst | Some t -> Lwt_unix.sleep t >|= fun _ -> `Timer let event e = Lwt_stream.get (T.events e) >|= function | Some (`Resize _ | #Unescape.event as x) -> x | None -> `End let simpleterm_lwt_timed ?delay ~f s0 = let term = T.create () in let rec loop (e, t) dim s = (e <?> t) >>= function | `End | `Key (`Escape, []) | `Key (`Uchar 67, [`Ctrl]) -> Lwt.return_unit | `Resize dim as evt -> invoke (event term, t) dim s evt | #Unescape.event as evt -> invoke (event term, t) dim s evt | `Timer as evt -> invoke (e, timer delay) dim s evt and invoke es dim s e = match f dim s e with | `Continue s -> loop es dim s | `Redraw (s, i) -> T.image term i >>= fun () -> loop es dim s | `Stop -> Lwt.return_unit in let size = T.size term in loop (event term, timer delay) size s0
null
https://raw.githubusercontent.com/cedlemo/OCaml-Notty-introduction/9295b43382354c504d5efcad3ba56cff6f34d2eb/common_lwt.ml
ocaml
open Notty open Lwt.Infix include Common module T = Notty_lwt.Term let simpleterm_lwt ~imgf ~f ~s = let term = T.create () in let imgf (w, h) s = I.(string A.(fg lightblack) "[ESC quits.]" <-> imgf (w, h - 1) s) in let step e s = match e with | `Key (`Escape, []) | `Key (`Uchar 67, [`Ctrl]) -> T.release term >|= fun () -> s | `Resize dim -> T.image term (imgf dim s) >|= fun () -> s | #Unescape.event as e -> match f s e with | Some s -> T.image term (imgf (T.size term) s) >|= fun () -> s | None -> T.release term >|= fun () -> s in ( T.image term (imgf (T.size term) s) >>= fun () -> Lwt_stream.fold_s step (T.events term) s ) |> Lwt_main.run |> ignore let timer = function | None -> Lwt.wait () |> fst | Some t -> Lwt_unix.sleep t >|= fun _ -> `Timer let event e = Lwt_stream.get (T.events e) >|= function | Some (`Resize _ | #Unescape.event as x) -> x | None -> `End let simpleterm_lwt_timed ?delay ~f s0 = let term = T.create () in let rec loop (e, t) dim s = (e <?> t) >>= function | `End | `Key (`Escape, []) | `Key (`Uchar 67, [`Ctrl]) -> Lwt.return_unit | `Resize dim as evt -> invoke (event term, t) dim s evt | #Unescape.event as evt -> invoke (event term, t) dim s evt | `Timer as evt -> invoke (e, timer delay) dim s evt and invoke es dim s e = match f dim s e with | `Continue s -> loop es dim s | `Redraw (s, i) -> T.image term i >>= fun () -> loop es dim s | `Stop -> Lwt.return_unit in let size = T.size term in loop (event term, timer delay) size s0
17b6dffc50fc9b39fbaa375687a0084998d56654cc085f320b39815976fbb66f
HealthSamurai/re-form
dev.cljs
(ns ^:figwheel-no-load ui.dev (:require [ui.core :as core] [figwheel.client :as figwheel :include-macros true] [re-frisk.core :refer [enable-re-frisk!]] [devtools.core :as devtools])) (devtools/install!) (enable-console-print!) (figwheel/watch-and-reload :websocket-url "ws:3002/figwheel-ws" :jsload-callback core/mount-root) (enable-re-frisk!) (core/init!)
null
https://raw.githubusercontent.com/HealthSamurai/re-form/810321d67e3946876c834998e3472d0693846953/example/env/dev/cljs/ui/dev.cljs
clojure
(ns ^:figwheel-no-load ui.dev (:require [ui.core :as core] [figwheel.client :as figwheel :include-macros true] [re-frisk.core :refer [enable-re-frisk!]] [devtools.core :as devtools])) (devtools/install!) (enable-console-print!) (figwheel/watch-and-reload :websocket-url "ws:3002/figwheel-ws" :jsload-callback core/mount-root) (enable-re-frisk!) (core/init!)
34309599320666141b91336a49ce80cc3c34f4e9a17bac106f9a913f899f3210
heraldry/heraldicon
rustre.cljs
(ns heraldicon.heraldry.charge.type.rustre (:require [heraldicon.heraldry.charge.interface :as charge.interface] [heraldicon.heraldry.charge.shared :as charge.shared] [heraldicon.interface :as interface])) (def charge-type :heraldry.charge.type/rustre) (defmethod charge.interface/display-name charge-type [_] :string.charge.type/rustre) (defmethod charge.interface/options charge-type [context] (-> (charge.shared/options context) (update :geometry dissoc :mirrored?) (update :geometry dissoc :reversed?))) (def ^:private base (let [height 100 width (/ height 1.3) width-half (/ width 2) height-half (/ height 2) hole-radius (/ width 4)] {:base-shape [["M" 0 (- height-half) "l" width-half height-half "l " (- width-half) height-half "l" (- width-half) (- height-half) "z"] ["M" hole-radius 0 "a" hole-radius hole-radius 0 0 0 (* hole-radius -2) 0 "a" hole-radius hole-radius 0 0 0 (* hole-radius 2) 0 "z"]] :base-width width :base-height height})) (defmethod interface/properties charge-type [context] (charge.shared/process-shape context base))
null
https://raw.githubusercontent.com/heraldry/heraldicon/3b52869f611023b496a29473a98c35ca89262aab/src/heraldicon/heraldry/charge/type/rustre.cljs
clojure
(ns heraldicon.heraldry.charge.type.rustre (:require [heraldicon.heraldry.charge.interface :as charge.interface] [heraldicon.heraldry.charge.shared :as charge.shared] [heraldicon.interface :as interface])) (def charge-type :heraldry.charge.type/rustre) (defmethod charge.interface/display-name charge-type [_] :string.charge.type/rustre) (defmethod charge.interface/options charge-type [context] (-> (charge.shared/options context) (update :geometry dissoc :mirrored?) (update :geometry dissoc :reversed?))) (def ^:private base (let [height 100 width (/ height 1.3) width-half (/ width 2) height-half (/ height 2) hole-radius (/ width 4)] {:base-shape [["M" 0 (- height-half) "l" width-half height-half "l " (- width-half) height-half "l" (- width-half) (- height-half) "z"] ["M" hole-radius 0 "a" hole-radius hole-radius 0 0 0 (* hole-radius -2) 0 "a" hole-radius hole-radius 0 0 0 (* hole-radius 2) 0 "z"]] :base-width width :base-height height})) (defmethod interface/properties charge-type [context] (charge.shared/process-shape context base))
b4c0b7536b6d455b1a2e7a079461a85d174537fa263810aeee42977f2c06b34b
SamB/coq
vernac.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (*i $Id$ i*) (* Parsing of vernacular. *) Read a vernac command on the specified input ( parse only ) . Raises [ End_of_file ] if EOF ( or Ctrl - D ) is reached . Raises [End_of_file] if EOF (or Ctrl-D) is reached. *) val parse_phrase : Pcoq.Gram.parsable * in_channel option -> Util.loc * Vernacexpr.vernac_expr Reads and executes commands from a stream . The boolean [ just_parsing ] disables interpretation of commands . The boolean [just_parsing] disables interpretation of commands. *) exception DuringCommandInterp of Util.loc * exn exception End_of_input val just_parsing : bool ref val raw_do_vernac : Pcoq.Gram.parsable -> unit (* Set XML hooks *) val set_xml_start_library : (unit -> unit) -> unit val set_xml_end_library : (unit -> unit) -> unit (* Load a vernac file, verbosely or not. Errors are annotated with file and location *) val load_vernac : bool -> string -> unit Compile a vernac file , verbosely or not ( f is assumed without .v suffix ) val compile : bool -> string -> unit Interpret a vernac AST val vernac_com : (Vernacexpr.vernac_expr -> unit) -> Util.loc * Vernacexpr.vernac_expr -> unit
null
https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/toplevel/vernac.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i $Id$ i Parsing of vernacular. Set XML hooks Load a vernac file, verbosely or not. Errors are annotated with file and location
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Read a vernac command on the specified input ( parse only ) . Raises [ End_of_file ] if EOF ( or Ctrl - D ) is reached . Raises [End_of_file] if EOF (or Ctrl-D) is reached. *) val parse_phrase : Pcoq.Gram.parsable * in_channel option -> Util.loc * Vernacexpr.vernac_expr Reads and executes commands from a stream . The boolean [ just_parsing ] disables interpretation of commands . The boolean [just_parsing] disables interpretation of commands. *) exception DuringCommandInterp of Util.loc * exn exception End_of_input val just_parsing : bool ref val raw_do_vernac : Pcoq.Gram.parsable -> unit val set_xml_start_library : (unit -> unit) -> unit val set_xml_end_library : (unit -> unit) -> unit val load_vernac : bool -> string -> unit Compile a vernac file , verbosely or not ( f is assumed without .v suffix ) val compile : bool -> string -> unit Interpret a vernac AST val vernac_com : (Vernacexpr.vernac_expr -> unit) -> Util.loc * Vernacexpr.vernac_expr -> unit
379851012482adeb22400ec35edcde569c3cc019a511a39f38a4c78b854bc927
ocaml/ocamlbuild
hygiene.ml
(***********************************************************************) (* *) (* ocamlbuild *) (* *) , , projet Gallium , INRIA Rocquencourt (* *) Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) Original author : (* Hygiene *) open My_std open Slurp exception Exit_hygiene_violations type rule = | Implies_not of pattern * pattern | Not of pattern and pattern = suffix and suffix = string type penalty = Warn | Fail type law = { law_name : string; law_rules : rule list; law_penalty : penalty } let list_collect f l = let rec loop result = function | [] -> List.rev result | x :: rest -> match f x with | None -> loop result rest | Some y -> loop (y :: result) rest in loop [] l let list_none_for_all f l = let rec loop = function | [] -> None | x :: rest -> match f x with | None -> loop rest | y -> y in loop l let sf = Printf.sprintf module SS = Set.Make(String);; let check ?sanitize laws entry = let penalties = ref [] in let microbes = ref SS.empty in let () = match sanitize with | Some fn -> if sys_file_exists fn then sys_remove fn | None -> () in let remove path name = if sanitize <> None then microbes := SS.add (filename_concat path name) !microbes in let check_rule = fun entries -> function | Not suffix -> list_collect begin function | File(path, name, _, true) -> if Filename.check_suffix name suffix && not ( Pathname.link_to_dir (filename_concat path name) !Options.build_dir ) then begin remove path name; Some(sf "File %s in %s has suffix %s" name path suffix) end else None | File _ | Dir _| Error _ | Nothing -> None end entries | Implies_not(suffix1, suffix2) -> list_collect begin function | File(path, name, _, true) -> if Filename.check_suffix name suffix1 then begin let base = Filename.chop_suffix name suffix1 in let name' = base ^ suffix2 in if List.exists begin function | File(_, name'', _, true) -> name' = name'' | File _ | Dir _ | Error _ | Nothing -> false end entries then begin remove path name'; Some(sf "Files %s and %s should not be together in %s" name name' path) end else None end else None | File _ | Dir _ | Error _ | Nothing -> None end entries in let rec check_entry = function | Dir(_,_,_,true,entries) -> List.iter begin fun law -> match List.concat (List.map (check_rule !*entries) law.law_rules) with | [] -> () | explanations -> penalties := (law, explanations) :: !penalties end laws; List.iter check_entry !*entries | Dir _ | File _ | Error _ | Nothing -> () in check_entry entry; begin let microbes = !microbes in if not (SS.is_empty microbes) then begin match sanitize with | None -> Log.eprintf "sanitize: the following are files that should probably not be in your\n\ source tree:\n"; SS.iter begin fun fn -> Log.eprintf " %s" fn end microbes; Log.eprintf "Remove them manually, don't use the -no-sanitize option, use -no-hygiene, or\n\ define hygiene exceptions using the tags or plugin mechanism.\n"; raise Exit_hygiene_violations | Some fn -> let m = SS.cardinal microbes in Log.eprintf "@[<hov 2>SANITIZE:@ a@ total@ of@ %d@ file%s@ that@ should@ probably\ @ not@ be@ in@ your@ source@ tree@ has@ been@ found.\ @ A@ script@ shell@ file@ %S@ is@ being@ created.\ @ Check@ this@ script@ and@ run@ it@ to@ remove@ unwanted@ files\ @ or@ use@ other@ options@ (such@ as@ defining@ hygiene@ exceptions\ @ or@ using@ the@ -no-hygiene@ option).@]" m (if m = 1 then "" else "s") fn; let oc = open_out_gen [Open_wronly; Open_creat; Open_trunc; Open_binary] 0o777 fn in See PR # 5338 : under mingw , one produces a shell script , which must follow Unix eol convention ; hence Open_binary . Unix eol convention; hence Open_binary. *) let fp = Printf.fprintf in fp oc "#!/bin/sh\n\ # File generated by ocamlbuild\n\ \n\ cd %s\n\ \n" (Shell.quote_filename_if_needed Pathname.pwd); SS.iter begin fun fn -> fp oc "rm -f %s\n" (Shell.quote_filename_if_needed fn) end microbes; (* Also clean itself *) fp oc "# Also clean the script itself\n"; fp oc "rm -f %s\n" (Shell.quote_filename_if_needed fn); close_out oc end; !penalties end ;;
null
https://raw.githubusercontent.com/ocaml/ocamlbuild/792b7c8abdbc712c98ed7e69469ed354b87e125b/src/hygiene.ml
ocaml
********************************************************************* ocamlbuild the special exception on linking described in file ../LICENSE. ********************************************************************* Hygiene Also clean itself
, , projet Gallium , INRIA Rocquencourt Copyright 2007 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with Original author : open My_std open Slurp exception Exit_hygiene_violations type rule = | Implies_not of pattern * pattern | Not of pattern and pattern = suffix and suffix = string type penalty = Warn | Fail type law = { law_name : string; law_rules : rule list; law_penalty : penalty } let list_collect f l = let rec loop result = function | [] -> List.rev result | x :: rest -> match f x with | None -> loop result rest | Some y -> loop (y :: result) rest in loop [] l let list_none_for_all f l = let rec loop = function | [] -> None | x :: rest -> match f x with | None -> loop rest | y -> y in loop l let sf = Printf.sprintf module SS = Set.Make(String);; let check ?sanitize laws entry = let penalties = ref [] in let microbes = ref SS.empty in let () = match sanitize with | Some fn -> if sys_file_exists fn then sys_remove fn | None -> () in let remove path name = if sanitize <> None then microbes := SS.add (filename_concat path name) !microbes in let check_rule = fun entries -> function | Not suffix -> list_collect begin function | File(path, name, _, true) -> if Filename.check_suffix name suffix && not ( Pathname.link_to_dir (filename_concat path name) !Options.build_dir ) then begin remove path name; Some(sf "File %s in %s has suffix %s" name path suffix) end else None | File _ | Dir _| Error _ | Nothing -> None end entries | Implies_not(suffix1, suffix2) -> list_collect begin function | File(path, name, _, true) -> if Filename.check_suffix name suffix1 then begin let base = Filename.chop_suffix name suffix1 in let name' = base ^ suffix2 in if List.exists begin function | File(_, name'', _, true) -> name' = name'' | File _ | Dir _ | Error _ | Nothing -> false end entries then begin remove path name'; Some(sf "Files %s and %s should not be together in %s" name name' path) end else None end else None | File _ | Dir _ | Error _ | Nothing -> None end entries in let rec check_entry = function | Dir(_,_,_,true,entries) -> List.iter begin fun law -> match List.concat (List.map (check_rule !*entries) law.law_rules) with | [] -> () | explanations -> penalties := (law, explanations) :: !penalties end laws; List.iter check_entry !*entries | Dir _ | File _ | Error _ | Nothing -> () in check_entry entry; begin let microbes = !microbes in if not (SS.is_empty microbes) then begin match sanitize with | None -> Log.eprintf "sanitize: the following are files that should probably not be in your\n\ source tree:\n"; SS.iter begin fun fn -> Log.eprintf " %s" fn end microbes; Log.eprintf "Remove them manually, don't use the -no-sanitize option, use -no-hygiene, or\n\ define hygiene exceptions using the tags or plugin mechanism.\n"; raise Exit_hygiene_violations | Some fn -> let m = SS.cardinal microbes in Log.eprintf "@[<hov 2>SANITIZE:@ a@ total@ of@ %d@ file%s@ that@ should@ probably\ @ not@ be@ in@ your@ source@ tree@ has@ been@ found.\ @ A@ script@ shell@ file@ %S@ is@ being@ created.\ @ Check@ this@ script@ and@ run@ it@ to@ remove@ unwanted@ files\ @ or@ use@ other@ options@ (such@ as@ defining@ hygiene@ exceptions\ @ or@ using@ the@ -no-hygiene@ option).@]" m (if m = 1 then "" else "s") fn; let oc = open_out_gen [Open_wronly; Open_creat; Open_trunc; Open_binary] 0o777 fn in See PR # 5338 : under mingw , one produces a shell script , which must follow Unix eol convention ; hence Open_binary . Unix eol convention; hence Open_binary. *) let fp = Printf.fprintf in fp oc "#!/bin/sh\n\ # File generated by ocamlbuild\n\ \n\ cd %s\n\ \n" (Shell.quote_filename_if_needed Pathname.pwd); SS.iter begin fun fn -> fp oc "rm -f %s\n" (Shell.quote_filename_if_needed fn) end microbes; fp oc "# Also clean the script itself\n"; fp oc "rm -f %s\n" (Shell.quote_filename_if_needed fn); close_out oc end; !penalties end ;;
076abef98dc8f8e7cbf2b56035417fd15a1e56bc49f582477193d1a6c8b08ad4
facebook/pyre-check
dependencyTrackedMemoryTest.ml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open OUnit2 open Core open Pyre module StringKey = struct type t = string type key = string [@@deriving sexp, compare] module KeySet = Caml.Set.Make (struct type t = key [@@deriving compare, sexp] end) type registered = string [@@deriving sexp, compare] module RegisteredSet = KeySet let to_string x = x let compare = String.compare let from_string x = x module Registry = struct let table = DependencyTrackedMemory.EncodedDependency.Table.create () let encode key = let add = function | None -> String.Set.singleton key | Some existing -> String.Set.add existing key in let encoded = DependencyTrackedMemory.EncodedDependency.make key ~hash:String.hash in DependencyTrackedMemory.EncodedDependency.Table.update table encoded ~f:add; encoded let decode hash = DependencyTrackedMemory.EncodedDependency.Table.find table hash >>| Set.to_list end end module StringDependencyKey = DependencyTrackedMemory.DependencyKey.Make (StringKey) module StringValue = struct type t = string let prefix = Prefix.make () let description = "Test1" let equal = String.equal end module OtherStringValue = struct type t = string let prefix = Prefix.make () let description = "Test2" let equal = String.equal end module TableA = DependencyTrackedMemory.DependencyTrackedTableWithCache (StringKey) (StringDependencyKey) (StringValue) module TableB = DependencyTrackedMemory.DependencyTrackedTableWithCache (StringKey) (StringDependencyKey) (OtherStringValue) let assert_dependency ~expected actual = let expected_set = StringDependencyKey.RegisteredSet.of_list expected in assert_bool "Check if the actual dependency overapproximate the expected one" (StringDependencyKey.RegisteredSet.subset expected_set actual) let table_a = TableA.create () let table_b = TableB.create () let test_dependency_table _ = let function_1 = "function_1" in let function_2 = "function_2" in let function_3 = "function_3" in let function_4 = "function_4" in let _value : string option = TableA.get table_a "Foo" ~dependency:function_1 in let _value : string option = TableA.get table_a "Bar" ~dependency:function_1 in let _value : string option = TableA.get table_a "Foo" ~dependency:function_2 in let _value : string option = TableA.get table_a "Foo" ~dependency:function_3 in assert_dependency ~expected:[function_3; function_2; function_1] (TableA.get_dependents ~kind:Get "Foo"); assert_dependency ~expected:[function_1] (TableA.get_dependents ~kind:Get "Bar"); let _value : string option = TableB.get table_b "Foo" ~dependency:function_4 in (* Ensure that different tables' same keys are encoded differently *) assert_dependency ~expected:[function_4] (TableB.get_dependents ~kind:Get "Foo"); (* Ensure that `reset_shared_memory` correctly resets all dependency-related info *) Memory.reset_shared_memory (); assert_dependency ~expected:[] (TableA.get_dependents ~kind:Get "Foo"); assert_dependency ~expected:[] (TableB.get_dependents ~kind:Get "Foo"); let _value : string option = TableB.get table_b "Foo" ~dependency:function_4 in assert_dependency ~expected:[function_4] (TableB.get_dependents ~kind:Get "Foo"); (* Ensure that the `get` interface also adds the corresponding dependencies *) TableA.get table_a "Foo" ~dependency:function_1 |> ignore; TableA.get table_a "Bar" ~dependency:function_1 |> ignore; TableA.get table_a "Foo" ~dependency:function_2 |> ignore; TableA.get table_a "Foo" ~dependency:function_3 |> ignore; assert_dependency ~expected:[function_3; function_2; function_1] (TableA.get_dependents ~kind:Get "Foo"); assert_dependency ~expected:[function_1] (TableA.get_dependents ~kind:Get "Bar"); (* Final cleanup *) Memory.reset_shared_memory (); () module UpdateDependencyTest = struct type t = { key: string; old_value: string option; new_value: string option; get_dependencies: string list; mem_dependencies: string list; } let assert_dependencies ~expected specification = let open Core in let setup_old_state { key; old_value; get_dependencies; mem_dependencies; _ } = Option.iter old_value ~f:(TableA.add table_a key); let _values : string option list = List.map get_dependencies ~f:(fun dependency -> TableA.get table_a key ~dependency) in let _values : bool list = List.map mem_dependencies ~f:(fun dependency -> TableA.mem table_a key ~dependency) in () in List.iter specification ~f:setup_old_state; let setup_new_state { key; new_value; _ } = Option.iter new_value ~f:(TableA.add table_a key) in let update _ = List.iter specification ~f:setup_new_state in let keys = List.map specification ~f:(fun { key; _ } -> key) |> TableB.KeySet.of_list in let _, actual = StringDependencyKey.Transaction.empty ~scheduler:(Test.mock_scheduler ()) |> TableA.add_to_transaction table_a ~keys |> StringDependencyKey.Transaction.execute ~update in assert_dependency ~expected actual; Memory.reset_shared_memory () end let test_update_dependency_table _ = UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = Some "NewAVal"; get_dependencies = []; mem_dependencies = ["dep_a"]; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = None; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = None; get_dependencies = []; mem_dependencies = ["dep_a"]; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = []; mem_dependencies = ["dep_a"]; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = ["dep_a"]; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = None; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = None; get_dependencies = []; mem_dependencies = ["dep_a"]; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "AVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"; "dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = None; new_value = Some "NewBVal"; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = None; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = None; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = None; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A1"; old_value = Some "A1Val"; new_value = Some "NewA1Val"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "A2"; old_value = Some "A2Val"; new_value = Some "A2Val"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "NewBVal"; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "BVal"; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "AVal"; get_dependencies = ["dep_a"; "dep_b"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "NewBVal"; get_dependencies = ["dep_b"; "dep_c"]; mem_dependencies = []; }; ] ~expected:["dep_b"; "dep_c"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "AVal"; get_dependencies = ["dep_a_b"; "dep_a_c"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "BVal"; get_dependencies = ["dep_a_b"; "dep_b_c"]; mem_dependencies = []; }; { key = "C"; old_value = Some "CVal"; new_value = Some "CVal"; get_dependencies = ["dep_a_c"; "dep_b_c"]; mem_dependencies = []; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a_b"; "dep_a_c"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "BVal"; get_dependencies = ["dep_a_b"; "dep_b_c"]; mem_dependencies = []; }; { key = "C"; old_value = Some "CVal"; new_value = Some "CVal"; get_dependencies = ["dep_a_c"; "dep_b_c"]; mem_dependencies = []; }; ] ~expected:["dep_a_b"; "dep_a_c"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a_b"; "dep_a_c"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "NewBVal"; get_dependencies = ["dep_a_b"; "dep_b_c"]; mem_dependencies = []; }; { key = "C"; old_value = Some "CVal"; new_value = Some "CVal"; get_dependencies = ["dep_a_c"; "dep_b_c"]; mem_dependencies = []; }; ] ~expected:["dep_a_b"; "dep_a_c"; "dep_b_c"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a_b"; "dep_a_c"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "NewBVal"; get_dependencies = ["dep_a_b"; "dep_b_c"]; mem_dependencies = []; }; { key = "C"; old_value = Some "CVal"; new_value = Some "NewCVal"; get_dependencies = ["dep_a_c"; "dep_b_c"]; mem_dependencies = []; }; ] ~expected:["dep_a_b"; "dep_a_c"; "dep_b_c"]; () let () = "memory" >::: [ "dependencies" >:: test_dependency_table; "update_dependencies" >:: test_update_dependency_table; ] |> Test.run
null
https://raw.githubusercontent.com/facebook/pyre-check/7f6b6970681966bda8066b6450043b349ab65749/source/service/test/dependencyTrackedMemoryTest.ml
ocaml
Ensure that different tables' same keys are encoded differently Ensure that `reset_shared_memory` correctly resets all dependency-related info Ensure that the `get` interface also adds the corresponding dependencies Final cleanup
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open OUnit2 open Core open Pyre module StringKey = struct type t = string type key = string [@@deriving sexp, compare] module KeySet = Caml.Set.Make (struct type t = key [@@deriving compare, sexp] end) type registered = string [@@deriving sexp, compare] module RegisteredSet = KeySet let to_string x = x let compare = String.compare let from_string x = x module Registry = struct let table = DependencyTrackedMemory.EncodedDependency.Table.create () let encode key = let add = function | None -> String.Set.singleton key | Some existing -> String.Set.add existing key in let encoded = DependencyTrackedMemory.EncodedDependency.make key ~hash:String.hash in DependencyTrackedMemory.EncodedDependency.Table.update table encoded ~f:add; encoded let decode hash = DependencyTrackedMemory.EncodedDependency.Table.find table hash >>| Set.to_list end end module StringDependencyKey = DependencyTrackedMemory.DependencyKey.Make (StringKey) module StringValue = struct type t = string let prefix = Prefix.make () let description = "Test1" let equal = String.equal end module OtherStringValue = struct type t = string let prefix = Prefix.make () let description = "Test2" let equal = String.equal end module TableA = DependencyTrackedMemory.DependencyTrackedTableWithCache (StringKey) (StringDependencyKey) (StringValue) module TableB = DependencyTrackedMemory.DependencyTrackedTableWithCache (StringKey) (StringDependencyKey) (OtherStringValue) let assert_dependency ~expected actual = let expected_set = StringDependencyKey.RegisteredSet.of_list expected in assert_bool "Check if the actual dependency overapproximate the expected one" (StringDependencyKey.RegisteredSet.subset expected_set actual) let table_a = TableA.create () let table_b = TableB.create () let test_dependency_table _ = let function_1 = "function_1" in let function_2 = "function_2" in let function_3 = "function_3" in let function_4 = "function_4" in let _value : string option = TableA.get table_a "Foo" ~dependency:function_1 in let _value : string option = TableA.get table_a "Bar" ~dependency:function_1 in let _value : string option = TableA.get table_a "Foo" ~dependency:function_2 in let _value : string option = TableA.get table_a "Foo" ~dependency:function_3 in assert_dependency ~expected:[function_3; function_2; function_1] (TableA.get_dependents ~kind:Get "Foo"); assert_dependency ~expected:[function_1] (TableA.get_dependents ~kind:Get "Bar"); let _value : string option = TableB.get table_b "Foo" ~dependency:function_4 in assert_dependency ~expected:[function_4] (TableB.get_dependents ~kind:Get "Foo"); Memory.reset_shared_memory (); assert_dependency ~expected:[] (TableA.get_dependents ~kind:Get "Foo"); assert_dependency ~expected:[] (TableB.get_dependents ~kind:Get "Foo"); let _value : string option = TableB.get table_b "Foo" ~dependency:function_4 in assert_dependency ~expected:[function_4] (TableB.get_dependents ~kind:Get "Foo"); TableA.get table_a "Foo" ~dependency:function_1 |> ignore; TableA.get table_a "Bar" ~dependency:function_1 |> ignore; TableA.get table_a "Foo" ~dependency:function_2 |> ignore; TableA.get table_a "Foo" ~dependency:function_3 |> ignore; assert_dependency ~expected:[function_3; function_2; function_1] (TableA.get_dependents ~kind:Get "Foo"); assert_dependency ~expected:[function_1] (TableA.get_dependents ~kind:Get "Bar"); Memory.reset_shared_memory (); () module UpdateDependencyTest = struct type t = { key: string; old_value: string option; new_value: string option; get_dependencies: string list; mem_dependencies: string list; } let assert_dependencies ~expected specification = let open Core in let setup_old_state { key; old_value; get_dependencies; mem_dependencies; _ } = Option.iter old_value ~f:(TableA.add table_a key); let _values : string option list = List.map get_dependencies ~f:(fun dependency -> TableA.get table_a key ~dependency) in let _values : bool list = List.map mem_dependencies ~f:(fun dependency -> TableA.mem table_a key ~dependency) in () in List.iter specification ~f:setup_old_state; let setup_new_state { key; new_value; _ } = Option.iter new_value ~f:(TableA.add table_a key) in let update _ = List.iter specification ~f:setup_new_state in let keys = List.map specification ~f:(fun { key; _ } -> key) |> TableB.KeySet.of_list in let _, actual = StringDependencyKey.Transaction.empty ~scheduler:(Test.mock_scheduler ()) |> TableA.add_to_transaction table_a ~keys |> StringDependencyKey.Transaction.execute ~update in assert_dependency ~expected actual; Memory.reset_shared_memory () end let test_update_dependency_table _ = UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = Some "NewAVal"; get_dependencies = []; mem_dependencies = ["dep_a"]; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = None; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = None; get_dependencies = []; mem_dependencies = ["dep_a"]; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = []; mem_dependencies = ["dep_a"]; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = ["dep_a"]; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = None; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = None; get_dependencies = []; mem_dependencies = ["dep_a"]; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "AVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"; "dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = None; new_value = Some "NewBVal"; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = None; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = None; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = None; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = None; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A1"; old_value = Some "A1Val"; new_value = Some "NewA1Val"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "A2"; old_value = Some "A2Val"; new_value = Some "A2Val"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "NewBVal"; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"; "dep_b"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "BVal"; get_dependencies = ["dep_b"]; mem_dependencies = []; }; ] ~expected:["dep_a"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "AVal"; get_dependencies = ["dep_a"; "dep_b"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "NewBVal"; get_dependencies = ["dep_b"; "dep_c"]; mem_dependencies = []; }; ] ~expected:["dep_b"; "dep_c"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "AVal"; get_dependencies = ["dep_a_b"; "dep_a_c"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "BVal"; get_dependencies = ["dep_a_b"; "dep_b_c"]; mem_dependencies = []; }; { key = "C"; old_value = Some "CVal"; new_value = Some "CVal"; get_dependencies = ["dep_a_c"; "dep_b_c"]; mem_dependencies = []; }; ] ~expected:[]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a_b"; "dep_a_c"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "BVal"; get_dependencies = ["dep_a_b"; "dep_b_c"]; mem_dependencies = []; }; { key = "C"; old_value = Some "CVal"; new_value = Some "CVal"; get_dependencies = ["dep_a_c"; "dep_b_c"]; mem_dependencies = []; }; ] ~expected:["dep_a_b"; "dep_a_c"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a_b"; "dep_a_c"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "NewBVal"; get_dependencies = ["dep_a_b"; "dep_b_c"]; mem_dependencies = []; }; { key = "C"; old_value = Some "CVal"; new_value = Some "CVal"; get_dependencies = ["dep_a_c"; "dep_b_c"]; mem_dependencies = []; }; ] ~expected:["dep_a_b"; "dep_a_c"; "dep_b_c"]; UpdateDependencyTest.assert_dependencies [ { key = "A"; old_value = Some "AVal"; new_value = Some "NewAVal"; get_dependencies = ["dep_a_b"; "dep_a_c"]; mem_dependencies = []; }; { key = "B"; old_value = Some "BVal"; new_value = Some "NewBVal"; get_dependencies = ["dep_a_b"; "dep_b_c"]; mem_dependencies = []; }; { key = "C"; old_value = Some "CVal"; new_value = Some "NewCVal"; get_dependencies = ["dep_a_c"; "dep_b_c"]; mem_dependencies = []; }; ] ~expected:["dep_a_b"; "dep_a_c"; "dep_b_c"]; () let () = "memory" >::: [ "dependencies" >:: test_dependency_table; "update_dependencies" >:: test_update_dependency_table; ] |> Test.run
49a6601fa5b622977be6d744da6b334c858569371f4e062f8e8a7a27a1b05837
graninas/Pragmatic-Type-Level-Design
Conv.hs
module HCell.Gloss.Conv where import CPrelude import HCell.Types import HCell.Gloss.Types coordsToGlossCell :: GlossBaseShift -> GridCellSize -> Coords -> GlossCoords coordsToGlossCell (GlossBaseShift (shiftX, shiftY)) (GridCellSize cellSize) (x, y) = GlossCoords (x', y') where x' = shiftX + fromIntegral (x * cellSize) y' = shiftY + fromIntegral (y * cellSize) getBaseShift :: GlossWindowSize -> BaseShift getBaseShift (GlossWindowSize (wX, wY)) = BaseShift (shiftX, shiftY) where shiftX = negate $ wX `div` 2 shiftY = negate $ wY `div` 2 getGlossBaseShift :: GlossWindowSize -> GlossBaseShift getGlossBaseShift gwnd = GlossBaseShift (fromIntegral shiftX, fromIntegral shiftY) where BaseShift (shiftX, shiftY) = getBaseShift gwnd getBareCellHalf :: BareCellSize -> BareCellHalf getBareCellHalf (BareCellSize s) = BareCellHalf $ s `div` 2 getGridCellSize :: BareCellSize -> CellSpaceSize -> GridCellSize getGridCellSize (BareCellSize bareCellSize) (CellSpaceSize cellSpaceSize) = GridCellSize $ bareCellSize + cellSpaceSize getGlossGridCellSize :: GridCellSize -> GlossGridCellSize getGlossGridCellSize (GridCellSize s) = GlossGridCellSize $ fromIntegral s getGlossBareCellSize :: BareCellSize -> GlossBareCellSize getGlossBareCellSize (BareCellSize s) = GlossBareCellSize $ fromIntegral s
null
https://raw.githubusercontent.com/graninas/Pragmatic-Type-Level-Design/a95f9a5d7ae5b443b9d8ef77b27f1aecf02f461a/demo-apps/hcell/src/HCell/Gloss/Conv.hs
haskell
module HCell.Gloss.Conv where import CPrelude import HCell.Types import HCell.Gloss.Types coordsToGlossCell :: GlossBaseShift -> GridCellSize -> Coords -> GlossCoords coordsToGlossCell (GlossBaseShift (shiftX, shiftY)) (GridCellSize cellSize) (x, y) = GlossCoords (x', y') where x' = shiftX + fromIntegral (x * cellSize) y' = shiftY + fromIntegral (y * cellSize) getBaseShift :: GlossWindowSize -> BaseShift getBaseShift (GlossWindowSize (wX, wY)) = BaseShift (shiftX, shiftY) where shiftX = negate $ wX `div` 2 shiftY = negate $ wY `div` 2 getGlossBaseShift :: GlossWindowSize -> GlossBaseShift getGlossBaseShift gwnd = GlossBaseShift (fromIntegral shiftX, fromIntegral shiftY) where BaseShift (shiftX, shiftY) = getBaseShift gwnd getBareCellHalf :: BareCellSize -> BareCellHalf getBareCellHalf (BareCellSize s) = BareCellHalf $ s `div` 2 getGridCellSize :: BareCellSize -> CellSpaceSize -> GridCellSize getGridCellSize (BareCellSize bareCellSize) (CellSpaceSize cellSpaceSize) = GridCellSize $ bareCellSize + cellSpaceSize getGlossGridCellSize :: GridCellSize -> GlossGridCellSize getGlossGridCellSize (GridCellSize s) = GlossGridCellSize $ fromIntegral s getGlossBareCellSize :: BareCellSize -> GlossBareCellSize getGlossBareCellSize (BareCellSize s) = GlossBareCellSize $ fromIntegral s
5f5c864fa0d326005d9d11d346978e8868cc095a36e56385bbbed7349bb65af1
synduce/Synduce
Skeleton.ml
open Base open EProps open Term open Option.Let_syntax open Utils (** A type to represent a grammar guess. *) type t = | SChoice of t list (** A choice of possible guesses. *) | SBin of Binop.t * t * t (** A binary expression. *) | SUn of Unop.t * t (** A unary expression. *) | SIte of t * t * t (** An if-then-else. *) | SType of RType.t (** A guess of some type (to be filled with the appropriate non-terminal). *) | STypedWith of RType.t * t list | SArg of int (** A direct reference to a function argument. *) | STuple of t list | SNonGuessable let rec pp (frmt : Formatter.t) (sk : t) : unit = match sk with | SChoice l -> Fmt.(pf frmt "(%a)" (list ~sep:vbar pp) l) | SBin (op, a, b) -> Fmt.(pf frmt "(%a %a %a)" Binop.pp op (box pp) a (box pp) b) | SUn (op, a) -> Fmt.(pf frmt "(%a %a)" Unop.pp op (box pp) a) | SIte (a, b, c) -> Fmt.(pf frmt "(ite@;%a@;%a@;%a)" (box pp) a (box pp) b (box pp) c) | SType t -> Fmt.(pf frmt "<%a?>" RType.pp t) | STypedWith (t, choices) -> Fmt.(pf frmt "<%a?>(%a)" RType.pp t (box (list ~sep:sp pp)) choices) | SArg i -> Fmt.(pf frmt "@%i" i) | STuple tl -> Fmt.(pf frmt "(tuple %a)" (box (list ~sep:sp pp)) tl) | SNonGuessable -> Fmt.(pf frmt "!?") ;; let rec of_expression ~(ctx : RContext.t) : Expression.t -> t option = function | EInt _ -> Some (SType RType.TInt) | EChar _ -> Some (SType RType.TChar) | EFalse | ETrue -> Some (SType RType.TBool) | EEmptySet t -> Some (SType (RType.TSet t)) | EApp (_, _) -> None | EVar v -> Option.( RContext.get_var ctx v >>= Variable.vtype ctx.parent >>= fun t -> Some (SType t)) | EBox boxkind -> (match boxkind with | Expression.Position i -> Some (SArg i) | _ -> None) | ETup tl -> let%map tl = all_or_none (List.map ~f:(of_expression ~ctx) tl) in STuple tl | EIte (a, b, c) -> let%bind a = of_expression ~ctx a in let%bind b = of_expression ~ctx b in let%map c = of_expression ~ctx c in SIte (a, b, c) | ESel _ | EData _ -> None | EOp (op, args) -> (match op with | Unary uop -> (match args with | [ arg ] -> let%map arg = of_expression ~ctx arg in SUn (uop, arg) | _ -> None) | Binary bop -> (match args with | arg1 :: arg2 :: tl -> let%bind arg1 = of_expression ~ctx arg1 in let%map arg2 = of_expression ~ctx (EOp (Binary bop, arg2 :: tl)) in SBin (bop, arg1, arg2) | [ arg ] -> of_expression ~ctx arg | [] -> None)) ;;
null
https://raw.githubusercontent.com/synduce/Synduce/48a258db3fc677d97587d0fb34eaa11f9d239ed5/src/lang/Skeleton.ml
ocaml
* A type to represent a grammar guess. * A choice of possible guesses. * A binary expression. * A unary expression. * An if-then-else. * A guess of some type (to be filled with the appropriate non-terminal). * A direct reference to a function argument.
open Base open EProps open Term open Option.Let_syntax open Utils type t = | SType of RType.t | STypedWith of RType.t * t list | STuple of t list | SNonGuessable let rec pp (frmt : Formatter.t) (sk : t) : unit = match sk with | SChoice l -> Fmt.(pf frmt "(%a)" (list ~sep:vbar pp) l) | SBin (op, a, b) -> Fmt.(pf frmt "(%a %a %a)" Binop.pp op (box pp) a (box pp) b) | SUn (op, a) -> Fmt.(pf frmt "(%a %a)" Unop.pp op (box pp) a) | SIte (a, b, c) -> Fmt.(pf frmt "(ite@;%a@;%a@;%a)" (box pp) a (box pp) b (box pp) c) | SType t -> Fmt.(pf frmt "<%a?>" RType.pp t) | STypedWith (t, choices) -> Fmt.(pf frmt "<%a?>(%a)" RType.pp t (box (list ~sep:sp pp)) choices) | SArg i -> Fmt.(pf frmt "@%i" i) | STuple tl -> Fmt.(pf frmt "(tuple %a)" (box (list ~sep:sp pp)) tl) | SNonGuessable -> Fmt.(pf frmt "!?") ;; let rec of_expression ~(ctx : RContext.t) : Expression.t -> t option = function | EInt _ -> Some (SType RType.TInt) | EChar _ -> Some (SType RType.TChar) | EFalse | ETrue -> Some (SType RType.TBool) | EEmptySet t -> Some (SType (RType.TSet t)) | EApp (_, _) -> None | EVar v -> Option.( RContext.get_var ctx v >>= Variable.vtype ctx.parent >>= fun t -> Some (SType t)) | EBox boxkind -> (match boxkind with | Expression.Position i -> Some (SArg i) | _ -> None) | ETup tl -> let%map tl = all_or_none (List.map ~f:(of_expression ~ctx) tl) in STuple tl | EIte (a, b, c) -> let%bind a = of_expression ~ctx a in let%bind b = of_expression ~ctx b in let%map c = of_expression ~ctx c in SIte (a, b, c) | ESel _ | EData _ -> None | EOp (op, args) -> (match op with | Unary uop -> (match args with | [ arg ] -> let%map arg = of_expression ~ctx arg in SUn (uop, arg) | _ -> None) | Binary bop -> (match args with | arg1 :: arg2 :: tl -> let%bind arg1 = of_expression ~ctx arg1 in let%map arg2 = of_expression ~ctx (EOp (Binary bop, arg2 :: tl)) in SBin (bop, arg1, arg2) | [ arg ] -> of_expression ~ctx arg | [] -> None)) ;;
0c492125c5fac3cb8f0a918a32b7d22736fcd20787dfb35815a162ee6590dd7a
lukstafi/invargent
Terms.ml
* Data structures and printing for InvarGenT. Released under the GNU General Public Licence ( version 2 or higher ) , NO WARRANTY of correctness etc . ( C ) 2013 @author ( AT ) gmail.com @since Mar 2013 Released under the GNU General Public Licence (version 2 or higher), NO WARRANTY of correctness etc. (C) Lukasz Stafiniak 2013 @author Lukasz Stafiniak lukstafi (AT) gmail.com @since Mar 2013 *) let parse_if_as_integer = ref true let show_extypes = ref false * { 2 Definitions } let debug = ref false open Aux open Defs type cns_name = | CNam of string | Extype of int let tuple = CNam "Tuple" let numtype = CNam "Num" let booltype = CNam "Bool" let stringtype = CNam "String" let builtin_progseq = "builtin_progseq" module CNames = Set.Make (struct type t = cns_name let compare = Pervasives.compare end) let cnames_of_list l = List.fold_right CNames.add l CNames.empty let add_cnames l vs = List.fold_right CNames.add l vs let init_types = cnames_of_list [tuple; numtype; CNam "Int"; CNam "Float"; CNam "Bytes"; CNam "Char"; booltype; stringtype; CNam "Array"] type lc = loc type pat = | Zero | One of loc | PVar of string * loc | PAnd of pat * pat * loc | PCons of cns_name * pat list * loc let pat_loc = function | Zero -> dummy_loc | One loc -> loc | PVar (_, loc) -> loc | PAnd (_, _, loc) -> loc | PCons (_, _, loc) -> loc type ('a, 'b) expr = | Var of string * loc | Num of int * loc | NumAdd of ('a, 'b) expr * ('a, 'b) expr * loc | NumCoef of int * ('a, 'b) expr * loc | String of string * loc | Cons of cns_name * ('a, 'b) expr list * loc | App of ('a, 'b) expr * ('a, 'b) expr * loc | Lam of 'b * ('a, 'b) clause list * loc | ExLam of int * ('a, 'b) clause list * loc | Letrec of string option * 'a * string * ('a, 'b) expr * ('a, 'b) expr * loc | Letin of string option * pat * ('a, 'b) expr * ('a, 'b) expr * loc | AssertFalse of loc | RuntimeFailure of ('a, 'b) expr * loc | AssertLeq of ('a, 'b) expr * ('a, 'b) expr * ('a, 'b) expr * loc | AssertEqty of ('a, 'b) expr * ('a, 'b) expr * ('a, 'b) expr * loc and ('a, 'b) clause = pat * (('a, 'b) expr * ('a, 'b) expr) list * ('a, 'b) expr let rec equal_pat p q = match p, q with | Zero, Zero -> true | One _, One _ -> true | PVar (x, _), PVar (y, _) -> x = y | PAnd (a, b, _), PAnd (c, d, _) -> equal_pat a c && equal_pat b d || equal_pat a d && equal_pat b c | PCons (x, xs, _), PCons (y, ys, _) -> x = y && List.for_all2 equal_pat xs ys | _ -> false let rec equal_expr x y = match x, y with | Var (x, _), Var (y, _) -> x = y | Num (i, _), Num (j, _) -> i = j | NumAdd (a, b, _), NumAdd (c, d, _) -> equal_expr a c && equal_expr b d || equal_expr a d && equal_expr b c | NumCoef (x, a, _), NumCoef (y, b, _) -> x = y && equal_expr a b | String (x, _), String (y, _) -> x = y | Cons (a, xs, _), Cons (b, ys, _) -> a = b && List.for_all2 equal_expr xs ys | App (a, b, _), App (c, d, _) -> equal_expr a c && equal_expr b d | Lam (_, xs, _), Lam (_, ys, _) -> List.for_all2 equal_clause xs ys | ExLam (i, xs, _), ExLam (j, ys, _) -> i = j && List.for_all2 equal_clause xs ys | Letrec (_, _, x, a, b, _), Letrec (_, _, y, c, d, _) -> x = y && equal_expr a c && equal_expr b d | Letin (_, x, a, b, _), Letin (_, y, c, d, _) -> equal_pat x y && equal_expr a c && equal_expr b d | AssertFalse _, AssertFalse _ -> true | RuntimeFailure (s, _), RuntimeFailure (t, _) -> equal_expr s t | AssertLeq (a, b, c, _), AssertLeq (d, e, f, _) -> equal_expr a d && equal_expr b e && equal_expr c f | AssertEqty (a, b, c, _), AssertEqty (d, e, f, _) -> equal_expr a d && equal_expr b e && equal_expr c f | _ -> false and equal_clause (p, xs, a) (q, ys, b) = equal_pat p q && List.for_all2 (fun (a, b) (c, d) -> equal_expr a c && equal_expr b d) xs ys && equal_expr a b let expr_loc = function | Var (_, loc) | Num (_, loc) | NumAdd (_, _, loc) | NumCoef (_, _, loc) | String (_, loc) | Cons (_, _, loc) | App (_, _, loc) | Lam (_, _, loc) | ExLam (_, _, loc) | Letrec (_, _, _, _, _, loc) | Letin (_, _, _, _, loc) | AssertFalse loc | RuntimeFailure (_, loc) | AssertLeq (_, _, _, loc) | AssertEqty (_, _, _, loc) -> loc let clause_loc (pat, _, exp) = loc_union (pat_loc pat) (expr_loc exp) let cns_str = function | CNam c -> c | Extype i -> "Ex"^string_of_int i type alien_subterm = | Num_term of NumDefs.term | Order_term of OrderDefs.term type typ = | TVar of var_name | TCons of cns_name * typ list | Fun of typ * typ | Alien of alien_subterm let tdelta = TVar delta let tdelta' = TVar delta' let num x = Alien (Num_term x) let rec return_type = function | Fun (_, r) -> return_type r | t -> t let rec arg_types = function | Fun (a, r) -> a::arg_types r | t -> [] type uexpr = (unit, unit) expr type iexpr = (int list, (var_name * var_name) list) expr let fuse_exprs = let rec aux e1 e2 = match e1, e2 with | Cons (n1, es, lc1), Cons (n2, fs, lc2) -> assert (n1==n2 && lc1==lc2); Cons (n1, combine es fs, lc1) | NumAdd (e1, e2, lc1), NumAdd (f1, f2, lc2) -> assert (lc1==lc2); NumAdd (aux e1 f1, aux e2 f2, lc1) | NumCoef (x, a, lc1), NumCoef (y, b, lc2) -> assert (x==y && lc1==lc2); NumCoef (x, aux a b, lc1) | App (e1, e2, lc1), App (f1, f2, lc2) -> assert (lc1==lc2); App (aux e1 f1, aux e2 f2, lc1) | Lam (ms, cls1, lc1), Lam (ns, cls2, lc2) -> assert (lc1==lc2); Lam (ms@ns, combine_cls cls1 cls2, lc1) | ExLam (k1, cls1, lc1), ExLam (k2, cls2, lc2) -> assert (k1==k2 && lc1==lc2); ExLam (k1, combine_cls cls1 cls2, lc1) | Letrec (docu1, ms, x, e1, e2, lc1), Letrec (docu2, ns, y, f1, f2, lc2) -> assert (x==y && lc1==lc2 && docu1==docu2); Letrec (docu1, ms@ns, x, aux e1 f1, aux e2 f2, lc1) | Letin (docu1, p1, e1, e2, lc1), Letin (docu2, p2, f1, f2, lc2) -> assert (p1==p2 && lc1==lc2 && docu1==docu2); Letin (docu1, p1, aux e1 f1, aux e2 f2, lc1) | AssertLeq (e1, e2, e3, lc1), AssertLeq (f1, f2, f3, lc2) -> assert (lc1==lc2); AssertLeq (aux e1 f1, aux e2 f2, aux e3 f3, lc1) | AssertEqty (e1, e2, e3, lc1), AssertEqty (f1, f2, f3, lc2) -> assert (lc1==lc2); AssertEqty (aux e1 f1, aux e2 f2, aux e3 f3, lc1) | (Var _ as e), f | (Num _ as e), f | (String _ as e), f | (AssertFalse _ as e), f -> assert (e==f); e | RuntimeFailure (s, lc1), RuntimeFailure (t, lc2) -> assert (lc1==lc2); RuntimeFailure (aux s t, lc1) | _ -> assert false and combine es fs = List.map2 aux es fs and aux_cl (p1, guards1, e1) (p2, guards2, e2) = assert (p1 = p2); let guards = List.map2 (fun (e1, e2) (f1, f2) -> aux e1 f1, aux e2 f2) guards1 guards2 in p1, guards, aux e1 e2 and combine_cls es fs = List.map2 aux_cl es fs in function | [] -> assert false | [e] -> e | e::es -> List.fold_left aux e es * { 3 Mapping and folding } type typ_map = { map_tvar : var_name -> typ; map_tcons : string -> typ list -> typ; map_exty : int -> typ list -> typ; map_fun : typ -> typ -> typ; map_alien : alien_subterm -> typ } type 'a typ_fold = { fold_tvar : var_name -> 'a; fold_tcons : string -> 'a list -> 'a; fold_exty : int -> 'a list -> 'a; fold_fun : 'a -> 'a -> 'a; fold_alien : alien_subterm -> 'a } let typ_id_map = { map_tvar = (fun v -> TVar v); map_tcons = (fun n tys -> TCons (CNam n, tys)); map_exty = (fun i tys -> TCons (Extype i, tys)); map_fun = (fun t1 t2 -> Fun (t1, t2)); map_alien = (fun a -> Alien a) } let typ_make_fold op base = { fold_tvar = (fun _ -> base); fold_tcons = (fun _ tys -> List.fold_left op base tys); fold_exty = (fun _ tys -> List.fold_left op base tys); fold_fun = (fun t1 t2 -> op t1 t2); fold_alien = (fun _ -> base) } let typ_map tmap t = let rec aux = function | TVar v -> tmap.map_tvar v | TCons (CNam n, tys) -> tmap.map_tcons n (List.map aux tys) | TCons (Extype i, tys) -> tmap.map_exty i (List.map aux tys) | Fun (t1, t2) -> tmap.map_fun (aux t1) (aux t2) | Alien a -> tmap.map_alien a in aux t let typ_fold tfold t = let rec aux = function | TVar v -> tfold.fold_tvar v | TCons (CNam n, tys) -> tfold.fold_tcons n (List.map aux tys) | TCons (Extype i, tys) -> tfold.fold_exty i (List.map aux tys) | Fun (t1, t2) -> tfold.fold_fun (aux t1) (aux t2) | Alien a -> tfold.fold_alien a in aux t let sb_typ_unary arg = typ_map {typ_id_map with map_tvar = fun v -> if v = delta then arg else TVar v} let sb_typ_binary arg1 arg2 = typ_map {typ_id_map with map_tvar = fun v -> if v = delta then arg1 else if v = delta' then arg2 else TVar v} * { 3 Zipper } type typ_dir = | TCons_dir of cns_name * typ list * typ list | Fun_left of typ | Fun_right of typ type typ_loc = {typ_sub : typ; typ_ctx : typ_dir list} let typ_up t = match t.typ_sub with | TVar v -> None | TCons (_, []) -> None | TCons (n, t1::ts) -> Some {typ_sub = t1; typ_ctx = TCons_dir (n, [], ts) :: t.typ_ctx} | Fun (t1, t2) -> Some {typ_sub = t1; typ_ctx = Fun_left t2 :: t.typ_ctx} | Alien _ -> None let typ_down t = match t.typ_ctx with | [] -> None | TCons_dir (n, ts_l, ts_r)::ctx -> Some {typ_sub=TCons (n, ts_l@[t.typ_sub]@ts_r); typ_ctx=ctx} | Fun_left t2::ctx -> Some {typ_sub=Fun (t.typ_sub, t2); typ_ctx=ctx} | Fun_right t1::ctx -> Some {typ_sub=Fun (t1, t.typ_sub); typ_ctx=ctx} let rec typ_next ?(same_level=false) t = match t.typ_ctx with | [] -> None | (TCons_dir (n, ts_l, []))::_ when not same_level -> bind_opt (typ_down t) (typ_next ~same_level) | (TCons_dir (n, ts_l, []))::_ (* when same_level *) -> None | (TCons_dir (n, ts_l, t_r::ts_r))::ctx -> Some {typ_sub=t_r; typ_ctx=TCons_dir (n, ts_l@[t.typ_sub], ts_r)::ctx} | Fun_left t2::ctx -> Some {typ_sub = t2; typ_ctx = Fun_right t.typ_sub::ctx} | Fun_right _ :: _ when not same_level -> bind_opt (typ_down t) (typ_next ~same_level) | Fun_right _ :: _ (* when same_level *) -> None let rec typ_out t = if t.typ_ctx = [] then t.typ_sub else match typ_down t with Some t -> typ_out t | None -> assert false * { 3 Substitutions } let alien_term_size = function | Num_term t -> NumDefs.term_size t | Order_term t -> OrderDefs.term_size t let typ_size = typ_fold {(typ_make_fold (fun i j -> i+j+1) 1) with fold_alien = alien_term_size} let fvs_alien_term = function | Num_term t -> NumDefs.fvs_term t | Order_term t -> OrderDefs.fvs_term t let has_var_alien_term v = function | Num_term t -> NumDefs.has_var_term v t | Order_term t -> OrderDefs.has_var_term v t let fvs_typ = typ_fold {(typ_make_fold VarSet.union VarSet.empty) with fold_tvar = (fun v -> VarSet.singleton v); fold_alien = fvs_alien_term} let has_var_typ v = typ_fold {(typ_make_fold (||) false) with fold_tvar = (fun v2 -> v = v2); fold_alien = (has_var_alien_term v)} type subst = (typ * loc) VarMap.t type hvsubst = var_name VarMap.t exception Contradiction of sort * string * (typ * typ) option * loc let num_unbox ~t2 lc = function | Alien (Num_term t) -> t | TVar v when var_sort v = Num_sort -> NumDefs.Lin (1,1,v) | t -> raise (Contradiction (Num_sort, "sort mismatch", Some (t2, t), lc)) let order_unbox ~t2 lc = function | Alien (Order_term t) -> t | TVar v when var_sort v = Order_sort -> OrderDefs.OVar v | t -> raise (Contradiction (Order_sort, "sort mismatch", Some (t2, t), lc)) let num_v_unbox v2 lc = function | Alien (Num_term t) -> t | TVar v when var_sort v = Num_sort -> NumDefs.Lin (1,1,v) | t -> raise (Contradiction (Num_sort, "sort mismatch", Some (TVar v2, t), lc)) let order_v_unbox v2 lc = function | Alien (Order_term t) -> t | TVar v when var_sort v = Order_sort -> OrderDefs.OVar v | t -> raise (Contradiction (Order_sort, "sort mismatch", Some (TVar v2, t), lc)) let subst_alien_term sb = function | Num_term t -> Num_term (NumDefs.subst_term num_v_unbox sb t) | Order_term t -> Order_term (OrderDefs.subst_term order_v_unbox sb t) let subst_typ sb t = if VarMap.is_empty sb then t else typ_map {typ_id_map with map_tvar = (fun v -> try fst (VarMap.find v sb) with Not_found -> TVar v); map_alien = fun t -> Alien (subst_alien_term sb t)} t let hvsubst_alien_term sb = function | Num_term t -> Num_term (NumDefs.hvsubst_term sb t) | Order_term t -> Order_term (OrderDefs.hvsubst_term sb t) let hvsubst_typ sb = typ_map {typ_id_map with map_tvar = (fun v -> TVar (try VarMap.find v sb with Not_found -> v)); map_alien = fun t -> Alien (hvsubst_alien_term sb t)} let subst_one v s t = let modif = ref false in let res = typ_map {typ_id_map with map_tvar = fun w -> if v = w then (modif:=true; s) else TVar w} t in !modif, res let subst_sb ~sb = VarMap.map (fun (t, loc) -> subst_typ sb t, loc) let hvsubst_sb sb = VarMap.map (fun (t, loc) -> hvsubst_typ sb t, loc) let update_sb ~more_sb sb = add_to_varmap (varmap_to_assoc more_sb) (VarMap.map (fun (t, loc) -> subst_typ more_sb t, loc) sb) let update_one_sb x sx sb = let more_sb = VarMap.singleton x sx in VarMap.add x sx (VarMap.map (fun (t, loc as st) -> if has_var_typ x t then subst_typ more_sb t, loc else st) sb) let update_one_sb_check do_check f x sx sb = if not do_check then update_one_sb x sx sb else let more_sb = VarMap.singleton x sx in VarMap.add x sx (VarMap.mapi (fun v (t, loc as st) -> if has_var_typ x t then (f v t loc; subst_typ more_sb t, loc) else st) sb) let revert_renaming sb = varmap_of_assoc (List.map (function | v1, (TVar v2, lc) -> v2, (TVar v1, lc) | v1, (Alien (Num_term (NumDefs.Lin (j,k,v2))), lc) -> v2, (Alien (Num_term (NumDefs.Lin (k,j,v1))), lc) | _ -> assert false) (varmap_to_assoc sb)) let c_subst_typ sb t = let rec aux t = try fst (List.assoc t sb) with Not_found -> match t with | TVar _ -> t | TCons (n, args) -> TCons (n, List.map aux args) | Fun (t1, t2) -> Fun (aux t1, aux t2) | Alien _ -> t in aux t let n_subst_typ sb t = let rec aux = function | TVar _ as t -> t | TCons (n, args) -> (try List.assoc n sb args with Not_found -> TCons (n, List.map aux args)) | Fun (t1, t2) -> Fun (aux t1, aux t2) | Alien _ as n -> n in aux t let map_in_subst f = VarMap.map (fun (t, lc) -> f t, lc) (** {3 Formulas} *) type alien_atom = | Num_atom of NumDefs.atom | Order_atom of OrderDefs.atom type atom = | Eqty of typ * typ * loc | CFalse of loc | PredVarU of int * typ * loc | PredVarB of int * typ * typ * loc | NotEx of typ * loc | RetType of typ * typ * loc | A of alien_atom let a_num a = A (Num_atom a) let fvs_alien_atom = function | Num_atom a -> NumDefs.fvs_atom a | Order_atom a -> OrderDefs.fvs_atom a let fvs_atom = function | Eqty (t1, t2, _) -> VarSet.union (fvs_typ t1) (fvs_typ t2) | CFalse _ -> VarSet.empty | PredVarU (_, t, _) -> fvs_typ t | PredVarB (_, t1, t2, _) -> VarSet.union (fvs_typ t1) (fvs_typ t2) | NotEx (t, _) -> fvs_typ t | RetType (t1, t2, _) -> VarSet.union (fvs_typ t1) (fvs_typ t2) | A a -> fvs_alien_atom a let prim_constr_var = function | Eqty (TVar v, _, _) -> Some v | RetType (TVar v, _, _) -> Some v | A (Num_atom a) -> NumDefs.prim_constr_var a | A (Order_atom a) -> OrderDefs.prim_constr_var a | _ -> None let alien_atom_loc = function | Num_atom a -> NumDefs.atom_loc a | Order_atom a -> OrderDefs.atom_loc a let atom_loc = function | Eqty (_, _, loc) | CFalse loc | PredVarU (_, _, loc) | PredVarB (_, _, _, loc) | NotEx (_, loc) | RetType (_, _, loc) -> loc | A a -> alien_atom_loc a let replace_loc_alien_atom loc = function | Num_atom a -> Num_atom (NumDefs.replace_loc_atom loc a) | Order_atom a -> Order_atom (OrderDefs.replace_loc_atom loc a) let replace_loc_atom loc = function | Eqty (t1, t2, _) -> Eqty (t1, t2, loc) | CFalse _ -> CFalse loc | PredVarU (n, t, _) -> PredVarU (n, t, loc) | PredVarB (n, t1, t2, _) -> PredVarB (n, t1, t2, loc) | NotEx (t, _) -> NotEx (t, loc) | RetType (t1, t2, _) -> RetType (t1, t2, loc) | A a -> A (replace_loc_alien_atom loc a) let eq_alien_atom = function | Num_atom a1, Num_atom a2 -> NumDefs.eq_atom a1 a2 | Order_atom a1, Order_atom a2 -> OrderDefs.eq_atom a1 a2 | _ -> false let eq_atom a1 a2 = a1 == a2 || match a1, a2 with | Eqty (t1, t2, _), Eqty (t3, t4, _) when t1=t3 && t2=t4 || t1=t4 && t2=t3 -> true | CFalse _, CFalse _ -> true | PredVarU (n1, t1, _), PredVarU (n2, t2, _) when n1=n2 && t1=t2 -> true | PredVarB (n1, t1, t2, _), PredVarB (n2, t3, t4, _) when n1=n2 && t1=t3 && t2=t4 -> true | A a1, A a2 -> eq_alien_atom (a1, a2) | _ -> false (* TODO: optimize *) let subformula phi1 phi2 = List.for_all (fun a1 -> List.exists (eq_atom a1) phi2) phi1 let formula_inter cnj1 cnj2 = List.filter (fun a -> List.exists (eq_atom a) cnj2) cnj1 let formula_diff cnj1 cnj2 = List.filter (fun a -> not (List.exists (eq_atom a) cnj2)) cnj1 let subst_alien_atom sb = function | Num_atom a -> Num_atom (NumDefs.subst_atom num_v_unbox sb a) | Order_atom a -> Order_atom (OrderDefs.subst_atom order_v_unbox sb a) let subst_atom sb = function | Eqty (t1, t2, loc) -> Eqty (subst_typ sb t1, subst_typ sb t2, loc) | CFalse _ as a -> a | PredVarU (n, t, lc) -> PredVarU (n, subst_typ sb t, lc) | PredVarB (n, t1, t2, lc) -> PredVarB (n, subst_typ sb t1, subst_typ sb t2, lc) | NotEx (t, lc) -> NotEx (subst_typ sb t, lc) | RetType (t1, t2, lc) -> RetType (subst_typ sb t1, subst_typ sb t2, lc) | A a -> A (subst_alien_atom sb a) let hvsubst_alien_atom sb = function | Num_atom a -> Num_atom (NumDefs.hvsubst_atom sb a) | Order_atom a -> Order_atom (OrderDefs.hvsubst_atom sb a) let hvsubst_atom sb = function | Eqty (t1, t2, loc) -> Eqty (hvsubst_typ sb t1, hvsubst_typ sb t2, loc) | CFalse _ as a -> a | PredVarU (n, t, lc) -> PredVarU (n, hvsubst_typ sb t, lc) | PredVarB (n, t1, t2, lc) -> PredVarB (n, hvsubst_typ sb t1, hvsubst_typ sb t2, lc) | NotEx (t, lc) -> NotEx (hvsubst_typ sb t, lc) | RetType (t1, t2, lc) -> RetType (hvsubst_typ sb t1, hvsubst_typ sb t2, lc) | A a -> A (hvsubst_alien_atom sb a) let sb_atom_unary arg = function | Eqty (t1, t2, lc) -> Eqty (sb_typ_unary arg t1, sb_typ_unary arg t2, lc) | CFalse _ as a -> a | PredVarU (_, t, _) -> assert false | PredVarB (_, t1, t2, _) -> assert false | NotEx _ -> assert false | RetType (t1, t2, lc) -> assert false | A _ as a -> a let sb_atom_binary arg1 arg2 = function | Eqty (t1, t2, lc) -> Eqty (sb_typ_binary arg1 arg2 t1, sb_typ_binary arg1 arg2 t2, lc) | CFalse _ as a -> a | PredVarU (_, t, _) -> assert false | PredVarB (_, t1, t2, _) -> assert false | NotEx _ -> assert false | RetType _ -> assert false | A _ as a -> a let subst_fo_atom sb = function | Eqty (t1, t2, loc) -> Eqty (subst_typ sb t1, subst_typ sb t2, loc) | RetType (t1, t2, loc) -> RetType (subst_typ sb t1, subst_typ sb t2, loc) | CFalse _ as a -> a | (PredVarU _ | PredVarB _ | NotEx _) as a -> a | A a -> A (subst_alien_atom sb a) let alien_atom_size = function | Num_atom a -> NumDefs.atom_size a | Order_atom a -> OrderDefs.atom_size a let atom_size = function | Eqty (t1, t2, _) -> typ_size t1 + typ_size t2 + 1 | RetType (t1, t2, _) -> typ_size t1 + typ_size t2 + 1 | CFalse _ -> 1 | PredVarU (_, t, _) -> typ_size t + 1 | PredVarB (_, t1, t2, _) -> typ_size t1 + typ_size t2 + 1 | NotEx (t, _) -> typ_size t + 1 | A a -> alien_atom_size a type formula = atom list type sep_formula = { cnj_typ : subst; cnj_num : NumDefs.formula; cnj_ord : OrderDefs.formula; cnj_so : formula } type ('a, 'b, 'c, 'd) sep_sorts = { at_typ : 'a; at_num : 'b; at_ord : 'c; at_so : 'd } let fvs_formula phi = List.fold_left VarSet.union VarSet.empty (List.map fvs_atom phi) let fvs_typs phi = List.fold_left VarSet.union VarSet.empty (List.map fvs_typ phi) let fvs_sb sb = VarMap.fold (fun v (t, _) acc -> VarSet.add v (VarSet.union (fvs_typ t) acc)) sb VarSet.empty let subst_formula sb phi = if VarMap.is_empty sb then phi else List.map (subst_atom sb) phi let hvsubst_formula sb phi = List.map (hvsubst_atom sb) phi let update_sep ?(typ_updated=false) ~more phi = {cnj_typ = if typ_updated then more.cnj_typ else update_sb ~more_sb:more.cnj_typ phi.cnj_typ; cnj_num = more.cnj_num @ phi.cnj_num; cnj_ord = more.cnj_ord @ phi.cnj_ord; cnj_so = more.cnj_so @ phi.cnj_so} let typ_sort = function | TCons _ | Fun _ -> Type_sort | TVar (VNam (s, _) | VId (s, _)) -> s | Alien (Num_term _) -> Num_sort | Alien (Order_term _) -> Order_sort let sep_formulas cnj = let cnj_typ, cnj_num, cnj_ord, cnj_so = List.fold_left (fun (cnj_typ, cnj_num, cnj_ord, cnj_so) -> function | (Eqty (TVar v, t, lc) | Eqty (t, TVar v, lc)) when var_sort v = Type_sort -> VarMap.add v (t,lc) cnj_typ, cnj_num, cnj_ord, cnj_so | Eqty (t1, t2, lc) when typ_sort t1 = Num_sort -> cnj_typ, NumDefs.Eq (num_unbox ~t2 lc t1, num_unbox ~t2:t1 lc t2, lc) ::cnj_num, cnj_ord, cnj_so | Eqty _ -> assert false | A (Num_atom a) -> cnj_typ, a::cnj_num, cnj_ord, cnj_so | A (Order_atom a) -> cnj_typ, cnj_num, a::cnj_ord, cnj_so | (PredVarU _ | PredVarB _ | NotEx _ | CFalse _ | RetType _) as a -> cnj_typ, cnj_num, cnj_ord, a::cnj_so) (VarMap.empty, [], [], []) cnj in {cnj_typ; cnj_num; cnj_ord; cnj_so} let sep_unsolved cnj = let new_notex = ref false in let at_typ, at_num, at_ord, at_so = List.fold_left (fun (cnj_typ, cnj_num, cnj_ord, cnj_so) -> function | Eqty (t1, t2, loc) when typ_sort t1 = Type_sort -> (t1, t2, loc)::cnj_typ, cnj_num, cnj_ord, cnj_so | Eqty (t1, t2, lc) when typ_sort t1 = Num_sort -> cnj_typ, NumDefs.Eq (num_unbox ~t2 lc t1, num_unbox ~t2:t1 lc t2, lc) ::cnj_num, cnj_ord, cnj_so | Eqty (t1, t2, lc) when typ_sort t1 = Order_sort -> cnj_typ, cnj_num, OrderDefs.Eq (order_unbox ~t2 lc t1, order_unbox ~t2:t1 lc t2, lc) ::cnj_ord, cnj_so | Eqty _ -> assert false | A (Num_atom a) -> cnj_typ, a::cnj_num, cnj_ord, cnj_so | A (Order_atom a) -> cnj_typ, cnj_num, a::cnj_ord, cnj_so | NotEx _ as a -> new_notex := true; cnj_typ, cnj_num, cnj_ord, a::cnj_so | (PredVarU _ | PredVarB _ | CFalse _ | RetType _) as a -> cnj_typ, cnj_num, cnj_ord, a::cnj_so) ([], [], [], []) cnj in !new_notex, {at_typ; at_num; at_ord; at_so} let assoc_to_formula sb = List.fold_left (fun acc (v, (t,loc)) -> Eqty (TVar v, t, loc)::acc) [] sb let to_formula sb = VarMap.fold (fun v (t,loc) acc -> Eqty (TVar v, t, loc)::acc) sb [] let unsep_formulas {cnj_typ; cnj_so; cnj_num} = cnj_so @ to_formula cnj_typ @ List.map (fun a -> A (Num_atom a)) cnj_num let replace_loc loc phi = List.map (replace_loc_atom loc) phi let formula_loc phi = List.fold_left loc_union dummy_loc (List.map atom_loc phi) let subst_fo_formula sb phi = if VarMap.is_empty sb then phi else List.map (subst_fo_atom sb) phi let sb_phi_unary arg = List.map (sb_atom_unary arg) let sb_phi_binary arg1 arg2 = List.map (sb_atom_binary arg1 arg2) type typ_scheme = var_name list * formula * typ type answer = var_name list * formula * The annotation , besides providing the type scheme , tells whether nested type schemes have free variables in scope of the scheme . On [ ] annotations , provides the argument and the return type separately . nested type schemes have free variables in scope of the scheme. On [Lam] annotations, provides the argument and the return type separately. *) type texpr = (typ_scheme * bool, (typ * typ) option) expr let extype_id = ref 0 let predvar_id = ref 0 type struct_item = | TypConstr of string option * cns_name * sort list * loc | PrimTyp of string option * cns_name * sort list * string * loc | ValConstr of string option * cns_name * var_name list * formula * typ list * cns_name * var_name list * loc | PrimVal of string option * string * typ_scheme * (string, string) choice * loc | LetRecVal of string option * string * uexpr * typ_scheme option * uexpr list * loc | LetVal of string option * pat * uexpr * typ_scheme option * loc type annot_item = | ITypConstr of string option * cns_name * sort list * loc | IPrimTyp of string option * cns_name * sort list * string * loc | IValConstr of string option * cns_name * var_name list * formula * typ list * cns_name * typ list * loc | IPrimVal of string option * string * typ_scheme * (string, string) choice * loc | ILetRecVal of string option * string * texpr * typ_scheme * texpr list * (pat * int option) list * loc | ILetVal of string option * pat * texpr * typ_scheme * (string * typ_scheme) list * (pat * int option) list * loc let rec enc_funtype res = function | [] -> res | arg::args -> Fun (arg, enc_funtype res args) let typ_scheme_of_item ?(env=[]) = function | TypConstr _ -> raise Not_found | PrimTyp _ -> raise Not_found | ValConstr (_, _, vs, phi, args, c_n, c_args, _) -> vs, phi, enc_funtype (TCons (c_n, List.map (fun v->TVar v) c_args)) args | PrimVal (_, _, t, _, _) -> t | LetRecVal (_, name, _, _, _, _) | LetVal (_, PVar (name, _), _, _, _) -> List.assoc name env | LetVal _ -> raise Not_found exception NoAnswer of sort * string * (typ * typ) option * loc exception Suspect of formula * loc let convert = function | NoAnswer (sort, msg, tys, lc) -> Contradiction (sort, msg, tys, lc) | Contradiction (sort, msg, tys, lc) -> NoAnswer (sort, msg, tys, lc) | e -> e let alien_atom_sort = function | Num_atom _ -> Num_sort | Order_atom _ -> Order_sort let atom_sort = function | Eqty (t1, t2, lc) -> let s1 = typ_sort t1 and s2 = typ_sort t2 in if s1 = s2 then s1 else raise (Contradiction (s1, "Sort mismatch", Some (t1, t2), lc)) | RetType _ -> Type_sort | CFalse _ -> Type_sort | PredVarU _ -> Type_sort | PredVarB _ -> Type_sort | NotEx _ -> Type_sort | A a -> alien_atom_sort a * { 2 Global tables } type sigma = (cns_name, var_name list * formula * typ list * cns_name * var_name list) Hashtbl.t let sigma : sigma = Hashtbl.create 128 let ex_type_chi = Hashtbl.create 128 let all_ex_types = ref [] * { 2 Printing } open Format let rec pr_pat ppf = function | Zero -> fprintf ppf "%s" "!" | One _ -> fprintf ppf "%s" "_" | PVar (x, _) -> fprintf ppf "%s" x | PAnd (pat1, pat2, _) -> fprintf ppf "@[<2>%a@ as@ %a@]" pr_pat pat1 pr_more_pat pat2 | PCons (CNam "Tuple", pats, _) -> fprintf ppf "@[<2>(%a)@]" (pr_sep_list "," ~pr_hd:pr_pat pr_more_pat) pats | PCons (x, [], _) -> fprintf ppf "%s" (cns_str x) | PCons (x, [pat], _) -> fprintf ppf "@[<2>%s@ %a@]" (cns_str x) pr_one_pat pat | PCons (x, pats, _) -> fprintf ppf "@[<2>%s@ (%a)@]" (cns_str x) (pr_sep_list "," ~pr_hd:pr_pat pr_more_pat) pats and pr_more_pat ppf = function | PAnd _ as p -> fprintf ppf "(%a)" (pr_pat) p | p -> pr_pat ppf p and pr_one_pat ppf = function | Zero -> fprintf ppf "%s" "!" | One _ -> fprintf ppf "%s" "_" | PVar (x, _) -> fprintf ppf "%s" x | PCons (CNam "Tuple", pats, _) -> fprintf ppf "@[<2>(%a)@]" (pr_sep_list "," ~pr_hd:pr_pat pr_more_pat) pats | PCons (x, [], _) -> fprintf ppf "%s" (cns_str x) | p -> fprintf ppf "(%a)" pr_pat p let collect_lambdas e = let rec aux pats = function | Lam (_, [pat, [], exp], _) -> aux (pat::pats) exp | expr -> List.rev pats, expr in aux [] e let rec collect_apps e = let rec aux args = function | App (f, arg, _) -> aux (arg::args) f | expr -> expr::args in aux [] e type ('a, 'b) pr_expr_annot = | LetRecNode of 'a | LamNode of 'b | MatchVal of 'b | MatchRes of 'b | LamOpen of 'b | MatchValOpen of 'b | MatchResOpen of 'b | LetInOpen of 'b | LetInNode of 'b let pr_expr ?export_num ?export_if ?export_bool ?export_progseq ?export_runtime_failure pr_ann ppf exp = let rec aux ppf = function | Var (s, _) -> fprintf ppf "%s" s | String (s, _) -> fprintf ppf "\"%s\"" s | Num (i, _) -> (match export_num with | None -> fprintf ppf "%d" i | Some (fname, _, _, _, _) -> fprintf ppf "(%s %d)" fname i) | NumAdd (a, b, _) -> (match export_num with | None -> fprintf ppf "@[<2>%a@ +@ %a@]" aux a aux b | Some (_, lbr, op, _, rbr) -> fprintf ppf "@[<2>%s%a@ %s@ %a%s@]" lbr aux a op aux b rbr) | NumCoef (x, a, _) -> (match export_num with | None -> fprintf ppf "@[<2>%d@ *@ %a@]" x aux a | Some (fname, lbr, _, op, rbr) -> fprintf ppf "@[<2>%s%s %d@ %s@ %a%s@]" lbr fname x op aux a rbr) | Cons (CNam "Tuple", exps, _) -> fprintf ppf "@[<2>(%a)@]" (pr_sep_list "," aux) exps | Cons (CNam "True", [], _) when export_bool <> None -> fprintf ppf "%s" (try List.assoc true (unsome export_bool) with Not_found -> "true") | Cons (CNam "False", [], _) when export_bool <> None -> fprintf ppf "%s" (try List.assoc false (unsome export_bool) with Not_found -> "false") | App (App (Var (f, _), e1, _), e2, _) when f = builtin_progseq -> let kwd_beg, kwd_mid, kwd_end = try unsome export_progseq with Not_found -> "(", ";", ")" in fprintf ppf "@[<0>(%s%a@ %s@ %a%s)@]" kwd_beg aux e1 kwd_mid aux e2 kwd_end | App (Lam (_, [PCons (CNam "True", [], _), [], e1; PCons (CNam "False", [], _), [], e2], _), cond, _) when export_if <> None -> let kwd_if, kwd_then, kwd_else = try unsome export_if with Not_found -> "if", "then", "else" in fprintf ppf "@[<0>(%s@ %a@ %s@ %a@ %s@ %a)@]" kwd_if aux cond kwd_then aux e1 kwd_else aux e2 | App (Lam (_, [PCons (CNam "False", [], _), [], e1; PCons (CNam "True", [], _), [], e2], _), cond, _) when export_if <> None -> let kwd_if, kwd_then, kwd_else = try unsome export_if with Not_found -> "if", "then", "else" in fprintf ppf "@[<0>(%s@ %a@ %s@ %a@ %s@ %a)@]" kwd_if aux cond kwd_then aux e1 kwd_else aux e2 | App (Lam (_, [One _, ([lhs1, rhs1] as ineqs), e1; One _, [NumAdd (rhs2, Num (1, _), _), lhs2], e2], _), Cons (CNam "Tuple", [], _), _) when export_if <> None && equal_expr lhs1 lhs2 && equal_expr rhs1 rhs2 -> let kwd_if, kwd_then, kwd_else = try unsome export_if with Not_found -> "if", "then", "else" in fprintf ppf "@[<0>(%s@ %a@ %s@ %a@ %s@ %a)@]" kwd_if (pr_sep_list "&&" pr_guard_leq) ineqs kwd_then aux e1 kwd_else aux e2 | App (Lam (_, [One _, ineqs, e1; One _, [], e2], _), Cons (CNam "Tuple", [], _), _) when export_if <> None -> let kwd_if, kwd_then, kwd_else = try unsome export_if with Not_found -> "if", "then", "else" in fprintf ppf "@[<0>(%s@ %a@ %s@ %a@ %s@ %a)@]" kwd_if (pr_sep_list "&&" pr_guard_leq) ineqs kwd_then aux e1 kwd_else aux e2 | Cons (x, [], _) -> fprintf ppf "%s" (cns_str x) | Cons (x, [exp], _) -> fprintf ppf "@[<2>%s@ %a@]" (cns_str x) (pr_one_expr pr_ann) exp | Cons (x, exps, _) -> fprintf ppf "@[<2>%s@ (%a)@]" (cns_str x) (pr_sep_list "," aux) exps | Lam (_, [_], _) as exp -> let pats, expr = collect_lambdas exp in fprintf ppf "@[<2>(fun@ %a@ ->@ %a)@]" (pr_sep_list "" pr_one_pat) pats aux expr | Lam (ann, cs, _) -> fprintf ppf "@[<2>%a(function@ %a)%a@]" pr_ann (LamOpen ann) (pr_pre_sep_list "| " (pr_clause pr_ann)) cs pr_ann (LamNode ann) | ExLam (_, cs, _) -> fprintf ppf "@[<0>(efunction@ %a)@]" (pr_pre_sep_list "| " (pr_clause pr_ann)) cs | App (Lam (ann, [(v,[],body)], _), def, _) -> fprintf ppf "@[<0>let@ @[<4>%a%a%a@] =@ @[<2>%a@]@ in@ @[<0>%a@]@]" pr_ann (LetInOpen ann) pr_more_pat v pr_ann (LetInNode ann) aux def aux body | App (Lam (ann, cls, _), def, _) -> fprintf ppf "@[<0>%a(match@ @[<4>%a%a%a@] with@ @[<2>%a@])%a@]" pr_ann (MatchResOpen ann) pr_ann (MatchValOpen ann) aux def pr_ann (MatchVal ann) (pr_pre_sep_list "| " (pr_clause pr_ann)) cls pr_ann (MatchRes ann) | App _ as exp -> let fargs = collect_apps exp in fprintf ppf "@[<2>%a@]" (pr_sep_list "" (pr_one_expr pr_ann)) fargs | Letrec (docu, ann, x, exp, range, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<0>let rec %s@ %a=@ @[<2>%a@] in@ @[<0>%a@]@]" x pr_ann (LetRecNode ann) aux exp aux range | Letin (docu, pat, exp, range, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<0>let %a =@ @[<2>%a@] in@ @[<0>%a@]@]" pr_pat pat aux exp aux range | AssertFalse _ -> fprintf ppf "assert false" | RuntimeFailure (s, _) -> (match export_runtime_failure with | None -> fprintf ppf "@[<2>(runtime_failure@ %a)@]" aux s | Some fname -> fprintf ppf "@[<2>(%s@ %a)@]" fname aux s) | AssertLeq (e1, e2, range, _) -> fprintf ppf "@[<0>assert@[<2>@ %a@ ≤@ %a@];@ %a@]" aux e1 aux e2 aux range | AssertEqty (e1, e2, range, _) -> fprintf ppf "@[<0>assert@ = type@[<2>@ %a@ %a@];@ %a@]" aux e1 aux e2 aux range and pr_guard_leq ppf (e1, e2) = fprintf ppf "@[<2>%a@ <=@ %a@]" aux e1 aux e2 and pr_clause pr_ann ppf (pat, guards, exp) = if guards = [] then fprintf ppf "@[<2>%a@ ->@ %a@]" pr_pat pat aux exp else fprintf ppf "@[<2>%a@ when@ %a@ ->@ %a@]" pr_pat pat (pr_sep_list "&&" pr_guard_leq) guards aux exp and pr_one_expr pr_ann ppf exp = match exp with | Var _ | Num _ | Cons (_, [], _) -> aux ppf exp | _ -> fprintf ppf "(%a)" aux exp in aux ppf exp let pr_uexpr ppf = pr_expr (fun ppf _ -> fprintf ppf "") ppf let pr_iexpr ppf = pr_expr (fun ppf _ -> fprintf ppf "") ppf let collect_argtys ty = let rec aux args = function | Fun (arg, res) -> aux (arg::args) res | res -> res::args in List.rev (aux [] ty) let pr_exty = ref (fun ppf (i, rty) -> failwith "not implemented") let pr_alien_atom ppf = function | Num_atom a -> NumDefs.pr_atom ppf a | Order_atom a -> OrderDefs.pr_atom ppf a let pr_alien_ty ppf = function | Num_term t -> NumDefs.pr_term ppf t | Order_term t -> OrderDefs.pr_term ppf t let alien_no_parens = function | Num_term t -> NumDefs.term_no_parens t | Order_term t -> OrderDefs.term_no_parens t (* Using "X" because "script chi" is not available on all systems. *) let rec pr_atom ppf = function | Eqty (t1, t2, _) -> fprintf ppf "@[<2>%a@ =@ %a@]" pr_one_ty t1 pr_one_ty t2 | RetType (t1, t2, _) -> fprintf ppf "@[<2>RetType@ (%a,@ %a)@]" pr_one_ty t1 pr_one_ty t2 | CFalse _ -> pp_print_string ppf "FALSE" | PredVarU (i,ty,lc) -> fprintf ppf "@[<2>X%d(%a)@]" i pr_ty ty | PredVarB (i,t1,t2,lc) -> fprintf ppf "@[<2>X%d(%a,@ %a)@]" i pr_ty t1 pr_ty t2 | NotEx (t,lc) -> fprintf ppf "@[<2>NotEx(%a)@]" pr_ty t | A a -> pr_alien_atom ppf a and pr_formula ppf atoms = pr_sep_list " ∧" pr_atom ppf atoms and pr_ty ppf = function | TVar v -> fprintf ppf "%s" (var_str v) | TCons (CNam "Tuple", []) -> fprintf ppf "()" | TCons (CNam c, []) -> fprintf ppf "%s" c | TCons (CNam "Tuple", exps) -> fprintf ppf "@[<2>(%a)@]" (pr_sep_list "," pr_ty) exps | TCons (CNam c, [(TVar _ | TCons (_, [])) as ty]) -> fprintf ppf "@[<2>%s@ %a@]" c pr_one_ty ty | TCons (CNam c, [Alien t as ty]) when alien_no_parens t -> fprintf ppf "@[<2>%s@ %a@]" c pr_one_ty ty | TCons (CNam c, exps) -> fprintf ppf "@[<2>%s@ (%a)@]" c (pr_sep_list "," pr_ty ) exps | TCons (Extype i, args) -> !pr_exty ppf (i, args) | Fun _ as ty -> let tys = collect_argtys ty in fprintf ppf "@[<2>%a@]" (pr_sep_list " →" pr_fun_ty) tys | Alien t -> pr_alien_ty ppf t and pr_one_ty ppf ty = match ty with | TVar _ | Alien _ | TCons (_, []) -> pr_ty ppf ty | _ -> fprintf ppf "(%a)" pr_ty ty and pr_fun_ty ppf ty = match ty with | Fun _ -> fprintf ppf "(%a)" pr_ty ty | _ -> pr_ty ppf ty let pr_sort ppf = function | Num_sort -> fprintf ppf "num" | Type_sort -> fprintf ppf "type" | Order_sort -> fprintf ppf "order" let pr_cns ppf name = fprintf ppf "%s" (cns_str name) let pr_typscheme ppf = function | [], [], ty -> pr_ty ppf ty | vs, [], ty -> fprintf ppf "@[<0>∀%a.@ %a@]" (pr_sep_list "," pr_tyvar) vs pr_ty ty | vs, phi, ty -> fprintf ppf "@[<0>∀%a[%a].@ %a@]" (pr_sep_list "," pr_tyvar) vs pr_formula phi pr_ty ty let pr_ans ppf = function | [], ans -> pr_formula ppf ans | vs, ans -> fprintf ppf "@[<2>∃%a.@ %a@]" (pr_sep_list "," pr_tyvar) vs pr_formula ans let pr_subst ppf sb = pr_sep_list ";" (fun ppf (v,(t,_)) -> fprintf ppf "%s:=%a" (var_str v) pr_ty t) ppf (varmap_to_assoc sb) let pr_hvsubst ppf sb = pr_sep_list ";" (fun ppf (v,t) -> fprintf ppf "%s:=%s" (var_str v) (var_str t)) ppf (varmap_to_assoc sb) let pr_typ_dir ppf = function | TCons_dir (n, ts_l, []) -> fprintf ppf "@[<2>%s@ (%a,@ ^)@]" (cns_str n) (pr_sep_list "," pr_ty) ts_l | TCons_dir (n, ts_l, ts_r) -> fprintf ppf "@[<2>%s@ (%a,@ ^,@ %a)@]" (cns_str n) (pr_sep_list "," pr_ty) ts_l (pr_sep_list "," pr_ty) ts_r | Fun_left t2 -> fprintf ppf "@[<2>^ →@ %a@]" pr_ty t2 | Fun_right t1 -> fprintf ppf "@[<2>%a →@ ^@]" pr_ty t1 let pr_typ_loc ppf t = fprintf ppf "@[<2>%a@ <-@ [%a]@]" pr_ty t.typ_sub (pr_sep_list ";" pr_typ_dir) t.typ_ctx let pr_opt_sig_tysch ppf = function | None -> () | Some tysch -> fprintf ppf "@ :@ %a" pr_typscheme tysch let pr_opt_tests pr_ann ppf = function | [] -> () | tests -> fprintf ppf "@\n@[<2>test@ %a@]" (pr_sep_list ";" (pr_expr pr_ann)) tests let pr_opt_utests = pr_opt_tests (fun ppf _ -> fprintf ppf "") let pr_sig_item ppf = function | ITypConstr (_, Extype _, _, _) when not !show_extypes -> () | ITypConstr (docu, name, [], _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>datatype@ %s@]" (cns_str name) | IPrimTyp (docu, name, [], _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external type@ %s@]" (cns_str name) | ITypConstr (docu, name, sorts, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>datatype@ %s@ :@ %a@]" (cns_str name) (pr_sep_list " *" pr_sort) sorts | IPrimTyp (docu, name, sorts, _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external type@ %s@ :@ %a@]" (cns_str name) (pr_sep_list " *" pr_sort) sorts | IValConstr (_, Extype _, _, _, _, Extype _, _, _) when not !show_extypes -> () | IValConstr (docu, name, [], [], [], c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ %a@]" (cns_str name) pr_ty res | IValConstr (docu, name, [], [], args, c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ %a@ ⟶@ %a@]" (cns_str name) (pr_sep_list " *" pr_ty) args pr_ty res | IValConstr (docu, name, vs, [], [], c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ ∀%a.@ %a@]" (cns_str name) (pr_sep_list "," pr_tyvar) vs pr_ty res | IValConstr (docu, name, vs, phi, [], c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ ∀%a[%a].@ %a@]" (cns_str name) (pr_sep_list "," pr_tyvar) vs pr_formula phi pr_ty res | IValConstr (docu, name, vs, [], args, c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ ∀%a.%a@ ⟶@ %a@]" (cns_str name) (pr_sep_list "," pr_tyvar) vs (pr_sep_list " *" pr_ty) args pr_ty res | IValConstr (docu, name, vs, phi, args, c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ ∀%a[%a].%a@ ⟶@ %a@]" (cns_str name) (pr_sep_list "," pr_tyvar) vs pr_formula phi (pr_sep_list " *" pr_ty) args pr_ty res | IPrimVal (docu, name, tysch, Left _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external@ %s@ :@ %a@]" name pr_typscheme tysch | IPrimVal (docu, name, tysch, Right _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external val@ %s@ :@ %a@]" name pr_typscheme tysch | ILetRecVal (docu, name, expr, tysch, tests, _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>val@ %s :@ %a@]" name pr_typscheme tysch | ILetVal (docu, _, _, _, tyschs, _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); pr_line_list "\n" (fun ppf (name,tysch) -> fprintf ppf "@[<2>val@ %s :@ %a@]" name pr_typscheme tysch) ppf tyschs let pr_signature ppf p = let p = if !show_extypes then p else List.filter (function | ITypConstr (_, Extype _, _, _) | IValConstr (_, Extype _, _, _, _, Extype _, _, _) -> false | _ -> true) p in pr_line_list "\n" pr_sig_item ppf p let pr_struct_item ppf = function | TypConstr (docu, name, sorts, lc) -> pr_sig_item ppf (ITypConstr (docu, name, sorts, lc)) | PrimTyp (docu, name, sorts, expansion, lc) -> fprintf ppf "@[<2>%a@ =@ \"%s\"@]" pr_sig_item (IPrimTyp (docu, name, sorts, expansion, lc)) expansion | ValConstr (docu, name, vs, phi, args, c_n, c_args, lc) -> let c_args = List.map (fun v -> TVar v) c_args in pr_sig_item ppf (IValConstr (docu, name, vs, phi, args, c_n, c_args, lc)) | PrimVal (docu, name, tysch, Left ext_def, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external@ %s@ :@ %a@ =@ \"%s\"@]" name pr_typscheme tysch ext_def | PrimVal (docu, name, tysch, Right ext_def, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external let@ %s@ :@ %a@ =@ \"%s\"@]" name pr_typscheme tysch ext_def | LetRecVal (docu, name, expr, tysch, tests, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>let rec@ %s%a@ =@ %a@]%a" name pr_opt_sig_tysch tysch pr_uexpr expr pr_opt_utests tests | LetVal (docu, pat, expr, tysch, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>let@ %a@ %a@ =@ %a@]" pr_pat pat pr_opt_sig_tysch tysch pr_uexpr expr let pr_program ppf p = let p = if !show_extypes then p else List.filter (function | TypConstr (_, Extype _, _, _) | ValConstr (_, Extype _, _, _, _, Extype _, _, _) -> false | _ -> true) p in pr_line_list "\n" pr_struct_item ppf p let pr_exception ppf = function | Report_toplevel (what, None) -> Format.fprintf ppf "%!\n%s\n%!" what | Report_toplevel (what, Some where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\n%s\n%!" what | Contradiction (sort, what, None, where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\nContradiction in %s: %s\n%!" (sort_str sort) what | Contradiction (sort, what, Some (ty1, ty2), where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\nContradiction in %s: %s\ntypes involved:\n%a\n%a\n%!" (sort_str sort) what pr_ty ty1 pr_ty ty2 | NoAnswer (sort, what, None, where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\nNo answer in %s: %s\n%!" (sort_str sort) what | NoAnswer (sort, what, Some (ty1, ty2), where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\nNo answer in %s: %s\ntypes involved:\n%a\n%a\n%!" (sort_str sort) what pr_ty ty1 pr_ty ty2 | exn -> raise exn let pr_to_str pr_f e = ignore (Format.flush_str_formatter ()); pr_f Format.str_formatter e; Format.flush_str_formatter () (** {2 Unification} *) let connected ?(validate=fun _ -> ()) target (vs, phi) = let phi = List.sort (fun a b -> atom_size a - atom_size b) phi in [ * " connected : target=%a@ vs=%a@\nphi=%a@\n% ! " pr_vars ( vars_of_list target ) pr_vars ( vars_of_list vs ) pr_formula phi ; * ] pr_vars (vars_of_list target) pr_vars (vars_of_list vs) pr_formula phi; *]*) let nodes = List.map (function | Eqty (TVar _, TVar _, _) as c -> let cvs = fvs_atom c in c, cvs, cvs | (Eqty (TVar v, t, _) | Eqty (t, TVar v, _)) as c when typ_sort t = Type_sort -> c, VarSet.singleton v, fvs_typ t | c -> let cvs = fvs_atom c in c, cvs, cvs) phi in let rec loop acc vs nvs rem = let more, rem = List.partition (fun (c, ivs, ovs) -> List.exists (flip VarSet.mem ivs) nvs) rem in let mvs = List.fold_left VarSet.union VarSet.empty (List.map thr3 more) in let nvs = VarSet.elements (VarSet.diff mvs (VarSet.union vs (vars_of_list nvs))) in let acc = List.fold_left (fun acc (c,_,_) -> let acc' = c::acc in try validate acc'; acc' with Contradiction _ -> [ * " connected - loop : % a incomp . acc=%a@\n% ! " pr_atom c pr_formula acc ; * ] pr_atom c pr_formula acc; *]*) acc) acc more in [ * " connected - loop : nvs=%a@\nacc=%a@\n% ! " pr_vars ( vars_of_list nvs ) pr_formula acc ; * ] pr_vars (vars_of_list nvs) pr_formula acc; *]*) if nvs = [] then acc else loop acc (VarSet.union mvs vs) nvs rem in let ans = loop [] VarSet.empty target nodes in [ * " connected : target=%a@ vs=%a@ phi=%a@ ans=%a@\n% ! " pr_vars ( vars_of_list target ) pr_vars ( vars_of_list vs ) pr_formula phi pr_formula ans ; * ] pr_vars (vars_of_list target) pr_vars (vars_of_list vs) pr_formula phi pr_formula ans; *]*) VarSet.elements (VarSet.inter (fvs_formula ans) (vars_of_list vs)), ans let var_not_left_of q v t = VarSet.for_all (fun w -> q.cmp_v v w <> Left_of) (fvs_typ t) If [ v ] is not a [ bvs ] parameter , the LHS variable has to be existential and not upstream ( i.e. left of ) of any RHS universal variable . If [ v ] is a [ bvs ] parameter , the RHS must not contain a universal non-[bvs ] variable to the right of all [ bvs ] variables . Existential variables are not constrained : do not need to be same as or to the left of [ v ] . existential and not upstream (i.e. left of) of any RHS universal variable. If [v] is a [bvs] parameter, the RHS must not contain a universal non-[bvs] variable to the right of all [bvs] variables. Existential variables are not constrained: do not need to be same as or to the left of [v]. *) (* FIXME: fail on out-of-scope parameters. *) let quant_viol q bvs v t = let uv = q.uni_v v and bv = VarSet.mem v bvs in let npvs = List.filter (fun v-> not (VarSet.mem v bvs)) (VarSet.elements (fvs_typ t)) in let uni_vs = List.filter q.uni_v (if bv then npvs else v::npvs) in let res = (not bv && uv) || List.exists (fun v2 -> q.cmp_v v v2 = Left_of) uni_vs in [ * if res then " quant_viol : v=%s bv=%b uv=%b v2=%s@\n% ! " ( var_str v ) bv uv ( if List.exists ( fun v2 - > q.cmp_v v v2 = Left_of ) uni_vs then var_str ( List.find ( fun v2 - > q.cmp_v v v2 = Left_of ) uni_vs ) else " none " ) ; * ] "quant_viol: v=%s bv=%b uv=%b v2=%s@\n%!" (var_str v) bv uv (if List.exists (fun v2 -> q.cmp_v v v2 = Left_of) uni_vs then var_str (List.find (fun v2 -> q.cmp_v v v2 = Left_of) uni_vs) else "none"); *]*) res let registered_notex_vars = Hashtbl.create 32 let register_notex v = Hashtbl.add registered_notex_vars v () let is_old_notex v = Hashtbl.mem registered_notex_vars v (** Separate type sort and number sort constraints, *) let unify ?use_quants ?bvs ?(sb=VarMap.empty) q cnj = let use_quants, bvs = match use_quants, bvs with | None, None -> (* assert false *)false, VarSet.empty | Some false, None -> false, VarSet.empty | Some true, None -> true, VarSet.empty | (None | Some true), Some bvs -> true, bvs | _ -> assert false in [ * " unify : bvs=%a@ cnj=@ % a@\n% ! " pr_vars bvs pr_formula cnj ; * ] pr_vars bvs pr_formula cnj; *]*) let check_quant_viol w t' loc = if quant_viol q bvs w t' then raise (Contradiction (Type_sort, "Quantifier violation", Some (TVar w, t'), loc)) in let new_notex, cnj = sep_unsolved cnj in let rec aux sb num_cn ord_cn = function | [] -> sb, num_cn, ord_cn | (t1, t2, loc)::cnj when t1 = t2 -> aux sb num_cn ord_cn cnj | (t1, t2, loc)::cnj -> match subst_typ sb t1, subst_typ sb t2 with | t1, t2 when t1 = t2 -> aux sb num_cn ord_cn cnj | Alien (Num_term t1), Alien (Num_term t2) -> aux sb (NumDefs.Eq (t1, t2, loc)::num_cn) ord_cn cnj | (TVar v, Alien (Num_term t) | Alien (Num_term t), TVar v) when var_sort v = Num_sort -> aux sb NumDefs.(Eq (Lin (1,1,v), t, loc)::num_cn) ord_cn cnj | TVar v1, TVar v2 when var_sort v1 = Num_sort && var_sort v2 = Num_sort -> aux sb NumDefs.(Eq (Lin (1,1,v1), Lin (1,1,v2), loc)::num_cn) ord_cn cnj | Alien (Order_term t1), Alien (Order_term t2) -> aux sb num_cn (OrderDefs.Eq (t1, t2, loc)::ord_cn) cnj | (TVar v, Alien (Order_term t) | Alien (Order_term t), TVar v) when var_sort v = Order_sort -> aux sb num_cn OrderDefs.(Eq (OVar v, t, loc)::ord_cn) cnj | TVar v1, TVar v2 when var_sort v1 = Order_sort && var_sort v2 = Order_sort -> aux sb num_cn OrderDefs.(Eq (OVar v1, OVar v2, loc)::ord_cn) cnj | (Alien _ as t1, t2 | t1, (Alien _ as t2)) -> raise (Contradiction (Type_sort, "Type sort mismatch", Some (t1, t2), loc)) | (TVar v as tv, (TCons (Extype _, _) as t) | (TCons (Extype _, _) as t), (TVar v as tv)) when is_old_notex v -> raise (Contradiction (Type_sort, "Should not be existential", Some (tv, t), loc)) | (TVar v as tv, t | t, (TVar v as tv)) when VarSet.mem v (fvs_typ t) -> raise (Contradiction (Type_sort, "Occurs check fail", Some (tv, t), loc)) | (TVar v, t | t, TVar v) when use_quants && quant_viol q bvs v t -> raise (Contradiction (Type_sort, "Quantifier violation", Some (TVar v, t), loc)) | (TVar v1 as tv1, (TVar v2 as tv2)) -> if q.cmp_v v1 v2 = Left_of then aux (update_one_sb_check use_quants check_quant_viol v2 (tv1, loc) sb) num_cn ord_cn cnj else aux (update_one_sb_check use_quants check_quant_viol v1 (tv2, loc) sb) num_cn ord_cn cnj | (TVar v, t | t, TVar v) -> aux (update_one_sb_check use_quants check_quant_viol v (t, loc) sb) num_cn ord_cn cnj | (TCons (f, f_args) as t1, (TCons (g, g_args) as t2)) when f=g -> let more_cnj = try List.combine f_args g_args with Invalid_argument _ -> raise (Contradiction (Type_sort, "Type arity mismatch", Some (t1, t2), loc)) in aux sb num_cn ord_cn (List.map (fun (t1,t2)->t1,t2,loc) more_cnj @ cnj) | Fun (f1, a1), Fun (f2, a2) -> let more_cnj = [f1, f2, loc; a1, a2, loc] in aux sb num_cn ord_cn (more_cnj @ cnj) | (TCons (f, _) as t1, (TCons (g, _) as t2)) -> [ * " unify : mismatch f=%s g=%s@ t1=%a@ t2=%a@\n% ! " ( cns_str f ) ( cns_str g ) pr_ty t1 pr_ty t2 ; * ] (cns_str f) (cns_str g) pr_ty t1 pr_ty t2; *]*) raise (Contradiction (Type_sort, "Type mismatch", Some (t1, t2), loc)) | t1, t2 -> [ * " unify : t1=%a@ t2=%a@\n% ! " pr_ty t1 pr_ty t2 ; * ] pr_ty t1 pr_ty t2; *]*) raise (Contradiction (Type_sort, "Type mismatch", Some (t1, t2), loc)) in let cnj_typ, cnj_num, cnj_ord = aux sb cnj.at_num cnj.at_ord cnj.at_typ in if new_notex then List.iter (function | NotEx (t, loc) -> (match subst_typ cnj_typ t with | TCons (Extype _, _) as st -> raise (Contradiction (Type_sort, "Should not be existential", Some (t, st), loc)) | _ -> ()) | _ -> ()) cnj.at_so; {cnj_typ; cnj_num; cnj_ord; cnj_so=cnj.at_so} let solve_retypes ?use_quants ?bvs ~sb q cnj = let rec aux sb num_cn ord_cn so_cn = function | RetType (TCons _ as t1, t2, loc)::cnj -> let res = unify ?use_quants ?bvs ~sb q [Eqty (t1, t2, loc)] in aux res.cnj_typ (res.cnj_num @ num_cn) (res.cnj_ord @ ord_cn) (res.cnj_so @ so_cn) cnj | RetType (Fun (_, t1), t2, loc)::cnj -> aux sb num_cn ord_cn so_cn (RetType (t1, t2, loc)::cnj) | RetType (TVar _ as t1, t2, loc)::cnj -> (match subst_typ sb t1, subst_typ sb t2 with | TCons _ as t1, t2 -> let res = unify ?use_quants ?bvs ~sb q [Eqty (t1, t2, loc)] in aux res.cnj_typ (res.cnj_num @ num_cn) (res.cnj_ord @ ord_cn) (res.cnj_so @ so_cn) cnj | Fun (_, t1), t2 -> aux sb num_cn ord_cn so_cn (RetType (t1, t2, loc)::cnj) | TVar _ as t1, t2 -> aux sb num_cn ord_cn (RetType (t1, t2, loc)::so_cn) cnj | t1, t2 -> raise (Contradiction (Type_sort, "Return type should be existential", Some (t1, t2), loc))) | RetType (t1, t2, loc)::cnj -> raise (Contradiction (Type_sort, "Return type should be existential", Some (t1, t2), loc)) | a::cnj -> aux sb num_cn ord_cn (a::so_cn) cnj | [] -> {cnj_typ = sb; cnj_num = num_cn; cnj_ord = ord_cn; cnj_so = so_cn} in aux sb [] [] [] cnj let solve ?use_quants ?bvs ?sb q cnj = let res = unify ?use_quants ?bvs ?sb q cnj in let res' = solve_retypes ?use_quants ?bvs ~sb:res.cnj_typ q res.cnj_so in {res' with cnj_num = res'.cnj_num @ res.cnj_num; cnj_ord = res'.cnj_ord @ res.cnj_ord} let subst_of_cnj ?(elim_uni=false) q cnj = let sb, cnj = partition_map (function | Eqty (TVar v, t, lc) when (elim_uni || not (q.uni_v v)) && VarSet.for_all (fun v2 -> q.cmp_v v v2 <> Left_of) (fvs_typ t) -> Left (v,(t,lc)) | Eqty (t, TVar v, lc) when (elim_uni || not (q.uni_v v)) && VarSet.for_all (fun v2 -> q.cmp_v v v2 <> Left_of) (fvs_typ t) -> Left (v,(t,lc)) | c -> Right c) cnj in varmap_of_assoc sb, cnj let combine_sbs ?use_quants ?bvs q ?(more_phi=[]) sbs = unify ?use_quants ?bvs q (more_phi @ concat_map to_formula sbs) let subst_solved ?use_quants ?bvs q sb ~cnj = let cnj = List.map (fun (v,(t,lc)) -> Eqty (subst_typ sb (TVar v), subst_typ sb t, lc)) (varmap_to_assoc cnj) in unify ?use_quants ?bvs q cnj let cleanup q vs ans = let cmp_v v1 v2 = let c1 = List.mem v1 vs and c2 = List.mem v2 vs in if c1 && c2 then Same_quant else if c1 then Right_of else if c2 then Left_of else q.cmp_v v1 v2 in (* TODO: could use [unify] by treating [vs] as [Downstream] in [q.cmp_v] *) let {cnj_typ=clean; cnj_num; cnj_so} = unify ~use_quants:false {q with cmp_v} (to_formula ans) in let sb, ans = VarMap.partition (fun x _ -> List.mem x vs) clean in assert (cnj_num = []); assert (cnj_so = []); let ansvs = fvs_sb ans in List.filter (flip VarSet.mem ansvs) vs, ans * { 2 Nice variables } let typvars = "abcrst" let numvars = "nkijml" let typvars_n = String.length typvars let numvars_n = String.length numvars let next_typ fvs = let rec aux i = let ch, n = i mod typvars_n, i / typvars_n in let v s = VNam (s, Char.escaped typvars.[ch] ^ (if n>0 then string_of_int n else "")) in if VarSet.mem (v Num_sort) fvs || VarSet.mem (v Type_sort) fvs then aux (i+1) else v Type_sort in aux 0 let next_num fvs = let rec aux i = let ch, n = i mod numvars_n, i / numvars_n in let v s = VNam (s, Char.escaped numvars.[ch] ^ (if n>0 then string_of_int n else "")) in if VarSet.mem (v Num_sort) fvs || VarSet.mem (v Type_sort) fvs then aux (i+1) else v Num_sort in aux 0 let next_var allvs s = if s = Type_sort then next_typ allvs else next_num allvs let nice_ans ?sb ?(fvs=VarSet.empty) (vs, phi) = let named_vs, vs = List.partition (function VNam _ -> true | _ -> false) vs in let fvs = VarSet.union fvs (fvs_formula phi) in let fvs, sb = match sb with | None -> fvs, VarMap.empty | Some sb -> add_vars (varmap_codom sb) fvs, sb in let vs = List.filter (fun v -> VarSet.mem v fvs || VarMap.mem v sb) vs in let allvs, rn = fold_map (fun fvs v -> let w = next_var fvs (var_sort v) in VarSet.add w fvs, (v, w)) fvs vs in let rvs = List.map snd rn in let sb = add_to_varmap rn sb in sb, (named_vs @ rvs, hvsubst_formula sb phi) let () = pr_exty := fun ppf (i, args) -> let vs, phi, ty, ety_n, pvs = Hashtbl.find sigma (Extype i) in let ty = match ty with [ty] -> ty | _ -> assert false in let sb = try varmap_of_assoc (List.map2 (fun v t -> v, (t, dummy_loc)) pvs args) with Invalid_argument("List.map2") -> (* assert false *) VarMap.empty in let phi, ty = if VarMap.is_empty sb then phi, ty else subst_formula sb phi, subst_typ sb ty in let evs = VarSet.elements (VarSet.diff (vars_of_list vs) (vars_of_list pvs)) in let phi = Eqty (ty, ty, dummy_loc)::phi in let _, (evs, phi) = nice_ans (evs, phi) in let ty, phi = match phi with | Eqty (ty, tv, _)::phi -> ty, phi | _ -> assert false in TODO : " @[<2>∃%d:%a[%a].%a@ ] " better ? if !show_extypes then fprintf ppf "∃%d:" i else fprintf ppf "∃"; if phi = [] then fprintf ppf "%a.%a" (pr_sep_list "," pr_tyvar) evs pr_ty ty else fprintf ppf "%a[%a].%a" (pr_sep_list "," pr_tyvar) evs pr_formula phi pr_ty ty (** {2 Globals} *) let fresh_var_id = ref 0 let fresh_typ_var () = incr fresh_var_id; VId (Type_sort, !fresh_var_id) let fresh_num_var () = incr fresh_var_id; VId (Num_sort, !fresh_var_id) let fresh_var s = incr fresh_var_id; VId (s, !fresh_var_id) let freshen_var v = incr fresh_var_id; VId (var_sort v, !fresh_var_id) let parser_more_items = ref [] let parser_unary_typs = let t = Hashtbl.create 15 in Hashtbl.add t "Num" (); t let parser_unary_vals = Hashtbl.create 31 let parser_last_typ = ref 0 let parser_last_num = ref 0 let ty_unit = TCons (tuple, []) let ty_string = TCons (stringtype, []) let builtin_gamma = [ (let a = VNam (Type_sort, "a") in let va = TVar a in builtin_progseq, ([a], [], Fun (ty_unit, Fun (va, va)))); ] let setup_builtins () = Hashtbl.add parser_unary_typs "Num" (); Hashtbl.add sigma (CNam "True") ([], [], [], booltype, []); Hashtbl.add sigma (CNam "False") ([], [], [], booltype, []) let () = setup_builtins () let reset_state () = extype_id := 0; all_ex_types := []; predvar_id := 0; Hashtbl.clear sigma; Hashtbl.clear ex_type_chi; fresh_var_id := 0; parser_more_items := []; Hashtbl.clear parser_unary_typs; Hashtbl.clear parser_unary_vals; Hashtbl.clear registered_notex_vars; parser_last_typ := 0; parser_last_num := 0; setup_builtins ()
null
https://raw.githubusercontent.com/lukstafi/invargent/e25d8b12d9f9a8e2d5269001dd14cf93abcb7549/src/Terms.ml
ocaml
when same_level when same_level * {3 Formulas} TODO: optimize Using "X" because "script chi" is not available on all systems. * {2 Unification} FIXME: fail on out-of-scope parameters. * Separate type sort and number sort constraints, assert false TODO: could use [unify] by treating [vs] as [Downstream] in [q.cmp_v] assert false * {2 Globals}
* Data structures and printing for InvarGenT. Released under the GNU General Public Licence ( version 2 or higher ) , NO WARRANTY of correctness etc . ( C ) 2013 @author ( AT ) gmail.com @since Mar 2013 Released under the GNU General Public Licence (version 2 or higher), NO WARRANTY of correctness etc. (C) Lukasz Stafiniak 2013 @author Lukasz Stafiniak lukstafi (AT) gmail.com @since Mar 2013 *) let parse_if_as_integer = ref true let show_extypes = ref false * { 2 Definitions } let debug = ref false open Aux open Defs type cns_name = | CNam of string | Extype of int let tuple = CNam "Tuple" let numtype = CNam "Num" let booltype = CNam "Bool" let stringtype = CNam "String" let builtin_progseq = "builtin_progseq" module CNames = Set.Make (struct type t = cns_name let compare = Pervasives.compare end) let cnames_of_list l = List.fold_right CNames.add l CNames.empty let add_cnames l vs = List.fold_right CNames.add l vs let init_types = cnames_of_list [tuple; numtype; CNam "Int"; CNam "Float"; CNam "Bytes"; CNam "Char"; booltype; stringtype; CNam "Array"] type lc = loc type pat = | Zero | One of loc | PVar of string * loc | PAnd of pat * pat * loc | PCons of cns_name * pat list * loc let pat_loc = function | Zero -> dummy_loc | One loc -> loc | PVar (_, loc) -> loc | PAnd (_, _, loc) -> loc | PCons (_, _, loc) -> loc type ('a, 'b) expr = | Var of string * loc | Num of int * loc | NumAdd of ('a, 'b) expr * ('a, 'b) expr * loc | NumCoef of int * ('a, 'b) expr * loc | String of string * loc | Cons of cns_name * ('a, 'b) expr list * loc | App of ('a, 'b) expr * ('a, 'b) expr * loc | Lam of 'b * ('a, 'b) clause list * loc | ExLam of int * ('a, 'b) clause list * loc | Letrec of string option * 'a * string * ('a, 'b) expr * ('a, 'b) expr * loc | Letin of string option * pat * ('a, 'b) expr * ('a, 'b) expr * loc | AssertFalse of loc | RuntimeFailure of ('a, 'b) expr * loc | AssertLeq of ('a, 'b) expr * ('a, 'b) expr * ('a, 'b) expr * loc | AssertEqty of ('a, 'b) expr * ('a, 'b) expr * ('a, 'b) expr * loc and ('a, 'b) clause = pat * (('a, 'b) expr * ('a, 'b) expr) list * ('a, 'b) expr let rec equal_pat p q = match p, q with | Zero, Zero -> true | One _, One _ -> true | PVar (x, _), PVar (y, _) -> x = y | PAnd (a, b, _), PAnd (c, d, _) -> equal_pat a c && equal_pat b d || equal_pat a d && equal_pat b c | PCons (x, xs, _), PCons (y, ys, _) -> x = y && List.for_all2 equal_pat xs ys | _ -> false let rec equal_expr x y = match x, y with | Var (x, _), Var (y, _) -> x = y | Num (i, _), Num (j, _) -> i = j | NumAdd (a, b, _), NumAdd (c, d, _) -> equal_expr a c && equal_expr b d || equal_expr a d && equal_expr b c | NumCoef (x, a, _), NumCoef (y, b, _) -> x = y && equal_expr a b | String (x, _), String (y, _) -> x = y | Cons (a, xs, _), Cons (b, ys, _) -> a = b && List.for_all2 equal_expr xs ys | App (a, b, _), App (c, d, _) -> equal_expr a c && equal_expr b d | Lam (_, xs, _), Lam (_, ys, _) -> List.for_all2 equal_clause xs ys | ExLam (i, xs, _), ExLam (j, ys, _) -> i = j && List.for_all2 equal_clause xs ys | Letrec (_, _, x, a, b, _), Letrec (_, _, y, c, d, _) -> x = y && equal_expr a c && equal_expr b d | Letin (_, x, a, b, _), Letin (_, y, c, d, _) -> equal_pat x y && equal_expr a c && equal_expr b d | AssertFalse _, AssertFalse _ -> true | RuntimeFailure (s, _), RuntimeFailure (t, _) -> equal_expr s t | AssertLeq (a, b, c, _), AssertLeq (d, e, f, _) -> equal_expr a d && equal_expr b e && equal_expr c f | AssertEqty (a, b, c, _), AssertEqty (d, e, f, _) -> equal_expr a d && equal_expr b e && equal_expr c f | _ -> false and equal_clause (p, xs, a) (q, ys, b) = equal_pat p q && List.for_all2 (fun (a, b) (c, d) -> equal_expr a c && equal_expr b d) xs ys && equal_expr a b let expr_loc = function | Var (_, loc) | Num (_, loc) | NumAdd (_, _, loc) | NumCoef (_, _, loc) | String (_, loc) | Cons (_, _, loc) | App (_, _, loc) | Lam (_, _, loc) | ExLam (_, _, loc) | Letrec (_, _, _, _, _, loc) | Letin (_, _, _, _, loc) | AssertFalse loc | RuntimeFailure (_, loc) | AssertLeq (_, _, _, loc) | AssertEqty (_, _, _, loc) -> loc let clause_loc (pat, _, exp) = loc_union (pat_loc pat) (expr_loc exp) let cns_str = function | CNam c -> c | Extype i -> "Ex"^string_of_int i type alien_subterm = | Num_term of NumDefs.term | Order_term of OrderDefs.term type typ = | TVar of var_name | TCons of cns_name * typ list | Fun of typ * typ | Alien of alien_subterm let tdelta = TVar delta let tdelta' = TVar delta' let num x = Alien (Num_term x) let rec return_type = function | Fun (_, r) -> return_type r | t -> t let rec arg_types = function | Fun (a, r) -> a::arg_types r | t -> [] type uexpr = (unit, unit) expr type iexpr = (int list, (var_name * var_name) list) expr let fuse_exprs = let rec aux e1 e2 = match e1, e2 with | Cons (n1, es, lc1), Cons (n2, fs, lc2) -> assert (n1==n2 && lc1==lc2); Cons (n1, combine es fs, lc1) | NumAdd (e1, e2, lc1), NumAdd (f1, f2, lc2) -> assert (lc1==lc2); NumAdd (aux e1 f1, aux e2 f2, lc1) | NumCoef (x, a, lc1), NumCoef (y, b, lc2) -> assert (x==y && lc1==lc2); NumCoef (x, aux a b, lc1) | App (e1, e2, lc1), App (f1, f2, lc2) -> assert (lc1==lc2); App (aux e1 f1, aux e2 f2, lc1) | Lam (ms, cls1, lc1), Lam (ns, cls2, lc2) -> assert (lc1==lc2); Lam (ms@ns, combine_cls cls1 cls2, lc1) | ExLam (k1, cls1, lc1), ExLam (k2, cls2, lc2) -> assert (k1==k2 && lc1==lc2); ExLam (k1, combine_cls cls1 cls2, lc1) | Letrec (docu1, ms, x, e1, e2, lc1), Letrec (docu2, ns, y, f1, f2, lc2) -> assert (x==y && lc1==lc2 && docu1==docu2); Letrec (docu1, ms@ns, x, aux e1 f1, aux e2 f2, lc1) | Letin (docu1, p1, e1, e2, lc1), Letin (docu2, p2, f1, f2, lc2) -> assert (p1==p2 && lc1==lc2 && docu1==docu2); Letin (docu1, p1, aux e1 f1, aux e2 f2, lc1) | AssertLeq (e1, e2, e3, lc1), AssertLeq (f1, f2, f3, lc2) -> assert (lc1==lc2); AssertLeq (aux e1 f1, aux e2 f2, aux e3 f3, lc1) | AssertEqty (e1, e2, e3, lc1), AssertEqty (f1, f2, f3, lc2) -> assert (lc1==lc2); AssertEqty (aux e1 f1, aux e2 f2, aux e3 f3, lc1) | (Var _ as e), f | (Num _ as e), f | (String _ as e), f | (AssertFalse _ as e), f -> assert (e==f); e | RuntimeFailure (s, lc1), RuntimeFailure (t, lc2) -> assert (lc1==lc2); RuntimeFailure (aux s t, lc1) | _ -> assert false and combine es fs = List.map2 aux es fs and aux_cl (p1, guards1, e1) (p2, guards2, e2) = assert (p1 = p2); let guards = List.map2 (fun (e1, e2) (f1, f2) -> aux e1 f1, aux e2 f2) guards1 guards2 in p1, guards, aux e1 e2 and combine_cls es fs = List.map2 aux_cl es fs in function | [] -> assert false | [e] -> e | e::es -> List.fold_left aux e es * { 3 Mapping and folding } type typ_map = { map_tvar : var_name -> typ; map_tcons : string -> typ list -> typ; map_exty : int -> typ list -> typ; map_fun : typ -> typ -> typ; map_alien : alien_subterm -> typ } type 'a typ_fold = { fold_tvar : var_name -> 'a; fold_tcons : string -> 'a list -> 'a; fold_exty : int -> 'a list -> 'a; fold_fun : 'a -> 'a -> 'a; fold_alien : alien_subterm -> 'a } let typ_id_map = { map_tvar = (fun v -> TVar v); map_tcons = (fun n tys -> TCons (CNam n, tys)); map_exty = (fun i tys -> TCons (Extype i, tys)); map_fun = (fun t1 t2 -> Fun (t1, t2)); map_alien = (fun a -> Alien a) } let typ_make_fold op base = { fold_tvar = (fun _ -> base); fold_tcons = (fun _ tys -> List.fold_left op base tys); fold_exty = (fun _ tys -> List.fold_left op base tys); fold_fun = (fun t1 t2 -> op t1 t2); fold_alien = (fun _ -> base) } let typ_map tmap t = let rec aux = function | TVar v -> tmap.map_tvar v | TCons (CNam n, tys) -> tmap.map_tcons n (List.map aux tys) | TCons (Extype i, tys) -> tmap.map_exty i (List.map aux tys) | Fun (t1, t2) -> tmap.map_fun (aux t1) (aux t2) | Alien a -> tmap.map_alien a in aux t let typ_fold tfold t = let rec aux = function | TVar v -> tfold.fold_tvar v | TCons (CNam n, tys) -> tfold.fold_tcons n (List.map aux tys) | TCons (Extype i, tys) -> tfold.fold_exty i (List.map aux tys) | Fun (t1, t2) -> tfold.fold_fun (aux t1) (aux t2) | Alien a -> tfold.fold_alien a in aux t let sb_typ_unary arg = typ_map {typ_id_map with map_tvar = fun v -> if v = delta then arg else TVar v} let sb_typ_binary arg1 arg2 = typ_map {typ_id_map with map_tvar = fun v -> if v = delta then arg1 else if v = delta' then arg2 else TVar v} * { 3 Zipper } type typ_dir = | TCons_dir of cns_name * typ list * typ list | Fun_left of typ | Fun_right of typ type typ_loc = {typ_sub : typ; typ_ctx : typ_dir list} let typ_up t = match t.typ_sub with | TVar v -> None | TCons (_, []) -> None | TCons (n, t1::ts) -> Some {typ_sub = t1; typ_ctx = TCons_dir (n, [], ts) :: t.typ_ctx} | Fun (t1, t2) -> Some {typ_sub = t1; typ_ctx = Fun_left t2 :: t.typ_ctx} | Alien _ -> None let typ_down t = match t.typ_ctx with | [] -> None | TCons_dir (n, ts_l, ts_r)::ctx -> Some {typ_sub=TCons (n, ts_l@[t.typ_sub]@ts_r); typ_ctx=ctx} | Fun_left t2::ctx -> Some {typ_sub=Fun (t.typ_sub, t2); typ_ctx=ctx} | Fun_right t1::ctx -> Some {typ_sub=Fun (t1, t.typ_sub); typ_ctx=ctx} let rec typ_next ?(same_level=false) t = match t.typ_ctx with | [] -> None | (TCons_dir (n, ts_l, []))::_ when not same_level -> bind_opt (typ_down t) (typ_next ~same_level) | (TCons_dir (n, ts_l, t_r::ts_r))::ctx -> Some {typ_sub=t_r; typ_ctx=TCons_dir (n, ts_l@[t.typ_sub], ts_r)::ctx} | Fun_left t2::ctx -> Some {typ_sub = t2; typ_ctx = Fun_right t.typ_sub::ctx} | Fun_right _ :: _ when not same_level -> bind_opt (typ_down t) (typ_next ~same_level) let rec typ_out t = if t.typ_ctx = [] then t.typ_sub else match typ_down t with Some t -> typ_out t | None -> assert false * { 3 Substitutions } let alien_term_size = function | Num_term t -> NumDefs.term_size t | Order_term t -> OrderDefs.term_size t let typ_size = typ_fold {(typ_make_fold (fun i j -> i+j+1) 1) with fold_alien = alien_term_size} let fvs_alien_term = function | Num_term t -> NumDefs.fvs_term t | Order_term t -> OrderDefs.fvs_term t let has_var_alien_term v = function | Num_term t -> NumDefs.has_var_term v t | Order_term t -> OrderDefs.has_var_term v t let fvs_typ = typ_fold {(typ_make_fold VarSet.union VarSet.empty) with fold_tvar = (fun v -> VarSet.singleton v); fold_alien = fvs_alien_term} let has_var_typ v = typ_fold {(typ_make_fold (||) false) with fold_tvar = (fun v2 -> v = v2); fold_alien = (has_var_alien_term v)} type subst = (typ * loc) VarMap.t type hvsubst = var_name VarMap.t exception Contradiction of sort * string * (typ * typ) option * loc let num_unbox ~t2 lc = function | Alien (Num_term t) -> t | TVar v when var_sort v = Num_sort -> NumDefs.Lin (1,1,v) | t -> raise (Contradiction (Num_sort, "sort mismatch", Some (t2, t), lc)) let order_unbox ~t2 lc = function | Alien (Order_term t) -> t | TVar v when var_sort v = Order_sort -> OrderDefs.OVar v | t -> raise (Contradiction (Order_sort, "sort mismatch", Some (t2, t), lc)) let num_v_unbox v2 lc = function | Alien (Num_term t) -> t | TVar v when var_sort v = Num_sort -> NumDefs.Lin (1,1,v) | t -> raise (Contradiction (Num_sort, "sort mismatch", Some (TVar v2, t), lc)) let order_v_unbox v2 lc = function | Alien (Order_term t) -> t | TVar v when var_sort v = Order_sort -> OrderDefs.OVar v | t -> raise (Contradiction (Order_sort, "sort mismatch", Some (TVar v2, t), lc)) let subst_alien_term sb = function | Num_term t -> Num_term (NumDefs.subst_term num_v_unbox sb t) | Order_term t -> Order_term (OrderDefs.subst_term order_v_unbox sb t) let subst_typ sb t = if VarMap.is_empty sb then t else typ_map {typ_id_map with map_tvar = (fun v -> try fst (VarMap.find v sb) with Not_found -> TVar v); map_alien = fun t -> Alien (subst_alien_term sb t)} t let hvsubst_alien_term sb = function | Num_term t -> Num_term (NumDefs.hvsubst_term sb t) | Order_term t -> Order_term (OrderDefs.hvsubst_term sb t) let hvsubst_typ sb = typ_map {typ_id_map with map_tvar = (fun v -> TVar (try VarMap.find v sb with Not_found -> v)); map_alien = fun t -> Alien (hvsubst_alien_term sb t)} let subst_one v s t = let modif = ref false in let res = typ_map {typ_id_map with map_tvar = fun w -> if v = w then (modif:=true; s) else TVar w} t in !modif, res let subst_sb ~sb = VarMap.map (fun (t, loc) -> subst_typ sb t, loc) let hvsubst_sb sb = VarMap.map (fun (t, loc) -> hvsubst_typ sb t, loc) let update_sb ~more_sb sb = add_to_varmap (varmap_to_assoc more_sb) (VarMap.map (fun (t, loc) -> subst_typ more_sb t, loc) sb) let update_one_sb x sx sb = let more_sb = VarMap.singleton x sx in VarMap.add x sx (VarMap.map (fun (t, loc as st) -> if has_var_typ x t then subst_typ more_sb t, loc else st) sb) let update_one_sb_check do_check f x sx sb = if not do_check then update_one_sb x sx sb else let more_sb = VarMap.singleton x sx in VarMap.add x sx (VarMap.mapi (fun v (t, loc as st) -> if has_var_typ x t then (f v t loc; subst_typ more_sb t, loc) else st) sb) let revert_renaming sb = varmap_of_assoc (List.map (function | v1, (TVar v2, lc) -> v2, (TVar v1, lc) | v1, (Alien (Num_term (NumDefs.Lin (j,k,v2))), lc) -> v2, (Alien (Num_term (NumDefs.Lin (k,j,v1))), lc) | _ -> assert false) (varmap_to_assoc sb)) let c_subst_typ sb t = let rec aux t = try fst (List.assoc t sb) with Not_found -> match t with | TVar _ -> t | TCons (n, args) -> TCons (n, List.map aux args) | Fun (t1, t2) -> Fun (aux t1, aux t2) | Alien _ -> t in aux t let n_subst_typ sb t = let rec aux = function | TVar _ as t -> t | TCons (n, args) -> (try List.assoc n sb args with Not_found -> TCons (n, List.map aux args)) | Fun (t1, t2) -> Fun (aux t1, aux t2) | Alien _ as n -> n in aux t let map_in_subst f = VarMap.map (fun (t, lc) -> f t, lc) type alien_atom = | Num_atom of NumDefs.atom | Order_atom of OrderDefs.atom type atom = | Eqty of typ * typ * loc | CFalse of loc | PredVarU of int * typ * loc | PredVarB of int * typ * typ * loc | NotEx of typ * loc | RetType of typ * typ * loc | A of alien_atom let a_num a = A (Num_atom a) let fvs_alien_atom = function | Num_atom a -> NumDefs.fvs_atom a | Order_atom a -> OrderDefs.fvs_atom a let fvs_atom = function | Eqty (t1, t2, _) -> VarSet.union (fvs_typ t1) (fvs_typ t2) | CFalse _ -> VarSet.empty | PredVarU (_, t, _) -> fvs_typ t | PredVarB (_, t1, t2, _) -> VarSet.union (fvs_typ t1) (fvs_typ t2) | NotEx (t, _) -> fvs_typ t | RetType (t1, t2, _) -> VarSet.union (fvs_typ t1) (fvs_typ t2) | A a -> fvs_alien_atom a let prim_constr_var = function | Eqty (TVar v, _, _) -> Some v | RetType (TVar v, _, _) -> Some v | A (Num_atom a) -> NumDefs.prim_constr_var a | A (Order_atom a) -> OrderDefs.prim_constr_var a | _ -> None let alien_atom_loc = function | Num_atom a -> NumDefs.atom_loc a | Order_atom a -> OrderDefs.atom_loc a let atom_loc = function | Eqty (_, _, loc) | CFalse loc | PredVarU (_, _, loc) | PredVarB (_, _, _, loc) | NotEx (_, loc) | RetType (_, _, loc) -> loc | A a -> alien_atom_loc a let replace_loc_alien_atom loc = function | Num_atom a -> Num_atom (NumDefs.replace_loc_atom loc a) | Order_atom a -> Order_atom (OrderDefs.replace_loc_atom loc a) let replace_loc_atom loc = function | Eqty (t1, t2, _) -> Eqty (t1, t2, loc) | CFalse _ -> CFalse loc | PredVarU (n, t, _) -> PredVarU (n, t, loc) | PredVarB (n, t1, t2, _) -> PredVarB (n, t1, t2, loc) | NotEx (t, _) -> NotEx (t, loc) | RetType (t1, t2, _) -> RetType (t1, t2, loc) | A a -> A (replace_loc_alien_atom loc a) let eq_alien_atom = function | Num_atom a1, Num_atom a2 -> NumDefs.eq_atom a1 a2 | Order_atom a1, Order_atom a2 -> OrderDefs.eq_atom a1 a2 | _ -> false let eq_atom a1 a2 = a1 == a2 || match a1, a2 with | Eqty (t1, t2, _), Eqty (t3, t4, _) when t1=t3 && t2=t4 || t1=t4 && t2=t3 -> true | CFalse _, CFalse _ -> true | PredVarU (n1, t1, _), PredVarU (n2, t2, _) when n1=n2 && t1=t2 -> true | PredVarB (n1, t1, t2, _), PredVarB (n2, t3, t4, _) when n1=n2 && t1=t3 && t2=t4 -> true | A a1, A a2 -> eq_alien_atom (a1, a2) | _ -> false let subformula phi1 phi2 = List.for_all (fun a1 -> List.exists (eq_atom a1) phi2) phi1 let formula_inter cnj1 cnj2 = List.filter (fun a -> List.exists (eq_atom a) cnj2) cnj1 let formula_diff cnj1 cnj2 = List.filter (fun a -> not (List.exists (eq_atom a) cnj2)) cnj1 let subst_alien_atom sb = function | Num_atom a -> Num_atom (NumDefs.subst_atom num_v_unbox sb a) | Order_atom a -> Order_atom (OrderDefs.subst_atom order_v_unbox sb a) let subst_atom sb = function | Eqty (t1, t2, loc) -> Eqty (subst_typ sb t1, subst_typ sb t2, loc) | CFalse _ as a -> a | PredVarU (n, t, lc) -> PredVarU (n, subst_typ sb t, lc) | PredVarB (n, t1, t2, lc) -> PredVarB (n, subst_typ sb t1, subst_typ sb t2, lc) | NotEx (t, lc) -> NotEx (subst_typ sb t, lc) | RetType (t1, t2, lc) -> RetType (subst_typ sb t1, subst_typ sb t2, lc) | A a -> A (subst_alien_atom sb a) let hvsubst_alien_atom sb = function | Num_atom a -> Num_atom (NumDefs.hvsubst_atom sb a) | Order_atom a -> Order_atom (OrderDefs.hvsubst_atom sb a) let hvsubst_atom sb = function | Eqty (t1, t2, loc) -> Eqty (hvsubst_typ sb t1, hvsubst_typ sb t2, loc) | CFalse _ as a -> a | PredVarU (n, t, lc) -> PredVarU (n, hvsubst_typ sb t, lc) | PredVarB (n, t1, t2, lc) -> PredVarB (n, hvsubst_typ sb t1, hvsubst_typ sb t2, lc) | NotEx (t, lc) -> NotEx (hvsubst_typ sb t, lc) | RetType (t1, t2, lc) -> RetType (hvsubst_typ sb t1, hvsubst_typ sb t2, lc) | A a -> A (hvsubst_alien_atom sb a) let sb_atom_unary arg = function | Eqty (t1, t2, lc) -> Eqty (sb_typ_unary arg t1, sb_typ_unary arg t2, lc) | CFalse _ as a -> a | PredVarU (_, t, _) -> assert false | PredVarB (_, t1, t2, _) -> assert false | NotEx _ -> assert false | RetType (t1, t2, lc) -> assert false | A _ as a -> a let sb_atom_binary arg1 arg2 = function | Eqty (t1, t2, lc) -> Eqty (sb_typ_binary arg1 arg2 t1, sb_typ_binary arg1 arg2 t2, lc) | CFalse _ as a -> a | PredVarU (_, t, _) -> assert false | PredVarB (_, t1, t2, _) -> assert false | NotEx _ -> assert false | RetType _ -> assert false | A _ as a -> a let subst_fo_atom sb = function | Eqty (t1, t2, loc) -> Eqty (subst_typ sb t1, subst_typ sb t2, loc) | RetType (t1, t2, loc) -> RetType (subst_typ sb t1, subst_typ sb t2, loc) | CFalse _ as a -> a | (PredVarU _ | PredVarB _ | NotEx _) as a -> a | A a -> A (subst_alien_atom sb a) let alien_atom_size = function | Num_atom a -> NumDefs.atom_size a | Order_atom a -> OrderDefs.atom_size a let atom_size = function | Eqty (t1, t2, _) -> typ_size t1 + typ_size t2 + 1 | RetType (t1, t2, _) -> typ_size t1 + typ_size t2 + 1 | CFalse _ -> 1 | PredVarU (_, t, _) -> typ_size t + 1 | PredVarB (_, t1, t2, _) -> typ_size t1 + typ_size t2 + 1 | NotEx (t, _) -> typ_size t + 1 | A a -> alien_atom_size a type formula = atom list type sep_formula = { cnj_typ : subst; cnj_num : NumDefs.formula; cnj_ord : OrderDefs.formula; cnj_so : formula } type ('a, 'b, 'c, 'd) sep_sorts = { at_typ : 'a; at_num : 'b; at_ord : 'c; at_so : 'd } let fvs_formula phi = List.fold_left VarSet.union VarSet.empty (List.map fvs_atom phi) let fvs_typs phi = List.fold_left VarSet.union VarSet.empty (List.map fvs_typ phi) let fvs_sb sb = VarMap.fold (fun v (t, _) acc -> VarSet.add v (VarSet.union (fvs_typ t) acc)) sb VarSet.empty let subst_formula sb phi = if VarMap.is_empty sb then phi else List.map (subst_atom sb) phi let hvsubst_formula sb phi = List.map (hvsubst_atom sb) phi let update_sep ?(typ_updated=false) ~more phi = {cnj_typ = if typ_updated then more.cnj_typ else update_sb ~more_sb:more.cnj_typ phi.cnj_typ; cnj_num = more.cnj_num @ phi.cnj_num; cnj_ord = more.cnj_ord @ phi.cnj_ord; cnj_so = more.cnj_so @ phi.cnj_so} let typ_sort = function | TCons _ | Fun _ -> Type_sort | TVar (VNam (s, _) | VId (s, _)) -> s | Alien (Num_term _) -> Num_sort | Alien (Order_term _) -> Order_sort let sep_formulas cnj = let cnj_typ, cnj_num, cnj_ord, cnj_so = List.fold_left (fun (cnj_typ, cnj_num, cnj_ord, cnj_so) -> function | (Eqty (TVar v, t, lc) | Eqty (t, TVar v, lc)) when var_sort v = Type_sort -> VarMap.add v (t,lc) cnj_typ, cnj_num, cnj_ord, cnj_so | Eqty (t1, t2, lc) when typ_sort t1 = Num_sort -> cnj_typ, NumDefs.Eq (num_unbox ~t2 lc t1, num_unbox ~t2:t1 lc t2, lc) ::cnj_num, cnj_ord, cnj_so | Eqty _ -> assert false | A (Num_atom a) -> cnj_typ, a::cnj_num, cnj_ord, cnj_so | A (Order_atom a) -> cnj_typ, cnj_num, a::cnj_ord, cnj_so | (PredVarU _ | PredVarB _ | NotEx _ | CFalse _ | RetType _) as a -> cnj_typ, cnj_num, cnj_ord, a::cnj_so) (VarMap.empty, [], [], []) cnj in {cnj_typ; cnj_num; cnj_ord; cnj_so} let sep_unsolved cnj = let new_notex = ref false in let at_typ, at_num, at_ord, at_so = List.fold_left (fun (cnj_typ, cnj_num, cnj_ord, cnj_so) -> function | Eqty (t1, t2, loc) when typ_sort t1 = Type_sort -> (t1, t2, loc)::cnj_typ, cnj_num, cnj_ord, cnj_so | Eqty (t1, t2, lc) when typ_sort t1 = Num_sort -> cnj_typ, NumDefs.Eq (num_unbox ~t2 lc t1, num_unbox ~t2:t1 lc t2, lc) ::cnj_num, cnj_ord, cnj_so | Eqty (t1, t2, lc) when typ_sort t1 = Order_sort -> cnj_typ, cnj_num, OrderDefs.Eq (order_unbox ~t2 lc t1, order_unbox ~t2:t1 lc t2, lc) ::cnj_ord, cnj_so | Eqty _ -> assert false | A (Num_atom a) -> cnj_typ, a::cnj_num, cnj_ord, cnj_so | A (Order_atom a) -> cnj_typ, cnj_num, a::cnj_ord, cnj_so | NotEx _ as a -> new_notex := true; cnj_typ, cnj_num, cnj_ord, a::cnj_so | (PredVarU _ | PredVarB _ | CFalse _ | RetType _) as a -> cnj_typ, cnj_num, cnj_ord, a::cnj_so) ([], [], [], []) cnj in !new_notex, {at_typ; at_num; at_ord; at_so} let assoc_to_formula sb = List.fold_left (fun acc (v, (t,loc)) -> Eqty (TVar v, t, loc)::acc) [] sb let to_formula sb = VarMap.fold (fun v (t,loc) acc -> Eqty (TVar v, t, loc)::acc) sb [] let unsep_formulas {cnj_typ; cnj_so; cnj_num} = cnj_so @ to_formula cnj_typ @ List.map (fun a -> A (Num_atom a)) cnj_num let replace_loc loc phi = List.map (replace_loc_atom loc) phi let formula_loc phi = List.fold_left loc_union dummy_loc (List.map atom_loc phi) let subst_fo_formula sb phi = if VarMap.is_empty sb then phi else List.map (subst_fo_atom sb) phi let sb_phi_unary arg = List.map (sb_atom_unary arg) let sb_phi_binary arg1 arg2 = List.map (sb_atom_binary arg1 arg2) type typ_scheme = var_name list * formula * typ type answer = var_name list * formula * The annotation , besides providing the type scheme , tells whether nested type schemes have free variables in scope of the scheme . On [ ] annotations , provides the argument and the return type separately . nested type schemes have free variables in scope of the scheme. On [Lam] annotations, provides the argument and the return type separately. *) type texpr = (typ_scheme * bool, (typ * typ) option) expr let extype_id = ref 0 let predvar_id = ref 0 type struct_item = | TypConstr of string option * cns_name * sort list * loc | PrimTyp of string option * cns_name * sort list * string * loc | ValConstr of string option * cns_name * var_name list * formula * typ list * cns_name * var_name list * loc | PrimVal of string option * string * typ_scheme * (string, string) choice * loc | LetRecVal of string option * string * uexpr * typ_scheme option * uexpr list * loc | LetVal of string option * pat * uexpr * typ_scheme option * loc type annot_item = | ITypConstr of string option * cns_name * sort list * loc | IPrimTyp of string option * cns_name * sort list * string * loc | IValConstr of string option * cns_name * var_name list * formula * typ list * cns_name * typ list * loc | IPrimVal of string option * string * typ_scheme * (string, string) choice * loc | ILetRecVal of string option * string * texpr * typ_scheme * texpr list * (pat * int option) list * loc | ILetVal of string option * pat * texpr * typ_scheme * (string * typ_scheme) list * (pat * int option) list * loc let rec enc_funtype res = function | [] -> res | arg::args -> Fun (arg, enc_funtype res args) let typ_scheme_of_item ?(env=[]) = function | TypConstr _ -> raise Not_found | PrimTyp _ -> raise Not_found | ValConstr (_, _, vs, phi, args, c_n, c_args, _) -> vs, phi, enc_funtype (TCons (c_n, List.map (fun v->TVar v) c_args)) args | PrimVal (_, _, t, _, _) -> t | LetRecVal (_, name, _, _, _, _) | LetVal (_, PVar (name, _), _, _, _) -> List.assoc name env | LetVal _ -> raise Not_found exception NoAnswer of sort * string * (typ * typ) option * loc exception Suspect of formula * loc let convert = function | NoAnswer (sort, msg, tys, lc) -> Contradiction (sort, msg, tys, lc) | Contradiction (sort, msg, tys, lc) -> NoAnswer (sort, msg, tys, lc) | e -> e let alien_atom_sort = function | Num_atom _ -> Num_sort | Order_atom _ -> Order_sort let atom_sort = function | Eqty (t1, t2, lc) -> let s1 = typ_sort t1 and s2 = typ_sort t2 in if s1 = s2 then s1 else raise (Contradiction (s1, "Sort mismatch", Some (t1, t2), lc)) | RetType _ -> Type_sort | CFalse _ -> Type_sort | PredVarU _ -> Type_sort | PredVarB _ -> Type_sort | NotEx _ -> Type_sort | A a -> alien_atom_sort a * { 2 Global tables } type sigma = (cns_name, var_name list * formula * typ list * cns_name * var_name list) Hashtbl.t let sigma : sigma = Hashtbl.create 128 let ex_type_chi = Hashtbl.create 128 let all_ex_types = ref [] * { 2 Printing } open Format let rec pr_pat ppf = function | Zero -> fprintf ppf "%s" "!" | One _ -> fprintf ppf "%s" "_" | PVar (x, _) -> fprintf ppf "%s" x | PAnd (pat1, pat2, _) -> fprintf ppf "@[<2>%a@ as@ %a@]" pr_pat pat1 pr_more_pat pat2 | PCons (CNam "Tuple", pats, _) -> fprintf ppf "@[<2>(%a)@]" (pr_sep_list "," ~pr_hd:pr_pat pr_more_pat) pats | PCons (x, [], _) -> fprintf ppf "%s" (cns_str x) | PCons (x, [pat], _) -> fprintf ppf "@[<2>%s@ %a@]" (cns_str x) pr_one_pat pat | PCons (x, pats, _) -> fprintf ppf "@[<2>%s@ (%a)@]" (cns_str x) (pr_sep_list "," ~pr_hd:pr_pat pr_more_pat) pats and pr_more_pat ppf = function | PAnd _ as p -> fprintf ppf "(%a)" (pr_pat) p | p -> pr_pat ppf p and pr_one_pat ppf = function | Zero -> fprintf ppf "%s" "!" | One _ -> fprintf ppf "%s" "_" | PVar (x, _) -> fprintf ppf "%s" x | PCons (CNam "Tuple", pats, _) -> fprintf ppf "@[<2>(%a)@]" (pr_sep_list "," ~pr_hd:pr_pat pr_more_pat) pats | PCons (x, [], _) -> fprintf ppf "%s" (cns_str x) | p -> fprintf ppf "(%a)" pr_pat p let collect_lambdas e = let rec aux pats = function | Lam (_, [pat, [], exp], _) -> aux (pat::pats) exp | expr -> List.rev pats, expr in aux [] e let rec collect_apps e = let rec aux args = function | App (f, arg, _) -> aux (arg::args) f | expr -> expr::args in aux [] e type ('a, 'b) pr_expr_annot = | LetRecNode of 'a | LamNode of 'b | MatchVal of 'b | MatchRes of 'b | LamOpen of 'b | MatchValOpen of 'b | MatchResOpen of 'b | LetInOpen of 'b | LetInNode of 'b let pr_expr ?export_num ?export_if ?export_bool ?export_progseq ?export_runtime_failure pr_ann ppf exp = let rec aux ppf = function | Var (s, _) -> fprintf ppf "%s" s | String (s, _) -> fprintf ppf "\"%s\"" s | Num (i, _) -> (match export_num with | None -> fprintf ppf "%d" i | Some (fname, _, _, _, _) -> fprintf ppf "(%s %d)" fname i) | NumAdd (a, b, _) -> (match export_num with | None -> fprintf ppf "@[<2>%a@ +@ %a@]" aux a aux b | Some (_, lbr, op, _, rbr) -> fprintf ppf "@[<2>%s%a@ %s@ %a%s@]" lbr aux a op aux b rbr) | NumCoef (x, a, _) -> (match export_num with | None -> fprintf ppf "@[<2>%d@ *@ %a@]" x aux a | Some (fname, lbr, _, op, rbr) -> fprintf ppf "@[<2>%s%s %d@ %s@ %a%s@]" lbr fname x op aux a rbr) | Cons (CNam "Tuple", exps, _) -> fprintf ppf "@[<2>(%a)@]" (pr_sep_list "," aux) exps | Cons (CNam "True", [], _) when export_bool <> None -> fprintf ppf "%s" (try List.assoc true (unsome export_bool) with Not_found -> "true") | Cons (CNam "False", [], _) when export_bool <> None -> fprintf ppf "%s" (try List.assoc false (unsome export_bool) with Not_found -> "false") | App (App (Var (f, _), e1, _), e2, _) when f = builtin_progseq -> let kwd_beg, kwd_mid, kwd_end = try unsome export_progseq with Not_found -> "(", ";", ")" in fprintf ppf "@[<0>(%s%a@ %s@ %a%s)@]" kwd_beg aux e1 kwd_mid aux e2 kwd_end | App (Lam (_, [PCons (CNam "True", [], _), [], e1; PCons (CNam "False", [], _), [], e2], _), cond, _) when export_if <> None -> let kwd_if, kwd_then, kwd_else = try unsome export_if with Not_found -> "if", "then", "else" in fprintf ppf "@[<0>(%s@ %a@ %s@ %a@ %s@ %a)@]" kwd_if aux cond kwd_then aux e1 kwd_else aux e2 | App (Lam (_, [PCons (CNam "False", [], _), [], e1; PCons (CNam "True", [], _), [], e2], _), cond, _) when export_if <> None -> let kwd_if, kwd_then, kwd_else = try unsome export_if with Not_found -> "if", "then", "else" in fprintf ppf "@[<0>(%s@ %a@ %s@ %a@ %s@ %a)@]" kwd_if aux cond kwd_then aux e1 kwd_else aux e2 | App (Lam (_, [One _, ([lhs1, rhs1] as ineqs), e1; One _, [NumAdd (rhs2, Num (1, _), _), lhs2], e2], _), Cons (CNam "Tuple", [], _), _) when export_if <> None && equal_expr lhs1 lhs2 && equal_expr rhs1 rhs2 -> let kwd_if, kwd_then, kwd_else = try unsome export_if with Not_found -> "if", "then", "else" in fprintf ppf "@[<0>(%s@ %a@ %s@ %a@ %s@ %a)@]" kwd_if (pr_sep_list "&&" pr_guard_leq) ineqs kwd_then aux e1 kwd_else aux e2 | App (Lam (_, [One _, ineqs, e1; One _, [], e2], _), Cons (CNam "Tuple", [], _), _) when export_if <> None -> let kwd_if, kwd_then, kwd_else = try unsome export_if with Not_found -> "if", "then", "else" in fprintf ppf "@[<0>(%s@ %a@ %s@ %a@ %s@ %a)@]" kwd_if (pr_sep_list "&&" pr_guard_leq) ineqs kwd_then aux e1 kwd_else aux e2 | Cons (x, [], _) -> fprintf ppf "%s" (cns_str x) | Cons (x, [exp], _) -> fprintf ppf "@[<2>%s@ %a@]" (cns_str x) (pr_one_expr pr_ann) exp | Cons (x, exps, _) -> fprintf ppf "@[<2>%s@ (%a)@]" (cns_str x) (pr_sep_list "," aux) exps | Lam (_, [_], _) as exp -> let pats, expr = collect_lambdas exp in fprintf ppf "@[<2>(fun@ %a@ ->@ %a)@]" (pr_sep_list "" pr_one_pat) pats aux expr | Lam (ann, cs, _) -> fprintf ppf "@[<2>%a(function@ %a)%a@]" pr_ann (LamOpen ann) (pr_pre_sep_list "| " (pr_clause pr_ann)) cs pr_ann (LamNode ann) | ExLam (_, cs, _) -> fprintf ppf "@[<0>(efunction@ %a)@]" (pr_pre_sep_list "| " (pr_clause pr_ann)) cs | App (Lam (ann, [(v,[],body)], _), def, _) -> fprintf ppf "@[<0>let@ @[<4>%a%a%a@] =@ @[<2>%a@]@ in@ @[<0>%a@]@]" pr_ann (LetInOpen ann) pr_more_pat v pr_ann (LetInNode ann) aux def aux body | App (Lam (ann, cls, _), def, _) -> fprintf ppf "@[<0>%a(match@ @[<4>%a%a%a@] with@ @[<2>%a@])%a@]" pr_ann (MatchResOpen ann) pr_ann (MatchValOpen ann) aux def pr_ann (MatchVal ann) (pr_pre_sep_list "| " (pr_clause pr_ann)) cls pr_ann (MatchRes ann) | App _ as exp -> let fargs = collect_apps exp in fprintf ppf "@[<2>%a@]" (pr_sep_list "" (pr_one_expr pr_ann)) fargs | Letrec (docu, ann, x, exp, range, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<0>let rec %s@ %a=@ @[<2>%a@] in@ @[<0>%a@]@]" x pr_ann (LetRecNode ann) aux exp aux range | Letin (docu, pat, exp, range, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<0>let %a =@ @[<2>%a@] in@ @[<0>%a@]@]" pr_pat pat aux exp aux range | AssertFalse _ -> fprintf ppf "assert false" | RuntimeFailure (s, _) -> (match export_runtime_failure with | None -> fprintf ppf "@[<2>(runtime_failure@ %a)@]" aux s | Some fname -> fprintf ppf "@[<2>(%s@ %a)@]" fname aux s) | AssertLeq (e1, e2, range, _) -> fprintf ppf "@[<0>assert@[<2>@ %a@ ≤@ %a@];@ %a@]" aux e1 aux e2 aux range | AssertEqty (e1, e2, range, _) -> fprintf ppf "@[<0>assert@ = type@[<2>@ %a@ %a@];@ %a@]" aux e1 aux e2 aux range and pr_guard_leq ppf (e1, e2) = fprintf ppf "@[<2>%a@ <=@ %a@]" aux e1 aux e2 and pr_clause pr_ann ppf (pat, guards, exp) = if guards = [] then fprintf ppf "@[<2>%a@ ->@ %a@]" pr_pat pat aux exp else fprintf ppf "@[<2>%a@ when@ %a@ ->@ %a@]" pr_pat pat (pr_sep_list "&&" pr_guard_leq) guards aux exp and pr_one_expr pr_ann ppf exp = match exp with | Var _ | Num _ | Cons (_, [], _) -> aux ppf exp | _ -> fprintf ppf "(%a)" aux exp in aux ppf exp let pr_uexpr ppf = pr_expr (fun ppf _ -> fprintf ppf "") ppf let pr_iexpr ppf = pr_expr (fun ppf _ -> fprintf ppf "") ppf let collect_argtys ty = let rec aux args = function | Fun (arg, res) -> aux (arg::args) res | res -> res::args in List.rev (aux [] ty) let pr_exty = ref (fun ppf (i, rty) -> failwith "not implemented") let pr_alien_atom ppf = function | Num_atom a -> NumDefs.pr_atom ppf a | Order_atom a -> OrderDefs.pr_atom ppf a let pr_alien_ty ppf = function | Num_term t -> NumDefs.pr_term ppf t | Order_term t -> OrderDefs.pr_term ppf t let alien_no_parens = function | Num_term t -> NumDefs.term_no_parens t | Order_term t -> OrderDefs.term_no_parens t let rec pr_atom ppf = function | Eqty (t1, t2, _) -> fprintf ppf "@[<2>%a@ =@ %a@]" pr_one_ty t1 pr_one_ty t2 | RetType (t1, t2, _) -> fprintf ppf "@[<2>RetType@ (%a,@ %a)@]" pr_one_ty t1 pr_one_ty t2 | CFalse _ -> pp_print_string ppf "FALSE" | PredVarU (i,ty,lc) -> fprintf ppf "@[<2>X%d(%a)@]" i pr_ty ty | PredVarB (i,t1,t2,lc) -> fprintf ppf "@[<2>X%d(%a,@ %a)@]" i pr_ty t1 pr_ty t2 | NotEx (t,lc) -> fprintf ppf "@[<2>NotEx(%a)@]" pr_ty t | A a -> pr_alien_atom ppf a and pr_formula ppf atoms = pr_sep_list " ∧" pr_atom ppf atoms and pr_ty ppf = function | TVar v -> fprintf ppf "%s" (var_str v) | TCons (CNam "Tuple", []) -> fprintf ppf "()" | TCons (CNam c, []) -> fprintf ppf "%s" c | TCons (CNam "Tuple", exps) -> fprintf ppf "@[<2>(%a)@]" (pr_sep_list "," pr_ty) exps | TCons (CNam c, [(TVar _ | TCons (_, [])) as ty]) -> fprintf ppf "@[<2>%s@ %a@]" c pr_one_ty ty | TCons (CNam c, [Alien t as ty]) when alien_no_parens t -> fprintf ppf "@[<2>%s@ %a@]" c pr_one_ty ty | TCons (CNam c, exps) -> fprintf ppf "@[<2>%s@ (%a)@]" c (pr_sep_list "," pr_ty ) exps | TCons (Extype i, args) -> !pr_exty ppf (i, args) | Fun _ as ty -> let tys = collect_argtys ty in fprintf ppf "@[<2>%a@]" (pr_sep_list " →" pr_fun_ty) tys | Alien t -> pr_alien_ty ppf t and pr_one_ty ppf ty = match ty with | TVar _ | Alien _ | TCons (_, []) -> pr_ty ppf ty | _ -> fprintf ppf "(%a)" pr_ty ty and pr_fun_ty ppf ty = match ty with | Fun _ -> fprintf ppf "(%a)" pr_ty ty | _ -> pr_ty ppf ty let pr_sort ppf = function | Num_sort -> fprintf ppf "num" | Type_sort -> fprintf ppf "type" | Order_sort -> fprintf ppf "order" let pr_cns ppf name = fprintf ppf "%s" (cns_str name) let pr_typscheme ppf = function | [], [], ty -> pr_ty ppf ty | vs, [], ty -> fprintf ppf "@[<0>∀%a.@ %a@]" (pr_sep_list "," pr_tyvar) vs pr_ty ty | vs, phi, ty -> fprintf ppf "@[<0>∀%a[%a].@ %a@]" (pr_sep_list "," pr_tyvar) vs pr_formula phi pr_ty ty let pr_ans ppf = function | [], ans -> pr_formula ppf ans | vs, ans -> fprintf ppf "@[<2>∃%a.@ %a@]" (pr_sep_list "," pr_tyvar) vs pr_formula ans let pr_subst ppf sb = pr_sep_list ";" (fun ppf (v,(t,_)) -> fprintf ppf "%s:=%a" (var_str v) pr_ty t) ppf (varmap_to_assoc sb) let pr_hvsubst ppf sb = pr_sep_list ";" (fun ppf (v,t) -> fprintf ppf "%s:=%s" (var_str v) (var_str t)) ppf (varmap_to_assoc sb) let pr_typ_dir ppf = function | TCons_dir (n, ts_l, []) -> fprintf ppf "@[<2>%s@ (%a,@ ^)@]" (cns_str n) (pr_sep_list "," pr_ty) ts_l | TCons_dir (n, ts_l, ts_r) -> fprintf ppf "@[<2>%s@ (%a,@ ^,@ %a)@]" (cns_str n) (pr_sep_list "," pr_ty) ts_l (pr_sep_list "," pr_ty) ts_r | Fun_left t2 -> fprintf ppf "@[<2>^ →@ %a@]" pr_ty t2 | Fun_right t1 -> fprintf ppf "@[<2>%a →@ ^@]" pr_ty t1 let pr_typ_loc ppf t = fprintf ppf "@[<2>%a@ <-@ [%a]@]" pr_ty t.typ_sub (pr_sep_list ";" pr_typ_dir) t.typ_ctx let pr_opt_sig_tysch ppf = function | None -> () | Some tysch -> fprintf ppf "@ :@ %a" pr_typscheme tysch let pr_opt_tests pr_ann ppf = function | [] -> () | tests -> fprintf ppf "@\n@[<2>test@ %a@]" (pr_sep_list ";" (pr_expr pr_ann)) tests let pr_opt_utests = pr_opt_tests (fun ppf _ -> fprintf ppf "") let pr_sig_item ppf = function | ITypConstr (_, Extype _, _, _) when not !show_extypes -> () | ITypConstr (docu, name, [], _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>datatype@ %s@]" (cns_str name) | IPrimTyp (docu, name, [], _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external type@ %s@]" (cns_str name) | ITypConstr (docu, name, sorts, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>datatype@ %s@ :@ %a@]" (cns_str name) (pr_sep_list " *" pr_sort) sorts | IPrimTyp (docu, name, sorts, _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external type@ %s@ :@ %a@]" (cns_str name) (pr_sep_list " *" pr_sort) sorts | IValConstr (_, Extype _, _, _, _, Extype _, _, _) when not !show_extypes -> () | IValConstr (docu, name, [], [], [], c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ %a@]" (cns_str name) pr_ty res | IValConstr (docu, name, [], [], args, c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ %a@ ⟶@ %a@]" (cns_str name) (pr_sep_list " *" pr_ty) args pr_ty res | IValConstr (docu, name, vs, [], [], c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ ∀%a.@ %a@]" (cns_str name) (pr_sep_list "," pr_tyvar) vs pr_ty res | IValConstr (docu, name, vs, phi, [], c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ ∀%a[%a].@ %a@]" (cns_str name) (pr_sep_list "," pr_tyvar) vs pr_formula phi pr_ty res | IValConstr (docu, name, vs, [], args, c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ ∀%a.%a@ ⟶@ %a@]" (cns_str name) (pr_sep_list "," pr_tyvar) vs (pr_sep_list " *" pr_ty) args pr_ty res | IValConstr (docu, name, vs, phi, args, c_n, c_args, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); let res = TCons (c_n, c_args) in fprintf ppf "@[<2>datacons@ %s@ :@ ∀%a[%a].%a@ ⟶@ %a@]" (cns_str name) (pr_sep_list "," pr_tyvar) vs pr_formula phi (pr_sep_list " *" pr_ty) args pr_ty res | IPrimVal (docu, name, tysch, Left _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external@ %s@ :@ %a@]" name pr_typscheme tysch | IPrimVal (docu, name, tysch, Right _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external val@ %s@ :@ %a@]" name pr_typscheme tysch | ILetRecVal (docu, name, expr, tysch, tests, _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>val@ %s :@ %a@]" name pr_typscheme tysch | ILetVal (docu, _, _, _, tyschs, _, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); pr_line_list "\n" (fun ppf (name,tysch) -> fprintf ppf "@[<2>val@ %s :@ %a@]" name pr_typscheme tysch) ppf tyschs let pr_signature ppf p = let p = if !show_extypes then p else List.filter (function | ITypConstr (_, Extype _, _, _) | IValConstr (_, Extype _, _, _, _, Extype _, _, _) -> false | _ -> true) p in pr_line_list "\n" pr_sig_item ppf p let pr_struct_item ppf = function | TypConstr (docu, name, sorts, lc) -> pr_sig_item ppf (ITypConstr (docu, name, sorts, lc)) | PrimTyp (docu, name, sorts, expansion, lc) -> fprintf ppf "@[<2>%a@ =@ \"%s\"@]" pr_sig_item (IPrimTyp (docu, name, sorts, expansion, lc)) expansion | ValConstr (docu, name, vs, phi, args, c_n, c_args, lc) -> let c_args = List.map (fun v -> TVar v) c_args in pr_sig_item ppf (IValConstr (docu, name, vs, phi, args, c_n, c_args, lc)) | PrimVal (docu, name, tysch, Left ext_def, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external@ %s@ :@ %a@ =@ \"%s\"@]" name pr_typscheme tysch ext_def | PrimVal (docu, name, tysch, Right ext_def, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>external let@ %s@ :@ %a@ =@ \"%s\"@]" name pr_typscheme tysch ext_def | LetRecVal (docu, name, expr, tysch, tests, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>let rec@ %s%a@ =@ %a@]%a" name pr_opt_sig_tysch tysch pr_uexpr expr pr_opt_utests tests | LetVal (docu, pat, expr, tysch, _) -> (match docu with | None -> () | Some doc -> fprintf ppf "(**%s*)@\n" doc); fprintf ppf "@[<2>let@ %a@ %a@ =@ %a@]" pr_pat pat pr_opt_sig_tysch tysch pr_uexpr expr let pr_program ppf p = let p = if !show_extypes then p else List.filter (function | TypConstr (_, Extype _, _, _) | ValConstr (_, Extype _, _, _, _, Extype _, _, _) -> false | _ -> true) p in pr_line_list "\n" pr_struct_item ppf p let pr_exception ppf = function | Report_toplevel (what, None) -> Format.fprintf ppf "%!\n%s\n%!" what | Report_toplevel (what, Some where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\n%s\n%!" what | Contradiction (sort, what, None, where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\nContradiction in %s: %s\n%!" (sort_str sort) what | Contradiction (sort, what, Some (ty1, ty2), where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\nContradiction in %s: %s\ntypes involved:\n%a\n%a\n%!" (sort_str sort) what pr_ty ty1 pr_ty ty2 | NoAnswer (sort, what, None, where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\nNo answer in %s: %s\n%!" (sort_str sort) what | NoAnswer (sort, what, Some (ty1, ty2), where) -> pr_loc_long ppf where; Format.fprintf ppf "%!\nNo answer in %s: %s\ntypes involved:\n%a\n%a\n%!" (sort_str sort) what pr_ty ty1 pr_ty ty2 | exn -> raise exn let pr_to_str pr_f e = ignore (Format.flush_str_formatter ()); pr_f Format.str_formatter e; Format.flush_str_formatter () let connected ?(validate=fun _ -> ()) target (vs, phi) = let phi = List.sort (fun a b -> atom_size a - atom_size b) phi in [ * " connected : target=%a@ vs=%a@\nphi=%a@\n% ! " pr_vars ( vars_of_list target ) pr_vars ( vars_of_list vs ) pr_formula phi ; * ] pr_vars (vars_of_list target) pr_vars (vars_of_list vs) pr_formula phi; *]*) let nodes = List.map (function | Eqty (TVar _, TVar _, _) as c -> let cvs = fvs_atom c in c, cvs, cvs | (Eqty (TVar v, t, _) | Eqty (t, TVar v, _)) as c when typ_sort t = Type_sort -> c, VarSet.singleton v, fvs_typ t | c -> let cvs = fvs_atom c in c, cvs, cvs) phi in let rec loop acc vs nvs rem = let more, rem = List.partition (fun (c, ivs, ovs) -> List.exists (flip VarSet.mem ivs) nvs) rem in let mvs = List.fold_left VarSet.union VarSet.empty (List.map thr3 more) in let nvs = VarSet.elements (VarSet.diff mvs (VarSet.union vs (vars_of_list nvs))) in let acc = List.fold_left (fun acc (c,_,_) -> let acc' = c::acc in try validate acc'; acc' with Contradiction _ -> [ * " connected - loop : % a incomp . acc=%a@\n% ! " pr_atom c pr_formula acc ; * ] pr_atom c pr_formula acc; *]*) acc) acc more in [ * " connected - loop : nvs=%a@\nacc=%a@\n% ! " pr_vars ( vars_of_list nvs ) pr_formula acc ; * ] pr_vars (vars_of_list nvs) pr_formula acc; *]*) if nvs = [] then acc else loop acc (VarSet.union mvs vs) nvs rem in let ans = loop [] VarSet.empty target nodes in [ * " connected : target=%a@ vs=%a@ phi=%a@ ans=%a@\n% ! " pr_vars ( vars_of_list target ) pr_vars ( vars_of_list vs ) pr_formula phi pr_formula ans ; * ] pr_vars (vars_of_list target) pr_vars (vars_of_list vs) pr_formula phi pr_formula ans; *]*) VarSet.elements (VarSet.inter (fvs_formula ans) (vars_of_list vs)), ans let var_not_left_of q v t = VarSet.for_all (fun w -> q.cmp_v v w <> Left_of) (fvs_typ t) If [ v ] is not a [ bvs ] parameter , the LHS variable has to be existential and not upstream ( i.e. left of ) of any RHS universal variable . If [ v ] is a [ bvs ] parameter , the RHS must not contain a universal non-[bvs ] variable to the right of all [ bvs ] variables . Existential variables are not constrained : do not need to be same as or to the left of [ v ] . existential and not upstream (i.e. left of) of any RHS universal variable. If [v] is a [bvs] parameter, the RHS must not contain a universal non-[bvs] variable to the right of all [bvs] variables. Existential variables are not constrained: do not need to be same as or to the left of [v]. *) let quant_viol q bvs v t = let uv = q.uni_v v and bv = VarSet.mem v bvs in let npvs = List.filter (fun v-> not (VarSet.mem v bvs)) (VarSet.elements (fvs_typ t)) in let uni_vs = List.filter q.uni_v (if bv then npvs else v::npvs) in let res = (not bv && uv) || List.exists (fun v2 -> q.cmp_v v v2 = Left_of) uni_vs in [ * if res then " quant_viol : v=%s bv=%b uv=%b v2=%s@\n% ! " ( var_str v ) bv uv ( if List.exists ( fun v2 - > q.cmp_v v v2 = Left_of ) uni_vs then var_str ( List.find ( fun v2 - > q.cmp_v v v2 = Left_of ) uni_vs ) else " none " ) ; * ] "quant_viol: v=%s bv=%b uv=%b v2=%s@\n%!" (var_str v) bv uv (if List.exists (fun v2 -> q.cmp_v v v2 = Left_of) uni_vs then var_str (List.find (fun v2 -> q.cmp_v v v2 = Left_of) uni_vs) else "none"); *]*) res let registered_notex_vars = Hashtbl.create 32 let register_notex v = Hashtbl.add registered_notex_vars v () let is_old_notex v = Hashtbl.mem registered_notex_vars v let unify ?use_quants ?bvs ?(sb=VarMap.empty) q cnj = let use_quants, bvs = match use_quants, bvs with | Some false, None -> false, VarSet.empty | Some true, None -> true, VarSet.empty | (None | Some true), Some bvs -> true, bvs | _ -> assert false in [ * " unify : bvs=%a@ cnj=@ % a@\n% ! " pr_vars bvs pr_formula cnj ; * ] pr_vars bvs pr_formula cnj; *]*) let check_quant_viol w t' loc = if quant_viol q bvs w t' then raise (Contradiction (Type_sort, "Quantifier violation", Some (TVar w, t'), loc)) in let new_notex, cnj = sep_unsolved cnj in let rec aux sb num_cn ord_cn = function | [] -> sb, num_cn, ord_cn | (t1, t2, loc)::cnj when t1 = t2 -> aux sb num_cn ord_cn cnj | (t1, t2, loc)::cnj -> match subst_typ sb t1, subst_typ sb t2 with | t1, t2 when t1 = t2 -> aux sb num_cn ord_cn cnj | Alien (Num_term t1), Alien (Num_term t2) -> aux sb (NumDefs.Eq (t1, t2, loc)::num_cn) ord_cn cnj | (TVar v, Alien (Num_term t) | Alien (Num_term t), TVar v) when var_sort v = Num_sort -> aux sb NumDefs.(Eq (Lin (1,1,v), t, loc)::num_cn) ord_cn cnj | TVar v1, TVar v2 when var_sort v1 = Num_sort && var_sort v2 = Num_sort -> aux sb NumDefs.(Eq (Lin (1,1,v1), Lin (1,1,v2), loc)::num_cn) ord_cn cnj | Alien (Order_term t1), Alien (Order_term t2) -> aux sb num_cn (OrderDefs.Eq (t1, t2, loc)::ord_cn) cnj | (TVar v, Alien (Order_term t) | Alien (Order_term t), TVar v) when var_sort v = Order_sort -> aux sb num_cn OrderDefs.(Eq (OVar v, t, loc)::ord_cn) cnj | TVar v1, TVar v2 when var_sort v1 = Order_sort && var_sort v2 = Order_sort -> aux sb num_cn OrderDefs.(Eq (OVar v1, OVar v2, loc)::ord_cn) cnj | (Alien _ as t1, t2 | t1, (Alien _ as t2)) -> raise (Contradiction (Type_sort, "Type sort mismatch", Some (t1, t2), loc)) | (TVar v as tv, (TCons (Extype _, _) as t) | (TCons (Extype _, _) as t), (TVar v as tv)) when is_old_notex v -> raise (Contradiction (Type_sort, "Should not be existential", Some (tv, t), loc)) | (TVar v as tv, t | t, (TVar v as tv)) when VarSet.mem v (fvs_typ t) -> raise (Contradiction (Type_sort, "Occurs check fail", Some (tv, t), loc)) | (TVar v, t | t, TVar v) when use_quants && quant_viol q bvs v t -> raise (Contradiction (Type_sort, "Quantifier violation", Some (TVar v, t), loc)) | (TVar v1 as tv1, (TVar v2 as tv2)) -> if q.cmp_v v1 v2 = Left_of then aux (update_one_sb_check use_quants check_quant_viol v2 (tv1, loc) sb) num_cn ord_cn cnj else aux (update_one_sb_check use_quants check_quant_viol v1 (tv2, loc) sb) num_cn ord_cn cnj | (TVar v, t | t, TVar v) -> aux (update_one_sb_check use_quants check_quant_viol v (t, loc) sb) num_cn ord_cn cnj | (TCons (f, f_args) as t1, (TCons (g, g_args) as t2)) when f=g -> let more_cnj = try List.combine f_args g_args with Invalid_argument _ -> raise (Contradiction (Type_sort, "Type arity mismatch", Some (t1, t2), loc)) in aux sb num_cn ord_cn (List.map (fun (t1,t2)->t1,t2,loc) more_cnj @ cnj) | Fun (f1, a1), Fun (f2, a2) -> let more_cnj = [f1, f2, loc; a1, a2, loc] in aux sb num_cn ord_cn (more_cnj @ cnj) | (TCons (f, _) as t1, (TCons (g, _) as t2)) -> [ * " unify : mismatch f=%s g=%s@ t1=%a@ t2=%a@\n% ! " ( cns_str f ) ( cns_str g ) pr_ty t1 pr_ty t2 ; * ] (cns_str f) (cns_str g) pr_ty t1 pr_ty t2; *]*) raise (Contradiction (Type_sort, "Type mismatch", Some (t1, t2), loc)) | t1, t2 -> [ * " unify : t1=%a@ t2=%a@\n% ! " pr_ty t1 pr_ty t2 ; * ] pr_ty t1 pr_ty t2; *]*) raise (Contradiction (Type_sort, "Type mismatch", Some (t1, t2), loc)) in let cnj_typ, cnj_num, cnj_ord = aux sb cnj.at_num cnj.at_ord cnj.at_typ in if new_notex then List.iter (function | NotEx (t, loc) -> (match subst_typ cnj_typ t with | TCons (Extype _, _) as st -> raise (Contradiction (Type_sort, "Should not be existential", Some (t, st), loc)) | _ -> ()) | _ -> ()) cnj.at_so; {cnj_typ; cnj_num; cnj_ord; cnj_so=cnj.at_so} let solve_retypes ?use_quants ?bvs ~sb q cnj = let rec aux sb num_cn ord_cn so_cn = function | RetType (TCons _ as t1, t2, loc)::cnj -> let res = unify ?use_quants ?bvs ~sb q [Eqty (t1, t2, loc)] in aux res.cnj_typ (res.cnj_num @ num_cn) (res.cnj_ord @ ord_cn) (res.cnj_so @ so_cn) cnj | RetType (Fun (_, t1), t2, loc)::cnj -> aux sb num_cn ord_cn so_cn (RetType (t1, t2, loc)::cnj) | RetType (TVar _ as t1, t2, loc)::cnj -> (match subst_typ sb t1, subst_typ sb t2 with | TCons _ as t1, t2 -> let res = unify ?use_quants ?bvs ~sb q [Eqty (t1, t2, loc)] in aux res.cnj_typ (res.cnj_num @ num_cn) (res.cnj_ord @ ord_cn) (res.cnj_so @ so_cn) cnj | Fun (_, t1), t2 -> aux sb num_cn ord_cn so_cn (RetType (t1, t2, loc)::cnj) | TVar _ as t1, t2 -> aux sb num_cn ord_cn (RetType (t1, t2, loc)::so_cn) cnj | t1, t2 -> raise (Contradiction (Type_sort, "Return type should be existential", Some (t1, t2), loc))) | RetType (t1, t2, loc)::cnj -> raise (Contradiction (Type_sort, "Return type should be existential", Some (t1, t2), loc)) | a::cnj -> aux sb num_cn ord_cn (a::so_cn) cnj | [] -> {cnj_typ = sb; cnj_num = num_cn; cnj_ord = ord_cn; cnj_so = so_cn} in aux sb [] [] [] cnj let solve ?use_quants ?bvs ?sb q cnj = let res = unify ?use_quants ?bvs ?sb q cnj in let res' = solve_retypes ?use_quants ?bvs ~sb:res.cnj_typ q res.cnj_so in {res' with cnj_num = res'.cnj_num @ res.cnj_num; cnj_ord = res'.cnj_ord @ res.cnj_ord} let subst_of_cnj ?(elim_uni=false) q cnj = let sb, cnj = partition_map (function | Eqty (TVar v, t, lc) when (elim_uni || not (q.uni_v v)) && VarSet.for_all (fun v2 -> q.cmp_v v v2 <> Left_of) (fvs_typ t) -> Left (v,(t,lc)) | Eqty (t, TVar v, lc) when (elim_uni || not (q.uni_v v)) && VarSet.for_all (fun v2 -> q.cmp_v v v2 <> Left_of) (fvs_typ t) -> Left (v,(t,lc)) | c -> Right c) cnj in varmap_of_assoc sb, cnj let combine_sbs ?use_quants ?bvs q ?(more_phi=[]) sbs = unify ?use_quants ?bvs q (more_phi @ concat_map to_formula sbs) let subst_solved ?use_quants ?bvs q sb ~cnj = let cnj = List.map (fun (v,(t,lc)) -> Eqty (subst_typ sb (TVar v), subst_typ sb t, lc)) (varmap_to_assoc cnj) in unify ?use_quants ?bvs q cnj let cleanup q vs ans = let cmp_v v1 v2 = let c1 = List.mem v1 vs and c2 = List.mem v2 vs in if c1 && c2 then Same_quant else if c1 then Right_of else if c2 then Left_of else q.cmp_v v1 v2 in let {cnj_typ=clean; cnj_num; cnj_so} = unify ~use_quants:false {q with cmp_v} (to_formula ans) in let sb, ans = VarMap.partition (fun x _ -> List.mem x vs) clean in assert (cnj_num = []); assert (cnj_so = []); let ansvs = fvs_sb ans in List.filter (flip VarSet.mem ansvs) vs, ans * { 2 Nice variables } let typvars = "abcrst" let numvars = "nkijml" let typvars_n = String.length typvars let numvars_n = String.length numvars let next_typ fvs = let rec aux i = let ch, n = i mod typvars_n, i / typvars_n in let v s = VNam (s, Char.escaped typvars.[ch] ^ (if n>0 then string_of_int n else "")) in if VarSet.mem (v Num_sort) fvs || VarSet.mem (v Type_sort) fvs then aux (i+1) else v Type_sort in aux 0 let next_num fvs = let rec aux i = let ch, n = i mod numvars_n, i / numvars_n in let v s = VNam (s, Char.escaped numvars.[ch] ^ (if n>0 then string_of_int n else "")) in if VarSet.mem (v Num_sort) fvs || VarSet.mem (v Type_sort) fvs then aux (i+1) else v Num_sort in aux 0 let next_var allvs s = if s = Type_sort then next_typ allvs else next_num allvs let nice_ans ?sb ?(fvs=VarSet.empty) (vs, phi) = let named_vs, vs = List.partition (function VNam _ -> true | _ -> false) vs in let fvs = VarSet.union fvs (fvs_formula phi) in let fvs, sb = match sb with | None -> fvs, VarMap.empty | Some sb -> add_vars (varmap_codom sb) fvs, sb in let vs = List.filter (fun v -> VarSet.mem v fvs || VarMap.mem v sb) vs in let allvs, rn = fold_map (fun fvs v -> let w = next_var fvs (var_sort v) in VarSet.add w fvs, (v, w)) fvs vs in let rvs = List.map snd rn in let sb = add_to_varmap rn sb in sb, (named_vs @ rvs, hvsubst_formula sb phi) let () = pr_exty := fun ppf (i, args) -> let vs, phi, ty, ety_n, pvs = Hashtbl.find sigma (Extype i) in let ty = match ty with [ty] -> ty | _ -> assert false in let sb = try varmap_of_assoc (List.map2 (fun v t -> v, (t, dummy_loc)) pvs args) with Invalid_argument("List.map2") -> let phi, ty = if VarMap.is_empty sb then phi, ty else subst_formula sb phi, subst_typ sb ty in let evs = VarSet.elements (VarSet.diff (vars_of_list vs) (vars_of_list pvs)) in let phi = Eqty (ty, ty, dummy_loc)::phi in let _, (evs, phi) = nice_ans (evs, phi) in let ty, phi = match phi with | Eqty (ty, tv, _)::phi -> ty, phi | _ -> assert false in TODO : " @[<2>∃%d:%a[%a].%a@ ] " better ? if !show_extypes then fprintf ppf "∃%d:" i else fprintf ppf "∃"; if phi = [] then fprintf ppf "%a.%a" (pr_sep_list "," pr_tyvar) evs pr_ty ty else fprintf ppf "%a[%a].%a" (pr_sep_list "," pr_tyvar) evs pr_formula phi pr_ty ty let fresh_var_id = ref 0 let fresh_typ_var () = incr fresh_var_id; VId (Type_sort, !fresh_var_id) let fresh_num_var () = incr fresh_var_id; VId (Num_sort, !fresh_var_id) let fresh_var s = incr fresh_var_id; VId (s, !fresh_var_id) let freshen_var v = incr fresh_var_id; VId (var_sort v, !fresh_var_id) let parser_more_items = ref [] let parser_unary_typs = let t = Hashtbl.create 15 in Hashtbl.add t "Num" (); t let parser_unary_vals = Hashtbl.create 31 let parser_last_typ = ref 0 let parser_last_num = ref 0 let ty_unit = TCons (tuple, []) let ty_string = TCons (stringtype, []) let builtin_gamma = [ (let a = VNam (Type_sort, "a") in let va = TVar a in builtin_progseq, ([a], [], Fun (ty_unit, Fun (va, va)))); ] let setup_builtins () = Hashtbl.add parser_unary_typs "Num" (); Hashtbl.add sigma (CNam "True") ([], [], [], booltype, []); Hashtbl.add sigma (CNam "False") ([], [], [], booltype, []) let () = setup_builtins () let reset_state () = extype_id := 0; all_ex_types := []; predvar_id := 0; Hashtbl.clear sigma; Hashtbl.clear ex_type_chi; fresh_var_id := 0; parser_more_items := []; Hashtbl.clear parser_unary_typs; Hashtbl.clear parser_unary_vals; Hashtbl.clear registered_notex_vars; parser_last_typ := 0; parser_last_num := 0; setup_builtins ()
178b619e82fb8bf6a876cdf8e4d4094e37be9512b12235cd913a74d30baa5193
monadbobo/ocaml-core
pipe.ml
open Core.Std open Import open Deferred_std module Stream = Async_stream module Q = Queue let show_debug_messages = ref false let check_invariant = ref false module Blocked_read = struct A [ Blocked_read.t ] represents a blocked read attempt . If someone reads from an empty pipe , they enqueue a [ Blocked_read.t ] in the queue of [ blocked_reads ] . Later , when values are written to a pipe , that will cause some number of blocked reads to be filled , first come first serve . The blocked - read constructor specifies how many values a read should consume from the pipe when it gets its turn . If a pipe is closed , then all blocked reads will be filled with [ ` Eof ] . pipe, they enqueue a [Blocked_read.t] in the queue of [blocked_reads]. Later, when values are written to a pipe, that will cause some number of blocked reads to be filled, first come first serve. The blocked-read constructor specifies how many values a read should consume from the pipe when it gets its turn. If a pipe is closed, then all blocked reads will be filled with [`Eof]. *) type 'a t = | Zero of [ `Eof | `Ok ] Ivar.t | One of [ `Eof | `Ok of 'a ] Ivar.t | All of [ `Eof | `Ok of 'a Q.t ] Ivar.t | At_most of int * [ `Eof | `Ok of 'a Q.t ] Ivar.t with sexp_of let invariant t = try match t with | Zero _ | All _ | One _ -> () | At_most (i, _) -> assert (i > 0); with | exn -> failwiths "Pipe.Blocked_read.invariant failed" (exn, t) <:sexp_of< exn * a t >> ;; let is_empty = function | Zero i -> Ivar.is_empty i | One i -> Ivar.is_empty i | All i -> Ivar.is_empty i | At_most (_, i) -> Ivar.is_empty i ;; let fill_with_eof = function | Zero i -> Ivar.fill i `Eof | One i -> Ivar.fill i `Eof | All i -> Ivar.fill i `Eof | At_most (_, i) -> Ivar.fill i `Eof end module Blocked_flush = struct (* A [Blocked_flush.t] represents a blocked flush operation, which can be enabled by a future read. If someone does [flushed p] on a pipe, that blocks until everything that's currently in the pipe at that point has drained out of the pipe. When we call [flushed], it records the total amount of data that has been written so far in [fill_when_num_values_read]. We fill the [Flush.t] with [`Ok] when this amount of data has been read from the pipe. A [Blocked_flush.t] can also be filled with [`Reader_closed], which happens when the reader end of the pipe is closed, and we are thus sure that the unread elements preceding the flush will never be read. *) type t = { fill_when_num_values_read : int; ready : [ `Ok | `Reader_closed ] Ivar.t; } with fields, sexp_of let fill t v = Ivar.fill t.ready v end type ('a, 'phantom) t = { (* [id] is an integer used to distinguish pipes when debugging. *) id : int; (* [buffer] holds values written to the pipe that have not yet been read. *) buffer : 'a Q.t; (* [size_budget] governs pushback on writers to the pipe. There is *no* invariant that [Q.length buffer <= size_budget]. There is no hard upper bound on the number of elements that can be stuffed into the [buffer]. This is due to the way we handle writes. When we do a write, all of the values written are immediately enqueued into [buffer]. After the write, if [Q.length buffer <= t.size_budget], then the writer will be notified to continue writing. After the write, if [length t > t.size_budget], then the write will block until the pipe is under budget. *) mutable size_budget : int; (* [pushback] is used to give feedback to writers about whether they should write to the pipe. [pushback] is full iff [length t <= t.size_budget || is_closed t]. *) mutable pushback : unit Ivar.t; [ num_values_read ] keeps track of the total number of values that have been read from the pipe . We do not have to worry about overflow in [ num_values_read ] . You 'd need to write 2 ^ 62 elements to the pipe , which would take about 146 years , at a flow rate of 1 size - unit / nanosecond . from the pipe. We do not have to worry about overflow in [num_values_read]. You'd need to write 2^62 elements to the pipe, which would take about 146 years, at a flow rate of 1 size-unit/nanosecond. *) mutable num_values_read : int; (* [blocked_flushes] holds flushes whose preceding elements have not been completely read. For each blocked flush, the number of elements that need to be read from the pipe in order to fill the flush is: fill_when_num_values_read - num_values_read Keeping the data in this form allows us to change a single field (num_values_read) when we consume values instead of having to iterate over the whole queue of flushes. *) blocked_flushes : Blocked_flush.t Q.t; (* [blocked_reads] holds reads that are waiting on data to be written to the pipe. *) blocked_reads : 'a Blocked_read.t Q.t; (* [closed] is filled when we close the write end of the pipe. *) closed : unit Ivar.t; } with fields, sexp_of type ('a, 'phantom) pipe = ('a, 'phantom) t with sexp_of let hash t = Hashtbl.hash t.id let equal (t1 : (_, _) t) t2 = phys_equal t1 t2 let is_empty t = Q.is_empty t.buffer let is_closed t = Ivar.is_full t.closed let closed t = Ivar.read t.closed let pushback t = Ivar.read t.pushback let length t = Q.length t.buffer let invariant t = try assert (t.size_budget >= 0); assert (Ivar.is_full t.pushback = (length t <= t.size_budget || is_closed t)); Q.iter t.blocked_flushes ~f:(fun f -> assert (f.Blocked_flush.fill_when_num_values_read > t.num_values_read)); assert (List.is_sorted ~compare (List.map (Q.to_list t.blocked_flushes) ~f:Blocked_flush.fill_when_num_values_read)); if is_empty t then assert (Q.is_empty t.blocked_flushes); (* If data is available, no one is waiting for it. This would need to change if we ever implement [read_exactly] as an atomic operation. *) if not (is_empty t) then assert (Q.is_empty t.blocked_reads); Q.iter t.blocked_reads ~f:(fun read -> Blocked_read.invariant read; assert (Blocked_read.is_empty read)); (* You never block trying to read a closed pipe. *) if is_closed t then assert (Q.is_empty t.blocked_reads); with | exn -> failwiths "Pipe.invariant failed" (exn, t) <:sexp_of< exn * (a, b) t >> ;; module Reader = struct type phantom with sexp_of type 'a t = ('a, phantom) pipe with sexp_of let invariant = invariant end module Writer = struct type phantom with sexp_of type 'a t = ('a, phantom) pipe with sexp_of let invariant = invariant end let id_ref = ref 0 let create () = incr id_ref; let t = { id = !id_ref ; closed = Ivar.create (); size_budget = 0 ; pushback = Ivar.create (); buffer = Q.create () ; num_values_read = 0 ; blocked_flushes = Q.create () ; blocked_reads = Q.create () ; } in Ivar.fill t.pushback (); (* initially, the pipe does not pushback *) if !check_invariant then invariant t; (t, t) ;; let update_pushback t = if length t <= t.size_budget || is_closed t then Ivar.fill_if_empty t.pushback () else if Ivar.is_full t.pushback then t.pushback <- Ivar.create (); ;; let close t = if !show_debug_messages then Debug.log "close" t <:sexp_of< (a, b) t >>; if !check_invariant then invariant t; if not (is_closed t) then begin Ivar.fill t.closed (); if is_empty t then begin Q.iter t.blocked_reads ~f:Blocked_read.fill_with_eof; Q.clear t.blocked_reads; end; update_pushback t; end; ;; let close_read t = if !show_debug_messages then Debug.log "close_read" t <:sexp_of< (a, b) t >>; if !check_invariant then invariant t; Q.iter t.blocked_flushes ~f:(fun flush -> Blocked_flush.fill flush `Reader_closed); Q.clear t.blocked_flushes; Q.clear t.buffer; update_pushback t; (* we just cleared the buffer, so may need to fill [t.pushback] *) close t; ;; let rec fill_flushes t = match Q.peek t.blocked_flushes with | None -> () | Some flush -> if t.num_values_read >= flush.Blocked_flush.fill_when_num_values_read then begin Blocked_flush.fill flush `Ok; ignore (Q.dequeue_exn t.blocked_flushes : Blocked_flush.t); fill_flushes t; end ;; (* [consume_all t] reads all the elements in [t], in constant time. *) let consume_all t = let result = Q.create () in t.num_values_read <- t.num_values_read + length t; Q.transfer ~src:t.buffer ~dst:result; fill_flushes t; update_pushback t; result ;; let consume_one t = assert (length t >= 1); let result = Q.dequeue_exn t.buffer in t.num_values_read <- t.num_values_read + 1; fill_flushes t; update_pushback t; result; ;; (* [consume_at_most t num_values] reads [min num_values (length t)] items. It is an error if [is_empty t] or [num_values < 0]. *) let consume_at_most t num_values = assert (num_values >= 0); if num_values >= length t then consume_all t (* fast because it can use [Q.transfer] *) else begin t.num_values_read <- t.num_values_read + num_values; fill_flushes t; let result = Q.create () in for i = 1 to num_values do Q.enqueue result (Q.dequeue_exn t.buffer); done; update_pushback t; result end ;; let set_size_budget t size_budget = if size_budget < 0 then failwiths "negative size_budget" size_budget <:sexp_of< int >>; t.size_budget <- size_budget; update_pushback t; ;; let fill_blocked_reads t = while not (Q.is_empty t.blocked_reads) && not (is_empty t) do let module R = Blocked_read in match Q.dequeue_exn t.blocked_reads with | R.Zero ivar -> Ivar.fill ivar `Ok | R.One ivar -> Ivar.fill ivar (`Ok (consume_one t)) | R.All ivar -> Ivar.fill ivar (`Ok (consume_all t)) | R.At_most (n, ivar) -> Ivar.fill ivar (`Ok (consume_at_most t n)) done; ;; (* checks all invariants, calls a passed in f to handle a write, then updates reads and pushback *) let start_write t = if !show_debug_messages then Debug.log "write" t <:sexp_of< (a, b) t >>; if !check_invariant then invariant t; if is_closed t then failwiths "write to closed pipe" t <:sexp_of< (a, b) t >>; ;; let finish_write t = fill_blocked_reads t; update_pushback t; ;; let write' t values = start_write t; Q.transfer ~src:values ~dst:t.buffer; finish_write t; pushback t; ;; let write_no_pushback t value = start_write t; Q.enqueue t.buffer value; finish_write t; ;; let write t value = write_no_pushback t value; pushback t ;; let with_write t ~f = pushback t >>| fun () -> if is_closed t then `Closed else `Ok (f (fun x -> write_no_pushback t x)) ;; let start_read t label = if !show_debug_messages then Debug.log label t <:sexp_of< (a, b) t >>; if !check_invariant then invariant t; ;; let read_now t = start_read t "read_now"; if is_empty t then begin if is_closed t then `Eof else `Nothing_available end else begin assert (Q.is_empty t.blocked_reads); `Ok (consume_all t) end ;; let clear t = match read_now t with | `Eof | `Nothing_available | `Ok _ -> () ;; let read' t = start_read t "read'"; match read_now t with | (`Ok _ | `Eof) as r -> return r | `Nothing_available -> Deferred.create (fun ivar -> Q.enqueue t.blocked_reads (Blocked_read.All ivar)) ;; let read t = start_read t "read"; if is_empty t then begin if is_closed t then return `Eof else Deferred.create (fun ivar -> Q.enqueue t.blocked_reads (Blocked_read.One ivar)) end else begin assert (Q.is_empty t.blocked_reads); return (`Ok (consume_one t)) end ;; let read_at_most t ~num_values = start_read t "read_at_most"; if num_values <= 0 then failwiths "Pipe.read_at_most num_values < 0" num_values <:sexp_of< int >>; if is_empty t then begin if is_closed t then return `Eof else Deferred.create (fun ivar -> Q.enqueue t.blocked_reads (Blocked_read.At_most (num_values, ivar))) end else begin assert (Q.is_empty t.blocked_reads); return (`Ok (consume_at_most t num_values)) end ;; let values_available t = start_read t "values_available"; if not (is_empty t) then return `Ok else if is_closed t then return `Eof else Deferred.create (fun ivar -> Q.enqueue t.blocked_reads (Blocked_read.Zero ivar)) ;; [ read_exactly t ~num_values ] loops , getting you all [ num_values ] items , up to EOF . let read_exactly t ~num_values = start_read t "read_exactly"; if num_values <= 0 then failwiths "Pipe.read_exactly got num_values <= 0" num_values <:sexp_of< int >>; Deferred.create (fun finish -> let result = Q.create () in let rec loop () = let already_read = Q.length result in assert (already_read <= num_values); if already_read = num_values then Ivar.fill finish (`Exactly result) else begin read_at_most t ~num_values:(num_values - already_read) >>> function | `Eof -> Ivar.fill finish (if already_read = 0 then `Eof else `Fewer result) | `Ok q -> Q.transfer ~src:q ~dst:result; loop (); end in loop ()) ;; let flushed t = if is_empty t then return `Ok else (* [t] might be closed. But the read end can't be closed, because if it were, then [t] would be empty. If the write end is closed but not the read end, then we want to enqueue a blocked flush because the enqueued values may get read. *) Deferred.create (fun ready -> Q.enqueue t.blocked_flushes { Blocked_flush. fill_when_num_values_read = t.num_values_read + length t; ready; }) ;; let fold_gen t ~init ~f = if !check_invariant then invariant t; Deferred.create (fun finished -> let rec loop b = read' t >>> function | `Eof -> Ivar.fill finished b | `Ok q -> f b q loop in loop init) ;; let fold' t ~init ~f = fold_gen t ~init ~f:(fun b q loop -> f b q >>> loop) let fold t ~init ~f = fold_gen t ~init ~f:(fun init q loop -> loop (Q.fold q ~init ~f)) let iter_gen t ~f = fold_gen t ~init:() ~f:(fun () q loop -> f q loop) let drain t = iter_gen t ~f:(fun _ loop -> loop ()) let drain_and_count t = fold_gen t ~init:0 ~f:(fun sum q loop -> loop (sum + Q.length q)) let iter' t ~f = fold' t ~init:() ~f:(fun () q -> f q) let iter t ~f = iter' t ~f:(fun q -> Deferred.Queue.iter q ~f) let iter_without_pushback t ~f = iter_gen t ~f:(fun q loop -> Q.iter q ~f; loop ()) let read_all input = let result = Q.create () in iter_gen input ~f:(fun q loop -> Q.transfer ~src:q ~dst:result; loop ()); >>| fun () -> result ;; let to_list r = read_all r >>| Q.to_list (* CR201206 dpowers: remove this *) let to_stream t = Stream.create (fun tail -> iter_without_pushback t ~f:(fun x -> Tail.extend tail x) >>> fun () -> Tail.close_exn tail) ;; (* The implementation of [of_stream] does as much batching as possible. It grabs as many items as are available into an internal queue. Once it has grabbed everything, it writes it to the pipe and then blocks waiting for the next element from the stream. There's no possibility that we'll starve the pipe reading an endless stream, just accumulating the elements into our private queue forever without ever writing them downstream to the pipe. Why? because while we're running, the stream-producer *isn't* running -- there are no Async block points in the queue-accumulator loop. So the queue-accumulator loop will eventually catch up to the current stream tail, at which point we'll do the pipe-write and then block on the stream... thus giving the stream-producer a chance to make more elements. One can't implement [of_stream] using [Stream.iter] or [Stream.iter'] because you need to be able to stop early when the consumer closes the pipe. Also, using either of those would entail significantly more deferred overhead, whereas the below implementation uses a deferred only when it needs to wait for data from the stream. *) (* CR201206 dpowers: remove this *) let of_stream s = let r, w = create () in let q = Q.create () in let transfer () = if not (Q.is_empty q) then (* Can not pushback on the stream, so ignore the pushback on the pipe. *) whenever (write' w q); in let rec loop s = assert (not (is_closed w)); let next_deferred = Stream.next s in match Deferred.peek next_deferred with | Some next -> loop_next next | None -> transfer (); upon next_deferred check_closed_loop_next and check_closed_loop_next next = if not (is_closed w) then loop_next next and loop_next = function | Stream.Nil -> transfer (); close w | Stream.Cons (x, s) -> Q.enqueue q x; loop s in loop s; r ;; let transfer_gen input output ~f = if !check_invariant then begin invariant input; invariant output; end; Deferred.create (fun result -> let output_closed () = close_read input; Ivar.fill result () in let rec loop () = choose [ choice (values_available input) (function `Eof | `Ok as x -> x); choice (closed output) (fun () -> `Output_closed); ] >>> function | `Output_closed -> output_closed () | `Eof -> Ivar.fill result () | `Ok -> match read_now input with | `Eof -> Ivar.fill result () | `Nothing_available -> loop () | `Ok inq -> f inq continue and continue outq = if is_closed output then output_closed () else write' output outq >>> loop in loop ()) ;; let transfer' input output ~f = transfer_gen input output ~f:(fun q k -> f q >>> k) let transfer input output ~f = transfer_gen input output ~f:(fun q k -> k (Q.map q ~f)) let transfer_id input output = transfer_gen input output ~f:(fun q k -> k q) let map_gen input ~f = let (result, output) = create () in upon (transfer_gen input output ~f) (fun () -> close output); result ;; let map' input ~f = map_gen input ~f:(fun q k -> f q >>> k) let map input ~f = map_gen input ~f:(fun q k -> k (Q.map q ~f)) let filter_map' input ~f = map' input ~f:(fun q -> Deferred.Queue.filter_map q ~f) let filter_map input ~f = map_gen input ~f:(fun q k -> k (Q.filter_map q ~f)) let filter input ~f = filter_map input ~f:(fun x -> if f x then Some x else None) let of_list l = let reader, writer = create () in whenever (write' writer (Q.of_list l)); close writer; reader ;; let interleave inputs = if !check_invariant then List.iter inputs ~f:invariant; let (output, writer) = create () in upon (Deferred.List.iter inputs ~how:`Parallel ~f:(fun input -> transfer_id input writer)) (fun () -> close writer); output ;; let concat inputs = let r, w = create () in upon (Deferred.List.iter inputs ~f:(fun input -> transfer_id input w)) (fun () -> close w); r ;; TEST_MODULE = struct let () = check_invariant := true; show_debug_messages := false; ;; let stabilize = Scheduler.run_cycles_until_no_jobs_remain let read_result d = Q.to_list (Option.value_exn (Deferred.peek d)) TEST_UNIT = List.iter (List.init 10 ~f:(fun i -> List.init i ~f:Fn.id)) ~f:(fun l -> let reader = of_list l in upon (read_all reader) (fun q -> assert (Q.to_list q = l))); stabilize (); ;; (* ==================== close, close_read ==================== *) TEST_UNIT = let (reader, writer) = create () in assert (not (is_closed writer)); close writer; assert (Deferred.is_determined (closed reader)); assert (is_closed reader); assert (is_closed writer); ;; TEST_UNIT = let (reader, writer) = create () in assert (not (is_closed writer)); close_read reader; assert (Deferred.is_determined (closed reader)); assert (is_closed reader); assert (is_closed writer); ;; TEST_UNIT = let check_read read = let (reader, writer) = create () in let d = read reader in assert (Deferred.peek d = None); close writer; stabilize (); assert (Deferred.peek d = Some `Eof); let d = read reader in stabilize (); assert (Deferred.peek d = Some `Eof); in check_read read'; check_read read; check_read (fun reader -> read_at_most reader ~num_values:1); check_read (fun reader -> read_exactly reader ~num_values:1); check_read values_available; ;; TEST_UNIT = let check_read read get_values = let (reader, writer) = create () in whenever (write writer 13); close writer; let d = read reader in stabilize (); match Deferred.peek d with | Some z -> assert ([13] = get_values z) | None -> assert false in check_read read' (function `Ok q -> Q.to_list q | _ -> assert false); check_read read (function `Ok a -> [a] | _ -> assert false); check_read (fun r -> read_at_most r ~num_values:1) (function `Ok q -> Q.to_list q | _ -> assert false); check_read (fun r -> read_exactly r ~num_values:1) (function `Exactly q -> Q.to_list q | _ -> assert false); check_read (fun r -> return (read_now r)) (function `Ok q -> Q.to_list q | _ -> assert false); check_read read_all Q.to_list; ;; TEST_UNIT = let (reader, writer) = create () in let f1 = flushed writer in whenever (write writer 13); let f2 = flushed writer in close_read reader; stabilize (); assert (Deferred.peek f1 = Some `Ok); assert (Deferred.peek f2 = Some `Reader_closed); ;; (* ==================== pushback ==================== *) TEST_UNIT = let (_, writer) = create () in let p = write writer () in close writer; stabilize (); assert (Deferred.peek p = Some ()); ;; TEST_UNIT = let (reader, writer) = create () in let p = write writer () in close_read reader; stabilize (); assert (Deferred.peek p = Some ()); ;; TEST_UNIT = let (reader, writer) = create () in let p = write writer () in stabilize (); assert (Deferred.peek p = None); ignore (read_now reader); stabilize (); assert (Deferred.peek p = Some ()); ;; TEST_UNIT = let (reader, writer) = create () in let p = write writer () in let _ = write writer () in assert (length writer = 2); stabilize (); assert (Deferred.peek p = None); ignore (read reader); stabilize (); assert (length writer = 1); assert (Deferred.peek p = None); ignore (read reader); stabilize (); assert (length writer = 0); assert (Deferred.peek p = Some ()); ;; (* ==================== read_all ==================== *) TEST_UNIT = let (reader, writer) = create () in close writer; let d = read_all reader in stabilize (); assert (read_result d = []); ;; TEST_UNIT = let (reader, writer) = create () in whenever (write writer 13); close writer; let d = read_all reader in stabilize (); assert (read_result d = [13]); ;; (* ==================== read_at_most ==================== *) TEST_UNIT = let (reader, writer) = create () in whenever (write' writer (Q.of_list [12; 13; 14])); close writer; let d = read_at_most reader ~num_values:2 >>| function | `Eof -> assert false | `Ok q -> q in stabilize (); assert (read_result d = [12; 13]); ;; TEST_UNIT = let (reader, writer) = create () in whenever (write' writer (Q.of_list [12; 13; 14])); close writer; let d = read_at_most reader ~num_values:4 >>| function | `Eof -> assert false | `Ok q -> q in stabilize (); assert (read_result d = [12; 13; 14]); ;; (* ==================== clear ==================== *) TEST_UNIT = let l = [ 12; 13 ] in let (reader, writer) = create () in let p = write' writer (Q.of_list l) in clear reader; stabilize (); assert (Deferred.peek p = Some ()); assert (length reader = 0); whenever (write' writer (Q.of_list l)); close writer; let d = read_all reader in stabilize (); assert (read_result d = l); ;; (* ==================== map ==================== *) TEST_UNIT = let (reader, writer) = create () in let reader = map reader ~f:(fun x -> x + 13) in whenever (write' writer (Q.of_list [ 1; 2; 3 ])); let d = read_at_most reader ~num_values:2 >>| function | `Eof -> assert false | `Ok q -> close_read reader; q in stabilize (); assert (is_closed writer); assert (read_result d = [ 14; 15 ]); ;; (* ==================== of_stream ==================== *) TEST_UNIT = let tail = Tail.create () in let pipe = of_stream (Tail.collect tail) in stabilize (); assert (length pipe = 0); Tail.extend tail 13; stabilize (); assert (length pipe = 1); Tail.extend tail 14; Tail.extend tail 15; stabilize (); assert (length pipe = 3); let d = read_all pipe in Tail.close_exn tail; stabilize (); assert (read_result d = [ 13; 14; 15 ]); ;; (* ==================== interleave ==================== *) TEST_UNIT = let t = interleave [] in let d = read_all t in stabilize (); assert (read_result d = []); ;; TEST_UNIT = let l = [ 1 ; 2; 3 ] in let t = interleave [ of_list l ] in let d = read_all t in stabilize (); assert (read_result d = l); ;; TEST_UNIT = let l = [ 1 ; 2; 3 ] in let t = interleave [ of_list l; of_list l ] in let d = read_all t in stabilize (); assert (List.length (read_result d) = 2 * List.length l); ;; end ;;
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/async/core/lib/pipe.ml
ocaml
A [Blocked_flush.t] represents a blocked flush operation, which can be enabled by a future read. If someone does [flushed p] on a pipe, that blocks until everything that's currently in the pipe at that point has drained out of the pipe. When we call [flushed], it records the total amount of data that has been written so far in [fill_when_num_values_read]. We fill the [Flush.t] with [`Ok] when this amount of data has been read from the pipe. A [Blocked_flush.t] can also be filled with [`Reader_closed], which happens when the reader end of the pipe is closed, and we are thus sure that the unread elements preceding the flush will never be read. [id] is an integer used to distinguish pipes when debugging. [buffer] holds values written to the pipe that have not yet been read. [size_budget] governs pushback on writers to the pipe. There is *no* invariant that [Q.length buffer <= size_budget]. There is no hard upper bound on the number of elements that can be stuffed into the [buffer]. This is due to the way we handle writes. When we do a write, all of the values written are immediately enqueued into [buffer]. After the write, if [Q.length buffer <= t.size_budget], then the writer will be notified to continue writing. After the write, if [length t > t.size_budget], then the write will block until the pipe is under budget. [pushback] is used to give feedback to writers about whether they should write to the pipe. [pushback] is full iff [length t <= t.size_budget || is_closed t]. [blocked_flushes] holds flushes whose preceding elements have not been completely read. For each blocked flush, the number of elements that need to be read from the pipe in order to fill the flush is: fill_when_num_values_read - num_values_read Keeping the data in this form allows us to change a single field (num_values_read) when we consume values instead of having to iterate over the whole queue of flushes. [blocked_reads] holds reads that are waiting on data to be written to the pipe. [closed] is filled when we close the write end of the pipe. If data is available, no one is waiting for it. This would need to change if we ever implement [read_exactly] as an atomic operation. You never block trying to read a closed pipe. initially, the pipe does not pushback we just cleared the buffer, so may need to fill [t.pushback] [consume_all t] reads all the elements in [t], in constant time. [consume_at_most t num_values] reads [min num_values (length t)] items. It is an error if [is_empty t] or [num_values < 0]. fast because it can use [Q.transfer] checks all invariants, calls a passed in f to handle a write, then updates reads and pushback [t] might be closed. But the read end can't be closed, because if it were, then [t] would be empty. If the write end is closed but not the read end, then we want to enqueue a blocked flush because the enqueued values may get read. CR201206 dpowers: remove this The implementation of [of_stream] does as much batching as possible. It grabs as many items as are available into an internal queue. Once it has grabbed everything, it writes it to the pipe and then blocks waiting for the next element from the stream. There's no possibility that we'll starve the pipe reading an endless stream, just accumulating the elements into our private queue forever without ever writing them downstream to the pipe. Why? because while we're running, the stream-producer *isn't* running -- there are no Async block points in the queue-accumulator loop. So the queue-accumulator loop will eventually catch up to the current stream tail, at which point we'll do the pipe-write and then block on the stream... thus giving the stream-producer a chance to make more elements. One can't implement [of_stream] using [Stream.iter] or [Stream.iter'] because you need to be able to stop early when the consumer closes the pipe. Also, using either of those would entail significantly more deferred overhead, whereas the below implementation uses a deferred only when it needs to wait for data from the stream. CR201206 dpowers: remove this Can not pushback on the stream, so ignore the pushback on the pipe. ==================== close, close_read ==================== ==================== pushback ==================== ==================== read_all ==================== ==================== read_at_most ==================== ==================== clear ==================== ==================== map ==================== ==================== of_stream ==================== ==================== interleave ====================
open Core.Std open Import open Deferred_std module Stream = Async_stream module Q = Queue let show_debug_messages = ref false let check_invariant = ref false module Blocked_read = struct A [ Blocked_read.t ] represents a blocked read attempt . If someone reads from an empty pipe , they enqueue a [ Blocked_read.t ] in the queue of [ blocked_reads ] . Later , when values are written to a pipe , that will cause some number of blocked reads to be filled , first come first serve . The blocked - read constructor specifies how many values a read should consume from the pipe when it gets its turn . If a pipe is closed , then all blocked reads will be filled with [ ` Eof ] . pipe, they enqueue a [Blocked_read.t] in the queue of [blocked_reads]. Later, when values are written to a pipe, that will cause some number of blocked reads to be filled, first come first serve. The blocked-read constructor specifies how many values a read should consume from the pipe when it gets its turn. If a pipe is closed, then all blocked reads will be filled with [`Eof]. *) type 'a t = | Zero of [ `Eof | `Ok ] Ivar.t | One of [ `Eof | `Ok of 'a ] Ivar.t | All of [ `Eof | `Ok of 'a Q.t ] Ivar.t | At_most of int * [ `Eof | `Ok of 'a Q.t ] Ivar.t with sexp_of let invariant t = try match t with | Zero _ | All _ | One _ -> () | At_most (i, _) -> assert (i > 0); with | exn -> failwiths "Pipe.Blocked_read.invariant failed" (exn, t) <:sexp_of< exn * a t >> ;; let is_empty = function | Zero i -> Ivar.is_empty i | One i -> Ivar.is_empty i | All i -> Ivar.is_empty i | At_most (_, i) -> Ivar.is_empty i ;; let fill_with_eof = function | Zero i -> Ivar.fill i `Eof | One i -> Ivar.fill i `Eof | All i -> Ivar.fill i `Eof | At_most (_, i) -> Ivar.fill i `Eof end module Blocked_flush = struct type t = { fill_when_num_values_read : int; ready : [ `Ok | `Reader_closed ] Ivar.t; } with fields, sexp_of let fill t v = Ivar.fill t.ready v end type ('a, 'phantom) t = id : int; buffer : 'a Q.t; mutable size_budget : int; mutable pushback : unit Ivar.t; [ num_values_read ] keeps track of the total number of values that have been read from the pipe . We do not have to worry about overflow in [ num_values_read ] . You 'd need to write 2 ^ 62 elements to the pipe , which would take about 146 years , at a flow rate of 1 size - unit / nanosecond . from the pipe. We do not have to worry about overflow in [num_values_read]. You'd need to write 2^62 elements to the pipe, which would take about 146 years, at a flow rate of 1 size-unit/nanosecond. *) mutable num_values_read : int; blocked_flushes : Blocked_flush.t Q.t; blocked_reads : 'a Blocked_read.t Q.t; closed : unit Ivar.t; } with fields, sexp_of type ('a, 'phantom) pipe = ('a, 'phantom) t with sexp_of let hash t = Hashtbl.hash t.id let equal (t1 : (_, _) t) t2 = phys_equal t1 t2 let is_empty t = Q.is_empty t.buffer let is_closed t = Ivar.is_full t.closed let closed t = Ivar.read t.closed let pushback t = Ivar.read t.pushback let length t = Q.length t.buffer let invariant t = try assert (t.size_budget >= 0); assert (Ivar.is_full t.pushback = (length t <= t.size_budget || is_closed t)); Q.iter t.blocked_flushes ~f:(fun f -> assert (f.Blocked_flush.fill_when_num_values_read > t.num_values_read)); assert (List.is_sorted ~compare (List.map (Q.to_list t.blocked_flushes) ~f:Blocked_flush.fill_when_num_values_read)); if is_empty t then assert (Q.is_empty t.blocked_flushes); if not (is_empty t) then assert (Q.is_empty t.blocked_reads); Q.iter t.blocked_reads ~f:(fun read -> Blocked_read.invariant read; assert (Blocked_read.is_empty read)); if is_closed t then assert (Q.is_empty t.blocked_reads); with | exn -> failwiths "Pipe.invariant failed" (exn, t) <:sexp_of< exn * (a, b) t >> ;; module Reader = struct type phantom with sexp_of type 'a t = ('a, phantom) pipe with sexp_of let invariant = invariant end module Writer = struct type phantom with sexp_of type 'a t = ('a, phantom) pipe with sexp_of let invariant = invariant end let id_ref = ref 0 let create () = incr id_ref; let t = { id = !id_ref ; closed = Ivar.create (); size_budget = 0 ; pushback = Ivar.create (); buffer = Q.create () ; num_values_read = 0 ; blocked_flushes = Q.create () ; blocked_reads = Q.create () ; } in if !check_invariant then invariant t; (t, t) ;; let update_pushback t = if length t <= t.size_budget || is_closed t then Ivar.fill_if_empty t.pushback () else if Ivar.is_full t.pushback then t.pushback <- Ivar.create (); ;; let close t = if !show_debug_messages then Debug.log "close" t <:sexp_of< (a, b) t >>; if !check_invariant then invariant t; if not (is_closed t) then begin Ivar.fill t.closed (); if is_empty t then begin Q.iter t.blocked_reads ~f:Blocked_read.fill_with_eof; Q.clear t.blocked_reads; end; update_pushback t; end; ;; let close_read t = if !show_debug_messages then Debug.log "close_read" t <:sexp_of< (a, b) t >>; if !check_invariant then invariant t; Q.iter t.blocked_flushes ~f:(fun flush -> Blocked_flush.fill flush `Reader_closed); Q.clear t.blocked_flushes; Q.clear t.buffer; close t; ;; let rec fill_flushes t = match Q.peek t.blocked_flushes with | None -> () | Some flush -> if t.num_values_read >= flush.Blocked_flush.fill_when_num_values_read then begin Blocked_flush.fill flush `Ok; ignore (Q.dequeue_exn t.blocked_flushes : Blocked_flush.t); fill_flushes t; end ;; let consume_all t = let result = Q.create () in t.num_values_read <- t.num_values_read + length t; Q.transfer ~src:t.buffer ~dst:result; fill_flushes t; update_pushback t; result ;; let consume_one t = assert (length t >= 1); let result = Q.dequeue_exn t.buffer in t.num_values_read <- t.num_values_read + 1; fill_flushes t; update_pushback t; result; ;; let consume_at_most t num_values = assert (num_values >= 0); if num_values >= length t then else begin t.num_values_read <- t.num_values_read + num_values; fill_flushes t; let result = Q.create () in for i = 1 to num_values do Q.enqueue result (Q.dequeue_exn t.buffer); done; update_pushback t; result end ;; let set_size_budget t size_budget = if size_budget < 0 then failwiths "negative size_budget" size_budget <:sexp_of< int >>; t.size_budget <- size_budget; update_pushback t; ;; let fill_blocked_reads t = while not (Q.is_empty t.blocked_reads) && not (is_empty t) do let module R = Blocked_read in match Q.dequeue_exn t.blocked_reads with | R.Zero ivar -> Ivar.fill ivar `Ok | R.One ivar -> Ivar.fill ivar (`Ok (consume_one t)) | R.All ivar -> Ivar.fill ivar (`Ok (consume_all t)) | R.At_most (n, ivar) -> Ivar.fill ivar (`Ok (consume_at_most t n)) done; ;; let start_write t = if !show_debug_messages then Debug.log "write" t <:sexp_of< (a, b) t >>; if !check_invariant then invariant t; if is_closed t then failwiths "write to closed pipe" t <:sexp_of< (a, b) t >>; ;; let finish_write t = fill_blocked_reads t; update_pushback t; ;; let write' t values = start_write t; Q.transfer ~src:values ~dst:t.buffer; finish_write t; pushback t; ;; let write_no_pushback t value = start_write t; Q.enqueue t.buffer value; finish_write t; ;; let write t value = write_no_pushback t value; pushback t ;; let with_write t ~f = pushback t >>| fun () -> if is_closed t then `Closed else `Ok (f (fun x -> write_no_pushback t x)) ;; let start_read t label = if !show_debug_messages then Debug.log label t <:sexp_of< (a, b) t >>; if !check_invariant then invariant t; ;; let read_now t = start_read t "read_now"; if is_empty t then begin if is_closed t then `Eof else `Nothing_available end else begin assert (Q.is_empty t.blocked_reads); `Ok (consume_all t) end ;; let clear t = match read_now t with | `Eof | `Nothing_available | `Ok _ -> () ;; let read' t = start_read t "read'"; match read_now t with | (`Ok _ | `Eof) as r -> return r | `Nothing_available -> Deferred.create (fun ivar -> Q.enqueue t.blocked_reads (Blocked_read.All ivar)) ;; let read t = start_read t "read"; if is_empty t then begin if is_closed t then return `Eof else Deferred.create (fun ivar -> Q.enqueue t.blocked_reads (Blocked_read.One ivar)) end else begin assert (Q.is_empty t.blocked_reads); return (`Ok (consume_one t)) end ;; let read_at_most t ~num_values = start_read t "read_at_most"; if num_values <= 0 then failwiths "Pipe.read_at_most num_values < 0" num_values <:sexp_of< int >>; if is_empty t then begin if is_closed t then return `Eof else Deferred.create (fun ivar -> Q.enqueue t.blocked_reads (Blocked_read.At_most (num_values, ivar))) end else begin assert (Q.is_empty t.blocked_reads); return (`Ok (consume_at_most t num_values)) end ;; let values_available t = start_read t "values_available"; if not (is_empty t) then return `Ok else if is_closed t then return `Eof else Deferred.create (fun ivar -> Q.enqueue t.blocked_reads (Blocked_read.Zero ivar)) ;; [ read_exactly t ~num_values ] loops , getting you all [ num_values ] items , up to EOF . let read_exactly t ~num_values = start_read t "read_exactly"; if num_values <= 0 then failwiths "Pipe.read_exactly got num_values <= 0" num_values <:sexp_of< int >>; Deferred.create (fun finish -> let result = Q.create () in let rec loop () = let already_read = Q.length result in assert (already_read <= num_values); if already_read = num_values then Ivar.fill finish (`Exactly result) else begin read_at_most t ~num_values:(num_values - already_read) >>> function | `Eof -> Ivar.fill finish (if already_read = 0 then `Eof else `Fewer result) | `Ok q -> Q.transfer ~src:q ~dst:result; loop (); end in loop ()) ;; let flushed t = if is_empty t then return `Ok else Deferred.create (fun ready -> Q.enqueue t.blocked_flushes { Blocked_flush. fill_when_num_values_read = t.num_values_read + length t; ready; }) ;; let fold_gen t ~init ~f = if !check_invariant then invariant t; Deferred.create (fun finished -> let rec loop b = read' t >>> function | `Eof -> Ivar.fill finished b | `Ok q -> f b q loop in loop init) ;; let fold' t ~init ~f = fold_gen t ~init ~f:(fun b q loop -> f b q >>> loop) let fold t ~init ~f = fold_gen t ~init ~f:(fun init q loop -> loop (Q.fold q ~init ~f)) let iter_gen t ~f = fold_gen t ~init:() ~f:(fun () q loop -> f q loop) let drain t = iter_gen t ~f:(fun _ loop -> loop ()) let drain_and_count t = fold_gen t ~init:0 ~f:(fun sum q loop -> loop (sum + Q.length q)) let iter' t ~f = fold' t ~init:() ~f:(fun () q -> f q) let iter t ~f = iter' t ~f:(fun q -> Deferred.Queue.iter q ~f) let iter_without_pushback t ~f = iter_gen t ~f:(fun q loop -> Q.iter q ~f; loop ()) let read_all input = let result = Q.create () in iter_gen input ~f:(fun q loop -> Q.transfer ~src:q ~dst:result; loop ()); >>| fun () -> result ;; let to_list r = read_all r >>| Q.to_list let to_stream t = Stream.create (fun tail -> iter_without_pushback t ~f:(fun x -> Tail.extend tail x) >>> fun () -> Tail.close_exn tail) ;; let of_stream s = let r, w = create () in let q = Q.create () in let transfer () = if not (Q.is_empty q) then whenever (write' w q); in let rec loop s = assert (not (is_closed w)); let next_deferred = Stream.next s in match Deferred.peek next_deferred with | Some next -> loop_next next | None -> transfer (); upon next_deferred check_closed_loop_next and check_closed_loop_next next = if not (is_closed w) then loop_next next and loop_next = function | Stream.Nil -> transfer (); close w | Stream.Cons (x, s) -> Q.enqueue q x; loop s in loop s; r ;; let transfer_gen input output ~f = if !check_invariant then begin invariant input; invariant output; end; Deferred.create (fun result -> let output_closed () = close_read input; Ivar.fill result () in let rec loop () = choose [ choice (values_available input) (function `Eof | `Ok as x -> x); choice (closed output) (fun () -> `Output_closed); ] >>> function | `Output_closed -> output_closed () | `Eof -> Ivar.fill result () | `Ok -> match read_now input with | `Eof -> Ivar.fill result () | `Nothing_available -> loop () | `Ok inq -> f inq continue and continue outq = if is_closed output then output_closed () else write' output outq >>> loop in loop ()) ;; let transfer' input output ~f = transfer_gen input output ~f:(fun q k -> f q >>> k) let transfer input output ~f = transfer_gen input output ~f:(fun q k -> k (Q.map q ~f)) let transfer_id input output = transfer_gen input output ~f:(fun q k -> k q) let map_gen input ~f = let (result, output) = create () in upon (transfer_gen input output ~f) (fun () -> close output); result ;; let map' input ~f = map_gen input ~f:(fun q k -> f q >>> k) let map input ~f = map_gen input ~f:(fun q k -> k (Q.map q ~f)) let filter_map' input ~f = map' input ~f:(fun q -> Deferred.Queue.filter_map q ~f) let filter_map input ~f = map_gen input ~f:(fun q k -> k (Q.filter_map q ~f)) let filter input ~f = filter_map input ~f:(fun x -> if f x then Some x else None) let of_list l = let reader, writer = create () in whenever (write' writer (Q.of_list l)); close writer; reader ;; let interleave inputs = if !check_invariant then List.iter inputs ~f:invariant; let (output, writer) = create () in upon (Deferred.List.iter inputs ~how:`Parallel ~f:(fun input -> transfer_id input writer)) (fun () -> close writer); output ;; let concat inputs = let r, w = create () in upon (Deferred.List.iter inputs ~f:(fun input -> transfer_id input w)) (fun () -> close w); r ;; TEST_MODULE = struct let () = check_invariant := true; show_debug_messages := false; ;; let stabilize = Scheduler.run_cycles_until_no_jobs_remain let read_result d = Q.to_list (Option.value_exn (Deferred.peek d)) TEST_UNIT = List.iter (List.init 10 ~f:(fun i -> List.init i ~f:Fn.id)) ~f:(fun l -> let reader = of_list l in upon (read_all reader) (fun q -> assert (Q.to_list q = l))); stabilize (); ;; TEST_UNIT = let (reader, writer) = create () in assert (not (is_closed writer)); close writer; assert (Deferred.is_determined (closed reader)); assert (is_closed reader); assert (is_closed writer); ;; TEST_UNIT = let (reader, writer) = create () in assert (not (is_closed writer)); close_read reader; assert (Deferred.is_determined (closed reader)); assert (is_closed reader); assert (is_closed writer); ;; TEST_UNIT = let check_read read = let (reader, writer) = create () in let d = read reader in assert (Deferred.peek d = None); close writer; stabilize (); assert (Deferred.peek d = Some `Eof); let d = read reader in stabilize (); assert (Deferred.peek d = Some `Eof); in check_read read'; check_read read; check_read (fun reader -> read_at_most reader ~num_values:1); check_read (fun reader -> read_exactly reader ~num_values:1); check_read values_available; ;; TEST_UNIT = let check_read read get_values = let (reader, writer) = create () in whenever (write writer 13); close writer; let d = read reader in stabilize (); match Deferred.peek d with | Some z -> assert ([13] = get_values z) | None -> assert false in check_read read' (function `Ok q -> Q.to_list q | _ -> assert false); check_read read (function `Ok a -> [a] | _ -> assert false); check_read (fun r -> read_at_most r ~num_values:1) (function `Ok q -> Q.to_list q | _ -> assert false); check_read (fun r -> read_exactly r ~num_values:1) (function `Exactly q -> Q.to_list q | _ -> assert false); check_read (fun r -> return (read_now r)) (function `Ok q -> Q.to_list q | _ -> assert false); check_read read_all Q.to_list; ;; TEST_UNIT = let (reader, writer) = create () in let f1 = flushed writer in whenever (write writer 13); let f2 = flushed writer in close_read reader; stabilize (); assert (Deferred.peek f1 = Some `Ok); assert (Deferred.peek f2 = Some `Reader_closed); ;; TEST_UNIT = let (_, writer) = create () in let p = write writer () in close writer; stabilize (); assert (Deferred.peek p = Some ()); ;; TEST_UNIT = let (reader, writer) = create () in let p = write writer () in close_read reader; stabilize (); assert (Deferred.peek p = Some ()); ;; TEST_UNIT = let (reader, writer) = create () in let p = write writer () in stabilize (); assert (Deferred.peek p = None); ignore (read_now reader); stabilize (); assert (Deferred.peek p = Some ()); ;; TEST_UNIT = let (reader, writer) = create () in let p = write writer () in let _ = write writer () in assert (length writer = 2); stabilize (); assert (Deferred.peek p = None); ignore (read reader); stabilize (); assert (length writer = 1); assert (Deferred.peek p = None); ignore (read reader); stabilize (); assert (length writer = 0); assert (Deferred.peek p = Some ()); ;; TEST_UNIT = let (reader, writer) = create () in close writer; let d = read_all reader in stabilize (); assert (read_result d = []); ;; TEST_UNIT = let (reader, writer) = create () in whenever (write writer 13); close writer; let d = read_all reader in stabilize (); assert (read_result d = [13]); ;; TEST_UNIT = let (reader, writer) = create () in whenever (write' writer (Q.of_list [12; 13; 14])); close writer; let d = read_at_most reader ~num_values:2 >>| function | `Eof -> assert false | `Ok q -> q in stabilize (); assert (read_result d = [12; 13]); ;; TEST_UNIT = let (reader, writer) = create () in whenever (write' writer (Q.of_list [12; 13; 14])); close writer; let d = read_at_most reader ~num_values:4 >>| function | `Eof -> assert false | `Ok q -> q in stabilize (); assert (read_result d = [12; 13; 14]); ;; TEST_UNIT = let l = [ 12; 13 ] in let (reader, writer) = create () in let p = write' writer (Q.of_list l) in clear reader; stabilize (); assert (Deferred.peek p = Some ()); assert (length reader = 0); whenever (write' writer (Q.of_list l)); close writer; let d = read_all reader in stabilize (); assert (read_result d = l); ;; TEST_UNIT = let (reader, writer) = create () in let reader = map reader ~f:(fun x -> x + 13) in whenever (write' writer (Q.of_list [ 1; 2; 3 ])); let d = read_at_most reader ~num_values:2 >>| function | `Eof -> assert false | `Ok q -> close_read reader; q in stabilize (); assert (is_closed writer); assert (read_result d = [ 14; 15 ]); ;; TEST_UNIT = let tail = Tail.create () in let pipe = of_stream (Tail.collect tail) in stabilize (); assert (length pipe = 0); Tail.extend tail 13; stabilize (); assert (length pipe = 1); Tail.extend tail 14; Tail.extend tail 15; stabilize (); assert (length pipe = 3); let d = read_all pipe in Tail.close_exn tail; stabilize (); assert (read_result d = [ 13; 14; 15 ]); ;; TEST_UNIT = let t = interleave [] in let d = read_all t in stabilize (); assert (read_result d = []); ;; TEST_UNIT = let l = [ 1 ; 2; 3 ] in let t = interleave [ of_list l ] in let d = read_all t in stabilize (); assert (read_result d = l); ;; TEST_UNIT = let l = [ 1 ; 2; 3 ] in let t = interleave [ of_list l; of_list l ] in let d = read_all t in stabilize (); assert (List.length (read_result d) = 2 * List.length l); ;; end ;;
4376c08101094ccc5e42ba63806e2ebf6ceb026312b9fc6b444e3f9334d1dc79
chefy-io/clojure-katas
reverse_binary.clj
(ns clojure-katas.reverse-binary (:require [clojure-katas.core :as core])) (core/defproblem compute "Credit: Spotify Puzzle: / Your task will be to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11. The input contains a single line with an integer N, 1 ≤ N ≤ 1000000000. The output one line with one integer, the number we get by reversing the binary representation of N. Sample input 1: 13 Sample output 1: 11 Sample input 2: 47 Sample output 2: 61 " [num])
null
https://raw.githubusercontent.com/chefy-io/clojure-katas/81efe02dfe5add9e10146e10dd2b34f072f7686e/src/clojure_katas/reverse_binary.clj
clojure
(ns clojure-katas.reverse-binary (:require [clojure-katas.core :as core])) (core/defproblem compute "Credit: Spotify Puzzle: / Your task will be to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11. The input contains a single line with an integer N, 1 ≤ N ≤ 1000000000. The output one line with one integer, the number we get by reversing the binary representation of N. Sample input 1: 13 Sample output 1: 11 Sample input 2: 47 Sample output 2: 61 " [num])
34caf8fd87cdba4e8a6b1eeead09dc18cf6bcf72efb35145b1bb80ec70ed4336
AndrewRademacher/aeson-casing
Main.hs
module Main where import Test.Tasty import qualified Data.Aeson.Casing.Test as Casing main :: IO () main = defaultMain $ testGroup "Tests" [ Casing.tests ]
null
https://raw.githubusercontent.com/AndrewRademacher/aeson-casing/a6acbc40f6cffce7692cab5022d98732dc7a68b3/test/Main.hs
haskell
module Main where import Test.Tasty import qualified Data.Aeson.Casing.Test as Casing main :: IO () main = defaultMain $ testGroup "Tests" [ Casing.tests ]
0495bf870b7091f7f8e760878697a749c52b7e23ac46e3e2be245cfb9af17c7a
ahrefs/devkit
stage_merge.ml
open Enum type ('a,'b) value = Left of 'a | Right of 'b | Both of ('a * 'b) let stage_merge compare ~left ~right ~multi return key1 key2 v1 v2 = let multi_ret next found ret = match left, multi with | true, true -> .< if not .~found then .~ret else .~next () >. | true, false -> ret | false, _ -> .< .~next () >. in .< fun e1 e2 -> let _found = ref false in let rec next () = let _prev_found = .~(if multi && left then .< let prev = !_found in _found := false; prev>. else .< false >.) in match peek e1, peek e2 with | None, None -> raise No_more_elements | Some x, None -> junk e1; .~(let ret = return (key1 .<x>.) (Left (v1 .<x>.)) in multi_ret .<next>. .<_prev_found>. ret) | None, Some y -> junk e2; .~(if right then return (key2 .<y>.) (Right (v2 .<y>.)) else .< raise No_more_elements >.) | Some x, Some y -> let k1 = .~(key1 .<x>.) in let k2 = .~(key2 .<y>.) in match .~compare k1 k2 with | 0 -> .~(if not multi then .< junk e1 >. else if left then .< _found := true >. else .< () >.); junk e2; .~(return .<k1>. (Both (v1 .<x>., v2 .<y>.))) | n when n < 0 -> junk e1; .~(let ret = return .<k1>. (Left (v1 .<x>.)) in multi_ret .<next>. .<_prev_found>. ret) n > 0 in from next >. (* helpers *) let lift f x = .<f .~x>. (* csp *) let fst_ x = .<fst .~x>. let snd_ x = .<snd .~x>. let some x = .<Some .~x>. let id x = x let same f x = f x x let ($) f g = fun x -> f @@ g x let print_code code = let open Format in format_code std_formatter (close_code code); pp_print_newline std_formatter (); pp_print_newline std_formatter () (* generate *) let wrap ret v1 v2 = fun k v -> let v = match v with Left x -> Left (v1 x) | Right x -> Right (v2 x) | Both (x,y) -> Both (v1 x, v2 y) in ret k v let ret_pair _k v = match v with Left x -> .< .~x, None >. | Right x -> .< None, .~x >. | Both (x,y) -> .<.~x, .~y >. let ret_assoc k v = match v with Left x -> .<.~k, .~x, None>. | Right x -> .<.~k, None, .~x>. | Both (x,y) -> .<.~k, .~x, .~y>. let ret_full _k v = match v with Left x -> .< `Left .~x >. | Right x -> .< `Right .~x >. | Both (x,y) -> .< `Both (.~x, .~y) >. let ret_add_key f k v = .< .~k, .~(f k v) >. let () = print_endline "[@@@ocaml.warning \"-27-39\"]"; print_endline "" let () = let bool k = k false; k true in bool @@ fun assoc -> bool @@ fun multi -> bool @@ fun right -> bool @@ fun left -> bool @@ fun by -> match by, assoc with | true, true -> () (* assoc doesn't need `by`, has explicit key already *) | false, false -> () (* we don't want non-`by` variants, except for assoc which has explicit key *) | _ -> let dir = match left, right with | true, true -> "full" | true, false -> "left" | false, true -> "right" | false, false -> "inner" in let str b name = if b then name else "" in let name = String.concat "_" @@ List.filter ((<>) "") @@ ["join"; str assoc "assoc"; dir; str multi "multi"; str by "by"] in Printf.printf "let %s =\n" name; let stage cmp ret k1 k2 v = stage_merge cmp ~left ~right ~multi ret k1 k2 v v in let gen key v ret = if by then print_code .< fun cmp k1 k2 -> .~(stage .<cmp>. ret (fun x -> .<k1 .~x>.) (fun x -> .<k2 .~x>.) v) >. else print_code .< fun cmp -> .~(stage .<cmp>. ret key key v) >. in let gen v1 v2 = match assoc, left && right with | false, false -> gen id id (wrap ret_pair v1 v2) | false, true -> gen id id ret_full | true, false -> gen fst_ snd_ (wrap ret_assoc v1 v2) | true, true -> gen fst_ snd_ (ret_add_key @@ ret_full) in begin match left, right with | true, true -> gen id id | true, false -> gen id some | false, true -> gen some id | false, false -> gen id id end; if by then Printf.printf "let %s_key cmp k = %s cmp k k\n\n" name name let stage_full_merge return key v = .< fun cmp -> .~(stage_merge .<cmp>. ~left:true ~right:true ~multi:false return key key v v) >. let () = print_endline "let merge ="; print_code @@ stage_full_merge (wrap ret_pair some some) id id let () = print_endline "let merge_assoc ="; print_code @@ stage_full_merge (wrap ret_assoc some some) fst_ snd_ let ( ) = print_endline " let merge_by = " ; print_code @@ . < fun compare key1 key2 - > .~(stage_full_merge ( ret_pair some some ) ( fun x - > .<key1 .~x > . ) ( fun x - > .<key2 .~x > . ) ) compare > . let () = print_endline "let merge_by ="; print_code @@ .< fun compare key1 key2 -> .~(stage_full_merge (ret_pair some some) (fun x -> .<key1 .~x>.) (fun x -> .<key2 .~x>.)) compare >. *)
null
https://raw.githubusercontent.com/ahrefs/devkit/559c2df8f6eacb091e0eac38f508c45b6567bdd8/stage_merge.ml
ocaml
helpers csp generate assoc doesn't need `by`, has explicit key already we don't want non-`by` variants, except for assoc which has explicit key
open Enum type ('a,'b) value = Left of 'a | Right of 'b | Both of ('a * 'b) let stage_merge compare ~left ~right ~multi return key1 key2 v1 v2 = let multi_ret next found ret = match left, multi with | true, true -> .< if not .~found then .~ret else .~next () >. | true, false -> ret | false, _ -> .< .~next () >. in .< fun e1 e2 -> let _found = ref false in let rec next () = let _prev_found = .~(if multi && left then .< let prev = !_found in _found := false; prev>. else .< false >.) in match peek e1, peek e2 with | None, None -> raise No_more_elements | Some x, None -> junk e1; .~(let ret = return (key1 .<x>.) (Left (v1 .<x>.)) in multi_ret .<next>. .<_prev_found>. ret) | None, Some y -> junk e2; .~(if right then return (key2 .<y>.) (Right (v2 .<y>.)) else .< raise No_more_elements >.) | Some x, Some y -> let k1 = .~(key1 .<x>.) in let k2 = .~(key2 .<y>.) in match .~compare k1 k2 with | 0 -> .~(if not multi then .< junk e1 >. else if left then .< _found := true >. else .< () >.); junk e2; .~(return .<k1>. (Both (v1 .<x>., v2 .<y>.))) | n when n < 0 -> junk e1; .~(let ret = return .<k1>. (Left (v1 .<x>.)) in multi_ret .<next>. .<_prev_found>. ret) n > 0 in from next >. let fst_ x = .<fst .~x>. let snd_ x = .<snd .~x>. let some x = .<Some .~x>. let id x = x let same f x = f x x let ($) f g = fun x -> f @@ g x let print_code code = let open Format in format_code std_formatter (close_code code); pp_print_newline std_formatter (); pp_print_newline std_formatter () let wrap ret v1 v2 = fun k v -> let v = match v with Left x -> Left (v1 x) | Right x -> Right (v2 x) | Both (x,y) -> Both (v1 x, v2 y) in ret k v let ret_pair _k v = match v with Left x -> .< .~x, None >. | Right x -> .< None, .~x >. | Both (x,y) -> .<.~x, .~y >. let ret_assoc k v = match v with Left x -> .<.~k, .~x, None>. | Right x -> .<.~k, None, .~x>. | Both (x,y) -> .<.~k, .~x, .~y>. let ret_full _k v = match v with Left x -> .< `Left .~x >. | Right x -> .< `Right .~x >. | Both (x,y) -> .< `Both (.~x, .~y) >. let ret_add_key f k v = .< .~k, .~(f k v) >. let () = print_endline "[@@@ocaml.warning \"-27-39\"]"; print_endline "" let () = let bool k = k false; k true in bool @@ fun assoc -> bool @@ fun multi -> bool @@ fun right -> bool @@ fun left -> bool @@ fun by -> match by, assoc with | _ -> let dir = match left, right with | true, true -> "full" | true, false -> "left" | false, true -> "right" | false, false -> "inner" in let str b name = if b then name else "" in let name = String.concat "_" @@ List.filter ((<>) "") @@ ["join"; str assoc "assoc"; dir; str multi "multi"; str by "by"] in Printf.printf "let %s =\n" name; let stage cmp ret k1 k2 v = stage_merge cmp ~left ~right ~multi ret k1 k2 v v in let gen key v ret = if by then print_code .< fun cmp k1 k2 -> .~(stage .<cmp>. ret (fun x -> .<k1 .~x>.) (fun x -> .<k2 .~x>.) v) >. else print_code .< fun cmp -> .~(stage .<cmp>. ret key key v) >. in let gen v1 v2 = match assoc, left && right with | false, false -> gen id id (wrap ret_pair v1 v2) | false, true -> gen id id ret_full | true, false -> gen fst_ snd_ (wrap ret_assoc v1 v2) | true, true -> gen fst_ snd_ (ret_add_key @@ ret_full) in begin match left, right with | true, true -> gen id id | true, false -> gen id some | false, true -> gen some id | false, false -> gen id id end; if by then Printf.printf "let %s_key cmp k = %s cmp k k\n\n" name name let stage_full_merge return key v = .< fun cmp -> .~(stage_merge .<cmp>. ~left:true ~right:true ~multi:false return key key v v) >. let () = print_endline "let merge ="; print_code @@ stage_full_merge (wrap ret_pair some some) id id let () = print_endline "let merge_assoc ="; print_code @@ stage_full_merge (wrap ret_assoc some some) fst_ snd_ let ( ) = print_endline " let merge_by = " ; print_code @@ . < fun compare key1 key2 - > .~(stage_full_merge ( ret_pair some some ) ( fun x - > .<key1 .~x > . ) ( fun x - > .<key2 .~x > . ) ) compare > . let () = print_endline "let merge_by ="; print_code @@ .< fun compare key1 key2 -> .~(stage_full_merge (ret_pair some some) (fun x -> .<key1 .~x>.) (fun x -> .<key2 .~x>.)) compare >. *)
4f7f065d4cd36b388f8f176045c0cd45dc9f11e1767c0b1cc9ff50700a0ff4cd
huiyaozheng/Mirage-zmq
config.ml
open Mirage let main = foreign ~packages:[package "mirage-zmq"] "Unikernel.Main" (stackv4 @-> job) let stack = generic_stackv4 default_network let () = register "push_unikernel" [ main $ stack ]
null
https://raw.githubusercontent.com/huiyaozheng/Mirage-zmq/af288a3378a7c357bd5646a3abf4fd5ae777369b/test/Queue_size/PUSH_send_limited/config.ml
ocaml
open Mirage let main = foreign ~packages:[package "mirage-zmq"] "Unikernel.Main" (stackv4 @-> job) let stack = generic_stackv4 default_network let () = register "push_unikernel" [ main $ stack ]
099ce67802219c218f8a1d8b7496f32466fbaa72cdf4d96a8e93699b7a898034
nvim-treesitter/nvim-treesitter
injections.scm
[ (line_comment) (block_comment) (nesting_block_comment) ] @comment (token_string_tokens) @d
null
https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/c2c454c29a92e2d0db955fc1d6841566c28e3ecd/queries/d/injections.scm
scheme
[ (line_comment) (block_comment) (nesting_block_comment) ] @comment (token_string_tokens) @d
e50f630ac7eb2a3f005afa19eb5301c60b55c1f907e21ddb42f860dfe2a1bab7
Cahu/krpc-hs
KerbalAlarmClock.hs
module KRPCHS.KerbalAlarmClock ( AlarmAction(..) , AlarmType(..) , Alarm , alarmWithName , alarmWithNameStream , alarmWithNameStreamReq , alarmRemove , getAlarmAction , getAlarmActionStream , getAlarmActionStreamReq , getAlarmID , getAlarmIDStream , getAlarmIDStreamReq , getAlarmMargin , getAlarmMarginStream , getAlarmMarginStreamReq , getAlarmName , getAlarmNameStream , getAlarmNameStreamReq , getAlarmNotes , getAlarmNotesStream , getAlarmNotesStreamReq , getAlarmRemaining , getAlarmRemainingStream , getAlarmRemainingStreamReq , getAlarmRepeat , getAlarmRepeatStream , getAlarmRepeatStreamReq , getAlarmRepeatPeriod , getAlarmRepeatPeriodStream , getAlarmRepeatPeriodStreamReq , getAlarmTime , getAlarmTimeStream , getAlarmTimeStreamReq , getAlarmType , getAlarmTypeStream , getAlarmTypeStreamReq , getAlarmVessel , getAlarmVesselStream , getAlarmVesselStreamReq , getAlarmXferOriginBody , getAlarmXferOriginBodyStream , getAlarmXferOriginBodyStreamReq , getAlarmXferTargetBody , getAlarmXferTargetBodyStream , getAlarmXferTargetBodyStreamReq , setAlarmAction , setAlarmMargin , setAlarmName , setAlarmNotes , setAlarmRepeat , setAlarmRepeatPeriod , setAlarmTime , setAlarmVessel , setAlarmXferOriginBody , setAlarmXferTargetBody , alarmsWithType , alarmsWithTypeStream , alarmsWithTypeStreamReq , createAlarm , createAlarmStream , createAlarmStreamReq , getAlarms , getAlarmsStream , getAlarmsStreamReq , getAvailable , getAvailableStream , getAvailableStreamReq ) where import qualified Data.Text import qualified KRPCHS.SpaceCenter import KRPCHS.Internal.Requests import KRPCHS.Internal.SerializeUtils - Represents an alarm . Obtained by calling - < see cref="M : . Alarms " / > , - < see cref="M : . AlarmWithName " / > or - < see cref="M : . AlarmsWithType " / > . - Represents an alarm. Obtained by calling - <see cref="M:KerbalAlarmClock.Alarms" />, - <see cref="M:KerbalAlarmClock.AlarmWithName" /> or - <see cref="M:KerbalAlarmClock.AlarmsWithType" />. -} newtype Alarm = Alarm { alarmId :: Int } deriving (Show, Eq, Ord) instance PbSerializable Alarm where encodePb = encodePb . alarmId decodePb b = Alarm <$> decodePb b instance KRPCResponseExtractable Alarm {- - The action performed by an alarm when it fires. -} data AlarmAction = AlarmAction'DoNothing | AlarmAction'DoNothingDeleteWhenPassed | AlarmAction'KillWarp | AlarmAction'KillWarpOnly | AlarmAction'MessageOnly | AlarmAction'PauseGame deriving (Show, Eq, Ord, Enum) instance PbSerializable AlarmAction where encodePb = encodePb . fromEnum decodePb b = toEnum <$> decodePb b instance KRPCResponseExtractable AlarmAction {- - The type of an alarm. -} data AlarmType = AlarmType'Raw | AlarmType'Maneuver | AlarmType'Crew | AlarmType'Distance | AlarmType'EarthTime | AlarmType'LaunchRendevous | AlarmType'SOIChange | AlarmType'SOIChangeAuto | AlarmType'Transfer | AlarmType'TransferModelled | AlarmType'ManeuverAuto | AlarmType'Apoapsis | AlarmType'Periapsis | AlarmType'AscendingNode | AlarmType'DescendingNode | AlarmType'Closest | AlarmType'Contract | AlarmType'ContractAuto deriving (Show, Eq, Ord, Enum) instance PbSerializable AlarmType where encodePb = encodePb . fromEnum decodePb b = toEnum <$> decodePb b instance KRPCResponseExtractable AlarmType - Get the alarm with the given < paramref name="name " / > , ornullif no alarms have that name . If more than one alarm has the name , - only returns one of them.<param name="name">Name of the alarm to search for . - Get the alarm with the given <paramref name="name" />, ornullif no alarms have that name. If more than one alarm has the name, - only returns one of them.<param name="name">Name of the alarm to search for. -} alarmWithName :: Data.Text.Text -> RPCContext (KRPCHS.KerbalAlarmClock.Alarm) alarmWithName nameArg = do let r = makeRequest "KerbalAlarmClock" "AlarmWithName" [makeArgument 0 nameArg] res <- sendRequest r processResponse res alarmWithNameStreamReq :: Data.Text.Text -> KRPCStreamReq (KRPCHS.KerbalAlarmClock.Alarm) alarmWithNameStreamReq nameArg = let req = makeRequest "KerbalAlarmClock" "AlarmWithName" [makeArgument 0 nameArg] in makeStream req alarmWithNameStream :: Data.Text.Text -> RPCContext (KRPCStream (KRPCHS.KerbalAlarmClock.Alarm)) alarmWithNameStream nameArg = requestStream $ alarmWithNameStreamReq nameArg {- - Removes the alarm. -} alarmRemove :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext () alarmRemove thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_Remove" [makeArgument 0 thisArg] res <- sendRequest r processResponse res {- - The action that the alarm triggers. -} getAlarmAction :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.KerbalAlarmClock.AlarmAction) getAlarmAction thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Action" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmActionStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.KerbalAlarmClock.AlarmAction) getAlarmActionStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Action" [makeArgument 0 thisArg] in makeStream req getAlarmActionStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.KerbalAlarmClock.AlarmAction)) getAlarmActionStream thisArg = requestStream $ getAlarmActionStreamReq thisArg {- - The unique identifier for the alarm. -} getAlarmID :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Data.Text.Text) getAlarmID thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_ID" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmIDStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Data.Text.Text) getAlarmIDStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_ID" [makeArgument 0 thisArg] in makeStream req getAlarmIDStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Data.Text.Text)) getAlarmIDStream thisArg = requestStream $ getAlarmIDStreamReq thisArg - The number of seconds before the event that the alarm will fire . - The number of seconds before the event that the alarm will fire. -} getAlarmMargin :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Double) getAlarmMargin thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Margin" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmMarginStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Double) getAlarmMarginStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Margin" [makeArgument 0 thisArg] in makeStream req getAlarmMarginStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Double)) getAlarmMarginStream thisArg = requestStream $ getAlarmMarginStreamReq thisArg {- - The short name of the alarm. -} getAlarmName :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Data.Text.Text) getAlarmName thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Name" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmNameStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Data.Text.Text) getAlarmNameStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Name" [makeArgument 0 thisArg] in makeStream req getAlarmNameStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Data.Text.Text)) getAlarmNameStream thisArg = requestStream $ getAlarmNameStreamReq thisArg {- - The long description of the alarm. -} getAlarmNotes :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Data.Text.Text) getAlarmNotes thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Notes" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmNotesStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Data.Text.Text) getAlarmNotesStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Notes" [makeArgument 0 thisArg] in makeStream req getAlarmNotesStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Data.Text.Text)) getAlarmNotesStream thisArg = requestStream $ getAlarmNotesStreamReq thisArg - The number of seconds until the alarm will fire . - The number of seconds until the alarm will fire. -} getAlarmRemaining :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Double) getAlarmRemaining thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Remaining" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmRemainingStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Double) getAlarmRemainingStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Remaining" [makeArgument 0 thisArg] in makeStream req getAlarmRemainingStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Double)) getAlarmRemainingStream thisArg = requestStream $ getAlarmRemainingStreamReq thisArg {- - Whether the alarm will be repeated after it has fired. -} getAlarmRepeat :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Bool) getAlarmRepeat thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Repeat" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmRepeatStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Bool) getAlarmRepeatStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Repeat" [makeArgument 0 thisArg] in makeStream req getAlarmRepeatStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Bool)) getAlarmRepeatStream thisArg = requestStream $ getAlarmRepeatStreamReq thisArg {- - The time delay to automatically create an alarm after it has fired. -} getAlarmRepeatPeriod :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Double) getAlarmRepeatPeriod thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_RepeatPeriod" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmRepeatPeriodStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Double) getAlarmRepeatPeriodStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_RepeatPeriod" [makeArgument 0 thisArg] in makeStream req getAlarmRepeatPeriodStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Double)) getAlarmRepeatPeriodStream thisArg = requestStream $ getAlarmRepeatPeriodStreamReq thisArg {- - The time at which the alarm will fire. -} getAlarmTime :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Double) getAlarmTime thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Time" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmTimeStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Double) getAlarmTimeStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Time" [makeArgument 0 thisArg] in makeStream req getAlarmTimeStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Double)) getAlarmTimeStream thisArg = requestStream $ getAlarmTimeStreamReq thisArg {- - The type of the alarm. -} getAlarmType :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.KerbalAlarmClock.AlarmType) getAlarmType thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Type" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmTypeStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.KerbalAlarmClock.AlarmType) getAlarmTypeStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Type" [makeArgument 0 thisArg] in makeStream req getAlarmTypeStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.KerbalAlarmClock.AlarmType)) getAlarmTypeStream thisArg = requestStream $ getAlarmTypeStreamReq thisArg {- - The vessel that the alarm is attached to. -} getAlarmVessel :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.SpaceCenter.Vessel) getAlarmVessel thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Vessel" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmVesselStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.SpaceCenter.Vessel) getAlarmVesselStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Vessel" [makeArgument 0 thisArg] in makeStream req getAlarmVesselStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.SpaceCenter.Vessel)) getAlarmVesselStream thisArg = requestStream $ getAlarmVesselStreamReq thisArg {- - The celestial body the vessel is departing from. -} getAlarmXferOriginBody :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.SpaceCenter.CelestialBody) getAlarmXferOriginBody thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_XferOriginBody" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmXferOriginBodyStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.SpaceCenter.CelestialBody) getAlarmXferOriginBodyStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_XferOriginBody" [makeArgument 0 thisArg] in makeStream req getAlarmXferOriginBodyStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.SpaceCenter.CelestialBody)) getAlarmXferOriginBodyStream thisArg = requestStream $ getAlarmXferOriginBodyStreamReq thisArg {- - The celestial body the vessel is arriving at. -} getAlarmXferTargetBody :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.SpaceCenter.CelestialBody) getAlarmXferTargetBody thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_XferTargetBody" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmXferTargetBodyStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.SpaceCenter.CelestialBody) getAlarmXferTargetBodyStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_XferTargetBody" [makeArgument 0 thisArg] in makeStream req getAlarmXferTargetBodyStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.SpaceCenter.CelestialBody)) getAlarmXferTargetBodyStream thisArg = requestStream $ getAlarmXferTargetBodyStreamReq thisArg {- - The action that the alarm triggers. -} setAlarmAction :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCHS.KerbalAlarmClock.AlarmAction -> RPCContext () setAlarmAction thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Action" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res - The number of seconds before the event that the alarm will fire . - The number of seconds before the event that the alarm will fire. -} setAlarmMargin :: KRPCHS.KerbalAlarmClock.Alarm -> Double -> RPCContext () setAlarmMargin thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Margin" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res {- - The short name of the alarm. -} setAlarmName :: KRPCHS.KerbalAlarmClock.Alarm -> Data.Text.Text -> RPCContext () setAlarmName thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Name" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res {- - The long description of the alarm. -} setAlarmNotes :: KRPCHS.KerbalAlarmClock.Alarm -> Data.Text.Text -> RPCContext () setAlarmNotes thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Notes" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res {- - Whether the alarm will be repeated after it has fired. -} setAlarmRepeat :: KRPCHS.KerbalAlarmClock.Alarm -> Bool -> RPCContext () setAlarmRepeat thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Repeat" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res {- - The time delay to automatically create an alarm after it has fired. -} setAlarmRepeatPeriod :: KRPCHS.KerbalAlarmClock.Alarm -> Double -> RPCContext () setAlarmRepeatPeriod thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_RepeatPeriod" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res {- - The time at which the alarm will fire. -} setAlarmTime :: KRPCHS.KerbalAlarmClock.Alarm -> Double -> RPCContext () setAlarmTime thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Time" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res {- - The vessel that the alarm is attached to. -} setAlarmVessel :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCHS.SpaceCenter.Vessel -> RPCContext () setAlarmVessel thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Vessel" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res {- - The celestial body the vessel is departing from. -} setAlarmXferOriginBody :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCHS.SpaceCenter.CelestialBody -> RPCContext () setAlarmXferOriginBody thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_XferOriginBody" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res {- - The celestial body the vessel is arriving at. -} setAlarmXferTargetBody :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCHS.SpaceCenter.CelestialBody -> RPCContext () setAlarmXferTargetBody thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_XferTargetBody" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res - Get a list of alarms of the specified < paramref name="type " />.<param name="type">Type of alarm to return . - Get a list of alarms of the specified <paramref name="type" />.<param name="type">Type of alarm to return. -} alarmsWithType :: KRPCHS.KerbalAlarmClock.AlarmType -> RPCContext ([KRPCHS.KerbalAlarmClock.Alarm]) alarmsWithType typeArg = do let r = makeRequest "KerbalAlarmClock" "AlarmsWithType" [makeArgument 0 typeArg] res <- sendRequest r processResponse res alarmsWithTypeStreamReq :: KRPCHS.KerbalAlarmClock.AlarmType -> KRPCStreamReq ([KRPCHS.KerbalAlarmClock.Alarm]) alarmsWithTypeStreamReq typeArg = let req = makeRequest "KerbalAlarmClock" "AlarmsWithType" [makeArgument 0 typeArg] in makeStream req alarmsWithTypeStream :: KRPCHS.KerbalAlarmClock.AlarmType -> RPCContext (KRPCStream ([KRPCHS.KerbalAlarmClock.Alarm])) alarmsWithTypeStream typeArg = requestStream $ alarmsWithTypeStreamReq typeArg - Create a new alarm and return it.<param name="type">Type of the new alarm.<param name="name">Name of the new alarm.<param name="ut">Time at which the new alarm should trigger . - Create a new alarm and return it.<param name="type">Type of the new alarm.<param name="name">Name of the new alarm.<param name="ut">Time at which the new alarm should trigger. -} createAlarm :: KRPCHS.KerbalAlarmClock.AlarmType -> Data.Text.Text -> Double -> RPCContext (KRPCHS.KerbalAlarmClock.Alarm) createAlarm typeArg nameArg utArg = do let r = makeRequest "KerbalAlarmClock" "CreateAlarm" [makeArgument 0 typeArg, makeArgument 1 nameArg, makeArgument 2 utArg] res <- sendRequest r processResponse res createAlarmStreamReq :: KRPCHS.KerbalAlarmClock.AlarmType -> Data.Text.Text -> Double -> KRPCStreamReq (KRPCHS.KerbalAlarmClock.Alarm) createAlarmStreamReq typeArg nameArg utArg = let req = makeRequest "KerbalAlarmClock" "CreateAlarm" [makeArgument 0 typeArg, makeArgument 1 nameArg, makeArgument 2 utArg] in makeStream req createAlarmStream :: KRPCHS.KerbalAlarmClock.AlarmType -> Data.Text.Text -> Double -> RPCContext (KRPCStream (KRPCHS.KerbalAlarmClock.Alarm)) createAlarmStream typeArg nameArg utArg = requestStream $ createAlarmStreamReq typeArg nameArg utArg {- - A list of all the alarms. -} getAlarms :: RPCContext ([KRPCHS.KerbalAlarmClock.Alarm]) getAlarms = do let r = makeRequest "KerbalAlarmClock" "get_Alarms" [] res <- sendRequest r processResponse res getAlarmsStreamReq :: KRPCStreamReq ([KRPCHS.KerbalAlarmClock.Alarm]) getAlarmsStreamReq = let req = makeRequest "KerbalAlarmClock" "get_Alarms" [] in makeStream req getAlarmsStream :: RPCContext (KRPCStream ([KRPCHS.KerbalAlarmClock.Alarm])) getAlarmsStream = requestStream $ getAlarmsStreamReq - Whether Kerbal Alarm Clock is available . - Whether Kerbal Alarm Clock is available. -} getAvailable :: RPCContext (Bool) getAvailable = do let r = makeRequest "KerbalAlarmClock" "get_Available" [] res <- sendRequest r processResponse res getAvailableStreamReq :: KRPCStreamReq (Bool) getAvailableStreamReq = let req = makeRequest "KerbalAlarmClock" "get_Available" [] in makeStream req getAvailableStream :: RPCContext (KRPCStream (Bool)) getAvailableStream = requestStream $ getAvailableStreamReq
null
https://raw.githubusercontent.com/Cahu/krpc-hs/418f88f2acad8d50dd716d9a3477178332f00806/src/KRPCHS/KerbalAlarmClock.hs
haskell
- The action performed by an alarm when it fires. - The type of an alarm. - Removes the alarm. - The action that the alarm triggers. - The unique identifier for the alarm. - The short name of the alarm. - The long description of the alarm. - Whether the alarm will be repeated after it has fired. - The time delay to automatically create an alarm after it has fired. - The time at which the alarm will fire. - The type of the alarm. - The vessel that the alarm is attached to. - The celestial body the vessel is departing from. - The celestial body the vessel is arriving at. - The action that the alarm triggers. - The short name of the alarm. - The long description of the alarm. - Whether the alarm will be repeated after it has fired. - The time delay to automatically create an alarm after it has fired. - The time at which the alarm will fire. - The vessel that the alarm is attached to. - The celestial body the vessel is departing from. - The celestial body the vessel is arriving at. - A list of all the alarms.
module KRPCHS.KerbalAlarmClock ( AlarmAction(..) , AlarmType(..) , Alarm , alarmWithName , alarmWithNameStream , alarmWithNameStreamReq , alarmRemove , getAlarmAction , getAlarmActionStream , getAlarmActionStreamReq , getAlarmID , getAlarmIDStream , getAlarmIDStreamReq , getAlarmMargin , getAlarmMarginStream , getAlarmMarginStreamReq , getAlarmName , getAlarmNameStream , getAlarmNameStreamReq , getAlarmNotes , getAlarmNotesStream , getAlarmNotesStreamReq , getAlarmRemaining , getAlarmRemainingStream , getAlarmRemainingStreamReq , getAlarmRepeat , getAlarmRepeatStream , getAlarmRepeatStreamReq , getAlarmRepeatPeriod , getAlarmRepeatPeriodStream , getAlarmRepeatPeriodStreamReq , getAlarmTime , getAlarmTimeStream , getAlarmTimeStreamReq , getAlarmType , getAlarmTypeStream , getAlarmTypeStreamReq , getAlarmVessel , getAlarmVesselStream , getAlarmVesselStreamReq , getAlarmXferOriginBody , getAlarmXferOriginBodyStream , getAlarmXferOriginBodyStreamReq , getAlarmXferTargetBody , getAlarmXferTargetBodyStream , getAlarmXferTargetBodyStreamReq , setAlarmAction , setAlarmMargin , setAlarmName , setAlarmNotes , setAlarmRepeat , setAlarmRepeatPeriod , setAlarmTime , setAlarmVessel , setAlarmXferOriginBody , setAlarmXferTargetBody , alarmsWithType , alarmsWithTypeStream , alarmsWithTypeStreamReq , createAlarm , createAlarmStream , createAlarmStreamReq , getAlarms , getAlarmsStream , getAlarmsStreamReq , getAvailable , getAvailableStream , getAvailableStreamReq ) where import qualified Data.Text import qualified KRPCHS.SpaceCenter import KRPCHS.Internal.Requests import KRPCHS.Internal.SerializeUtils - Represents an alarm . Obtained by calling - < see cref="M : . Alarms " / > , - < see cref="M : . AlarmWithName " / > or - < see cref="M : . AlarmsWithType " / > . - Represents an alarm. Obtained by calling - <see cref="M:KerbalAlarmClock.Alarms" />, - <see cref="M:KerbalAlarmClock.AlarmWithName" /> or - <see cref="M:KerbalAlarmClock.AlarmsWithType" />. -} newtype Alarm = Alarm { alarmId :: Int } deriving (Show, Eq, Ord) instance PbSerializable Alarm where encodePb = encodePb . alarmId decodePb b = Alarm <$> decodePb b instance KRPCResponseExtractable Alarm data AlarmAction = AlarmAction'DoNothing | AlarmAction'DoNothingDeleteWhenPassed | AlarmAction'KillWarp | AlarmAction'KillWarpOnly | AlarmAction'MessageOnly | AlarmAction'PauseGame deriving (Show, Eq, Ord, Enum) instance PbSerializable AlarmAction where encodePb = encodePb . fromEnum decodePb b = toEnum <$> decodePb b instance KRPCResponseExtractable AlarmAction data AlarmType = AlarmType'Raw | AlarmType'Maneuver | AlarmType'Crew | AlarmType'Distance | AlarmType'EarthTime | AlarmType'LaunchRendevous | AlarmType'SOIChange | AlarmType'SOIChangeAuto | AlarmType'Transfer | AlarmType'TransferModelled | AlarmType'ManeuverAuto | AlarmType'Apoapsis | AlarmType'Periapsis | AlarmType'AscendingNode | AlarmType'DescendingNode | AlarmType'Closest | AlarmType'Contract | AlarmType'ContractAuto deriving (Show, Eq, Ord, Enum) instance PbSerializable AlarmType where encodePb = encodePb . fromEnum decodePb b = toEnum <$> decodePb b instance KRPCResponseExtractable AlarmType - Get the alarm with the given < paramref name="name " / > , ornullif no alarms have that name . If more than one alarm has the name , - only returns one of them.<param name="name">Name of the alarm to search for . - Get the alarm with the given <paramref name="name" />, ornullif no alarms have that name. If more than one alarm has the name, - only returns one of them.<param name="name">Name of the alarm to search for. -} alarmWithName :: Data.Text.Text -> RPCContext (KRPCHS.KerbalAlarmClock.Alarm) alarmWithName nameArg = do let r = makeRequest "KerbalAlarmClock" "AlarmWithName" [makeArgument 0 nameArg] res <- sendRequest r processResponse res alarmWithNameStreamReq :: Data.Text.Text -> KRPCStreamReq (KRPCHS.KerbalAlarmClock.Alarm) alarmWithNameStreamReq nameArg = let req = makeRequest "KerbalAlarmClock" "AlarmWithName" [makeArgument 0 nameArg] in makeStream req alarmWithNameStream :: Data.Text.Text -> RPCContext (KRPCStream (KRPCHS.KerbalAlarmClock.Alarm)) alarmWithNameStream nameArg = requestStream $ alarmWithNameStreamReq nameArg alarmRemove :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext () alarmRemove thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_Remove" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmAction :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.KerbalAlarmClock.AlarmAction) getAlarmAction thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Action" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmActionStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.KerbalAlarmClock.AlarmAction) getAlarmActionStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Action" [makeArgument 0 thisArg] in makeStream req getAlarmActionStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.KerbalAlarmClock.AlarmAction)) getAlarmActionStream thisArg = requestStream $ getAlarmActionStreamReq thisArg getAlarmID :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Data.Text.Text) getAlarmID thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_ID" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmIDStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Data.Text.Text) getAlarmIDStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_ID" [makeArgument 0 thisArg] in makeStream req getAlarmIDStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Data.Text.Text)) getAlarmIDStream thisArg = requestStream $ getAlarmIDStreamReq thisArg - The number of seconds before the event that the alarm will fire . - The number of seconds before the event that the alarm will fire. -} getAlarmMargin :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Double) getAlarmMargin thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Margin" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmMarginStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Double) getAlarmMarginStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Margin" [makeArgument 0 thisArg] in makeStream req getAlarmMarginStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Double)) getAlarmMarginStream thisArg = requestStream $ getAlarmMarginStreamReq thisArg getAlarmName :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Data.Text.Text) getAlarmName thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Name" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmNameStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Data.Text.Text) getAlarmNameStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Name" [makeArgument 0 thisArg] in makeStream req getAlarmNameStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Data.Text.Text)) getAlarmNameStream thisArg = requestStream $ getAlarmNameStreamReq thisArg getAlarmNotes :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Data.Text.Text) getAlarmNotes thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Notes" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmNotesStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Data.Text.Text) getAlarmNotesStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Notes" [makeArgument 0 thisArg] in makeStream req getAlarmNotesStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Data.Text.Text)) getAlarmNotesStream thisArg = requestStream $ getAlarmNotesStreamReq thisArg - The number of seconds until the alarm will fire . - The number of seconds until the alarm will fire. -} getAlarmRemaining :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Double) getAlarmRemaining thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Remaining" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmRemainingStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Double) getAlarmRemainingStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Remaining" [makeArgument 0 thisArg] in makeStream req getAlarmRemainingStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Double)) getAlarmRemainingStream thisArg = requestStream $ getAlarmRemainingStreamReq thisArg getAlarmRepeat :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Bool) getAlarmRepeat thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Repeat" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmRepeatStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Bool) getAlarmRepeatStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Repeat" [makeArgument 0 thisArg] in makeStream req getAlarmRepeatStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Bool)) getAlarmRepeatStream thisArg = requestStream $ getAlarmRepeatStreamReq thisArg getAlarmRepeatPeriod :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Double) getAlarmRepeatPeriod thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_RepeatPeriod" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmRepeatPeriodStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Double) getAlarmRepeatPeriodStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_RepeatPeriod" [makeArgument 0 thisArg] in makeStream req getAlarmRepeatPeriodStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Double)) getAlarmRepeatPeriodStream thisArg = requestStream $ getAlarmRepeatPeriodStreamReq thisArg getAlarmTime :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (Double) getAlarmTime thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Time" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmTimeStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (Double) getAlarmTimeStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Time" [makeArgument 0 thisArg] in makeStream req getAlarmTimeStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (Double)) getAlarmTimeStream thisArg = requestStream $ getAlarmTimeStreamReq thisArg getAlarmType :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.KerbalAlarmClock.AlarmType) getAlarmType thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Type" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmTypeStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.KerbalAlarmClock.AlarmType) getAlarmTypeStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Type" [makeArgument 0 thisArg] in makeStream req getAlarmTypeStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.KerbalAlarmClock.AlarmType)) getAlarmTypeStream thisArg = requestStream $ getAlarmTypeStreamReq thisArg getAlarmVessel :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.SpaceCenter.Vessel) getAlarmVessel thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_Vessel" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmVesselStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.SpaceCenter.Vessel) getAlarmVesselStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_Vessel" [makeArgument 0 thisArg] in makeStream req getAlarmVesselStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.SpaceCenter.Vessel)) getAlarmVesselStream thisArg = requestStream $ getAlarmVesselStreamReq thisArg getAlarmXferOriginBody :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.SpaceCenter.CelestialBody) getAlarmXferOriginBody thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_XferOriginBody" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmXferOriginBodyStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.SpaceCenter.CelestialBody) getAlarmXferOriginBodyStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_XferOriginBody" [makeArgument 0 thisArg] in makeStream req getAlarmXferOriginBodyStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.SpaceCenter.CelestialBody)) getAlarmXferOriginBodyStream thisArg = requestStream $ getAlarmXferOriginBodyStreamReq thisArg getAlarmXferTargetBody :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCHS.SpaceCenter.CelestialBody) getAlarmXferTargetBody thisArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_get_XferTargetBody" [makeArgument 0 thisArg] res <- sendRequest r processResponse res getAlarmXferTargetBodyStreamReq :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCStreamReq (KRPCHS.SpaceCenter.CelestialBody) getAlarmXferTargetBodyStreamReq thisArg = let req = makeRequest "KerbalAlarmClock" "Alarm_get_XferTargetBody" [makeArgument 0 thisArg] in makeStream req getAlarmXferTargetBodyStream :: KRPCHS.KerbalAlarmClock.Alarm -> RPCContext (KRPCStream (KRPCHS.SpaceCenter.CelestialBody)) getAlarmXferTargetBodyStream thisArg = requestStream $ getAlarmXferTargetBodyStreamReq thisArg setAlarmAction :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCHS.KerbalAlarmClock.AlarmAction -> RPCContext () setAlarmAction thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Action" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res - The number of seconds before the event that the alarm will fire . - The number of seconds before the event that the alarm will fire. -} setAlarmMargin :: KRPCHS.KerbalAlarmClock.Alarm -> Double -> RPCContext () setAlarmMargin thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Margin" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res setAlarmName :: KRPCHS.KerbalAlarmClock.Alarm -> Data.Text.Text -> RPCContext () setAlarmName thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Name" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res setAlarmNotes :: KRPCHS.KerbalAlarmClock.Alarm -> Data.Text.Text -> RPCContext () setAlarmNotes thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Notes" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res setAlarmRepeat :: KRPCHS.KerbalAlarmClock.Alarm -> Bool -> RPCContext () setAlarmRepeat thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Repeat" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res setAlarmRepeatPeriod :: KRPCHS.KerbalAlarmClock.Alarm -> Double -> RPCContext () setAlarmRepeatPeriod thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_RepeatPeriod" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res setAlarmTime :: KRPCHS.KerbalAlarmClock.Alarm -> Double -> RPCContext () setAlarmTime thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Time" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res setAlarmVessel :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCHS.SpaceCenter.Vessel -> RPCContext () setAlarmVessel thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_Vessel" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res setAlarmXferOriginBody :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCHS.SpaceCenter.CelestialBody -> RPCContext () setAlarmXferOriginBody thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_XferOriginBody" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res setAlarmXferTargetBody :: KRPCHS.KerbalAlarmClock.Alarm -> KRPCHS.SpaceCenter.CelestialBody -> RPCContext () setAlarmXferTargetBody thisArg valueArg = do let r = makeRequest "KerbalAlarmClock" "Alarm_set_XferTargetBody" [makeArgument 0 thisArg, makeArgument 1 valueArg] res <- sendRequest r processResponse res - Get a list of alarms of the specified < paramref name="type " />.<param name="type">Type of alarm to return . - Get a list of alarms of the specified <paramref name="type" />.<param name="type">Type of alarm to return. -} alarmsWithType :: KRPCHS.KerbalAlarmClock.AlarmType -> RPCContext ([KRPCHS.KerbalAlarmClock.Alarm]) alarmsWithType typeArg = do let r = makeRequest "KerbalAlarmClock" "AlarmsWithType" [makeArgument 0 typeArg] res <- sendRequest r processResponse res alarmsWithTypeStreamReq :: KRPCHS.KerbalAlarmClock.AlarmType -> KRPCStreamReq ([KRPCHS.KerbalAlarmClock.Alarm]) alarmsWithTypeStreamReq typeArg = let req = makeRequest "KerbalAlarmClock" "AlarmsWithType" [makeArgument 0 typeArg] in makeStream req alarmsWithTypeStream :: KRPCHS.KerbalAlarmClock.AlarmType -> RPCContext (KRPCStream ([KRPCHS.KerbalAlarmClock.Alarm])) alarmsWithTypeStream typeArg = requestStream $ alarmsWithTypeStreamReq typeArg - Create a new alarm and return it.<param name="type">Type of the new alarm.<param name="name">Name of the new alarm.<param name="ut">Time at which the new alarm should trigger . - Create a new alarm and return it.<param name="type">Type of the new alarm.<param name="name">Name of the new alarm.<param name="ut">Time at which the new alarm should trigger. -} createAlarm :: KRPCHS.KerbalAlarmClock.AlarmType -> Data.Text.Text -> Double -> RPCContext (KRPCHS.KerbalAlarmClock.Alarm) createAlarm typeArg nameArg utArg = do let r = makeRequest "KerbalAlarmClock" "CreateAlarm" [makeArgument 0 typeArg, makeArgument 1 nameArg, makeArgument 2 utArg] res <- sendRequest r processResponse res createAlarmStreamReq :: KRPCHS.KerbalAlarmClock.AlarmType -> Data.Text.Text -> Double -> KRPCStreamReq (KRPCHS.KerbalAlarmClock.Alarm) createAlarmStreamReq typeArg nameArg utArg = let req = makeRequest "KerbalAlarmClock" "CreateAlarm" [makeArgument 0 typeArg, makeArgument 1 nameArg, makeArgument 2 utArg] in makeStream req createAlarmStream :: KRPCHS.KerbalAlarmClock.AlarmType -> Data.Text.Text -> Double -> RPCContext (KRPCStream (KRPCHS.KerbalAlarmClock.Alarm)) createAlarmStream typeArg nameArg utArg = requestStream $ createAlarmStreamReq typeArg nameArg utArg getAlarms :: RPCContext ([KRPCHS.KerbalAlarmClock.Alarm]) getAlarms = do let r = makeRequest "KerbalAlarmClock" "get_Alarms" [] res <- sendRequest r processResponse res getAlarmsStreamReq :: KRPCStreamReq ([KRPCHS.KerbalAlarmClock.Alarm]) getAlarmsStreamReq = let req = makeRequest "KerbalAlarmClock" "get_Alarms" [] in makeStream req getAlarmsStream :: RPCContext (KRPCStream ([KRPCHS.KerbalAlarmClock.Alarm])) getAlarmsStream = requestStream $ getAlarmsStreamReq - Whether Kerbal Alarm Clock is available . - Whether Kerbal Alarm Clock is available. -} getAvailable :: RPCContext (Bool) getAvailable = do let r = makeRequest "KerbalAlarmClock" "get_Available" [] res <- sendRequest r processResponse res getAvailableStreamReq :: KRPCStreamReq (Bool) getAvailableStreamReq = let req = makeRequest "KerbalAlarmClock" "get_Available" [] in makeStream req getAvailableStream :: RPCContext (KRPCStream (Bool)) getAvailableStream = requestStream $ getAvailableStreamReq
ce238055a77324f6d2b209d49463264b79d0c2be3ccbde591fa43f67765de28e
LaurentMazare/ocaml-torch
predict.ml
Evaluation using a pre - trained ResNet model . The pre - trained weight file can be found at : -torch/releases/download/v0.1-unstable/resnet18.ot -torch/releases/download/v0.1-unstable/resnet34.ot -torch/releases/download/v0.1-unstable/densenet121.ot -torch/releases/download/v0.1-unstable/vgg13.ot -torch/releases/download/v0.1-unstable/vgg16.ot -torch/releases/download/v0.1-unstable/vgg19.ot -torch/releases/download/v0.1-unstable/squeezenet1_0.ot -torch/releases/download/v0.1-unstable/squeezenet1_1.ot -torch/releases/download/v0.1-unstable/alexnet.ot -torch/releases/download/v0.1-unstable/inception-v3.ot -torch/releases/download/v0.1-unstable/mobilenet-v2.ot -torch/releases/download/v0.1-unstable/efficientnet-b0.ot -torch/releases/download/v0.1-unstable/efficientnet-b1.ot -torch/releases/download/v0.1-unstable/efficientnet-b2.ot -torch/releases/download/v0.1-unstable/efficientnet-b3.ot -torch/releases/download/v0.1-unstable/efficientnet-b4.ot The pre-trained weight file can be found at: -torch/releases/download/v0.1-unstable/resnet18.ot -torch/releases/download/v0.1-unstable/resnet34.ot -torch/releases/download/v0.1-unstable/densenet121.ot -torch/releases/download/v0.1-unstable/vgg13.ot -torch/releases/download/v0.1-unstable/vgg16.ot -torch/releases/download/v0.1-unstable/vgg19.ot -torch/releases/download/v0.1-unstable/squeezenet1_0.ot -torch/releases/download/v0.1-unstable/squeezenet1_1.ot -torch/releases/download/v0.1-unstable/alexnet.ot -torch/releases/download/v0.1-unstable/inception-v3.ot -torch/releases/download/v0.1-unstable/mobilenet-v2.ot -torch/releases/download/v0.1-unstable/efficientnet-b0.ot -torch/releases/download/v0.1-unstable/efficientnet-b1.ot -torch/releases/download/v0.1-unstable/efficientnet-b2.ot -torch/releases/download/v0.1-unstable/efficientnet-b3.ot -torch/releases/download/v0.1-unstable/efficientnet-b4.ot *) open Base open Torch open Torch_vision let () = let module Sys = Caml.Sys in if Array.length Sys.argv <> 3 then Printf.failwithf "usage: %s resnet18.ot input.png" Sys.argv.(0) (); let image = Imagenet.load_image Sys.argv.(2) in let vs = Var_store.create ~name:"rn" ~device:Cpu () in let model = match Caml.Filename.basename Sys.argv.(1) with | "vgg11.ot" -> Vgg.vgg11 vs ~num_classes:1000 | "vgg13.ot" -> Vgg.vgg13 vs ~num_classes:1000 | "vgg16.ot" -> Vgg.vgg16 vs ~num_classes:1000 | "vgg19.ot" -> Vgg.vgg19 vs ~num_classes:1000 | "squeezenet1_0.ot" -> Squeezenet.squeezenet1_0 vs ~num_classes:1000 | "squeezenet1_1.ot" -> Squeezenet.squeezenet1_1 vs ~num_classes:1000 | "densenet121.ot" -> Densenet.densenet121 vs ~num_classes:1000 | "densenet161.ot" -> Densenet.densenet161 vs ~num_classes:1000 | "densenet169.ot" -> Densenet.densenet169 vs ~num_classes:1000 | "resnet34.ot" -> Resnet.resnet34 vs ~num_classes:1000 | "resnet50.ot" -> Resnet.resnet50 vs ~num_classes:1000 | "resnet101.ot" -> Resnet.resnet101 vs ~num_classes:1000 | "resnet152.ot" -> Resnet.resnet152 vs ~num_classes:1000 | "resnet18.ot" -> Resnet.resnet18 vs ~num_classes:1000 | "mobilenet-v2.ot" -> Mobilenet.v2 vs ~num_classes:1000 | "alexnet.ot" -> Alexnet.alexnet vs ~num_classes:1000 | "inception-v3.ot" -> Inception.v3 vs ~num_classes:1000 | "efficientnet-b0.ot" -> Efficientnet.b0 vs ~num_classes:1000 | "efficientnet-b1.ot" -> Efficientnet.b1 vs ~num_classes:1000 | "efficientnet-b2.ot" -> Efficientnet.b2 vs ~num_classes:1000 | "efficientnet-b3.ot" -> Efficientnet.b3 vs ~num_classes:1000 | "efficientnet-b4.ot" -> Efficientnet.b4 vs ~num_classes:1000 | "efficientnet-b5.ot" -> Efficientnet.b5 vs ~num_classes:1000 | "efficientnet-b6.ot" -> Efficientnet.b6 vs ~num_classes:1000 | "efficientnet-b7.ot" -> Efficientnet.b7 vs ~num_classes:1000 | otherwise -> Printf.failwithf "unsupported model %s, try with resnet18.ot" otherwise () in Stdio.printf "Loading weights from %s\n%!" Sys.argv.(1); Serialize.load_multi_ ~named_tensors:(Var_store.all_vars vs) ~filename:Sys.argv.(1); let probabilities = Layer.forward_ model image ~is_training:false |> Tensor.softmax ~dim:(-1) ~dtype:(T Float) in Imagenet.Classes.top probabilities ~k:5 |> List.iter ~f:(fun (name, probability) -> Stdio.printf "%s: %.2f%%\n%!" name (100. *. probability))
null
https://raw.githubusercontent.com/LaurentMazare/ocaml-torch/a82b906a22c7c23138af16fab497a08e5167d249/examples/pretrained/predict.ml
ocaml
Evaluation using a pre - trained ResNet model . The pre - trained weight file can be found at : -torch/releases/download/v0.1-unstable/resnet18.ot -torch/releases/download/v0.1-unstable/resnet34.ot -torch/releases/download/v0.1-unstable/densenet121.ot -torch/releases/download/v0.1-unstable/vgg13.ot -torch/releases/download/v0.1-unstable/vgg16.ot -torch/releases/download/v0.1-unstable/vgg19.ot -torch/releases/download/v0.1-unstable/squeezenet1_0.ot -torch/releases/download/v0.1-unstable/squeezenet1_1.ot -torch/releases/download/v0.1-unstable/alexnet.ot -torch/releases/download/v0.1-unstable/inception-v3.ot -torch/releases/download/v0.1-unstable/mobilenet-v2.ot -torch/releases/download/v0.1-unstable/efficientnet-b0.ot -torch/releases/download/v0.1-unstable/efficientnet-b1.ot -torch/releases/download/v0.1-unstable/efficientnet-b2.ot -torch/releases/download/v0.1-unstable/efficientnet-b3.ot -torch/releases/download/v0.1-unstable/efficientnet-b4.ot The pre-trained weight file can be found at: -torch/releases/download/v0.1-unstable/resnet18.ot -torch/releases/download/v0.1-unstable/resnet34.ot -torch/releases/download/v0.1-unstable/densenet121.ot -torch/releases/download/v0.1-unstable/vgg13.ot -torch/releases/download/v0.1-unstable/vgg16.ot -torch/releases/download/v0.1-unstable/vgg19.ot -torch/releases/download/v0.1-unstable/squeezenet1_0.ot -torch/releases/download/v0.1-unstable/squeezenet1_1.ot -torch/releases/download/v0.1-unstable/alexnet.ot -torch/releases/download/v0.1-unstable/inception-v3.ot -torch/releases/download/v0.1-unstable/mobilenet-v2.ot -torch/releases/download/v0.1-unstable/efficientnet-b0.ot -torch/releases/download/v0.1-unstable/efficientnet-b1.ot -torch/releases/download/v0.1-unstable/efficientnet-b2.ot -torch/releases/download/v0.1-unstable/efficientnet-b3.ot -torch/releases/download/v0.1-unstable/efficientnet-b4.ot *) open Base open Torch open Torch_vision let () = let module Sys = Caml.Sys in if Array.length Sys.argv <> 3 then Printf.failwithf "usage: %s resnet18.ot input.png" Sys.argv.(0) (); let image = Imagenet.load_image Sys.argv.(2) in let vs = Var_store.create ~name:"rn" ~device:Cpu () in let model = match Caml.Filename.basename Sys.argv.(1) with | "vgg11.ot" -> Vgg.vgg11 vs ~num_classes:1000 | "vgg13.ot" -> Vgg.vgg13 vs ~num_classes:1000 | "vgg16.ot" -> Vgg.vgg16 vs ~num_classes:1000 | "vgg19.ot" -> Vgg.vgg19 vs ~num_classes:1000 | "squeezenet1_0.ot" -> Squeezenet.squeezenet1_0 vs ~num_classes:1000 | "squeezenet1_1.ot" -> Squeezenet.squeezenet1_1 vs ~num_classes:1000 | "densenet121.ot" -> Densenet.densenet121 vs ~num_classes:1000 | "densenet161.ot" -> Densenet.densenet161 vs ~num_classes:1000 | "densenet169.ot" -> Densenet.densenet169 vs ~num_classes:1000 | "resnet34.ot" -> Resnet.resnet34 vs ~num_classes:1000 | "resnet50.ot" -> Resnet.resnet50 vs ~num_classes:1000 | "resnet101.ot" -> Resnet.resnet101 vs ~num_classes:1000 | "resnet152.ot" -> Resnet.resnet152 vs ~num_classes:1000 | "resnet18.ot" -> Resnet.resnet18 vs ~num_classes:1000 | "mobilenet-v2.ot" -> Mobilenet.v2 vs ~num_classes:1000 | "alexnet.ot" -> Alexnet.alexnet vs ~num_classes:1000 | "inception-v3.ot" -> Inception.v3 vs ~num_classes:1000 | "efficientnet-b0.ot" -> Efficientnet.b0 vs ~num_classes:1000 | "efficientnet-b1.ot" -> Efficientnet.b1 vs ~num_classes:1000 | "efficientnet-b2.ot" -> Efficientnet.b2 vs ~num_classes:1000 | "efficientnet-b3.ot" -> Efficientnet.b3 vs ~num_classes:1000 | "efficientnet-b4.ot" -> Efficientnet.b4 vs ~num_classes:1000 | "efficientnet-b5.ot" -> Efficientnet.b5 vs ~num_classes:1000 | "efficientnet-b6.ot" -> Efficientnet.b6 vs ~num_classes:1000 | "efficientnet-b7.ot" -> Efficientnet.b7 vs ~num_classes:1000 | otherwise -> Printf.failwithf "unsupported model %s, try with resnet18.ot" otherwise () in Stdio.printf "Loading weights from %s\n%!" Sys.argv.(1); Serialize.load_multi_ ~named_tensors:(Var_store.all_vars vs) ~filename:Sys.argv.(1); let probabilities = Layer.forward_ model image ~is_training:false |> Tensor.softmax ~dim:(-1) ~dtype:(T Float) in Imagenet.Classes.top probabilities ~k:5 |> List.iter ~f:(fun (name, probability) -> Stdio.printf "%s: %.2f%%\n%!" name (100. *. probability))
faeafba2472ba87524b703da4fe7a9b86bd88da91766bd132e7369c76576c675
shayne-fletcher/zen
test_dot.ml
module Dotfile = struct let open_write (name : string) (buf : string) : unit= let ch = open_out name in output ch buf 0 (String.length buf) ; close_out ch let image_of_dotfile (dotfile : string) = let pid = Unix.create_process "dot.exe" [|"dot.exe"; "-Tpng"; "-O"; dotfile|] Unix.stdin Unix.stdout Unix.stderr in let _ = Unix.waitpid [] pid in () let render_dotfile (dotfile : string) : unit = let _ = Unix.create_process "dotty.exe" [|"dotty.exe"; dotfile|] Unix.stdin Unix.stdout Unix.stderr in () end open Gt open Dotfile module G : Directed_graph.S with type node = Char.t = Directed_graph.Make (Char) let g : G.t = G.of_adjacency [ 'a', ['b'] ; 'b', ['e'; 'f'; 'c'] ; 'c', ['d'; 'g'] ; 'd', ['c'; 'h'] ; 'e', ['a'; 'f'] ; 'f', ['g'] ; 'g', ['f'; 'h'] ; 'h', ['h'] ; ] let s = Filename.temp_file "" ".dot" let () = open_write s (G.to_dot_digraph (fun (c : char) -> Bytes.to_string (Bytes.make 1 c)) g); render_dotfile s
null
https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/gt/test_dot.ml
ocaml
module Dotfile = struct let open_write (name : string) (buf : string) : unit= let ch = open_out name in output ch buf 0 (String.length buf) ; close_out ch let image_of_dotfile (dotfile : string) = let pid = Unix.create_process "dot.exe" [|"dot.exe"; "-Tpng"; "-O"; dotfile|] Unix.stdin Unix.stdout Unix.stderr in let _ = Unix.waitpid [] pid in () let render_dotfile (dotfile : string) : unit = let _ = Unix.create_process "dotty.exe" [|"dotty.exe"; dotfile|] Unix.stdin Unix.stdout Unix.stderr in () end open Gt open Dotfile module G : Directed_graph.S with type node = Char.t = Directed_graph.Make (Char) let g : G.t = G.of_adjacency [ 'a', ['b'] ; 'b', ['e'; 'f'; 'c'] ; 'c', ['d'; 'g'] ; 'd', ['c'; 'h'] ; 'e', ['a'; 'f'] ; 'f', ['g'] ; 'g', ['f'; 'h'] ; 'h', ['h'] ; ] let s = Filename.temp_file "" ".dot" let () = open_write s (G.to_dot_digraph (fun (c : char) -> Bytes.to_string (Bytes.make 1 c)) g); render_dotfile s
622e01fa37331b56a16744e60bfff022f735f941c043f4db081368d1dafa741c
ucsd-progsys/liquidhaskell
Ple1.hs
{-@ LIQUID "--expect-any-error" @-} -- this tests reflection + PLE + holes {-@ LIQUID "--reflection" @-} {-@ LIQUID "--ple" @-} module Ple1 where import Ple1Lib @ check : : _ - > { adder 10 20 = = 300 } @ check () = ()
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/measure/neg/Ple1.hs
haskell
@ LIQUID "--expect-any-error" @ this tests reflection + PLE + holes @ LIQUID "--reflection" @ @ LIQUID "--ple" @
module Ple1 where import Ple1Lib @ check : : _ - > { adder 10 20 = = 300 } @ check () = ()
8ffe4c6acd82432be5da0d29f8da6a447ebb8c31db7335bce88d1e84ded5e638
greghendershott/frog
params.rkt
#lang racket/base (require racket/match "./util.rkt") (provide (all-defined-out)) (module+ test (require rackunit)) (define current-scheme/host (make-parameter "")) (define current-uri-prefix (make-parameter #f (λ (v) (and v (match (regexp-replace #px"/+$" v "") ["" #f] [v v]))))) (define current-title (make-parameter "Untitled Site")) (define current-author (make-parameter "The Unknown Author")) (define current-editor (make-parameter "$EDITOR")) (define current-editor-command (make-parameter "{editor} {filename}")) (define current-permalink (make-parameter "/{year}/{month}/{title}.html")) (define current-index-full? (make-parameter #f)) ;index pages: full posts? (define current-feed-full? (make-parameter #f)) ;feeds: full posts? (define current-show-tag-counts? (make-parameter #t)) (define current-max-feed-items (make-parameter 999)) (define current-decorate-feed-uris? (make-parameter #t)) (define current-feed-image-bugs? (make-parameter #f)) (define current-posts-per-page (make-parameter 10)) (define current-index-newest-first? (make-parameter #t)) (define current-posts-index-uri (make-parameter "/index.html")) (define current-source-dir (make-parameter "_src")) (define current-output-dir (make-parameter ".")) (define current-watch-rate (make-parameter 5)) (define current-rebuild? (make-parameter (λ (path change-type) (cond [(not (member (path-get-extension path) '(#".html" #".txt" #".xml"))) (display #"\007") ; beep (hopefully) #t] [else #f]))))
null
https://raw.githubusercontent.com/greghendershott/frog/93d8b442c2e619334612b7e2d091e4eb33995021/frog/private/params.rkt
racket
index pages: full posts? feeds: full posts? beep (hopefully)
#lang racket/base (require racket/match "./util.rkt") (provide (all-defined-out)) (module+ test (require rackunit)) (define current-scheme/host (make-parameter "")) (define current-uri-prefix (make-parameter #f (λ (v) (and v (match (regexp-replace #px"/+$" v "") ["" #f] [v v]))))) (define current-title (make-parameter "Untitled Site")) (define current-author (make-parameter "The Unknown Author")) (define current-editor (make-parameter "$EDITOR")) (define current-editor-command (make-parameter "{editor} {filename}")) (define current-permalink (make-parameter "/{year}/{month}/{title}.html")) (define current-show-tag-counts? (make-parameter #t)) (define current-max-feed-items (make-parameter 999)) (define current-decorate-feed-uris? (make-parameter #t)) (define current-feed-image-bugs? (make-parameter #f)) (define current-posts-per-page (make-parameter 10)) (define current-index-newest-first? (make-parameter #t)) (define current-posts-index-uri (make-parameter "/index.html")) (define current-source-dir (make-parameter "_src")) (define current-output-dir (make-parameter ".")) (define current-watch-rate (make-parameter 5)) (define current-rebuild? (make-parameter (λ (path change-type) (cond [(not (member (path-get-extension path) '(#".html" #".txt" #".xml"))) #t] [else #f]))))
113cd76fd81233f9aecab2ca8871cd1c8b091990961fef8e178b4baf86c144d0
facebookarchive/duckling_old
measure.clj
( ;; Distance ;; NEED TO PUSH THE NORMALIZATION IN THE HELPER + CREATE Function to combine distance " two distance tokens in a row " [ ( dim : distance # ( not (: latent % ) ) ) ( dim : distance # ( not (: latent % ) ) ) ] ; sequence of two tokens with a distance dimension ( combine - distance % 1 % 2 ) ; same thing , with " and " in between like " 3 feets and 2 inches " " two distance tokens separated by and " [ ( dim : distance # ( not (: latent % ) ) ) # " ( ? i)and " ( dim : distance # ( not (: latent % ) ) ) ] ; sequence of two tokens with a time fn ( combine - distance % 1 % 3 ) ; latent distance "number as distance" (dim :number) {:dim :distance :latent true :value (:value %1)} "half" #"반" {:dim :distance :latent true :value 0.5 } "<latent dist> km" [(dim :distance) #"(?i)km|(킬|키)로((미|메)터)?"] (-> %1 (dissoc :latent) (merge {:unit "kilometre" :normalized {:value (* 1000 (-> %1 :value)) :unit "metre"}})) "<latent dist> feet" [(dim :distance) #"(?i)('|f(oo|ee)?ts?)|피트"] (-> %1 (dissoc :latent) (merge {:unit "foot" :normalized {:value (* 0.3048 (-> %1 :value)) :unit "metre"}})) "<latent dist> inch" [(dim :distance) #"(?i)(''|inch(es)?)|인치"] (-> %1 (dissoc :latent) (merge {:unit "inch" :normalized {:value (* 0.0254 (-> %1 :value)) :unit "metre"}})) ;;temporary hack "<latent dist> feet and <latent dist> inch " [(dim :distance) #"(?i)('|f(oo|ee)?ts?)|피트" (dim :distance) #"(?i)(''|inch(es)?)|인치"] (-> %1 (dissoc :latent) (merge {:unit "foot" :normalized {:value (+ (* 0.3048 (-> %1 :value)) (* 0.0254 (-> %3 :value))) :unit "metre"}})) "<latent dist> yard" [(dim :distance) #"(?i)y(ar)?ds?|야드"] (-> %1 (dissoc :latent) (merge {:unit "yard" :normalized {:value (* 0.9144 (-> %1 :value)) :unit "metre"}})) "<dist> meters" [(dim :distance) #"(?i)m|(미|메|매)터"] (-> %1 (dissoc :latent) (merge {:unit "metre"})) "<dist> centimeters" [(dim :distance) #"(?i)cm|센(티|치)((미|메)터)?"] (-> %1 (dissoc :latent) (merge {:unit "centimetre" :normalized {:value (* 0.01 (-> %1 :value)) :unit "metre"}})) "<dist> miles" [(dim :distance) #"(?i)miles?|마일즈?"] (-> %1 (dissoc :latent) (merge {:unit "mile" :normalized {:value (* 1609 (-> %1 :value)) :unit "metre"}})) ;; volume ; latent volume "number as volume" (dim :number) {:dim :volume :latent true :value (:value %1)} "<latent vol> ml" [(dim :volume) #"(?i)ml|(밀|미)리리터"] (-> %1 (dissoc :latent) (merge {:unit "millilitre" :normalized {:value (* 0.001 (-> %1 :value)) :unit "litre"}})) "<vol> hectoliters" [(dim :volume) #"(핵|헥)토리터"] (-> %1 (dissoc :latent) (merge {:unit "hectolitre" :normalized {:value (* 100 (-> %1 :value)) :unit "litre"}})) "<vol> liters" [(dim :volume) #"(?i)l|리터"] (-> %1 (dissoc :latent) (merge {:unit "litre"})) "<latent vol> gallon" [(dim :volume) #"(?i)gal(l?ons?)?|갤(런|론)"] (-> %1 (dissoc :latent) (merge {:unit "gallon" :normalized {:value (* 3.785 (-> %1 :value)) :unit "litre"}})) ;; Quantity ; quantity token inherits metadata from product three teaspoons "<number> <units>" [(dim :number) (dim :leven-unit)] {:dim :quantity :value (:value %1) :unit (:value %2) :form :no-product} 3 pounds of flour - 3파운드의 밀가루 "<quantity> of product" [(dim :quantity #(= :no-product (:form %))) #"의" (dim :leven-product)] (-> %1 (assoc :product (:value %3)) (dissoc :form)) 3 pounds of flour - 밀가루 3파운드 "<quantity> of product" [(dim :leven-product) (dim :quantity #(= :no-product (:form %)))] (-> %2 (assoc :product (:value %1)) (dissoc :form)) ; units ; "pounds" #"파운(드|즈)" {:dim :leven-unit :value "pound"} "gram" #"그(램|람)" {:dim :leven-unit :value "그램"} "근" #"근" {:dim :leven-unit :value "근"} "개" #"개" {:dim :leven-unit :value "개"} "cup - 컵" #"컵" {:dim :leven-unit :value "cup"} "Bowl - 그릇" #"그릇" {:dim :leven-unit :value "bowl"} "dish - 접시" #"그릇" {:dim :leven-unit :value "dish"} "판 - a pizza => 피자한판" #"판" {:dim :leven-unit :value "판"} ; products "삼겹살" #"삼겹살" {:dim :leven-product :value "삼겹살"} ; coke "콜라" #"콜라" {:dim :leven-product :value "콜라"} )
null
https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/ko/rules/measure.clj
clojure
Distance NEED TO PUSH THE NORMALIZATION IN THE HELPER + CREATE Function to combine distance sequence of two tokens with a distance dimension same thing , with " and " in between like " 3 feets and 2 inches " sequence of two tokens with a time fn latent distance temporary hack volume latent volume Quantity quantity token inherits metadata from product units products coke
( " two distance tokens in a row " ( combine - distance % 1 % 2 ) " two distance tokens separated by and " ( combine - distance % 1 % 3 ) "number as distance" (dim :number) {:dim :distance :latent true :value (:value %1)} "half" #"반" {:dim :distance :latent true :value 0.5 } "<latent dist> km" [(dim :distance) #"(?i)km|(킬|키)로((미|메)터)?"] (-> %1 (dissoc :latent) (merge {:unit "kilometre" :normalized {:value (* 1000 (-> %1 :value)) :unit "metre"}})) "<latent dist> feet" [(dim :distance) #"(?i)('|f(oo|ee)?ts?)|피트"] (-> %1 (dissoc :latent) (merge {:unit "foot" :normalized {:value (* 0.3048 (-> %1 :value)) :unit "metre"}})) "<latent dist> inch" [(dim :distance) #"(?i)(''|inch(es)?)|인치"] (-> %1 (dissoc :latent) (merge {:unit "inch" :normalized {:value (* 0.0254 (-> %1 :value)) :unit "metre"}})) "<latent dist> feet and <latent dist> inch " [(dim :distance) #"(?i)('|f(oo|ee)?ts?)|피트" (dim :distance) #"(?i)(''|inch(es)?)|인치"] (-> %1 (dissoc :latent) (merge {:unit "foot" :normalized {:value (+ (* 0.3048 (-> %1 :value)) (* 0.0254 (-> %3 :value))) :unit "metre"}})) "<latent dist> yard" [(dim :distance) #"(?i)y(ar)?ds?|야드"] (-> %1 (dissoc :latent) (merge {:unit "yard" :normalized {:value (* 0.9144 (-> %1 :value)) :unit "metre"}})) "<dist> meters" [(dim :distance) #"(?i)m|(미|메|매)터"] (-> %1 (dissoc :latent) (merge {:unit "metre"})) "<dist> centimeters" [(dim :distance) #"(?i)cm|센(티|치)((미|메)터)?"] (-> %1 (dissoc :latent) (merge {:unit "centimetre" :normalized {:value (* 0.01 (-> %1 :value)) :unit "metre"}})) "<dist> miles" [(dim :distance) #"(?i)miles?|마일즈?"] (-> %1 (dissoc :latent) (merge {:unit "mile" :normalized {:value (* 1609 (-> %1 :value)) :unit "metre"}})) "number as volume" (dim :number) {:dim :volume :latent true :value (:value %1)} "<latent vol> ml" [(dim :volume) #"(?i)ml|(밀|미)리리터"] (-> %1 (dissoc :latent) (merge {:unit "millilitre" :normalized {:value (* 0.001 (-> %1 :value)) :unit "litre"}})) "<vol> hectoliters" [(dim :volume) #"(핵|헥)토리터"] (-> %1 (dissoc :latent) (merge {:unit "hectolitre" :normalized {:value (* 100 (-> %1 :value)) :unit "litre"}})) "<vol> liters" [(dim :volume) #"(?i)l|리터"] (-> %1 (dissoc :latent) (merge {:unit "litre"})) "<latent vol> gallon" [(dim :volume) #"(?i)gal(l?ons?)?|갤(런|론)"] (-> %1 (dissoc :latent) (merge {:unit "gallon" :normalized {:value (* 3.785 (-> %1 :value)) :unit "litre"}})) three teaspoons "<number> <units>" [(dim :number) (dim :leven-unit)] {:dim :quantity :value (:value %1) :unit (:value %2) :form :no-product} 3 pounds of flour - 3파운드의 밀가루 "<quantity> of product" [(dim :quantity #(= :no-product (:form %))) #"의" (dim :leven-product)] (-> %1 (assoc :product (:value %3)) (dissoc :form)) 3 pounds of flour - 밀가루 3파운드 "<quantity> of product" [(dim :leven-product) (dim :quantity #(= :no-product (:form %)))] (-> %2 (assoc :product (:value %1)) (dissoc :form)) "pounds" #"파운(드|즈)" {:dim :leven-unit :value "pound"} "gram" #"그(램|람)" {:dim :leven-unit :value "그램"} "근" #"근" {:dim :leven-unit :value "근"} "개" #"개" {:dim :leven-unit :value "개"} "cup - 컵" #"컵" {:dim :leven-unit :value "cup"} "Bowl - 그릇" #"그릇" {:dim :leven-unit :value "bowl"} "dish - 접시" #"그릇" {:dim :leven-unit :value "dish"} "판 - a pizza => 피자한판" #"판" {:dim :leven-unit :value "판"} "삼겹살" #"삼겹살" {:dim :leven-product :value "삼겹살"} "콜라" #"콜라" {:dim :leven-product :value "콜라"} )
ed2b97da363598f339b1bc22c237b17ada2ef6a918262b05b6d5b5143388ba8a
mpenet/hayt
dsl.clj
(ns qbits.hayt.dsl (:refer-clojure :exclude [update group-by]) (:require [qbits.hayt.ns :as uns])) (doseq [module '(statement clause)] (uns/alias-ns (symbol (str "qbits.hayt.dsl." module))))
null
https://raw.githubusercontent.com/mpenet/hayt/7bbc06fae481bda89295dcc39d06382c4ba64568/src/clj/qbits/hayt/dsl.clj
clojure
(ns qbits.hayt.dsl (:refer-clojure :exclude [update group-by]) (:require [qbits.hayt.ns :as uns])) (doseq [module '(statement clause)] (uns/alias-ns (symbol (str "qbits.hayt.dsl." module))))
4550cc97e8d36c4bcd7faa791b0f2648bb098fd8682491884ec62aeeb22a9774
herd/herdtools7
op.mli
(****************************************************************************) (* the diy toolsuite *) (* *) , University College London , UK . , INRIA Paris - Rocquencourt , France . (* *) Copyright 2010 - present Institut National de Recherche en Informatique et (* en Automatique and the authors. All rights reserved. *) (* *) This software is governed by the CeCILL - B license under French law and (* abiding by the rules of distribution of free software. You can use, *) modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . (****************************************************************************) (** Syntax of unary, binary and ternary operations *) (**********) (* Binary *) (**********) type op = | Add | Sub | Mul | Div | And | Or | Xor | Nor | AndNot2 (* Arithmetic shift right *) | ASR | CapaAdd | Alignd | Alignu | Build | ClrPerm | CpyType | CSeal | Cthi | Seal | SetValue | CapaSub | CapaSubs | CapaSetTag | Unseal (* Logical shift left *) | ShiftLeft | ShiftRight | Lsr Return C - style boolean ( zero is false , not zero is true ) | Lt | Gt | Eq | Ne | Le | Ge (* on integers *) | Max | Min (* Build tagged location from location and tag *) | SetTag | SquashMutable | CheckPerms of string Change non - integer to integer given as second argument . * If argument is integer , it is left as is . * If argument is integer, it is left as is. *) | ToInteger val pp_op : op -> string val is_infix : op -> bool val pp_ptx_cmp_op : op -> string (*********) Unary (*********) type 'aop op1 = | Not Low order bit index is zero | SetBit of int | UnSetBit of int | ReadBit of int | LeftShift of int | LogicalRightShift of int | ArithRightShift of int | AddK of int | AndK of string | Mask of MachSize.sz | Sxt of MachSize.sz (* Sign extension *) | Inv (* Logical not or inverse *) | TagLoc (* Get tag memory location from location *) | CapaTagLoc | TagExtract (* Extract tag from tagged location *) | LocExtract (* Extract actual location from location *) | UnSetXBits of int * int | CapaGetTag | CheckSealed | CapaStrip | IsVirtual (* Predicate for virtual adresses *) get TLB entry from location | PTELoc (* get PTE entry from location *) | Offset (* get offset from base (symbolic) location *) | IsInstr (* Check nature of constant *) | ArchOp1 of 'aop val pp_op1 : bool -> (bool -> 'aop -> string) -> 'aop op1 -> string (***********) Ternary (***********) type op3 = If val pp_op3 : op3 -> string -> string -> string -> string
null
https://raw.githubusercontent.com/herd/herdtools7/d0fa745ab09a1607b4a192f8fcb16548786f7a9e/lib/op.mli
ocaml
************************************************************************** the diy toolsuite en Automatique and the authors. All rights reserved. abiding by the rules of distribution of free software. You can use, ************************************************************************** * Syntax of unary, binary and ternary operations ******** Binary ******** Arithmetic shift right Logical shift left on integers Build tagged location from location and tag ******* ******* Sign extension Logical not or inverse Get tag memory location from location Extract tag from tagged location Extract actual location from location Predicate for virtual adresses get PTE entry from location get offset from base (symbolic) location Check nature of constant ********* *********
, University College London , UK . , INRIA Paris - Rocquencourt , France . Copyright 2010 - present Institut National de Recherche en Informatique et This software is governed by the CeCILL - B license under French law and modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . type op = | Add | Sub | Mul | Div | And | Or | Xor | Nor | AndNot2 | ASR | CapaAdd | Alignd | Alignu | Build | ClrPerm | CpyType | CSeal | Cthi | Seal | SetValue | CapaSub | CapaSubs | CapaSetTag | Unseal | ShiftLeft | ShiftRight | Lsr Return C - style boolean ( zero is false , not zero is true ) | Lt | Gt | Eq | Ne | Le | Ge | Max | Min | SetTag | SquashMutable | CheckPerms of string Change non - integer to integer given as second argument . * If argument is integer , it is left as is . * If argument is integer, it is left as is. *) | ToInteger val pp_op : op -> string val is_infix : op -> bool val pp_ptx_cmp_op : op -> string Unary type 'aop op1 = | Not Low order bit index is zero | SetBit of int | UnSetBit of int | ReadBit of int | LeftShift of int | LogicalRightShift of int | ArithRightShift of int | AddK of int | AndK of string | Mask of MachSize.sz | CapaTagLoc | UnSetXBits of int * int | CapaGetTag | CheckSealed | CapaStrip get TLB entry from location | ArchOp1 of 'aop val pp_op1 : bool -> (bool -> 'aop -> string) -> 'aop op1 -> string Ternary type op3 = If val pp_op3 : op3 -> string -> string -> string -> string
7c5b00aafcdd2ee27d01109273a734a6c80b3d920f508694fd36e8b0fc66c9f3
ocaml-multicore/tezos
test_activation.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) * Testing ------- Component : Protocol ( activation ) Invocation : dune exec \ / proto_alpha / lib_protocol / test / integration / operations / main.exe \ -- test " ^activation$ " Subject : The activation operation creates an implicit contract from a registered commitment present in the context . It is parametrized by a public key hash ( pkh ) and a secret . The commitments are composed of : - a blinded pkh that can be revealed by the secret ; - an amount . The commitments and the secrets are generated from /scripts / create_genesis / create_genesis.py and should be coherent . ------- Component: Protocol (activation) Invocation: dune exec \ src/proto_alpha/lib_protocol/test/integration/operations/main.exe \ -- test "^activation$" Subject: The activation operation creates an implicit contract from a registered commitment present in the context. It is parametrized by a public key hash (pkh) and a secret. The commitments are composed of : - a blinded pkh that can be revealed by the secret ; - an amount. The commitments and the secrets are generated from /scripts/create_genesis/create_genesis.py and should be coherent. *) open Protocol open Alpha_context open Test_tez (* Generated commitments and secrets *) let commitments = List.map (fun (bpkh, a) -> Commitment. { blinded_public_key_hash = Blinded_public_key_hash.of_b58check_exn bpkh; amount = Tez.of_mutez_exn (Int64.of_string a); }) [ ("btz1bRL4X5BWo2Fj4EsBdUwexXqgTf75uf1qa", "23932454669343"); ("btz1SxjV1syBgftgKy721czKi3arVkVwYUFSv", "72954577464032"); ("btz1LtoNCjiW23txBTenALaf5H6NKF1L3c1gw", "217487035428349"); ("btz1SUd3mMhEBcWudrn8u361MVAec4WYCcFoy", "4092742372031"); ("btz1MvBXf4orko1tsGmzkjLbpYSgnwUjEe81r", "17590039016550"); ("btz1LoDZ3zsjgG3k3cqTpUMc9bsXbchu9qMXT", "26322312350555"); ("btz1RMfq456hFV5AeDiZcQuZhoMv2dMpb9hpP", "244951387881443"); ("btz1Y9roTh4A7PsMBkp8AgdVFrqUDNaBE59y1", "80065050465525"); ("btz1Q1N2ePwhVw5ED3aaRVek6EBzYs1GDkSVD", "3569618927693"); ("btz1VFFVsVMYHd5WfaDTAt92BeQYGK8Ri4eLy", "9034781424478"); ] type secret_account = { account : public_key_hash; activation_code : Blinded_public_key_hash.activation_code; amount : Tez.t; } let secrets () = Exported from proto_alpha client - TODO : remove when relocated to lib_crypto let read_key mnemonic email password = match Tezos_client_base.Bip39.of_words mnemonic with | None -> assert false | Some t -> TODO : unicode normalization ( ) ... let passphrase = Bytes.(cat (of_string email) (of_string password)) in let sk = Tezos_client_base.Bip39.to_seed ~passphrase t in let sk = Bytes.sub sk 0 32 in let sk : Signature.Secret_key.t = Ed25519 (Data_encoding.Binary.of_bytes_exn Ed25519.Secret_key.encoding sk) in let pk = Signature.Secret_key.to_public_key sk in let pkh = Signature.Public_key.hash pk in (pkh, pk, sk) in List.map (fun (mnemonic, secret, amount, pkh, password, email) -> let (pkh', pk, sk) = read_key mnemonic email password in let pkh = Signature.Public_key_hash.of_b58check_exn pkh in assert (Signature.Public_key_hash.equal pkh pkh') ; let account = Account.{pkh; pk; sk} in Account.add_account account ; { account = account.pkh; activation_code = Stdlib.Option.get (Blinded_public_key_hash.activation_code_of_hex secret); amount = WithExceptions.Option.to_exn ~none:(Invalid_argument "tez conversion") (Tez.of_mutez (Int64.of_string amount)); }) [ ( [ "envelope"; "hospital"; "mind"; "sunset"; "cancel"; "muscle"; "leisure"; "thumb"; "wine"; "market"; "exit"; "lucky"; "style"; "picnic"; "success"; ], "0f39ed0b656509c2ecec4771712d9cddefe2afac", "23932454669343", "tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF", "z0eZHQQGKt", "" ); ( [ "flag"; "quote"; "will"; "valley"; "mouse"; "chat"; "hold"; "prosper"; "silk"; "tent"; "cruel"; "cause"; "demise"; "bottom"; "practice"; ], "41f98b15efc63fa893d61d7d6eee4a2ce9427ac4", "72954577464032", "tz1X4maqF9tC1Yn4jULjHRAyzjAtc25Z68TX", "MHErskWPE6", "" ); ( [ "library"; "away"; "inside"; "paper"; "wise"; "focus"; "sweet"; "expose"; "require"; "change"; "stove"; "planet"; "zone"; "reflect"; "finger"; ], "411dfef031eeecc506de71c9df9f8e44297cf5ba", "217487035428349", "tz1SWBY7rWMutEuWS54Pt33MkzAS6eWkUuTc", "0AO6BzQNfN", "" ); ( [ "cruel"; "fluid"; "damage"; "demand"; "mimic"; "above"; "village"; "alpha"; "vendor"; "staff"; "absent"; "uniform"; "fire"; "asthma"; "milk"; ], "08d7d355bc3391d12d140780b39717d9f46fcf87", "4092742372031", "tz1amUjiZaevaxQy5wKn4SSRvVoERCip3nZS", "9kbZ7fR6im", "" ); ( [ "opera"; "divorce"; "easy"; "myself"; "idea"; "aim"; "dash"; "scout"; "case"; "resource"; "vote"; "humor"; "ticket"; "client"; "edge"; ], "9b7cad042fba557618bdc4b62837c5f125b50e56", "17590039016550", "tz1Zaee3QBtD4ErY1SzqUvyYTrENrExu6yQM", "suxT5H09yY", "" ); ( [ "token"; "similar"; "ginger"; "tongue"; "gun"; "sort"; "piano"; "month"; "hotel"; "vote"; "undo"; "success"; "hobby"; "shell"; "cart"; ], "124c0ca217f11ffc6c7b76a743d867c8932e5afd", "26322312350555", "tz1geDUUhfXK1EMj7VQdRjug1MoFe6gHWnCU", "4odVdLykaa", "" ); ( [ "shield"; "warrior"; "gorilla"; "birth"; "steak"; "neither"; "feel"; "only"; "liberty"; "float"; "oven"; "extend"; "pulse"; "suffer"; "vapor"; ], "ac7a2125beea68caf5266a647f24dce9fea018a7", "244951387881443", "tz1h3nY7jcZciJgAwRhWcrEwqfVp7VQoffur", "A6yeMqBFG8", "" ); ( [ "waste"; "open"; "scan"; "tip"; "subway"; "dance"; "rent"; "copper"; "garlic"; "laundry"; "defense"; "clerk"; "another"; "staff"; "liar"; ], "2b3e94be133a960fa0ef87f6c0922c19f9d87ca2", "80065050465525", "tz1VzL4Xrb3fL3ckvqCWy6bdGMzU2w9eoRqs", "oVZqpq60sk", "" ); ( [ "fiber"; "next"; "property"; "cradle"; "silk"; "obey"; "gossip"; "push"; "key"; "second"; "across"; "minimum"; "nice"; "boil"; "age"; ], "dac31640199f2babc157aadc0021cd71128ca9ea", "3569618927693", "tz1RUHg536oRKhPLFfttcB5gSWAhh4E9TWjX", "FfytQTTVbu", "" ); ( [ "print"; "labor"; "budget"; "speak"; "poem"; "diet"; "chunk"; "eternal"; "book"; "saddle"; "pioneer"; "ankle"; "happy"; "only"; "exclude"; ], "bb841227f250a066eb8429e56937ad504d7b34dd", "9034781424478", "tz1M1LFbgctcPWxstrao9aLr2ECW1fV4pH5u", "zknAl3lrX2", "" ); ] (** Helper: Create a genesis block with predefined commitments, accounts and balances. *) let activation_init () = Context.init ~consensus_threshold:0 ~commitments 1 >|=? fun (b, cs) -> secrets () |> fun ss -> (b, cs, ss) (** Verify the genesis block created by [activation_init] can be baked. *) let test_simple_init_with_commitments () = activation_init () >>=? fun (blk, _contracts, _secrets) -> Block.bake blk >>=? fun _ -> return_unit (** A single activation *) let test_single_activation () = activation_init () >>=? fun (blk, _contracts, secrets) -> let ({account; activation_code; amount = expected_amount; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in (* Contract does not exist *) Assert.balance_is ~loc:__LOC__ (B blk) (Contract.implicit_contract account) Tez.zero >>=? fun () -> Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>=? fun blk -> (* Contract does exist *) Assert.balance_is ~loc:__LOC__ (B blk) (Contract.implicit_contract account) expected_amount * 10 activations , one per bake . let test_multi_activation_1 () = activation_init () >>=? fun (blk, _contracts, secrets) -> List.fold_left_es (fun blk {account; activation_code; amount = expected_amount; _} -> Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>=? fun blk -> Assert.balance_is ~loc:__LOC__ (B blk) (Contract.implicit_contract account) expected_amount >|=? fun () -> blk) blk secrets >>=? fun _ -> return_unit * All of the 10 activations occur in one bake . let test_multi_activation_2 () = activation_init () >>=? fun (blk, _contracts, secrets) -> List.fold_left_es (fun ops {account; activation_code; _} -> Op.activation (B blk) account activation_code >|=? fun op -> op :: ops) [] secrets >>=? fun ops -> Block.bake ~operations:ops blk >>=? fun blk -> List.iter_es (fun {account; amount = expected_amount; _} -> (* Contract does exist *) Assert.balance_is ~loc:__LOC__ (B blk) (Contract.implicit_contract account) expected_amount) secrets (** Transfer with activated account. *) let test_activation_and_transfer () = activation_init () >>=? fun (blk, contracts, secrets) -> let ({account; activation_code; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in let bootstrap_contract = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let first_contract = Contract.implicit_contract account in Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>=? fun blk -> Context.Contract.balance (B blk) bootstrap_contract >>=? fun amount -> Test_tez.( /? ) amount 2L >>?= fun half_amount -> Context.Contract.balance (B blk) first_contract >>=? fun activated_amount_before -> Op.transaction (B blk) bootstrap_contract first_contract half_amount >>=? fun operation -> Block.bake ~operation blk >>=? fun blk -> Assert.balance_was_credited ~loc:__LOC__ (B blk) (Contract.implicit_contract account) activated_amount_before half_amount (** Transfer to an unactivated account and then activating it. *) let test_transfer_to_unactivated_then_activate () = activation_init () >>=? fun (blk, contracts, secrets) -> let ({account; activation_code; amount} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in let bootstrap_contract = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let unactivated_commitment_contract = Contract.implicit_contract account in Context.Contract.balance (B blk) bootstrap_contract >>=? fun b_amount -> b_amount /? 2L >>?= fun b_half_amount -> Incremental.begin_construction blk >>=? fun inc -> Op.transaction (I inc) bootstrap_contract unactivated_commitment_contract b_half_amount >>=? fun op -> Incremental.add_operation inc op >>=? fun inc -> Op.activation (I inc) account activation_code >>=? fun op' -> Incremental.add_operation inc op' >>=? fun inc -> Incremental.finalize_block inc >>=? fun blk2 -> Assert.balance_was_credited ~loc:__LOC__ (B blk2) (Contract.implicit_contract account) amount b_half_amount (****************************************************************) (* The following test scenarios are supposed to raise errors. *) (****************************************************************) (** Invalid pkh activation: expected to fail as the context does not contain any commitment. *) let test_invalid_activation_with_no_commitments () = Context.init 1 >>=? fun (blk, _) -> let secrets = secrets () in let ({account; activation_code; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Apply.Invalid_activation _ -> true | _ -> false) (** Wrong activation: wrong secret given in the operation. *) let test_invalid_activation_wrong_secret () = activation_init () >>=? fun (blk, _, secrets) -> let ({account; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.nth secrets 0 in let ({activation_code; _} as _second_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.nth secrets 1 in Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Apply.Invalid_activation _ -> true | _ -> false) (** Invalid pkh activation : expected to fail as the context does not contain an associated commitment. *) let test_invalid_activation_inexistent_pkh () = activation_init () >>=? fun (blk, _, secrets) -> let ({activation_code; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in let inexistent_pkh = Signature.Public_key_hash.of_b58check_exn "tz1PeQHGKPWSpNoozvxgqLN9TFsj6rDqNV3o" in Op.activation (B blk) inexistent_pkh activation_code >>=? fun operation -> Block.bake ~operation blk >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Apply.Invalid_activation _ -> true | _ -> false) (** Invalid pkh activation : expected to fail as the commitment has already been claimed. *) let test_invalid_double_activation () = activation_init () >>=? fun (blk, _, secrets) -> let ({account; activation_code; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in Incremental.begin_construction blk >>=? fun inc -> Op.activation (I inc) account activation_code >>=? fun op -> Incremental.add_operation inc op >>=? fun inc -> Op.activation (I inc) account activation_code >>=? fun op' -> Incremental.add_operation inc op' >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Apply.Invalid_activation _ -> true | _ -> false) (** Transfer from an unactivated commitment account. *) let test_invalid_transfer_from_unactivated_account () = activation_init () >>=? fun (blk, contracts, secrets) -> let ({account; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in let bootstrap_contract = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let unactivated_commitment_contract = Contract.implicit_contract account in (* No activation *) Op.transaction (B blk) unactivated_commitment_contract bootstrap_contract Tez.one >>=? fun operation -> Block.bake ~operation blk >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Contract_storage.Empty_implicit_contract pkh -> if pkh = account then true else false | _ -> false) let tests = [ Tztest.tztest "init with commitments" `Quick test_simple_init_with_commitments; Tztest.tztest "single activation" `Quick test_single_activation; Tztest.tztest "multi-activation one-by-one" `Quick test_multi_activation_1; Tztest.tztest "multi-activation all at a time" `Quick test_multi_activation_2; Tztest.tztest "activation and transfer" `Quick test_activation_and_transfer; Tztest.tztest "transfer to unactivated account then activate" `Quick test_transfer_to_unactivated_then_activate; Tztest.tztest "invalid activation with no commitments" `Quick test_invalid_activation_with_no_commitments; Tztest.tztest "invalid activation with commitments" `Quick test_invalid_activation_inexistent_pkh; Tztest.tztest "invalid double activation" `Quick test_invalid_double_activation; Tztest.tztest "wrong activation code" `Quick test_invalid_activation_wrong_secret; Tztest.tztest "invalid transfer from unactivated account" `Quick test_invalid_transfer_from_unactivated_account; ]
null
https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/test/integration/operations/test_activation.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** Generated commitments and secrets * Helper: Create a genesis block with predefined commitments, accounts and balances. * Verify the genesis block created by [activation_init] can be baked. * A single activation Contract does not exist Contract does exist Contract does exist * Transfer with activated account. * Transfer to an unactivated account and then activating it. ************************************************************** The following test scenarios are supposed to raise errors. ************************************************************** * Invalid pkh activation: expected to fail as the context does not contain any commitment. * Wrong activation: wrong secret given in the operation. * Invalid pkh activation : expected to fail as the context does not contain an associated commitment. * Invalid pkh activation : expected to fail as the commitment has already been claimed. * Transfer from an unactivated commitment account. No activation
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < > 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 * Testing ------- Component : Protocol ( activation ) Invocation : dune exec \ / proto_alpha / lib_protocol / test / integration / operations / main.exe \ -- test " ^activation$ " Subject : The activation operation creates an implicit contract from a registered commitment present in the context . It is parametrized by a public key hash ( pkh ) and a secret . The commitments are composed of : - a blinded pkh that can be revealed by the secret ; - an amount . The commitments and the secrets are generated from /scripts / create_genesis / create_genesis.py and should be coherent . ------- Component: Protocol (activation) Invocation: dune exec \ src/proto_alpha/lib_protocol/test/integration/operations/main.exe \ -- test "^activation$" Subject: The activation operation creates an implicit contract from a registered commitment present in the context. It is parametrized by a public key hash (pkh) and a secret. The commitments are composed of : - a blinded pkh that can be revealed by the secret ; - an amount. The commitments and the secrets are generated from /scripts/create_genesis/create_genesis.py and should be coherent. *) open Protocol open Alpha_context open Test_tez let commitments = List.map (fun (bpkh, a) -> Commitment. { blinded_public_key_hash = Blinded_public_key_hash.of_b58check_exn bpkh; amount = Tez.of_mutez_exn (Int64.of_string a); }) [ ("btz1bRL4X5BWo2Fj4EsBdUwexXqgTf75uf1qa", "23932454669343"); ("btz1SxjV1syBgftgKy721czKi3arVkVwYUFSv", "72954577464032"); ("btz1LtoNCjiW23txBTenALaf5H6NKF1L3c1gw", "217487035428349"); ("btz1SUd3mMhEBcWudrn8u361MVAec4WYCcFoy", "4092742372031"); ("btz1MvBXf4orko1tsGmzkjLbpYSgnwUjEe81r", "17590039016550"); ("btz1LoDZ3zsjgG3k3cqTpUMc9bsXbchu9qMXT", "26322312350555"); ("btz1RMfq456hFV5AeDiZcQuZhoMv2dMpb9hpP", "244951387881443"); ("btz1Y9roTh4A7PsMBkp8AgdVFrqUDNaBE59y1", "80065050465525"); ("btz1Q1N2ePwhVw5ED3aaRVek6EBzYs1GDkSVD", "3569618927693"); ("btz1VFFVsVMYHd5WfaDTAt92BeQYGK8Ri4eLy", "9034781424478"); ] type secret_account = { account : public_key_hash; activation_code : Blinded_public_key_hash.activation_code; amount : Tez.t; } let secrets () = Exported from proto_alpha client - TODO : remove when relocated to lib_crypto let read_key mnemonic email password = match Tezos_client_base.Bip39.of_words mnemonic with | None -> assert false | Some t -> TODO : unicode normalization ( ) ... let passphrase = Bytes.(cat (of_string email) (of_string password)) in let sk = Tezos_client_base.Bip39.to_seed ~passphrase t in let sk = Bytes.sub sk 0 32 in let sk : Signature.Secret_key.t = Ed25519 (Data_encoding.Binary.of_bytes_exn Ed25519.Secret_key.encoding sk) in let pk = Signature.Secret_key.to_public_key sk in let pkh = Signature.Public_key.hash pk in (pkh, pk, sk) in List.map (fun (mnemonic, secret, amount, pkh, password, email) -> let (pkh', pk, sk) = read_key mnemonic email password in let pkh = Signature.Public_key_hash.of_b58check_exn pkh in assert (Signature.Public_key_hash.equal pkh pkh') ; let account = Account.{pkh; pk; sk} in Account.add_account account ; { account = account.pkh; activation_code = Stdlib.Option.get (Blinded_public_key_hash.activation_code_of_hex secret); amount = WithExceptions.Option.to_exn ~none:(Invalid_argument "tez conversion") (Tez.of_mutez (Int64.of_string amount)); }) [ ( [ "envelope"; "hospital"; "mind"; "sunset"; "cancel"; "muscle"; "leisure"; "thumb"; "wine"; "market"; "exit"; "lucky"; "style"; "picnic"; "success"; ], "0f39ed0b656509c2ecec4771712d9cddefe2afac", "23932454669343", "tz1MawerETND6bqJqx8GV3YHUrvMBCDasRBF", "z0eZHQQGKt", "" ); ( [ "flag"; "quote"; "will"; "valley"; "mouse"; "chat"; "hold"; "prosper"; "silk"; "tent"; "cruel"; "cause"; "demise"; "bottom"; "practice"; ], "41f98b15efc63fa893d61d7d6eee4a2ce9427ac4", "72954577464032", "tz1X4maqF9tC1Yn4jULjHRAyzjAtc25Z68TX", "MHErskWPE6", "" ); ( [ "library"; "away"; "inside"; "paper"; "wise"; "focus"; "sweet"; "expose"; "require"; "change"; "stove"; "planet"; "zone"; "reflect"; "finger"; ], "411dfef031eeecc506de71c9df9f8e44297cf5ba", "217487035428349", "tz1SWBY7rWMutEuWS54Pt33MkzAS6eWkUuTc", "0AO6BzQNfN", "" ); ( [ "cruel"; "fluid"; "damage"; "demand"; "mimic"; "above"; "village"; "alpha"; "vendor"; "staff"; "absent"; "uniform"; "fire"; "asthma"; "milk"; ], "08d7d355bc3391d12d140780b39717d9f46fcf87", "4092742372031", "tz1amUjiZaevaxQy5wKn4SSRvVoERCip3nZS", "9kbZ7fR6im", "" ); ( [ "opera"; "divorce"; "easy"; "myself"; "idea"; "aim"; "dash"; "scout"; "case"; "resource"; "vote"; "humor"; "ticket"; "client"; "edge"; ], "9b7cad042fba557618bdc4b62837c5f125b50e56", "17590039016550", "tz1Zaee3QBtD4ErY1SzqUvyYTrENrExu6yQM", "suxT5H09yY", "" ); ( [ "token"; "similar"; "ginger"; "tongue"; "gun"; "sort"; "piano"; "month"; "hotel"; "vote"; "undo"; "success"; "hobby"; "shell"; "cart"; ], "124c0ca217f11ffc6c7b76a743d867c8932e5afd", "26322312350555", "tz1geDUUhfXK1EMj7VQdRjug1MoFe6gHWnCU", "4odVdLykaa", "" ); ( [ "shield"; "warrior"; "gorilla"; "birth"; "steak"; "neither"; "feel"; "only"; "liberty"; "float"; "oven"; "extend"; "pulse"; "suffer"; "vapor"; ], "ac7a2125beea68caf5266a647f24dce9fea018a7", "244951387881443", "tz1h3nY7jcZciJgAwRhWcrEwqfVp7VQoffur", "A6yeMqBFG8", "" ); ( [ "waste"; "open"; "scan"; "tip"; "subway"; "dance"; "rent"; "copper"; "garlic"; "laundry"; "defense"; "clerk"; "another"; "staff"; "liar"; ], "2b3e94be133a960fa0ef87f6c0922c19f9d87ca2", "80065050465525", "tz1VzL4Xrb3fL3ckvqCWy6bdGMzU2w9eoRqs", "oVZqpq60sk", "" ); ( [ "fiber"; "next"; "property"; "cradle"; "silk"; "obey"; "gossip"; "push"; "key"; "second"; "across"; "minimum"; "nice"; "boil"; "age"; ], "dac31640199f2babc157aadc0021cd71128ca9ea", "3569618927693", "tz1RUHg536oRKhPLFfttcB5gSWAhh4E9TWjX", "FfytQTTVbu", "" ); ( [ "print"; "labor"; "budget"; "speak"; "poem"; "diet"; "chunk"; "eternal"; "book"; "saddle"; "pioneer"; "ankle"; "happy"; "only"; "exclude"; ], "bb841227f250a066eb8429e56937ad504d7b34dd", "9034781424478", "tz1M1LFbgctcPWxstrao9aLr2ECW1fV4pH5u", "zknAl3lrX2", "" ); ] let activation_init () = Context.init ~consensus_threshold:0 ~commitments 1 >|=? fun (b, cs) -> secrets () |> fun ss -> (b, cs, ss) let test_simple_init_with_commitments () = activation_init () >>=? fun (blk, _contracts, _secrets) -> Block.bake blk >>=? fun _ -> return_unit let test_single_activation () = activation_init () >>=? fun (blk, _contracts, secrets) -> let ({account; activation_code; amount = expected_amount; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in Assert.balance_is ~loc:__LOC__ (B blk) (Contract.implicit_contract account) Tez.zero >>=? fun () -> Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>=? fun blk -> Assert.balance_is ~loc:__LOC__ (B blk) (Contract.implicit_contract account) expected_amount * 10 activations , one per bake . let test_multi_activation_1 () = activation_init () >>=? fun (blk, _contracts, secrets) -> List.fold_left_es (fun blk {account; activation_code; amount = expected_amount; _} -> Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>=? fun blk -> Assert.balance_is ~loc:__LOC__ (B blk) (Contract.implicit_contract account) expected_amount >|=? fun () -> blk) blk secrets >>=? fun _ -> return_unit * All of the 10 activations occur in one bake . let test_multi_activation_2 () = activation_init () >>=? fun (blk, _contracts, secrets) -> List.fold_left_es (fun ops {account; activation_code; _} -> Op.activation (B blk) account activation_code >|=? fun op -> op :: ops) [] secrets >>=? fun ops -> Block.bake ~operations:ops blk >>=? fun blk -> List.iter_es (fun {account; amount = expected_amount; _} -> Assert.balance_is ~loc:__LOC__ (B blk) (Contract.implicit_contract account) expected_amount) secrets let test_activation_and_transfer () = activation_init () >>=? fun (blk, contracts, secrets) -> let ({account; activation_code; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in let bootstrap_contract = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let first_contract = Contract.implicit_contract account in Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>=? fun blk -> Context.Contract.balance (B blk) bootstrap_contract >>=? fun amount -> Test_tez.( /? ) amount 2L >>?= fun half_amount -> Context.Contract.balance (B blk) first_contract >>=? fun activated_amount_before -> Op.transaction (B blk) bootstrap_contract first_contract half_amount >>=? fun operation -> Block.bake ~operation blk >>=? fun blk -> Assert.balance_was_credited ~loc:__LOC__ (B blk) (Contract.implicit_contract account) activated_amount_before half_amount let test_transfer_to_unactivated_then_activate () = activation_init () >>=? fun (blk, contracts, secrets) -> let ({account; activation_code; amount} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in let bootstrap_contract = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let unactivated_commitment_contract = Contract.implicit_contract account in Context.Contract.balance (B blk) bootstrap_contract >>=? fun b_amount -> b_amount /? 2L >>?= fun b_half_amount -> Incremental.begin_construction blk >>=? fun inc -> Op.transaction (I inc) bootstrap_contract unactivated_commitment_contract b_half_amount >>=? fun op -> Incremental.add_operation inc op >>=? fun inc -> Op.activation (I inc) account activation_code >>=? fun op' -> Incremental.add_operation inc op' >>=? fun inc -> Incremental.finalize_block inc >>=? fun blk2 -> Assert.balance_was_credited ~loc:__LOC__ (B blk2) (Contract.implicit_contract account) amount b_half_amount let test_invalid_activation_with_no_commitments () = Context.init 1 >>=? fun (blk, _) -> let secrets = secrets () in let ({account; activation_code; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Apply.Invalid_activation _ -> true | _ -> false) let test_invalid_activation_wrong_secret () = activation_init () >>=? fun (blk, _, secrets) -> let ({account; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.nth secrets 0 in let ({activation_code; _} as _second_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.nth secrets 1 in Op.activation (B blk) account activation_code >>=? fun operation -> Block.bake ~operation blk >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Apply.Invalid_activation _ -> true | _ -> false) let test_invalid_activation_inexistent_pkh () = activation_init () >>=? fun (blk, _, secrets) -> let ({activation_code; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in let inexistent_pkh = Signature.Public_key_hash.of_b58check_exn "tz1PeQHGKPWSpNoozvxgqLN9TFsj6rDqNV3o" in Op.activation (B blk) inexistent_pkh activation_code >>=? fun operation -> Block.bake ~operation blk >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Apply.Invalid_activation _ -> true | _ -> false) let test_invalid_double_activation () = activation_init () >>=? fun (blk, _, secrets) -> let ({account; activation_code; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in Incremental.begin_construction blk >>=? fun inc -> Op.activation (I inc) account activation_code >>=? fun op -> Incremental.add_operation inc op >>=? fun inc -> Op.activation (I inc) account activation_code >>=? fun op' -> Incremental.add_operation inc op' >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Apply.Invalid_activation _ -> true | _ -> false) let test_invalid_transfer_from_unactivated_account () = activation_init () >>=? fun (blk, contracts, secrets) -> let ({account; _} as _first_one) = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd secrets in let bootstrap_contract = WithExceptions.Option.get ~loc:__LOC__ @@ List.hd contracts in let unactivated_commitment_contract = Contract.implicit_contract account in Op.transaction (B blk) unactivated_commitment_contract bootstrap_contract Tez.one >>=? fun operation -> Block.bake ~operation blk >>= fun res -> Assert.proto_error ~loc:__LOC__ res (function | Contract_storage.Empty_implicit_contract pkh -> if pkh = account then true else false | _ -> false) let tests = [ Tztest.tztest "init with commitments" `Quick test_simple_init_with_commitments; Tztest.tztest "single activation" `Quick test_single_activation; Tztest.tztest "multi-activation one-by-one" `Quick test_multi_activation_1; Tztest.tztest "multi-activation all at a time" `Quick test_multi_activation_2; Tztest.tztest "activation and transfer" `Quick test_activation_and_transfer; Tztest.tztest "transfer to unactivated account then activate" `Quick test_transfer_to_unactivated_then_activate; Tztest.tztest "invalid activation with no commitments" `Quick test_invalid_activation_with_no_commitments; Tztest.tztest "invalid activation with commitments" `Quick test_invalid_activation_inexistent_pkh; Tztest.tztest "invalid double activation" `Quick test_invalid_double_activation; Tztest.tztest "wrong activation code" `Quick test_invalid_activation_wrong_secret; Tztest.tztest "invalid transfer from unactivated account" `Quick test_invalid_transfer_from_unactivated_account; ]
cc00e76cf3b1a21e8dbd44f77038ed0125a5bd3ba7ff7ca87c91d4114084d45a
andrewthad/chronos
Spec.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE StandaloneDeriving # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE NumericUnderscores # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Main (main) where import Chronos.Types import qualified Data.Aeson as AE import Data.ByteString (ByteString) import Data.Int (Int64) import Data.List (intercalate) import Data.Text (Text) import Data.Text.Lazy.Builder (Builder) import Test.Framework (defaultMain,defaultMainWithOpts,testGroup,Test) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit (Assertion,(@?=),assertBool) import Test.QuickCheck (Gen,Arbitrary(..),discard,genericShrink,elements,suchThat) import Test.QuickCheck (choose,chooseInt,arbitraryBoundedEnum) import Test.QuickCheck.Property (failed,succeeded,Result(..)) import qualified Chronos as C import qualified Data.Attoparsec.ByteString as AttoBS import qualified Data.Attoparsec.Text as Atto import qualified Data.ByteString.Builder as BBuilder import qualified Data.ByteString.Lazy as LByteString import qualified Data.Text as Text import qualified Data.Text.Lazy as LText import qualified Data.Text.Lazy.Builder as Builder import qualified Test.Framework as TF import qualified Test.Framework.Providers.HUnit as PH import qualified Torsor as T -- We increase the default number of property-based tests (provided by quickcheck ) to 1000 . Some of the encoding and decoding functions we test have special behavior when the minute is zero , which only happens in 1/60 of the generated scenarios . If we only generate 100 scenarios , there is a 18.62 % chance that none of these will have zero as the minute . If we increase this to 1000 , that probability drops to -- almost nothing. main :: IO () main = defaultMainWithOpts tests mempty { TF.ropt_test_options = Just mempty { TF.topt_maximum_generated_tests = Just 1000 , TF.topt_maximum_unsuitable_generated_tests = Just 10000 } } tests :: [Test] tests = [ testGroup "Time of Day" [ testGroup "Text" [ testGroup "Text Parsing Spec Tests" [ PH.testCase "No Separator + microseconds" (timeOfDayParse Nothing "165956.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + microseconds" (timeOfDayParse (Just ':') "16:59:56.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + milliseconds" (timeOfDayParse (Just ':') "05:00:58.675" (TimeOfDay 05 00 58675000000)) , PH.testCase "Separator + deciseconds" (timeOfDayParse (Just ':') "05:00:58.9" (TimeOfDay 05 00 58900000000)) , PH.testCase "Separator + no subseconds" (timeOfDayParse (Just ':') "23:08:01" (TimeOfDay 23 8 1000000000)) , PH.testCase "Separator + nanoseconds" (timeOfDayParse (Just ':') "05:00:58.111222999" (TimeOfDay 05 00 58111222999)) , PH.testCase "Separator + 10e-18 seconds (truncate)" (timeOfDayParse (Just ':') "05:00:58.111222333444555666" (TimeOfDay 05 00 58111222333)) , PH.testCase "Separator + opt seconds (absent)" (parseMatch (C.parser_HMS_opt_S (Just ':')) "00:01" (TimeOfDay 0 1 0)) , PH.testCase "Separator + opt seconds (present)" (parseMatch (C.parser_HMS_opt_S (Just ':')) "00:01:05" (TimeOfDay 0 1 5000000000)) , PH.testCase "No Separator + opt seconds (absent)" (parseMatch (C.parser_HMS_opt_S Nothing) "0001" (TimeOfDay 0 1 0)) , PH.testCase "No Separator + opt seconds (present)" (parseMatch (C.parser_HMS_opt_S Nothing) "000105" (TimeOfDay 0 1 5000000000)) ] , testGroup "Text Builder Spec Tests" [ PH.testCase "No Separator + microseconds" (timeOfDayBuilder (SubsecondPrecisionFixed 6) Nothing "165956.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + microseconds" (timeOfDayBuilder (SubsecondPrecisionFixed 6) (Just ':') "16:59:56.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + no subseconds" (timeOfDayBuilder (SubsecondPrecisionFixed 0) (Just ':') "23:08:01" (TimeOfDay 23 8 1000000000)) ] , testProperty "Text Builder Parser Isomorphism (H:M:S)" $ propEncodeDecodeIso (LText.toStrict . Builder.toLazyText . C.builder_HMS (SubsecondPrecisionFixed 9) (Just ':')) (either (const Nothing) Just . Atto.parseOnly (C.parser_HMS (Just ':'))) ] , testGroup "ByteString" [ testGroup "Parser Spec Tests" [ PH.testCase "No Separator + microseconds" (bsTimeOfDayParse Nothing "165956.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + microseconds" (bsTimeOfDayParse (Just ':') "16:59:56.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + milliseconds" (bsTimeOfDayParse (Just ':') "05:00:58.675" (TimeOfDay 05 00 58675000000)) , PH.testCase "Separator + deciseconds" (bsTimeOfDayParse (Just ':') "05:00:58.9" (TimeOfDay 05 00 58900000000)) , PH.testCase "Separator + no subseconds" (bsTimeOfDayParse (Just ':') "23:08:01" (TimeOfDay 23 8 1000000000)) , PH.testCase "Separator + nanoseconds" (bsTimeOfDayParse (Just ':') "05:00:58.111222999" (TimeOfDay 05 00 58111222999)) , PH.testCase "Separator + 10e-18 seconds (truncate)" (bsTimeOfDayParse (Just ':') "05:00:58.111222333444555666" (TimeOfDay 05 00 58111222333)) , PH.testCase "Separator + opt seconds (absent)" (bsParseMatch (C.parserUtf8_HMS_opt_S (Just ':')) "00:01" (TimeOfDay 0 1 0)) , PH.testCase "Separator + opt seconds (present)" (bsParseMatch (C.parserUtf8_HMS_opt_S (Just ':')) "00:01:05" (TimeOfDay 0 1 5000000000)) , PH.testCase "No Separator + opt seconds (absent)" (bsParseMatch (C.parserUtf8_HMS_opt_S Nothing) "0001" (TimeOfDay 0 1 0)) , PH.testCase "No Separator + opt seconds (present)" (bsParseMatch (C.parserUtf8_HMS_opt_S Nothing) "000105" (TimeOfDay 0 1 5000000000)) ] , testGroup "Builder Spec Tests" [ PH.testCase "No Separator + microseconds" (bsTimeOfDayBuilder (SubsecondPrecisionFixed 6) Nothing "165956.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + microseconds" (bsTimeOfDayBuilder (SubsecondPrecisionFixed 6) (Just ':') "16:59:56.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + no subseconds" (bsTimeOfDayBuilder (SubsecondPrecisionFixed 0) (Just ':') "23:08:01" (TimeOfDay 23 8 1000000000)) ] , testProperty "Builder Parser Isomorphism (H:M:S)" $ propEncodeDecodeIso (LByteString.toStrict . BBuilder.toLazyByteString . C.builderUtf8_HMS (SubsecondPrecisionFixed 9) (Just ':')) (either (const Nothing) Just . AttoBS.parseOnly (C.parserUtf8_HMS (Just ':'))) ] ] , testGroup "Date" [ testGroup "Ymd Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse (C.parser_Ymd Nothing) "20160101" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 1" (dateParse (C.parser_Ymd (Just '-')) "2016-01-01" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 2" (dateParse (C.parser_Ymd (Just '-')) "1876-09-27" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Dmy Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse (C.parser_Dmy Nothing) "01012016" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 1" (dateParse (C.parser_Dmy (Just '-')) "01-01-2016" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 2" (dateParse (C.parser_Dmy (Just '-')) "27-09-1876" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Ymd Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse C.parser_Ymd_lenient "20160101" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 1" (dateParse C.parser_Ymd_lenient "2016!01@01" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 2" (dateParse C.parser_Ymd_lenient "1876z09+27" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Dmy Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse C.parser_Dmy_lenient "01012016" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 1" (dateParse C.parser_Dmy_lenient "01!01@2016" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 2" (dateParse C.parser_Dmy_lenient "27z09+1876" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Mdy Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse C.parser_Mdy_lenient "01022016" (Date (Year 2016) (Month 0) (DayOfMonth 2))) , PH.testCase "Passes With Separator 1" (dateParse C.parser_Mdy_lenient "01!02@2016" (Date (Year 2016) (Month 0) (DayOfMonth 2))) , PH.testCase "Passes With Separator 2" (dateParse C.parser_Mdy_lenient "09+27z1876" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Builder Spec Tests" $ [ PH.testCase "No Separator" (dateBuilder Nothing "20160101" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Separator 1" (dateBuilder (Just '-') "2016-01-01" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Separator 2" (dateBuilder (Just '-') "1876-09-27" (Date (Year 1876) (Month 8) (DayOfMonth 27))) , PH.testCase "zero-pad year" (dateBuilder (Just '-') "0001-01-01" (Date (Year 1) (Month 0) (DayOfMonth 1))) ] , testProperty "Builder Parser Isomorphism (Y-m-d)" $ propEncodeDecodeIso (LText.toStrict . Builder.toLazyText . C.builder_Ymd (Just '-')) (either (const Nothing) Just . Atto.parseOnly (C.parser_Ymd (Just '-'))) ] , testGroup "Datetime" [ testGroup "DmyHMS Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse (C.parser_DmyHMS (DatetimeFormat Nothing Nothing Nothing)) "01022016010223" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse (C.parser_DmyHMS (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02:23" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) ] , testGroup "YmdHMS Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse (C.parser_YmdHMS (DatetimeFormat Nothing Nothing Nothing)) "20160101010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse (C.parser_YmdHMS (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-01 01:02:23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) ] , testGroup "MdyHMS Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse (C.parser_MdyHMS (DatetimeFormat Nothing Nothing Nothing)) "01012016010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse (C.parser_MdyHMS (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-01-2016 01:02:23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) ] , testGroup "DmyHMS Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse C.parser_DmyHMS_lenient "01022016010223" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse C.parser_DmyHMS_lenient "01z02x2016$01;02:23" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_DmyHMS_lenient "01-02-2016 01:02:23" "Failed reading: input does not start with a digit") , PH.testCase "Fails with some nonuniform empty Separators" (datetimeParseFail C.parser_DmyHMS_lenient "01-02-201601:02:23" "Failed reading: satisfy") ] , testGroup "YmdHMS Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse C.parser_YmdHMS_lenient "20160101010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse C.parser_YmdHMS_lenient "2016!01z01^01a02c23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_YmdHMS_lenient "2016-01-02 01:02:03" "Failed reading: input does not start with a digit") ] , testGroup "MdyHMS Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse C.parser_MdyHMS_lenient "01012016010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse C.parser_MdyHMS_lenient "01z01%2016^01a02c23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_MdyHMS_lenient "01-02-2016 01:02:03" "Failed reading: input does not start with a digit") ] , testGroup "DmyHMS Optional Seconds Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse (C.parser_DmyHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "01022016010223" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse (C.parser_DmyHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "010220160102" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse (C.parser_DmyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02:23" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse (C.parser_DmyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail (C.parser_DmyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02:" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail (C.parser_DmyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02" "Failed reading: input does not start with a digit") ] , testGroup "YmdHMS Optional Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse (C.parser_YmdHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "20160101010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse (C.parser_YmdHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "201601010102" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse (C.parser_YmdHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-01 01:02:23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse (C.parser_YmdHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-01 01:02" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail (C.parser_YmdHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-02 01:02:" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail (C.parser_YmdHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-02 01:02" "Failed reading: input does not start with a digit") ] , testGroup "MdyHMS Optional Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse (C.parser_MdyHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "01012016010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse (C.parser_MdyHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "010120160102" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse (C.parser_MdyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-01-2016 01:02:23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse (C.parser_MdyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-01-2016 01:02" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail (C.parser_MdyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02:" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail (C.parser_MdyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02" "Failed reading: input does not start with a digit") ] , testGroup "DmyHMS Optional Seconds Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator with seconds" (datetimeParse C.parser_DmyHMS_opt_S_lenient "01022016010223" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator without seconds" (datetimeParse C.parser_DmyHMS_opt_S_lenient "010220160102" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator with seconds" (datetimeParse C.parser_DmyHMS_opt_S_lenient "01z02x2016$01;02:23" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator without seconds" (datetimeParse C.parser_DmyHMS_opt_S_lenient "01z02x2016$01;02" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail C.parser_DmyHMS_opt_S_lenient "01z02x2016$01;02^" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_DmyHMS_opt_S_lenient "01-02-2016 01:02" "Failed reading: input does not start with a digit") ] , testGroup "YmdHMS Optional Seconds Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse C.parser_YmdHMS_opt_S_lenient "20160101010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse C.parser_YmdHMS_opt_S_lenient "201601010102" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse C.parser_YmdHMS_opt_S_lenient "2016!01z01^01a02c23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse C.parser_YmdHMS_opt_S_lenient "2016!01z01^01a02" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail C.parser_YmdHMS_opt_S_lenient "2016!01z01^01a02^" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_YmdHMS_opt_S_lenient "2016-01-02 01:02" "Failed reading: input does not start with a digit") ] , testGroup "MdyHMS Optional Seconds Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse C.parser_MdyHMS_opt_S_lenient "01012016010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse C.parser_MdyHMS_opt_S_lenient "010120160102" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse C.parser_MdyHMS_opt_S_lenient "01z01!2016^01a02c23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse C.parser_MdyHMS_opt_S_lenient "01z01(2016^01a02" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail C.parser_MdyHMS_opt_S_lenient "01z01!2016^01a02^" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_MdyHMS_opt_S_lenient "01-02-2016 01:02" "Failed reading: input does not start with a digit") ] , testGroup "Builder Parser Isomorphism" $ [ testProperty "(Y-m-dTH:M:S)" $ propEncodeDecodeIsoSettings (\format -> LText.toStrict . Builder.toLazyText . C.builder_YmdHMS (SubsecondPrecisionFixed 9) format) (\format -> either (const Nothing) Just . Atto.parseOnly (C.parser_YmdHMS format)) , testProperty "Builder Parser Isomorphism (YmdHMS)" $ propEncodeDecodeIso (LText.toStrict . Builder.toLazyText . C.builder_YmdHMS (SubsecondPrecisionFixed 9) (DatetimeFormat Nothing Nothing Nothing)) (either (const Nothing) Just . Atto.parseOnly (C.parser_YmdHMS (DatetimeFormat Nothing Nothing Nothing))) ] , testProperty "ISO-8601 Roundtrip" $ propEncodeDecodeIso C.encodeShortTextIso8601Zulu (\input -> case C.decodeShortTextIso8601 input of Just (OffsetDatetime dt (Offset 0)) -> Just dt _ -> Nothing ) , testProperty "ISO-8601 Zoneless Roundtrip" $ propEncodeDecodeIso C.encodeShortTextIso8601Zoneless (\input -> case C.decodeShortTextIso8601Zoneless input of Just dt -> Just dt _ -> Nothing ) ] , testGroup "Offset Datetime" [ testGroup "Builder Spec Tests" $ [ PH.testCase "W3C" $ matchBuilder "1997-07-16T19:20:30.450+01:00" $ C.builderW3Cz $ OffsetDatetime ( Datetime ( Date (Year 1997) C.july (DayOfMonth 16) ) ( TimeOfDay 19 20 30450000000 ) ) (Offset 60) ] , testProperty "Builder Parser Isomorphism (YmdHMSz)" $ propEncodeDecodeIsoSettings (\(offsetFormat,datetimeFormat) offsetDatetime -> LText.toStrict $ Builder.toLazyText $ C.builder_YmdHMSz offsetFormat (SubsecondPrecisionFixed 9) datetimeFormat offsetDatetime ) (\(offsetFormat,datetimeFormat) input -> either (const Nothing) Just $ flip Atto.parseOnly input $ C.parser_YmdHMSz offsetFormat datetimeFormat ) ] , testGroup "Posix Time" [ PH.testCase "Get now" $ do now <- C.now assertBool "Current time is the beginning of the epoch." (now /= C.epoch) ] , testGroup "Conversion" [ testGroup "POSIX to Datetime" [ PH.testCase "Epoch" $ C.timeToDatetime (Time 0) @?= Datetime (Date (Year 1970) C.january (DayOfMonth 1)) (TimeOfDay 0 0 0) , PH.testCase "Billion Seconds" $ C.timeToDatetime (Time $ 10 ^ 18) @?= Datetime (Date (Year 2001) C.september (DayOfMonth 9)) (TimeOfDay 1 46 (40 * 10 ^ 9)) , testProperty "Isomorphism" $ propEncodeDecodeFullIso C.timeToDatetime C.datetimeToTime ] ] , testGroup "TimeInterval" [ testGroup "within" [ testProperty "Verify that Time bounds are inside TimeInterval" propWithinInsideInterval , testProperty "Verify that the sum of Time and the span of TimeInterval is outside the interval" propWithinOutsideInterval ] , testGroup "timeIntervalToTimespan" [ PH.testCase "Verify Timespan correctness with TimeInterval" (C.timeIntervalToTimespan (TimeInterval (Time 13) (Time 25)) @?= Timespan 12) , PH.testCase "Verify Timespan correctness with equal TimeInterval bounds" (C.timeIntervalToTimespan (TimeInterval (Time 13) (Time 13)) @?= Timespan 0) , testProperty "Almost isomorphism" propEncodeDecodeTimeInterval ] , testGroup "whole" [ PH.testCase "Verify TimeInterval's bound correctness" (C.whole @?= TimeInterval (Time (minBound :: Int64)) (Time (maxBound :: Int64))) ] , testGroup "singleton" [ testProperty "Verify that upper and lower bound are always equals" propSingletonBoundsEquals ] , testGroup "width" [ testProperty "Verify Time bounds correctness with TimeSpan" propWidthVerifyBounds ] , testGroup "timeIntervalBuilder" [ testProperty "Verify TimeInterval construction correctness" propTimeIntervalBuilder ] ] , testGroup "Datetime Conversions" [ testGroup "datetimeToDayOfWeek" [ PH.testCase "February 2nd 2020" (C.datetimeToDayOfWeek (Datetime (Date (Year 2020) (Month 1) (DayOfMonth 2)) (TimeOfDay 0 0 0)) @?= DayOfWeek 0) , PH.testCase "July 10th 2019" (C.datetimeToDayOfWeek (Datetime (Date (Year 2019) (Month 6) (DayOfMonth 10)) (TimeOfDay 0 0 0)) @?= DayOfWeek 3) , PH.testCase "November 16th 1946" (C.datetimeToDayOfWeek (Datetime (Date (Year 1946) (Month 10) (DayOfMonth 16)) (TimeOfDay 0 0 0)) @?= DayOfWeek 6) , PH.testCase "February 29th 2024 (Leap Year)" (C.datetimeToDayOfWeek (Datetime (Date (Year 2024) (Month 1) (DayOfMonth 29)) (TimeOfDay 0 0 0)) @?= DayOfWeek 4) ] ] , testGroup "timeToDayOfWeek Conversions" [ PH.testCase "Sunday, February 9, 2020 4:00:00 PM" (C.timeToDayOfWeek (Time 1581264000000000000) @?= DayOfWeek 0) , PH.testCase "Monday, April 9, 2001 4:00:00 PM" (C.timeToDayOfWeek (Time 986832000000000000) @?= DayOfWeek 1) , PH.testCase "Tuesday, March 7, 1995 4:00:00 PM" (C.timeToDayOfWeek (Time 794592000000000000) @?= DayOfWeek 2) , PH.testCase "Wednesday, June 17, 1987 4:00:00 PM" (C.timeToDayOfWeek (Time 550944000000000000) @?= DayOfWeek 3) , PH.testCase "Thursday, December 18, 1980 4:00:00 PM" (C.timeToDayOfWeek (Time 346003200000000000) @?= DayOfWeek 4) , PH.testCase "Friday, October 10, 1975 4:00:00 PM" (C.timeToDayOfWeek (Time 182188800000000000) @?= DayOfWeek 5) , PH.testCase "Saturday, August 11, 1973 4:00:00 PM" (C.timeToDayOfWeek (Time 113932800000000000) @?= DayOfWeek 6) , PH.testCase "Thursday, January 1, 1970 12:00:00 AM" (C.timeToDayOfWeek (Time 0) @?= DayOfWeek 4) , PH.testCase "Saturday, June 14, 1969 4:00:00 PM" (C.timeToDayOfWeek (Time (-17308800000000000)) @?= DayOfWeek 6) , PH.testCase "Tuesday, June 6, 1944 4:00:00 PM" (C.timeToDayOfWeek (Time (-806918400000000000)) @?= DayOfWeek 2) ] , testGroup "timeToOffsetDatetime" [ PH.testCase "EpochNeg4h" (C.timeToOffsetDatetime (Offset (-240)) (Time 0) @?= OffsetDatetime ( Datetime ( Date (Year 1969) C.december (DayOfMonth 31) ) ( TimeOfDay 20 0 0 ) ) (Offset (-240)) ) ] , testGroup "json" [ PH.testCase "Datetime" $ let dt = Datetime (Date (Year 3000) (Month 11) (DayOfMonth 31)) (TimeOfDay 0 0 0) in AE.eitherDecode (AE.encode dt) @?= Right dt ] ] failure :: String -> Result failure msg = failed { reason = msg , theException = Nothing } propEncodeDecodeFullIso :: (Eq a,Show a,Show b) => (a -> b) -> (b -> a) -> a -> Result propEncodeDecodeFullIso f g a = let fa = f a gfa = g fa in if gfa == a then succeeded else failure $ concat [ "x: ", show a, "\n" , "f(x): ", show fa, "\n" , "g(f(x)): ", show gfa, "\n" ] propEncodeDecodeIso :: Eq a => (a -> b) -> (b -> Maybe a) -> a -> Bool propEncodeDecodeIso f g a = g (f a) == Just a propEncodeDecodeIsoSettings :: (Eq a,Show a,Show b,Show e) => (e -> a -> b) -> (e -> b -> Maybe a) -> e -> a -> Result propEncodeDecodeIsoSettings f g e a = let fa = f e a gfa = g e fa in if gfa == Just a then succeeded else failure $ concat [ "env: ", show e, "\n" , "x: ", show a, "\n" , "f(x): ", show fa, "\n" , "g(f(x)): ", show gfa, "\n" ] parseMatch :: (Eq a, Show a) => Atto.Parser a -> Text -> a -> Assertion parseMatch p t expected = do Atto.parseOnly (p <* Atto.endOfInput) t @?= Right expected bsParseMatch :: (Eq a, Show a) => AttoBS.Parser a -> ByteString -> a -> Assertion bsParseMatch p t expected = do AttoBS.parseOnly (p <* AttoBS.endOfInput) t @?= Right expected timeOfDayParse :: Maybe Char -> Text -> TimeOfDay -> Assertion timeOfDayParse m t expected = Atto.parseOnly (C.parser_HMS m <* Atto.endOfInput) t @?= Right expected bsTimeOfDayParse :: Maybe Char -> ByteString -> TimeOfDay -> Assertion bsTimeOfDayParse m t expected = AttoBS.parseOnly (C.parserUtf8_HMS m <* AttoBS.endOfInput) t @?= Right expected timeOfDayBuilder :: SubsecondPrecision -> Maybe Char -> Text -> TimeOfDay -> Assertion timeOfDayBuilder sp m expected tod = LText.toStrict (Builder.toLazyText (C.builder_HMS sp m tod)) @?= expected bsTimeOfDayBuilder :: SubsecondPrecision -> Maybe Char -> Text -> TimeOfDay -> Assertion bsTimeOfDayBuilder sp m expected tod = LText.toStrict (Builder.toLazyText (C.builder_HMS sp m tod)) @?= expected dateParse :: Atto.Parser Date -> Text -> Date -> Assertion dateParse p t expected = Atto.parseOnly (p <* Atto.endOfInput) t @?= Right expected dateParseFail : : . Parser Date - > Text - > String - > Assertion t expected = -- Atto.parseOnly (p <* Atto.endOfInput) t -- @?= Left expected datetimeParse :: Atto.Parser Datetime -> Text -> Datetime -> Assertion datetimeParse p t expected = Atto.parseOnly (p <* Atto.endOfInput) t @?= Right expected datetimeParseFail :: Atto.Parser Datetime -> Text -> String -> Assertion datetimeParseFail p t expected = Atto.parseOnly (p <* Atto.endOfInput) t @?= Left expected dateBuilder :: Maybe Char -> Text -> Date -> Assertion dateBuilder m expected tod = LText.toStrict (Builder.toLazyText (C.builder_Ymd m tod)) @?= expected matchBuilder :: Text -> Builder -> Assertion matchBuilder a b = LText.toStrict (Builder.toLazyText b) @?= a propWithinInsideInterval :: TimeInterval -> Bool propWithinInsideInterval ti@(TimeInterval t0 t1) = C.within t1 ti && C.within t0 ti propWithinOutsideInterval :: RelatedTimes -> Bool propWithinOutsideInterval (RelatedTimes t ti@(TimeInterval t0 t1)) | t == t0 = discard | t == t1 = discard | t1 <= t0 = discard | t0 < (Time 0) = discard | t < (Time 0) = discard | otherwise = let span = C.timeIntervalToTimespan ti tm = T.add span t in not $ C.within tm ti propEncodeDecodeTimeInterval :: TimeInterval -> Bool propEncodeDecodeTimeInterval ti@(TimeInterval t0 t1) | t0 < (Time 0) = discard | t0 >= t1 = discard | otherwise = let span = C.timeIntervalToTimespan ti tm = T.add span t0 in t1 == tm propSingletonBoundsEquals :: Time -> Bool propSingletonBoundsEquals tm = let (TimeInterval (Time ti) (Time te)) = C.singleton tm in ti == te propWidthVerifyBounds :: TimeInterval -> Bool propWidthVerifyBounds ti@(TimeInterval (Time lower) (Time upper)) = let tiWidth = (getTimespan . C.width) ti in T.add lower tiWidth == upper && T.difference upper tiWidth == lower propTimeIntervalBuilder :: Time -> Time -> Bool propTimeIntervalBuilder t0 t1 = let (TimeInterval ti te) = (C.timeIntervalBuilder t0 t1) in (getTime te) >= (getTime ti) instance Arbitrary TimeOfDay where arbitrary = TimeOfDay <$> choose (0,23) <*> choose (0,59) -- never use leap seconds for property-based tests <*> ( do subsecPrecision <- chooseInt (0,9) secs <- chooseInt (0,59) case subsecPrecision of 0 -> pure (fromIntegral @Int @Int64 secs * 1_000_000_000) _ -> do subsecs <- chooseInt (0,((10 :: Int) ^ subsecPrecision) - 1) let subsecs' = subsecs * ((10 :: Int) ^ (9 - subsecPrecision)) if subsecs' < 0 || subsecs' >= 1_000_000_000 then error "Mistake in Arbitrary instance for TimeOfDay" else pure ( (fromIntegral @Int @Int64 secs * 1_000_000_000) + (fromIntegral @Int @Int64 subsecs) ) ) instance Arbitrary Date where arbitrary = Date <$> fmap Year (choose (1800,2100)) <*> fmap Month (choose (0,11)) <*> fmap DayOfMonth (choose (1,28)) instance Arbitrary Datetime where arbitrary = Datetime <$> arbitrary <*> arbitrary -- instance Arbitrary UtcTime where -- arbitrary = UtcTime -- <$> fmap Day (choose (-100000,100000)) < * > choose ( 0,24 * 60 * 60 * 1000000000 - 1 ) instance Arbitrary OffsetDatetime where arbitrary = OffsetDatetime <$> arbitrary <*> arbitrary instance Arbitrary DatetimeFormat where arbitrary = DatetimeFormat <$> elements [Nothing, Just '/', Just ':', Just '-', Just '.'] <*> elements [Nothing, Just '/', Just ':', Just '-', Just 'T'] <*> elements [Nothing, Just ':', Just '-'] shrink (DatetimeFormat a b c) | a == Just '-', b == Just 'T', c == Just ':' = [] | otherwise = [DatetimeFormat (Just '-') (Just 'T') (Just ':')] instance Arbitrary OffsetFormat where arbitrary = arbitraryBoundedEnum shrink = genericShrink deriving instance Arbitrary Time instance Arbitrary TimeInterval where arbitrary = do t0 <- arbitrary t1 <- suchThat arbitrary (>= t0) pure (TimeInterval t0 t1) data RelatedTimes = RelatedTimes Time TimeInterval deriving (Show) instance Arbitrary RelatedTimes where arbitrary = do ti@(TimeInterval t0 t1) <- arbitrary tm <- fmap Time (choose (getTime t0, getTime t1)) pure $ RelatedTimes tm ti instance Arbitrary Offset where arbitrary = fmap Offset (choose ((-24) * 60, 24 * 60))
null
https://raw.githubusercontent.com/andrewthad/chronos/49a5605860746bbfc6e75dff3fbc69b69ea92338/test/Spec.hs
haskell
# LANGUAGE OverloadedStrings # We increase the default number of property-based tests (provided almost nothing. Atto.parseOnly (p <* Atto.endOfInput) t @?= Left expected never use leap seconds for property-based tests instance Arbitrary UtcTime where arbitrary = UtcTime <$> fmap Day (choose (-100000,100000))
# LANGUAGE StandaloneDeriving # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE NumericUnderscores # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # module Main (main) where import Chronos.Types import qualified Data.Aeson as AE import Data.ByteString (ByteString) import Data.Int (Int64) import Data.List (intercalate) import Data.Text (Text) import Data.Text.Lazy.Builder (Builder) import Test.Framework (defaultMain,defaultMainWithOpts,testGroup,Test) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.HUnit (Assertion,(@?=),assertBool) import Test.QuickCheck (Gen,Arbitrary(..),discard,genericShrink,elements,suchThat) import Test.QuickCheck (choose,chooseInt,arbitraryBoundedEnum) import Test.QuickCheck.Property (failed,succeeded,Result(..)) import qualified Chronos as C import qualified Data.Attoparsec.ByteString as AttoBS import qualified Data.Attoparsec.Text as Atto import qualified Data.ByteString.Builder as BBuilder import qualified Data.ByteString.Lazy as LByteString import qualified Data.Text as Text import qualified Data.Text.Lazy as LText import qualified Data.Text.Lazy.Builder as Builder import qualified Test.Framework as TF import qualified Test.Framework.Providers.HUnit as PH import qualified Torsor as T by quickcheck ) to 1000 . Some of the encoding and decoding functions we test have special behavior when the minute is zero , which only happens in 1/60 of the generated scenarios . If we only generate 100 scenarios , there is a 18.62 % chance that none of these will have zero as the minute . If we increase this to 1000 , that probability drops to main :: IO () main = defaultMainWithOpts tests mempty { TF.ropt_test_options = Just mempty { TF.topt_maximum_generated_tests = Just 1000 , TF.topt_maximum_unsuitable_generated_tests = Just 10000 } } tests :: [Test] tests = [ testGroup "Time of Day" [ testGroup "Text" [ testGroup "Text Parsing Spec Tests" [ PH.testCase "No Separator + microseconds" (timeOfDayParse Nothing "165956.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + microseconds" (timeOfDayParse (Just ':') "16:59:56.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + milliseconds" (timeOfDayParse (Just ':') "05:00:58.675" (TimeOfDay 05 00 58675000000)) , PH.testCase "Separator + deciseconds" (timeOfDayParse (Just ':') "05:00:58.9" (TimeOfDay 05 00 58900000000)) , PH.testCase "Separator + no subseconds" (timeOfDayParse (Just ':') "23:08:01" (TimeOfDay 23 8 1000000000)) , PH.testCase "Separator + nanoseconds" (timeOfDayParse (Just ':') "05:00:58.111222999" (TimeOfDay 05 00 58111222999)) , PH.testCase "Separator + 10e-18 seconds (truncate)" (timeOfDayParse (Just ':') "05:00:58.111222333444555666" (TimeOfDay 05 00 58111222333)) , PH.testCase "Separator + opt seconds (absent)" (parseMatch (C.parser_HMS_opt_S (Just ':')) "00:01" (TimeOfDay 0 1 0)) , PH.testCase "Separator + opt seconds (present)" (parseMatch (C.parser_HMS_opt_S (Just ':')) "00:01:05" (TimeOfDay 0 1 5000000000)) , PH.testCase "No Separator + opt seconds (absent)" (parseMatch (C.parser_HMS_opt_S Nothing) "0001" (TimeOfDay 0 1 0)) , PH.testCase "No Separator + opt seconds (present)" (parseMatch (C.parser_HMS_opt_S Nothing) "000105" (TimeOfDay 0 1 5000000000)) ] , testGroup "Text Builder Spec Tests" [ PH.testCase "No Separator + microseconds" (timeOfDayBuilder (SubsecondPrecisionFixed 6) Nothing "165956.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + microseconds" (timeOfDayBuilder (SubsecondPrecisionFixed 6) (Just ':') "16:59:56.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + no subseconds" (timeOfDayBuilder (SubsecondPrecisionFixed 0) (Just ':') "23:08:01" (TimeOfDay 23 8 1000000000)) ] , testProperty "Text Builder Parser Isomorphism (H:M:S)" $ propEncodeDecodeIso (LText.toStrict . Builder.toLazyText . C.builder_HMS (SubsecondPrecisionFixed 9) (Just ':')) (either (const Nothing) Just . Atto.parseOnly (C.parser_HMS (Just ':'))) ] , testGroup "ByteString" [ testGroup "Parser Spec Tests" [ PH.testCase "No Separator + microseconds" (bsTimeOfDayParse Nothing "165956.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + microseconds" (bsTimeOfDayParse (Just ':') "16:59:56.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + milliseconds" (bsTimeOfDayParse (Just ':') "05:00:58.675" (TimeOfDay 05 00 58675000000)) , PH.testCase "Separator + deciseconds" (bsTimeOfDayParse (Just ':') "05:00:58.9" (TimeOfDay 05 00 58900000000)) , PH.testCase "Separator + no subseconds" (bsTimeOfDayParse (Just ':') "23:08:01" (TimeOfDay 23 8 1000000000)) , PH.testCase "Separator + nanoseconds" (bsTimeOfDayParse (Just ':') "05:00:58.111222999" (TimeOfDay 05 00 58111222999)) , PH.testCase "Separator + 10e-18 seconds (truncate)" (bsTimeOfDayParse (Just ':') "05:00:58.111222333444555666" (TimeOfDay 05 00 58111222333)) , PH.testCase "Separator + opt seconds (absent)" (bsParseMatch (C.parserUtf8_HMS_opt_S (Just ':')) "00:01" (TimeOfDay 0 1 0)) , PH.testCase "Separator + opt seconds (present)" (bsParseMatch (C.parserUtf8_HMS_opt_S (Just ':')) "00:01:05" (TimeOfDay 0 1 5000000000)) , PH.testCase "No Separator + opt seconds (absent)" (bsParseMatch (C.parserUtf8_HMS_opt_S Nothing) "0001" (TimeOfDay 0 1 0)) , PH.testCase "No Separator + opt seconds (present)" (bsParseMatch (C.parserUtf8_HMS_opt_S Nothing) "000105" (TimeOfDay 0 1 5000000000)) ] , testGroup "Builder Spec Tests" [ PH.testCase "No Separator + microseconds" (bsTimeOfDayBuilder (SubsecondPrecisionFixed 6) Nothing "165956.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + microseconds" (bsTimeOfDayBuilder (SubsecondPrecisionFixed 6) (Just ':') "16:59:56.246052" (TimeOfDay 16 59 56246052000)) , PH.testCase "Separator + no subseconds" (bsTimeOfDayBuilder (SubsecondPrecisionFixed 0) (Just ':') "23:08:01" (TimeOfDay 23 8 1000000000)) ] , testProperty "Builder Parser Isomorphism (H:M:S)" $ propEncodeDecodeIso (LByteString.toStrict . BBuilder.toLazyByteString . C.builderUtf8_HMS (SubsecondPrecisionFixed 9) (Just ':')) (either (const Nothing) Just . AttoBS.parseOnly (C.parserUtf8_HMS (Just ':'))) ] ] , testGroup "Date" [ testGroup "Ymd Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse (C.parser_Ymd Nothing) "20160101" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 1" (dateParse (C.parser_Ymd (Just '-')) "2016-01-01" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 2" (dateParse (C.parser_Ymd (Just '-')) "1876-09-27" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Dmy Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse (C.parser_Dmy Nothing) "01012016" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 1" (dateParse (C.parser_Dmy (Just '-')) "01-01-2016" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 2" (dateParse (C.parser_Dmy (Just '-')) "27-09-1876" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Ymd Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse C.parser_Ymd_lenient "20160101" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 1" (dateParse C.parser_Ymd_lenient "2016!01@01" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 2" (dateParse C.parser_Ymd_lenient "1876z09+27" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Dmy Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse C.parser_Dmy_lenient "01012016" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 1" (dateParse C.parser_Dmy_lenient "01!01@2016" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Passes With Separator 2" (dateParse C.parser_Dmy_lenient "27z09+1876" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Mdy Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (dateParse C.parser_Mdy_lenient "01022016" (Date (Year 2016) (Month 0) (DayOfMonth 2))) , PH.testCase "Passes With Separator 1" (dateParse C.parser_Mdy_lenient "01!02@2016" (Date (Year 2016) (Month 0) (DayOfMonth 2))) , PH.testCase "Passes With Separator 2" (dateParse C.parser_Mdy_lenient "09+27z1876" (Date (Year 1876) (Month 8) (DayOfMonth 27))) ] , testGroup "Builder Spec Tests" $ [ PH.testCase "No Separator" (dateBuilder Nothing "20160101" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Separator 1" (dateBuilder (Just '-') "2016-01-01" (Date (Year 2016) (Month 0) (DayOfMonth 1))) , PH.testCase "Separator 2" (dateBuilder (Just '-') "1876-09-27" (Date (Year 1876) (Month 8) (DayOfMonth 27))) , PH.testCase "zero-pad year" (dateBuilder (Just '-') "0001-01-01" (Date (Year 1) (Month 0) (DayOfMonth 1))) ] , testProperty "Builder Parser Isomorphism (Y-m-d)" $ propEncodeDecodeIso (LText.toStrict . Builder.toLazyText . C.builder_Ymd (Just '-')) (either (const Nothing) Just . Atto.parseOnly (C.parser_Ymd (Just '-'))) ] , testGroup "Datetime" [ testGroup "DmyHMS Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse (C.parser_DmyHMS (DatetimeFormat Nothing Nothing Nothing)) "01022016010223" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse (C.parser_DmyHMS (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02:23" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) ] , testGroup "YmdHMS Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse (C.parser_YmdHMS (DatetimeFormat Nothing Nothing Nothing)) "20160101010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse (C.parser_YmdHMS (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-01 01:02:23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) ] , testGroup "MdyHMS Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse (C.parser_MdyHMS (DatetimeFormat Nothing Nothing Nothing)) "01012016010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse (C.parser_MdyHMS (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-01-2016 01:02:23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) ] , testGroup "DmyHMS Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse C.parser_DmyHMS_lenient "01022016010223" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse C.parser_DmyHMS_lenient "01z02x2016$01;02:23" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_DmyHMS_lenient "01-02-2016 01:02:23" "Failed reading: input does not start with a digit") , PH.testCase "Fails with some nonuniform empty Separators" (datetimeParseFail C.parser_DmyHMS_lenient "01-02-201601:02:23" "Failed reading: satisfy") ] , testGroup "YmdHMS Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse C.parser_YmdHMS_lenient "20160101010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse C.parser_YmdHMS_lenient "2016!01z01^01a02c23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_YmdHMS_lenient "2016-01-02 01:02:03" "Failed reading: input does not start with a digit") ] , testGroup "MdyHMS Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator" (datetimeParse C.parser_MdyHMS_lenient "01012016010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator" (datetimeParse C.parser_MdyHMS_lenient "01z01%2016^01a02c23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_MdyHMS_lenient "01-02-2016 01:02:03" "Failed reading: input does not start with a digit") ] , testGroup "DmyHMS Optional Seconds Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse (C.parser_DmyHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "01022016010223" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse (C.parser_DmyHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "010220160102" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse (C.parser_DmyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02:23" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse (C.parser_DmyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail (C.parser_DmyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02:" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail (C.parser_DmyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02" "Failed reading: input does not start with a digit") ] , testGroup "YmdHMS Optional Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse (C.parser_YmdHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "20160101010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse (C.parser_YmdHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "201601010102" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse (C.parser_YmdHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-01 01:02:23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse (C.parser_YmdHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-01 01:02" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail (C.parser_YmdHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-02 01:02:" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail (C.parser_YmdHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "2016-01-02 01:02" "Failed reading: input does not start with a digit") ] , testGroup "MdyHMS Optional Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse (C.parser_MdyHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "01012016010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse (C.parser_MdyHMS_opt_S (DatetimeFormat Nothing Nothing Nothing)) "010120160102" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse (C.parser_MdyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-01-2016 01:02:23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse (C.parser_MdyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-01-2016 01:02" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail (C.parser_MdyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02:" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail (C.parser_MdyHMS_opt_S (DatetimeFormat (Just '-') (Just ' ') (Just ':'))) "01-02-2016 01:02" "Failed reading: input does not start with a digit") ] , testGroup "DmyHMS Optional Seconds Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator with seconds" (datetimeParse C.parser_DmyHMS_opt_S_lenient "01022016010223" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator without seconds" (datetimeParse C.parser_DmyHMS_opt_S_lenient "010220160102" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator with seconds" (datetimeParse C.parser_DmyHMS_opt_S_lenient "01z02x2016$01;02:23" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator without seconds" (datetimeParse C.parser_DmyHMS_opt_S_lenient "01z02x2016$01;02" $ Datetime (Date (Year 2016) (Month 1) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail C.parser_DmyHMS_opt_S_lenient "01z02x2016$01;02^" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_DmyHMS_opt_S_lenient "01-02-2016 01:02" "Failed reading: input does not start with a digit") ] , testGroup "YmdHMS Optional Seconds Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse C.parser_YmdHMS_opt_S_lenient "20160101010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse C.parser_YmdHMS_opt_S_lenient "201601010102" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse C.parser_YmdHMS_opt_S_lenient "2016!01z01^01a02c23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse C.parser_YmdHMS_opt_S_lenient "2016!01z01^01a02" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail C.parser_YmdHMS_opt_S_lenient "2016!01z01^01a02^" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_YmdHMS_opt_S_lenient "2016-01-02 01:02" "Failed reading: input does not start with a digit") ] , testGroup "MdyHMS Optional Seconds Lenient Parser Spec Tests" $ [ PH.testCase "Passes With No Separator With Seconds" (datetimeParse C.parser_MdyHMS_opt_S_lenient "01012016010223" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With No Separator Without Seconds" (datetimeParse C.parser_MdyHMS_opt_S_lenient "010120160102" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Passes With With Separator With Seconds" (datetimeParse C.parser_MdyHMS_opt_S_lenient "01z01!2016^01a02c23" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 23000000000) ) , PH.testCase "Passes With With Separator Without Seconds" (datetimeParse C.parser_MdyHMS_opt_S_lenient "01z01(2016^01a02" $ Datetime (Date (Year 2016) (Month 0) (DayOfMonth 1)) (TimeOfDay 01 02 0) ) , PH.testCase "Fails with trailing seperator" (datetimeParseFail C.parser_MdyHMS_opt_S_lenient "01z01!2016^01a02^" "not enough input") , PH.testCase "Fails with extra seperators" (datetimeParseFail C.parser_MdyHMS_opt_S_lenient "01-02-2016 01:02" "Failed reading: input does not start with a digit") ] , testGroup "Builder Parser Isomorphism" $ [ testProperty "(Y-m-dTH:M:S)" $ propEncodeDecodeIsoSettings (\format -> LText.toStrict . Builder.toLazyText . C.builder_YmdHMS (SubsecondPrecisionFixed 9) format) (\format -> either (const Nothing) Just . Atto.parseOnly (C.parser_YmdHMS format)) , testProperty "Builder Parser Isomorphism (YmdHMS)" $ propEncodeDecodeIso (LText.toStrict . Builder.toLazyText . C.builder_YmdHMS (SubsecondPrecisionFixed 9) (DatetimeFormat Nothing Nothing Nothing)) (either (const Nothing) Just . Atto.parseOnly (C.parser_YmdHMS (DatetimeFormat Nothing Nothing Nothing))) ] , testProperty "ISO-8601 Roundtrip" $ propEncodeDecodeIso C.encodeShortTextIso8601Zulu (\input -> case C.decodeShortTextIso8601 input of Just (OffsetDatetime dt (Offset 0)) -> Just dt _ -> Nothing ) , testProperty "ISO-8601 Zoneless Roundtrip" $ propEncodeDecodeIso C.encodeShortTextIso8601Zoneless (\input -> case C.decodeShortTextIso8601Zoneless input of Just dt -> Just dt _ -> Nothing ) ] , testGroup "Offset Datetime" [ testGroup "Builder Spec Tests" $ [ PH.testCase "W3C" $ matchBuilder "1997-07-16T19:20:30.450+01:00" $ C.builderW3Cz $ OffsetDatetime ( Datetime ( Date (Year 1997) C.july (DayOfMonth 16) ) ( TimeOfDay 19 20 30450000000 ) ) (Offset 60) ] , testProperty "Builder Parser Isomorphism (YmdHMSz)" $ propEncodeDecodeIsoSettings (\(offsetFormat,datetimeFormat) offsetDatetime -> LText.toStrict $ Builder.toLazyText $ C.builder_YmdHMSz offsetFormat (SubsecondPrecisionFixed 9) datetimeFormat offsetDatetime ) (\(offsetFormat,datetimeFormat) input -> either (const Nothing) Just $ flip Atto.parseOnly input $ C.parser_YmdHMSz offsetFormat datetimeFormat ) ] , testGroup "Posix Time" [ PH.testCase "Get now" $ do now <- C.now assertBool "Current time is the beginning of the epoch." (now /= C.epoch) ] , testGroup "Conversion" [ testGroup "POSIX to Datetime" [ PH.testCase "Epoch" $ C.timeToDatetime (Time 0) @?= Datetime (Date (Year 1970) C.january (DayOfMonth 1)) (TimeOfDay 0 0 0) , PH.testCase "Billion Seconds" $ C.timeToDatetime (Time $ 10 ^ 18) @?= Datetime (Date (Year 2001) C.september (DayOfMonth 9)) (TimeOfDay 1 46 (40 * 10 ^ 9)) , testProperty "Isomorphism" $ propEncodeDecodeFullIso C.timeToDatetime C.datetimeToTime ] ] , testGroup "TimeInterval" [ testGroup "within" [ testProperty "Verify that Time bounds are inside TimeInterval" propWithinInsideInterval , testProperty "Verify that the sum of Time and the span of TimeInterval is outside the interval" propWithinOutsideInterval ] , testGroup "timeIntervalToTimespan" [ PH.testCase "Verify Timespan correctness with TimeInterval" (C.timeIntervalToTimespan (TimeInterval (Time 13) (Time 25)) @?= Timespan 12) , PH.testCase "Verify Timespan correctness with equal TimeInterval bounds" (C.timeIntervalToTimespan (TimeInterval (Time 13) (Time 13)) @?= Timespan 0) , testProperty "Almost isomorphism" propEncodeDecodeTimeInterval ] , testGroup "whole" [ PH.testCase "Verify TimeInterval's bound correctness" (C.whole @?= TimeInterval (Time (minBound :: Int64)) (Time (maxBound :: Int64))) ] , testGroup "singleton" [ testProperty "Verify that upper and lower bound are always equals" propSingletonBoundsEquals ] , testGroup "width" [ testProperty "Verify Time bounds correctness with TimeSpan" propWidthVerifyBounds ] , testGroup "timeIntervalBuilder" [ testProperty "Verify TimeInterval construction correctness" propTimeIntervalBuilder ] ] , testGroup "Datetime Conversions" [ testGroup "datetimeToDayOfWeek" [ PH.testCase "February 2nd 2020" (C.datetimeToDayOfWeek (Datetime (Date (Year 2020) (Month 1) (DayOfMonth 2)) (TimeOfDay 0 0 0)) @?= DayOfWeek 0) , PH.testCase "July 10th 2019" (C.datetimeToDayOfWeek (Datetime (Date (Year 2019) (Month 6) (DayOfMonth 10)) (TimeOfDay 0 0 0)) @?= DayOfWeek 3) , PH.testCase "November 16th 1946" (C.datetimeToDayOfWeek (Datetime (Date (Year 1946) (Month 10) (DayOfMonth 16)) (TimeOfDay 0 0 0)) @?= DayOfWeek 6) , PH.testCase "February 29th 2024 (Leap Year)" (C.datetimeToDayOfWeek (Datetime (Date (Year 2024) (Month 1) (DayOfMonth 29)) (TimeOfDay 0 0 0)) @?= DayOfWeek 4) ] ] , testGroup "timeToDayOfWeek Conversions" [ PH.testCase "Sunday, February 9, 2020 4:00:00 PM" (C.timeToDayOfWeek (Time 1581264000000000000) @?= DayOfWeek 0) , PH.testCase "Monday, April 9, 2001 4:00:00 PM" (C.timeToDayOfWeek (Time 986832000000000000) @?= DayOfWeek 1) , PH.testCase "Tuesday, March 7, 1995 4:00:00 PM" (C.timeToDayOfWeek (Time 794592000000000000) @?= DayOfWeek 2) , PH.testCase "Wednesday, June 17, 1987 4:00:00 PM" (C.timeToDayOfWeek (Time 550944000000000000) @?= DayOfWeek 3) , PH.testCase "Thursday, December 18, 1980 4:00:00 PM" (C.timeToDayOfWeek (Time 346003200000000000) @?= DayOfWeek 4) , PH.testCase "Friday, October 10, 1975 4:00:00 PM" (C.timeToDayOfWeek (Time 182188800000000000) @?= DayOfWeek 5) , PH.testCase "Saturday, August 11, 1973 4:00:00 PM" (C.timeToDayOfWeek (Time 113932800000000000) @?= DayOfWeek 6) , PH.testCase "Thursday, January 1, 1970 12:00:00 AM" (C.timeToDayOfWeek (Time 0) @?= DayOfWeek 4) , PH.testCase "Saturday, June 14, 1969 4:00:00 PM" (C.timeToDayOfWeek (Time (-17308800000000000)) @?= DayOfWeek 6) , PH.testCase "Tuesday, June 6, 1944 4:00:00 PM" (C.timeToDayOfWeek (Time (-806918400000000000)) @?= DayOfWeek 2) ] , testGroup "timeToOffsetDatetime" [ PH.testCase "EpochNeg4h" (C.timeToOffsetDatetime (Offset (-240)) (Time 0) @?= OffsetDatetime ( Datetime ( Date (Year 1969) C.december (DayOfMonth 31) ) ( TimeOfDay 20 0 0 ) ) (Offset (-240)) ) ] , testGroup "json" [ PH.testCase "Datetime" $ let dt = Datetime (Date (Year 3000) (Month 11) (DayOfMonth 31)) (TimeOfDay 0 0 0) in AE.eitherDecode (AE.encode dt) @?= Right dt ] ] failure :: String -> Result failure msg = failed { reason = msg , theException = Nothing } propEncodeDecodeFullIso :: (Eq a,Show a,Show b) => (a -> b) -> (b -> a) -> a -> Result propEncodeDecodeFullIso f g a = let fa = f a gfa = g fa in if gfa == a then succeeded else failure $ concat [ "x: ", show a, "\n" , "f(x): ", show fa, "\n" , "g(f(x)): ", show gfa, "\n" ] propEncodeDecodeIso :: Eq a => (a -> b) -> (b -> Maybe a) -> a -> Bool propEncodeDecodeIso f g a = g (f a) == Just a propEncodeDecodeIsoSettings :: (Eq a,Show a,Show b,Show e) => (e -> a -> b) -> (e -> b -> Maybe a) -> e -> a -> Result propEncodeDecodeIsoSettings f g e a = let fa = f e a gfa = g e fa in if gfa == Just a then succeeded else failure $ concat [ "env: ", show e, "\n" , "x: ", show a, "\n" , "f(x): ", show fa, "\n" , "g(f(x)): ", show gfa, "\n" ] parseMatch :: (Eq a, Show a) => Atto.Parser a -> Text -> a -> Assertion parseMatch p t expected = do Atto.parseOnly (p <* Atto.endOfInput) t @?= Right expected bsParseMatch :: (Eq a, Show a) => AttoBS.Parser a -> ByteString -> a -> Assertion bsParseMatch p t expected = do AttoBS.parseOnly (p <* AttoBS.endOfInput) t @?= Right expected timeOfDayParse :: Maybe Char -> Text -> TimeOfDay -> Assertion timeOfDayParse m t expected = Atto.parseOnly (C.parser_HMS m <* Atto.endOfInput) t @?= Right expected bsTimeOfDayParse :: Maybe Char -> ByteString -> TimeOfDay -> Assertion bsTimeOfDayParse m t expected = AttoBS.parseOnly (C.parserUtf8_HMS m <* AttoBS.endOfInput) t @?= Right expected timeOfDayBuilder :: SubsecondPrecision -> Maybe Char -> Text -> TimeOfDay -> Assertion timeOfDayBuilder sp m expected tod = LText.toStrict (Builder.toLazyText (C.builder_HMS sp m tod)) @?= expected bsTimeOfDayBuilder :: SubsecondPrecision -> Maybe Char -> Text -> TimeOfDay -> Assertion bsTimeOfDayBuilder sp m expected tod = LText.toStrict (Builder.toLazyText (C.builder_HMS sp m tod)) @?= expected dateParse :: Atto.Parser Date -> Text -> Date -> Assertion dateParse p t expected = Atto.parseOnly (p <* Atto.endOfInput) t @?= Right expected dateParseFail : : . Parser Date - > Text - > String - > Assertion t expected = datetimeParse :: Atto.Parser Datetime -> Text -> Datetime -> Assertion datetimeParse p t expected = Atto.parseOnly (p <* Atto.endOfInput) t @?= Right expected datetimeParseFail :: Atto.Parser Datetime -> Text -> String -> Assertion datetimeParseFail p t expected = Atto.parseOnly (p <* Atto.endOfInput) t @?= Left expected dateBuilder :: Maybe Char -> Text -> Date -> Assertion dateBuilder m expected tod = LText.toStrict (Builder.toLazyText (C.builder_Ymd m tod)) @?= expected matchBuilder :: Text -> Builder -> Assertion matchBuilder a b = LText.toStrict (Builder.toLazyText b) @?= a propWithinInsideInterval :: TimeInterval -> Bool propWithinInsideInterval ti@(TimeInterval t0 t1) = C.within t1 ti && C.within t0 ti propWithinOutsideInterval :: RelatedTimes -> Bool propWithinOutsideInterval (RelatedTimes t ti@(TimeInterval t0 t1)) | t == t0 = discard | t == t1 = discard | t1 <= t0 = discard | t0 < (Time 0) = discard | t < (Time 0) = discard | otherwise = let span = C.timeIntervalToTimespan ti tm = T.add span t in not $ C.within tm ti propEncodeDecodeTimeInterval :: TimeInterval -> Bool propEncodeDecodeTimeInterval ti@(TimeInterval t0 t1) | t0 < (Time 0) = discard | t0 >= t1 = discard | otherwise = let span = C.timeIntervalToTimespan ti tm = T.add span t0 in t1 == tm propSingletonBoundsEquals :: Time -> Bool propSingletonBoundsEquals tm = let (TimeInterval (Time ti) (Time te)) = C.singleton tm in ti == te propWidthVerifyBounds :: TimeInterval -> Bool propWidthVerifyBounds ti@(TimeInterval (Time lower) (Time upper)) = let tiWidth = (getTimespan . C.width) ti in T.add lower tiWidth == upper && T.difference upper tiWidth == lower propTimeIntervalBuilder :: Time -> Time -> Bool propTimeIntervalBuilder t0 t1 = let (TimeInterval ti te) = (C.timeIntervalBuilder t0 t1) in (getTime te) >= (getTime ti) instance Arbitrary TimeOfDay where arbitrary = TimeOfDay <$> choose (0,23) <*> choose (0,59) <*> ( do subsecPrecision <- chooseInt (0,9) secs <- chooseInt (0,59) case subsecPrecision of 0 -> pure (fromIntegral @Int @Int64 secs * 1_000_000_000) _ -> do subsecs <- chooseInt (0,((10 :: Int) ^ subsecPrecision) - 1) let subsecs' = subsecs * ((10 :: Int) ^ (9 - subsecPrecision)) if subsecs' < 0 || subsecs' >= 1_000_000_000 then error "Mistake in Arbitrary instance for TimeOfDay" else pure ( (fromIntegral @Int @Int64 secs * 1_000_000_000) + (fromIntegral @Int @Int64 subsecs) ) ) instance Arbitrary Date where arbitrary = Date <$> fmap Year (choose (1800,2100)) <*> fmap Month (choose (0,11)) <*> fmap DayOfMonth (choose (1,28)) instance Arbitrary Datetime where arbitrary = Datetime <$> arbitrary <*> arbitrary < * > choose ( 0,24 * 60 * 60 * 1000000000 - 1 ) instance Arbitrary OffsetDatetime where arbitrary = OffsetDatetime <$> arbitrary <*> arbitrary instance Arbitrary DatetimeFormat where arbitrary = DatetimeFormat <$> elements [Nothing, Just '/', Just ':', Just '-', Just '.'] <*> elements [Nothing, Just '/', Just ':', Just '-', Just 'T'] <*> elements [Nothing, Just ':', Just '-'] shrink (DatetimeFormat a b c) | a == Just '-', b == Just 'T', c == Just ':' = [] | otherwise = [DatetimeFormat (Just '-') (Just 'T') (Just ':')] instance Arbitrary OffsetFormat where arbitrary = arbitraryBoundedEnum shrink = genericShrink deriving instance Arbitrary Time instance Arbitrary TimeInterval where arbitrary = do t0 <- arbitrary t1 <- suchThat arbitrary (>= t0) pure (TimeInterval t0 t1) data RelatedTimes = RelatedTimes Time TimeInterval deriving (Show) instance Arbitrary RelatedTimes where arbitrary = do ti@(TimeInterval t0 t1) <- arbitrary tm <- fmap Time (choose (getTime t0, getTime t1)) pure $ RelatedTimes tm ti instance Arbitrary Offset where arbitrary = fmap Offset (choose ((-24) * 60, 24 * 60))
8f1cc9af640f11b88245c617fd2151ca852e7bf37a5e430fe4862c683388d324
thomanil/clojureTetris
model.clj
(ns clojureTetris.model) FIXME Trim down shape matrices , and factor rotate funs to take any matrix dimensions ( not just 4x4 ) (def base-square-shape [[0 0 0 0] [0 1 1 0] [0 1 1 0] [0 0 0 0]]) (def base-I-shape [[0 0 1 0] [0 0 1 0] [0 0 1 0] [0 0 1 0]]) (def base-S-right-shape [[0 0 0 0] [0 1 1 1] [1 1 1 0] [0 0 0 0]]) (def base-S-left-shape [[0 0 0 0] [1 1 1 0] [0 1 1 1] [0 0 0 0]]) (def base-L-right-shape [[0 0 1 0] [0 0 1 0] [0 1 1 0] [0 0 0 0]]) (def base-L-left-shape [[0 0 1 0] [0 0 1 0] [0 0 1 1] [0 0 0 0]]) (def base-T-shape [[0 0 1 0] [0 1 1 0] [0 0 1 0] [0 0 0 0]]) (defn random-shape [] "Returns a random shape" (let [no-of-shapes 7 dice-roll (rand-int no-of-shapes)] (cond (= dice-roll 0) base-square-shape (= dice-roll 1) base-I-shape (= dice-roll 2) base-S-right-shape (= dice-roll 3) base-S-left-shape (= dice-roll 4) base-L-right-shape (= dice-roll 5) base-L-left-shape (= dice-roll 6) base-T-shape))) FIXME use the flatten fn from core / core 1.2 instead (defn flatten [x] "Takes any nested combination of sequential things (lists, vectors, etc.) and returns their contents as a single, flat sequence. (flatten nil) returns nil." (filter (complement sequential?) (rest (tree-seq sequential? seq x)))) (defn flatten-matrix [matrix] "Turn matrix into flat list" (flatten matrix)) (defn unflatten-matrix [width flat-matrix] "Reconstruct matrix of given width from a flat list" (let [partitioned-matrix (partition width flat-matrix)] (vec(map vec partitioned-matrix)))) (defn xy [x y matrix] "Convenience method for accessing elements within two dimensional vectors" ((matrix y) x)) (defn new-matrix [x y] "Create vector (of vectors), with length x and width y" (let [row (vec (repeat x 0))] (vec (repeat y row)))) (defn matrix-height [matrix] "Determine height of given matrix" (count matrix)) (defn matrix-width [matrix] "Determine width of given matrix" (count (matrix 0))) (defn matrix-contains [matrix value] "Returns true if matrix has at least one occurence of given value" (some #{value} (flatten-matrix matrix))) (defn map-matrix [matrix f] "Runs function f on each element in matrix, returning new matrix with results." (let [mapped-flat-matrix (map f (flatten-matrix matrix)) width (matrix-width matrix) partitioned-matrix (partition width mapped-flat-matrix)] (vec(map vec partitioned-matrix)))) (defn flat-pos [x y matrix] "Turn matrix x y coordinate into x position for corresponding flattened list" (+ x (* y (matrix-height matrix)))) (defn unflat-pos [i matrix] "Turn flat x coord into coordinate for supplied matrix" (let [y (quot i (matrix-width matrix)) x (- i (* y (matrix-width matrix)))] [x y])) (defn piece [x y shape] "Returns new piece structure with given coordinates and shape" {:x x :y y :shape shape}) (defn move [old-piece direction speed] "Returns new piece, with direction updated to move in specified direction" (let [x (old-piece :x) y (old-piece :y) shape (old-piece :shape)] (cond (= direction :left)(piece (- x speed) y shape) (= direction :right)(piece (+ x speed) y shape) (= direction :up)(piece x (- y speed) shape) (= direction :down)(piece x (+ y speed) shape)))) (defn game-over? [field-shape] "Determines if game is over based on shape of given field. If any elements in the top row are filled, the game should end." (let [top-row (field-shape 0)] (some #{1} top-row))) FIXME replace with map - indexed from clojure / core 1.2 "Returns a lazy sequence of [index, item] pairs, where items come from 's' and indexes count up from zero. (indexed '(a b c d)) => ([0 a] [1 b] [2 c] [3 d])" (map vector (iterate inc 0) s)) (defn map-matrix-indexed [matrix f] "Maps each element, supplying the item itself and the x and y coords for that element" (let [flat-indexed-matrix (indexed (flatten-matrix matrix)) mapped-matrix (map (fn [item] (let [item-xy-pos (unflat-pos (item 0) matrix) x (item-xy-pos 0) y (item-xy-pos 1) item-contents (xy x y matrix)] (f (item 1) x y) )) flat-indexed-matrix)] (unflatten-matrix (matrix-width matrix) mapped-matrix))) (defn matrix-each-indexed [matrix f] "Run function for each element in matrix, supplying element and x and y coords" (map-matrix-indexed matrix (fn [state x y] (f state x y)))) (defn rotated-clockwise [m] "nth dest row = every nth element of each src row" [[(xy 0 3 m) (xy 0 2 m) (xy 0 1 m) (xy 0 0 m)] [(xy 1 3 m) (xy 1 2 m) (xy 1 1 m) (xy 1 0 m)] [(xy 2 3 m) (xy 2 2 m) (xy 2 1 m) (xy 2 0 m)] [(xy 3 3 m) (xy 3 2 m) (xy 3 1 m) (xy 3 0 m)]]) (defn outside-matrix? [x y matrix] "Convenience method for accessing elements within two dimensional vectors" (let [height (matrix-height matrix) width (matrix-width matrix)] (if (or (< x 0) (< y 0) (> x (- width 1)) (> y (- height 1))) true false))) (defn field-overlap? [piece field] "Checks if set any tiles in the piece shape overlaps corresponding set tiles in the enclosing field" (let [tile-overlap-mask (map-matrix-indexed (piece :shape) (fn [tile-state tile-x tile-y] (let [field-x (+ (piece :x) tile-x) field-y (+ (piece :y) tile-y)] (when (and (= tile-state 1) (not(outside-matrix? field-x field-y field))) (+ (xy field-x field-y field) tile-state)))))] (some #{2} (flatten tile-overlap-mask)))) (defn outside-field? [piece field] "Checks if any part of the given piece is outside the playing field" (let [tiles-outside-mask (map-matrix-indexed (piece :shape) (fn [tile-state tile-x tile-y] (when (= tile-state 1) (let [field-x (+ (piece :x) tile-x) field-y (+ (piece :y) tile-y)] (outside-matrix? field-x field-y field)))))] (some #{true} (flatten tiles-outside-mask)))) (defn merge-into [piece field] "Sticky collision with playing field, merge given piece shape into field in the pieces current position" (map-matrix-indexed field (fn [field-state field-x field-y] (let [x-pos-in-piece (- field-x (piece :x)) y-pos-in-piece (- field-y (piece :y)) piece-matrix (piece :shape)] (if (and (>= x-pos-in-piece 0) (>= y-pos-in-piece 0) (< x-pos-in-piece (matrix-width piece-matrix)) (< y-pos-in-piece (matrix-height piece-matrix))) (max field-state (xy x-pos-in-piece y-pos-in-piece piece-matrix)) field-state))))) (defn will-stick? [piece direction speed field] "Checks if placing a piece matrix in xy pos within a (larger) field matrix yields a stuck piece. True if one or several solid piece elements right above field bottom or any solid field elements" (if (= direction :down) (let [moved-piece (move piece :down speed)] (or (field-overlap? moved-piece field) (outside-field? moved-piece field))) false)) (defn list-of-full-rows [field] "Returns list of y coordinates of the rows which are full in given field" (let [detected-rows (map (fn [row] (let [sum-of-row (apply + (row 1))] (if (= sum-of-row (matrix-width field)) (row 0) -1)))(indexed field))] (vec(remove #{-1} detected-rows)))) (defn clear-full-rows [field] "Returns field which is cleared of full rows and shuffled accordingly each recursion: find first full row in current field drop that row, concat an empty row on top continue until no more full rows remain" (let [drop-nth-row (fn [n matrix] (vec(concat (take n matrix) (drop (+ n 1) matrix))))] (loop [shuffled-field field] (if (empty? (list-of-full-rows shuffled-field)) shuffled-field (recur (vec(concat [(vec (repeat (matrix-width field) 0))] (drop-nth-row ((list-of-full-rows shuffled-field) 0) shuffled-field))))))))
null
https://raw.githubusercontent.com/thomanil/clojureTetris/6cd9ba6750261e4790cfd7af5c146ba028d370cd/src/clojureTetris/model.clj
clojure
(ns clojureTetris.model) FIXME Trim down shape matrices , and factor rotate funs to take any matrix dimensions ( not just 4x4 ) (def base-square-shape [[0 0 0 0] [0 1 1 0] [0 1 1 0] [0 0 0 0]]) (def base-I-shape [[0 0 1 0] [0 0 1 0] [0 0 1 0] [0 0 1 0]]) (def base-S-right-shape [[0 0 0 0] [0 1 1 1] [1 1 1 0] [0 0 0 0]]) (def base-S-left-shape [[0 0 0 0] [1 1 1 0] [0 1 1 1] [0 0 0 0]]) (def base-L-right-shape [[0 0 1 0] [0 0 1 0] [0 1 1 0] [0 0 0 0]]) (def base-L-left-shape [[0 0 1 0] [0 0 1 0] [0 0 1 1] [0 0 0 0]]) (def base-T-shape [[0 0 1 0] [0 1 1 0] [0 0 1 0] [0 0 0 0]]) (defn random-shape [] "Returns a random shape" (let [no-of-shapes 7 dice-roll (rand-int no-of-shapes)] (cond (= dice-roll 0) base-square-shape (= dice-roll 1) base-I-shape (= dice-roll 2) base-S-right-shape (= dice-roll 3) base-S-left-shape (= dice-roll 4) base-L-right-shape (= dice-roll 5) base-L-left-shape (= dice-roll 6) base-T-shape))) FIXME use the flatten fn from core / core 1.2 instead (defn flatten [x] "Takes any nested combination of sequential things (lists, vectors, etc.) and returns their contents as a single, flat sequence. (flatten nil) returns nil." (filter (complement sequential?) (rest (tree-seq sequential? seq x)))) (defn flatten-matrix [matrix] "Turn matrix into flat list" (flatten matrix)) (defn unflatten-matrix [width flat-matrix] "Reconstruct matrix of given width from a flat list" (let [partitioned-matrix (partition width flat-matrix)] (vec(map vec partitioned-matrix)))) (defn xy [x y matrix] "Convenience method for accessing elements within two dimensional vectors" ((matrix y) x)) (defn new-matrix [x y] "Create vector (of vectors), with length x and width y" (let [row (vec (repeat x 0))] (vec (repeat y row)))) (defn matrix-height [matrix] "Determine height of given matrix" (count matrix)) (defn matrix-width [matrix] "Determine width of given matrix" (count (matrix 0))) (defn matrix-contains [matrix value] "Returns true if matrix has at least one occurence of given value" (some #{value} (flatten-matrix matrix))) (defn map-matrix [matrix f] "Runs function f on each element in matrix, returning new matrix with results." (let [mapped-flat-matrix (map f (flatten-matrix matrix)) width (matrix-width matrix) partitioned-matrix (partition width mapped-flat-matrix)] (vec(map vec partitioned-matrix)))) (defn flat-pos [x y matrix] "Turn matrix x y coordinate into x position for corresponding flattened list" (+ x (* y (matrix-height matrix)))) (defn unflat-pos [i matrix] "Turn flat x coord into coordinate for supplied matrix" (let [y (quot i (matrix-width matrix)) x (- i (* y (matrix-width matrix)))] [x y])) (defn piece [x y shape] "Returns new piece structure with given coordinates and shape" {:x x :y y :shape shape}) (defn move [old-piece direction speed] "Returns new piece, with direction updated to move in specified direction" (let [x (old-piece :x) y (old-piece :y) shape (old-piece :shape)] (cond (= direction :left)(piece (- x speed) y shape) (= direction :right)(piece (+ x speed) y shape) (= direction :up)(piece x (- y speed) shape) (= direction :down)(piece x (+ y speed) shape)))) (defn game-over? [field-shape] "Determines if game is over based on shape of given field. If any elements in the top row are filled, the game should end." (let [top-row (field-shape 0)] (some #{1} top-row))) FIXME replace with map - indexed from clojure / core 1.2 "Returns a lazy sequence of [index, item] pairs, where items come from 's' and indexes count up from zero. (indexed '(a b c d)) => ([0 a] [1 b] [2 c] [3 d])" (map vector (iterate inc 0) s)) (defn map-matrix-indexed [matrix f] "Maps each element, supplying the item itself and the x and y coords for that element" (let [flat-indexed-matrix (indexed (flatten-matrix matrix)) mapped-matrix (map (fn [item] (let [item-xy-pos (unflat-pos (item 0) matrix) x (item-xy-pos 0) y (item-xy-pos 1) item-contents (xy x y matrix)] (f (item 1) x y) )) flat-indexed-matrix)] (unflatten-matrix (matrix-width matrix) mapped-matrix))) (defn matrix-each-indexed [matrix f] "Run function for each element in matrix, supplying element and x and y coords" (map-matrix-indexed matrix (fn [state x y] (f state x y)))) (defn rotated-clockwise [m] "nth dest row = every nth element of each src row" [[(xy 0 3 m) (xy 0 2 m) (xy 0 1 m) (xy 0 0 m)] [(xy 1 3 m) (xy 1 2 m) (xy 1 1 m) (xy 1 0 m)] [(xy 2 3 m) (xy 2 2 m) (xy 2 1 m) (xy 2 0 m)] [(xy 3 3 m) (xy 3 2 m) (xy 3 1 m) (xy 3 0 m)]]) (defn outside-matrix? [x y matrix] "Convenience method for accessing elements within two dimensional vectors" (let [height (matrix-height matrix) width (matrix-width matrix)] (if (or (< x 0) (< y 0) (> x (- width 1)) (> y (- height 1))) true false))) (defn field-overlap? [piece field] "Checks if set any tiles in the piece shape overlaps corresponding set tiles in the enclosing field" (let [tile-overlap-mask (map-matrix-indexed (piece :shape) (fn [tile-state tile-x tile-y] (let [field-x (+ (piece :x) tile-x) field-y (+ (piece :y) tile-y)] (when (and (= tile-state 1) (not(outside-matrix? field-x field-y field))) (+ (xy field-x field-y field) tile-state)))))] (some #{2} (flatten tile-overlap-mask)))) (defn outside-field? [piece field] "Checks if any part of the given piece is outside the playing field" (let [tiles-outside-mask (map-matrix-indexed (piece :shape) (fn [tile-state tile-x tile-y] (when (= tile-state 1) (let [field-x (+ (piece :x) tile-x) field-y (+ (piece :y) tile-y)] (outside-matrix? field-x field-y field)))))] (some #{true} (flatten tiles-outside-mask)))) (defn merge-into [piece field] "Sticky collision with playing field, merge given piece shape into field in the pieces current position" (map-matrix-indexed field (fn [field-state field-x field-y] (let [x-pos-in-piece (- field-x (piece :x)) y-pos-in-piece (- field-y (piece :y)) piece-matrix (piece :shape)] (if (and (>= x-pos-in-piece 0) (>= y-pos-in-piece 0) (< x-pos-in-piece (matrix-width piece-matrix)) (< y-pos-in-piece (matrix-height piece-matrix))) (max field-state (xy x-pos-in-piece y-pos-in-piece piece-matrix)) field-state))))) (defn will-stick? [piece direction speed field] "Checks if placing a piece matrix in xy pos within a (larger) field matrix yields a stuck piece. True if one or several solid piece elements right above field bottom or any solid field elements" (if (= direction :down) (let [moved-piece (move piece :down speed)] (or (field-overlap? moved-piece field) (outside-field? moved-piece field))) false)) (defn list-of-full-rows [field] "Returns list of y coordinates of the rows which are full in given field" (let [detected-rows (map (fn [row] (let [sum-of-row (apply + (row 1))] (if (= sum-of-row (matrix-width field)) (row 0) -1)))(indexed field))] (vec(remove #{-1} detected-rows)))) (defn clear-full-rows [field] "Returns field which is cleared of full rows and shuffled accordingly each recursion: find first full row in current field drop that row, concat an empty row on top continue until no more full rows remain" (let [drop-nth-row (fn [n matrix] (vec(concat (take n matrix) (drop (+ n 1) matrix))))] (loop [shuffled-field field] (if (empty? (list-of-full-rows shuffled-field)) shuffled-field (recur (vec(concat [(vec (repeat (matrix-width field) 0))] (drop-nth-row ((list-of-full-rows shuffled-field) 0) shuffled-field))))))))
58888586f9449974baa36d07fdaa158eb836bc050949ed286fb68b60b31b6e37
OCamlPro/ocp-build
buildOCamlMeta.mli
(**************************************************************************) (* *) (* Typerex Tools *) (* *) Copyright 2011 - 2017 OCamlPro SAS (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU General Public License version 3 described in the file (* LICENSE. *) (* *) (**************************************************************************) val load_META_files : BuildOCP.state -> string -> string -> unit
null
https://raw.githubusercontent.com/OCamlPro/ocp-build/56aff560bb438c12b2929feaf8379bc6f31b9840/tools/ocp-build/ocaml/buildOCamlMeta.mli
ocaml
************************************************************************ Typerex Tools All rights reserved. This file is distributed under the terms of LICENSE. ************************************************************************
Copyright 2011 - 2017 OCamlPro SAS the GNU General Public License version 3 described in the file val load_META_files : BuildOCP.state -> string -> string -> unit
95b501b5d4dd1dc0c2a8a3a4ee76619bc27bbe8dfeec18b739602c2b1ca4410c
plumatic/plumbing
positional.clj
(ns plumbing.graph.positional "A compilation method for graphs that avoids maps for speed. Prone to failure for graphs with more nodes than `max-graph-size`." (:use plumbing.core) (:require [schema.core :as s] [plumbing.fnk.schema :as schema] [plumbing.fnk.pfnk :as pfnk] [plumbing.fnk.impl :as fnk-impl]) (:import clojure.lang.IFn)) (def max-graph-size "The positional compilation algorithm provided by this namespace reliably succeeds only with graphs with `max-graph-size` or less nodes. The basic strategy is to generate a defrecord field for each node (of which there is a limit of around 120) and then generate a constructor function (whose code size grows linearly in the number of nodes)." 100) (defn def-graph-record "Define a record for the output of a graph. It is usable as a function to be as close to a map as possible. Return the typename." ([g] (def-graph-record g (gensym "graph-record"))) ([g record-type-name] ;; NOTE: This eval is needed because we want to define a record based on ;; information (a graph) that's only available at runtime. (eval `(defrecord ~record-type-name ~(->> g pfnk/output-schema keys (mapv (comp symbol name))) IFn (invoke [this# k#] (get this# k#)) (invoke [this# k# not-found#] (get this# k# not-found#)) (applyTo [this# args#] (apply get this# args#)))) record-type-name)) (defn graph-let-bindings "Compute the bindings for functions and intermediates needed to form the body of a positional graph, E.g. [`[[f-3 ~some-function]] `[[intermediate-3 (f-3 intermediate-1 intermediate-2)]]]" [g g-value-syms] (->> g (map (fn [[kw f]] (let [f-sym (-> kw name (str "-fn") gensym) arg-forms (map-from-keys g-value-syms (pfnk/input-schema-keys f)) [f arg-forms] (fnk-impl/efficient-call-forms f arg-forms)] [[f-sym f] [(g-value-syms kw) (cons f-sym arg-forms)]]))) (apply map vector))) (defn eval-bound "Evaluate a form with some symbols bound to some values." [form bindings] ((eval `(fn [~(mapv first bindings)] ~form)) (map second bindings))) (defn graph-form "Construct [body-form bindings-needed-for-eval] for a positional graph." [g arg-keywords] (let [value-syms (->> g pfnk/io-schemata (mapcat schema/explicit-schema-key-map) (map key) (map-from-keys (comp gensym name))) [needed-bindings value-bindings] (graph-let-bindings g value-syms) record-type (def-graph-record g)] [`(fn positional-graph# ;; Name it just for kicks. ~(mapv value-syms arg-keywords) (let ~(vec (apply concat value-bindings)) (new ~record-type ~@(->> g pfnk/output-schema keys (mapv value-syms))))) needed-bindings])) (defn positional-flat-compile "Positional compile for a flat (non-nested) graph." [g] (let [arg-ks (->> g pfnk/input-schema-keys) [positional-fn-form eval-bindings] (graph-form g arg-ks) input-schema (pfnk/input-schema g) pos-fn-sym (gensym "pos") input-schema-sym (gensym "input-schema") output-schema-sym (gensym "output-schema")] (vary-meta ;; workaround evaluation quirks (eval-bound `(let [~pos-fn-sym ~positional-fn-form] ~(fnk-impl/positional-fnk-form (fnk-impl/schema-override 'graph-positional output-schema-sym) input-schema-sym (vec (schema/explicit-schema-key-map input-schema)) (into {} (for [k (keys (schema/explicit-schema-key-map input-schema))] [k (symbol (name k))])) (list `(~pos-fn-sym ~@(mapv (comp symbol name) arg-ks))) nil)) (into eval-bindings [[input-schema-sym input-schema] [output-schema-sym (pfnk/output-schema g)]])) assoc :schema (let [[is os] (pfnk/io-schemata g)] (s/=> os is)))))
null
https://raw.githubusercontent.com/plumatic/plumbing/e0fbe3dbe47a7d52e7bfbf2e94edffbed5351308/src/plumbing/graph/positional.clj
clojure
NOTE: This eval is needed because we want to define a record based on information (a graph) that's only available at runtime. Name it just for kicks. workaround evaluation quirks
(ns plumbing.graph.positional "A compilation method for graphs that avoids maps for speed. Prone to failure for graphs with more nodes than `max-graph-size`." (:use plumbing.core) (:require [schema.core :as s] [plumbing.fnk.schema :as schema] [plumbing.fnk.pfnk :as pfnk] [plumbing.fnk.impl :as fnk-impl]) (:import clojure.lang.IFn)) (def max-graph-size "The positional compilation algorithm provided by this namespace reliably succeeds only with graphs with `max-graph-size` or less nodes. The basic strategy is to generate a defrecord field for each node (of which there is a limit of around 120) and then generate a constructor function (whose code size grows linearly in the number of nodes)." 100) (defn def-graph-record "Define a record for the output of a graph. It is usable as a function to be as close to a map as possible. Return the typename." ([g] (def-graph-record g (gensym "graph-record"))) ([g record-type-name] (eval `(defrecord ~record-type-name ~(->> g pfnk/output-schema keys (mapv (comp symbol name))) IFn (invoke [this# k#] (get this# k#)) (invoke [this# k# not-found#] (get this# k# not-found#)) (applyTo [this# args#] (apply get this# args#)))) record-type-name)) (defn graph-let-bindings "Compute the bindings for functions and intermediates needed to form the body of a positional graph, E.g. [`[[f-3 ~some-function]] `[[intermediate-3 (f-3 intermediate-1 intermediate-2)]]]" [g g-value-syms] (->> g (map (fn [[kw f]] (let [f-sym (-> kw name (str "-fn") gensym) arg-forms (map-from-keys g-value-syms (pfnk/input-schema-keys f)) [f arg-forms] (fnk-impl/efficient-call-forms f arg-forms)] [[f-sym f] [(g-value-syms kw) (cons f-sym arg-forms)]]))) (apply map vector))) (defn eval-bound "Evaluate a form with some symbols bound to some values." [form bindings] ((eval `(fn [~(mapv first bindings)] ~form)) (map second bindings))) (defn graph-form "Construct [body-form bindings-needed-for-eval] for a positional graph." [g arg-keywords] (let [value-syms (->> g pfnk/io-schemata (mapcat schema/explicit-schema-key-map) (map key) (map-from-keys (comp gensym name))) [needed-bindings value-bindings] (graph-let-bindings g value-syms) record-type (def-graph-record g)] [`(fn ~(mapv value-syms arg-keywords) (let ~(vec (apply concat value-bindings)) (new ~record-type ~@(->> g pfnk/output-schema keys (mapv value-syms))))) needed-bindings])) (defn positional-flat-compile "Positional compile for a flat (non-nested) graph." [g] (let [arg-ks (->> g pfnk/input-schema-keys) [positional-fn-form eval-bindings] (graph-form g arg-ks) input-schema (pfnk/input-schema g) pos-fn-sym (gensym "pos") input-schema-sym (gensym "input-schema") output-schema-sym (gensym "output-schema")] (eval-bound `(let [~pos-fn-sym ~positional-fn-form] ~(fnk-impl/positional-fnk-form (fnk-impl/schema-override 'graph-positional output-schema-sym) input-schema-sym (vec (schema/explicit-schema-key-map input-schema)) (into {} (for [k (keys (schema/explicit-schema-key-map input-schema))] [k (symbol (name k))])) (list `(~pos-fn-sym ~@(mapv (comp symbol name) arg-ks))) nil)) (into eval-bindings [[input-schema-sym input-schema] [output-schema-sym (pfnk/output-schema g)]])) assoc :schema (let [[is os] (pfnk/io-schemata g)] (s/=> os is)))))
c66a3c300edd5b38adc4fc5233da36200715cbe5280e520a9e14533fe57337a7
rizo/snowflake-os
lexing.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , 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 Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ I d : lexing.ml , v 1.24 2005 - 10 - 25 18:34:07 doligez Exp $ (* The run-time library for lexers generated by camllex *) type position = { pos_fname : string; pos_lnum : int; pos_bol : int; pos_cnum : int; } let dummy_pos = { pos_fname = ""; pos_lnum = 0; pos_bol = 0; pos_cnum = -1; } type lexbuf = { refill_buff : lexbuf -> unit; mutable lex_buffer : string; mutable lex_buffer_len : int; mutable lex_abs_pos : int; mutable lex_start_pos : int; mutable lex_curr_pos : int; mutable lex_last_pos : int; mutable lex_last_action : int; mutable lex_eof_reached : bool; mutable lex_mem : int array; mutable lex_start_p : position; mutable lex_curr_p : position; } type lex_tables = { lex_base: string; lex_backtrk: string; lex_default: string; lex_trans: string; lex_check: string; lex_base_code : string; lex_backtrk_code : string; lex_default_code : string; lex_trans_code : string; lex_check_code : string; lex_code: string;} external c_engine : lex_tables -> int -> lexbuf -> int = "caml_lex_engine" external c_new_engine : lex_tables -> int -> lexbuf -> int = "caml_new_lex_engine" let engine tbl state buf = let result = c_engine tbl state buf in if result >= 0 then begin buf.lex_start_p <- buf.lex_curr_p; buf.lex_curr_p <- {buf.lex_curr_p with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos}; end; result ;; let new_engine tbl state buf = let result = c_new_engine tbl state buf in if result >= 0 then begin buf.lex_start_p <- buf.lex_curr_p; buf.lex_curr_p <- {buf.lex_curr_p with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos}; end; result ;; let lex_refill read_fun aux_buffer lexbuf = let read = read_fun aux_buffer (String.length aux_buffer) in let n = if read > 0 then read else (lexbuf.lex_eof_reached <- true; 0) in Current state of the buffer : < -------|---------------------|----------- > | junk | valid data | junk | ^ ^ ^ ^ 0 start_pos buffer_end String.length buffer <-------|---------------------|-----------> | junk | valid data | junk | ^ ^ ^ ^ 0 start_pos buffer_end String.length buffer *) if lexbuf.lex_buffer_len + n > String.length lexbuf.lex_buffer then begin (* There is not enough space at the end of the buffer *) if lexbuf.lex_buffer_len - lexbuf.lex_start_pos + n <= String.length lexbuf.lex_buffer then begin (* But there is enough space if we reclaim the junk at the beginning of the buffer *) String.blit lexbuf.lex_buffer lexbuf.lex_start_pos lexbuf.lex_buffer 0 (lexbuf.lex_buffer_len - lexbuf.lex_start_pos) end else begin We must grow the buffer . Doubling its size will provide enough space since n < = String.length aux_buffer < = String.length buffer . Watch out for string length overflow , though . space since n <= String.length aux_buffer <= String.length buffer. Watch out for string length overflow, though. *) let newlen = min (2 * String.length lexbuf.lex_buffer) Sys.max_string_length in if lexbuf.lex_buffer_len - lexbuf.lex_start_pos + n > newlen then failwith "Lexing.lex_refill: cannot grow buffer"; let newbuf = String.create newlen in (* Copy the valid data to the beginning of the new buffer *) String.blit lexbuf.lex_buffer lexbuf.lex_start_pos newbuf 0 (lexbuf.lex_buffer_len - lexbuf.lex_start_pos); lexbuf.lex_buffer <- newbuf end; (* Reallocation or not, we have shifted the data left by start_pos characters; update the positions *) let s = lexbuf.lex_start_pos in lexbuf.lex_abs_pos <- lexbuf.lex_abs_pos + s; lexbuf.lex_curr_pos <- lexbuf.lex_curr_pos - s; lexbuf.lex_start_pos <- 0; lexbuf.lex_last_pos <- lexbuf.lex_last_pos - s; lexbuf.lex_buffer_len <- lexbuf.lex_buffer_len - s ; let t = lexbuf.lex_mem in for i = 0 to Array.length t-1 do let v = t.(i) in if v >= 0 then t.(i) <- v-s done end; (* There is now enough space at the end of the buffer *) String.blit aux_buffer 0 lexbuf.lex_buffer lexbuf.lex_buffer_len n; lexbuf.lex_buffer_len <- lexbuf.lex_buffer_len + n let zero_pos = { pos_fname = ""; pos_lnum = 1; pos_bol = 0; pos_cnum = 0; };; let from_function f = { refill_buff = lex_refill f (String.create 512); lex_buffer = String.create 1024; lex_buffer_len = 0; lex_abs_pos = 0; lex_start_pos = 0; lex_curr_pos = 0; lex_last_pos = 0; lex_last_action = 0; lex_mem = [||]; lex_eof_reached = false; lex_start_p = zero_pos; lex_curr_p = zero_pos; } let from_channel ic = from_function (fun buf n -> input ic buf 0 n) let from_string s = { refill_buff = (fun lexbuf -> lexbuf.lex_eof_reached <- true); lex_buffer = s ^ ""; lex_buffer_len = String.length s; lex_abs_pos = 0; lex_start_pos = 0; lex_curr_pos = 0; lex_last_pos = 0; lex_last_action = 0; lex_mem = [||]; lex_eof_reached = true; lex_start_p = zero_pos; lex_curr_p = zero_pos; } let lexeme lexbuf = let len = lexbuf.lex_curr_pos - lexbuf.lex_start_pos in let s = String.create len in String.unsafe_blit lexbuf.lex_buffer lexbuf.lex_start_pos s 0 len; s let sub_lexeme lexbuf i1 i2 = let len = i2-i1 in let s = String.create len in String.unsafe_blit lexbuf.lex_buffer i1 s 0 len; s let sub_lexeme_opt lexbuf i1 i2 = if i1 >= 0 then begin let len = i2-i1 in let s = String.create len in String.unsafe_blit lexbuf.lex_buffer i1 s 0 len; Some s end else begin None end let sub_lexeme_char lexbuf i = lexbuf.lex_buffer.[i] let sub_lexeme_char_opt lexbuf i = if i >= 0 then Some lexbuf.lex_buffer.[i] else None let lexeme_char lexbuf i = String.get lexbuf.lex_buffer (lexbuf.lex_start_pos + i) let lexeme_start lexbuf = lexbuf.lex_start_p.pos_cnum;; let lexeme_end lexbuf = lexbuf.lex_curr_p.pos_cnum;; let lexeme_start_p lexbuf = lexbuf.lex_start_p;; let lexeme_end_p lexbuf = lexbuf.lex_curr_p;; (* Discard data left in lexer buffer. *) let flush_input lb = lb.lex_curr_pos <- 0; lb.lex_abs_pos <- 0; lb.lex_curr_p <- {lb.lex_curr_p with pos_cnum = 0}; lb.lex_buffer_len <- 0; ;;
null
https://raw.githubusercontent.com/rizo/snowflake-os/51df43d9ba715532d325e8880d3b8b2c589cd075/libraries/stdlib/lexing.ml
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* The run-time library for lexers generated by camllex There is not enough space at the end of the buffer But there is enough space if we reclaim the junk at the beginning of the buffer Copy the valid data to the beginning of the new buffer Reallocation or not, we have shifted the data left by start_pos characters; update the positions There is now enough space at the end of the buffer Discard data left in lexer buffer.
, 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 Library General Public License , with $ I d : lexing.ml , v 1.24 2005 - 10 - 25 18:34:07 doligez Exp $ type position = { pos_fname : string; pos_lnum : int; pos_bol : int; pos_cnum : int; } let dummy_pos = { pos_fname = ""; pos_lnum = 0; pos_bol = 0; pos_cnum = -1; } type lexbuf = { refill_buff : lexbuf -> unit; mutable lex_buffer : string; mutable lex_buffer_len : int; mutable lex_abs_pos : int; mutable lex_start_pos : int; mutable lex_curr_pos : int; mutable lex_last_pos : int; mutable lex_last_action : int; mutable lex_eof_reached : bool; mutable lex_mem : int array; mutable lex_start_p : position; mutable lex_curr_p : position; } type lex_tables = { lex_base: string; lex_backtrk: string; lex_default: string; lex_trans: string; lex_check: string; lex_base_code : string; lex_backtrk_code : string; lex_default_code : string; lex_trans_code : string; lex_check_code : string; lex_code: string;} external c_engine : lex_tables -> int -> lexbuf -> int = "caml_lex_engine" external c_new_engine : lex_tables -> int -> lexbuf -> int = "caml_new_lex_engine" let engine tbl state buf = let result = c_engine tbl state buf in if result >= 0 then begin buf.lex_start_p <- buf.lex_curr_p; buf.lex_curr_p <- {buf.lex_curr_p with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos}; end; result ;; let new_engine tbl state buf = let result = c_new_engine tbl state buf in if result >= 0 then begin buf.lex_start_p <- buf.lex_curr_p; buf.lex_curr_p <- {buf.lex_curr_p with pos_cnum = buf.lex_abs_pos + buf.lex_curr_pos}; end; result ;; let lex_refill read_fun aux_buffer lexbuf = let read = read_fun aux_buffer (String.length aux_buffer) in let n = if read > 0 then read else (lexbuf.lex_eof_reached <- true; 0) in Current state of the buffer : < -------|---------------------|----------- > | junk | valid data | junk | ^ ^ ^ ^ 0 start_pos buffer_end String.length buffer <-------|---------------------|-----------> | junk | valid data | junk | ^ ^ ^ ^ 0 start_pos buffer_end String.length buffer *) if lexbuf.lex_buffer_len + n > String.length lexbuf.lex_buffer then begin if lexbuf.lex_buffer_len - lexbuf.lex_start_pos + n <= String.length lexbuf.lex_buffer then begin String.blit lexbuf.lex_buffer lexbuf.lex_start_pos lexbuf.lex_buffer 0 (lexbuf.lex_buffer_len - lexbuf.lex_start_pos) end else begin We must grow the buffer . Doubling its size will provide enough space since n < = String.length aux_buffer < = String.length buffer . Watch out for string length overflow , though . space since n <= String.length aux_buffer <= String.length buffer. Watch out for string length overflow, though. *) let newlen = min (2 * String.length lexbuf.lex_buffer) Sys.max_string_length in if lexbuf.lex_buffer_len - lexbuf.lex_start_pos + n > newlen then failwith "Lexing.lex_refill: cannot grow buffer"; let newbuf = String.create newlen in String.blit lexbuf.lex_buffer lexbuf.lex_start_pos newbuf 0 (lexbuf.lex_buffer_len - lexbuf.lex_start_pos); lexbuf.lex_buffer <- newbuf end; let s = lexbuf.lex_start_pos in lexbuf.lex_abs_pos <- lexbuf.lex_abs_pos + s; lexbuf.lex_curr_pos <- lexbuf.lex_curr_pos - s; lexbuf.lex_start_pos <- 0; lexbuf.lex_last_pos <- lexbuf.lex_last_pos - s; lexbuf.lex_buffer_len <- lexbuf.lex_buffer_len - s ; let t = lexbuf.lex_mem in for i = 0 to Array.length t-1 do let v = t.(i) in if v >= 0 then t.(i) <- v-s done end; String.blit aux_buffer 0 lexbuf.lex_buffer lexbuf.lex_buffer_len n; lexbuf.lex_buffer_len <- lexbuf.lex_buffer_len + n let zero_pos = { pos_fname = ""; pos_lnum = 1; pos_bol = 0; pos_cnum = 0; };; let from_function f = { refill_buff = lex_refill f (String.create 512); lex_buffer = String.create 1024; lex_buffer_len = 0; lex_abs_pos = 0; lex_start_pos = 0; lex_curr_pos = 0; lex_last_pos = 0; lex_last_action = 0; lex_mem = [||]; lex_eof_reached = false; lex_start_p = zero_pos; lex_curr_p = zero_pos; } let from_channel ic = from_function (fun buf n -> input ic buf 0 n) let from_string s = { refill_buff = (fun lexbuf -> lexbuf.lex_eof_reached <- true); lex_buffer = s ^ ""; lex_buffer_len = String.length s; lex_abs_pos = 0; lex_start_pos = 0; lex_curr_pos = 0; lex_last_pos = 0; lex_last_action = 0; lex_mem = [||]; lex_eof_reached = true; lex_start_p = zero_pos; lex_curr_p = zero_pos; } let lexeme lexbuf = let len = lexbuf.lex_curr_pos - lexbuf.lex_start_pos in let s = String.create len in String.unsafe_blit lexbuf.lex_buffer lexbuf.lex_start_pos s 0 len; s let sub_lexeme lexbuf i1 i2 = let len = i2-i1 in let s = String.create len in String.unsafe_blit lexbuf.lex_buffer i1 s 0 len; s let sub_lexeme_opt lexbuf i1 i2 = if i1 >= 0 then begin let len = i2-i1 in let s = String.create len in String.unsafe_blit lexbuf.lex_buffer i1 s 0 len; Some s end else begin None end let sub_lexeme_char lexbuf i = lexbuf.lex_buffer.[i] let sub_lexeme_char_opt lexbuf i = if i >= 0 then Some lexbuf.lex_buffer.[i] else None let lexeme_char lexbuf i = String.get lexbuf.lex_buffer (lexbuf.lex_start_pos + i) let lexeme_start lexbuf = lexbuf.lex_start_p.pos_cnum;; let lexeme_end lexbuf = lexbuf.lex_curr_p.pos_cnum;; let lexeme_start_p lexbuf = lexbuf.lex_start_p;; let lexeme_end_p lexbuf = lexbuf.lex_curr_p;; let flush_input lb = lb.lex_curr_pos <- 0; lb.lex_abs_pos <- 0; lb.lex_curr_p <- {lb.lex_curr_p with pos_cnum = 0}; lb.lex_buffer_len <- 0; ;;
f15aa7801dfa96d2f3d442d3e40dd0bc9204e07671d0345404ed1cf45a2bccaa
inaka/elvis_core
fail_export_used_types.erl
-module fail_export_used_types. -type my_type() :: my | type. -export [my_fun/1]. -spec my_fun(my_type()) -> my_type(). my_fun(my) -> type; my_fun(type) -> my.
null
https://raw.githubusercontent.com/inaka/elvis_core/72df3ba9dae03cb070fa7af3b266c38bb3095778/test/examples/fail_export_used_types.erl
erlang
-module fail_export_used_types. -type my_type() :: my | type. -export [my_fun/1]. -spec my_fun(my_type()) -> my_type(). my_fun(my) -> type; my_fun(type) -> my.
ab49e924ecb11d0f8d9f0d02ceb7cac2d61183d2c6cd210e9125d0214ccffd9c
ocaml/dune
x.ml
let buy_it = "buy " ^ Lib.Y.it let () = print_endline buy_it
null
https://raw.githubusercontent.com/ocaml/dune/fc7b95148e1c71c4cb322dc852b6b6514044c611/test/blackbox-tests/test-cases/melange/mli.t/x.ml
ocaml
let buy_it = "buy " ^ Lib.Y.it let () = print_endline buy_it
5c2dc8801701a1bc5f544609493319c613a80b0ed488d2905fc793c04d84235e
ragkousism/Guix-on-Hurd
wordnet.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2013 , 2016 < > Copyright © 2016 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages wordnet) #:use-module (guix packages) #:use-module (guix build-system gnu) #:use-module (guix licenses) #:use-module (guix download) #:use-module (gnu packages) #:use-module (gnu packages gcc) #:use-module (gnu packages tcl)) (define-public wordnet (package (name "wordnet") (version "3.0") (source (origin (method url-fetch) (uri (string-append "/" version "/WordNet-" version ".tar.bz2")) (sha256 (base32 "08pgjvd2vvmqk3h641x63nxp7wqimb9r30889mkyfh2agc62sjbc")) (patches (search-patches "wordnet-CVE-2008-2149.patch" "wordnet-CVE-2008-3908-pt1.patch" "wordnet-CVE-2008-3908-pt2.patch")))) (build-system gnu-build-system) (arguments `(#:configure-flags (list (string-append "--with-tcl=" (assoc-ref %build-inputs "tcl") "/lib") (string-append "--with-tk=" (assoc-ref %build-inputs "tk") "/lib") Provide the ` result ' field in ` Tcl_Interp ' . ;; See <>. "CFLAGS=-DUSE_INTERP_RESULT -O2") #:phases (modify-phases %standard-phases (add-after 'install 'post-install (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (bin (assoc-ref outputs "tk")) (tk (assoc-ref inputs "tk")) (tkv ,(let ((v (package-version tk))) (string-take v (string-index-right v #\.))))) Move ` wishwn ' and ` wnb ' to BIN . (for-each (lambda (prog) (let ((orig (string-append out "/bin/" prog)) (dst (string-append bin "/bin/" prog)) (dir (string-append tk "/lib/tk" tkv))) (mkdir-p (dirname dst)) (copy-file orig dst) (delete-file orig) (wrap-program dst `("TK_LIBRARY" "" = (,dir)) `("PATH" ":" prefix (,(string-append out "/bin")))))) '("wishwn" "wnb")) #t)))))) (outputs '("out" for the Tcl / Tk GUI Build with a patched GCC to work around < > . ;; (Specifically the 'DEFAULTPATH' string literal is what we want to ;; prevent from being chunked so that grafting can "see" it and patch it.) (native-inputs `(("gcc@6" ,gcc-6))) (inputs `(("tk" ,tk) ("tcl" ,tcl))) (home-page "/") (synopsis "Lexical database for the English language") (description "WordNet is a large lexical database of English. Nouns, verbs, adjectives and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations. The resulting network of meaningfully related words and concepts can be navigated with the browser. WordNet is also freely and publicly available for download. WordNet's structure makes it a useful tool for computational linguistics and natural language processing.") (license x11)))
null
https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/wordnet.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. See <>. (Specifically the 'DEFAULTPATH' string literal is what we want to prevent from being chunked so that grafting can "see" it and patch it.)
Copyright © 2013 , 2016 < > Copyright © 2016 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (gnu packages wordnet) #:use-module (guix packages) #:use-module (guix build-system gnu) #:use-module (guix licenses) #:use-module (guix download) #:use-module (gnu packages) #:use-module (gnu packages gcc) #:use-module (gnu packages tcl)) (define-public wordnet (package (name "wordnet") (version "3.0") (source (origin (method url-fetch) (uri (string-append "/" version "/WordNet-" version ".tar.bz2")) (sha256 (base32 "08pgjvd2vvmqk3h641x63nxp7wqimb9r30889mkyfh2agc62sjbc")) (patches (search-patches "wordnet-CVE-2008-2149.patch" "wordnet-CVE-2008-3908-pt1.patch" "wordnet-CVE-2008-3908-pt2.patch")))) (build-system gnu-build-system) (arguments `(#:configure-flags (list (string-append "--with-tcl=" (assoc-ref %build-inputs "tcl") "/lib") (string-append "--with-tk=" (assoc-ref %build-inputs "tk") "/lib") Provide the ` result ' field in ` Tcl_Interp ' . "CFLAGS=-DUSE_INTERP_RESULT -O2") #:phases (modify-phases %standard-phases (add-after 'install 'post-install (lambda* (#:key inputs outputs #:allow-other-keys) (let ((out (assoc-ref outputs "out")) (bin (assoc-ref outputs "tk")) (tk (assoc-ref inputs "tk")) (tkv ,(let ((v (package-version tk))) (string-take v (string-index-right v #\.))))) Move ` wishwn ' and ` wnb ' to BIN . (for-each (lambda (prog) (let ((orig (string-append out "/bin/" prog)) (dst (string-append bin "/bin/" prog)) (dir (string-append tk "/lib/tk" tkv))) (mkdir-p (dirname dst)) (copy-file orig dst) (delete-file orig) (wrap-program dst `("TK_LIBRARY" "" = (,dir)) `("PATH" ":" prefix (,(string-append out "/bin")))))) '("wishwn" "wnb")) #t)))))) (outputs '("out" for the Tcl / Tk GUI Build with a patched GCC to work around < > . (native-inputs `(("gcc@6" ,gcc-6))) (inputs `(("tk" ,tk) ("tcl" ,tcl))) (home-page "/") (synopsis "Lexical database for the English language") (description "WordNet is a large lexical database of English. Nouns, verbs, adjectives and adverbs are grouped into sets of cognitive synonyms (synsets), each expressing a distinct concept. Synsets are interlinked by means of conceptual-semantic and lexical relations. The resulting network of meaningfully related words and concepts can be navigated with the browser. WordNet is also freely and publicly available for download. WordNet's structure makes it a useful tool for computational linguistics and natural language processing.") (license x11)))
8df5329bcccf00c1c828d863403def5c779c655cae29b3e44c76b2c9759a040f
fission-codes/fission
Types.hs
module Fission.Web.Server.PowerDNS.Types ( URL (..) , ApiKey (..) ) where import Fission.Prelude newtype URL = URL { getUrl :: Text } deriving newtype ( Eq , Display , Show , FromJSON , IsString ) newtype ApiKey = ApiKey { getApiKey :: Text } deriving newtype ( Eq , Display , Show , FromJSON , IsString )
null
https://raw.githubusercontent.com/fission-codes/fission/a0b46415e1e8b858aa6c6e503a7f2943a14e8218/fission-web-server/library/Fission/Web/Server/PowerDNS/Types.hs
haskell
module Fission.Web.Server.PowerDNS.Types ( URL (..) , ApiKey (..) ) where import Fission.Prelude newtype URL = URL { getUrl :: Text } deriving newtype ( Eq , Display , Show , FromJSON , IsString ) newtype ApiKey = ApiKey { getApiKey :: Text } deriving newtype ( Eq , Display , Show , FromJSON , IsString )
a945c82e5b2b92f0e9f0d2a0ba270180b9674e1caeb57e3bba25cb397c7d1933
ranjitjhala/haddock-annot
Hidden.hs
-- #hide module Hidden where hidden :: Int -> Int hidden a = a
null
https://raw.githubusercontent.com/ranjitjhala/haddock-annot/ffaa182b17c3047887ff43dbe358c246011903f6/haddock-2.9.3/examples/Hidden.hs
haskell
#hide
module Hidden where hidden :: Int -> Int hidden a = a
c089b363b400ec38462f900079a9b5527009073935cea23505c7e520fe8dd0f2
robert-strandh/SICL
cleavir-configuration.lisp
(cl:in-package #:sicl-boot) (defmethod cleavir-literals:allocate-lexical-location ((client client) environment) (cleavir-ast:make-ast 'cleavir-ast:lexical-ast :name (gensym))) (defmethod cleavir-literals:convert-initialization-form ((client client) form environment) (let ((cst (cst:cst-from-expression form))) (cleavir-cst-to-ast:convert client cst environment))) (defmethod cleavir-literals:convert-creation-form ((client client) form lexical-ast environment) (let ((cst (cst:cst-from-expression form))) (cleavir-ast:make-ast 'cleavir-ast:lexical-bind-ast :origin nil :value-ast (cleavir-cst-to-ast:convert client cst environment) :lexical-variable-ast lexical-ast))) (defmethod cleavir-cst-to-ast:trivial-constant-p ((client client) (object integer)) (<= #.(- (expt 2 62)) object #.(1- (expt 2 62)))) (defmethod cleavir-cst-to-ast:trivial-constant-p ((client client) (object symbol)) t)
null
https://raw.githubusercontent.com/robert-strandh/SICL/9b3d43fe05ee84beaca6da22e17e14dbc55d9375/Code/Boot/cleavir-configuration.lisp
lisp
(cl:in-package #:sicl-boot) (defmethod cleavir-literals:allocate-lexical-location ((client client) environment) (cleavir-ast:make-ast 'cleavir-ast:lexical-ast :name (gensym))) (defmethod cleavir-literals:convert-initialization-form ((client client) form environment) (let ((cst (cst:cst-from-expression form))) (cleavir-cst-to-ast:convert client cst environment))) (defmethod cleavir-literals:convert-creation-form ((client client) form lexical-ast environment) (let ((cst (cst:cst-from-expression form))) (cleavir-ast:make-ast 'cleavir-ast:lexical-bind-ast :origin nil :value-ast (cleavir-cst-to-ast:convert client cst environment) :lexical-variable-ast lexical-ast))) (defmethod cleavir-cst-to-ast:trivial-constant-p ((client client) (object integer)) (<= #.(- (expt 2 62)) object #.(1- (expt 2 62)))) (defmethod cleavir-cst-to-ast:trivial-constant-p ((client client) (object symbol)) t)
3e90bd8d52dbb87c15da4bdb5977725700c6c64e4ba30b99d3e040a0cc3d39ef
racket/typed-racket
opaque-object-contract.rkt
#; (exn-pred #rx"uncontracted typed.*blaming: .*opaque-object-contract.rkt") #lang racket/base (module a typed/racket/optional (provide c%) (define c% (class object% (super-new) (define/public (m) (void))))) (module b typed/racket/deep (require/typed (submod ".." a) [c% (Class [m (-> Void)])]) (provide o) (: o (Object)) (define o (new (class c% (super-new) (define/public (n) (void)))))) (require 'b) (require racket/class) (send o m) (send o n)
null
https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/fail/optional/opaque-object-contract.rkt
racket
(exn-pred #rx"uncontracted typed.*blaming: .*opaque-object-contract.rkt") #lang racket/base (module a typed/racket/optional (provide c%) (define c% (class object% (super-new) (define/public (m) (void))))) (module b typed/racket/deep (require/typed (submod ".." a) [c% (Class [m (-> Void)])]) (provide o) (: o (Object)) (define o (new (class c% (super-new) (define/public (n) (void)))))) (require 'b) (require racket/class) (send o m) (send o n)
28b58bdd80150ba02bbd6b37a5588bbcba996b43d6f857c9b3f1510fe3e16ded
rescript-lang/rescript-compiler
TranslateStructure.ml
open GenTypeCommon let rec addAnnotationsToTypes_ ~config ~(expr : Typedtree.expression) (argTypes : argType list) = match (expr.exp_desc, expr.exp_type.desc, argTypes) with | _, _, {aName; aType = GroupOfLabeledArgs fields} :: nextTypes -> let fields1, nextTypes1 = addAnnotationsToFields ~config expr fields nextTypes in {aName; aType = GroupOfLabeledArgs fields1} :: nextTypes1 | Texp_function {param; cases = [{c_rhs}]}, _, {aType} :: nextTypes -> let nextTypes1 = nextTypes |> addAnnotationsToTypes_ ~config ~expr:c_rhs in let aName = Ident.name param in {aName; aType} :: nextTypes1 | Texp_construct ({txt = Lident "Function$"}, _, [funExpr]), _, _ -> let : function$ < _ , _ > = Function$(x = > x | > string_of_int , [ ` Has_arity1 ] ) addAnnotationsToTypes_ ~config ~expr:funExpr argTypes | Texp_apply ({exp_desc = Texp_ident (path, _, _)}, [(_, Some expr1)]), _, _ -> ( match path |> TranslateTypeExprFromTypes.pathToList |> List.rev with | ["Js"; "Internal"; fn_mk] Uncurried function definition uses Js . Internal.fn_mkX ( ... ) String.length fn_mk >= 5 && String.sub fn_mk 0 5 = "fn_mk" -> argTypes |> addAnnotationsToTypes_ ~config ~expr:expr1 | _ -> argTypes) | _ -> argTypes and addAnnotationsToTypes ~config ~(expr : Typedtree.expression) (argTypes : argType list) = let argTypes = addAnnotationsToTypes_ ~config ~expr argTypes in if argTypes |> List.filter (fun {aName} -> aName = "param") |> List.length > 1 then (* Underscore "_" appears as "param", can occur more than once *) argTypes |> List.mapi (fun i {aName; aType} -> {aName = aName ^ "_" ^ string_of_int i; aType}) else argTypes and addAnnotationsToFields ~config (expr : Typedtree.expression) (fields : fields) (argTypes : argType list) = match (expr.exp_desc, fields, argTypes) with | _, [], _ -> ([], argTypes |> addAnnotationsToTypes ~config ~expr) | Texp_function {cases = [{c_rhs}]}, field :: nextFields, _ -> let nextFields1, types1 = addAnnotationsToFields ~config c_rhs nextFields argTypes in let nameJS, nameRE = TranslateTypeDeclarations.renameRecordField ~attributes:expr.exp_attributes ~nameRE:field.nameRE in ({field with nameJS; nameRE} :: nextFields1, types1) | _ -> (fields, argTypes) (** Recover from expr the renaming annotations on named arguments. *) let addAnnotationsToFunctionType ~config (expr : Typedtree.expression) (type_ : type_) = match type_ with | Function function_ -> let argTypes = function_.argTypes |> addAnnotationsToTypes ~config ~expr in Function {function_ with argTypes} | _ -> type_ let removeValueBindingDuplicates structureItems = let rec processBindings (bindings : Typedtree.value_binding list) ~seen = match bindings with | ({vb_pat = {pat_desc = Tpat_var (id, _)}} as binding) :: otherBindings -> let name = Ident.name id in if !seen |> StringSet.mem name then otherBindings |> processBindings ~seen else ( seen := !seen |> StringSet.add name; binding :: (otherBindings |> processBindings ~seen)) | binding :: otherBindings -> binding :: (otherBindings |> processBindings ~seen) | [] -> [] in let rec processItems (items : Typedtree.structure_item list) ~acc ~seen = match items with | ({Typedtree.str_desc = Tstr_value (loc, valueBindings)} as item) :: otherItems -> let bindings = valueBindings |> processBindings ~seen in let item = {item with str_desc = Tstr_value (loc, bindings)} in otherItems |> processItems ~acc:(item :: acc) ~seen | item :: otherItems -> otherItems |> processItems ~acc:(item :: acc) ~seen | [] -> acc in structureItems |> List.rev |> processItems ~acc:[] ~seen:(ref StringSet.empty) let translateValueBinding ~config ~outputFileRelative ~resolver ~typeEnv {Typedtree.vb_attributes; vb_expr; vb_pat} : Translation.t = match vb_pat.pat_desc with | Tpat_var (id, _) | Tpat_alias ({pat_desc = Tpat_any}, id, _) -> let name = id |> Ident.name in if !Debug.translation then Log_.item "Translate Value Binding %s\n" name; let moduleItem = Runtime.newModuleItem ~name in typeEnv |> TypeEnv.updateModuleItem ~moduleItem; if vb_attributes |> Annotation.fromAttributes ~loc:vb_pat.pat_loc = GenType then id |> Ident.name |> Translation.translateValue ~attributes:vb_attributes ~config ~docString:(Annotation.getDocString vb_attributes) ~outputFileRelative ~resolver ~typeEnv ~typeExpr:vb_pat.pat_type ~addAnnotationsToFunction: (addAnnotationsToFunctionType ~config vb_expr) else Translation.empty | _ -> Translation.empty let rec removeDuplicateValueBindings (structureItems : Typedtree.structure_item list) = match structureItems with | ({Typedtree.str_desc = Tstr_value (loc, valueBindings)} as structureItem) :: rest -> let boundInRest, filteredRest = rest |> removeDuplicateValueBindings in let valueBindingsFiltered = valueBindings |> List.filter (fun valueBinding -> match valueBinding with | {Typedtree.vb_pat = {pat_desc = Tpat_var (id, _)}} -> not (boundInRest |> StringSet.mem (id |> Ident.name)) | _ -> true) in let bound = valueBindings |> List.fold_left (fun bound (valueBinding : Typedtree.value_binding) -> match valueBinding with | {vb_pat = {pat_desc = Tpat_var (id, _)}} -> bound |> StringSet.add (id |> Ident.name) | _ -> bound) boundInRest in ( bound, {structureItem with str_desc = Tstr_value (loc, valueBindingsFiltered)} :: filteredRest ) | structureItem :: rest -> let boundInRest, filteredRest = rest |> removeDuplicateValueBindings in (boundInRest, structureItem :: filteredRest) | [] -> (StringSet.empty, []) let rec translateModuleBinding ~config ~outputFileRelative ~resolver ~typeEnv ({mb_id; mb_expr; mb_attributes} : Typedtree.module_binding) : Translation.t = let name = mb_id |> Ident.name in if !Debug.translation then Log_.item "Translate Module Binding %s\n" name; let moduleItem = Runtime.newModuleItem ~name in typeEnv |> TypeEnv.updateModuleItem ~moduleItem; let typeEnv = typeEnv |> TypeEnv.newModule ~name in match mb_expr.mod_desc with | Tmod_structure structure -> let isLetPrivate = mb_attributes |> Annotation.hasAttribute Annotation.tagIsInternLocal in if isLetPrivate then Translation.empty else structure |> translateStructure ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Tmod_apply _ -> ( (* Only look at the resulting type of the module *) match mb_expr.mod_type with | Mty_signature signature -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Mty_ident _ -> logNotImplemented ("Mty_ident " ^ __LOC__); Translation.empty | Mty_functor _ -> logNotImplemented ("Mty_functor " ^ __LOC__); Translation.empty | Mty_alias _ -> logNotImplemented ("Mty_alias " ^ __LOC__); Translation.empty) | Tmod_unpack (_, moduleType) -> ( match moduleType with | Mty_signature signature -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Mty_ident path -> ( match typeEnv |> TypeEnv.lookupModuleTypeSignature ~path with | None -> Translation.empty | Some (signature, _) -> signature |> TranslateSignature.translateSignature ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine) | Mty_functor _ -> logNotImplemented ("Mty_functor " ^ __LOC__); Translation.empty | Mty_alias _ -> logNotImplemented ("Mty_alias " ^ __LOC__); Translation.empty) | Tmod_ident (path, _) -> let dep = path |> Dependencies.fromPath ~config ~typeEnv in let internal = dep |> Dependencies.isInternal in typeEnv |> TypeEnv.addModuleEquation ~dep ~internal; Translation.empty | Tmod_functor _ -> logNotImplemented ("Tmod_functor " ^ __LOC__); Translation.empty | Tmod_constraint (_, Mty_ident path, Tmodtype_explicit _, Tcoerce_none) -> ( match typeEnv |> TypeEnv.lookupModuleTypeSignature ~path with | None -> Translation.empty | Some (signature, _) -> signature |> TranslateSignature.translateSignature ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine) | Tmod_constraint (_, Mty_signature signature, Tmodtype_explicit _, Tcoerce_none) -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Tmod_constraint ( {mod_desc = Tmod_structure structure}, _, Tmodtype_implicit, Tcoerce_structure _ ) -> { structure with str_items = structure.str_items |> removeDuplicateValueBindings |> snd; } |> translateStructure ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Tmod_constraint ( _, _, Tmodtype_explicit {mty_desc = Tmty_signature {sig_type = signature}}, _ ) -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Tmod_constraint _ -> logNotImplemented ("Tmod_constraint " ^ __LOC__); Translation.empty and translateStructureItem ~config ~outputFileRelative ~resolver ~typeEnv structItem : Translation.t = match structItem with | {Typedtree.str_desc = Typedtree.Tstr_type (recFlag, typeDeclarations)} -> { importTypes = []; codeItems = []; typeDeclarations = typeDeclarations |> TranslateTypeDeclarations.translateTypeDeclarations ~config ~outputFileRelative ~recursive:(recFlag = Recursive) ~resolver ~typeEnv; } | {Typedtree.str_desc = Tstr_value (_loc, valueBindings)} -> valueBindings |> List.map (translateValueBinding ~config ~outputFileRelative ~resolver ~typeEnv) |> Translation.combine | {Typedtree.str_desc = Tstr_primitive valueDescription} -> (* external declaration *) valueDescription |> Translation.translatePrimitive ~config ~outputFileRelative ~resolver ~typeEnv | {Typedtree.str_desc = Tstr_module moduleBinding} -> moduleBinding |> translateModuleBinding ~config ~outputFileRelative ~resolver ~typeEnv | {Typedtree.str_desc = Tstr_modtype moduleTypeDeclaration} -> moduleTypeDeclaration |> TranslateSignature.translateModuleTypeDeclaration ~config ~outputFileRelative ~resolver ~typeEnv | {Typedtree.str_desc = Tstr_recmodule moduleBindings} -> moduleBindings |> List.map (translateModuleBinding ~config ~outputFileRelative ~resolver ~typeEnv) |> Translation.combine | { Typedtree.str_desc = 's encoding of bs.module : include with constraint . Tstr_include { incl_mod = { mod_desc = Tmod_constraint ( { mod_desc = Tmod_structure { str_items = [({str_desc = Tstr_primitive _} as structItem1)]; }; }, _, _, _ ); }; _; }; _; } -> structItem1 |> translateStructureItem ~config ~outputFileRelative ~resolver ~typeEnv | {Typedtree.str_desc = Tstr_include {incl_type = signature}} -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | {Typedtree.str_desc = Tstr_eval _} -> logNotImplemented ("Tstr_eval " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_typext _} -> logNotImplemented ("Tstr_typext " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_exception _} -> logNotImplemented ("Tstr_exception " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_open _} -> logNotImplemented ("Tstr_open " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_class _} -> logNotImplemented ("Tstr_class " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_class_type _} -> logNotImplemented ("Tstr_class_type " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_attribute _} -> logNotImplemented ("Tstr_attribute " ^ __LOC__); Translation.empty and translateStructure ~config ~outputFileRelative ~resolver ~typeEnv structure : Translation.t list = if !Debug.translation then Log_.item "Translate Structure\n"; structure.Typedtree.str_items |> removeValueBindingDuplicates |> List.map (fun structItem -> structItem |> translateStructureItem ~config ~outputFileRelative ~resolver ~typeEnv)
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/6c4514c4c80f440a9f7f9cf4ae7721bdac315b57/jscomp/gentype/TranslateStructure.ml
ocaml
Underscore "_" appears as "param", can occur more than once * Recover from expr the renaming annotations on named arguments. Only look at the resulting type of the module external declaration
open GenTypeCommon let rec addAnnotationsToTypes_ ~config ~(expr : Typedtree.expression) (argTypes : argType list) = match (expr.exp_desc, expr.exp_type.desc, argTypes) with | _, _, {aName; aType = GroupOfLabeledArgs fields} :: nextTypes -> let fields1, nextTypes1 = addAnnotationsToFields ~config expr fields nextTypes in {aName; aType = GroupOfLabeledArgs fields1} :: nextTypes1 | Texp_function {param; cases = [{c_rhs}]}, _, {aType} :: nextTypes -> let nextTypes1 = nextTypes |> addAnnotationsToTypes_ ~config ~expr:c_rhs in let aName = Ident.name param in {aName; aType} :: nextTypes1 | Texp_construct ({txt = Lident "Function$"}, _, [funExpr]), _, _ -> let : function$ < _ , _ > = Function$(x = > x | > string_of_int , [ ` Has_arity1 ] ) addAnnotationsToTypes_ ~config ~expr:funExpr argTypes | Texp_apply ({exp_desc = Texp_ident (path, _, _)}, [(_, Some expr1)]), _, _ -> ( match path |> TranslateTypeExprFromTypes.pathToList |> List.rev with | ["Js"; "Internal"; fn_mk] Uncurried function definition uses Js . Internal.fn_mkX ( ... ) String.length fn_mk >= 5 && String.sub fn_mk 0 5 = "fn_mk" -> argTypes |> addAnnotationsToTypes_ ~config ~expr:expr1 | _ -> argTypes) | _ -> argTypes and addAnnotationsToTypes ~config ~(expr : Typedtree.expression) (argTypes : argType list) = let argTypes = addAnnotationsToTypes_ ~config ~expr argTypes in if argTypes |> List.filter (fun {aName} -> aName = "param") |> List.length > 1 then argTypes |> List.mapi (fun i {aName; aType} -> {aName = aName ^ "_" ^ string_of_int i; aType}) else argTypes and addAnnotationsToFields ~config (expr : Typedtree.expression) (fields : fields) (argTypes : argType list) = match (expr.exp_desc, fields, argTypes) with | _, [], _ -> ([], argTypes |> addAnnotationsToTypes ~config ~expr) | Texp_function {cases = [{c_rhs}]}, field :: nextFields, _ -> let nextFields1, types1 = addAnnotationsToFields ~config c_rhs nextFields argTypes in let nameJS, nameRE = TranslateTypeDeclarations.renameRecordField ~attributes:expr.exp_attributes ~nameRE:field.nameRE in ({field with nameJS; nameRE} :: nextFields1, types1) | _ -> (fields, argTypes) let addAnnotationsToFunctionType ~config (expr : Typedtree.expression) (type_ : type_) = match type_ with | Function function_ -> let argTypes = function_.argTypes |> addAnnotationsToTypes ~config ~expr in Function {function_ with argTypes} | _ -> type_ let removeValueBindingDuplicates structureItems = let rec processBindings (bindings : Typedtree.value_binding list) ~seen = match bindings with | ({vb_pat = {pat_desc = Tpat_var (id, _)}} as binding) :: otherBindings -> let name = Ident.name id in if !seen |> StringSet.mem name then otherBindings |> processBindings ~seen else ( seen := !seen |> StringSet.add name; binding :: (otherBindings |> processBindings ~seen)) | binding :: otherBindings -> binding :: (otherBindings |> processBindings ~seen) | [] -> [] in let rec processItems (items : Typedtree.structure_item list) ~acc ~seen = match items with | ({Typedtree.str_desc = Tstr_value (loc, valueBindings)} as item) :: otherItems -> let bindings = valueBindings |> processBindings ~seen in let item = {item with str_desc = Tstr_value (loc, bindings)} in otherItems |> processItems ~acc:(item :: acc) ~seen | item :: otherItems -> otherItems |> processItems ~acc:(item :: acc) ~seen | [] -> acc in structureItems |> List.rev |> processItems ~acc:[] ~seen:(ref StringSet.empty) let translateValueBinding ~config ~outputFileRelative ~resolver ~typeEnv {Typedtree.vb_attributes; vb_expr; vb_pat} : Translation.t = match vb_pat.pat_desc with | Tpat_var (id, _) | Tpat_alias ({pat_desc = Tpat_any}, id, _) -> let name = id |> Ident.name in if !Debug.translation then Log_.item "Translate Value Binding %s\n" name; let moduleItem = Runtime.newModuleItem ~name in typeEnv |> TypeEnv.updateModuleItem ~moduleItem; if vb_attributes |> Annotation.fromAttributes ~loc:vb_pat.pat_loc = GenType then id |> Ident.name |> Translation.translateValue ~attributes:vb_attributes ~config ~docString:(Annotation.getDocString vb_attributes) ~outputFileRelative ~resolver ~typeEnv ~typeExpr:vb_pat.pat_type ~addAnnotationsToFunction: (addAnnotationsToFunctionType ~config vb_expr) else Translation.empty | _ -> Translation.empty let rec removeDuplicateValueBindings (structureItems : Typedtree.structure_item list) = match structureItems with | ({Typedtree.str_desc = Tstr_value (loc, valueBindings)} as structureItem) :: rest -> let boundInRest, filteredRest = rest |> removeDuplicateValueBindings in let valueBindingsFiltered = valueBindings |> List.filter (fun valueBinding -> match valueBinding with | {Typedtree.vb_pat = {pat_desc = Tpat_var (id, _)}} -> not (boundInRest |> StringSet.mem (id |> Ident.name)) | _ -> true) in let bound = valueBindings |> List.fold_left (fun bound (valueBinding : Typedtree.value_binding) -> match valueBinding with | {vb_pat = {pat_desc = Tpat_var (id, _)}} -> bound |> StringSet.add (id |> Ident.name) | _ -> bound) boundInRest in ( bound, {structureItem with str_desc = Tstr_value (loc, valueBindingsFiltered)} :: filteredRest ) | structureItem :: rest -> let boundInRest, filteredRest = rest |> removeDuplicateValueBindings in (boundInRest, structureItem :: filteredRest) | [] -> (StringSet.empty, []) let rec translateModuleBinding ~config ~outputFileRelative ~resolver ~typeEnv ({mb_id; mb_expr; mb_attributes} : Typedtree.module_binding) : Translation.t = let name = mb_id |> Ident.name in if !Debug.translation then Log_.item "Translate Module Binding %s\n" name; let moduleItem = Runtime.newModuleItem ~name in typeEnv |> TypeEnv.updateModuleItem ~moduleItem; let typeEnv = typeEnv |> TypeEnv.newModule ~name in match mb_expr.mod_desc with | Tmod_structure structure -> let isLetPrivate = mb_attributes |> Annotation.hasAttribute Annotation.tagIsInternLocal in if isLetPrivate then Translation.empty else structure |> translateStructure ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Tmod_apply _ -> ( match mb_expr.mod_type with | Mty_signature signature -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Mty_ident _ -> logNotImplemented ("Mty_ident " ^ __LOC__); Translation.empty | Mty_functor _ -> logNotImplemented ("Mty_functor " ^ __LOC__); Translation.empty | Mty_alias _ -> logNotImplemented ("Mty_alias " ^ __LOC__); Translation.empty) | Tmod_unpack (_, moduleType) -> ( match moduleType with | Mty_signature signature -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Mty_ident path -> ( match typeEnv |> TypeEnv.lookupModuleTypeSignature ~path with | None -> Translation.empty | Some (signature, _) -> signature |> TranslateSignature.translateSignature ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine) | Mty_functor _ -> logNotImplemented ("Mty_functor " ^ __LOC__); Translation.empty | Mty_alias _ -> logNotImplemented ("Mty_alias " ^ __LOC__); Translation.empty) | Tmod_ident (path, _) -> let dep = path |> Dependencies.fromPath ~config ~typeEnv in let internal = dep |> Dependencies.isInternal in typeEnv |> TypeEnv.addModuleEquation ~dep ~internal; Translation.empty | Tmod_functor _ -> logNotImplemented ("Tmod_functor " ^ __LOC__); Translation.empty | Tmod_constraint (_, Mty_ident path, Tmodtype_explicit _, Tcoerce_none) -> ( match typeEnv |> TypeEnv.lookupModuleTypeSignature ~path with | None -> Translation.empty | Some (signature, _) -> signature |> TranslateSignature.translateSignature ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine) | Tmod_constraint (_, Mty_signature signature, Tmodtype_explicit _, Tcoerce_none) -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Tmod_constraint ( {mod_desc = Tmod_structure structure}, _, Tmodtype_implicit, Tcoerce_structure _ ) -> { structure with str_items = structure.str_items |> removeDuplicateValueBindings |> snd; } |> translateStructure ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Tmod_constraint ( _, _, Tmodtype_explicit {mty_desc = Tmty_signature {sig_type = signature}}, _ ) -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | Tmod_constraint _ -> logNotImplemented ("Tmod_constraint " ^ __LOC__); Translation.empty and translateStructureItem ~config ~outputFileRelative ~resolver ~typeEnv structItem : Translation.t = match structItem with | {Typedtree.str_desc = Typedtree.Tstr_type (recFlag, typeDeclarations)} -> { importTypes = []; codeItems = []; typeDeclarations = typeDeclarations |> TranslateTypeDeclarations.translateTypeDeclarations ~config ~outputFileRelative ~recursive:(recFlag = Recursive) ~resolver ~typeEnv; } | {Typedtree.str_desc = Tstr_value (_loc, valueBindings)} -> valueBindings |> List.map (translateValueBinding ~config ~outputFileRelative ~resolver ~typeEnv) |> Translation.combine | {Typedtree.str_desc = Tstr_primitive valueDescription} -> valueDescription |> Translation.translatePrimitive ~config ~outputFileRelative ~resolver ~typeEnv | {Typedtree.str_desc = Tstr_module moduleBinding} -> moduleBinding |> translateModuleBinding ~config ~outputFileRelative ~resolver ~typeEnv | {Typedtree.str_desc = Tstr_modtype moduleTypeDeclaration} -> moduleTypeDeclaration |> TranslateSignature.translateModuleTypeDeclaration ~config ~outputFileRelative ~resolver ~typeEnv | {Typedtree.str_desc = Tstr_recmodule moduleBindings} -> moduleBindings |> List.map (translateModuleBinding ~config ~outputFileRelative ~resolver ~typeEnv) |> Translation.combine | { Typedtree.str_desc = 's encoding of bs.module : include with constraint . Tstr_include { incl_mod = { mod_desc = Tmod_constraint ( { mod_desc = Tmod_structure { str_items = [({str_desc = Tstr_primitive _} as structItem1)]; }; }, _, _, _ ); }; _; }; _; } -> structItem1 |> translateStructureItem ~config ~outputFileRelative ~resolver ~typeEnv | {Typedtree.str_desc = Tstr_include {incl_type = signature}} -> signature |> TranslateSignatureFromTypes.translateSignatureFromTypes ~config ~outputFileRelative ~resolver ~typeEnv |> Translation.combine | {Typedtree.str_desc = Tstr_eval _} -> logNotImplemented ("Tstr_eval " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_typext _} -> logNotImplemented ("Tstr_typext " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_exception _} -> logNotImplemented ("Tstr_exception " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_open _} -> logNotImplemented ("Tstr_open " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_class _} -> logNotImplemented ("Tstr_class " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_class_type _} -> logNotImplemented ("Tstr_class_type " ^ __LOC__); Translation.empty | {Typedtree.str_desc = Tstr_attribute _} -> logNotImplemented ("Tstr_attribute " ^ __LOC__); Translation.empty and translateStructure ~config ~outputFileRelative ~resolver ~typeEnv structure : Translation.t list = if !Debug.translation then Log_.item "Translate Structure\n"; structure.Typedtree.str_items |> removeValueBindingDuplicates |> List.map (fun structItem -> structItem |> translateStructureItem ~config ~outputFileRelative ~resolver ~typeEnv)
257a026dbfc8946da9d7913a8a13b194afecf0dce2365fd07c9524ba7586c87b
esl/MongooseIM
mongoose_graphql_vcard_admin_mutation.erl
-module(mongoose_graphql_vcard_admin_mutation). -behaviour(mongoose_graphql). -include("mod_vcard.hrl"). -export([execute/4]). -import(mongoose_graphql_helper, [make_error/2]). -ignore_xref([execute/4]). -include("../mongoose_graphql_types.hrl"). -include("mongoose.hrl"). -include("jlib.hrl"). execute(_Ctx, vcard, <<"setVcard">>, #{<<"user">> := CallerJID, <<"vcard">> := VcardInput}) -> case mod_vcard_api:set_vcard(CallerJID, VcardInput) of {ok, _} = Vcard -> Vcard; Error -> make_error(Error, #{user => jid:to_binary(CallerJID)}) end.
null
https://raw.githubusercontent.com/esl/MongooseIM/25671900c8593d37088cd069514d5eade9085f5b/src/graphql/admin/mongoose_graphql_vcard_admin_mutation.erl
erlang
-module(mongoose_graphql_vcard_admin_mutation). -behaviour(mongoose_graphql). -include("mod_vcard.hrl"). -export([execute/4]). -import(mongoose_graphql_helper, [make_error/2]). -ignore_xref([execute/4]). -include("../mongoose_graphql_types.hrl"). -include("mongoose.hrl"). -include("jlib.hrl"). execute(_Ctx, vcard, <<"setVcard">>, #{<<"user">> := CallerJID, <<"vcard">> := VcardInput}) -> case mod_vcard_api:set_vcard(CallerJID, VcardInput) of {ok, _} = Vcard -> Vcard; Error -> make_error(Error, #{user => jid:to_binary(CallerJID)}) end.
46bc62cc8b8231e6b74e63c6c3f9c3a291f67a38b2aa7a530bd09fa84b83fb7d
ruricolist/cloture
clojure-repl.lisp
(in-package #:cloture) (in-readtable clojure-shortcut) (defun compile-and-eval (form) (funcall (compile nil (eval `(lambda () ,form))))) (defun repl () (with-clojure-printer () (let ((*readtable* (find-readtable 'cloture)) (*package* (find-package "user"))) (catch 'quit (loop (format t "~&~a=> " (package-name *package*)) (finish-output) (with-simple-restart (abort "Return to Clojure REPL") (let* ((form (read)) (result (compile-and-eval form))) (shiftf *** ** * result) (format t "~s" result) (finish-output)))))))) (defun-1 #_exit () (throw 'quit (values))) (defun-1 #_quit () (#_exit))
null
https://raw.githubusercontent.com/ruricolist/cloture/623c15c8d2e5e91eb87f46e3ecb3975880109948/clojure-repl.lisp
lisp
(in-package #:cloture) (in-readtable clojure-shortcut) (defun compile-and-eval (form) (funcall (compile nil (eval `(lambda () ,form))))) (defun repl () (with-clojure-printer () (let ((*readtable* (find-readtable 'cloture)) (*package* (find-package "user"))) (catch 'quit (loop (format t "~&~a=> " (package-name *package*)) (finish-output) (with-simple-restart (abort "Return to Clojure REPL") (let* ((form (read)) (result (compile-and-eval form))) (shiftf *** ** * result) (format t "~s" result) (finish-output)))))))) (defun-1 #_exit () (throw 'quit (values))) (defun-1 #_quit () (#_exit))
177b634f60d96598740be4890cebfa30722350d0f78e45b84cb8d91ebd11755d
zadean/xqerl
xqldb_string_table2.erl
Copyright ( c ) 2018 - 2020 . SPDX - FileCopyrightText : 2022 % SPDX - License - Identifier : Apache-2.0 A string table is a lookup for each distinct string and a 32 bit integer . %% The ID for the string is made up of a hash followed by a pigeonhole %% offset value in case of collision. %% When a collision occurs, the offset is increased and appended to the hash. %% When there is no collision, 0 is appended. %% Looking up a value by string means getting its hash value, appending min and ( all 1 bits ) tails , and then selecting each possible ID until it %% is found. This means that there is a maximum nr. of collisions possible, so the table should not get too large . ( 95 % max size ? ) Linear Probing %% Every value is written to file. This can slow down insert operations. %% Note: For all intents and purposes, a 'string' is a UTF8 binary value. -module(xqldb_string_table2). -behaviour(gen_server). -include("xqerl_db.hrl"). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3 ]). %% ==================================================================== %% API functions %% ==================================================================== -export([ start_link/3, stop/1, insert/2, lookup/2 ]). -type state() :: #{indx_file => file:io_device()}. %% Open or create a new string table server. -spec start_link( open | new, DBDirectory :: file:name_all(), TableName :: string() ) -> {ok, Pid :: pid()}. start_link(new, DBDirectory, TableName) -> gen_server:start_link(?MODULE, [new, DBDirectory, TableName], []); start_link(open, DBDirectory, TableName) -> gen_server:start_link(?MODULE, [open, DBDirectory, TableName], []). %% Shutdown this server. -spec stop(db()) -> ok | {ok, _}. stop(#{texts := Pid}) when is_pid(Pid) -> gen_server:stop(Pid). %% Returns the binary value for the given ID, or error if no such ID exists. -spec lookup(db(), Id :: binary()) -> Value :: binary() | error. lookup(#{texts := Pid}, Id) when is_pid(Pid), byte_size(Id) =< 63 -> Id; lookup(#{texts := Pid}, Id) when is_pid(Pid), byte_size(Id) =:= 64 -> gen_server:call(Pid, {lookup, Id}); lookup(_, _) -> error. %% Returns the ID for a binary value in the table. %% If no such value exists, creates a new value in the table and returns its ID. -spec insert(db(), Value :: binary()) -> Id :: binary(). insert(#{texts := Pid}, Value) when is_pid(Pid), byte_size(Value) =< 63 -> Value; insert(#{texts := Pid}, Value) when is_pid(Pid) -> gen_server:call(Pid, {insert, Value}). %% ==================================================================== Internal functions %% ==================================================================== Creates a new string table in the DBDirectory in the DB DBName , with the name TableName . Deletes any existing DB file with the same name . -spec new( DBDirectory :: file:name_all(), TableName :: string() ) -> state(). new(DBDirectory, TableName) when is_binary(DBDirectory) -> new(binary_to_list(DBDirectory), TableName); new(DBDirectory, TableName) -> init_state(DBDirectory, TableName). Opens an existing string table in the DBDirectory in the DB DBName , with the name TableName . -spec open( DBDirectory :: file:name_all(), TableName :: string() ) -> state(). open(DBDirectory, TableName) when is_binary(DBDirectory) -> open(binary_to_list(DBDirectory), TableName); open(DBDirectory, TableName) -> init_state(DBDirectory, TableName). init_state(DBDirectory, TableName) -> AbsTabName = filename:join(DBDirectory, TableName), ok = filelib:ensure_dir(AbsTabName), IndxName = AbsTabName ++ ".heap", {ok, IndxFile} = dets:open_file(IndxName, []), #{indx_file => IndxFile}. lookup_string_from_id(Id, IndxFile, ReplyTo) -> Reply = case dets:lookup(IndxFile, Id) of [] -> error; [{_, String}] -> String end, gen_server:reply(ReplyTo, Reply). upsert_string_value(String, #{indx_file := IndxFile} = State) -> Hash = hash(String), case dets:lookup(IndxFile, Hash) of [] -> dets:insert(IndxFile, {Hash, String}), {Hash, State}; [_] -> {Hash, State} end. %% ==================================================================== %% Callbacks %% ==================================================================== init([new, DBDirectory, TableName]) -> State = new(DBDirectory, TableName), {ok, State}; init([open, DBDirectory, TableName]) -> State = open(DBDirectory, TableName), {ok, State}. terminate(_Reason, #{indx_file := IndxFile}) -> dets:close(IndxFile). handle_cast(_Request, State) -> {noreply, State}. handle_call({insert, Value}, _From, State) -> {Reply, State1} = upsert_string_value(Value, State), {reply, Reply, State1}; handle_call({lookup, Id}, From, #{indx_file := IndxFile} = State) -> Fun = fun() -> lookup_string_from_id(Id, IndxFile, From) end, _ = erlang:spawn_link(Fun), {noreply, State}. handle_info(_Request, State) -> {noreply, State}. code_change(_, State, _) -> {ok, State}. hash(Value) -> crypto:hash(sha512, Value).
null
https://raw.githubusercontent.com/zadean/xqerl/06c651ec832d0ac2b77bef92c1b4ab14d8da8883/src/xqldb_string_table2.erl
erlang
The ID for the string is made up of a hash followed by a pigeonhole offset value in case of collision. When a collision occurs, the offset is increased and appended to the hash. When there is no collision, 0 is appended. Looking up a value by string means getting its hash value, appending is found. This means that there is a maximum nr. of collisions possible, max size ? ) Every value is written to file. This can slow down insert operations. Note: For all intents and purposes, a 'string' is a UTF8 binary value. ==================================================================== API functions ==================================================================== Open or create a new string table server. Shutdown this server. Returns the binary value for the given ID, or error if no such ID exists. Returns the ID for a binary value in the table. If no such value exists, creates a new value in the table and returns its ID. ==================================================================== ==================================================================== ==================================================================== Callbacks ====================================================================
Copyright ( c ) 2018 - 2020 . SPDX - FileCopyrightText : 2022 SPDX - License - Identifier : Apache-2.0 A string table is a lookup for each distinct string and a 32 bit integer . min and ( all 1 bits ) tails , and then selecting each possible ID until it Linear Probing -module(xqldb_string_table2). -behaviour(gen_server). -include("xqerl_db.hrl"). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3 ]). -export([ start_link/3, stop/1, insert/2, lookup/2 ]). -type state() :: #{indx_file => file:io_device()}. -spec start_link( open | new, DBDirectory :: file:name_all(), TableName :: string() ) -> {ok, Pid :: pid()}. start_link(new, DBDirectory, TableName) -> gen_server:start_link(?MODULE, [new, DBDirectory, TableName], []); start_link(open, DBDirectory, TableName) -> gen_server:start_link(?MODULE, [open, DBDirectory, TableName], []). -spec stop(db()) -> ok | {ok, _}. stop(#{texts := Pid}) when is_pid(Pid) -> gen_server:stop(Pid). -spec lookup(db(), Id :: binary()) -> Value :: binary() | error. lookup(#{texts := Pid}, Id) when is_pid(Pid), byte_size(Id) =< 63 -> Id; lookup(#{texts := Pid}, Id) when is_pid(Pid), byte_size(Id) =:= 64 -> gen_server:call(Pid, {lookup, Id}); lookup(_, _) -> error. -spec insert(db(), Value :: binary()) -> Id :: binary(). insert(#{texts := Pid}, Value) when is_pid(Pid), byte_size(Value) =< 63 -> Value; insert(#{texts := Pid}, Value) when is_pid(Pid) -> gen_server:call(Pid, {insert, Value}). Internal functions Creates a new string table in the DBDirectory in the DB DBName , with the name TableName . Deletes any existing DB file with the same name . -spec new( DBDirectory :: file:name_all(), TableName :: string() ) -> state(). new(DBDirectory, TableName) when is_binary(DBDirectory) -> new(binary_to_list(DBDirectory), TableName); new(DBDirectory, TableName) -> init_state(DBDirectory, TableName). Opens an existing string table in the DBDirectory in the DB DBName , with the name TableName . -spec open( DBDirectory :: file:name_all(), TableName :: string() ) -> state(). open(DBDirectory, TableName) when is_binary(DBDirectory) -> open(binary_to_list(DBDirectory), TableName); open(DBDirectory, TableName) -> init_state(DBDirectory, TableName). init_state(DBDirectory, TableName) -> AbsTabName = filename:join(DBDirectory, TableName), ok = filelib:ensure_dir(AbsTabName), IndxName = AbsTabName ++ ".heap", {ok, IndxFile} = dets:open_file(IndxName, []), #{indx_file => IndxFile}. lookup_string_from_id(Id, IndxFile, ReplyTo) -> Reply = case dets:lookup(IndxFile, Id) of [] -> error; [{_, String}] -> String end, gen_server:reply(ReplyTo, Reply). upsert_string_value(String, #{indx_file := IndxFile} = State) -> Hash = hash(String), case dets:lookup(IndxFile, Hash) of [] -> dets:insert(IndxFile, {Hash, String}), {Hash, State}; [_] -> {Hash, State} end. init([new, DBDirectory, TableName]) -> State = new(DBDirectory, TableName), {ok, State}; init([open, DBDirectory, TableName]) -> State = open(DBDirectory, TableName), {ok, State}. terminate(_Reason, #{indx_file := IndxFile}) -> dets:close(IndxFile). handle_cast(_Request, State) -> {noreply, State}. handle_call({insert, Value}, _From, State) -> {Reply, State1} = upsert_string_value(Value, State), {reply, Reply, State1}; handle_call({lookup, Id}, From, #{indx_file := IndxFile} = State) -> Fun = fun() -> lookup_string_from_id(Id, IndxFile, From) end, _ = erlang:spawn_link(Fun), {noreply, State}. handle_info(_Request, State) -> {noreply, State}. code_change(_, State, _) -> {ok, State}. hash(Value) -> crypto:hash(sha512, Value).
71b7ac18f28d937cc0fcee0a291e71d0ab1740883e33099cba841db695a56517
unnohideyuki/bunny
sample215.hs
take' :: Int -> [a] -> [a] take' n xs | n <= 0 = [] take' n [] = [] take' n (x:xs) = x : take' (n-1) xs main = print $ take' 5 [1, 2, 3, 4, 5, 6, 7]
null
https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/test/samples/sample215.hs
haskell
take' :: Int -> [a] -> [a] take' n xs | n <= 0 = [] take' n [] = [] take' n (x:xs) = x : take' (n-1) xs main = print $ take' 5 [1, 2, 3, 4, 5, 6, 7]
5576972b7363e1c133a95a5637c02194ca290fa046833d99fdc6cde0cdec947e
m4b/rdr
MachImports.ml
open Binary open MachBindOpcodes open MachLoadCommand (* table of tuples: <seg-index, seg-offset, type, symbol-library-ordinal, symbol-name, addend> symbol flags are undocumented *) (* TODO: move the special fields (if any) and match them with what's on disk/in c structs? *) type bind_information = { seg_index: int; seg_offset: int; bind_type: int; symbol_library_ordinal: int; symbol_name: string; symbol_flags: int; addend: int; special_dylib: int; (* seeing self = 0 assuming this means the symbol is imported from itself, because its... libSystem.B.dylib? *) } type import = { bi: bind_information; dylib: string; is_lazy: bool; offset: int; size: int; } type t = import list let empty = [] let import_to_string import = if (import.is_lazy) then Printf.sprintf "%s ~> %s" import.bi.symbol_name import.dylib else Printf.sprintf "%s -> %s" import.bi.symbol_name import.dylib let print_import import = Printf.printf "%s\n" @@ import_to_string import let imports_to_string imports = List.fold_left (fun acc import -> (Printf.sprintf "%s" @@ import_to_string import) ^ acc ) "" imports let print (imports:t) = List.iter print_import imports TODO : dyld lazy binder sets bind type to initial record as MachBindOpcodes.kBIND_TYPE_POINTER let empty_bind_information = { seg_index = 0; seg_offset = 0x0; bind_type = 0x0; special_dylib = 1; symbol_library_ordinal = 0; symbol_name = ""; symbol_flags = 0; addend = 0} let empty_bind_information is_lazy = let bind_type = if (is_lazy) then MachBindOpcodes.kBIND_TYPE_POINTER else 0x0 in { seg_index = 0; seg_offset = 0x0; bind_type = bind_type; special_dylib = 1; symbol_library_ordinal = 0; symbol_name = ""; symbol_flags = 0; addend = 0} let bind_information_to_string bi = Printf.sprintf "%s seg_index: %x seg_offset: 0x%x lib_ordinal: %d type: %d flags: %d special_dylib: %d" bi.symbol_name bi.seg_index bi.seg_offset bi.symbol_library_ordinal bi.bind_type bi.symbol_flags bi.special_dylib let print_bind_information bis = List.iteri (fun i bi -> Printf.printf "%s\n" (bind_information_to_string bi)) bis let sort = List.sort (fun i1 i2 -> if (i1.is_lazy) then if (i2.is_lazy) then compare i1.offset i2.offset else -1 else if (i2.is_lazy) then 1 else compare i1.offset i2.offset ) interpreter for BIND opcodes : runs on prebound ( non lazy ) symbols ( usually dylib extern consts and extern variables ) , and lazy symbols ( usually dylib functions ) runs on prebound (non lazy) symbols (usually dylib extern consts and extern variables), and lazy symbols (usually dylib functions) *) let debug = false let interp = false let sizeof_ptr64 = 8 let bind_interpreter bytes pos size is_lazy = let bind_info = empty_bind_information is_lazy in let rec loop pos acc bind_info = if (pos >= size) then begin if (debug) then Printf.printf "End of opcode stream\n"; acc end else let opcode = i8 bytes pos in if (interp) then begin let i = read_line() in ignore i; end; if (debug) then begin Printf.printf "%s -> 0x%x\n0x%x with %s\n" (MachBindOpcodes.opcode_to_string @@ MachBindOpcodes.get_opcode @@ opcode land kBIND_OPCODE_MASK) opcode pos (bind_information_to_string bind_info); end; match (get_opcode @@ opcode land kBIND_OPCODE_MASK) with (* we do nothing, don't update our records, and add a new, fresh record *) | BIND_OPCODE_DONE -> loop (pos + 1) acc (empty_bind_information is_lazy) | BIND_OPCODE_SET_DYLIB_ORDINAL_IMM -> let symbol_library_ordinal = opcode land kBIND_IMMEDIATE_MASK in loop (pos + 1) acc {bind_info with symbol_library_ordinal} | BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB -> let symbol_library_ordinal,pos' = Leb128.get_uleb128 bytes (pos + 1) in loop pos' acc {bind_info with symbol_library_ordinal} | BIND_OPCODE_SET_DYLIB_SPECIAL_IMM -> (* dyld puts the immediate into the symbol_library_ordinal field... *) let special_dylib = opcode land kBIND_IMMEDIATE_MASK in (* Printf.printf "special_dylib: 0x%x\n" special_dylib; *) loop (pos + 1) acc {bind_info with special_dylib} | BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM -> let symbol_flags = opcode land kBIND_IMMEDIATE_MASK in let symbol_name, pos' = stringo bytes (pos + 1) in loop pos' acc {bind_info with symbol_name; symbol_flags} | BIND_OPCODE_SET_TYPE_IMM -> let bind_type = opcode land kBIND_IMMEDIATE_MASK in loop (pos + 1) acc {bind_info with bind_type} | BIND_OPCODE_SET_ADDEND_SLEB -> let addend, pos' = Leb128.get_sleb128 bytes (pos + 1) in loop pos' acc {bind_info with addend} (* WARNING *) | BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB -> let seg_index = opcode land kBIND_IMMEDIATE_MASK in (* dyld sets the address to the segActualLoadAddress(segIndex) + uleb128: address = segActualLoadAddress(segmentIndex) + read_uleb128(p, end); *) let seg_offset,pos' = Leb128.get_uleb128 bytes (pos + 1) in loop pos' acc {bind_info with seg_index; seg_offset} | BIND_OPCODE_ADD_ADDR_ULEB -> let addr,pos' = Leb128.get_uleb128 bytes (pos + 1) in let seg_offset = bind_info.seg_offset + addr in loop pos' acc {bind_info with seg_offset} (* record the record by placing its value into our list*) | BIND_OPCODE_DO_BIND -> hmmmm , from dyld : if ( address > = segmentEndAddress ) throwBadBindingAddress(address , segmentEndAddress , segmentIndex , start , end , p ) ; ( this->*handler)(context , address , type , symbolName , symboFlags , addend , libraryOrdinal , " " , & last ) ; address + = ) ; < ------- THIS GUY if ( address >= segmentEndAddress ) throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p); (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last); address += sizeof(intptr_t); <------- THIS GUY *) sizeof_intptr_t loop (pos + 1) (bind_info::acc) {bind_info with seg_offset} (* not verified value interpretation *) | BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB -> dyld : if ( address > = segmentEndAddress ) throwBadBindingAddress(address , segmentEndAddress , segmentIndex , start , end , p ) ; ( this->*handler)(context , address , type , symbolName , symboFlags , addend , libraryOrdinal , " " , & last ) ; address + = read_uleb128(p , end ) + sizeof(intptr_t ) ; if ( address >= segmentEndAddress ) throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p); (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last); address += read_uleb128(p, end) + sizeof(intptr_t); *) so we bind the old record , then increment bind info address for the next guy , plus the ptr offset ? let addr,pos' = Leb128.get_uleb128 bytes (pos + 1) in let seg_offset = bind_info.seg_offset + addr + sizeof_ptr64 in loop pos' (bind_info::acc) {bind_info with seg_offset} | BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED -> dyld : if ( address > = segmentEndAddress ) throwBadBindingAddress(address , segmentEndAddress , segmentIndex , start , end , p ) ; ( this->*handler)(context , address , type , symbolName , symboFlags , addend , libraryOrdinal , " " , & last ) ; address + = immediate*sizeof(intptr_t ) + sizeof(intptr_t ) ; break ; if ( address >= segmentEndAddress ) throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p); (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last); address += immediate*sizeof(intptr_t) + sizeof(intptr_t); break; *) (* similarly, we bind the old record, then perform address manipulation for the next record *) let scale = opcode land kBIND_IMMEDIATE_MASK in let seg_offset = bind_info.seg_offset + (scale * sizeof_ptr64) + sizeof_ptr64 in loop (pos + 1) (bind_info::acc) {bind_info with seg_offset} | BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB -> dyld : count = read_uleb128(p , end ) ; skip = read_uleb128(p , end ) ; for ( ; i < count ; + + i ) { if ( address > = segmentEndAddress ) throwBadBindingAddress(address , segmentEndAddress , segmentIndex , start , end , p ) ; ( this->*handler)(context , address , type , symbolName , symboFlags , addend , libraryOrdinal , " " , & last ) ; address + = skip + sizeof(intptr_t ) ; } break ; count = read_uleb128(p, end); skip = read_uleb128(p, end); for (uint32_t i=0; i < count; ++i) { if ( address >= segmentEndAddress ) throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p); (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last); address += skip + sizeof(intptr_t); } break; *) let count,pos' = Leb128.get_uleb128 bytes (pos + 1) in let skip,pos'' = Leb128.get_uleb128 bytes pos' in let addr = ref bind_info.seg_offset in for i = 0 to count - 1 do addr := !addr + skip + sizeof_ptr64; done; let seg_offset = !addr in loop pos'' (bind_info::acc) {bind_info with seg_offset} in loop pos [] bind_info let bind_information_to_import libraries segments ~is_lazy:is_lazy bi = let offset = (List.nth segments bi.seg_index).MachLoadCommand.Types.fileoff + bi.seg_offset in let size = if (bi.bind_type == MachBindOpcodes.kBIND_TYPE_POINTER) then 8 else 0 in let dylib = libraries.(bi.symbol_library_ordinal) in {bi; dylib; is_lazy; offset; size} let get_imports binary dyld_info libs segments = let bind_off = dyld_info.MachLoadCommand.Types.bind_off in let bind_size = dyld_info.MachLoadCommand.Types.bind_size in let lazy_bind_off = dyld_info.MachLoadCommand.Types.lazy_bind_off in let lazy_bind_size = dyld_info.MachLoadCommand.Types.lazy_bind_size in let non_lazy_bytes = Bytes.sub binary bind_off bind_size in let lazy_bytes = Bytes.sub binary lazy_bind_off lazy_bind_size in let non_lazy_bi = bind_interpreter non_lazy_bytes 0 bind_size false in let lazy_bi = bind_interpreter lazy_bytes 0 lazy_bind_size true in let nli = List.map (bind_information_to_import libs segments ~is_lazy:false) non_lazy_bi in let li = List.map (bind_information_to_import libs segments ~is_lazy:true) lazy_bi in nli@li |> sort (* non-lazy: extern [const] <var_type> <var_name> or specially requested prebound symbols ? *)
null
https://raw.githubusercontent.com/m4b/rdr/2bf1f73fc317cd74f8c7cacd542889df729bd003/lib/mach/MachImports.ml
ocaml
table of tuples: <seg-index, seg-offset, type, symbol-library-ordinal, symbol-name, addend> symbol flags are undocumented TODO: move the special fields (if any) and match them with what's on disk/in c structs? seeing self = 0 assuming this means the symbol is imported from itself, because its... libSystem.B.dylib? we do nothing, don't update our records, and add a new, fresh record dyld puts the immediate into the symbol_library_ordinal field... Printf.printf "special_dylib: 0x%x\n" special_dylib; WARNING dyld sets the address to the segActualLoadAddress(segIndex) + uleb128: address = segActualLoadAddress(segmentIndex) + read_uleb128(p, end); record the record by placing its value into our list not verified value interpretation similarly, we bind the old record, then perform address manipulation for the next record non-lazy: extern [const] <var_type> <var_name> or specially requested prebound symbols ?
open Binary open MachBindOpcodes open MachLoadCommand type bind_information = { seg_index: int; seg_offset: int; bind_type: int; symbol_library_ordinal: int; symbol_name: string; symbol_flags: int; addend: int; } type import = { bi: bind_information; dylib: string; is_lazy: bool; offset: int; size: int; } type t = import list let empty = [] let import_to_string import = if (import.is_lazy) then Printf.sprintf "%s ~> %s" import.bi.symbol_name import.dylib else Printf.sprintf "%s -> %s" import.bi.symbol_name import.dylib let print_import import = Printf.printf "%s\n" @@ import_to_string import let imports_to_string imports = List.fold_left (fun acc import -> (Printf.sprintf "%s" @@ import_to_string import) ^ acc ) "" imports let print (imports:t) = List.iter print_import imports TODO : dyld lazy binder sets bind type to initial record as MachBindOpcodes.kBIND_TYPE_POINTER let empty_bind_information = { seg_index = 0; seg_offset = 0x0; bind_type = 0x0; special_dylib = 1; symbol_library_ordinal = 0; symbol_name = ""; symbol_flags = 0; addend = 0} let empty_bind_information is_lazy = let bind_type = if (is_lazy) then MachBindOpcodes.kBIND_TYPE_POINTER else 0x0 in { seg_index = 0; seg_offset = 0x0; bind_type = bind_type; special_dylib = 1; symbol_library_ordinal = 0; symbol_name = ""; symbol_flags = 0; addend = 0} let bind_information_to_string bi = Printf.sprintf "%s seg_index: %x seg_offset: 0x%x lib_ordinal: %d type: %d flags: %d special_dylib: %d" bi.symbol_name bi.seg_index bi.seg_offset bi.symbol_library_ordinal bi.bind_type bi.symbol_flags bi.special_dylib let print_bind_information bis = List.iteri (fun i bi -> Printf.printf "%s\n" (bind_information_to_string bi)) bis let sort = List.sort (fun i1 i2 -> if (i1.is_lazy) then if (i2.is_lazy) then compare i1.offset i2.offset else -1 else if (i2.is_lazy) then 1 else compare i1.offset i2.offset ) interpreter for BIND opcodes : runs on prebound ( non lazy ) symbols ( usually dylib extern consts and extern variables ) , and lazy symbols ( usually dylib functions ) runs on prebound (non lazy) symbols (usually dylib extern consts and extern variables), and lazy symbols (usually dylib functions) *) let debug = false let interp = false let sizeof_ptr64 = 8 let bind_interpreter bytes pos size is_lazy = let bind_info = empty_bind_information is_lazy in let rec loop pos acc bind_info = if (pos >= size) then begin if (debug) then Printf.printf "End of opcode stream\n"; acc end else let opcode = i8 bytes pos in if (interp) then begin let i = read_line() in ignore i; end; if (debug) then begin Printf.printf "%s -> 0x%x\n0x%x with %s\n" (MachBindOpcodes.opcode_to_string @@ MachBindOpcodes.get_opcode @@ opcode land kBIND_OPCODE_MASK) opcode pos (bind_information_to_string bind_info); end; match (get_opcode @@ opcode land kBIND_OPCODE_MASK) with | BIND_OPCODE_DONE -> loop (pos + 1) acc (empty_bind_information is_lazy) | BIND_OPCODE_SET_DYLIB_ORDINAL_IMM -> let symbol_library_ordinal = opcode land kBIND_IMMEDIATE_MASK in loop (pos + 1) acc {bind_info with symbol_library_ordinal} | BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB -> let symbol_library_ordinal,pos' = Leb128.get_uleb128 bytes (pos + 1) in loop pos' acc {bind_info with symbol_library_ordinal} | BIND_OPCODE_SET_DYLIB_SPECIAL_IMM -> let special_dylib = opcode land kBIND_IMMEDIATE_MASK in loop (pos + 1) acc {bind_info with special_dylib} | BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM -> let symbol_flags = opcode land kBIND_IMMEDIATE_MASK in let symbol_name, pos' = stringo bytes (pos + 1) in loop pos' acc {bind_info with symbol_name; symbol_flags} | BIND_OPCODE_SET_TYPE_IMM -> let bind_type = opcode land kBIND_IMMEDIATE_MASK in loop (pos + 1) acc {bind_info with bind_type} | BIND_OPCODE_SET_ADDEND_SLEB -> let addend, pos' = Leb128.get_sleb128 bytes (pos + 1) in loop pos' acc {bind_info with addend} | BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB -> let seg_index = opcode land kBIND_IMMEDIATE_MASK in let seg_offset,pos' = Leb128.get_uleb128 bytes (pos + 1) in loop pos' acc {bind_info with seg_index; seg_offset} | BIND_OPCODE_ADD_ADDR_ULEB -> let addr,pos' = Leb128.get_uleb128 bytes (pos + 1) in let seg_offset = bind_info.seg_offset + addr in loop pos' acc {bind_info with seg_offset} | BIND_OPCODE_DO_BIND -> hmmmm , from dyld : if ( address > = segmentEndAddress ) throwBadBindingAddress(address , segmentEndAddress , segmentIndex , start , end , p ) ; ( this->*handler)(context , address , type , symbolName , symboFlags , addend , libraryOrdinal , " " , & last ) ; address + = ) ; < ------- THIS GUY if ( address >= segmentEndAddress ) throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p); (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last); address += sizeof(intptr_t); <------- THIS GUY *) sizeof_intptr_t loop (pos + 1) (bind_info::acc) {bind_info with seg_offset} | BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB -> dyld : if ( address > = segmentEndAddress ) throwBadBindingAddress(address , segmentEndAddress , segmentIndex , start , end , p ) ; ( this->*handler)(context , address , type , symbolName , symboFlags , addend , libraryOrdinal , " " , & last ) ; address + = read_uleb128(p , end ) + sizeof(intptr_t ) ; if ( address >= segmentEndAddress ) throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p); (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last); address += read_uleb128(p, end) + sizeof(intptr_t); *) so we bind the old record , then increment bind info address for the next guy , plus the ptr offset ? let addr,pos' = Leb128.get_uleb128 bytes (pos + 1) in let seg_offset = bind_info.seg_offset + addr + sizeof_ptr64 in loop pos' (bind_info::acc) {bind_info with seg_offset} | BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED -> dyld : if ( address > = segmentEndAddress ) throwBadBindingAddress(address , segmentEndAddress , segmentIndex , start , end , p ) ; ( this->*handler)(context , address , type , symbolName , symboFlags , addend , libraryOrdinal , " " , & last ) ; address + = immediate*sizeof(intptr_t ) + sizeof(intptr_t ) ; break ; if ( address >= segmentEndAddress ) throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p); (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last); address += immediate*sizeof(intptr_t) + sizeof(intptr_t); break; *) let scale = opcode land kBIND_IMMEDIATE_MASK in let seg_offset = bind_info.seg_offset + (scale * sizeof_ptr64) + sizeof_ptr64 in loop (pos + 1) (bind_info::acc) {bind_info with seg_offset} | BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB -> dyld : count = read_uleb128(p , end ) ; skip = read_uleb128(p , end ) ; for ( ; i < count ; + + i ) { if ( address > = segmentEndAddress ) throwBadBindingAddress(address , segmentEndAddress , segmentIndex , start , end , p ) ; ( this->*handler)(context , address , type , symbolName , symboFlags , addend , libraryOrdinal , " " , & last ) ; address + = skip + sizeof(intptr_t ) ; } break ; count = read_uleb128(p, end); skip = read_uleb128(p, end); for (uint32_t i=0; i < count; ++i) { if ( address >= segmentEndAddress ) throwBadBindingAddress(address, segmentEndAddress, segmentIndex, start, end, p); (this->*handler)(context, address, type, symbolName, symboFlags, addend, libraryOrdinal, "", &last); address += skip + sizeof(intptr_t); } break; *) let count,pos' = Leb128.get_uleb128 bytes (pos + 1) in let skip,pos'' = Leb128.get_uleb128 bytes pos' in let addr = ref bind_info.seg_offset in for i = 0 to count - 1 do addr := !addr + skip + sizeof_ptr64; done; let seg_offset = !addr in loop pos'' (bind_info::acc) {bind_info with seg_offset} in loop pos [] bind_info let bind_information_to_import libraries segments ~is_lazy:is_lazy bi = let offset = (List.nth segments bi.seg_index).MachLoadCommand.Types.fileoff + bi.seg_offset in let size = if (bi.bind_type == MachBindOpcodes.kBIND_TYPE_POINTER) then 8 else 0 in let dylib = libraries.(bi.symbol_library_ordinal) in {bi; dylib; is_lazy; offset; size} let get_imports binary dyld_info libs segments = let bind_off = dyld_info.MachLoadCommand.Types.bind_off in let bind_size = dyld_info.MachLoadCommand.Types.bind_size in let lazy_bind_off = dyld_info.MachLoadCommand.Types.lazy_bind_off in let lazy_bind_size = dyld_info.MachLoadCommand.Types.lazy_bind_size in let non_lazy_bytes = Bytes.sub binary bind_off bind_size in let lazy_bytes = Bytes.sub binary lazy_bind_off lazy_bind_size in let non_lazy_bi = bind_interpreter non_lazy_bytes 0 bind_size false in let lazy_bi = bind_interpreter lazy_bytes 0 lazy_bind_size true in let nli = List.map (bind_information_to_import libs segments ~is_lazy:false) non_lazy_bi in let li = List.map (bind_information_to_import libs segments ~is_lazy:true) lazy_bi in nli@li |> sort
fd927b517a334b0fa4e6c5ba259f94ea59d10016b1ff199a7b2a1c48be5c6499
typelead/intellij-eta
InstanceSigs00001.hs
# LANGUAGE InstanceSigs # module InstanceSigs00001 where data T a = MkT a a instance Eq a => Eq (T a) where (==) :: T a -> T a -> Bool -- The signature (==) (MkT x1 x2) (MkTy y1 y2) = x1==y1 && x2==y2
null
https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/test/resources/fixtures/eta/sources/InstanceSigs00001.hs
haskell
The signature
# LANGUAGE InstanceSigs # module InstanceSigs00001 where data T a = MkT a a instance Eq a => Eq (T a) where (==) (MkT x1 x2) (MkTy y1 y2) = x1==y1 && x2==y2
24915e17b903bb7f26ce808cc497b6cdcfc0386be28840b9831d7d81e377474a
MLstate/opalang
compilationUtils.ml
Copyright © 2011 MLstate This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with . If not , see < / > . Copyright © 2011 MLstate This file is part of Opa. Opa is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Opa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Opa. If not, see </>. *) (** Some functions used by compilation passes. *) (* -- *) let slash2filename f = let n = String.length f in let buf = Buffer.create n in for i = 0 to n-1 do if f.[i] = '/' then Buffer.add_string buf File.path_sep else Buffer.add_char buf f.[i] done; Buffer.contents buf * new version of StaticsInclude : see file ofile.ml let file_content_and_embedded ?(warn_no_embedded=false) f = match StaticsInclude.get_file f with | Some c -> c | None -> (if warn_no_embedded then prerr_endline (Printf.sprintf "%s is not embedded" f)); File.content (PathTransform.string_to_mysys f) let output fname s = if not (File.output fname s) then failwith (Printf.sprintf "Can't write file \"%s\" (current path is \"%s\")" fname (Sys.getcwd ()))
null
https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/opa/compilationUtils.ml
ocaml
* Some functions used by compilation passes. --
Copyright © 2011 MLstate This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with . If not , see < / > . Copyright © 2011 MLstate This file is part of Opa. Opa is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Opa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Opa. If not, see </>. *) let slash2filename f = let n = String.length f in let buf = Buffer.create n in for i = 0 to n-1 do if f.[i] = '/' then Buffer.add_string buf File.path_sep else Buffer.add_char buf f.[i] done; Buffer.contents buf * new version of StaticsInclude : see file ofile.ml let file_content_and_embedded ?(warn_no_embedded=false) f = match StaticsInclude.get_file f with | Some c -> c | None -> (if warn_no_embedded then prerr_endline (Printf.sprintf "%s is not embedded" f)); File.content (PathTransform.string_to_mysys f) let output fname s = if not (File.output fname s) then failwith (Printf.sprintf "Can't write file \"%s\" (current path is \"%s\")" fname (Sys.getcwd ()))
2cbce2b794b67164dcb65c23f9be24fe7559cf32d5f730f0f4bbbd9b90b270de
mariaschett/ppltr
blk_generator.ml
Copyright 2020 and 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 . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Core let parse_bytecode bc = Sedlexing.Latin1.from_string bc |> Ebso.Parser.parse ~ignore_data_section:true let sliding_window xs sz = if sz <= 0 then [[]] else let rec sw xs acc = if List.length xs <= sz then xs :: acc else sw (List.tl_exn xs) (List.take xs sz :: acc) in sw xs [] |> List.rev let drop_non_encodable b = let open Ebso.Program in match b with | NotEncodable _ -> None | Next b | Terminal (b, _) -> Some b let equiv_mod_wsz b1 b2 = let abstract_block b = to distinguish values between -7 and + 7 let word_size = 4 in Ebso.Program.val_to_const word_size b in Sorg.Program_schema.alpha_equal (abstract_block b1) (abstract_block b2) let rec insert_block gbs b = match gbs with | [] -> [(b, 1)] | (b', n) :: gbs -> if equiv_mod_wsz b b' then (b', n + 1) :: gbs else (b', n) :: insert_block gbs b let generate_blks bcs = List.map ~f:parse_bytecode bcs |> List.concat_map ~f:Ebso.Program.split_into_bbs |> List.filter_map ~f:drop_non_encodable let write_blks in_csv out_csv = Csv.Rows.load ~has_header:true in_csv |> List.map ~f:(fun r -> Csv.Row.find r "bytecode") |> generate_blks |> List.map ~f:Ebso.Printer.show_ebso_snippet |> List.cons Ebso.Printer.ebso_snippet_header |> Csv.save out_csv let window_blks sz bs = let bs = List.map ~f:parse_bytecode bs in let bbs = List.concat_map bs ~f:(fun b -> sliding_window b sz) in let lenbbs = List.length bbs in Out_channel.print_endline ("Transformed blocks into " ^ (Int.to_string lenbbs) ^ " windowed blocks."); List.foldi bbs ~init:[] ~f:(fun i gbs b -> Out_channel.print_endline ("Processing block " ^ (Int.to_string i) ^ " of " ^ (Int.to_string lenbbs)); insert_block gbs b) let write_windowed_blks in_csv out_csv peephole_sz = Csv.Rows.load ~has_header:true in_csv |> List.map ~f:(fun r -> Csv.Row.find r "source bytecode") |> window_blks peephole_sz |> List.rev_map ~f:(fun (p, c) -> Ebso.Printer.show_ebso_snippet p @ [[%show: int] c]) |> List.cons (Ebso.Printer.ebso_snippet_header @ ["instances"]) |> Csv.save out_csv
null
https://raw.githubusercontent.com/mariaschett/ppltr/67f45f9e329800e6c39094d7c3c3af8d168638da/lib/blk_generator.ml
ocaml
Copyright 2020 and 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 . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *) open Core let parse_bytecode bc = Sedlexing.Latin1.from_string bc |> Ebso.Parser.parse ~ignore_data_section:true let sliding_window xs sz = if sz <= 0 then [[]] else let rec sw xs acc = if List.length xs <= sz then xs :: acc else sw (List.tl_exn xs) (List.take xs sz :: acc) in sw xs [] |> List.rev let drop_non_encodable b = let open Ebso.Program in match b with | NotEncodable _ -> None | Next b | Terminal (b, _) -> Some b let equiv_mod_wsz b1 b2 = let abstract_block b = to distinguish values between -7 and + 7 let word_size = 4 in Ebso.Program.val_to_const word_size b in Sorg.Program_schema.alpha_equal (abstract_block b1) (abstract_block b2) let rec insert_block gbs b = match gbs with | [] -> [(b, 1)] | (b', n) :: gbs -> if equiv_mod_wsz b b' then (b', n + 1) :: gbs else (b', n) :: insert_block gbs b let generate_blks bcs = List.map ~f:parse_bytecode bcs |> List.concat_map ~f:Ebso.Program.split_into_bbs |> List.filter_map ~f:drop_non_encodable let write_blks in_csv out_csv = Csv.Rows.load ~has_header:true in_csv |> List.map ~f:(fun r -> Csv.Row.find r "bytecode") |> generate_blks |> List.map ~f:Ebso.Printer.show_ebso_snippet |> List.cons Ebso.Printer.ebso_snippet_header |> Csv.save out_csv let window_blks sz bs = let bs = List.map ~f:parse_bytecode bs in let bbs = List.concat_map bs ~f:(fun b -> sliding_window b sz) in let lenbbs = List.length bbs in Out_channel.print_endline ("Transformed blocks into " ^ (Int.to_string lenbbs) ^ " windowed blocks."); List.foldi bbs ~init:[] ~f:(fun i gbs b -> Out_channel.print_endline ("Processing block " ^ (Int.to_string i) ^ " of " ^ (Int.to_string lenbbs)); insert_block gbs b) let write_windowed_blks in_csv out_csv peephole_sz = Csv.Rows.load ~has_header:true in_csv |> List.map ~f:(fun r -> Csv.Row.find r "source bytecode") |> window_blks peephole_sz |> List.rev_map ~f:(fun (p, c) -> Ebso.Printer.show_ebso_snippet p @ [[%show: int] c]) |> List.cons (Ebso.Printer.ebso_snippet_header @ ["instances"]) |> Csv.save out_csv
0267fab3cd2a1f66b0cc83f404bac00a443b9c640018b4344fb787e1a6b44992
melange-re/melange
bsb_path_resolver.ml
open Ext_json_types let ( // ) = Ext_path.combine let cache : string Hash_string.t = Hash_string.create 0 let extract_paths_from_importmap cwd json = match json with | Obj { map } -> ( match Map_string.find_opt map Bsb_build_schemas.workspace with | Some (Obj { map }) -> Map_string.bindings map |> List.iter (fun (key, value) -> match value with | Ext_json_types.Str { str } -> Hash_string.add cache key (Ext_path.normalize_absolute_path (cwd // str)) | _ -> ()) | _ -> ()) | _ -> () let resolve_import_map_package package = Hash_string.find_opt cache package
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/mel/bsb_path_resolver.ml
ocaml
open Ext_json_types let ( // ) = Ext_path.combine let cache : string Hash_string.t = Hash_string.create 0 let extract_paths_from_importmap cwd json = match json with | Obj { map } -> ( match Map_string.find_opt map Bsb_build_schemas.workspace with | Some (Obj { map }) -> Map_string.bindings map |> List.iter (fun (key, value) -> match value with | Ext_json_types.Str { str } -> Hash_string.add cache key (Ext_path.normalize_absolute_path (cwd // str)) | _ -> ()) | _ -> ()) | _ -> () let resolve_import_map_package package = Hash_string.find_opt cache package
ac1e0f29762d2c86f5c85875456f084ca64701181f7f5a2bc333f9822a64b283
nd/sicp
2.41.scm
;;append-map is the same as flatmap (defined in mzscheme) (define (triples n s) (append-map (lambda (i) (append-map (lambda (j) (append-map (lambda (k) (list (list i j k))) (filter (lambda (k) (and (not (= i k)) (not (= j k)) (= (+ i j k) s))) (enumerate-interval 1 n)))) (filter (lambda (j) (not (= i j))) (enumerate-interval 1 n)))) (enumerate-interval 1 n)))
null
https://raw.githubusercontent.com/nd/sicp/d8587a0403d95af7c7bcf59b812f98c4f8550afd/ch02/2.41.scm
scheme
append-map is the same as flatmap (defined in mzscheme)
(define (triples n s) (append-map (lambda (i) (append-map (lambda (j) (append-map (lambda (k) (list (list i j k))) (filter (lambda (k) (and (not (= i k)) (not (= j k)) (= (+ i j k) s))) (enumerate-interval 1 n)))) (filter (lambda (j) (not (= i j))) (enumerate-interval 1 n)))) (enumerate-interval 1 n)))
4e139a20d42f6ec21eaa630b6fa6c49e525154c1fca98b37278bc55fececdb0d
meriken/ju
project.clj
(defproject ju "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :source-paths ["src" "src-cljc"] :repositories {"4thline.org-repo" ""} Luminus [org.clojure/clojure "1.7.0"] [selmer "0.9.5"] [markdown-clj "0.9.82"] [environ "1.0.1"] [metosin/ring-middleware-format "0.6.0"] [metosin/ring-http-response "0.6.5"] [bouncer "0.3.3"] [org.clojure/tools.nrepl "0.2.12"] [com.taoensso/tower "3.0.2"] [com.taoensso/timbre "4.1.4"] [com.fzakaria/slf4j-timbre "0.2.1"] [compojure "1.4.0"] ;not compatible with launch4j ;[ring-webjars "0.1.1"] ;[org.webjars/bootstrap "3.3.6"] ;[org.webjars/jquery "2.1.4"] [ring/ring-defaults "0.1.5"] [ring "1.4.0" :exclusions [ring/ring-jetty-adapter]] [mount "0.1.5"] [buddy "0.8.2"] [ conman " 0.2.7 " ] [mysql/mysql-connector-java "5.1.34"] [org.clojure/clojurescript "1.7.170" :scope "provided"] [reagent "0.5.1"] [reagent-forms "0.5.13"] [reagent-utils "0.1.5"] [secretary "1.2.3"] [org.clojure/core.async "0.2.374"] [cljs-ajax "0.5.1"] [metosin/compojure-api "0.24.1"] [ metosin / ring - swagger - ui " 2.1.3 - 4 " ] [ org.immutant/web " 2.1.1 " : exclusions [ ch.qos.logback/logback-classic ] ] [org.immutant/web "2.1.2" :exclusions [ch.qos.logback/logback-classic]] [com.h2database/h2 "1.4.191"] [org.hsqldb/hsqldb "2.3.3"] [clj-http "2.0.0"] [korma "0.4.2"] [org.clojure/java.jdbc "0.3.7"] [pandect "0.5.4"] [ venantius / accountant " 0.1.6 " ] [jayq "2.5.4"] [com.andrewmcveigh/cljs-time "0.3.14"] [org.clojure/data.codec "0.1.0"] [ring-middleware-format "0.7.0"] [digest "1.4.4"] [org.clojure/math.numeric-tower "0.0.4"] ;[commons-lang/commons-lang "2.6"] [org.apache.commons/commons-lang3 "3.1"] [log4j "1.2.17" :exclusions [javax.mail/mail javax.jms/jms com.sun.jdmk/jmxtools com.sun.jmx/jmxri]] [com.twelvemonkeys.imageio/imageio-core "3.1.1"] [com.twelvemonkeys.imageio/imageio-jpeg "3.1.1"] [cheshire "5.5.0"] [clj-rss "0.2.3"] [org.clojure/math.combinatorics "0.1.1"] [org.fourthline.cling/cling-core "2.1.1-SNAPSHOT"] [org.fourthline.cling/cling-support "2.1.1-SNAPSHOT"] [ org.bitlet/weupnp " 0.1.4 " ] ] :min-lein-version "2.0.0" :uberjar-name "ju.jar" :jvm-opts [;"-server" "-XX:ThreadStackSize=4096" "-XX:-OmitStackTraceInFastThrow" "-Xmx1g" "-XX:+UseParNewGC" "-XX:+UseConcMarkSweepGC" ;"-XX:+UseG1GC" "-XX:MaxGCPauseMillis=1000" ] :resource-paths ["resources" "target/cljsbuild"] :main ju.core :plugins [[lein-environ "1.0.1"] [lein-cljsbuild "1.1.1"] [lein-uberwar "0.1.0"]] :uberwar {:handler ju.handler/app :init ju.handler/init :destroy ju.handler/destroy :name "ju.war"} :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :cljsbuild {:builds {:app {:source-paths ["src-cljs" "src-cljc"] :compiler {:output-to "target/cljsbuild/public/js/app.js" :output-dir "target/cljsbuild/public/js/out" :externs ["react/externs/react.js" "externs/gpt.js" "externs/jquery.js" "externs/hoverIntent.js" "externs/twitter-bootstrap.js" "externs/blueimp.js" "externs/highlight.js" "externs/emojione.js" "externs/bootstrap-dialog.js"] :pretty-print true}}}} :profiles {:uberjar {:omit-source true :env {:production true} :prep-tasks ["compile" ["cljsbuild" "once"]] :cljsbuild {:builds {:app {:source-paths ["env/prod/cljs"] :compiler {:optimizations :advanced :pretty-print false :closure-warnings {:externs-validation :off :non-standard-jsdoc :off}}}}} :aot :all :source-paths ["env/prod/clj"]} :dev [:project/dev :profiles/dev] :test [:project/test :profiles/test] :project/dev {:dependencies [[prone "0.8.2"] [ring/ring-mock "0.3.0"] [ring/ring-devel "1.4.0"] [pjstadig/humane-test-output "0.7.1"] [com.cemerick/piggieback "0.2.2-SNAPSHOT"] [lein-figwheel "0.5.0-2"] [mvxcvi/puget "1.0.0"]] :plugins [[lein-figwheel "0.5.0-2"]] :cljsbuild {:builds {:app {:source-paths ["env/dev/cljs"] :compiler {:main "ju.app" :asset-path "/js/out" :optimizations :none :source-map true}}}} :figwheel {:http-server-root "public" :server-port 3449 :nrepl-port 7002 :nrepl-middleware ["cemerick.piggieback/wrap-cljs-repl"] :css-dirs ["resources/public/css"] :ring-handler ju.handler/app} :source-paths ["env/dev/clj"] :repl-options {:init-ns ju.core} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)] when : nrepl - port is set the application starts the nREPL server on load :env {:dev true :port 8888 :nrepl-port 7000 :log-level :trace}} :project/test {:env {:test true :port 3001 :nrepl-port 7001 :log-level :trace}} :profiles/dev {} :profiles/test {}})
null
https://raw.githubusercontent.com/meriken/ju/99caa4625535d3da66002c460bf16d8708cabd7e/project.clj
clojure
not compatible with launch4j [ring-webjars "0.1.1"] [org.webjars/bootstrap "3.3.6"] [org.webjars/jquery "2.1.4"] [commons-lang/commons-lang "2.6"] "-server" "-XX:+UseG1GC"
(defproject ju "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :source-paths ["src" "src-cljc"] :repositories {"4thline.org-repo" ""} Luminus [org.clojure/clojure "1.7.0"] [selmer "0.9.5"] [markdown-clj "0.9.82"] [environ "1.0.1"] [metosin/ring-middleware-format "0.6.0"] [metosin/ring-http-response "0.6.5"] [bouncer "0.3.3"] [org.clojure/tools.nrepl "0.2.12"] [com.taoensso/tower "3.0.2"] [com.taoensso/timbre "4.1.4"] [com.fzakaria/slf4j-timbre "0.2.1"] [compojure "1.4.0"] [ring/ring-defaults "0.1.5"] [ring "1.4.0" :exclusions [ring/ring-jetty-adapter]] [mount "0.1.5"] [buddy "0.8.2"] [ conman " 0.2.7 " ] [mysql/mysql-connector-java "5.1.34"] [org.clojure/clojurescript "1.7.170" :scope "provided"] [reagent "0.5.1"] [reagent-forms "0.5.13"] [reagent-utils "0.1.5"] [secretary "1.2.3"] [org.clojure/core.async "0.2.374"] [cljs-ajax "0.5.1"] [metosin/compojure-api "0.24.1"] [ metosin / ring - swagger - ui " 2.1.3 - 4 " ] [ org.immutant/web " 2.1.1 " : exclusions [ ch.qos.logback/logback-classic ] ] [org.immutant/web "2.1.2" :exclusions [ch.qos.logback/logback-classic]] [com.h2database/h2 "1.4.191"] [org.hsqldb/hsqldb "2.3.3"] [clj-http "2.0.0"] [korma "0.4.2"] [org.clojure/java.jdbc "0.3.7"] [pandect "0.5.4"] [ venantius / accountant " 0.1.6 " ] [jayq "2.5.4"] [com.andrewmcveigh/cljs-time "0.3.14"] [org.clojure/data.codec "0.1.0"] [ring-middleware-format "0.7.0"] [digest "1.4.4"] [org.clojure/math.numeric-tower "0.0.4"] [org.apache.commons/commons-lang3 "3.1"] [log4j "1.2.17" :exclusions [javax.mail/mail javax.jms/jms com.sun.jdmk/jmxtools com.sun.jmx/jmxri]] [com.twelvemonkeys.imageio/imageio-core "3.1.1"] [com.twelvemonkeys.imageio/imageio-jpeg "3.1.1"] [cheshire "5.5.0"] [clj-rss "0.2.3"] [org.clojure/math.combinatorics "0.1.1"] [org.fourthline.cling/cling-core "2.1.1-SNAPSHOT"] [org.fourthline.cling/cling-support "2.1.1-SNAPSHOT"] [ org.bitlet/weupnp " 0.1.4 " ] ] :min-lein-version "2.0.0" :uberjar-name "ju.jar" "-XX:ThreadStackSize=4096" "-XX:-OmitStackTraceInFastThrow" "-Xmx1g" "-XX:+UseParNewGC" "-XX:+UseConcMarkSweepGC" "-XX:MaxGCPauseMillis=1000" ] :resource-paths ["resources" "target/cljsbuild"] :main ju.core :plugins [[lein-environ "1.0.1"] [lein-cljsbuild "1.1.1"] [lein-uberwar "0.1.0"]] :uberwar {:handler ju.handler/app :init ju.handler/init :destroy ju.handler/destroy :name "ju.war"} :clean-targets ^{:protect false} [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :cljsbuild {:builds {:app {:source-paths ["src-cljs" "src-cljc"] :compiler {:output-to "target/cljsbuild/public/js/app.js" :output-dir "target/cljsbuild/public/js/out" :externs ["react/externs/react.js" "externs/gpt.js" "externs/jquery.js" "externs/hoverIntent.js" "externs/twitter-bootstrap.js" "externs/blueimp.js" "externs/highlight.js" "externs/emojione.js" "externs/bootstrap-dialog.js"] :pretty-print true}}}} :profiles {:uberjar {:omit-source true :env {:production true} :prep-tasks ["compile" ["cljsbuild" "once"]] :cljsbuild {:builds {:app {:source-paths ["env/prod/cljs"] :compiler {:optimizations :advanced :pretty-print false :closure-warnings {:externs-validation :off :non-standard-jsdoc :off}}}}} :aot :all :source-paths ["env/prod/clj"]} :dev [:project/dev :profiles/dev] :test [:project/test :profiles/test] :project/dev {:dependencies [[prone "0.8.2"] [ring/ring-mock "0.3.0"] [ring/ring-devel "1.4.0"] [pjstadig/humane-test-output "0.7.1"] [com.cemerick/piggieback "0.2.2-SNAPSHOT"] [lein-figwheel "0.5.0-2"] [mvxcvi/puget "1.0.0"]] :plugins [[lein-figwheel "0.5.0-2"]] :cljsbuild {:builds {:app {:source-paths ["env/dev/cljs"] :compiler {:main "ju.app" :asset-path "/js/out" :optimizations :none :source-map true}}}} :figwheel {:http-server-root "public" :server-port 3449 :nrepl-port 7002 :nrepl-middleware ["cemerick.piggieback/wrap-cljs-repl"] :css-dirs ["resources/public/css"] :ring-handler ju.handler/app} :source-paths ["env/dev/clj"] :repl-options {:init-ns ju.core} :injections [(require 'pjstadig.humane-test-output) (pjstadig.humane-test-output/activate!)] when : nrepl - port is set the application starts the nREPL server on load :env {:dev true :port 8888 :nrepl-port 7000 :log-level :trace}} :project/test {:env {:test true :port 3001 :nrepl-port 7001 :log-level :trace}} :profiles/dev {} :profiles/test {}})
6103ac72ea83e05567a2c7f7589b1f55aaefe2a43c62d90b6e5c0d98985f9688
FundingCircle/fc4-framework
test_utils.clj
(ns fc4.test-utils "Utility functions to integrate clojure.spec.test/check and expound with clojure.test. Originally inspired by -Stevcev/dc628109abd840c7553de1c5d7d55608" (:require [clojure.test :as t :refer [is]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [expound.alpha :as expound])) (defn make-opts "Helper to construct options to be passed to st/check. See -api.html#clojure.spec.test.alpha/check" [num-tests gen] {:gen gen :clojure.spec.test.check/opts {:num-tests num-tests}}) ;; TODO: maybe this should be a macro; might improve stack traces (which ;; currently show the `is` as being in this file, in this fn, because it ;; is.) (defn check "Helper fn to integrate clojure.spec.test/check with clojure.test. The third (optional) arg is a map of generator overrides, e.g. `{:foo/bar #(s/gen string?)}`" ([sym] (check sym 1000 {})) ([sym num-tests] (check sym num-tests {})) ([sym num-tests gen] (let [results (st/check sym (make-opts num-tests gen))] (is (nil? (-> results first :failure)) (binding [s/*explain-out* expound/printer] (expound/explain-results-str results))))))
null
https://raw.githubusercontent.com/FundingCircle/fc4-framework/674af39e7edb2cbfd3e1941e6abe80fd87d93bed/test/fc4/test_utils.clj
clojure
TODO: maybe this should be a macro; might improve stack traces (which currently show the `is` as being in this file, in this fn, because it is.)
(ns fc4.test-utils "Utility functions to integrate clojure.spec.test/check and expound with clojure.test. Originally inspired by -Stevcev/dc628109abd840c7553de1c5d7d55608" (:require [clojure.test :as t :refer [is]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [expound.alpha :as expound])) (defn make-opts "Helper to construct options to be passed to st/check. See -api.html#clojure.spec.test.alpha/check" [num-tests gen] {:gen gen :clojure.spec.test.check/opts {:num-tests num-tests}}) (defn check "Helper fn to integrate clojure.spec.test/check with clojure.test. The third (optional) arg is a map of generator overrides, e.g. `{:foo/bar #(s/gen string?)}`" ([sym] (check sym 1000 {})) ([sym num-tests] (check sym num-tests {})) ([sym num-tests gen] (let [results (st/check sym (make-opts num-tests gen))] (is (nil? (-> results first :failure)) (binding [s/*explain-out* expound/printer] (expound/explain-results-str results))))))
a5234b5574b8ed3b4cb7972fe81f8cb112c12dcaf01bec2f14794ae2c21705ed
haskell-mafia/boris
Data.hs
# LANGUAGE NoImplicitPrelude # module Boris.Http.Data ( ConfigLocation (..) , ClientLocale (..) ) where import Data.Time.Zones (TZ) import Mismi.S3 (Address) import P newtype ConfigLocation = ConfigLocation { configLocationAddress :: Address } deriving (Eq, Show) data ClientLocale = ClientLocale { clientLocaleTZ :: TZ } deriving (Eq, Show)
null
https://raw.githubusercontent.com/haskell-mafia/boris/fb670071600e8b2d8dbb9191fcf6bf8488f83f5a/boris-http/src/Boris/Http/Data.hs
haskell
# LANGUAGE NoImplicitPrelude # module Boris.Http.Data ( ConfigLocation (..) , ClientLocale (..) ) where import Data.Time.Zones (TZ) import Mismi.S3 (Address) import P newtype ConfigLocation = ConfigLocation { configLocationAddress :: Address } deriving (Eq, Show) data ClientLocale = ClientLocale { clientLocaleTZ :: TZ } deriving (Eq, Show)
4a7151e8166246d27f09b66b15f3f9f7d91e57ac8d763846b1af85c6d6048778
matijapretnar/millet
webInterpreter.mli
include WebBackend.S
null
https://raw.githubusercontent.com/matijapretnar/millet/6d451ad010e602b653116a0bd77a6fb28c2052f9/src/05-backends/interpreter/web/webInterpreter.mli
ocaml
include WebBackend.S
bd729664001f248b5ba9139b35e33c271adb68891e05c1210d86402b7cd0f48f
nunchaku-inria/nunchaku
TypeUnify.ml
(* This file is free software, part of nunchaku. See file "license" for more details. *) (** {1 Unification of Types} *) module TI = TermInner module TyI = TypePoly module Subst = Var.Subst module Loc = Location let section = Utils.Section.make "unif" $ inject let loc = Location.internal module TI = TermInner module T = TermTyped . Default module U = TermTyped . Util(T ) module = Make(T ) let repr = T.repr let loc = Location.internal module TI = TermInner module T = TermTyped.Default module U = TermTyped.Util(T) module Unif = Make(T) let repr = T.repr *) type 'a sequence = ('a -> unit) -> unit module Make(T : TI.REPR_LOC) = struct module P = TI.Print(T) module Ty = TypePoly.Make(T) exception Fail of (T.t * T.t) list * string * Raised when unification fails . The list of pairs of types is the unification stack ( with the innermost types first ) unification stack (with the innermost types first) *) let fpf = Format.fprintf let spf = CCFormat.sprintf let pp_ty = P.pp let () = Printexc.register_printer (function | Fail (stack, msg) -> let pp2 out (ty1,ty2) = fpf out "@[<hv2>trying to unify@ @[<2>`@[%a@]`@ at %a@]@ @[<2>and `@[%a@]`@ at %a@]@]" pp_ty ty1 Loc.pp (T.loc ty1) pp_ty ty2 Loc.pp (T.loc ty2) in Some (spf "@[<hv2>unification error: %s:@ %a@]" msg (CCFormat.list pp2) stack) | _ -> None ) (* does [var] occur in [ty]? *) let rec occur_check_ ~var ty = match Ty.repr ty with | TyI.App (f, l) -> occur_check_ ~var f || List.exists (occur_check_ ~var) l | TyI.Var _ -> false (* bound var *) | TyI.Const _ | TyI.Builtin _ -> false | TyI.Meta var' -> assert (MetaVar.can_bind var'); MetaVar.equal var var' | TyI.Arrow (a,b) -> occur_check_ ~var a || occur_check_ ~var b | TyI.Forall (_,t) -> occur_check_ ~var t (* NOTE: after dependent types are added, will need to recurse into types too for unification and occur-check *) let push_ a b c = (a,b) :: c let fail ~stack msg = raise (Fail (stack, msg)) let failf ~stack fmt = Utils.exn_ksprintf fmt ~f:(fun msg -> raise (Fail (stack, msg))) let rec flatten_app_ f l = match Ty.repr f with | TyI.App (f1, l1) -> flatten_app_ f1 (l1 @ l) | _ -> f, l (* bound: set of bound variables, that cannot be unified *) let unify_exn ty1 ty2 = Utils.debugf ~section 5 "@[<hv2>unify `@[%a@]`@ and `@[%a@]`@]" (fun k-> k pp_ty ty1 pp_ty ty2); let bound = ref Subst.empty in (* keep a stack of unification attempts *) let rec unify_ ~stack ty1 ty2 = let stack = push_ ( ty1) ( ty2) stack in match Ty.repr ty1, Ty.repr ty2 with | TyI.Builtin s1, TyI.Builtin s2 -> if TI.TyBuiltin.equal s1 s2 then () else fail ~stack "incompatible symbols" | TyI.Const i1, TyI.Const i2 -> if ID.equal i1 i2 then () else fail ~stack "incompatible symbols" | TyI.Var v1, TyI.Var v2 when Var.equal v1 v2 -> () | TyI.Var v1, TyI.Var v2 -> begin try let var = Subst.find_exn ~subst:!bound v1 in let var' = Subst.find_exn ~subst:!bound v2 in if Var.equal var var' then () else failf ~stack "bound variables %a and %a are incompatible" Var.pp v1 Var.pp v2 with Not_found -> fail ~stack "incompatible variables" end | TyI.Meta v1, TyI.Meta v2 when MetaVar.equal v1 v2 -> () | TyI.Meta var, _ -> assert (MetaVar.can_bind var); (* TODO: check that ty2 is closed! not bound vars allowed *) if occur_check_ ~var ty2 then ( failf ~stack "cycle detected (variable %a occurs in type)" MetaVar.pp var ) else ( MetaVar.bind ~var ty2 ) | _, TyI.Meta var -> assert (MetaVar.can_bind var); if occur_check_ ~var ty1 then ( failf ~stack "cycle detected (variable %a occurs in type)" MetaVar.pp var ) else ( MetaVar.bind ~var ty1 ) | TyI.App (f1,l1), TyI.App (f2,l2) -> (* NOTE: if partial application in types is allowed, we must allow [length l1 <> length l2]. In that case, unification proceeds from the right *) let f1, l1 = flatten_app_ f1 l1 in let f2, l2 = flatten_app_ f2 l2 in if List.length l1<>List.length l2 then failf ~stack "different number of arguments (%d and %d resp.)" (List.length l1) (List.length l2); unify_ ~stack f1 f2; List.iter2 (unify_ ~stack) l1 l2 | TyI.Arrow (l1,r1), TyI.Arrow (l2,r2) -> unify_ ~stack l1 l2; unify_ ~stack r1 r2 | TyI.Forall (v1,t1), TyI.Forall (v2,t2) -> assert (not (Subst.mem ~subst:!bound v1)); assert (not (Subst.mem ~subst:!bound v2)); let v = Var.make ~ty:(Var.ty v1) ~name:"?" in bound := Subst.add ~subst:(Subst.add ~subst:!bound v2 v) v1 v; unify_ ~stack t1 t2 | TyI.Const _, _ | TyI.Builtin _,_ | TyI.App (_,_),_ | TyI.Arrow (_,_),_ -> fail ~stack "incompatible types" | TyI.Var _, _ -> fail ~stack "incompatible types" | TyI.Forall (_,_),_ -> fail ~stack "incompatible types" in unify_ ~stack:[] ty1 ty2 $ R let v = U.ty_meta_var ~loc ( MetaVar.make ~name:"x " ) in let f = U.ty_var ~loc ( Var.make ~ty : U.ty_type ~name:"f " ) in let a ' = ID.make " a " in let a = U.ty_const ~loc a ' in let t1 = U.ty_app ~loc f [ v ] in let t2 = U.ty_app ~loc f [ a ] in Unif.unify_exn t1 t2 ; assert_bool " v is a " ( match T.repr v with | TI.Const i d ' - > ID.equal a ' i d ' | _ - > false ) ; let v = U.ty_meta_var ~loc (MetaVar.make ~name:"x") in let f = U.ty_var ~loc (Var.make ~ty:U.ty_type ~name:"f") in let a' = ID.make "a" in let a = U.ty_const ~loc a' in let t1 = U.ty_app ~loc f [v] in let t2 = U.ty_app ~loc f [a] in Unif.unify_exn t1 t2; assert_bool "v is a" (match T.repr v with | TI.Const id' -> ID.equal a' id' | _ -> false ); *) type meta_vars_set = T.t MetaVar.t ID.Map.t (* a set of meta-variable with their reference *) let free_meta_vars ?(init=ID.Map.empty) ty = let rec aux acc ty = match Ty.repr ty with | TyI.Builtin _ | TyI.Const _ -> acc | TyI.Var v -> aux acc (Var.ty v) (* type can also contain metas *) | TyI.Meta var -> assert (MetaVar.can_bind var); ID.Map.add (MetaVar.id var) var acc | TyI.App (f,l) -> let acc = aux acc f in List.fold_left aux acc l | TyI.Arrow (a,b) -> let acc = aux acc a in aux acc b | TyI.Forall (v,t) -> (* the variable should not be a meta *) let acc = aux acc (Var.ty v) in aux acc t in aux init ty end
null
https://raw.githubusercontent.com/nunchaku-inria/nunchaku/16f33db3f5e92beecfb679a13329063b194f753d/src/core/TypeUnify.ml
ocaml
This file is free software, part of nunchaku. See file "license" for more details. * {1 Unification of Types} does [var] occur in [ty]? bound var NOTE: after dependent types are added, will need to recurse into types too for unification and occur-check bound: set of bound variables, that cannot be unified keep a stack of unification attempts TODO: check that ty2 is closed! not bound vars allowed NOTE: if partial application in types is allowed, we must allow [length l1 <> length l2]. In that case, unification proceeds from the right a set of meta-variable with their reference type can also contain metas the variable should not be a meta
module TI = TermInner module TyI = TypePoly module Subst = Var.Subst module Loc = Location let section = Utils.Section.make "unif" $ inject let loc = Location.internal module TI = TermInner module T = TermTyped . Default module U = TermTyped . Util(T ) module = Make(T ) let repr = T.repr let loc = Location.internal module TI = TermInner module T = TermTyped.Default module U = TermTyped.Util(T) module Unif = Make(T) let repr = T.repr *) type 'a sequence = ('a -> unit) -> unit module Make(T : TI.REPR_LOC) = struct module P = TI.Print(T) module Ty = TypePoly.Make(T) exception Fail of (T.t * T.t) list * string * Raised when unification fails . The list of pairs of types is the unification stack ( with the innermost types first ) unification stack (with the innermost types first) *) let fpf = Format.fprintf let spf = CCFormat.sprintf let pp_ty = P.pp let () = Printexc.register_printer (function | Fail (stack, msg) -> let pp2 out (ty1,ty2) = fpf out "@[<hv2>trying to unify@ @[<2>`@[%a@]`@ at %a@]@ @[<2>and `@[%a@]`@ at %a@]@]" pp_ty ty1 Loc.pp (T.loc ty1) pp_ty ty2 Loc.pp (T.loc ty2) in Some (spf "@[<hv2>unification error: %s:@ %a@]" msg (CCFormat.list pp2) stack) | _ -> None ) let rec occur_check_ ~var ty = match Ty.repr ty with | TyI.App (f, l) -> occur_check_ ~var f || List.exists (occur_check_ ~var) l | TyI.Const _ | TyI.Builtin _ -> false | TyI.Meta var' -> assert (MetaVar.can_bind var'); MetaVar.equal var var' | TyI.Arrow (a,b) -> occur_check_ ~var a || occur_check_ ~var b | TyI.Forall (_,t) -> occur_check_ ~var t let push_ a b c = (a,b) :: c let fail ~stack msg = raise (Fail (stack, msg)) let failf ~stack fmt = Utils.exn_ksprintf fmt ~f:(fun msg -> raise (Fail (stack, msg))) let rec flatten_app_ f l = match Ty.repr f with | TyI.App (f1, l1) -> flatten_app_ f1 (l1 @ l) | _ -> f, l let unify_exn ty1 ty2 = Utils.debugf ~section 5 "@[<hv2>unify `@[%a@]`@ and `@[%a@]`@]" (fun k-> k pp_ty ty1 pp_ty ty2); let bound = ref Subst.empty in let rec unify_ ~stack ty1 ty2 = let stack = push_ ( ty1) ( ty2) stack in match Ty.repr ty1, Ty.repr ty2 with | TyI.Builtin s1, TyI.Builtin s2 -> if TI.TyBuiltin.equal s1 s2 then () else fail ~stack "incompatible symbols" | TyI.Const i1, TyI.Const i2 -> if ID.equal i1 i2 then () else fail ~stack "incompatible symbols" | TyI.Var v1, TyI.Var v2 when Var.equal v1 v2 -> () | TyI.Var v1, TyI.Var v2 -> begin try let var = Subst.find_exn ~subst:!bound v1 in let var' = Subst.find_exn ~subst:!bound v2 in if Var.equal var var' then () else failf ~stack "bound variables %a and %a are incompatible" Var.pp v1 Var.pp v2 with Not_found -> fail ~stack "incompatible variables" end | TyI.Meta v1, TyI.Meta v2 when MetaVar.equal v1 v2 -> () | TyI.Meta var, _ -> assert (MetaVar.can_bind var); if occur_check_ ~var ty2 then ( failf ~stack "cycle detected (variable %a occurs in type)" MetaVar.pp var ) else ( MetaVar.bind ~var ty2 ) | _, TyI.Meta var -> assert (MetaVar.can_bind var); if occur_check_ ~var ty1 then ( failf ~stack "cycle detected (variable %a occurs in type)" MetaVar.pp var ) else ( MetaVar.bind ~var ty1 ) | TyI.App (f1,l1), TyI.App (f2,l2) -> let f1, l1 = flatten_app_ f1 l1 in let f2, l2 = flatten_app_ f2 l2 in if List.length l1<>List.length l2 then failf ~stack "different number of arguments (%d and %d resp.)" (List.length l1) (List.length l2); unify_ ~stack f1 f2; List.iter2 (unify_ ~stack) l1 l2 | TyI.Arrow (l1,r1), TyI.Arrow (l2,r2) -> unify_ ~stack l1 l2; unify_ ~stack r1 r2 | TyI.Forall (v1,t1), TyI.Forall (v2,t2) -> assert (not (Subst.mem ~subst:!bound v1)); assert (not (Subst.mem ~subst:!bound v2)); let v = Var.make ~ty:(Var.ty v1) ~name:"?" in bound := Subst.add ~subst:(Subst.add ~subst:!bound v2 v) v1 v; unify_ ~stack t1 t2 | TyI.Const _, _ | TyI.Builtin _,_ | TyI.App (_,_),_ | TyI.Arrow (_,_),_ -> fail ~stack "incompatible types" | TyI.Var _, _ -> fail ~stack "incompatible types" | TyI.Forall (_,_),_ -> fail ~stack "incompatible types" in unify_ ~stack:[] ty1 ty2 $ R let v = U.ty_meta_var ~loc ( MetaVar.make ~name:"x " ) in let f = U.ty_var ~loc ( Var.make ~ty : U.ty_type ~name:"f " ) in let a ' = ID.make " a " in let a = U.ty_const ~loc a ' in let t1 = U.ty_app ~loc f [ v ] in let t2 = U.ty_app ~loc f [ a ] in Unif.unify_exn t1 t2 ; assert_bool " v is a " ( match T.repr v with | TI.Const i d ' - > ID.equal a ' i d ' | _ - > false ) ; let v = U.ty_meta_var ~loc (MetaVar.make ~name:"x") in let f = U.ty_var ~loc (Var.make ~ty:U.ty_type ~name:"f") in let a' = ID.make "a" in let a = U.ty_const ~loc a' in let t1 = U.ty_app ~loc f [v] in let t2 = U.ty_app ~loc f [a] in Unif.unify_exn t1 t2; assert_bool "v is a" (match T.repr v with | TI.Const id' -> ID.equal a' id' | _ -> false ); *) type meta_vars_set = T.t MetaVar.t ID.Map.t let free_meta_vars ?(init=ID.Map.empty) ty = let rec aux acc ty = match Ty.repr ty with | TyI.Builtin _ | TyI.Const _ -> acc | TyI.Var v -> | TyI.Meta var -> assert (MetaVar.can_bind var); ID.Map.add (MetaVar.id var) var acc | TyI.App (f,l) -> let acc = aux acc f in List.fold_left aux acc l | TyI.Arrow (a,b) -> let acc = aux acc a in aux acc b | TyI.Forall (v,t) -> let acc = aux acc (Var.ty v) in aux acc t in aux init ty end
b101771b97e816410da893791ba83af0741b3663f9f63331f09d3d1b5d58a14a
Kalimehtar/gtk-cffi
color-chooser.lisp
;;; color-chooser.lisp -- GtkColorChooser ;;; Copyright ( C ) 2012 , < > ;;; (in-package :gtk-cffi) (defclass color-chooser (object) ()) (defslots color-chooser rgba prgba use-alpha :boolean) (defcfun gtk-color-chooser-add-palette :void (color-chooser pobject) (orientation orientation) (colors-per-line :int) (n-colors :int) (colors :pointer)) (defgeneric add-palette (color-chooser colors colors-per-line &key orientation) (:method ((color-chooser color-chooser) colors colors-per-line &key orientation) (let ((type 'gdk-cffi::rgba-struct) (n-colors (length colors))) (with-foreign-object (pcolors type n-colors) (dotimes (i n-colors) (destructuring-bind (red green blue alpha) (elt colors i) (template (field var) (('gdk-cffi::red red) ('gdk-cffi::green green) ('gdk-cffi::blue blue) ('gdk-cffi::alpha alpha)) `(setf (foreign-slot-value (mem-ref pcolors type i) type ,field) ,var)))) (gtk-color-chooser-add-palette color-chooser orientation colors-per-line n-colors colors)))))
null
https://raw.githubusercontent.com/Kalimehtar/gtk-cffi/fbd8a40a2bbda29f81b1a95ed2530debfe2afe9b/gtk/color-chooser.lisp
lisp
color-chooser.lisp -- GtkColorChooser Copyright ( C ) 2012 , < > (in-package :gtk-cffi) (defclass color-chooser (object) ()) (defslots color-chooser rgba prgba use-alpha :boolean) (defcfun gtk-color-chooser-add-palette :void (color-chooser pobject) (orientation orientation) (colors-per-line :int) (n-colors :int) (colors :pointer)) (defgeneric add-palette (color-chooser colors colors-per-line &key orientation) (:method ((color-chooser color-chooser) colors colors-per-line &key orientation) (let ((type 'gdk-cffi::rgba-struct) (n-colors (length colors))) (with-foreign-object (pcolors type n-colors) (dotimes (i n-colors) (destructuring-bind (red green blue alpha) (elt colors i) (template (field var) (('gdk-cffi::red red) ('gdk-cffi::green green) ('gdk-cffi::blue blue) ('gdk-cffi::alpha alpha)) `(setf (foreign-slot-value (mem-ref pcolors type i) type ,field) ,var)))) (gtk-color-chooser-add-palette color-chooser orientation colors-per-line n-colors colors)))))
f46ba3f50c388167d98cc2480997a4e22db96d39297ea001a1664d1dbacdd899
airalab/devcon5
Main.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # module Main where import Control.Concurrent (forkIO) import Control.Concurrent.Chan (newChan) import Control.Monad.Logger (LoggingT, logDebug, logError, logInfo, runChanLoggingT, runStderrLoggingT, unChanLoggingT) import Data.Base58String as B58 (toText) import qualified Data.Text as T import Network.Robonomics.InfoChan (publish, subscribe) import Options.Applicative import Pipes import Ethereum import Ipfs import Options import Robot main :: IO () main = run =<< execParser opts where opts = info (options <**> helper) (fullDesc <> progDesc "Robonomics Network DR-1 :: Devcon50 Worker") run :: Options -> IO () run Options{..} = runStderrLoggingT $ do $logInfo "Devcon50 Worker init..." objective <- liftIO generateObjective $logInfo $ "My ID: " <> B58.toText objective withIpfsDaemon $ \ipfsApi -> withEthereumAccount $ \keypair -> do $logInfo $ T.pack ("Ethereum address initialized: " ++ show (snd keypair)) -- Create log channel logChan <- liftIO newChan -- Spawn worker thread liftIO $ forkIO $ runChanLoggingT logChan $ do $logDebug "Worker thread launched" runEffect $ newLiabilities optionsProvider (fst keypair) >-> devcon50Worker optionsBase keypair >-> publish ipfsApi lighthouse -- Spawn trader thread liftIO $ forkIO $ runChanLoggingT logChan $ do $logDebug "Trader thread launched" runEffect $ subscribe ipfsApi lighthouse >-> devcon50Trader optionsBase objective optionsProvider keypair >-> publish ipfsApi lighthouse -- Logging in main thread unChanLoggingT logChan
null
https://raw.githubusercontent.com/airalab/devcon5/175ee57a51c828b99a904d90cd889819012a6261/app/Main.hs
haskell
# LANGUAGE OverloadedStrings # Create log channel Spawn worker thread Spawn trader thread Logging in main thread
# LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # module Main where import Control.Concurrent (forkIO) import Control.Concurrent.Chan (newChan) import Control.Monad.Logger (LoggingT, logDebug, logError, logInfo, runChanLoggingT, runStderrLoggingT, unChanLoggingT) import Data.Base58String as B58 (toText) import qualified Data.Text as T import Network.Robonomics.InfoChan (publish, subscribe) import Options.Applicative import Pipes import Ethereum import Ipfs import Options import Robot main :: IO () main = run =<< execParser opts where opts = info (options <**> helper) (fullDesc <> progDesc "Robonomics Network DR-1 :: Devcon50 Worker") run :: Options -> IO () run Options{..} = runStderrLoggingT $ do $logInfo "Devcon50 Worker init..." objective <- liftIO generateObjective $logInfo $ "My ID: " <> B58.toText objective withIpfsDaemon $ \ipfsApi -> withEthereumAccount $ \keypair -> do $logInfo $ T.pack ("Ethereum address initialized: " ++ show (snd keypair)) logChan <- liftIO newChan liftIO $ forkIO $ runChanLoggingT logChan $ do $logDebug "Worker thread launched" runEffect $ newLiabilities optionsProvider (fst keypair) >-> devcon50Worker optionsBase keypair >-> publish ipfsApi lighthouse liftIO $ forkIO $ runChanLoggingT logChan $ do $logDebug "Trader thread launched" runEffect $ subscribe ipfsApi lighthouse >-> devcon50Trader optionsBase objective optionsProvider keypair >-> publish ipfsApi lighthouse unChanLoggingT logChan
2c8b6ce337cf0f5d463ec3a909effc14062e2167014d01cf76589ef90224169f
Kakadu/fp2022
demoSingle.ml
* Copyright 2022 - 2023 , and contributors * SPDX - License - Identifier : CC0 - 1.0 open OCamlLabeledArgs_lib let () = Repl.run_single false
null
https://raw.githubusercontent.com/Kakadu/fp2022/5365f2f52e3e173cdb052abcfdbfb66fc70fe799/OCamlLabeledArgs/demos/demoSingle.ml
ocaml
* Copyright 2022 - 2023 , and contributors * SPDX - License - Identifier : CC0 - 1.0 open OCamlLabeledArgs_lib let () = Repl.run_single false
c5944d1e967c7daad3e47313e1411b8c22d2bb3ed590a65e52fd300ed8383eff
mirage/ocaml-github
github_cookie_jar.mli
* Copyright ( c ) 2012 Anil Madhavapeddy < > * Copyright ( c ) 2013 < > * * 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 . * * Copyright (c) 2012 Anil Madhavapeddy <> * Copyright (c) 2013 David Sheets <> * * 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. * *) type t val init : ?jar_path:string -> unit -> t Lwt.t val save : t -> name:string -> auth:Github_t.auth -> t Lwt.t val delete : t -> name:string -> t Lwt.t val get_all : t -> (string * Github_t.auth) list Lwt.t val get : t -> name:string -> Github_t.auth option Lwt.t val jar_path : t -> string
null
https://raw.githubusercontent.com/mirage/ocaml-github/429b8751c45d958644bf0e64452bf9b0460955ba/unix/github_cookie_jar.mli
ocaml
* Copyright ( c ) 2012 Anil Madhavapeddy < > * Copyright ( c ) 2013 < > * * 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 . * * Copyright (c) 2012 Anil Madhavapeddy <> * Copyright (c) 2013 David Sheets <> * * 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. * *) type t val init : ?jar_path:string -> unit -> t Lwt.t val save : t -> name:string -> auth:Github_t.auth -> t Lwt.t val delete : t -> name:string -> t Lwt.t val get_all : t -> (string * Github_t.auth) list Lwt.t val get : t -> name:string -> Github_t.auth option Lwt.t val jar_path : t -> string
403bee31c7e59488b45af50b840bad03ab7efe39fdd79d2647130f554da9210b
icicle-lang/icicle-ambiata
ANormal.hs
-- | A-normalise expressions -- A-normal form is where the function and arguments of an application -- can only be simple expressions such as values, variables, and primitives, -- and let bindings are serialised. -- -- For example, -- map ( + ( 5 - 2 ) ) [ 1,2,3 ] -- -- would end up as something like -- let a = 5 - 2 -- let b = (+a) -- let c = [1,2,3] -- in map b c -- -- Conversion to a-normal form is not a benefit in itself, but simplifies -- later transformations. # LANGUAGE NoImplicitPrelude # {-# LANGUAGE PatternGuards #-} {-# LANGUAGE BangPatterns #-} module Icicle.Common.Exp.Simp.ANormal ( anormal , anormalAllVars ) where import Icicle.Common.Base import Icicle.Common.Exp.Exp import Icicle.Common.Exp.Compounds import Icicle.Common.Fresh import P import Data.List (unzip) import Data.Hashable (Hashable) import qualified Data.Set as Set -- | A-normalise an expression. -- We need a fresh name supply. anormal :: (Hashable n, Eq n) => a -> Exp a n p -> Fresh n (Exp a n p) anormal a_fresh xx -- Annotate each expression with all the variables underneath it, -- then perform a-normalisation, then throw away the annotations = do let !x = allvarsExp xx !y <- anormalAllVars a_fresh x let !z = reannotX fst y return z -- | A-normalise an expression, annotated with all the mentioned variables. -- Computing the variable set once and reusing it is much faster than recomputing it each time. -- However, it does complicate constructing new expressions. -- We need to be careful when constructing expressions to return, -- as their variable set may be used by a parent recursive call. -- We can cheat a little with the variable set though: -- * a superset is allowed, as it will just make renaming more pessimistic -- * new fresh variables don't need to be mentioned, as they will not appear elsewhere as binders or mentioned -- anormalAllVars :: (Hashable n, Eq n) => a -> Exp (Ann a n) n p -> Fresh n (Exp (Ann a n) n p) anormalAllVars a_fresh xx = do (bs, x) <- pullSubExps a_fresh xx (ret,_) <- foldM insertBinding (x, snd $ annotOfExp x) (reverse bs) return ret where insertBinding (x,bs) (n,b) | n `Set.member` bs = do n' <- fresh let bs' = Set.insert n' $ Set.union (snd $ annotOfExp b) bs let a' = (a_fresh, bs') x' <- subst1 a' n (XVar a' n') x return (XLet a' n' b x', bs') | otherwise = do let bs' = Set.insert n $ Set.union (snd $ annotOfExp b) bs let a' = (a_fresh, bs') let x' = XLet a' n b x return (x', bs) -- | Recursively pull out sub-expressions to be bound pullSubExps :: (Hashable n, Eq n) => a -> Exp (Ann a n) n p -> Fresh n ([(Name n, Exp (Ann a n) n p)], Exp (Ann a n) n p) pullSubExps a_fresh xx = case xx of -- Values and other simple expressions can be left alone. XVar{} -> ret XPrim{} -> ret XValue{} -> ret An application - might as well do it in one go XApp{} -> do -- Grab the function and its arguments let (f,args) = takeApps xx Recurse over the function and grab its bindings , if any (bf, xf) <- extractBinding a_fresh f -- And with the arguments (bs, xs) <- unzip <$> mapM (extractBinding a_fresh) args -- Reconstruct the new application, using the non-binding bits. -- Its variable set is really the union of all the non-binding bits, -- but the original expressions' variable set is a good approximation. let vars' = snd $ annotOfExp xx let app' = makeApps (a_fresh, vars') xf xs -- Push all the bindings together return (concat (bf:bs), app') Lambdas are barriers . -- We don't want to pull anything out. XLam a n v x -> do x' <- anormalAllVars a_fresh x return ([], XLam a n v x') -- Just recurse over lets XLet _ n x y -> do (bx, x') <- pullSubExps a_fresh x (by, y') <- pullSubExps a_fresh y return (bx <> [(n, x')] <> by, y') where -- Return unchanged ret = return ([], xx) -- | Extract bindings for part of an application expression. -- If it's simple, just give it back. -- If it's interesting, anormalise it and bind it to a fresh name extractBinding :: (Hashable n, Eq n) => a -> Exp (Ann a n) n p -> Fresh n ([(Name n, Exp (Ann a n) n p)], Exp (Ann a n) n p) extractBinding a_fresh xx | isNormal xx = return ([], xx) | otherwise = do (bs,x') <- pullSubExps a_fresh xx n <- fresh -- The annotation here should strictly be singleton of n, -- however since it is fresh it won't conflict with other bindings. -- Empty might be faster. return (bs <> [(n,x')], XVar (a_fresh, Set.empty) n) -- | Check whether expression is worth extracting isNormal :: Exp a n p -> Bool isNormal xx = case xx of XVar{} -> True XPrim{} -> True XValue{} -> True XLam{} -> True XApp{} -> False XLet{} -> False
null
https://raw.githubusercontent.com/icicle-lang/icicle-ambiata/9b9cc45a75f66603007e4db7e5f3ba908cae2df2/icicle-data/src/Icicle/Common/Exp/Simp/ANormal.hs
haskell
| A-normalise expressions A-normal form is where the function and arguments of an application can only be simple expressions such as values, variables, and primitives, and let bindings are serialised. For example, would end up as something like let b = (+a) let c = [1,2,3] in map b c Conversion to a-normal form is not a benefit in itself, but simplifies later transformations. # LANGUAGE PatternGuards # # LANGUAGE BangPatterns # | A-normalise an expression. We need a fresh name supply. Annotate each expression with all the variables underneath it, then perform a-normalisation, then throw away the annotations | A-normalise an expression, annotated with all the mentioned variables. Computing the variable set once and reusing it is much faster than recomputing it each time. However, it does complicate constructing new expressions. We need to be careful when constructing expressions to return, as their variable set may be used by a parent recursive call. We can cheat a little with the variable set though: * a superset is allowed, as it will just make renaming more pessimistic * new fresh variables don't need to be mentioned, as they will not appear elsewhere as binders or mentioned | Recursively pull out sub-expressions to be bound Values and other simple expressions can be left alone. Grab the function and its arguments And with the arguments Reconstruct the new application, using the non-binding bits. Its variable set is really the union of all the non-binding bits, but the original expressions' variable set is a good approximation. Push all the bindings together We don't want to pull anything out. Just recurse over lets Return unchanged | Extract bindings for part of an application expression. If it's simple, just give it back. If it's interesting, anormalise it and bind it to a fresh name The annotation here should strictly be singleton of n, however since it is fresh it won't conflict with other bindings. Empty might be faster. | Check whether expression is worth extracting
map ( + ( 5 - 2 ) ) [ 1,2,3 ] let a = 5 - 2 # LANGUAGE NoImplicitPrelude # module Icicle.Common.Exp.Simp.ANormal ( anormal , anormalAllVars ) where import Icicle.Common.Base import Icicle.Common.Exp.Exp import Icicle.Common.Exp.Compounds import Icicle.Common.Fresh import P import Data.List (unzip) import Data.Hashable (Hashable) import qualified Data.Set as Set anormal :: (Hashable n, Eq n) => a -> Exp a n p -> Fresh n (Exp a n p) anormal a_fresh xx = do let !x = allvarsExp xx !y <- anormalAllVars a_fresh x let !z = reannotX fst y return z anormalAllVars :: (Hashable n, Eq n) => a -> Exp (Ann a n) n p -> Fresh n (Exp (Ann a n) n p) anormalAllVars a_fresh xx = do (bs, x) <- pullSubExps a_fresh xx (ret,_) <- foldM insertBinding (x, snd $ annotOfExp x) (reverse bs) return ret where insertBinding (x,bs) (n,b) | n `Set.member` bs = do n' <- fresh let bs' = Set.insert n' $ Set.union (snd $ annotOfExp b) bs let a' = (a_fresh, bs') x' <- subst1 a' n (XVar a' n') x return (XLet a' n' b x', bs') | otherwise = do let bs' = Set.insert n $ Set.union (snd $ annotOfExp b) bs let a' = (a_fresh, bs') let x' = XLet a' n b x return (x', bs) pullSubExps :: (Hashable n, Eq n) => a -> Exp (Ann a n) n p -> Fresh n ([(Name n, Exp (Ann a n) n p)], Exp (Ann a n) n p) pullSubExps a_fresh xx = case xx of XVar{} -> ret XPrim{} -> ret XValue{} -> ret An application - might as well do it in one go XApp{} let (f,args) = takeApps xx Recurse over the function and grab its bindings , if any (bf, xf) <- extractBinding a_fresh f (bs, xs) <- unzip <$> mapM (extractBinding a_fresh) args let vars' = snd $ annotOfExp xx let app' = makeApps (a_fresh, vars') xf xs return (concat (bf:bs), app') Lambdas are barriers . XLam a n v x -> do x' <- anormalAllVars a_fresh x return ([], XLam a n v x') XLet _ n x y -> do (bx, x') <- pullSubExps a_fresh x (by, y') <- pullSubExps a_fresh y return (bx <> [(n, x')] <> by, y') where ret = return ([], xx) extractBinding :: (Hashable n, Eq n) => a -> Exp (Ann a n) n p -> Fresh n ([(Name n, Exp (Ann a n) n p)], Exp (Ann a n) n p) extractBinding a_fresh xx | isNormal xx = return ([], xx) | otherwise = do (bs,x') <- pullSubExps a_fresh xx n <- fresh return (bs <> [(n,x')], XVar (a_fresh, Set.empty) n) isNormal :: Exp a n p -> Bool isNormal xx = case xx of XVar{} -> True XPrim{} -> True XValue{} -> True XLam{} -> True XApp{} -> False XLet{} -> False
1e0e9bd0e459658b751c4cee527576a4c54d276ccf8605fb8fa455e35f32ac2d
racket/typed-racket
gh-issue-293.rkt
#; (exn-pred #rx"type mismatch.*expected: Procedure.*given: String") #lang typed/racket (define-struct/exec foo ([x : Integer]) ["foo" : String])
null
https://raw.githubusercontent.com/racket/typed-racket/8b7bd594c66e53beba3d2568ca5ecb28f61c6d96/typed-racket-test/fail/gh-issue-293.rkt
racket
(exn-pred #rx"type mismatch.*expected: Procedure.*given: String") #lang typed/racket (define-struct/exec foo ([x : Integer]) ["foo" : String])
d68e42c511d167ff1955d868468c6d32ef00b8b42e906242c45455c04167f59c
ryanpbrewster/haskell
text_to_number.hs
-- text_to_number.hs - You have a sting which contains a number represented as English text . Your - task is to translate these numbers into their integer representation . The - numbers can range from negative 999,999,999 to positive 999,999,999 . The - following is an exhaustive list of English words that your program must - account for : - - negative , zero , one , two , three , four , five , six , seven , eight , nine , ten , - eleven , twelve , thirteen , fourteen , fifteen , sixteen , seventeen , eighteen , - nineteen , twenty , thirty , forty , fifty , sixty , seventy , eighty , ninety , - hundred , thousand , million - - Input sample : - - Your program should accept as its first argument a path to a filename . - Input example is the following - - fifteen - negative six hundred thirty eight - zero - two million one hundred seven - - * Negative numbers will be preceded by the word negative . - * The word " hundred " is not used when " thousand " could be . E.g. 1500 is - written " one thousand five hundred " , not " fifteen hundred " Output - - Print results in the following way . - - 15 - -638 - 0 - 2000107 - You have a sting which contains a number represented as English text. Your - task is to translate these numbers into their integer representation. The - numbers can range from negative 999,999,999 to positive 999,999,999. The - following is an exhaustive list of English words that your program must - account for: - - negative, zero, one, two, three, four, five, six, seven, eight, nine, ten, - eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, - nineteen, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety, - hundred, thousand, million - - Input sample: - - Your program should accept as its first argument a path to a filename. - Input example is the following - - fifteen - negative six hundred thirty eight - zero - two million one hundred seven - - * Negative numbers will be preceded by the word negative. - * The word "hundred" is not used when "thousand" could be. E.g. 1500 is - written "one thousand five hundred", not "fifteen hundred" Output - - Print results in the following way. - - 15 - -638 - 0 - 2000107 -} import System.Environment (getArgs) import qualified Data.Map as M primMap = M.fromList [("zero", 0) ,("one", 1) ,("two", 2) ,("three", 3) ,("four", 4) ,("five", 5) ,("six", 6) ,("seven", 7) ,("eight", 8) ,("nine", 9) ,("ten", 10) ,("eleven", 11) ,("twelve", 12) ,("thirteen", 13) ,("fourteen", 14) ,("fifteen", 15) ,("sixteen", 16) ,("seventeen",17) ,("eighteen", 18) ,("nineteen", 19) ,("twenty", 20) ,("thirty", 30) ,("forty", 40) ,("fifty", 50) ,("sixty", 60) ,("seventy", 70) ,("eighty", 80) ,("ninety", 90) ] quantMap = M.fromList [("hundred", 10^2) ,("thousand", 10^3) ,("million", 10^6) ] ttn = textToNumber . words textToNumber ("negative":ws) = -(textToNumber' ws 0) textToNumber ws = textToNumber' ws 0 textToNumber' [] cur = cur textToNumber' (w:ws) cur | w `M.member` primMap = textToNumber' ws (cur+(primMap M.! w)) | otherwise = let q = quantMap M.! w in if q > 100 then cur*q + textToNumber' ws 0 else textToNumber' ws (cur*q) main = do args <- getArgs txt <- readFile (head args) putStr $ solveProblem txt solveProblem txt = let lns = lines txt anss = map ttn lns in unlines $ map show anss
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/CodeEval/text_to_number.hs
haskell
text_to_number.hs
- You have a sting which contains a number represented as English text . Your - task is to translate these numbers into their integer representation . The - numbers can range from negative 999,999,999 to positive 999,999,999 . The - following is an exhaustive list of English words that your program must - account for : - - negative , zero , one , two , three , four , five , six , seven , eight , nine , ten , - eleven , twelve , thirteen , fourteen , fifteen , sixteen , seventeen , eighteen , - nineteen , twenty , thirty , forty , fifty , sixty , seventy , eighty , ninety , - hundred , thousand , million - - Input sample : - - Your program should accept as its first argument a path to a filename . - Input example is the following - - fifteen - negative six hundred thirty eight - zero - two million one hundred seven - - * Negative numbers will be preceded by the word negative . - * The word " hundred " is not used when " thousand " could be . E.g. 1500 is - written " one thousand five hundred " , not " fifteen hundred " Output - - Print results in the following way . - - 15 - -638 - 0 - 2000107 - You have a sting which contains a number represented as English text. Your - task is to translate these numbers into their integer representation. The - numbers can range from negative 999,999,999 to positive 999,999,999. The - following is an exhaustive list of English words that your program must - account for: - - negative, zero, one, two, three, four, five, six, seven, eight, nine, ten, - eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, - nineteen, twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety, - hundred, thousand, million - - Input sample: - - Your program should accept as its first argument a path to a filename. - Input example is the following - - fifteen - negative six hundred thirty eight - zero - two million one hundred seven - - * Negative numbers will be preceded by the word negative. - * The word "hundred" is not used when "thousand" could be. E.g. 1500 is - written "one thousand five hundred", not "fifteen hundred" Output - - Print results in the following way. - - 15 - -638 - 0 - 2000107 -} import System.Environment (getArgs) import qualified Data.Map as M primMap = M.fromList [("zero", 0) ,("one", 1) ,("two", 2) ,("three", 3) ,("four", 4) ,("five", 5) ,("six", 6) ,("seven", 7) ,("eight", 8) ,("nine", 9) ,("ten", 10) ,("eleven", 11) ,("twelve", 12) ,("thirteen", 13) ,("fourteen", 14) ,("fifteen", 15) ,("sixteen", 16) ,("seventeen",17) ,("eighteen", 18) ,("nineteen", 19) ,("twenty", 20) ,("thirty", 30) ,("forty", 40) ,("fifty", 50) ,("sixty", 60) ,("seventy", 70) ,("eighty", 80) ,("ninety", 90) ] quantMap = M.fromList [("hundred", 10^2) ,("thousand", 10^3) ,("million", 10^6) ] ttn = textToNumber . words textToNumber ("negative":ws) = -(textToNumber' ws 0) textToNumber ws = textToNumber' ws 0 textToNumber' [] cur = cur textToNumber' (w:ws) cur | w `M.member` primMap = textToNumber' ws (cur+(primMap M.! w)) | otherwise = let q = quantMap M.! w in if q > 100 then cur*q + textToNumber' ws 0 else textToNumber' ws (cur*q) main = do args <- getArgs txt <- readFile (head args) putStr $ solveProblem txt solveProblem txt = let lns = lines txt anss = map ttn lns in unlines $ map show anss
537db2377f3070ae8504127b33355f915cfa0d31101c11776339d70bc71beeda
eponai/sulolive
datascript_test.cljc
(ns eponai.common.datascript_test (:require [eponai.common.datascript :as project.d] [datascript.core :as d] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop #?@(:cljs [:include-macros true])] [clojure.test.check.clojure-test #?(:clj :refer :cljs :refer-macros) [defspec]])) (defn gen-datomic-keyword "generates a keywords which contains alphanumeric characters. Used to avoid keywords starting with underscore, like: :_ref or :foo/_bar" ([] (gen-datomic-keyword "not-a-key" nil)) ([forbidden-key replacement-key] (gen/bind (gen/not-empty gen/string-alphanumeric) (fn [s] (gen/bind gen/keyword-ns (fn [k] (if (= k forbidden-key) (gen/return replacement-key) (gen/return (if-let [n (namespace k)] (keyword (str n "/" s)) (keyword s)))))))))) (defn gen-datomic-schema [] (gen/hash-map :db/id (gen/return "#db.id[:db.part/db]") :db.install/_attribute (gen/return :db.part/db) :db/ident (gen-datomic-keyword) :db/valueType (gen/elements [:db.type/string :db.type/uuid :db.type/ref]) :db/cardinality (gen/elements [:db.cardinality/one :db.cardinality/many]) :db/doc gen/string-ascii)) (defn datomic-schema->datascript-txs [datomic-schema] (->> datomic-schema (map (fn [{:keys [db/ident db/valueType db/cardinality]}] (let [value (if (= valueType :db.type/ref) 1 "value") value (if (= cardinality :db.cardinality/many) (repeat 3 value) value)] [ident value]))) (group-by (fn [[k _]] (if-let [n (namespace k)] n k))) (reduce (fn [m [k pairs]] (assoc m k (->> pairs (map (partial apply hash-map)) (reduce merge {})))) {}) (vals))) (defspec datomic-schemas-can-be-translated-to-datascript 10 (prop/for-all [datomic-schema (gen/not-empty (gen/vector (gen-datomic-schema)))] (when-let [datascript-schema (project.d/schema-datomic->datascript datomic-schema)] (let [conn (d/create-conn datascript-schema)] ;; create an entity to have something to refer to (d/transact conn [{:foo "bar"}]) (when (every? (fn [{:keys [db/ident]}] (contains? datascript-schema ident)) datomic-schema) (let [datascript-txs (datomic-schema->datascript-txs datomic-schema) before-tx @conn res (d/transact conn datascript-txs)] (not= before-tx @conn)))))))
null
https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/test/eponai/common/datascript_test.cljc
clojure
create an entity to have something to refer to
(ns eponai.common.datascript_test (:require [eponai.common.datascript :as project.d] [datascript.core :as d] [clojure.test.check :as tc] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop #?@(:cljs [:include-macros true])] [clojure.test.check.clojure-test #?(:clj :refer :cljs :refer-macros) [defspec]])) (defn gen-datomic-keyword "generates a keywords which contains alphanumeric characters. Used to avoid keywords starting with underscore, like: :_ref or :foo/_bar" ([] (gen-datomic-keyword "not-a-key" nil)) ([forbidden-key replacement-key] (gen/bind (gen/not-empty gen/string-alphanumeric) (fn [s] (gen/bind gen/keyword-ns (fn [k] (if (= k forbidden-key) (gen/return replacement-key) (gen/return (if-let [n (namespace k)] (keyword (str n "/" s)) (keyword s)))))))))) (defn gen-datomic-schema [] (gen/hash-map :db/id (gen/return "#db.id[:db.part/db]") :db.install/_attribute (gen/return :db.part/db) :db/ident (gen-datomic-keyword) :db/valueType (gen/elements [:db.type/string :db.type/uuid :db.type/ref]) :db/cardinality (gen/elements [:db.cardinality/one :db.cardinality/many]) :db/doc gen/string-ascii)) (defn datomic-schema->datascript-txs [datomic-schema] (->> datomic-schema (map (fn [{:keys [db/ident db/valueType db/cardinality]}] (let [value (if (= valueType :db.type/ref) 1 "value") value (if (= cardinality :db.cardinality/many) (repeat 3 value) value)] [ident value]))) (group-by (fn [[k _]] (if-let [n (namespace k)] n k))) (reduce (fn [m [k pairs]] (assoc m k (->> pairs (map (partial apply hash-map)) (reduce merge {})))) {}) (vals))) (defspec datomic-schemas-can-be-translated-to-datascript 10 (prop/for-all [datomic-schema (gen/not-empty (gen/vector (gen-datomic-schema)))] (when-let [datascript-schema (project.d/schema-datomic->datascript datomic-schema)] (let [conn (d/create-conn datascript-schema)] (d/transact conn [{:foo "bar"}]) (when (every? (fn [{:keys [db/ident]}] (contains? datascript-schema ident)) datomic-schema) (let [datascript-txs (datomic-schema->datascript-txs datomic-schema) before-tx @conn res (d/transact conn datascript-txs)] (not= before-tx @conn)))))))
d0f2b24d1c820b19c0fcd343918738b530d99d3543b01e35ac2b6f880e4441ff
wilkerlucio/pathom
merge.cljc
(ns com.wsscode.pathom.merge (:require [com.wsscode.pathom.core :as p])) NAMESPACE DEPRECATED , use from core (def merge-queries* p/merge-queries*) (def merge-queries p/merge-queries)
null
https://raw.githubusercontent.com/wilkerlucio/pathom/4ec25055d3d156241e9174d68ec438c93c971b9b/src/com/wsscode/pathom/merge.cljc
clojure
(ns com.wsscode.pathom.merge (:require [com.wsscode.pathom.core :as p])) NAMESPACE DEPRECATED , use from core (def merge-queries* p/merge-queries*) (def merge-queries p/merge-queries)
70a239d1da679c5e12fb48d666197fd98f3ba64987bae0328cd91bd57ae2c97a
nuvla/ui
zip.cljs
(ns sixsq.nuvla.ui.utils.zip (:require ["jszip" :as jszip])) (defn create [files callback] (let [zip (jszip)] (doseq [{:keys [name file]} files] (.file zip name file)) (-> zip (.generateAsync #js{"type" "base64", "compression" "STORE"}) (.then #(callback (str "data:application/zip;base64," %))))))
null
https://raw.githubusercontent.com/nuvla/ui/c10704eabd339489722fa53bc99f11f21103c070/code/src/cljs/sixsq/nuvla/ui/utils/zip.cljs
clojure
(ns sixsq.nuvla.ui.utils.zip (:require ["jszip" :as jszip])) (defn create [files callback] (let [zip (jszip)] (doseq [{:keys [name file]} files] (.file zip name file)) (-> zip (.generateAsync #js{"type" "base64", "compression" "STORE"}) (.then #(callback (str "data:application/zip;base64," %))))))
64dca5b53008c7423b40a618f6e551d384f5f162e435cd0354062bb529e6aefb
bjorng/wings
wpc_ai.erl
%% wpc_ai.erl -- %% Adobe Illustrator ( .ai ) import by Some updates by %% For now: - Only Illustrator version 8 or less files parsed ( v9 - > pdf ) %% - Ignore line width, fill, clip mask, text %% %% %% $Id$ %% -module(wpc_ai). -export([init/0,menu/2,command/2,tryimport/2]). % tryimport is for debugging %% exported to wpc_ps wpc_svg_path -export([findpolyareas/1, polyareas_to_faces/1, subdivide_pas/2]). -import(lists, [reverse/1,splitwith/2,member/2, sublist/2,nthtail/2,map/2]). -include_lib("wings/e3d/e3d.hrl"). -include_lib("wings/intl_tools/wings_intl.hrl"). amount to scale AI coords by -record(cedge, {vs,cp1=nil,cp2=nil,ve}). %all are {x,y} pairs -record(polyarea, list of cedges ( CCW oriented , closed ) list of lists of cedges ( CW , closed ) -record(path, {ops=[], %list of pathops close=false}). %true or false -record(pathop, {opkind, %pmoveto, plineto, or pcurveto x1=0.0, y1=0.0, x2=0.0, y2=0.0, x3=0.0, y3=0.0}). -record(pstate, {curpath=#path{}, %current path objects=[]}). %object list (paths) init() -> true. menu({file,import}, Menu) -> Menu ++ [{"Adobe Illustrator (.ai)...",ai,[option]}]; menu(_, Menu) -> Menu. command({file,{import,{ai,Ask}}}, _St) when is_atom(Ask) -> DefBisect = wpa:pref_get(wpc_ai, bisections, 0), wpa:ask(Ask, ?__(1,"AI Import Options"), [{?__(2,"Number of edge bisections"), DefBisect}], fun(Res) -> {file,{import,ai,Res}} end); command({file,{import,ai,[Nsub]}}, St) -> Props = [{ext,".ai"},{ext_desc,?__(3,"Adobe Illustrator File")}], wpa:import(Props, fun(F) -> make_ai(F, Nsub) end, St); command(_, _) -> next. make_ai(Name, Nsubsteps) -> case catch tryimport(Name, Nsubsteps) of {ok, E3dFile} -> wpa:pref_set(wpc_ai, bisections, Nsubsteps), {ok, E3dFile}; {error,Reason} -> {error, ?__(1,"AI import failed")++": " ++ Reason}; _ -> {error, ?__(2,"AI import internal error")} end. tryimport(Name, Nsubsteps) -> case file:read_file(Name) of {ok,<<"%!PS-Adobe",Rest/binary>>} -> Objs = tokenize_bin(Rest), Closedpaths = [ P || P <- Objs, P#path.close == true ], Cntrs = getcontours(Closedpaths), Pas = findpolyareas(Cntrs), Pas1 = subdivide_pas(Pas,Nsubsteps), {Vs0,Fs,HEs} = polyareas_to_faces(Pas1), Center = e3d_vec:average(e3d_vec:bounding_box(Vs0)), Vec = e3d_vec:sub(e3d_vec:zero(),Center), Vs = reverse(center_object(Vec,Vs0)), Efs = [ #e3d_face{vs=X} || X <- Fs], Mesh = #e3d_mesh{type=polygon,vs=Vs,fs=Efs,he=HEs}, Obj = #e3d_object{name=Name,obj=Mesh}, {ok, #e3d_file{objs=[Obj]}}; {ok,_} -> {error,?__(1,"Not an Adobe Illustrator File (Version 8 or earlier)")}; {error,Reason} -> {error,file:format_error(Reason)} end. center_object(Vec,Vs) -> lists:foldl(fun(V,Acc) -> {X,Y,Z} = e3d_vec:add(V,Vec), [{X,Y,Z}|Acc] end,[],Vs). tokenize_bin(Bin) -> Chars = afterendsetup(Bin), Toks = tokenize(Chars, []), Objs = parsetokens(Toks), Objs. % skip until after %%EndSetup line, as we currently use nothing before that, % then convert rest of binary to list of characters afterendsetup(<<"%%EndSetup",Rest/binary>>) -> binary_to_list(Rest); afterendsetup(<<_,Rest/binary>>) -> afterendsetup(Rest); afterendsetup(_) -> []. tokenize first list ( characters from file ) into list of tokens ( accumulated reversed in second list , reversed at end ) . a token is { tnum , } , { tname , } , { tlitname , } , or { tstring } tokenize([], Toks) -> reverse(Toks); tokenize([C|T], Toks) when C == $\s; C == $\t; C == $\r; C == $\n; these 2 are " should n't happens " tokenize(T, Toks); tokenize("%" ++ T, Toks) -> tokenize(skipline(T), Toks); tokenize("/" ++ T, Toks) -> {Name,TT} = splitwith(fun isnttokbreak/1, T), tokenize(TT, [{tlitname,Name}|Toks]); tokenize("(" ++ T, Toks) -> tokenize(skipstring(T), [{tstring}|Toks]); tokenize("<" ++ T, Toks) -> tokenize(skiphexstring(T), [{tstring}|Toks]); tokenize([C|T], Toks) when C == $[; C == $]; C == ${; C == $} -> tokenize(T, [{tname,[C]}|Toks]); tokenize([C|_] = Arg, Toks) when C >= $0, C =< $9; C==$- -> {Tok,TT} = parsenum(Arg), tokenize(TT, [Tok|Toks]); tokenize(Arg, Toks) -> {Name,TT} = splitwith(fun isnttokbreak/1, Arg), tokenize(TT, [{tname,Name}|Toks]). % note: this list of chars be exactly those matched explicitly % by the non-default cases of tokenize, else get infinite loop isnttokbreak(C) -> not(member(C, " \t\r\n()<>[]{}/%")). % AI numbers are either ints or floats % no radix notation for ints, no scientific notation for floats parsenum([C|Rest]=L) -> case re:run(L, "^((\\+|\\-?)([0-9]+\\.[0-9]*)|(\\.[0-9]+))",[{capture,first}]) of {match,[{0,Length}]} -> Fstr = sublist(L, Length), F = list_to_float(Fstr), {{tnum,F}, nthtail(Length, L)}; nomatch -> case re:run(L, "^(\\+|-)?[0-9]+", [{capture,first}]) of {match, [{0, Length}]} -> Istr = sublist(L, Length), I = list_to_integer(Istr), {{tnum,float(I)}, nthtail(Length, L)}; nomatch -> {{tname,[C]}, Rest} end end. skip past next end of line , return rest skipline("\r\n" ++ T) -> T; skipline("\r" ++ T) -> T; % sometimes find files with only CRs! skipline("\n" ++ T) -> T; skipline([_|T]) -> skipline(T); skipline([]) -> []. % skip past next ")", but be careful about escaped ones % return rest skipstring([]) -> []; skipstring("\\") -> []; skipstring("\\" ++ [_|T]) -> skipstring(T); skipstring(")" ++ T) -> T; skipstring([_|T]) -> skipstring(T). % skip past next ">", return rest skiphexstring([]) -> []; skiphexstring(">" ++ L) -> L; skiphexstring([_|L]) -> skiphexstring(L). % consume tokens, return list of objects. % an object is either a path or a compoundpath. parsetokens(Toks) -> #pstate{objects=Objs}=parse(Toks, #pstate{}), Objs. parse([],#pstate{objects=Objs}=Pst) -> Pst#pstate{objects=reverse(Objs)}; parse([{tname,[_|_]=N}|T], Pst) -> parse(T,dorenderop(N,dopathop0(N,Pst))); parse([{tnum,X1},{tnum,Y1},{tname,[_|_]=N}|T], Pst) -> parse(T,dopathop2(N,{X1,Y1},Pst)); parse([{tnum,X1},{tnum,Y1},{tnum,X2},{tnum,Y2},{tname,[_|_]=N}|T], Pst) -> parse(T,dopathop4(N,{X1,Y1,X2,Y2},Pst)); parse([{tnum,X1},{tnum,Y1},{tnum,X2},{tnum,Y2},{tnum,X3},{tnum,Y3}, {tname,[_|_]=N}|T], Pst) -> parse(T,dopathop6(N,{X1,Y1,X2,Y2,X3,Y3},Pst)); parse([_|T], Pst) -> parse(T, Pst). check if C is a no - arg path operation , and if so , return a modified Pst , otherwise return original Pst dopathop0([C],Pst) when C == $h; C == $H -> P = Pst#pstate.curpath, Pst#pstate{curpath=P#path{close=true}}; dopathop0(_,Pst) -> Pst. dopathop2("m",{X1,Y1},Pst) -> finishpop(#pathop{opkind=pmoveto,x1=X1,y1=Y1},Pst); dopathop2([C],{X1,Y1},Pst) when C==$l; C==$L -> finishpop(#pathop{opkind=plineto,x1=X1,y1=Y1},Pst); dopathop2(_,_,Pst) -> Pst. dopathop4([C],{X2,Y2,X3,Y3},Pst) when C==$v; C==$V -> % start point and next bezier control point coincide % need curpath to have an op, so can get previous point! Pop = #pathop{opkind=pcurveto,x2=X2,y2=Y2,x3=X3,y3=Y3}, case Pst#pstate.curpath of #path{ops=[#pathop{opkind=pmoveto,x1=X1,y1=Y1}|_]} -> finishpop(Pop#pathop{x1=X1,y1=Y1},Pst); #path{ops=[#pathop{opkind=plineto,x1=X1,y1=Y1}|_]} -> finishpop(Pop#pathop{x1=X1,y1=Y1},Pst); #path{ops=[#pathop{opkind=pcurveto,x3=X1,y3=Y1}|_]} -> finishpop(Pop#pathop{x1=X1,y1=Y1},Pst); _ -> Pst end; dopathop4([C],{X1,Y1,X2,Y2},Pst) when C==$y; C==$Y -> % end point and previous bezier control point coincide finishpop(#pathop{opkind=pcurveto,x1=X1,y1=Y1,x2=X2,y2=Y2,x3=X2,y3=Y2},Pst); dopathop4(_,_,Pst) -> Pst. dopathop6([C],{X1,Y1,X2,Y2,X3,Y3},Pst) when C==$c; C==$C -> finishpop(#pathop{opkind=pcurveto,x1=X1,y1=Y1,x2=X2,y2=Y2,x3=X3,y3=Y3},Pst); dopathop6(_,_,Pst) -> Pst. % finish job of dopathop[2,4,6] by putting arg pathop onto curpath's ops list % and returning Pst with modified curpath finishpop(#pathop{opkind=pmoveto}=Pop, #pstate{curpath=#path{ops=[]}}=Pst) -> Pst#pstate{curpath=#path{ops=[Pop]}}; finishpop(_, #pstate{curpath=#path{ops=[]}}=Pst) -> Pst; % note: only pmoveto's can start path, so ignore others finishpop(Pop, #pstate{curpath=#path{ops=Ops}=P}=Pst) -> Pst#pstate{curpath=P#path{ops=[Pop|Ops]}}. If is a renderop , finish off curpath and put on objects list . dorenderop([C],Pst) when C==$n; C==$f; C==$s; C==$b; C==$B -> finishrop(true,Pst); dorenderop([C],Pst) when C==$N; C==$F; C==$S -> finishrop(false,Pst); dorenderop([$B,C],Pst) when C==$b; C==$g; C==$m; C==$c; C==$B -> finishrop(false,Pst); dorenderop(_,Pst) -> Pst. finishrop(Close,#pstate{curpath=P,objects=Objs}=Pst) -> #path{close=Pclose,ops=Ops} = P, Newp = P#path{close=Close or Pclose,ops=reverse(Ops)}, Pst#pstate{objects=[Newp|Objs],curpath=#path{}}. getcontours(Ps) -> map(fun getcedges/1, Ps). getcedges(#path{ops=[#pathop{opkind=pmoveto,x1=X,y1=Y}|Ops]}) -> getcedges(Ops,{X,Y},{X,Y},[]); getcedges(_) -> []. getcedges([],{X,Y},{X,Y},Acc) -> Acc1 = map(fun (CE) -> scalece(CE,?SCALEFAC) end, Acc), reverse(Acc1); prev ! = first , so close with line reverse([#cedge{vs=Prev,ve={X,Y}}|Acc]); getcedges([#pathop{opkind=plineto,x1=X,y1=Y}|Ops],Prev,First,Acc) -> getcedges(Ops,{X,Y},First,[#cedge{vs=Prev,ve={X,Y}}|Acc]); getcedges([#pathop{opkind=pcurveto,x1=X1,y1=Y1,x2=X2,y2=Y2,x3=X,y3=Y}|Ops], Prev,First,Acc) -> getcedges(Ops,{X,Y},First, [#cedge{vs=Prev,cp1={X1,Y1},cp2={X2,Y2},ve={X,Y}}|Acc]); getcedges([_|_],_,_,_) -> []. % funny path (probably moveto in middle), so return nothing scalece(#cedge{vs={Xs,Ys},cp1=nil,cp2=nil,ve={Xe,Ye}},F) -> #cedge{vs={Xs*F,Ys*F},cp1=nil,cp2=nil,ve={Xe*F,Ye*F}}; scalece(#cedge{vs={Xs,Ys},cp1={X1,Y1},cp2={X2,Y2},ve={Xe,Ye}},F) -> #cedge{vs={Xs*F,Ys*F},cp1={X1*F,Y1*F},cp2={X2*F,Y2*F},ve={Xe*F,Ye*F}}. Copied from old wpc_tt.erl %% polyareas_to_faces(Pas) -> VFpairs = map(fun pa2object/1, Pas), concatvfs(VFpairs). concatvfs(Vfp) -> concatvfs(Vfp, 0, [], [], []). concatvfs([{Vs,Fs,HardEdges}|Rest], Offset, Vsacc, Fsacc, Hdacc) -> Fs1 = offsetfaces(Fs, Offset), He1 = offsetfaces(HardEdges, Offset), Off1 = Offset + length(Vs), concatvfs(Rest, Off1, [Vs|Vsacc], Fsacc ++ Fs1, He1 ++ Hdacc); concatvfs([], _Offset, Vsacc, Fsacc, Hdacc) -> He = build_hard_edges(Hdacc, []), {lists:flatten(reverse(Vsacc)),Fsacc, He}. build_hard_edges([[First|_]=Loop|Rest], All) -> New = build_hard_edges(Loop, First, All), build_hard_edges(Rest, New); build_hard_edges([], All) -> All. build_hard_edges([A|[B|_]=Rest], First, All) -> build_hard_edges(Rest, First, [{A,B}|All]); build_hard_edges([Last], First, All) -> [{Last, First}|All]. Subdivide ( bisect each each ) Nsubsteps times . %% When bezier edges are subdivided, the inserted point goes %% at the proper place on the curve. subdivide_pas(Pas,0) -> Pas; subdivide_pas(Pas,Nsubsteps) -> map(fun (Pa) -> subdivide_pa(Pa,Nsubsteps) end, Pas). subdivide_pa(Pa, 0) -> Pa; subdivide_pa(#polyarea{boundary=B,islands=Isls}, N) -> subdivide_pa(#polyarea{boundary=subdivide_contour(B), islands=map(fun subdivide_contour/1, Isls)}, N-1). subdivide_contour(Cntr) -> lists:flatten(map(fun (CE) -> subdivide_cedge(CE,0.5) end, Cntr)). subdivide CE at parameter Alpha , returning two new CE 's in list . subdivide_cedge(#cedge{vs=Vs,cp1=nil,cp2=nil,ve=Ve},Alpha) -> Vm = lininterp(Alpha, Vs, Ve), [#cedge{vs=Vs,ve=Vm}, #cedge{vs=Vm,ve=Ve}]; subdivide_cedge(#cedge{vs=Vs,cp1=C1,cp2=C2,ve=Ve},Alpha) -> B0 = {Vs,C1,C2,Ve}, B1 = bezstep(B0,1,Alpha), B2 = bezstep(B1,2,Alpha), B3 = bezstep(B2,3,Alpha), [#cedge{vs=element(1,B0),cp1=element(1,B1),cp2=element(1,B2),ve=element(1,B3)}, #cedge{vs=element(1,B3),cp1=element(2,B2),cp2=element(3,B1),ve=element(4,B0)}]. bezstep(B,R,Alpha) -> list_to_tuple(bzss(B,0,3-R,Alpha)). bzss(_B,I,Ilim,_Alpha) when I > Ilim -> []; bzss(B,I,Ilim,Alpha) -> [lininterp(Alpha,element(I+1,B),element(I+2,B)) | bzss(B,I+1,Ilim,Alpha)]. lininterp(F,{X1,Y1},{X2,Y2}) -> {(1.0-F)*X1 + F*X2, (1.0-F)*Y1 + F*Y2}. findpolyareas(Cconts) -> Areas = map(fun ccarea/1, Cconts), {Cc,_Ar} = orientccw(Cconts, Areas), Cct = list_to_tuple(Cc), N = size(Cct), Art = list_to_tuple(Areas), Lent = list_to_tuple(map(fun length/1,Cc)), Seqn = lists:seq(1,N), Cls = [ {{I,J},classifyverts(element(I,Cct),element(J,Cct))} || I <- Seqn, J <- Seqn], Clsd = gb_trees:from_orddict(Cls), Cont = [ {{I,J},contains(I,J,Art,Lent,Clsd)} || I <- Seqn, J <- Seqn], Contd = gb_trees:from_orddict(Cont), Assigned = gb_sets:empty(), getpas(1,N,Contd,Cct,{[],Assigned}). getpas(I,N,Contd,Cct,{Pas,Ass}) when I > N -> case length(gb_sets:to_list(Ass)) of N -> reverse(Pas); _ -> %% not all assigned: loop again getpas(1,N,Contd,Cct,{Pas,Ass}) end; getpas(I,N,Contd,Cct,{Pas,Ass}=Acc) -> case gb_sets:is_member(I,Ass) of true -> getpas(I+1,N,Contd,Cct,Acc); _ -> case isboundary(I,N,Contd,Ass) of true -> %% have a new polyarea with boundary = contour I Ass1 = gb_sets:add(I,Ass), {Isls,Ass2} = getisls(I,N,N,Contd,Ass1,Ass1,[]), Cisls = lists:map(fun (K) -> revccont(element(K,Cct)) end, Isls), Pa = #polyarea{boundary=element(I,Cct), islands=Cisls}, getpas(I+1,N,Contd,Cct,{[Pa|Pas],Ass2}); _ -> getpas(I+1,N,Contd,Cct,Acc) end end. Return true if there is no unassigned J < = second arg , J /= I , %% such that contour J contains contour I. isboundary(_I,0,_Contd,_Ass) -> true; isboundary(I,I,Contd,Ass) -> isboundary(I,I-1,Contd,Ass); isboundary(I,J,Contd,Ass) -> case gb_sets:is_member(J,Ass) of true -> isboundary(I,J-1,Contd,Ass); _ -> case gb_trees:get({J,I},Contd) of true -> false; _ -> isboundary(I,J-1,Contd,Ass) end end. %% Find islands for contour I : i.e., unassigned contours directly inside it. %% Only have to check J and less. Ass , are ( assigned - so - far , islands - so - far ) . %% Ass0 is assigned before we started adding islands. %% Return {list of island indices, Assigned array with those indices added} getisls(_I,0,_N,_Contd,_Ass0,Ass,Isls) -> {reverse(Isls),Ass}; getisls(I,J,N,Contd,Ass0,Ass,Isls) -> case gb_sets:is_member(J,Ass) of true -> getisls(I,J-1,N,Contd,Ass0,Ass,Isls); _ -> case directlycont(I,J,N,Contd,Ass0) of true -> getisls(I,J-1,N,Contd,Ass0,gb_sets:add(J,Ass),[J|Isls]); _ -> getisls(I,J-1,N,Contd,Ass0,Ass,Isls) end end. directlycont(I,J,N,Contd,Ass) -> gb_trees:get({I,J},Contd) andalso lists:foldl(fun (K,DC) -> DC andalso (K == J orelse gb_sets:is_member(K,Ass) orelse not(gb_trees:get({K,J},Contd))) end, true, lists:seq(1,N)). ccarea(Ccont) -> 0.5 * lists:foldl(fun (#cedge{vs={X1,Y1},ve={X2,Y2}},A) -> A + X1*Y2 - X2*Y1 end, 0.0, Ccont). %% Reverse contours if area is negative (meaning they were Clockwise), and return revised Cconts and Areas . orientccw(Cconts, Areas) -> orientccw(Cconts, Areas, [], []). orientccw([], [], Cacc, Aacc) -> { reverse(Cacc), reverse(Aacc) }; orientccw([C|Ct], [A|At], Cacc, Aacc) -> if A >= 0.0 -> orientccw(Ct, At, [C|Cacc], [A|Aacc]); true -> orientccw(Ct, At, [revccont(C)|Cacc], [-A|Aacc]) end. revccont(C) -> reverse(map(fun revcedge/1, C)). reverse a cedge revcedge(#cedge{vs=Vs,cp1=Cp1,cp2=Cp2,ve=Ve}) -> #cedge{vs=Ve,cp1=Cp2,cp2=Cp1,ve=Vs}. %% classify vertices of contour B with respect to contour A. %% return {# inside A, # on A}. classifyverts(A,B) -> lists:foldl(fun (#cedge{vs=Vb},Acc) -> cfv(A,Vb,Acc) end, {0,0}, B). %% Decide whether vertex P is inside or on (as a vertex) contour A, and return modified pair . Assumes A is CCW oriented . CF Eric Haines ptinpoly.c in Graphics Gems IV cfv(A,P,{Inside,On}) -> #cedge{vs=Va0} = lists:last(A), if Va0 == P -> {Inside, On+1}; true -> Yflag0 = (element(2,Va0) > element(2,P)), case vinside(A, Va0, P, false, Yflag0) of true -> {Inside+1, On}; false -> {Inside, On}; on -> {Inside, On+1} end end. vinside([], _V0, _P, Inside, _Yflag0) -> Inside; vinside([#cedge{vs={X1,Y1}=V1}|Arest], {X0,Y0}, P={Xp,Yp}, Inside, Yflag0) -> if V1 == P -> on; true -> Yflag1 = (Y1 > Yp), Inside1 = if Yflag0 == Yflag1 -> Inside; true -> Xflag0 = (X0 >= Xp), Xflag1 = (X1 >= Xp), if Xflag0 == Xflag1 -> case Xflag0 of true -> not(Inside); _ -> Inside end; true -> Z = X1 - (Y1-Yp)*(X0-X1)/(Y0-Y1), if Z >= Xp -> not(Inside); true -> Inside end end end, vinside(Arest, V1, P, Inside1, Yflag1) end. I , J are indices into tuple of curved contours . Clsd is gb_tree mapping { I , J } to [ Inside , On , Outside ] . Return true if contour I contains at least 55 % of contour J 's vertices . %% (This low percentage is partly because we are dealing with polygonal approximations %% to curves, sometimes, and the containment relation may seem worse than it actually is.) %% Lengths (in Lent tuple) are used for calculating percentages. %% Areas (in Art tuple) are used for tie-breaking. %% Return false if contour I is different from contour J, and not contained in it. %% Return same if I == J or all vertices on I are on J (duplicate contour). contains(I,I,_,_,_) -> same; contains(I,J,Art,Lent,Clsd) -> LenI = element(I,Lent), LenJ = element(J,Lent), {JinsideI,On} = gb_trees:get({I,J},Clsd), if JinsideI == 0 -> false; On == LenJ, LenI == LenJ -> same; true -> if float(JinsideI) / float(LenJ) > 0.55 -> {IinsideJ,_} = gb_trees:get({J,I},Clsd), FIinJ = float(IinsideJ) / float(LenI), if FIinJ > 0.55 -> element(I,Art) >= element(J,Art); true -> true end; true -> false end end. Return { Vs , Fs } where Vs is list of { X , Y , Z } for vertices 0 , 1 , ... and Fs is list of lists , each sublist is a face ( CCW ordering of ( zero - based ) indices into Vs ) . pa2object(#polyarea{boundary=B,islands=Isls}) -> Vslist = [cel2vec(B, 0.0) | map(fun (L) -> cel2vec(L, 0.0) end, Isls)], Vtop = lists:flatten(Vslist), Vbot = lists:map(fun ({X,Y,Z}) -> {X,Y,Z-0.2} end, Vtop), Vs = Vtop ++ Vbot, Nlist = [length(B) | map(fun (L) -> length(L) end, Isls)], Ntot = lists:sum(Nlist), Fs1 = [FBtop | Holestop] = faces(Nlist,0,top), Fs2 = [FBbot | Holesbot] = faces(Nlist,Ntot,bot), Fsides = sidefaces(Nlist, Ntot), FtopQ = e3d__tri_quad:quadrangulate_face_with_holes(FBtop, Holestop, Vs), FbotQ = e3d__tri_quad:quadrangulate_face_with_holes(FBbot, Holesbot, Vs), Ft = [ F#e3d_face.vs || F <- FtopQ ], Fb = [ F#e3d_face.vs || F <- FbotQ ], Fs = Ft ++ Fb ++ Fsides, {Vs,Fs, [ F#e3d_face.vs || F <- Fs1 ++ Fs2]}. cel2vec(Cel, Z) -> map(fun (#cedge{vs={X,Y}}) -> {X,Y,Z} end, Cel). faces(Nlist,Org,Kind) -> faces(Nlist,Org,Kind,[]). faces([],_Org,_Kind,Acc) -> reverse(Acc); faces([N|T],Org,Kind,Acc) -> FI = case Kind of top -> #e3d_face{vs=lists:seq(Org, Org+N-1)}; bot -> #e3d_face{vs=lists:seq(Org+N-1, Org, -1)} end, faces(T,Org+N,Kind,[FI|Acc]). sidefaces(Nlist,Ntot) -> sidefaces(Nlist,0,Ntot,[]). sidefaces([],_Org,_Ntot,Acc) -> lists:append(reverse(Acc)); sidefaces([N|T],Org,Ntot,Acc) -> End = Org+N-1, Fs = [ [I, Ntot+I, wrap(Ntot+I+1,Ntot+Org,Ntot+End), wrap(I+1,Org,End)] || I <- lists:seq(Org, End) ], sidefaces(T,Org+N,Ntot,[Fs|Acc]). I should be in range ( Start , Start+1 , ... , End ) . Make it so . wrap(I,Start,End) -> Start + ((I-Start) rem (End+1-Start)). offsetfaces(Fl, Offset) -> map(fun (F) -> offsetface(F,Offset) end, Fl). offsetface(F, Offset) -> map(fun (V) -> V+Offset end, F).
null
https://raw.githubusercontent.com/bjorng/wings/1e2c2d62e93a98c263b167c7a41f8611e0ff08cd/plugins_src/import_export/wpc_ai.erl
erlang
For now: - Ignore line width, fill, clip mask, text $Id$ tryimport is for debugging exported to wpc_ps wpc_svg_path all are {x,y} pairs list of pathops true or false pmoveto, plineto, or pcurveto current path object list (paths) skip until after %%EndSetup line, as we currently use nothing before that, then convert rest of binary to list of characters note: this list of chars be exactly those matched explicitly by the non-default cases of tokenize, else get infinite loop AI numbers are either ints or floats no radix notation for ints, no scientific notation for floats sometimes find files with only CRs! skip past next ")", but be careful about escaped ones return rest skip past next ">", return rest consume tokens, return list of objects. an object is either a path or a compoundpath. start point and next bezier control point coincide need curpath to have an op, so can get previous point! end point and previous bezier control point coincide finish job of dopathop[2,4,6] by putting arg pathop onto curpath's ops list and returning Pst with modified curpath note: only pmoveto's can start path, so ignore others funny path (probably moveto in middle), so return nothing When bezier edges are subdivided, the inserted point goes at the proper place on the curve. not all assigned: loop again have a new polyarea with boundary = contour I such that contour J contains contour I. Find islands for contour I : i.e., unassigned contours directly inside it. Only have to check J and less. Ass0 is assigned before we started adding islands. Return {list of island indices, Assigned array with those indices added} Reverse contours if area is negative (meaning they were Clockwise), classify vertices of contour B with respect to contour A. return {# inside A, # on A}. Decide whether vertex P is inside or on (as a vertex) contour A, of contour J 's vertices . (This low percentage is partly because we are dealing with polygonal approximations to curves, sometimes, and the containment relation may seem worse than it actually is.) Lengths (in Lent tuple) are used for calculating percentages. Areas (in Art tuple) are used for tie-breaking. Return false if contour I is different from contour J, and not contained in it. Return same if I == J or all vertices on I are on J (duplicate contour).
wpc_ai.erl -- Adobe Illustrator ( .ai ) import by Some updates by - Only Illustrator version 8 or less files parsed ( v9 - > pdf ) -module(wpc_ai). -export([findpolyareas/1, polyareas_to_faces/1, subdivide_pas/2]). -import(lists, [reverse/1,splitwith/2,member/2, sublist/2,nthtail/2,map/2]). -include_lib("wings/e3d/e3d.hrl"). -include_lib("wings/intl_tools/wings_intl.hrl"). amount to scale AI coords by -record(polyarea, list of cedges ( CCW oriented , closed ) list of lists of cedges ( CW , closed ) -record(path, -record(pathop, x1=0.0, y1=0.0, x2=0.0, y2=0.0, x3=0.0, y3=0.0}). -record(pstate, init() -> true. menu({file,import}, Menu) -> Menu ++ [{"Adobe Illustrator (.ai)...",ai,[option]}]; menu(_, Menu) -> Menu. command({file,{import,{ai,Ask}}}, _St) when is_atom(Ask) -> DefBisect = wpa:pref_get(wpc_ai, bisections, 0), wpa:ask(Ask, ?__(1,"AI Import Options"), [{?__(2,"Number of edge bisections"), DefBisect}], fun(Res) -> {file,{import,ai,Res}} end); command({file,{import,ai,[Nsub]}}, St) -> Props = [{ext,".ai"},{ext_desc,?__(3,"Adobe Illustrator File")}], wpa:import(Props, fun(F) -> make_ai(F, Nsub) end, St); command(_, _) -> next. make_ai(Name, Nsubsteps) -> case catch tryimport(Name, Nsubsteps) of {ok, E3dFile} -> wpa:pref_set(wpc_ai, bisections, Nsubsteps), {ok, E3dFile}; {error,Reason} -> {error, ?__(1,"AI import failed")++": " ++ Reason}; _ -> {error, ?__(2,"AI import internal error")} end. tryimport(Name, Nsubsteps) -> case file:read_file(Name) of {ok,<<"%!PS-Adobe",Rest/binary>>} -> Objs = tokenize_bin(Rest), Closedpaths = [ P || P <- Objs, P#path.close == true ], Cntrs = getcontours(Closedpaths), Pas = findpolyareas(Cntrs), Pas1 = subdivide_pas(Pas,Nsubsteps), {Vs0,Fs,HEs} = polyareas_to_faces(Pas1), Center = e3d_vec:average(e3d_vec:bounding_box(Vs0)), Vec = e3d_vec:sub(e3d_vec:zero(),Center), Vs = reverse(center_object(Vec,Vs0)), Efs = [ #e3d_face{vs=X} || X <- Fs], Mesh = #e3d_mesh{type=polygon,vs=Vs,fs=Efs,he=HEs}, Obj = #e3d_object{name=Name,obj=Mesh}, {ok, #e3d_file{objs=[Obj]}}; {ok,_} -> {error,?__(1,"Not an Adobe Illustrator File (Version 8 or earlier)")}; {error,Reason} -> {error,file:format_error(Reason)} end. center_object(Vec,Vs) -> lists:foldl(fun(V,Acc) -> {X,Y,Z} = e3d_vec:add(V,Vec), [{X,Y,Z}|Acc] end,[],Vs). tokenize_bin(Bin) -> Chars = afterendsetup(Bin), Toks = tokenize(Chars, []), Objs = parsetokens(Toks), Objs. afterendsetup(<<"%%EndSetup",Rest/binary>>) -> binary_to_list(Rest); afterendsetup(<<_,Rest/binary>>) -> afterendsetup(Rest); afterendsetup(_) -> []. tokenize first list ( characters from file ) into list of tokens ( accumulated reversed in second list , reversed at end ) . a token is { tnum , } , { tname , } , { tlitname , } , or { tstring } tokenize([], Toks) -> reverse(Toks); tokenize([C|T], Toks) when C == $\s; C == $\t; C == $\r; C == $\n; these 2 are " should n't happens " tokenize(T, Toks); tokenize("%" ++ T, Toks) -> tokenize(skipline(T), Toks); tokenize("/" ++ T, Toks) -> {Name,TT} = splitwith(fun isnttokbreak/1, T), tokenize(TT, [{tlitname,Name}|Toks]); tokenize("(" ++ T, Toks) -> tokenize(skipstring(T), [{tstring}|Toks]); tokenize("<" ++ T, Toks) -> tokenize(skiphexstring(T), [{tstring}|Toks]); tokenize([C|T], Toks) when C == $[; C == $]; C == ${; C == $} -> tokenize(T, [{tname,[C]}|Toks]); tokenize([C|_] = Arg, Toks) when C >= $0, C =< $9; C==$- -> {Tok,TT} = parsenum(Arg), tokenize(TT, [Tok|Toks]); tokenize(Arg, Toks) -> {Name,TT} = splitwith(fun isnttokbreak/1, Arg), tokenize(TT, [{tname,Name}|Toks]). isnttokbreak(C) -> not(member(C, " \t\r\n()<>[]{}/%")). parsenum([C|Rest]=L) -> case re:run(L, "^((\\+|\\-?)([0-9]+\\.[0-9]*)|(\\.[0-9]+))",[{capture,first}]) of {match,[{0,Length}]} -> Fstr = sublist(L, Length), F = list_to_float(Fstr), {{tnum,F}, nthtail(Length, L)}; nomatch -> case re:run(L, "^(\\+|-)?[0-9]+", [{capture,first}]) of {match, [{0, Length}]} -> Istr = sublist(L, Length), I = list_to_integer(Istr), {{tnum,float(I)}, nthtail(Length, L)}; nomatch -> {{tname,[C]}, Rest} end end. skip past next end of line , return rest skipline("\r\n" ++ T) -> T; skipline("\n" ++ T) -> T; skipline([_|T]) -> skipline(T); skipline([]) -> []. skipstring([]) -> []; skipstring("\\") -> []; skipstring("\\" ++ [_|T]) -> skipstring(T); skipstring(")" ++ T) -> T; skipstring([_|T]) -> skipstring(T). skiphexstring([]) -> []; skiphexstring(">" ++ L) -> L; skiphexstring([_|L]) -> skiphexstring(L). parsetokens(Toks) -> #pstate{objects=Objs}=parse(Toks, #pstate{}), Objs. parse([],#pstate{objects=Objs}=Pst) -> Pst#pstate{objects=reverse(Objs)}; parse([{tname,[_|_]=N}|T], Pst) -> parse(T,dorenderop(N,dopathop0(N,Pst))); parse([{tnum,X1},{tnum,Y1},{tname,[_|_]=N}|T], Pst) -> parse(T,dopathop2(N,{X1,Y1},Pst)); parse([{tnum,X1},{tnum,Y1},{tnum,X2},{tnum,Y2},{tname,[_|_]=N}|T], Pst) -> parse(T,dopathop4(N,{X1,Y1,X2,Y2},Pst)); parse([{tnum,X1},{tnum,Y1},{tnum,X2},{tnum,Y2},{tnum,X3},{tnum,Y3}, {tname,[_|_]=N}|T], Pst) -> parse(T,dopathop6(N,{X1,Y1,X2,Y2,X3,Y3},Pst)); parse([_|T], Pst) -> parse(T, Pst). check if C is a no - arg path operation , and if so , return a modified Pst , otherwise return original Pst dopathop0([C],Pst) when C == $h; C == $H -> P = Pst#pstate.curpath, Pst#pstate{curpath=P#path{close=true}}; dopathop0(_,Pst) -> Pst. dopathop2("m",{X1,Y1},Pst) -> finishpop(#pathop{opkind=pmoveto,x1=X1,y1=Y1},Pst); dopathop2([C],{X1,Y1},Pst) when C==$l; C==$L -> finishpop(#pathop{opkind=plineto,x1=X1,y1=Y1},Pst); dopathop2(_,_,Pst) -> Pst. dopathop4([C],{X2,Y2,X3,Y3},Pst) when C==$v; C==$V -> Pop = #pathop{opkind=pcurveto,x2=X2,y2=Y2,x3=X3,y3=Y3}, case Pst#pstate.curpath of #path{ops=[#pathop{opkind=pmoveto,x1=X1,y1=Y1}|_]} -> finishpop(Pop#pathop{x1=X1,y1=Y1},Pst); #path{ops=[#pathop{opkind=plineto,x1=X1,y1=Y1}|_]} -> finishpop(Pop#pathop{x1=X1,y1=Y1},Pst); #path{ops=[#pathop{opkind=pcurveto,x3=X1,y3=Y1}|_]} -> finishpop(Pop#pathop{x1=X1,y1=Y1},Pst); _ -> Pst end; dopathop4([C],{X1,Y1,X2,Y2},Pst) when C==$y; C==$Y -> finishpop(#pathop{opkind=pcurveto,x1=X1,y1=Y1,x2=X2,y2=Y2,x3=X2,y3=Y2},Pst); dopathop4(_,_,Pst) -> Pst. dopathop6([C],{X1,Y1,X2,Y2,X3,Y3},Pst) when C==$c; C==$C -> finishpop(#pathop{opkind=pcurveto,x1=X1,y1=Y1,x2=X2,y2=Y2,x3=X3,y3=Y3},Pst); dopathop6(_,_,Pst) -> Pst. finishpop(#pathop{opkind=pmoveto}=Pop, #pstate{curpath=#path{ops=[]}}=Pst) -> Pst#pstate{curpath=#path{ops=[Pop]}}; finishpop(_, #pstate{curpath=#path{ops=[]}}=Pst) -> finishpop(Pop, #pstate{curpath=#path{ops=Ops}=P}=Pst) -> Pst#pstate{curpath=P#path{ops=[Pop|Ops]}}. If is a renderop , finish off curpath and put on objects list . dorenderop([C],Pst) when C==$n; C==$f; C==$s; C==$b; C==$B -> finishrop(true,Pst); dorenderop([C],Pst) when C==$N; C==$F; C==$S -> finishrop(false,Pst); dorenderop([$B,C],Pst) when C==$b; C==$g; C==$m; C==$c; C==$B -> finishrop(false,Pst); dorenderop(_,Pst) -> Pst. finishrop(Close,#pstate{curpath=P,objects=Objs}=Pst) -> #path{close=Pclose,ops=Ops} = P, Newp = P#path{close=Close or Pclose,ops=reverse(Ops)}, Pst#pstate{objects=[Newp|Objs],curpath=#path{}}. getcontours(Ps) -> map(fun getcedges/1, Ps). getcedges(#path{ops=[#pathop{opkind=pmoveto,x1=X,y1=Y}|Ops]}) -> getcedges(Ops,{X,Y},{X,Y},[]); getcedges(_) -> []. getcedges([],{X,Y},{X,Y},Acc) -> Acc1 = map(fun (CE) -> scalece(CE,?SCALEFAC) end, Acc), reverse(Acc1); prev ! = first , so close with line reverse([#cedge{vs=Prev,ve={X,Y}}|Acc]); getcedges([#pathop{opkind=plineto,x1=X,y1=Y}|Ops],Prev,First,Acc) -> getcedges(Ops,{X,Y},First,[#cedge{vs=Prev,ve={X,Y}}|Acc]); getcedges([#pathop{opkind=pcurveto,x1=X1,y1=Y1,x2=X2,y2=Y2,x3=X,y3=Y}|Ops], Prev,First,Acc) -> getcedges(Ops,{X,Y},First, [#cedge{vs=Prev,cp1={X1,Y1},cp2={X2,Y2},ve={X,Y}}|Acc]); getcedges([_|_],_,_,_) -> scalece(#cedge{vs={Xs,Ys},cp1=nil,cp2=nil,ve={Xe,Ye}},F) -> #cedge{vs={Xs*F,Ys*F},cp1=nil,cp2=nil,ve={Xe*F,Ye*F}}; scalece(#cedge{vs={Xs,Ys},cp1={X1,Y1},cp2={X2,Y2},ve={Xe,Ye}},F) -> #cedge{vs={Xs*F,Ys*F},cp1={X1*F,Y1*F},cp2={X2*F,Y2*F},ve={Xe*F,Ye*F}}. Copied from old wpc_tt.erl polyareas_to_faces(Pas) -> VFpairs = map(fun pa2object/1, Pas), concatvfs(VFpairs). concatvfs(Vfp) -> concatvfs(Vfp, 0, [], [], []). concatvfs([{Vs,Fs,HardEdges}|Rest], Offset, Vsacc, Fsacc, Hdacc) -> Fs1 = offsetfaces(Fs, Offset), He1 = offsetfaces(HardEdges, Offset), Off1 = Offset + length(Vs), concatvfs(Rest, Off1, [Vs|Vsacc], Fsacc ++ Fs1, He1 ++ Hdacc); concatvfs([], _Offset, Vsacc, Fsacc, Hdacc) -> He = build_hard_edges(Hdacc, []), {lists:flatten(reverse(Vsacc)),Fsacc, He}. build_hard_edges([[First|_]=Loop|Rest], All) -> New = build_hard_edges(Loop, First, All), build_hard_edges(Rest, New); build_hard_edges([], All) -> All. build_hard_edges([A|[B|_]=Rest], First, All) -> build_hard_edges(Rest, First, [{A,B}|All]); build_hard_edges([Last], First, All) -> [{Last, First}|All]. Subdivide ( bisect each each ) Nsubsteps times . subdivide_pas(Pas,0) -> Pas; subdivide_pas(Pas,Nsubsteps) -> map(fun (Pa) -> subdivide_pa(Pa,Nsubsteps) end, Pas). subdivide_pa(Pa, 0) -> Pa; subdivide_pa(#polyarea{boundary=B,islands=Isls}, N) -> subdivide_pa(#polyarea{boundary=subdivide_contour(B), islands=map(fun subdivide_contour/1, Isls)}, N-1). subdivide_contour(Cntr) -> lists:flatten(map(fun (CE) -> subdivide_cedge(CE,0.5) end, Cntr)). subdivide CE at parameter Alpha , returning two new CE 's in list . subdivide_cedge(#cedge{vs=Vs,cp1=nil,cp2=nil,ve=Ve},Alpha) -> Vm = lininterp(Alpha, Vs, Ve), [#cedge{vs=Vs,ve=Vm}, #cedge{vs=Vm,ve=Ve}]; subdivide_cedge(#cedge{vs=Vs,cp1=C1,cp2=C2,ve=Ve},Alpha) -> B0 = {Vs,C1,C2,Ve}, B1 = bezstep(B0,1,Alpha), B2 = bezstep(B1,2,Alpha), B3 = bezstep(B2,3,Alpha), [#cedge{vs=element(1,B0),cp1=element(1,B1),cp2=element(1,B2),ve=element(1,B3)}, #cedge{vs=element(1,B3),cp1=element(2,B2),cp2=element(3,B1),ve=element(4,B0)}]. bezstep(B,R,Alpha) -> list_to_tuple(bzss(B,0,3-R,Alpha)). bzss(_B,I,Ilim,_Alpha) when I > Ilim -> []; bzss(B,I,Ilim,Alpha) -> [lininterp(Alpha,element(I+1,B),element(I+2,B)) | bzss(B,I+1,Ilim,Alpha)]. lininterp(F,{X1,Y1},{X2,Y2}) -> {(1.0-F)*X1 + F*X2, (1.0-F)*Y1 + F*Y2}. findpolyareas(Cconts) -> Areas = map(fun ccarea/1, Cconts), {Cc,_Ar} = orientccw(Cconts, Areas), Cct = list_to_tuple(Cc), N = size(Cct), Art = list_to_tuple(Areas), Lent = list_to_tuple(map(fun length/1,Cc)), Seqn = lists:seq(1,N), Cls = [ {{I,J},classifyverts(element(I,Cct),element(J,Cct))} || I <- Seqn, J <- Seqn], Clsd = gb_trees:from_orddict(Cls), Cont = [ {{I,J},contains(I,J,Art,Lent,Clsd)} || I <- Seqn, J <- Seqn], Contd = gb_trees:from_orddict(Cont), Assigned = gb_sets:empty(), getpas(1,N,Contd,Cct,{[],Assigned}). getpas(I,N,Contd,Cct,{Pas,Ass}) when I > N -> case length(gb_sets:to_list(Ass)) of N -> reverse(Pas); _ -> getpas(1,N,Contd,Cct,{Pas,Ass}) end; getpas(I,N,Contd,Cct,{Pas,Ass}=Acc) -> case gb_sets:is_member(I,Ass) of true -> getpas(I+1,N,Contd,Cct,Acc); _ -> case isboundary(I,N,Contd,Ass) of true -> Ass1 = gb_sets:add(I,Ass), {Isls,Ass2} = getisls(I,N,N,Contd,Ass1,Ass1,[]), Cisls = lists:map(fun (K) -> revccont(element(K,Cct)) end, Isls), Pa = #polyarea{boundary=element(I,Cct), islands=Cisls}, getpas(I+1,N,Contd,Cct,{[Pa|Pas],Ass2}); _ -> getpas(I+1,N,Contd,Cct,Acc) end end. Return true if there is no unassigned J < = second arg , J /= I , isboundary(_I,0,_Contd,_Ass) -> true; isboundary(I,I,Contd,Ass) -> isboundary(I,I-1,Contd,Ass); isboundary(I,J,Contd,Ass) -> case gb_sets:is_member(J,Ass) of true -> isboundary(I,J-1,Contd,Ass); _ -> case gb_trees:get({J,I},Contd) of true -> false; _ -> isboundary(I,J-1,Contd,Ass) end end. Ass , are ( assigned - so - far , islands - so - far ) . getisls(_I,0,_N,_Contd,_Ass0,Ass,Isls) -> {reverse(Isls),Ass}; getisls(I,J,N,Contd,Ass0,Ass,Isls) -> case gb_sets:is_member(J,Ass) of true -> getisls(I,J-1,N,Contd,Ass0,Ass,Isls); _ -> case directlycont(I,J,N,Contd,Ass0) of true -> getisls(I,J-1,N,Contd,Ass0,gb_sets:add(J,Ass),[J|Isls]); _ -> getisls(I,J-1,N,Contd,Ass0,Ass,Isls) end end. directlycont(I,J,N,Contd,Ass) -> gb_trees:get({I,J},Contd) andalso lists:foldl(fun (K,DC) -> DC andalso (K == J orelse gb_sets:is_member(K,Ass) orelse not(gb_trees:get({K,J},Contd))) end, true, lists:seq(1,N)). ccarea(Ccont) -> 0.5 * lists:foldl(fun (#cedge{vs={X1,Y1},ve={X2,Y2}},A) -> A + X1*Y2 - X2*Y1 end, 0.0, Ccont). and return revised Cconts and Areas . orientccw(Cconts, Areas) -> orientccw(Cconts, Areas, [], []). orientccw([], [], Cacc, Aacc) -> { reverse(Cacc), reverse(Aacc) }; orientccw([C|Ct], [A|At], Cacc, Aacc) -> if A >= 0.0 -> orientccw(Ct, At, [C|Cacc], [A|Aacc]); true -> orientccw(Ct, At, [revccont(C)|Cacc], [-A|Aacc]) end. revccont(C) -> reverse(map(fun revcedge/1, C)). reverse a cedge revcedge(#cedge{vs=Vs,cp1=Cp1,cp2=Cp2,ve=Ve}) -> #cedge{vs=Ve,cp1=Cp2,cp2=Cp1,ve=Vs}. classifyverts(A,B) -> lists:foldl(fun (#cedge{vs=Vb},Acc) -> cfv(A,Vb,Acc) end, {0,0}, B). and return modified pair . Assumes A is CCW oriented . CF Eric Haines ptinpoly.c in Graphics Gems IV cfv(A,P,{Inside,On}) -> #cedge{vs=Va0} = lists:last(A), if Va0 == P -> {Inside, On+1}; true -> Yflag0 = (element(2,Va0) > element(2,P)), case vinside(A, Va0, P, false, Yflag0) of true -> {Inside+1, On}; false -> {Inside, On}; on -> {Inside, On+1} end end. vinside([], _V0, _P, Inside, _Yflag0) -> Inside; vinside([#cedge{vs={X1,Y1}=V1}|Arest], {X0,Y0}, P={Xp,Yp}, Inside, Yflag0) -> if V1 == P -> on; true -> Yflag1 = (Y1 > Yp), Inside1 = if Yflag0 == Yflag1 -> Inside; true -> Xflag0 = (X0 >= Xp), Xflag1 = (X1 >= Xp), if Xflag0 == Xflag1 -> case Xflag0 of true -> not(Inside); _ -> Inside end; true -> Z = X1 - (Y1-Yp)*(X0-X1)/(Y0-Y1), if Z >= Xp -> not(Inside); true -> Inside end end end, vinside(Arest, V1, P, Inside1, Yflag1) end. I , J are indices into tuple of curved contours . Clsd is gb_tree mapping { I , J } to [ Inside , On , Outside ] . contains(I,I,_,_,_) -> same; contains(I,J,Art,Lent,Clsd) -> LenI = element(I,Lent), LenJ = element(J,Lent), {JinsideI,On} = gb_trees:get({I,J},Clsd), if JinsideI == 0 -> false; On == LenJ, LenI == LenJ -> same; true -> if float(JinsideI) / float(LenJ) > 0.55 -> {IinsideJ,_} = gb_trees:get({J,I},Clsd), FIinJ = float(IinsideJ) / float(LenI), if FIinJ > 0.55 -> element(I,Art) >= element(J,Art); true -> true end; true -> false end end. Return { Vs , Fs } where Vs is list of { X , Y , Z } for vertices 0 , 1 , ... and Fs is list of lists , each sublist is a face ( CCW ordering of ( zero - based ) indices into Vs ) . pa2object(#polyarea{boundary=B,islands=Isls}) -> Vslist = [cel2vec(B, 0.0) | map(fun (L) -> cel2vec(L, 0.0) end, Isls)], Vtop = lists:flatten(Vslist), Vbot = lists:map(fun ({X,Y,Z}) -> {X,Y,Z-0.2} end, Vtop), Vs = Vtop ++ Vbot, Nlist = [length(B) | map(fun (L) -> length(L) end, Isls)], Ntot = lists:sum(Nlist), Fs1 = [FBtop | Holestop] = faces(Nlist,0,top), Fs2 = [FBbot | Holesbot] = faces(Nlist,Ntot,bot), Fsides = sidefaces(Nlist, Ntot), FtopQ = e3d__tri_quad:quadrangulate_face_with_holes(FBtop, Holestop, Vs), FbotQ = e3d__tri_quad:quadrangulate_face_with_holes(FBbot, Holesbot, Vs), Ft = [ F#e3d_face.vs || F <- FtopQ ], Fb = [ F#e3d_face.vs || F <- FbotQ ], Fs = Ft ++ Fb ++ Fsides, {Vs,Fs, [ F#e3d_face.vs || F <- Fs1 ++ Fs2]}. cel2vec(Cel, Z) -> map(fun (#cedge{vs={X,Y}}) -> {X,Y,Z} end, Cel). faces(Nlist,Org,Kind) -> faces(Nlist,Org,Kind,[]). faces([],_Org,_Kind,Acc) -> reverse(Acc); faces([N|T],Org,Kind,Acc) -> FI = case Kind of top -> #e3d_face{vs=lists:seq(Org, Org+N-1)}; bot -> #e3d_face{vs=lists:seq(Org+N-1, Org, -1)} end, faces(T,Org+N,Kind,[FI|Acc]). sidefaces(Nlist,Ntot) -> sidefaces(Nlist,0,Ntot,[]). sidefaces([],_Org,_Ntot,Acc) -> lists:append(reverse(Acc)); sidefaces([N|T],Org,Ntot,Acc) -> End = Org+N-1, Fs = [ [I, Ntot+I, wrap(Ntot+I+1,Ntot+Org,Ntot+End), wrap(I+1,Org,End)] || I <- lists:seq(Org, End) ], sidefaces(T,Org+N,Ntot,[Fs|Acc]). I should be in range ( Start , Start+1 , ... , End ) . Make it so . wrap(I,Start,End) -> Start + ((I-Start) rem (End+1-Start)). offsetfaces(Fl, Offset) -> map(fun (F) -> offsetface(F,Offset) end, Fl). offsetface(F, Offset) -> map(fun (V) -> V+Offset end, F).
5f33a5628156eb3c82f6e4569e47ad74c246e36c9ad93513542c47b5a33f6ac4
ertugrulcetin/kezban
core.cljc
(ns kezban.core (:require [clojure.pprint :as pp] [clojure.walk :as walk] [clojure.string :as str] #?(:clj [clojure.java.io :as io])) #?(:cljs (:require-macros [cljs.core :as core] [cljs.support :refer [assert-args]])) #?(:clj (:import (java.io StringWriter ByteArrayOutputStream PrintStream) (java.util.concurrent TimeUnit TimeoutException FutureTask) (java.net URL) (clojure.lang RT)))) #?(:cljs (defmacro assert-all "Internal - do not use!" [fnname & pairs] `(do (when-not ~(first pairs) (throw (ex-info ~(str fnname " requires " (second pairs)) {:clojure.error/phase :macro-syntax-check}))) ~(let [more (nnext pairs)] (when more (list* `assert-all fnname more)))))) #?(:clj (defmacro assert-all [& pairs] `(do (when-not ~(first pairs) (throw (IllegalArgumentException. (str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form)))))) ~(let [more (nnext pairs)] (when more (list* `assert-all more)))))) (defmacro def- [name x] (list `def (with-meta name (assoc (meta name) :private true)) x)) (defmacro when-let* "Multiple binding version of when-let" [bindings & body] (when (seq bindings) (assert-all #?(:cljs when-let*) (vector? bindings) "a vector for its binding" (even? (count bindings)) "exactly even forms in binding vector")) (if (seq bindings) `(when-let [~(first bindings) ~(second bindings)] (when-let* ~(vec (drop 2 bindings)) ~@body)) `(do ~@body))) (defmacro if-let* "Multiple binding version of if-let" ([bindings then] `(if-let* ~bindings ~then nil)) ([bindings then else] (when (seq bindings) (assert-all #?(:cljs if-let*) (vector? bindings) "a vector for its binding" (even? (count bindings)) "exactly even forms in binding vector")) (if (seq bindings) `(if-let [~(first bindings) ~(second bindings)] (if-let* ~(vec (drop 2 bindings)) ~then ~else) ~else) then))) (defmacro cond-as-> [expr name & clauses] (assert-all #?(:cljs cond-as->) (even? (count clauses)) "exactly even forms in clauses") (let [g (gensym) steps (map (fn [[test step]] `(if ~test ~step ~name)) (partition 2 clauses))] `(let [~g ~expr ~name ~g ~@(interleave (repeat name) (butlast steps))] ~(if (empty? steps) name (last steps))))) (defmacro ->>> "Takes a set of functions and value at the end of the arguments. Returns a result that is the composition of those funtions.Applies the rightmost of fns to the args(last arg is the value/input!), the next fn (left-to-right) to the result, etc." [& form] `((comp ~@(reverse (rest form))) ~(first form))) (defn nth-safe "Returns the value at the index. get returns nil if index out of bounds,unlike nth nth-safe does not throw an exception, returns nil instead.nth-safe also works for strings, Java arrays, regex Matchers and Lists, and, in O(n) time, for sequences." ([coll n] (nth-safe coll n nil)) ([coll n not-found] (nth coll n not-found))) (defn nnth [coll index & indices] (reduce #(nth-safe %1 %2) coll (cons index indices))) (defn- xor-result [x y] (if (and x y) false (or x y))) #?(:clj (defmacro xor ([] true) ([x] x) ([x & next] (let [first x second `(first '(~@next)) ;; used this eval approach because of lack of private function usage in macro! result (xor-result (eval first) (eval second))] `(if (= (count '~next) 1) ~result (xor ~result ~@(rest next))))))) #?(:clj (defmacro pprint-macro [form] `(pp/pprint (walk/macroexpand-all '~form)))) ;;does not support syntax-quote (defmacro quoted? [form] (if (coll? form) (let [f (first form) s (str f)] `(= "quote" ~s)) false)) (defn- type->str [type] (case type :char "class [C" :byte "class [B" :short "class [S" :int "class [I" :long "class [J" :float "class [F" :double "class [D" :boolean "class [Z" nil)) (defn array? ([arr] (array? nil arr)) ([type arr] (let [c (class arr)] (if type (and (= (type->str type) (str c)) (.isArray c)) (or (some-> c .isArray) false))))) (defn lazy? [x] (= "class clojure.lang.LazySeq" (str (type x)))) (defn any-pred [& preds] (complement (apply every-pred (map complement preds)))) (defmacro try-> [x & forms] `(try (-> ~x ~@forms) (catch #?(:clj Throwable) #?(:cljs js/Error) _#))) (defmacro try->> [x & forms] `(try (->> ~x ~@forms) (catch #?(:clj Throwable) #?(:cljs js/Error) _#))) (defn multi-comp ([fns a b] (multi-comp fns < a b)) ([[f & others :as fns] order a b] (if (seq fns) (let [result (compare (f a) (f b)) f-result (if (= order >) (* -1 result) result)] (if (= 0 f-result) (recur others order a b) f-result)) 0))) #?(:clj (defmacro with-out [& body] `(let [err-buffer# (ByteArrayOutputStream.) original-err# System/err tmp-err# (PrintStream. err-buffer# true "UTF-8") out# (with-out-str (try (System/setErr tmp-err#) ~@body (finally (System/setErr original-err#))))] {:out out# :err (.toString err-buffer# "UTF-8")}))) (defmacro letm [bindings] (assert-all #?(:cljs letm) (vector? bindings) "a vector for its binding" (even? (count bindings)) "an even number of forms in binding vector") `(let* ~(destructure bindings) (merge ~@(map #(hash-map (keyword %) %) (take-nth 2 bindings))))) (defn in? [x coll] (boolean (some #(= x %) coll))) (defn take-while-and-n-more [pred n coll] (let [[head tail] (split-with pred coll)] (concat head (take n tail)))) (defn dissoc-in ([m ks] (if-let [[k & ks] (seq ks)] (if (seq ks) (let [v (dissoc-in (get m k) ks)] (if (empty? v) (dissoc m k) (assoc m k v))) (dissoc m k)) m)) ([m ks & kss] (if-let [[ks' & kss] (seq kss)] (recur (dissoc-in m ks) ks' kss) (dissoc-in m ks)))) #?(:clj (defmacro with-timeout [ms & body] `(let [task# (FutureTask. (fn [] ~@body)) thr# (Thread. task#)] (try (.start thr#) (.get task# ~ms TimeUnit/MILLISECONDS) (catch TimeoutException _# (.cancel task# true) (.stop thr#) (throw (TimeoutException. "Execution timed out."))) (catch Exception e# (.cancel task# true) (.stop thr#) (throw e#)))))) #?(:clj (defn url->file [src f] (let [source (URL. src)] (with-open [i (.openStream source) o (io/output-stream f)] (io/copy i o)) f))) (defmacro cond-let [bindings & forms] (assert-all #?(:cljs cond-let) (vector? bindings) "a vector for its binding" (even? (count bindings)) "an even number of forms in binding vector") `(let* ~(destructure bindings) (cond ~@forms))) (defn keywordize [s] (-> s str/lower-case str/trim (str/replace #"\s+" "-") keyword)) #?(:clj (defn source-clj-file [ns] (require ns) (some->> ns ns-publics vals first meta :file (.getResourceAsStream (RT/baseLoader)) slurp))) #?(:clj (defmacro time* [& forms] `(let [start# (. System (nanoTime)) ret# (do ~@forms)] {:duration (/ (double (- (. System (nanoTime)) start#)) 1000000.0) :result ret#}))) (defn process-lazy-seq [f threshold lazy-s] (when-let [data (seq (take threshold lazy-s))] (doseq [d data] (f d)) (recur f threshold (drop threshold lazy-s)))) #?(:clj (defmacro when-no-aot [& body] `(when-not *compile-files* ~@body))) #?(:clj (defmacro defay [name & forms] `(do (def ~name (delay ~@forms)) (when-not *compile-files* (deref ~name))))) #?(:clj (defmacro locals [] (->> (keys &env) (map (fn [binding] [`(quote ~binding) binding])) (into {})))) (defmacro prog1 [first-form & body] `(let [~'<> ~first-form] ~@body ~'<>)) (defmacro defm [name params & body] `(def ~name (memoize (fn ~params ~@body))))
null
https://raw.githubusercontent.com/ertugrulcetin/kezban/ea4a3139718bb97c2a879f5161de98a92badb4f4/src/kezban/core.cljc
clojure
used this eval approach because of lack of private function usage in macro! does not support syntax-quote
(ns kezban.core (:require [clojure.pprint :as pp] [clojure.walk :as walk] [clojure.string :as str] #?(:clj [clojure.java.io :as io])) #?(:cljs (:require-macros [cljs.core :as core] [cljs.support :refer [assert-args]])) #?(:clj (:import (java.io StringWriter ByteArrayOutputStream PrintStream) (java.util.concurrent TimeUnit TimeoutException FutureTask) (java.net URL) (clojure.lang RT)))) #?(:cljs (defmacro assert-all "Internal - do not use!" [fnname & pairs] `(do (when-not ~(first pairs) (throw (ex-info ~(str fnname " requires " (second pairs)) {:clojure.error/phase :macro-syntax-check}))) ~(let [more (nnext pairs)] (when more (list* `assert-all fnname more)))))) #?(:clj (defmacro assert-all [& pairs] `(do (when-not ~(first pairs) (throw (IllegalArgumentException. (str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form)))))) ~(let [more (nnext pairs)] (when more (list* `assert-all more)))))) (defmacro def- [name x] (list `def (with-meta name (assoc (meta name) :private true)) x)) (defmacro when-let* "Multiple binding version of when-let" [bindings & body] (when (seq bindings) (assert-all #?(:cljs when-let*) (vector? bindings) "a vector for its binding" (even? (count bindings)) "exactly even forms in binding vector")) (if (seq bindings) `(when-let [~(first bindings) ~(second bindings)] (when-let* ~(vec (drop 2 bindings)) ~@body)) `(do ~@body))) (defmacro if-let* "Multiple binding version of if-let" ([bindings then] `(if-let* ~bindings ~then nil)) ([bindings then else] (when (seq bindings) (assert-all #?(:cljs if-let*) (vector? bindings) "a vector for its binding" (even? (count bindings)) "exactly even forms in binding vector")) (if (seq bindings) `(if-let [~(first bindings) ~(second bindings)] (if-let* ~(vec (drop 2 bindings)) ~then ~else) ~else) then))) (defmacro cond-as-> [expr name & clauses] (assert-all #?(:cljs cond-as->) (even? (count clauses)) "exactly even forms in clauses") (let [g (gensym) steps (map (fn [[test step]] `(if ~test ~step ~name)) (partition 2 clauses))] `(let [~g ~expr ~name ~g ~@(interleave (repeat name) (butlast steps))] ~(if (empty? steps) name (last steps))))) (defmacro ->>> "Takes a set of functions and value at the end of the arguments. Returns a result that is the composition of those funtions.Applies the rightmost of fns to the args(last arg is the value/input!), the next fn (left-to-right) to the result, etc." [& form] `((comp ~@(reverse (rest form))) ~(first form))) (defn nth-safe "Returns the value at the index. get returns nil if index out of bounds,unlike nth nth-safe does not throw an exception, returns nil instead.nth-safe also works for strings, Java arrays, regex Matchers and Lists, and, in O(n) time, for sequences." ([coll n] (nth-safe coll n nil)) ([coll n not-found] (nth coll n not-found))) (defn nnth [coll index & indices] (reduce #(nth-safe %1 %2) coll (cons index indices))) (defn- xor-result [x y] (if (and x y) false (or x y))) #?(:clj (defmacro xor ([] true) ([x] x) ([x & next] (let [first x second `(first '(~@next)) result (xor-result (eval first) (eval second))] `(if (= (count '~next) 1) ~result (xor ~result ~@(rest next))))))) #?(:clj (defmacro pprint-macro [form] `(pp/pprint (walk/macroexpand-all '~form)))) (defmacro quoted? [form] (if (coll? form) (let [f (first form) s (str f)] `(= "quote" ~s)) false)) (defn- type->str [type] (case type :char "class [C" :byte "class [B" :short "class [S" :int "class [I" :long "class [J" :float "class [F" :double "class [D" :boolean "class [Z" nil)) (defn array? ([arr] (array? nil arr)) ([type arr] (let [c (class arr)] (if type (and (= (type->str type) (str c)) (.isArray c)) (or (some-> c .isArray) false))))) (defn lazy? [x] (= "class clojure.lang.LazySeq" (str (type x)))) (defn any-pred [& preds] (complement (apply every-pred (map complement preds)))) (defmacro try-> [x & forms] `(try (-> ~x ~@forms) (catch #?(:clj Throwable) #?(:cljs js/Error) _#))) (defmacro try->> [x & forms] `(try (->> ~x ~@forms) (catch #?(:clj Throwable) #?(:cljs js/Error) _#))) (defn multi-comp ([fns a b] (multi-comp fns < a b)) ([[f & others :as fns] order a b] (if (seq fns) (let [result (compare (f a) (f b)) f-result (if (= order >) (* -1 result) result)] (if (= 0 f-result) (recur others order a b) f-result)) 0))) #?(:clj (defmacro with-out [& body] `(let [err-buffer# (ByteArrayOutputStream.) original-err# System/err tmp-err# (PrintStream. err-buffer# true "UTF-8") out# (with-out-str (try (System/setErr tmp-err#) ~@body (finally (System/setErr original-err#))))] {:out out# :err (.toString err-buffer# "UTF-8")}))) (defmacro letm [bindings] (assert-all #?(:cljs letm) (vector? bindings) "a vector for its binding" (even? (count bindings)) "an even number of forms in binding vector") `(let* ~(destructure bindings) (merge ~@(map #(hash-map (keyword %) %) (take-nth 2 bindings))))) (defn in? [x coll] (boolean (some #(= x %) coll))) (defn take-while-and-n-more [pred n coll] (let [[head tail] (split-with pred coll)] (concat head (take n tail)))) (defn dissoc-in ([m ks] (if-let [[k & ks] (seq ks)] (if (seq ks) (let [v (dissoc-in (get m k) ks)] (if (empty? v) (dissoc m k) (assoc m k v))) (dissoc m k)) m)) ([m ks & kss] (if-let [[ks' & kss] (seq kss)] (recur (dissoc-in m ks) ks' kss) (dissoc-in m ks)))) #?(:clj (defmacro with-timeout [ms & body] `(let [task# (FutureTask. (fn [] ~@body)) thr# (Thread. task#)] (try (.start thr#) (.get task# ~ms TimeUnit/MILLISECONDS) (catch TimeoutException _# (.cancel task# true) (.stop thr#) (throw (TimeoutException. "Execution timed out."))) (catch Exception e# (.cancel task# true) (.stop thr#) (throw e#)))))) #?(:clj (defn url->file [src f] (let [source (URL. src)] (with-open [i (.openStream source) o (io/output-stream f)] (io/copy i o)) f))) (defmacro cond-let [bindings & forms] (assert-all #?(:cljs cond-let) (vector? bindings) "a vector for its binding" (even? (count bindings)) "an even number of forms in binding vector") `(let* ~(destructure bindings) (cond ~@forms))) (defn keywordize [s] (-> s str/lower-case str/trim (str/replace #"\s+" "-") keyword)) #?(:clj (defn source-clj-file [ns] (require ns) (some->> ns ns-publics vals first meta :file (.getResourceAsStream (RT/baseLoader)) slurp))) #?(:clj (defmacro time* [& forms] `(let [start# (. System (nanoTime)) ret# (do ~@forms)] {:duration (/ (double (- (. System (nanoTime)) start#)) 1000000.0) :result ret#}))) (defn process-lazy-seq [f threshold lazy-s] (when-let [data (seq (take threshold lazy-s))] (doseq [d data] (f d)) (recur f threshold (drop threshold lazy-s)))) #?(:clj (defmacro when-no-aot [& body] `(when-not *compile-files* ~@body))) #?(:clj (defmacro defay [name & forms] `(do (def ~name (delay ~@forms)) (when-not *compile-files* (deref ~name))))) #?(:clj (defmacro locals [] (->> (keys &env) (map (fn [binding] [`(quote ~binding) binding])) (into {})))) (defmacro prog1 [first-form & body] `(let [~'<> ~first-form] ~@body ~'<>)) (defmacro defm [name params & body] `(def ~name (memoize (fn ~params ~@body))))
b97023f436ef71f5dcce3e9dfb90cd9143854e76efe4fb7b3d03fdaa0234cdef
ekmett/profunctors
Unsafe.hs
# LANGUAGE Trustworthy # # LANGUAGE ScopedTypeVariables # # LANGUAGE QuantifiedConstraints # -- | Copyright : ( C ) 2011 - 2021 -- License : BSD-style (see the file LICENSE) -- Maintainer : < > -- Stability : provisional -- Portability : portable -- For a good explanation of profunctors in Haskell see article : -- -- <-in-haskell.html> -- -- This module includes /unsafe/ composition operators that are useful in practice when it comes to generating optimal core in GHC . -- -- If you import this module you are taking upon yourself the obligation -- that you will only call the operators with @#@ in their names with functions -- that are operationally identity such as @newtype@ constructors or the field -- accessor of a @newtype@. -- -- If you are ever in doubt, use 'rmap' or 'lmap'. module Data.Profunctor.Unsafe ( -- * Profunctors Profunctor(..) ) where import Data.Profunctor.Internal
null
https://raw.githubusercontent.com/ekmett/profunctors/31cc18dc8da8980efd9e0cb3b31000351bb6ab5c/src/Data/Profunctor/Unsafe.hs
haskell
| License : BSD-style (see the file LICENSE) Stability : provisional Portability : portable <-in-haskell.html> This module includes /unsafe/ composition operators that are useful in If you import this module you are taking upon yourself the obligation that you will only call the operators with @#@ in their names with functions that are operationally identity such as @newtype@ constructors or the field accessor of a @newtype@. If you are ever in doubt, use 'rmap' or 'lmap'. * Profunctors
# LANGUAGE Trustworthy # # LANGUAGE ScopedTypeVariables # # LANGUAGE QuantifiedConstraints # Copyright : ( C ) 2011 - 2021 Maintainer : < > For a good explanation of profunctors in Haskell see article : practice when it comes to generating optimal core in GHC . module Data.Profunctor.Unsafe ( Profunctor(..) ) where import Data.Profunctor.Internal
a0fc6ebba69d057734368c29863e103f3d29f0be7e642ec12b2f89e0168c4d6e
sgbj/MaximaSharp
vaxinit.lisp
(setq *gentran-dir ".") (load "local.gtload.lisp")
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/contrib/gentran/vaxinit.lisp
lisp
(setq *gentran-dir ".") (load "local.gtload.lisp")
f5756031a785bdb5e874845b1740b2acc9fae53ff5995633a159c8cddbc2cae1
circuithub/haskell-gerber
Mirroring.hs
module Gerber.Mirroring ( Mirroring(..) ) where data Mirroring = MirrorNone | MirrorX | MirrorY | MirrorXY deriving ( Eq, Show )
null
https://raw.githubusercontent.com/circuithub/haskell-gerber/aa986c2bc67c23f1495de98ee71377752fdb9a16/gerber/lib/Gerber/Mirroring.hs
haskell
module Gerber.Mirroring ( Mirroring(..) ) where data Mirroring = MirrorNone | MirrorX | MirrorY | MirrorXY deriving ( Eq, Show )
639fc01cc9fd4939819e9faff50e041b9350bf6d4a7212737cd7935731a0a3d5
mbutterick/brag
test-old-token.rkt
#lang racket/base ;; Make sure the old token type also works fine. (require brag/examples/simple-line-drawing brag/support racket/list br-parser-tools/lex (prefix-in : br-parser-tools/lex-sre) rackunit) (define-tokens tokens (INTEGER STRING |;| EOF)) (define (make-tokenizer ip) (port-count-lines! ip) (define lex (lexer-src-pos [(:+ numeric) (token-INTEGER (string->number lexeme))] [upper-case (token-STRING lexeme)] ["b" (token-STRING " ")] [";" (|token-;| lexeme)] [whitespace (return-without-pos (lex input-port))] [(eof) (token-EOF 'eof)])) (lambda () (lex ip))) (define the-parsed-object-stx (parse (make-tokenizer (open-input-string #<<EOF 3 9 X; 6 3 b 3 X 3 b; 3 9 X; EOF )))) (check-true (syntax-original? the-parsed-object-stx)) ;; Does the rule name "drawing" also have the proper "original?" property set? (check-true (syntax-original? (first (syntax->list the-parsed-object-stx)))) (check-equal? (syntax->datum the-parsed-object-stx) '(drawing (rows (repeat 3) (chunk 9 "X") ";") (rows (repeat 6) (chunk 3 " ") (chunk 3 "X") (chunk 3 " ") ";") (rows (repeat 3) (chunk 9 "X") ";"))) (define the-parsed-object (syntax->list the-parsed-object-stx)) (check-equal? (syntax-line the-parsed-object-stx) 1) (check-equal? (syntax-column the-parsed-object-stx) 0) (check-equal? (syntax-position the-parsed-object-stx) 1) (check-equal? (syntax-span the-parsed-object-stx) 28) (check-equal? (length the-parsed-object) 4) (check-equal? (syntax->datum (second the-parsed-object)) '(rows (repeat 3) (chunk 9 "X") ";")) (check-equal? (syntax-line (list-ref the-parsed-object 1)) 1) (check-equal? (syntax->datum (third the-parsed-object)) '(rows (repeat 6) (chunk 3 " ") (chunk 3 "X") (chunk 3 " ") ";")) (check-equal? (syntax-line (list-ref the-parsed-object 2)) 2) (check-equal? (syntax->datum (fourth the-parsed-object)) '(rows (repeat 3) (chunk 9 "X") ";")) (check-equal? (syntax-line (list-ref the-parsed-object 3)) 3) ;; FIXME: add tests to make sure location is as we expect. ;; FIXME : handle the EOF issue better . Something in cfg - parser appears to deviate from br - parser - tools / yacc with regards to the stop ;; token.
null
https://raw.githubusercontent.com/mbutterick/brag/6c161ae31df9b4ae7f55a14f754c0b216b60c9a6/brag-lib/brag/test/test-old-token.rkt
racket
Make sure the old token type also works fine. | EOF)) | lexeme)] Does the rule name "drawing" also have the proper "original?" property set? FIXME: add tests to make sure location is as we expect. token.
#lang racket/base (require brag/examples/simple-line-drawing brag/support racket/list br-parser-tools/lex (prefix-in : br-parser-tools/lex-sre) rackunit) (define (make-tokenizer ip) (port-count-lines! ip) (define lex (lexer-src-pos [(:+ numeric) (token-INTEGER (string->number lexeme))] [upper-case (token-STRING lexeme)] ["b" (token-STRING " ")] [";" [whitespace (return-without-pos (lex input-port))] [(eof) (token-EOF 'eof)])) (lambda () (lex ip))) (define the-parsed-object-stx (parse (make-tokenizer (open-input-string #<<EOF EOF )))) (check-true (syntax-original? the-parsed-object-stx)) (check-true (syntax-original? (first (syntax->list the-parsed-object-stx)))) (check-equal? (syntax->datum the-parsed-object-stx) '(drawing (rows (repeat 3) (chunk 9 "X") ";") (rows (repeat 6) (chunk 3 " ") (chunk 3 "X") (chunk 3 " ") ";") (rows (repeat 3) (chunk 9 "X") ";"))) (define the-parsed-object (syntax->list the-parsed-object-stx)) (check-equal? (syntax-line the-parsed-object-stx) 1) (check-equal? (syntax-column the-parsed-object-stx) 0) (check-equal? (syntax-position the-parsed-object-stx) 1) (check-equal? (syntax-span the-parsed-object-stx) 28) (check-equal? (length the-parsed-object) 4) (check-equal? (syntax->datum (second the-parsed-object)) '(rows (repeat 3) (chunk 9 "X") ";")) (check-equal? (syntax-line (list-ref the-parsed-object 1)) 1) (check-equal? (syntax->datum (third the-parsed-object)) '(rows (repeat 6) (chunk 3 " ") (chunk 3 "X") (chunk 3 " ") ";")) (check-equal? (syntax-line (list-ref the-parsed-object 2)) 2) (check-equal? (syntax->datum (fourth the-parsed-object)) '(rows (repeat 3) (chunk 9 "X") ";")) (check-equal? (syntax-line (list-ref the-parsed-object 3)) 3) FIXME : handle the EOF issue better . Something in cfg - parser appears to deviate from br - parser - tools / yacc with regards to the stop
0f140a98e409b19e8607ea2b16d175bd393d9622dfcd219901ea88c590ee83a6
metabase/metabase
alert_test.clj
(ns metabase.api.alert-test "Tests for `/api/alert` endpoints." (:require [clojure.test :refer :all] [medley.core :as m] [metabase.email-test :as et] [metabase.http-client :as client] [metabase.models :refer [Card Collection Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as perms-group] [metabase.models.pulse :as pulse] [metabase.models.pulse-test :as pulse-test] [metabase.server.middleware.util :as mw.util] [metabase.test :as mt] [metabase.test.mock.util :refer [pulse-channel-defaults]] [metabase.util :as u] [toucan.db :as db])) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | Helper Fns & Macros | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- user-details [user-kwd] (-> user-kwd mt/fetch-user (select-keys [:email :first_name :is_qbnewb :is_superuser :last_name :common_name :locale]) (assoc :id true, :date_joined true))) (defn- pulse-card-details [card] (-> card (select-keys [:name :description :display]) (update :display name) (update :collection_id boolean) (assoc :id true, :include_csv false, :include_xls false, :dashboard_card_id false, :dashboard_id false, :parameter_mappings nil))) (defn- recipient-details [user-kwd] (-> user-kwd user-details (dissoc :is_qbnewb :is_superuser :date_joined :locale))) (defn- alert-client [username] (comp mt/boolean-ids-and-timestamps (partial mt/user-http-request username))) (defn- default-email-channel ([pulse-card] (default-email-channel pulse-card [(mt/fetch-user :rasta)])) ([pulse-card recipients] {:id pulse-card :enabled true :channel_type "email" :schedule_type "hourly" :schedule_hour 12 :schedule_day "mon" :recipients recipients :details {}})) (defn- alert-response [response] (m/dissoc-in response [:creator :last_login])) (defmacro ^:private with-test-email [& body] `(mt/with-temporary-setting-values [~'site-url ""] (mt/with-fake-inbox ~@body))) (defmacro ^:private with-alert-setup "Macro that will cleanup any created pulses and setups a fake-inbox to validate emails are sent for new alerts" [& body] `(mt/with-model-cleanup [Pulse] (with-test-email ~@body))) (defn- do-with-alert-in-collection [f] (pulse-test/with-pulse-in-collection [db collection alert card] (assert (db/exists? PulseCard :card_id (u/the-id card), :pulse_id (u/the-id alert))) ;; Make this Alert actually be an alert (db/update! Pulse (u/the-id alert) :alert_condition "rows") (let [alert (db/select-one Pulse :id (u/the-id alert))] (assert (pulse/is-alert? alert)) Since Alerts do not actually go in Collections , but rather their Cards do , put the Card in the Collection (db/update! Card (u/the-id card) :collection_id (u/the-id collection)) (let [card (db/select-one Card :id (u/the-id card))] (f db collection alert card))))) (defmacro ^:private with-alert-in-collection "Do `body` with a temporary Alert whose Card is in a Collection, setting the stage to write various tests below. (Make sure to grant All Users permissions to the Collection if needed.)" {:style/indent 1} [[db-binding collection-binding alert-binding card-binding] & body] I 'm always getting the order of these two mixed up , so let 's try to check that here (when alert-binding (assert (not= alert-binding 'card))) (when card-binding (assert (not= card-binding 'alert))) `(do-with-alert-in-collection (fn [~(or db-binding '_) ~(or collection-binding '_) ~(or alert-binding '_) ~(or card-binding '_)] ~@body))) ;; This stuff below is separate from `with-alert-in-collection` above! (defn- do-with-alerts-in-a-collection "Do `f` with the Cards associated with `alerts-or-ids` in a new temporary Collection. Grant perms to All Users to that Collection using `f`. (The name of this function is somewhat of a misnomer since the Alerts themselves aren't in Collections; it is their Cards that are. Alerts do not go in Collections; their perms are derived from their Cards.)" [grant-collection-perms-fn! alerts-or-ids f] (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp Collection [collection] (grant-collection-perms-fn! (perms-group/all-users) collection) ;; Go ahead and put all the Cards for all of the Alerts in the temp Collection (when (seq alerts-or-ids) (doseq [alert (db/select Pulse :id [:in (set (map u/the-id alerts-or-ids))]) :let [card (#'metabase.models.pulse/alert->card alert)]] (db/update! Card (u/the-id card) :collection_id (u/the-id collection)))) (f)))) (defmacro ^:private with-alerts-in-readable-collection [alerts-or-ids & body] `(do-with-alerts-in-a-collection perms/grant-collection-read-permissions! ~alerts-or-ids (fn [] ~@body))) (defmacro ^:private with-alerts-in-writeable-collection [alerts-or-ids & body] `(do-with-alerts-in-a-collection perms/grant-collection-readwrite-permissions! ~alerts-or-ids (fn [] ~@body))) ;;; +----------------------------------------------------------------------------------------------------------------+ | /api / alert/ * AUTHENTICATION Tests | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same ;; authentication test on every single individual endpoint (deftest auth-tests (is (= (get mw.util/response-unauthentic :body) (client/client :get 401 "alert"))) (is (= (get mw.util/response-unauthentic :body) (client/client :put 401 "alert/13")))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | GET /api/alert | ;;; +----------------------------------------------------------------------------------------------------------------+ ;; by default, archived Alerts should be excluded (deftest get-alerts-test (testing "archived alerts should be excluded" (is (= #{"Not Archived"} (with-alert-in-collection [_ _ not-archived-alert] (with-alert-in-collection [_ _ archived-alert] (db/update! Pulse (u/the-id not-archived-alert) :name "Not Archived") (db/update! Pulse (u/the-id archived-alert) :name "Archived", :archived true) (with-alerts-in-readable-collection [not-archived-alert archived-alert] (set (map :name (mt/user-http-request :rasta :get 200 "alert"))))))))) (testing "fetch archived alerts" (is (= #{"Archived"} (with-alert-in-collection [_ _ not-archived-alert] (with-alert-in-collection [_ _ archived-alert] (db/update! Pulse (u/the-id not-archived-alert) :name "Not Archived") (db/update! Pulse (u/the-id archived-alert) :name "Archived", :archived true) (with-alerts-in-readable-collection [not-archived-alert archived-alert] (set (map :name (mt/user-http-request :rasta :get 200 "alert?archived=true"))))))))) (testing "fetch alerts by user ID -- should return alerts created by the user, or alerts for which the user is a known recipient" (with-alert-in-collection [_ _ creator-alert] (with-alert-in-collection [_ _ recipient-alert] (with-alert-in-collection [_ _ other-alert] (with-alerts-in-readable-collection [creator-alert recipient-alert other-alert] (db/update! Pulse (u/the-id creator-alert) :name "LuckyCreator" :creator_id (mt/user->id :lucky)) (db/update! Pulse (u/the-id recipient-alert) :name "LuckyRecipient") (db/update! Pulse (u/the-id other-alert) :name "Other") (mt/with-temp* [PulseChannel [pulse-channel {:pulse_id (u/the-id recipient-alert)}] PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pulse-channel), :user_id (mt/user->id :lucky)}]] (is (= #{"LuckyCreator" "LuckyRecipient"} (set (map :name (mt/user-http-request :rasta :get 200 (str "alert?user_id=" (mt/user->id :lucky))))))) (is (= #{"LuckyRecipient" "Other"} (set (map :name (mt/user-http-request :rasta :get 200 (str "alert?user_id=" (mt/user->id :rasta))))))) (is (= #{} (set (map :name (mt/user-http-request :rasta :get 200 (str "alert?user_id=" (mt/user->id :trashbird)))))))))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | GET /api/alert/:id | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest get-alert-test (testing "an alert can be fetched by ID" (with-alert-in-collection [_ _ alert] (with-alerts-in-readable-collection [alert] (is (= (u/the-id alert) (:id (mt/user-http-request :rasta :get 200 (str "alert/" (u/the-id alert))))))))) (testing "fetching a non-existing alert returns an error" (mt/user-http-request :rasta :get 404 (str "alert/" 123)))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | POST /api/alert | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest post-alert-test (is (= {:errors {:alert_condition "value must be one of: `goal`, `rows`."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "not rows" :card "foobar"}))) (is (= {:errors {:alert_first_only "value must be a boolean."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows"}))) (is (= {:errors {:card "value must be a map with the keys `id`, `include_csv`, `include_xls`, and `dashboard_card_id`."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows" :alert_first_only false}))) (is (= {:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}}))) (is (= {:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil} :channels "foobar"}))) (is (= {:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil} :channels ["abc"]})))) (defn- new-alert-email [user body-map] (mt/email-to user {:subject "You set up an alert", :body (merge {"" true, "My question" true} body-map)})) (defn- added-to-alert-email [user body-map] (mt/email-to user {:subject "Crowberto Corv added you to an alert", :body (merge {"" true, "now getting alerts" true} body-map)})) (defn- unsubscribe-email [user body-map] (mt/email-to user {:subject "You unsubscribed from an alert", :body (merge {"" true} body-map)})) (defn- default-alert [card] {:id true :name nil :entity_id true :creator_id true :creator (user-details :rasta) :created_at true :updated_at true :card (pulse-card-details card) :alert_condition "rows" :alert_first_only false :alert_above_goal nil :archived false :channels [(merge pulse-channel-defaults {:channel_type "email" :schedule_type "hourly" :schedule_hour nil :recipients [(recipient-details :rasta)] :updated_at true :pulse_id true :id true :created_at true})] :skip_if_empty true :collection_id false :collection_position nil :dashboard_id false :parameters []}) (def ^:private daily-email-channel {:enabled true :channel_type "email" :entity_id true :schedule_type "daily" :schedule_hour 12 :schedule_day nil :recipients []}) ;; Check creation of a new rows alert with email notification (deftest new-rows-with-email-test (mt/with-temp* [Card [card {:name "My question"}]] (is (= [(-> (default-alert card) (assoc-in [:card :include_csv] true) (assoc-in [:card :collection_id] true) (update-in [:channels 0] merge {:schedule_hour 12, :schedule_type "daily", :recipients []})) (new-alert-email :rasta {"has any results" true})] (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp Collection [collection] (db/update! Card (u/the-id card) :collection_id (u/the-id collection)) (with-alert-setup (perms/grant-collection-read-permissions! (perms-group/all-users) collection) [(et/with-expected-messages 1 (alert-response ((alert-client :rasta) :post 200 "alert" {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :collection_id (u/the-id collection) :alert_condition "rows" :alert_first_only false :channels [daily-email-channel]}))) (et/regex-email-bodies #"" #"has any results" #"My question")]))))))) (defn- setify-recipient-emails [results] (update results :channels (fn [channels] (map #(update % :recipients set) channels)))) ;; An admin created alert should notify others they've been subscribed (deftest notify-subscribed-test (mt/with-temp* [Card [card {:name "My question"}]] (is (= {:response (-> (default-alert card) (assoc :creator (user-details :crowberto)) (assoc-in [:card :include_csv] true) (update-in [:channels 0] merge {:schedule_hour 12 :schedule_type "daily" :recipients (set (map recipient-details [:rasta :crowberto]))})) :emails (merge (et/email-to :crowberto {:subject "You set up an alert" :body {"" true "My question" true "now getting alerts" false "confirmation that your alert" true}}) (added-to-alert-email :rasta {"My question" true "now getting alerts" true "confirmation that your alert" false}))} (with-alert-setup (array-map :response (et/with-expected-messages 2 (-> ((alert-client :crowberto) :post 200 "alert" {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :alert_condition "rows" :alert_first_only false :channels [(assoc daily-email-channel :details {:emails nil} :recipients (mapv mt/fetch-user [:crowberto :rasta]))]}) setify-recipient-emails alert-response)) :emails (et/regex-email-bodies #"" #"now getting alerts" #"confirmation that your alert" #"My question"))))))) ;; Check creation of a below goal alert (deftest below-goal-alert-test (is (= (new-alert-email :rasta {"goes below its goal" true}) (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp* [Collection [collection] Card [card {:name "My question" :display "line" :collection_id (u/the-id collection)}]] (perms/grant-collection-read-permissions! (perms-group/all-users) collection) (with-alert-setup (et/with-expected-messages 1 (mt/user-http-request :rasta :post 200 "alert" {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :alert_condition "goal" :alert_above_goal false :alert_first_only false :channels [daily-email-channel]})) (et/regex-email-bodies #"" #"goes below its goal" #"My question"))))))) ;; Check creation of a above goal alert (deftest above-goal-alert-test (is (= (new-alert-email :rasta {"meets its goal" true}) (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp* [Collection [collection] Card [card {:name "My question" :display "bar" :collection_id (u/the-id collection)}]] (perms/grant-collection-read-permissions! (perms-group/all-users) collection) (with-alert-setup (et/with-expected-messages 1 (mt/user-http-request :rasta :post 200 "alert" {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :collection_id (u/the-id collection) :alert_condition "goal" :alert_above_goal true :alert_first_only false :channels [daily-email-channel]})) (et/regex-email-bodies #"" #"meets its goal" #"My question"))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | PUT /api/alert/:id | ;;; +----------------------------------------------------------------------------------------------------------------+ (deftest put-alert-test-2 (is (= {:errors {:alert_condition "value may be nil, or if non-nil, value must be one of: `goal`, `rows`."}} (mt/user-http-request :rasta :put 400 "alert/1" {:alert_condition "not rows"}))) (is (= {:errors {:alert_first_only "value may be nil, or if non-nil, value must be a boolean."}} (mt/user-http-request :rasta :put 400 "alert/1" {:alert_first_only 1000}))) (is (= {:errors {:card (str "value may be nil, or if non-nil, value must be a map with the keys `id`, `include_csv`, " "`include_xls`, and `dashboard_card_id`.")}} (mt/user-http-request :rasta :put 400 "alert/1" {:alert_condition "rows" :alert_first_only false :card "foobar"}))) (is (= {:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. The " "array cannot be empty.")}} (mt/user-http-request :rasta :put 400 "alert/1" {:alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil} :channels "foobar"}))) (is (= {:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. The " "array cannot be empty.")}} (mt/user-http-request :rasta :put 400 "alert/1" {:name "abc" :alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil} :channels ["abc"]})))) (defn default-alert-req ([card pulse-card-or-id] (default-alert-req card pulse-card-or-id {} [])) ([card pulse-card-or-id alert-map users] (merge {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :alert_condition "rows" :alert_first_only false :channels [(if (seq users) (default-email-channel (u/the-id pulse-card-or-id) users) (default-email-channel (u/the-id pulse-card-or-id)))] :skip_if_empty false} alert-map))) (defn basic-alert [] {:alert_condition "rows" :alert_first_only false :creator_id (mt/user->id :rasta) :name nil}) (defn recipient [pulse-channel-or-id username-keyword] (let [user (mt/fetch-user username-keyword)] {:user_id (u/the-id user) :pulse_channel_id (u/the-id pulse-channel-or-id)})) (defn pulse-card [alert-or-id card-or-id] {:pulse_id (u/the-id alert-or-id) :card_id (u/the-id card-or-id) :position 0}) (defn pulse-channel [alert-or-id] {:pulse_id (u/the-id alert-or-id)}) (defn- alert-url [alert-or-id] (format "alert/%d" (u/the-id alert-or-id))) (deftest update-alerts-admin-test (testing "Admin users can update any alert" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= (default-alert card) (mt/with-model-cleanup [Pulse] (alert-response ((alert-client :crowberto) :put 200 (alert-url alert) (default-alert-req card pc)))))))) (testing "Admin users can update any alert, changing the related alert attributes" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= (assoc (default-alert card) :alert_first_only true :alert_above_goal true :alert_condition "goal") (mt/with-model-cleanup [Pulse] (alert-response ((alert-client :crowberto) :put 200 (alert-url alert) (default-alert-req card (u/the-id pc) {:alert_first_only true, :alert_above_goal true, :alert_condition "goal"} [(mt/fetch-user :rasta)])))))))) (testing "Admin users can add a recipient, that recipient should be notified" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (is (= [(-> (default-alert card) (assoc-in [:channels 0 :recipients] (set (map recipient-details [:crowberto :rasta])))) (et/email-to :rasta {:subject "Crowberto Corv added you to an alert" :body {"" true, "now getting alerts" true}})] (with-alert-setup [(et/with-expected-messages 1 (alert-response (setify-recipient-emails ((alert-client :crowberto) :put 200 (alert-url alert) (default-alert-req card pc {} [(mt/fetch-user :crowberto) (mt/fetch-user :rasta)]))))) (et/regex-email-bodies #"" #"now getting alerts")])))))) (deftest update-alerts-non-admin-test (testing "Non-admin users can update alerts they created" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= (-> (default-alert card) (assoc-in [:card :collection_id] true)) (with-alerts-in-writeable-collection [alert] (mt/with-model-cleanup [Pulse] (alert-response ((alert-client :rasta) :put 200 (alert-url alert) (default-alert-req card pc))))))))) (testing "Non-admin users cannot change the recipients of an alert" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= (str "Non-admin users without monitoring or subscription permissions " "are not allowed to modify the channels for an alert") (with-alerts-in-writeable-collection [alert] (mt/with-model-cleanup [Pulse] ((alert-client :rasta) :put 403 (alert-url alert) (default-alert-req card pc {} [(mt/fetch-user :crowberto)]))))))))) (deftest admin-users-remove-recipient-test (testing "admin users can remove a recipieint, that recipient should be notified" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :crowberto)] PulseChannelRecipient [_ (recipient pc :rasta)]] (with-alert-setup (testing "API response" (is (= (-> (default-alert card) (assoc-in [:channels 0 :recipients] [(recipient-details :crowberto)])) (-> (mt/with-expected-messages 1 ((alert-client :crowberto) :put 200 (alert-url alert) (default-alert-req card (u/the-id pc) {} [(mt/fetch-user :crowberto)]))) alert-response)))) (testing "emails" (is (= (mt/email-to :rasta {:subject "You’ve been unsubscribed from an alert" :body {"" true "letting you know that Crowberto Corv" true}}) (mt/regex-email-bodies #"" #"letting you know that Crowberto Corv")))))))) (deftest update-alert-permissions-test (testing "Non-admin users cannot update alerts for cards in a collection they don't have access to" (is (= "You don't have permissions to do that." (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp* [Pulse [alert (assoc (basic-alert) :creator_id (mt/user->id :crowberto))] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (mt/with-non-admin-groups-no-root-collection-perms (with-alert-setup ((alert-client :rasta) :put 403 (alert-url alert) (default-alert-req card pc))))))))) (testing "Non-admin users can't edit alerts if they're not in the recipient list" (is (= "You don't have permissions to do that." (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (with-alert-setup ((alert-client :rasta) :put 403 (alert-url alert) (default-alert-req card pc)))))))) (testing "Non-admin users can update alerts in collection they have view permisisons" (mt/with-non-admin-groups-no-root-collection-perms (with-alert-in-collection [_ collection alert card] (mt/with-temp* [PulseCard [pc (pulse-card alert card)]] (perms/grant-collection-read-permissions! (perms-group/all-users) collection) (mt/user-http-request :rasta :put 200 (alert-url alert) (dissoc (default-alert-req card pc {} []) :card :channels)) (testing "but not allowed to edit the card" (mt/user-http-request :rasta :put 403 (alert-url alert) (dissoc (default-alert-req card pc {} []) :channels)))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ ;;; | GET /alert/question/:id | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- basic-alert-query [] {:name "Foo" :dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :checkins) :aggregation [["count"]] :breakout [[:field (mt/id :checkins :date) {:temporal-unit :hour}]]}}}) (defn- alert-question-url [card-or-id & [archived]] (if archived (format "alert/question/%d?archived=%b" (u/the-id card-or-id) archived) (format "alert/question/%d" (u/the-id card-or-id)))) (defn- api:alert-question-count [user-kw card-or-id & [archived]] (count ((alert-client user-kw) :get 200 (alert-question-url card-or-id archived)))) (deftest get-alert-question-test (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert {:alert_condition "rows" :alert_first_only false :alert_above_goal nil :skip_if_empty true :name nil}] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= [(-> (default-alert card) (assoc :can_write false) (update-in [:channels 0] merge {:schedule_hour 15, :schedule_type "daily"}) (assoc-in [:card :collection_id] true))] (mt/with-non-admin-groups-no-root-collection-perms (with-alert-setup (map alert-response (with-alerts-in-readable-collection [alert] ((alert-client :rasta) :get 200 (alert-question-url card))))))))) (testing "Non-admin users shouldn't see alerts they created if they're no longer recipients" (is (= {:count-1 1 :count-2 0} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (assoc (basic-alert) :alert_above_goal true)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [pcr (recipient pc :rasta)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (array-map :count-1 (count ((alert-client :rasta) :get 200 (alert-question-url card))) :count-2 (do (db/delete! PulseChannelRecipient :id (u/the-id pcr)) (api:alert-question-count :rasta card))))))))) (testing "Non-admin users should not see others alerts, admins see all alerts" (is (= {:rasta 1 :crowberto 2} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert-1 (assoc (basic-alert) :alert_above_goal false)] PulseCard [_ (pulse-card alert-1 card)] PulseChannel [pc-1 (pulse-channel alert-1)] PulseChannelRecipient [_ (recipient pc-1 :rasta)] ;; A separate admin created alert Pulse [alert-2 (assoc (basic-alert) :alert_above_goal false :creator_id (mt/user->id :crowberto))] PulseCard [_ (pulse-card alert-2 card)] PulseChannel [pc-2 (pulse-channel alert-2)] PulseChannelRecipient [_ (recipient pc-2 :crowberto)] PulseChannel [_ (assoc (pulse-channel alert-2) :channel_type "slack")]] (with-alerts-in-readable-collection [alert-1 alert-2] (with-alert-setup (array-map :rasta (api:alert-question-count :rasta card) :crowberto (api:alert-question-count :crowberto card)))))))) (testing "Archived alerts are excluded by default, unless `archived` parameter is sent" (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert-1 (assoc (basic-alert) :alert_above_goal false :archived true)] PulseCard [_ (pulse-card alert-1 card)] PulseChannel [pc-1 (pulse-channel alert-1)] PulseChannelRecipient [_ (recipient pc-1 :rasta)] ;; A separate admin created alert Pulse [alert-2 (assoc (basic-alert) :alert_above_goal false :archived true :creator_id (mt/user->id :crowberto))] PulseCard [_ (pulse-card alert-2 card)] PulseChannel [pc-2 (pulse-channel alert-2)] PulseChannelRecipient [_ (recipient pc-2 :crowberto)] PulseChannel [_ (assoc (pulse-channel alert-2) :channel_type "slack")]] (with-alerts-in-readable-collection [alert-1 alert-2] (with-alert-setup (is (= {:rasta 0 :crowberto 0} (array-map :rasta (api:alert-question-count :rasta card) :crowberto (api:alert-question-count :crowberto card)))) (is (= {:rasta 1 :crowberto 2} (array-map :rasta (api:alert-question-count :rasta card true) :crowberto (api:alert-question-count :crowberto card true))))))))) ;;; +----------------------------------------------------------------------------------------------------------------+ | PUT /api / alert/:id / unsubscribe | ;;; +----------------------------------------------------------------------------------------------------------------+ (defn- alert-unsubscribe-url [alert-or-id] (format "alert/%d/subscription" (u/the-id alert-or-id))) (defn- api:unsubscribe! [user-kw expected-status-code alert-or-id] (mt/user-http-request user-kw :delete expected-status-code (alert-unsubscribe-url alert-or-id))) (defn- recipient-emails [results] (->> results first :channels first :recipients (map :email) set)) (deftest unsubscribe-tests (testing "Alert has two recipients, and non-admin unsubscribes" (is (= {:recipients-1 #{"" ""} :recipients-2 #{""} :emails (unsubscribe-email :rasta {"Foo" true})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (array-map :recipients-1 (recipient-emails (mt/user-http-request :rasta :get 200 (alert-question-url card))) :recipients-2 (do (et/with-expected-messages 1 (api:unsubscribe! :rasta 204 alert)) (recipient-emails (mt/user-http-request :crowberto :get 200 (alert-question-url card)))) :emails (et/regex-email-bodies #"" #"Foo")))))))) (testing "Alert has two recipients, and admin unsubscribes" (is (= {:recipients-1 #{"" ""} :recipients-2 #{""} :emails (unsubscribe-email :crowberto {"Foo" true})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (array-map :recipients-1 (recipient-emails (mt/user-http-request :rasta :get 200 (alert-question-url card))) :recipients-2 (do (et/with-expected-messages 1 (api:unsubscribe! :crowberto 204 alert)) (recipient-emails (mt/user-http-request :crowberto :get 200 (alert-question-url card)))) :emails (et/regex-email-bodies #"" #"Foo")))))))) (testing "Alert should be archived if the last recipient unsubscribes" (is (= {:archived? true :emails (unsubscribe-email :rasta {"Foo" true})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (et/with-expected-messages 1 (api:unsubscribe! :rasta 204 alert)) (array-map :archived? (db/select-one-field :archived Pulse :id (u/the-id alert)) :emails (et/regex-email-bodies #"" #"Foo")))))))) (testing "Alert should not be archived if there is a slack channel" (is (= {:archived? false :emails (unsubscribe-email :rasta {"Foo" true})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc-1 (assoc (pulse-channel alert) :channel_type :email)] PulseChannel [_ (assoc (pulse-channel alert) :channel_type :slack)] PulseChannelRecipient [_ (recipient pc-1 :rasta)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (et/with-expected-messages 1 (api:unsubscribe! :rasta 204 alert)) (array-map :archived? (db/select-one-field :archived Pulse :id (u/the-id alert)) :emails (et/regex-email-bodies #"" #"Foo")))))))) (testing "If email is disabled, users should be unsubscribed" (is (= {:archived? false :emails (et/email-to :rasta {:subject "You’ve been unsubscribed from an alert", :body {"" true, "letting you know that Crowberto Corv" true}})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc-1 (assoc (pulse-channel alert) :channel_type :email)] PulseChannel [_pc-2 (assoc (pulse-channel alert) :channel_type :slack)] PulseChannelRecipient [_ (recipient pc-1 :rasta)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (et/with-expected-messages 1 ((alert-client :crowberto) :put 200 (alert-url alert) (assoc-in (default-alert-req card pc-1) [:channels 0 :enabled] false))) (array-map :archived? (db/select-one-field :archived Pulse :id (u/the-id alert)) :emails (et/regex-email-bodies #"" #"letting you know that Crowberto Corv")))))))) (testing "Re-enabling email should send users a subscribe notification" (is (= {:archived? false :emails (et/email-to :rasta {:subject "Crowberto Corv added you to an alert", :body {"" true, "now getting alerts about .*Foo" true}})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc-1 (assoc (pulse-channel alert) :channel_type :email, :enabled false)] PulseChannel [_pc-2 (assoc (pulse-channel alert) :channel_type :slack)] PulseChannelRecipient [_ (recipient pc-1 :rasta)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (et/with-expected-messages 1 ((alert-client :crowberto) :put 200 (alert-url alert) (assoc-in (default-alert-req card pc-1) [:channels 0 :enabled] true))) (array-map :archived? (db/select-one-field :archived Pulse :id (u/the-id alert)) :emails (et/regex-email-bodies #"" #"now getting alerts about .*Foo") :emails (et/regex-email-bodies #"" #"now getting alerts about .*Foo")))))))))
null
https://raw.githubusercontent.com/metabase/metabase/3b8f0d881c19c96bfdff95a275440db97b1e0173/test/metabase/api/alert_test.clj
clojure
+----------------------------------------------------------------------------------------------------------------+ | Helper Fns & Macros | +----------------------------------------------------------------------------------------------------------------+ Make this Alert actually be an alert This stuff below is separate from `with-alert-in-collection` above! it is their their perms are derived from their Cards.)" Go ahead and put all the Cards for all of the Alerts in the temp Collection +----------------------------------------------------------------------------------------------------------------+ +----------------------------------------------------------------------------------------------------------------+ We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same authentication test on every single individual endpoint +----------------------------------------------------------------------------------------------------------------+ | GET /api/alert | +----------------------------------------------------------------------------------------------------------------+ by default, archived Alerts should be excluded +----------------------------------------------------------------------------------------------------------------+ | GET /api/alert/:id | +----------------------------------------------------------------------------------------------------------------+ +----------------------------------------------------------------------------------------------------------------+ | POST /api/alert | +----------------------------------------------------------------------------------------------------------------+ Check creation of a new rows alert with email notification An admin created alert should notify others they've been subscribed Check creation of a below goal alert Check creation of a above goal alert +----------------------------------------------------------------------------------------------------------------+ | PUT /api/alert/:id | +----------------------------------------------------------------------------------------------------------------+ +----------------------------------------------------------------------------------------------------------------+ | GET /alert/question/:id | +----------------------------------------------------------------------------------------------------------------+ A separate admin created alert A separate admin created alert +----------------------------------------------------------------------------------------------------------------+ +----------------------------------------------------------------------------------------------------------------+
(ns metabase.api.alert-test "Tests for `/api/alert` endpoints." (:require [clojure.test :refer :all] [medley.core :as m] [metabase.email-test :as et] [metabase.http-client :as client] [metabase.models :refer [Card Collection Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as perms-group] [metabase.models.pulse :as pulse] [metabase.models.pulse-test :as pulse-test] [metabase.server.middleware.util :as mw.util] [metabase.test :as mt] [metabase.test.mock.util :refer [pulse-channel-defaults]] [metabase.util :as u] [toucan.db :as db])) (defn- user-details [user-kwd] (-> user-kwd mt/fetch-user (select-keys [:email :first_name :is_qbnewb :is_superuser :last_name :common_name :locale]) (assoc :id true, :date_joined true))) (defn- pulse-card-details [card] (-> card (select-keys [:name :description :display]) (update :display name) (update :collection_id boolean) (assoc :id true, :include_csv false, :include_xls false, :dashboard_card_id false, :dashboard_id false, :parameter_mappings nil))) (defn- recipient-details [user-kwd] (-> user-kwd user-details (dissoc :is_qbnewb :is_superuser :date_joined :locale))) (defn- alert-client [username] (comp mt/boolean-ids-and-timestamps (partial mt/user-http-request username))) (defn- default-email-channel ([pulse-card] (default-email-channel pulse-card [(mt/fetch-user :rasta)])) ([pulse-card recipients] {:id pulse-card :enabled true :channel_type "email" :schedule_type "hourly" :schedule_hour 12 :schedule_day "mon" :recipients recipients :details {}})) (defn- alert-response [response] (m/dissoc-in response [:creator :last_login])) (defmacro ^:private with-test-email [& body] `(mt/with-temporary-setting-values [~'site-url ""] (mt/with-fake-inbox ~@body))) (defmacro ^:private with-alert-setup "Macro that will cleanup any created pulses and setups a fake-inbox to validate emails are sent for new alerts" [& body] `(mt/with-model-cleanup [Pulse] (with-test-email ~@body))) (defn- do-with-alert-in-collection [f] (pulse-test/with-pulse-in-collection [db collection alert card] (assert (db/exists? PulseCard :card_id (u/the-id card), :pulse_id (u/the-id alert))) (db/update! Pulse (u/the-id alert) :alert_condition "rows") (let [alert (db/select-one Pulse :id (u/the-id alert))] (assert (pulse/is-alert? alert)) Since Alerts do not actually go in Collections , but rather their Cards do , put the Card in the Collection (db/update! Card (u/the-id card) :collection_id (u/the-id collection)) (let [card (db/select-one Card :id (u/the-id card))] (f db collection alert card))))) (defmacro ^:private with-alert-in-collection "Do `body` with a temporary Alert whose Card is in a Collection, setting the stage to write various tests below. (Make sure to grant All Users permissions to the Collection if needed.)" {:style/indent 1} [[db-binding collection-binding alert-binding card-binding] & body] I 'm always getting the order of these two mixed up , so let 's try to check that here (when alert-binding (assert (not= alert-binding 'card))) (when card-binding (assert (not= card-binding 'alert))) `(do-with-alert-in-collection (fn [~(or db-binding '_) ~(or collection-binding '_) ~(or alert-binding '_) ~(or card-binding '_)] ~@body))) (defn- do-with-alerts-in-a-collection "Do `f` with the Cards associated with `alerts-or-ids` in a new temporary Collection. Grant perms to All Users to that Collection using `f`. [grant-collection-perms-fn! alerts-or-ids f] (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp Collection [collection] (grant-collection-perms-fn! (perms-group/all-users) collection) (when (seq alerts-or-ids) (doseq [alert (db/select Pulse :id [:in (set (map u/the-id alerts-or-ids))]) :let [card (#'metabase.models.pulse/alert->card alert)]] (db/update! Card (u/the-id card) :collection_id (u/the-id collection)))) (f)))) (defmacro ^:private with-alerts-in-readable-collection [alerts-or-ids & body] `(do-with-alerts-in-a-collection perms/grant-collection-read-permissions! ~alerts-or-ids (fn [] ~@body))) (defmacro ^:private with-alerts-in-writeable-collection [alerts-or-ids & body] `(do-with-alerts-in-a-collection perms/grant-collection-readwrite-permissions! ~alerts-or-ids (fn [] ~@body))) | /api / alert/ * AUTHENTICATION Tests | (deftest auth-tests (is (= (get mw.util/response-unauthentic :body) (client/client :get 401 "alert"))) (is (= (get mw.util/response-unauthentic :body) (client/client :put 401 "alert/13")))) (deftest get-alerts-test (testing "archived alerts should be excluded" (is (= #{"Not Archived"} (with-alert-in-collection [_ _ not-archived-alert] (with-alert-in-collection [_ _ archived-alert] (db/update! Pulse (u/the-id not-archived-alert) :name "Not Archived") (db/update! Pulse (u/the-id archived-alert) :name "Archived", :archived true) (with-alerts-in-readable-collection [not-archived-alert archived-alert] (set (map :name (mt/user-http-request :rasta :get 200 "alert"))))))))) (testing "fetch archived alerts" (is (= #{"Archived"} (with-alert-in-collection [_ _ not-archived-alert] (with-alert-in-collection [_ _ archived-alert] (db/update! Pulse (u/the-id not-archived-alert) :name "Not Archived") (db/update! Pulse (u/the-id archived-alert) :name "Archived", :archived true) (with-alerts-in-readable-collection [not-archived-alert archived-alert] (set (map :name (mt/user-http-request :rasta :get 200 "alert?archived=true"))))))))) (testing "fetch alerts by user ID -- should return alerts created by the user, or alerts for which the user is a known recipient" (with-alert-in-collection [_ _ creator-alert] (with-alert-in-collection [_ _ recipient-alert] (with-alert-in-collection [_ _ other-alert] (with-alerts-in-readable-collection [creator-alert recipient-alert other-alert] (db/update! Pulse (u/the-id creator-alert) :name "LuckyCreator" :creator_id (mt/user->id :lucky)) (db/update! Pulse (u/the-id recipient-alert) :name "LuckyRecipient") (db/update! Pulse (u/the-id other-alert) :name "Other") (mt/with-temp* [PulseChannel [pulse-channel {:pulse_id (u/the-id recipient-alert)}] PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pulse-channel), :user_id (mt/user->id :lucky)}]] (is (= #{"LuckyCreator" "LuckyRecipient"} (set (map :name (mt/user-http-request :rasta :get 200 (str "alert?user_id=" (mt/user->id :lucky))))))) (is (= #{"LuckyRecipient" "Other"} (set (map :name (mt/user-http-request :rasta :get 200 (str "alert?user_id=" (mt/user->id :rasta))))))) (is (= #{} (set (map :name (mt/user-http-request :rasta :get 200 (str "alert?user_id=" (mt/user->id :trashbird)))))))))))))) (deftest get-alert-test (testing "an alert can be fetched by ID" (with-alert-in-collection [_ _ alert] (with-alerts-in-readable-collection [alert] (is (= (u/the-id alert) (:id (mt/user-http-request :rasta :get 200 (str "alert/" (u/the-id alert))))))))) (testing "fetching a non-existing alert returns an error" (mt/user-http-request :rasta :get 404 (str "alert/" 123)))) (deftest post-alert-test (is (= {:errors {:alert_condition "value must be one of: `goal`, `rows`."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "not rows" :card "foobar"}))) (is (= {:errors {:alert_first_only "value must be a boolean."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows"}))) (is (= {:errors {:card "value must be a map with the keys `id`, `include_csv`, `include_xls`, and `dashboard_card_id`."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows" :alert_first_only false}))) (is (= {:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}}))) (is (= {:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil} :channels "foobar"}))) (is (= {:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}} (mt/user-http-request :rasta :post 400 "alert" {:alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil} :channels ["abc"]})))) (defn- new-alert-email [user body-map] (mt/email-to user {:subject "You set up an alert", :body (merge {"" true, "My question" true} body-map)})) (defn- added-to-alert-email [user body-map] (mt/email-to user {:subject "Crowberto Corv added you to an alert", :body (merge {"" true, "now getting alerts" true} body-map)})) (defn- unsubscribe-email [user body-map] (mt/email-to user {:subject "You unsubscribed from an alert", :body (merge {"" true} body-map)})) (defn- default-alert [card] {:id true :name nil :entity_id true :creator_id true :creator (user-details :rasta) :created_at true :updated_at true :card (pulse-card-details card) :alert_condition "rows" :alert_first_only false :alert_above_goal nil :archived false :channels [(merge pulse-channel-defaults {:channel_type "email" :schedule_type "hourly" :schedule_hour nil :recipients [(recipient-details :rasta)] :updated_at true :pulse_id true :id true :created_at true})] :skip_if_empty true :collection_id false :collection_position nil :dashboard_id false :parameters []}) (def ^:private daily-email-channel {:enabled true :channel_type "email" :entity_id true :schedule_type "daily" :schedule_hour 12 :schedule_day nil :recipients []}) (deftest new-rows-with-email-test (mt/with-temp* [Card [card {:name "My question"}]] (is (= [(-> (default-alert card) (assoc-in [:card :include_csv] true) (assoc-in [:card :collection_id] true) (update-in [:channels 0] merge {:schedule_hour 12, :schedule_type "daily", :recipients []})) (new-alert-email :rasta {"has any results" true})] (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp Collection [collection] (db/update! Card (u/the-id card) :collection_id (u/the-id collection)) (with-alert-setup (perms/grant-collection-read-permissions! (perms-group/all-users) collection) [(et/with-expected-messages 1 (alert-response ((alert-client :rasta) :post 200 "alert" {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :collection_id (u/the-id collection) :alert_condition "rows" :alert_first_only false :channels [daily-email-channel]}))) (et/regex-email-bodies #"" #"has any results" #"My question")]))))))) (defn- setify-recipient-emails [results] (update results :channels (fn [channels] (map #(update % :recipients set) channels)))) (deftest notify-subscribed-test (mt/with-temp* [Card [card {:name "My question"}]] (is (= {:response (-> (default-alert card) (assoc :creator (user-details :crowberto)) (assoc-in [:card :include_csv] true) (update-in [:channels 0] merge {:schedule_hour 12 :schedule_type "daily" :recipients (set (map recipient-details [:rasta :crowberto]))})) :emails (merge (et/email-to :crowberto {:subject "You set up an alert" :body {"" true "My question" true "now getting alerts" false "confirmation that your alert" true}}) (added-to-alert-email :rasta {"My question" true "now getting alerts" true "confirmation that your alert" false}))} (with-alert-setup (array-map :response (et/with-expected-messages 2 (-> ((alert-client :crowberto) :post 200 "alert" {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :alert_condition "rows" :alert_first_only false :channels [(assoc daily-email-channel :details {:emails nil} :recipients (mapv mt/fetch-user [:crowberto :rasta]))]}) setify-recipient-emails alert-response)) :emails (et/regex-email-bodies #"" #"now getting alerts" #"confirmation that your alert" #"My question"))))))) (deftest below-goal-alert-test (is (= (new-alert-email :rasta {"goes below its goal" true}) (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp* [Collection [collection] Card [card {:name "My question" :display "line" :collection_id (u/the-id collection)}]] (perms/grant-collection-read-permissions! (perms-group/all-users) collection) (with-alert-setup (et/with-expected-messages 1 (mt/user-http-request :rasta :post 200 "alert" {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :alert_condition "goal" :alert_above_goal false :alert_first_only false :channels [daily-email-channel]})) (et/regex-email-bodies #"" #"goes below its goal" #"My question"))))))) (deftest above-goal-alert-test (is (= (new-alert-email :rasta {"meets its goal" true}) (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp* [Collection [collection] Card [card {:name "My question" :display "bar" :collection_id (u/the-id collection)}]] (perms/grant-collection-read-permissions! (perms-group/all-users) collection) (with-alert-setup (et/with-expected-messages 1 (mt/user-http-request :rasta :post 200 "alert" {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :collection_id (u/the-id collection) :alert_condition "goal" :alert_above_goal true :alert_first_only false :channels [daily-email-channel]})) (et/regex-email-bodies #"" #"meets its goal" #"My question"))))))) (deftest put-alert-test-2 (is (= {:errors {:alert_condition "value may be nil, or if non-nil, value must be one of: `goal`, `rows`."}} (mt/user-http-request :rasta :put 400 "alert/1" {:alert_condition "not rows"}))) (is (= {:errors {:alert_first_only "value may be nil, or if non-nil, value must be a boolean."}} (mt/user-http-request :rasta :put 400 "alert/1" {:alert_first_only 1000}))) (is (= {:errors {:card (str "value may be nil, or if non-nil, value must be a map with the keys `id`, `include_csv`, " "`include_xls`, and `dashboard_card_id`.")}} (mt/user-http-request :rasta :put 400 "alert/1" {:alert_condition "rows" :alert_first_only false :card "foobar"}))) (is (= {:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. The " "array cannot be empty.")}} (mt/user-http-request :rasta :put 400 "alert/1" {:alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil} :channels "foobar"}))) (is (= {:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. The " "array cannot be empty.")}} (mt/user-http-request :rasta :put 400 "alert/1" {:name "abc" :alert_condition "rows" :alert_first_only false :card {:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil} :channels ["abc"]})))) (defn default-alert-req ([card pulse-card-or-id] (default-alert-req card pulse-card-or-id {} [])) ([card pulse-card-or-id alert-map users] (merge {:card {:id (u/the-id card), :include_csv false, :include_xls false, :dashboard_card_id nil} :alert_condition "rows" :alert_first_only false :channels [(if (seq users) (default-email-channel (u/the-id pulse-card-or-id) users) (default-email-channel (u/the-id pulse-card-or-id)))] :skip_if_empty false} alert-map))) (defn basic-alert [] {:alert_condition "rows" :alert_first_only false :creator_id (mt/user->id :rasta) :name nil}) (defn recipient [pulse-channel-or-id username-keyword] (let [user (mt/fetch-user username-keyword)] {:user_id (u/the-id user) :pulse_channel_id (u/the-id pulse-channel-or-id)})) (defn pulse-card [alert-or-id card-or-id] {:pulse_id (u/the-id alert-or-id) :card_id (u/the-id card-or-id) :position 0}) (defn pulse-channel [alert-or-id] {:pulse_id (u/the-id alert-or-id)}) (defn- alert-url [alert-or-id] (format "alert/%d" (u/the-id alert-or-id))) (deftest update-alerts-admin-test (testing "Admin users can update any alert" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= (default-alert card) (mt/with-model-cleanup [Pulse] (alert-response ((alert-client :crowberto) :put 200 (alert-url alert) (default-alert-req card pc)))))))) (testing "Admin users can update any alert, changing the related alert attributes" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= (assoc (default-alert card) :alert_first_only true :alert_above_goal true :alert_condition "goal") (mt/with-model-cleanup [Pulse] (alert-response ((alert-client :crowberto) :put 200 (alert-url alert) (default-alert-req card (u/the-id pc) {:alert_first_only true, :alert_above_goal true, :alert_condition "goal"} [(mt/fetch-user :rasta)])))))))) (testing "Admin users can add a recipient, that recipient should be notified" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (is (= [(-> (default-alert card) (assoc-in [:channels 0 :recipients] (set (map recipient-details [:crowberto :rasta])))) (et/email-to :rasta {:subject "Crowberto Corv added you to an alert" :body {"" true, "now getting alerts" true}})] (with-alert-setup [(et/with-expected-messages 1 (alert-response (setify-recipient-emails ((alert-client :crowberto) :put 200 (alert-url alert) (default-alert-req card pc {} [(mt/fetch-user :crowberto) (mt/fetch-user :rasta)]))))) (et/regex-email-bodies #"" #"now getting alerts")])))))) (deftest update-alerts-non-admin-test (testing "Non-admin users can update alerts they created" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= (-> (default-alert card) (assoc-in [:card :collection_id] true)) (with-alerts-in-writeable-collection [alert] (mt/with-model-cleanup [Pulse] (alert-response ((alert-client :rasta) :put 200 (alert-url alert) (default-alert-req card pc))))))))) (testing "Non-admin users cannot change the recipients of an alert" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= (str "Non-admin users without monitoring or subscription permissions " "are not allowed to modify the channels for an alert") (with-alerts-in-writeable-collection [alert] (mt/with-model-cleanup [Pulse] ((alert-client :rasta) :put 403 (alert-url alert) (default-alert-req card pc {} [(mt/fetch-user :crowberto)]))))))))) (deftest admin-users-remove-recipient-test (testing "admin users can remove a recipieint, that recipient should be notified" (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :crowberto)] PulseChannelRecipient [_ (recipient pc :rasta)]] (with-alert-setup (testing "API response" (is (= (-> (default-alert card) (assoc-in [:channels 0 :recipients] [(recipient-details :crowberto)])) (-> (mt/with-expected-messages 1 ((alert-client :crowberto) :put 200 (alert-url alert) (default-alert-req card (u/the-id pc) {} [(mt/fetch-user :crowberto)]))) alert-response)))) (testing "emails" (is (= (mt/email-to :rasta {:subject "You’ve been unsubscribed from an alert" :body {"" true "letting you know that Crowberto Corv" true}}) (mt/regex-email-bodies #"" #"letting you know that Crowberto Corv")))))))) (deftest update-alert-permissions-test (testing "Non-admin users cannot update alerts for cards in a collection they don't have access to" (is (= "You don't have permissions to do that." (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp* [Pulse [alert (assoc (basic-alert) :creator_id (mt/user->id :crowberto))] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (mt/with-non-admin-groups-no-root-collection-perms (with-alert-setup ((alert-client :rasta) :put 403 (alert-url alert) (default-alert-req card pc))))))))) (testing "Non-admin users can't edit alerts if they're not in the recipient list" (is (= "You don't have permissions to do that." (mt/with-non-admin-groups-no-root-collection-perms (mt/with-temp* [Pulse [alert (basic-alert)] Card [card] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (with-alert-setup ((alert-client :rasta) :put 403 (alert-url alert) (default-alert-req card pc)))))))) (testing "Non-admin users can update alerts in collection they have view permisisons" (mt/with-non-admin-groups-no-root-collection-perms (with-alert-in-collection [_ collection alert card] (mt/with-temp* [PulseCard [pc (pulse-card alert card)]] (perms/grant-collection-read-permissions! (perms-group/all-users) collection) (mt/user-http-request :rasta :put 200 (alert-url alert) (dissoc (default-alert-req card pc {} []) :card :channels)) (testing "but not allowed to edit the card" (mt/user-http-request :rasta :put 403 (alert-url alert) (dissoc (default-alert-req card pc {} []) :channels)))))))) (defn- basic-alert-query [] {:name "Foo" :dataset_query {:database (mt/id) :type :query :query {:source-table (mt/id :checkins) :aggregation [["count"]] :breakout [[:field (mt/id :checkins :date) {:temporal-unit :hour}]]}}}) (defn- alert-question-url [card-or-id & [archived]] (if archived (format "alert/question/%d?archived=%b" (u/the-id card-or-id) archived) (format "alert/question/%d" (u/the-id card-or-id)))) (defn- api:alert-question-count [user-kw card-or-id & [archived]] (count ((alert-client user-kw) :get 200 (alert-question-url card-or-id archived)))) (deftest get-alert-question-test (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert {:alert_condition "rows" :alert_first_only false :alert_above_goal nil :skip_if_empty true :name nil}] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (is (= [(-> (default-alert card) (assoc :can_write false) (update-in [:channels 0] merge {:schedule_hour 15, :schedule_type "daily"}) (assoc-in [:card :collection_id] true))] (mt/with-non-admin-groups-no-root-collection-perms (with-alert-setup (map alert-response (with-alerts-in-readable-collection [alert] ((alert-client :rasta) :get 200 (alert-question-url card))))))))) (testing "Non-admin users shouldn't see alerts they created if they're no longer recipients" (is (= {:count-1 1 :count-2 0} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (assoc (basic-alert) :alert_above_goal true)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [pcr (recipient pc :rasta)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (array-map :count-1 (count ((alert-client :rasta) :get 200 (alert-question-url card))) :count-2 (do (db/delete! PulseChannelRecipient :id (u/the-id pcr)) (api:alert-question-count :rasta card))))))))) (testing "Non-admin users should not see others alerts, admins see all alerts" (is (= {:rasta 1 :crowberto 2} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert-1 (assoc (basic-alert) :alert_above_goal false)] PulseCard [_ (pulse-card alert-1 card)] PulseChannel [pc-1 (pulse-channel alert-1)] PulseChannelRecipient [_ (recipient pc-1 :rasta)] Pulse [alert-2 (assoc (basic-alert) :alert_above_goal false :creator_id (mt/user->id :crowberto))] PulseCard [_ (pulse-card alert-2 card)] PulseChannel [pc-2 (pulse-channel alert-2)] PulseChannelRecipient [_ (recipient pc-2 :crowberto)] PulseChannel [_ (assoc (pulse-channel alert-2) :channel_type "slack")]] (with-alerts-in-readable-collection [alert-1 alert-2] (with-alert-setup (array-map :rasta (api:alert-question-count :rasta card) :crowberto (api:alert-question-count :crowberto card)))))))) (testing "Archived alerts are excluded by default, unless `archived` parameter is sent" (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert-1 (assoc (basic-alert) :alert_above_goal false :archived true)] PulseCard [_ (pulse-card alert-1 card)] PulseChannel [pc-1 (pulse-channel alert-1)] PulseChannelRecipient [_ (recipient pc-1 :rasta)] Pulse [alert-2 (assoc (basic-alert) :alert_above_goal false :archived true :creator_id (mt/user->id :crowberto))] PulseCard [_ (pulse-card alert-2 card)] PulseChannel [pc-2 (pulse-channel alert-2)] PulseChannelRecipient [_ (recipient pc-2 :crowberto)] PulseChannel [_ (assoc (pulse-channel alert-2) :channel_type "slack")]] (with-alerts-in-readable-collection [alert-1 alert-2] (with-alert-setup (is (= {:rasta 0 :crowberto 0} (array-map :rasta (api:alert-question-count :rasta card) :crowberto (api:alert-question-count :crowberto card)))) (is (= {:rasta 1 :crowberto 2} (array-map :rasta (api:alert-question-count :rasta card true) :crowberto (api:alert-question-count :crowberto card true))))))))) | PUT /api / alert/:id / unsubscribe | (defn- alert-unsubscribe-url [alert-or-id] (format "alert/%d/subscription" (u/the-id alert-or-id))) (defn- api:unsubscribe! [user-kw expected-status-code alert-or-id] (mt/user-http-request user-kw :delete expected-status-code (alert-unsubscribe-url alert-or-id))) (defn- recipient-emails [results] (->> results first :channels first :recipients (map :email) set)) (deftest unsubscribe-tests (testing "Alert has two recipients, and non-admin unsubscribes" (is (= {:recipients-1 #{"" ""} :recipients-2 #{""} :emails (unsubscribe-email :rasta {"Foo" true})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (array-map :recipients-1 (recipient-emails (mt/user-http-request :rasta :get 200 (alert-question-url card))) :recipients-2 (do (et/with-expected-messages 1 (api:unsubscribe! :rasta 204 alert)) (recipient-emails (mt/user-http-request :crowberto :get 200 (alert-question-url card)))) :emails (et/regex-email-bodies #"" #"Foo")))))))) (testing "Alert has two recipients, and admin unsubscribes" (is (= {:recipients-1 #{"" ""} :recipients-2 #{""} :emails (unsubscribe-email :crowberto {"Foo" true})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)] PulseChannelRecipient [_ (recipient pc :crowberto)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (array-map :recipients-1 (recipient-emails (mt/user-http-request :rasta :get 200 (alert-question-url card))) :recipients-2 (do (et/with-expected-messages 1 (api:unsubscribe! :crowberto 204 alert)) (recipient-emails (mt/user-http-request :crowberto :get 200 (alert-question-url card)))) :emails (et/regex-email-bodies #"" #"Foo")))))))) (testing "Alert should be archived if the last recipient unsubscribes" (is (= {:archived? true :emails (unsubscribe-email :rasta {"Foo" true})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc (pulse-channel alert)] PulseChannelRecipient [_ (recipient pc :rasta)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (et/with-expected-messages 1 (api:unsubscribe! :rasta 204 alert)) (array-map :archived? (db/select-one-field :archived Pulse :id (u/the-id alert)) :emails (et/regex-email-bodies #"" #"Foo")))))))) (testing "Alert should not be archived if there is a slack channel" (is (= {:archived? false :emails (unsubscribe-email :rasta {"Foo" true})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc-1 (assoc (pulse-channel alert) :channel_type :email)] PulseChannel [_ (assoc (pulse-channel alert) :channel_type :slack)] PulseChannelRecipient [_ (recipient pc-1 :rasta)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (et/with-expected-messages 1 (api:unsubscribe! :rasta 204 alert)) (array-map :archived? (db/select-one-field :archived Pulse :id (u/the-id alert)) :emails (et/regex-email-bodies #"" #"Foo")))))))) (testing "If email is disabled, users should be unsubscribed" (is (= {:archived? false :emails (et/email-to :rasta {:subject "You’ve been unsubscribed from an alert", :body {"" true, "letting you know that Crowberto Corv" true}})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc-1 (assoc (pulse-channel alert) :channel_type :email)] PulseChannel [_pc-2 (assoc (pulse-channel alert) :channel_type :slack)] PulseChannelRecipient [_ (recipient pc-1 :rasta)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (et/with-expected-messages 1 ((alert-client :crowberto) :put 200 (alert-url alert) (assoc-in (default-alert-req card pc-1) [:channels 0 :enabled] false))) (array-map :archived? (db/select-one-field :archived Pulse :id (u/the-id alert)) :emails (et/regex-email-bodies #"" #"letting you know that Crowberto Corv")))))))) (testing "Re-enabling email should send users a subscribe notification" (is (= {:archived? false :emails (et/email-to :rasta {:subject "Crowberto Corv added you to an alert", :body {"" true, "now getting alerts about .*Foo" true}})} (mt/with-temp* [Card [card (basic-alert-query)] Pulse [alert (basic-alert)] PulseCard [_ (pulse-card alert card)] PulseChannel [pc-1 (assoc (pulse-channel alert) :channel_type :email, :enabled false)] PulseChannel [_pc-2 (assoc (pulse-channel alert) :channel_type :slack)] PulseChannelRecipient [_ (recipient pc-1 :rasta)]] (with-alerts-in-readable-collection [alert] (with-alert-setup (et/with-expected-messages 1 ((alert-client :crowberto) :put 200 (alert-url alert) (assoc-in (default-alert-req card pc-1) [:channels 0 :enabled] true))) (array-map :archived? (db/select-one-field :archived Pulse :id (u/the-id alert)) :emails (et/regex-email-bodies #"" #"now getting alerts about .*Foo") :emails (et/regex-email-bodies #"" #"now getting alerts about .*Foo")))))))))
f91d3a72e2d0c0f9d8441713a7a5335d9381d5260cc63c3c789b65de3c49353e
robert-strandh/Second-Climacs
io.lisp
(cl:in-package #:second-climacs-clim-base) (defmethod esa-buffer:frame-make-buffer-from-stream ((frame climacs) stream) (multiple-value-bind (buffer cursor) (base:make-empty-standard-buffer-and-cursor) (base:fill-buffer-from-stream cursor stream) buffer)) (defmethod esa-buffer:frame-save-buffer-to-stream ((frame climacs) (buffer base:standard-buffer) stream) (let* ((cluffer-buffer (base:cluffer-buffer buffer)) (class 'cluffer-standard-line:right-sticky-cursor) (cursor (make-instance class)) (first-line (cluffer:find-line cluffer-buffer 0))) (cluffer:attach-cursor cursor first-line) (loop until (cluffer:end-of-buffer-p cursor) do (write-char (cluffer-emacs:item-after-cursor cursor) stream) (cluffer-emacs:forward-item cursor)))) (defmethod esa-buffer:frame-make-new-buffer ((frame climacs) &key) (multiple-value-bind (buffer cursor) (base:make-empty-standard-buffer-and-cursor) (declare (ignore cursor)) buffer)) (defun file-name-extension (file-path) (let* ((namestring (namestring file-path)) (dot-position (position #\. namestring :from-end t))) (if (null dot-position) nil (subseq namestring (1+ dot-position))))) (defmethod esa-io:frame-find-file :around ((frame climacs) file-path) (let* ((extension (file-name-extension file-path)) (view-class (base:view-class extension)) (buffer (call-next-method)) (cluffer-buffer (base:cluffer-buffer buffer)) (first-line (cluffer:find-line cluffer-buffer 0)) (window (esa:current-window))) (clim:window-clear (left-gutter window)) (when (null view-class) (setf view-class 'fundamental-syntax:view)) (let* ((cursor (make-instance 'base:standard-cursor :buffer buffer)) (view (make-instance view-class :buffer buffer :cursor cursor))) (cluffer:attach-cursor cursor first-line) (push view (base:views frame)) (detach-view window) (attach-view window view)))) ;;; For some reason, write-file gives a string rather than a pathname ;;; to the default method of this generic function. (defmethod esa-io:check-buffer-writability (application-frame (pathname string) (buffer base:standard-buffer)) t)
null
https://raw.githubusercontent.com/robert-strandh/Second-Climacs/64826221fdbc9c615d61917bcafd0917e72c8673/Code/GUI/McCLIM-ESA/io.lisp
lisp
For some reason, write-file gives a string rather than a pathname to the default method of this generic function.
(cl:in-package #:second-climacs-clim-base) (defmethod esa-buffer:frame-make-buffer-from-stream ((frame climacs) stream) (multiple-value-bind (buffer cursor) (base:make-empty-standard-buffer-and-cursor) (base:fill-buffer-from-stream cursor stream) buffer)) (defmethod esa-buffer:frame-save-buffer-to-stream ((frame climacs) (buffer base:standard-buffer) stream) (let* ((cluffer-buffer (base:cluffer-buffer buffer)) (class 'cluffer-standard-line:right-sticky-cursor) (cursor (make-instance class)) (first-line (cluffer:find-line cluffer-buffer 0))) (cluffer:attach-cursor cursor first-line) (loop until (cluffer:end-of-buffer-p cursor) do (write-char (cluffer-emacs:item-after-cursor cursor) stream) (cluffer-emacs:forward-item cursor)))) (defmethod esa-buffer:frame-make-new-buffer ((frame climacs) &key) (multiple-value-bind (buffer cursor) (base:make-empty-standard-buffer-and-cursor) (declare (ignore cursor)) buffer)) (defun file-name-extension (file-path) (let* ((namestring (namestring file-path)) (dot-position (position #\. namestring :from-end t))) (if (null dot-position) nil (subseq namestring (1+ dot-position))))) (defmethod esa-io:frame-find-file :around ((frame climacs) file-path) (let* ((extension (file-name-extension file-path)) (view-class (base:view-class extension)) (buffer (call-next-method)) (cluffer-buffer (base:cluffer-buffer buffer)) (first-line (cluffer:find-line cluffer-buffer 0)) (window (esa:current-window))) (clim:window-clear (left-gutter window)) (when (null view-class) (setf view-class 'fundamental-syntax:view)) (let* ((cursor (make-instance 'base:standard-cursor :buffer buffer)) (view (make-instance view-class :buffer buffer :cursor cursor))) (cluffer:attach-cursor cursor first-line) (push view (base:views frame)) (detach-view window) (attach-view window view)))) (defmethod esa-io:check-buffer-writability (application-frame (pathname string) (buffer base:standard-buffer)) t)
fd323b85a534ddb6e9f2bbdf58103f0475beab28debe7065089377e1ec6d7bfd
cpeikert/ALCHEMY
Common.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE NoImplicitPrelude # # LANGUAGE PartialTypeSignatures # # LANGUAGE PolyKinds # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} # OPTIONS_GHC -fno - warn - partial - type - signatures # module Common where import Control.DeepSeq import Control.Monad.IO.Class import Crypto.Alchemy import Crypto.Lol import Crypto.Lol.Types import Data.Time.Clock import System.IO import Text.Printf import Prelude hiding (fromIntegral, div, (/)) -- a concrete Z_{2^e} data type type Z2E e = ZqBasic ('PP '(Prime2, e)) Int64 shorthand for Z_q type type Zq q = ZqBasic q Int64 Template Haskell is quicker than using the FMul type familiy $(mapM fDec [2912, 3640, 5460, 4095, 11648, 29120, 43680, 54600, 27300, 20475]) -- plaintext ring indices type H0 = F128 F64 * F7 F32 * F7 * F13 F8 * F5 * F7 * F13 F4 * F3 * F5 * F7 * F13 F9 * F5 * F7 * F13 -- corresponding ciphertext ring indices H0 * F13 * F7 type H1' = F29120 -- H1 * F13 * F5 type H2' = F43680 -- H2 * F5 * F3 type H3' = F54600 -- H3 * F5 * F3 H4 * F5 type H5' = F20475 -- H5 * F5 putStrLnIO :: MonadIO m => String -> m () putStrLnIO = liftIO . putStrLn printIO :: (MonadIO m, Show a) => a -> m () printIO = liftIO . print -- | Linear function mapping the decoding basis (relative to the -- largest common subring) to (the same number of) CRT slots. r first for convenient type apps (e ~ FGCD r s, e `Divides` r, e `Divides` s, Cyclotomic (c s zp), CRTSetCyc c zp) => Linear c e r s zp decToCRT = let crts = proxy crtSet (Proxy::Proxy e) phir = totientFact @r phie = totientFact @e dim = phir `div` phie -- only take as many crts as we need, otherwise linearDec fails in linearDec $ take dim crts {--- | Switch H0 -> H1-} switch1 : : ( LinearCycCtx _ expr ( PNoiseCyc p c ) ( FGCD H0 H1 ) H0 H1 zp , LinearCyc _ expr ( PNoiseCyc p c ) , NFData ( c H1 zp ) , Cyclotomic ( c H1 zp ) , CRTSetCyc c zp ) = > expr env ( _ - > PNoiseCyc p c H1 zp ) switch1 = linearCyc _ $ ! ! decToCRT @H0 -- force arg before application {--- | Switch H0 -> H1 -> H2-} : : ( LinearCycCtx _ expr ( PNoise p c ) ( FGCD H0 H1 ) H0 H1 zp , LinearCyc _ expr ( PNoiseCyc p c ) , NFData ( c H1 zp ) , Cyclotomic ( c H1 zp ) CRTSetCyc c zp , LinearCycCtx _ expr ( PNoise p c ) ( FGCD H1 H2 ) H1 H2 zp , NFData ( c H2 zp ) , Cyclotomic ( c H2 zp ) ) = > expr env ( _ - > PNoiseCyc p c H2 zp ) = ( linearCyc _ $ ! ! decToCRT @H1 ) . : switch1 -- strict composition switch1 :: _ => expr env (_ -> c H1 zp) switch1 = linearCyc_ $!! decToCRT @H0 switch2 :: _ => expr env (_ -> c H2 zp) switch2 = linearCyc_ $!! decToCRT @H1 switch3 :: _ => expr env (_ -> c H3 zp) switch3 = linearCyc_ $!! decToCRT @H2 switch4 :: _ => expr env (_ -> c H4 zp) switch4 = linearCyc_ $!! decToCRT @H3 switch5 :: _ => expr env (_ -> c H5 zp) switch5 = linearCyc_ $!! decToCRT @H4 {-# INLINABLE switch1 #-} {-# INLINABLE switch2 #-} # INLINABLE switch3 # # INLINABLE switch4 # {-# INLINABLE switch5 #-} -- timing functionality -- | time the 'seq'ing of a value timeWHNF :: (MonadIO m) => String -> a -> m a timeWHNF s m = liftIO $ do putStr' s wallStart <- getCurrentTime out <- return $! m printTimes wallStart 1 return out timeWHNFIO :: (MonadIO m) => String -> m a -> m a timeWHNFIO s mm = do liftIO $ putStr' s wallStart <- liftIO getCurrentTime m <- mm out <- return $! m liftIO $ printTimes wallStart 1 return out -- | time the 'deepseq'ing of a value timeNF :: (NFData a, MonadIO m) => String -> a -> m a timeNF s m = liftIO $ do putStr' s wallStart <- getCurrentTime out <- return $! force m printTimes wallStart 1 return out -- | time the 'deepseq'ing of a value timeNFIO :: (NFData a, MonadIO m) => String -> m a -> m a timeNFIO s mm = do liftIO $ putStr' s wallStart <- liftIO getCurrentTime m <- mm out <- return $! force m liftIO $ printTimes wallStart 1 return out commenting out because this does n't deepseq timeIO : : ( MonadIO m ) = > String - > m a - > m a timeIO s m = do liftIO $ putStr ' s getCurrentTime m ' < - m liftIO $ printTimes wallStart 1 return m ' timeIO :: (MonadIO m) => String -> m a -> m a timeIO s m = do liftIO $ putStr' s wallStart <- liftIO getCurrentTime m' <- m liftIO $ printTimes wallStart 1 return m' -} -- flushes the print buffer putStr' :: String -> IO () putStr' str = do putStr str hFlush stdout printTimes :: UTCTime -> Int -> IO () printTimes wallStart iters = do wallEnd <- getCurrentTime let wallTime = realToFrac $ diffUTCTime wallEnd wallStart :: Double printf "Wall time: %0.3fs" wallTime if iters == 1 then putStr "\n\n" else printf "\tAverage wall time: %0.3fs\n\n" $ wallTime / fromIntegral iters
null
https://raw.githubusercontent.com/cpeikert/ALCHEMY/adbef64576c6f6885600da66f59c5a4ad91810b7/examples/Common.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeOperators # a concrete Z_{2^e} data type plaintext ring indices corresponding ciphertext ring indices H1 * F13 * F5 H2 * F5 * F3 H3 * F5 * F3 H5 * F5 | Linear function mapping the decoding basis (relative to the largest common subring) to (the same number of) CRT slots. only take as many crts as we need, otherwise linearDec fails -- | Switch H0 -> H1 force arg before application -- | Switch H0 -> H1 -> H2 strict composition # INLINABLE switch1 # # INLINABLE switch2 # # INLINABLE switch5 # timing functionality | time the 'seq'ing of a value | time the 'deepseq'ing of a value | time the 'deepseq'ing of a value flushes the print buffer
# LANGUAGE NoImplicitPrelude # # LANGUAGE PartialTypeSignatures # # LANGUAGE PolyKinds # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # OPTIONS_GHC -fno - warn - partial - type - signatures # module Common where import Control.DeepSeq import Control.Monad.IO.Class import Crypto.Alchemy import Crypto.Lol import Crypto.Lol.Types import Data.Time.Clock import System.IO import Text.Printf import Prelude hiding (fromIntegral, div, (/)) type Z2E e = ZqBasic ('PP '(Prime2, e)) Int64 shorthand for Z_q type type Zq q = ZqBasic q Int64 Template Haskell is quicker than using the FMul type familiy $(mapM fDec [2912, 3640, 5460, 4095, 11648, 29120, 43680, 54600, 27300, 20475]) type H0 = F128 F64 * F7 F32 * F7 * F13 F8 * F5 * F7 * F13 F4 * F3 * F5 * F7 * F13 F9 * F5 * F7 * F13 H0 * F13 * F7 H4 * F5 putStrLnIO :: MonadIO m => String -> m () putStrLnIO = liftIO . putStrLn printIO :: (MonadIO m, Show a) => a -> m () printIO = liftIO . print r first for convenient type apps (e ~ FGCD r s, e `Divides` r, e `Divides` s, Cyclotomic (c s zp), CRTSetCyc c zp) => Linear c e r s zp decToCRT = let crts = proxy crtSet (Proxy::Proxy e) phir = totientFact @r phie = totientFact @e dim = phir `div` phie in linearDec $ take dim crts switch1 : : ( LinearCycCtx _ expr ( PNoiseCyc p c ) ( FGCD H0 H1 ) H0 H1 zp , LinearCyc _ expr ( PNoiseCyc p c ) , NFData ( c H1 zp ) , Cyclotomic ( c H1 zp ) , CRTSetCyc c zp ) = > expr env ( _ - > PNoiseCyc p c H1 zp ) : : ( LinearCycCtx _ expr ( PNoise p c ) ( FGCD H0 H1 ) H0 H1 zp , LinearCyc _ expr ( PNoiseCyc p c ) , NFData ( c H1 zp ) , Cyclotomic ( c H1 zp ) CRTSetCyc c zp , LinearCycCtx _ expr ( PNoise p c ) ( FGCD H1 H2 ) H1 H2 zp , NFData ( c H2 zp ) , Cyclotomic ( c H2 zp ) ) = > expr env ( _ - > PNoiseCyc p c H2 zp ) switch1 :: _ => expr env (_ -> c H1 zp) switch1 = linearCyc_ $!! decToCRT @H0 switch2 :: _ => expr env (_ -> c H2 zp) switch2 = linearCyc_ $!! decToCRT @H1 switch3 :: _ => expr env (_ -> c H3 zp) switch3 = linearCyc_ $!! decToCRT @H2 switch4 :: _ => expr env (_ -> c H4 zp) switch4 = linearCyc_ $!! decToCRT @H3 switch5 :: _ => expr env (_ -> c H5 zp) switch5 = linearCyc_ $!! decToCRT @H4 # INLINABLE switch3 # # INLINABLE switch4 # timeWHNF :: (MonadIO m) => String -> a -> m a timeWHNF s m = liftIO $ do putStr' s wallStart <- getCurrentTime out <- return $! m printTimes wallStart 1 return out timeWHNFIO :: (MonadIO m) => String -> m a -> m a timeWHNFIO s mm = do liftIO $ putStr' s wallStart <- liftIO getCurrentTime m <- mm out <- return $! m liftIO $ printTimes wallStart 1 return out timeNF :: (NFData a, MonadIO m) => String -> a -> m a timeNF s m = liftIO $ do putStr' s wallStart <- getCurrentTime out <- return $! force m printTimes wallStart 1 return out timeNFIO :: (NFData a, MonadIO m) => String -> m a -> m a timeNFIO s mm = do liftIO $ putStr' s wallStart <- liftIO getCurrentTime m <- mm out <- return $! force m liftIO $ printTimes wallStart 1 return out commenting out because this does n't deepseq timeIO : : ( MonadIO m ) = > String - > m a - > m a timeIO s m = do liftIO $ putStr ' s getCurrentTime m ' < - m liftIO $ printTimes wallStart 1 return m ' timeIO :: (MonadIO m) => String -> m a -> m a timeIO s m = do liftIO $ putStr' s wallStart <- liftIO getCurrentTime m' <- m liftIO $ printTimes wallStart 1 return m' -} putStr' :: String -> IO () putStr' str = do putStr str hFlush stdout printTimes :: UTCTime -> Int -> IO () printTimes wallStart iters = do wallEnd <- getCurrentTime let wallTime = realToFrac $ diffUTCTime wallEnd wallStart :: Double printf "Wall time: %0.3fs" wallTime if iters == 1 then putStr "\n\n" else printf "\tAverage wall time: %0.3fs\n\n" $ wallTime / fromIntegral iters
99d6d0fe49bde0276485ec5c65849d3345d3ed22ce458a63b93f2836de6916bd
facebookarchive/pfff
graph_code_ml.ml
* * Copyright ( C ) 2012 Facebook * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2012 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common module E = Entity_code module G = Graph_code open Ast_ml module V = Visitor_ml module Ast = Ast_ml (*****************************************************************************) (* Prelude *) (*****************************************************************************) * Obsolete file : see graph_code_cmt.ml for a more complete graph . * * Partial graph of dependencies for OCaml using essentially just the * open directives . * * todo ? if give edges a weight , then we need to modulate it depending on * the type of the reference . Two references to a function in another * module is more important than 10 references to some constructors ? * If we do some pattern matching on 20 constructors , is it more * important than two functions calls ? * So Type|Exception > Function|Class|Global > > Constructors|constants ? * * notes : * - ml vs mli ? just get rid of mli ? but one can also want to * care only about mli dependencies , like I did with my ' make ' . * We can introduce a Module entity that is the parent of the * ml and mli file ( this has - graph unify many things :) ) . * * TODO but there is still the issue about where to put the edge * when one module call a function in another module . Do we * link the call to the def in the mli or in the ml ? * * schema : * Root - > Dir - > Module - > File ( .ml ) - > # TODO * * - > File ( .mli ) * - > Dir - > File # no intermediate Module node when there is a dupe * # on a module name ( e.g. for main.ml ) * * - > Dir - > SubDir - > Module - > ... * Obsolete file: see graph_code_cmt.ml for a more complete graph. * * Partial graph of dependencies for OCaml using essentially just the * open directives. * * todo? if give edges a weight, then we need to modulate it depending on * the type of the reference. Two references to a function in another * module is more important than 10 references to some constructors? * If we do some pattern matching on 20 constructors, is it more * important than two functions calls? * So Type|Exception > Function|Class|Global >> Constructors|constants ? * * notes: * - ml vs mli? just get rid of mli? but one can also want to * care only about mli dependencies, like I did with my 'make doti'. * We can introduce a Module entity that is the parent of the * ml and mli file (this has-graph unify many things :) ). * * TODO but there is still the issue about where to put the edge * when one module call a function in another module. Do we * link the call to the def in the mli or in the ml? * * schema: * Root -> Dir -> Module -> File (.ml) -> # TODO * * -> File (.mli) * -> Dir -> File # no intermediate Module node when there is a dupe * # on a module name (e.g. for main.ml) * * -> Dir -> SubDir -> Module -> ... *) (*****************************************************************************) (* Types *) (*****************************************************************************) (*****************************************************************************) (* Helpers *) (*****************************************************************************) let parse file = Common.save_excursion Flag_parsing_ml.show_parsing_error false (fun ()-> Common.save_excursion Flag_parsing_ml.exn_when_lexical_error true (fun ()-> try Parse_ml.parse_program file with Parse_ml.Parse_error _ -> pr2 ("PARSING problem in: " ^ file); [] )) todo : move this code in another file ? module_analysis_ml.ml ? let lookup_module_name h_module_aliases s = try Hashtbl.find h_module_aliases s with Not_found -> s (*****************************************************************************) (* Defs *) (*****************************************************************************) (* * We just create the Dir, File, and Module entities. * See graph_code_cmt.ml if you want Function, Type, etc. *) let extract_defs ~g ~duplicate_modules ~ast ~readable ~file = ignore(ast); let dir = Common2.dirname readable in G.create_intermediate_directories_if_not_present g dir; let m = Module_ml.module_name_of_filename file in g +> G.add_node (readable, E.File); match () with | _ when List.mem m (Common2.keys duplicate_modules) -> we could attach to two parents when we are almost sure that * nobody will reference this module ( e.g. because it 's an * entry point ) , but then all the uses in those files would * propagate to two parents , so when we have a dupe , we * do n't create the intermediate Module node . If it 's referenced * somewhere then it will generate a lookup failure . * So just Dir - > File here , no Dir - > Module - > File . * nobody will reference this module (e.g. because it's an * entry point), but then all the uses in those files would * propagate to two parents, so when we have a dupe, we * don't create the intermediate Module node. If it's referenced * somewhere then it will generate a lookup failure. * So just Dir -> File here, no Dir -> Module -> File. *) g +> G.add_edge ((dir, E.Dir), (readable, E.File)) G.Has; (match m with | s when s =~ "Main.*" || s =~ "Demo.*" || s =~ "Test.*" || s =~ "Foo.*" -> () | _ when file =~ ".*external/" -> () | _ -> pr2 (spf "PB: module %s is already present (%s)" m (Common.dump (List.assoc m duplicate_modules))); ) | _ when G.has_node (m, E.Module) g -> (match G.parents (m, E.Module) g with probably because processed .mli or .ml before which created the node | [p] when p =*= (dir, E.Dir) -> g +> G.add_edge ((m, E.Module), (readable, E.File)) G.Has | x -> pr2 "multiple parents or no parents or wrong dir"; pr2_gen (x, dir, m); raise Impossible ) | _ -> (* Dir -> Module -> File *) g +> G.add_node (m, E.Module); g +> G.add_edge ((dir, E.Dir), (m, E.Module)) G.Has; g +> G.add_edge ((m, E.Module), (readable, E.File)) G.Has (*****************************************************************************) (* Uses *) (*****************************************************************************) let extract_uses ~g ~ast ~readable ~dupes = let src = (readable, E.File) in when do module A = Foo , A.foo is actually a reference to Foo.foo let h_module_aliases = Hashtbl.create 101 in let add_edge_if_existing_module s = let s = lookup_module_name h_module_aliases s in let target = (s, E.Module) in if G.has_node target g then g +> G.add_edge (src, target) G.Use else begin g +> G.add_node target; let parent_target = if List.mem s dupes then G.dupe else G.not_found in g +> G.add_edge (parent_target, target) G.Has; g +> G.add_edge (src, target) G.Use; pr2 (spf "PB: lookup fail on module %s in %s" (fst target) readable) end in let visitor = V.mk_visitor { V.default_visitor with todo ? does it cover all use cases of modules ? maybe need * to introduce a kmodule_name_ref helper in the visitor * that does that for us . * todo : if want to give more information on edges , need * to intercept the module name reference at a upper level * like in FunCallSimple . C - s for long_name in ast_ml.ml * to introduce a kmodule_name_ref helper in the visitor * that does that for us. * todo: if want to give more information on edges, need * to intercept the module name reference at a upper level * like in FunCallSimple. C-s for long_name in ast_ml.ml *) V.kitem = (fun (k, _) x -> (match x with | Open (_tok, (_qu, (Name (s,_)))) -> add_edge_if_existing_module s | Module (_, Name (s,_), _, (ModuleName ([], Name (s2,__)))) -> Hashtbl.add h_module_aliases s s2; | _ -> () ); k x ); V.kqualifier = (fun (k,_) qu -> (match qu with | [] -> () | (Name (s, _), _tok)::_rest -> add_edge_if_existing_module s ); k qu ); } in visitor (Program ast); () (*****************************************************************************) (* Main entry point *) (*****************************************************************************) let build ?(verbose=true) root files = let g = G.create () in G.create_initial_hierarchy g; let duplicate_modules = files +> Common.group_by_mapped_key (fun f -> Common2.basename f) +> List.filter (fun (_k, xs) -> List.length xs >= 2) +> List.map (fun (k, xs) -> Module_ml.module_name_of_filename k, xs) in step1 : creating the nodes and ' Has ' edges , the defs if verbose then pr2 "\nstep1: extract defs"; files +> Console.progress ~show:verbose (fun k -> List.iter (fun file -> k(); let readable = Common.readable ~root file in let ast = (* parse file *) () in extract_defs ~g ~duplicate_modules ~ast ~readable ~file; )); : creating the ' Use ' edges , the uses if verbose then pr2 "\nstep2: extract uses"; files +> Console.progress ~show:verbose (fun k -> List.iter (fun file -> k(); let readable = Common.readable ~root file in (* skip files under external/ for now *) if readable =~ ".*external/" || readable =~ "web/.*" then () else begin let ast = parse file in extract_uses ~g ~ast ~readable ~dupes:(List.map fst duplicate_modules); end )); g
null
https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/lang_ml/analyze/graph_code_ml.ml
ocaml
*************************************************************************** Prelude *************************************************************************** *************************************************************************** Types *************************************************************************** *************************************************************************** Helpers *************************************************************************** *************************************************************************** Defs *************************************************************************** * We just create the Dir, File, and Module entities. * See graph_code_cmt.ml if you want Function, Type, etc. Dir -> Module -> File *************************************************************************** Uses *************************************************************************** *************************************************************************** Main entry point *************************************************************************** parse file skip files under external/ for now
* * Copyright ( C ) 2012 Facebook * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation , with the * special exception on linking described in file license.txt . * * This library is distributed in the hope that it will be useful , but * WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file * license.txt for more details . * * Copyright (C) 2012 Facebook * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation, with the * special exception on linking described in file license.txt. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file * license.txt for more details. *) open Common module E = Entity_code module G = Graph_code open Ast_ml module V = Visitor_ml module Ast = Ast_ml * Obsolete file : see graph_code_cmt.ml for a more complete graph . * * Partial graph of dependencies for OCaml using essentially just the * open directives . * * todo ? if give edges a weight , then we need to modulate it depending on * the type of the reference . Two references to a function in another * module is more important than 10 references to some constructors ? * If we do some pattern matching on 20 constructors , is it more * important than two functions calls ? * So Type|Exception > Function|Class|Global > > Constructors|constants ? * * notes : * - ml vs mli ? just get rid of mli ? but one can also want to * care only about mli dependencies , like I did with my ' make ' . * We can introduce a Module entity that is the parent of the * ml and mli file ( this has - graph unify many things :) ) . * * TODO but there is still the issue about where to put the edge * when one module call a function in another module . Do we * link the call to the def in the mli or in the ml ? * * schema : * Root - > Dir - > Module - > File ( .ml ) - > # TODO * * - > File ( .mli ) * - > Dir - > File # no intermediate Module node when there is a dupe * # on a module name ( e.g. for main.ml ) * * - > Dir - > SubDir - > Module - > ... * Obsolete file: see graph_code_cmt.ml for a more complete graph. * * Partial graph of dependencies for OCaml using essentially just the * open directives. * * todo? if give edges a weight, then we need to modulate it depending on * the type of the reference. Two references to a function in another * module is more important than 10 references to some constructors? * If we do some pattern matching on 20 constructors, is it more * important than two functions calls? * So Type|Exception > Function|Class|Global >> Constructors|constants ? * * notes: * - ml vs mli? just get rid of mli? but one can also want to * care only about mli dependencies, like I did with my 'make doti'. * We can introduce a Module entity that is the parent of the * ml and mli file (this has-graph unify many things :) ). * * TODO but there is still the issue about where to put the edge * when one module call a function in another module. Do we * link the call to the def in the mli or in the ml? * * schema: * Root -> Dir -> Module -> File (.ml) -> # TODO * * -> File (.mli) * -> Dir -> File # no intermediate Module node when there is a dupe * # on a module name (e.g. for main.ml) * * -> Dir -> SubDir -> Module -> ... *) let parse file = Common.save_excursion Flag_parsing_ml.show_parsing_error false (fun ()-> Common.save_excursion Flag_parsing_ml.exn_when_lexical_error true (fun ()-> try Parse_ml.parse_program file with Parse_ml.Parse_error _ -> pr2 ("PARSING problem in: " ^ file); [] )) todo : move this code in another file ? module_analysis_ml.ml ? let lookup_module_name h_module_aliases s = try Hashtbl.find h_module_aliases s with Not_found -> s let extract_defs ~g ~duplicate_modules ~ast ~readable ~file = ignore(ast); let dir = Common2.dirname readable in G.create_intermediate_directories_if_not_present g dir; let m = Module_ml.module_name_of_filename file in g +> G.add_node (readable, E.File); match () with | _ when List.mem m (Common2.keys duplicate_modules) -> we could attach to two parents when we are almost sure that * nobody will reference this module ( e.g. because it 's an * entry point ) , but then all the uses in those files would * propagate to two parents , so when we have a dupe , we * do n't create the intermediate Module node . If it 's referenced * somewhere then it will generate a lookup failure . * So just Dir - > File here , no Dir - > Module - > File . * nobody will reference this module (e.g. because it's an * entry point), but then all the uses in those files would * propagate to two parents, so when we have a dupe, we * don't create the intermediate Module node. If it's referenced * somewhere then it will generate a lookup failure. * So just Dir -> File here, no Dir -> Module -> File. *) g +> G.add_edge ((dir, E.Dir), (readable, E.File)) G.Has; (match m with | s when s =~ "Main.*" || s =~ "Demo.*" || s =~ "Test.*" || s =~ "Foo.*" -> () | _ when file =~ ".*external/" -> () | _ -> pr2 (spf "PB: module %s is already present (%s)" m (Common.dump (List.assoc m duplicate_modules))); ) | _ when G.has_node (m, E.Module) g -> (match G.parents (m, E.Module) g with probably because processed .mli or .ml before which created the node | [p] when p =*= (dir, E.Dir) -> g +> G.add_edge ((m, E.Module), (readable, E.File)) G.Has | x -> pr2 "multiple parents or no parents or wrong dir"; pr2_gen (x, dir, m); raise Impossible ) | _ -> g +> G.add_node (m, E.Module); g +> G.add_edge ((dir, E.Dir), (m, E.Module)) G.Has; g +> G.add_edge ((m, E.Module), (readable, E.File)) G.Has let extract_uses ~g ~ast ~readable ~dupes = let src = (readable, E.File) in when do module A = Foo , A.foo is actually a reference to Foo.foo let h_module_aliases = Hashtbl.create 101 in let add_edge_if_existing_module s = let s = lookup_module_name h_module_aliases s in let target = (s, E.Module) in if G.has_node target g then g +> G.add_edge (src, target) G.Use else begin g +> G.add_node target; let parent_target = if List.mem s dupes then G.dupe else G.not_found in g +> G.add_edge (parent_target, target) G.Has; g +> G.add_edge (src, target) G.Use; pr2 (spf "PB: lookup fail on module %s in %s" (fst target) readable) end in let visitor = V.mk_visitor { V.default_visitor with todo ? does it cover all use cases of modules ? maybe need * to introduce a kmodule_name_ref helper in the visitor * that does that for us . * todo : if want to give more information on edges , need * to intercept the module name reference at a upper level * like in FunCallSimple . C - s for long_name in ast_ml.ml * to introduce a kmodule_name_ref helper in the visitor * that does that for us. * todo: if want to give more information on edges, need * to intercept the module name reference at a upper level * like in FunCallSimple. C-s for long_name in ast_ml.ml *) V.kitem = (fun (k, _) x -> (match x with | Open (_tok, (_qu, (Name (s,_)))) -> add_edge_if_existing_module s | Module (_, Name (s,_), _, (ModuleName ([], Name (s2,__)))) -> Hashtbl.add h_module_aliases s s2; | _ -> () ); k x ); V.kqualifier = (fun (k,_) qu -> (match qu with | [] -> () | (Name (s, _), _tok)::_rest -> add_edge_if_existing_module s ); k qu ); } in visitor (Program ast); () let build ?(verbose=true) root files = let g = G.create () in G.create_initial_hierarchy g; let duplicate_modules = files +> Common.group_by_mapped_key (fun f -> Common2.basename f) +> List.filter (fun (_k, xs) -> List.length xs >= 2) +> List.map (fun (k, xs) -> Module_ml.module_name_of_filename k, xs) in step1 : creating the nodes and ' Has ' edges , the defs if verbose then pr2 "\nstep1: extract defs"; files +> Console.progress ~show:verbose (fun k -> List.iter (fun file -> k(); let readable = Common.readable ~root file in extract_defs ~g ~duplicate_modules ~ast ~readable ~file; )); : creating the ' Use ' edges , the uses if verbose then pr2 "\nstep2: extract uses"; files +> Console.progress ~show:verbose (fun k -> List.iter (fun file -> k(); let readable = Common.readable ~root file in if readable =~ ".*external/" || readable =~ "web/.*" then () else begin let ast = parse file in extract_uses ~g ~ast ~readable ~dupes:(List.map fst duplicate_modules); end )); g
1e8ae7363540a91084684f863719b97d9ed5cba4ffe4e11a963a388954a88938
swarmpit/swarmpit
activate.cljs
(ns swarmpit.component.stack.activate (:require [material.icon :as icon] [material.components :as comp] [material.component.form :as form] [material.component.composite :as composite] [swarmpit.component.editor :as editor] [swarmpit.component.state :as state] [swarmpit.component.mixin :as mixin] [swarmpit.component.message :as message] [swarmpit.component.progress :as progress] [swarmpit.component.dialog :as dialog] [swarmpit.component.common :as common] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [swarmpit.url :refer [dispatch!]] [sablono.core :refer-macros [html]] [rum.core :as rum])) (def editor-id "compose") (def doc-compose-link "-started/part3/#your-first-docker-composeyml-file") (defn- form-name [value] (comp/text-field {:label "Name" :fullWidth true :name "name" :key "name" :variant "outlined" :defaultValue value :required true :disabled true :margin "normal" :InputLabelProps {:shrink true}})) (defn- form-editor [value] (comp/text-field {:id editor-id :fullWidth true :className "Swarmpit-codemirror" :name "config-view" :key "config-view" :multiline true :disabled true :required true :margin "normal" :InputLabelProps {:shrink true} :value value})) (defn- deploy-stack-handler [name] (ajax/post (routes/path-for-backend :stack {:name name}) {:params (state/get-value state/form-value-cursor) :state [:processing?] :on-success (fn [{:keys [origin?]}] (when origin? (dispatch! (routes/path-for-frontend :stack-info {:name name}))) (message/info (str "Stack " name " has been deployed."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack deploy failed. " (:error response))))})) (defn- delete-stackfile-handler [name] (ajax/delete (routes/path-for-backend :stack-file {:name name}) {:state [:deleting?] :on-success (fn [_] (dispatch! (routes/path-for-frontend :stack-list)) (message/info (str "Stackfile " name " has been removed."))) :on-error (fn [{:keys [response]}] (message/error (str "Stackfile removal failed. " (:error response))))})) (defn stackfile-handler [name] (ajax/get (routes/path-for-backend :stack-file {:name name}) {:state [:loading?] :on-success (fn [{:keys [response]}] (state/update-value [:spec] (:spec response) state/form-value-cursor))})) (defn- init-form-value [name] (state/set-value {:name name :spec {:compose ""}} state/form-value-cursor)) (def mixin-init-editor {:did-mount (fn [state] (let [editor (editor/yaml editor-id)] (.on editor "change" (fn [cm] (state/update-value [:spec :compose] (-> cm .getValue) state/form-value-cursor)))) state)}) (def mixin-init-form (mixin/init-form (fn [{{:keys [name]} :params}] (init-form-value name) (stackfile-handler name)))) (rum/defc form-edit < rum/reactive mixin-init-editor [{:keys [name spec]} {:keys [processing? deleting?]}] (comp/mui (html [:div.Swarmpit-form (dialog/confirm-dialog #(delete-stackfile-handler name) "Delete stackfile?" "Delete") [:div.Swarmpit-form-context (comp/container {:maxWidth "md" :className "Swarmpit-container"} (comp/card {:className "Swarmpit-form-card Swarmpit-fcard"} (comp/box {:className "Swarmpit-fcard-header"} (comp/typography {:className "Swarmpit-fcard-header-title" :variant "h6" :component "div"} "Activate stack")) (comp/card-content {:className "Swarmpit-fcard-content"} (form-name name) (form-editor (:compose spec))) (comp/card-actions {:className "Swarmpit-fcard-actions"} (composite/progress-button "Deploy" #(deploy-stack-handler name) processing? false {:startIcon (comp/svg {} icon/rocket-path)}) (comp/button {:color "default" :variant "outlined" :startIcon (comp/svg {} icon/trash-path) :disabled processing? :onClick #(state/update-value [:open] true dialog/dialog-cursor)} "Delete"))))]]))) (rum/defc form < rum/reactive mixin-init-form [_] (let [state (state/react state/form-state-cursor) stackfile (state/react state/form-value-cursor)] (progress/form (:loading? state) (form-edit stackfile state))))
null
https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/cljs/swarmpit/component/stack/activate.cljs
clojure
(ns swarmpit.component.stack.activate (:require [material.icon :as icon] [material.components :as comp] [material.component.form :as form] [material.component.composite :as composite] [swarmpit.component.editor :as editor] [swarmpit.component.state :as state] [swarmpit.component.mixin :as mixin] [swarmpit.component.message :as message] [swarmpit.component.progress :as progress] [swarmpit.component.dialog :as dialog] [swarmpit.component.common :as common] [swarmpit.ajax :as ajax] [swarmpit.routes :as routes] [swarmpit.url :refer [dispatch!]] [sablono.core :refer-macros [html]] [rum.core :as rum])) (def editor-id "compose") (def doc-compose-link "-started/part3/#your-first-docker-composeyml-file") (defn- form-name [value] (comp/text-field {:label "Name" :fullWidth true :name "name" :key "name" :variant "outlined" :defaultValue value :required true :disabled true :margin "normal" :InputLabelProps {:shrink true}})) (defn- form-editor [value] (comp/text-field {:id editor-id :fullWidth true :className "Swarmpit-codemirror" :name "config-view" :key "config-view" :multiline true :disabled true :required true :margin "normal" :InputLabelProps {:shrink true} :value value})) (defn- deploy-stack-handler [name] (ajax/post (routes/path-for-backend :stack {:name name}) {:params (state/get-value state/form-value-cursor) :state [:processing?] :on-success (fn [{:keys [origin?]}] (when origin? (dispatch! (routes/path-for-frontend :stack-info {:name name}))) (message/info (str "Stack " name " has been deployed."))) :on-error (fn [{:keys [response]}] (message/error (str "Stack deploy failed. " (:error response))))})) (defn- delete-stackfile-handler [name] (ajax/delete (routes/path-for-backend :stack-file {:name name}) {:state [:deleting?] :on-success (fn [_] (dispatch! (routes/path-for-frontend :stack-list)) (message/info (str "Stackfile " name " has been removed."))) :on-error (fn [{:keys [response]}] (message/error (str "Stackfile removal failed. " (:error response))))})) (defn stackfile-handler [name] (ajax/get (routes/path-for-backend :stack-file {:name name}) {:state [:loading?] :on-success (fn [{:keys [response]}] (state/update-value [:spec] (:spec response) state/form-value-cursor))})) (defn- init-form-value [name] (state/set-value {:name name :spec {:compose ""}} state/form-value-cursor)) (def mixin-init-editor {:did-mount (fn [state] (let [editor (editor/yaml editor-id)] (.on editor "change" (fn [cm] (state/update-value [:spec :compose] (-> cm .getValue) state/form-value-cursor)))) state)}) (def mixin-init-form (mixin/init-form (fn [{{:keys [name]} :params}] (init-form-value name) (stackfile-handler name)))) (rum/defc form-edit < rum/reactive mixin-init-editor [{:keys [name spec]} {:keys [processing? deleting?]}] (comp/mui (html [:div.Swarmpit-form (dialog/confirm-dialog #(delete-stackfile-handler name) "Delete stackfile?" "Delete") [:div.Swarmpit-form-context (comp/container {:maxWidth "md" :className "Swarmpit-container"} (comp/card {:className "Swarmpit-form-card Swarmpit-fcard"} (comp/box {:className "Swarmpit-fcard-header"} (comp/typography {:className "Swarmpit-fcard-header-title" :variant "h6" :component "div"} "Activate stack")) (comp/card-content {:className "Swarmpit-fcard-content"} (form-name name) (form-editor (:compose spec))) (comp/card-actions {:className "Swarmpit-fcard-actions"} (composite/progress-button "Deploy" #(deploy-stack-handler name) processing? false {:startIcon (comp/svg {} icon/rocket-path)}) (comp/button {:color "default" :variant "outlined" :startIcon (comp/svg {} icon/trash-path) :disabled processing? :onClick #(state/update-value [:open] true dialog/dialog-cursor)} "Delete"))))]]))) (rum/defc form < rum/reactive mixin-init-form [_] (let [state (state/react state/form-state-cursor) stackfile (state/react state/form-value-cursor)] (progress/form (:loading? state) (form-edit stackfile state))))
1a7c6cf228fbbb99f0e706426fe2395416ee3c00b9768be45ebc449589b12c18
elastic/eui-cljs
icon_index_edit.cljs
(ns eui.icon-index-edit (:require ["@elastic/eui/lib/components/icon/assets/index_edit.js" :as eui])) (def indexEdit eui/icon)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/icon_index_edit.cljs
clojure
(ns eui.icon-index-edit (:require ["@elastic/eui/lib/components/icon/assets/index_edit.js" :as eui])) (def indexEdit eui/icon)
55953bdffb11065bcbde6db6f03588fa95ac85dbf6e4dac0543affeea82f6aed
sibylfs/sibylfs_src
fs_test_util.ml
(****************************************************************************) Copyright ( c ) 2013 , 2014 , 2015 , , , , ( as part of the SibylFS project ) (* *) (* Permission to use, copy, modify, and/or 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. *) (* *) Meta : (* - Headers maintained using headache. *) (* - License source: *) (****************************************************************************) let rec split acc str char = try let spc = String.index str char in let next = String.sub str 0 spc in let str = String.sub str (spc+1) ((String.length str) - spc - 1) in split (next::acc) str char with Not_found -> List.rev (str::acc)
null
https://raw.githubusercontent.com/sibylfs/sibylfs_src/30675bc3b91e73f7133d0c30f18857bb1f4df8fa/fs_test/lib/fs_test_util.ml
ocaml
************************************************************************** Permission to use, copy, modify, and/or 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. 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 PERFORMANCE OF THIS SOFTWARE. - Headers maintained using headache. - License source: **************************************************************************
Copyright ( c ) 2013 , 2014 , 2015 , , , , ( as part of the SibylFS project ) THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR Meta : let rec split acc str char = try let spc = String.index str char in let next = String.sub str 0 spc in let str = String.sub str (spc+1) ((String.length str) - spc - 1) in split (next::acc) str char with Not_found -> List.rev (str::acc)
05e274788adfac1796865335d4ef8a50752616853dd4db3f4fd22bcf1e4d427a
bugarela/GADTInference
e2.hs
data T a where {TInt :: (a ~ Bool) => Int -> T a; TAny :: T a} e = \x -> case x of {TInt n -> (n > 0);TAny -> True} -- T t -> Bool
null
https://raw.githubusercontent.com/bugarela/GADTInference/dd179f6df2cd76055c25c33da3187a60815688d1/examples/inferred/e2.hs
haskell
T t -> Bool
data T a where {TInt :: (a ~ Bool) => Int -> T a; TAny :: T a} e = \x -> case x of {TInt n -> (n > 0);TAny -> True}
566e0c9dd3551418218ca9e6507d18d50993d14d7a5f00c3215ad7859b990f4b
tonyg/kali-scheme
memory2.scm
Copyright ( c ) 1993 , 1994 and . See file COPYING . ; An implementation of Pre-Scheme's memory interface that can detect some ; stray reads and writes. It has numerous limitiations: ; Allocations are always on page boundaries. ; No more than 16 megabytes can be allocated at once. More than 32 or 64 or so allocations result in addresses being ; bignums (dealloctions have no effect on this). ; ; Memory is represented as a vector of byte-vectors, with each byte-vector representing a 16 - megabyte page . Allocations are always made on page ; boundaries, so the byte-vectors only need be as large as the allocated ; areas. Pages are never re-used. Memory is one big vector , with markers at beginning and end of free blocks and allocationg by by address ordered first fit . ; Strings and things end up as bignums... (define *memory* (make-vector 0 0)) (define-record-type address :address (make-address index) address? (index address-index)) (define-record-discloser :address (lambda (addr) (list 'address (address-index addr)))) We add 100000000 to addresses to make them (define address-offset 100000000) (define (address->integer addr) (+ (address-index addr) address-offset)) (define (integer->address int) (make-address (- int address-offset))) (define (word-ref addr) (if (address? addr) (let ((index (address-index addr))) (if (and (= 0 (vector-ref *memory* (address-index addr))) (define (word-ref addr) (vector-ref *memory* (address-index addr))) (define *memory* (make-vector 16 #f)) ; vector of pages (define log-max-size 24) ; log of page size (define address-shift (- log-max-size)) ; turns addresses into page indices (define max-size (arithmetic-shift 1 log-max-size)) ; page size (define address-mask ; mask to get address within page (- (arithmetic-shift 1 log-max-size) 1)) (define *next-index* 0) ; next available page (define (reinitialize-memory) (set! *memory* (make-vector 16 #f)) (set! *next-index* 0)) ; Extend the page vector if necessary, and then make a page of the ; appropriate size. (define (allocate-memory size) (cond ((> size max-size) #f) ; the null pointer (else (if (>= *next-index* (vector-length *memory*)) (let ((new (make-vector (* 2 (vector-length *memory*))))) (do ((i 0 (+ i 1))) ((>= i (vector-length *memory*))) (vector-set! new i (vector-ref *memory* i))) (set! *memory* new))) (let ((index *next-index*)) (set! *next-index* (+ *next-index* 1)) (vector-set! *memory* index (make-code-vector size 0)) (arithmetic-shift index log-max-size))))) ; Turning an address into a page or page index (define (address->vector address) (vector-ref *memory* (arithmetic-shift address address-shift))) (define (address->vector-index address) (bitwise-and address address-mask)) Throw away the page containing ADDRESS , which must be the first address in ; that page, (define (deallocate-memory address) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (if (and vector (= byte-address 0)) (vector-set! *memory* (arithmetic-shift address address-shift) #f) (error "bad deallocation address" address)))) ; Various ways of accessing memory (define (unsigned-byte-ref address) (code-vector-ref (address->vector address) (address->vector-index address))) (define (signed-code-vector-ref bvec i) (let ((x (code-vector-ref bvec i))) (if (< x 128) x (bitwise-ior x -128)))) (define (word-ref address) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (if (not (= 0 (bitwise-and byte-address 3))) (error "unaligned address error" address) (+ (+ (arithmetic-shift (signed-code-vector-ref vector byte-address) 24) (arithmetic-shift (code-vector-ref vector (+ byte-address 1)) 16)) (+ (arithmetic-shift (code-vector-ref vector (+ byte-address 2)) 8) (code-vector-ref vector (+ byte-address 3))))))) (define (unsigned-byte-set! address value) (code-vector-set! (address->vector address) (address->vector-index address) (bitwise-and 255 value))) (define (word-set! address value) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (if (not (= 0 (bitwise-and byte-address 3))) (error "unaligned address error" address)) (code-vector-set! vector byte-address (bitwise-and 255 (arithmetic-shift value -24))) (code-vector-set! vector (+ byte-address 1) (bitwise-and 255 (arithmetic-shift value -16))) (code-vector-set! vector (+ byte-address 2) (bitwise-and 255 (arithmetic-shift value -8))) (code-vector-set! vector (+ byte-address 3) (bitwise-and 255 value)))) ; Block I/O procedures. (define (write-block port address count) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (do ((i 0 (+ i 1))) ((>= i count)) (write-char (ascii->char (code-vector-ref vector (+ i byte-address))) port)) (values count (enum errors no-errors)))) (define (read-block port address count) (cond ((not (char-ready? port)) (values 0 #f (enum errors no-errors))) ((eof-object? (s-peek-char port)) (values 0 #t (enum errors no-errors))) (else (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (let loop ((i 0)) (if (or (= i count) (not (char-ready? port))) (values i #f (enum errors no-errors)) (let ((c (s-read-char port))) (cond ((eof-object? c) (values i #f (enum errors no-errors))) (else (code-vector-set! vector (+ i byte-address) (char->ascii c)) (loop (+ i 1))))))))))) (define (copy-memory! from to count) (let ((from-vector (address->vector from)) (from-address (address->vector-index from)) (to-vector (address->vector to)) (to-address (address->vector-index to))) (do ((i 0 (+ i 1))) ((>= i count)) (code-vector-set! to-vector (+ i to-address) (code-vector-ref from-vector (+ i from-address)))))) (define (memory-equal? from to count) (let ((from-vector (address->vector from)) (from-address (address->vector-index from)) (to-vector (address->vector to)) (to-address (address->vector-index to))) (let loop ((i 0)) (cond ((>= i count) #t) ((= (code-vector-ref to-vector (+ i to-address)) (code-vector-ref from-vector (+ i from-address))) (loop (+ i 1))) (else #f))))) ; Turn the LENGTH bytes starting from ADDRESS into a string. (define (char-pointer->string address length) (let ((vector (address->vector address)) (byte-address (address->vector-index address)) (string (make-string length))) (do ((i 0 (+ i 1))) ((= i length)) (string-set! string i (ascii->char (code-vector-ref vector (+ byte-address i))))) string)) ; Turn the bytes from ADDRESS to the next nul (byte equal to 0) into a ; string. This is a trivial operation in C. (define (char-pointer->nul-terminated-string address) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (char-pointer->string address (index-of-first-nul vector byte-address)))) (define (index-of-first-nul vector address) (let loop ((i address)) (cond ((= i (code-vector-length vector)) (error "CHAR-POINTER->STRING called on pointer with no nul termination")) ((= 0 (code-vector-ref vector i)) (- i address)) (else (loop (+ i 1)))))) ; We really need these to work. (define address+ +) (define address- -) (define address-difference -) (define address->integer identity) (define integer->address identity) (define ...)
null
https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/prescheme/memory2.scm
scheme
An implementation of Pre-Scheme's memory interface that can detect some stray reads and writes. It has numerous limitiations: Allocations are always on page boundaries. No more than 16 megabytes can be allocated at once. bignums (dealloctions have no effect on this). Memory is represented as a vector of byte-vectors, with each byte-vector boundaries, so the byte-vectors only need be as large as the allocated areas. Pages are never re-used. Strings and things end up as bignums... vector of pages log of page size turns addresses into page indices page size mask to get address within page next available page Extend the page vector if necessary, and then make a page of the appropriate size. the null pointer Turning an address into a page or page index that page, Various ways of accessing memory Block I/O procedures. Turn the LENGTH bytes starting from ADDRESS into a string. Turn the bytes from ADDRESS to the next nul (byte equal to 0) into a string. This is a trivial operation in C. We really need these to work.
Copyright ( c ) 1993 , 1994 and . See file COPYING . More than 32 or 64 or so allocations result in addresses being representing a 16 - megabyte page . Allocations are always made on page Memory is one big vector , with markers at beginning and end of free blocks and allocationg by by address ordered first fit . (define *memory* (make-vector 0 0)) (define-record-type address :address (make-address index) address? (index address-index)) (define-record-discloser :address (lambda (addr) (list 'address (address-index addr)))) We add 100000000 to addresses to make them (define address-offset 100000000) (define (address->integer addr) (+ (address-index addr) address-offset)) (define (integer->address int) (make-address (- int address-offset))) (define (word-ref addr) (if (address? addr) (let ((index (address-index addr))) (if (and (= 0 (vector-ref *memory* (address-index addr))) (define (word-ref addr) (vector-ref *memory* (address-index addr))) (- (arithmetic-shift 1 log-max-size) 1)) (define (reinitialize-memory) (set! *memory* (make-vector 16 #f)) (set! *next-index* 0)) (define (allocate-memory size) (cond ((> size max-size) (else (if (>= *next-index* (vector-length *memory*)) (let ((new (make-vector (* 2 (vector-length *memory*))))) (do ((i 0 (+ i 1))) ((>= i (vector-length *memory*))) (vector-set! new i (vector-ref *memory* i))) (set! *memory* new))) (let ((index *next-index*)) (set! *next-index* (+ *next-index* 1)) (vector-set! *memory* index (make-code-vector size 0)) (arithmetic-shift index log-max-size))))) (define (address->vector address) (vector-ref *memory* (arithmetic-shift address address-shift))) (define (address->vector-index address) (bitwise-and address address-mask)) Throw away the page containing ADDRESS , which must be the first address in (define (deallocate-memory address) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (if (and vector (= byte-address 0)) (vector-set! *memory* (arithmetic-shift address address-shift) #f) (error "bad deallocation address" address)))) (define (unsigned-byte-ref address) (code-vector-ref (address->vector address) (address->vector-index address))) (define (signed-code-vector-ref bvec i) (let ((x (code-vector-ref bvec i))) (if (< x 128) x (bitwise-ior x -128)))) (define (word-ref address) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (if (not (= 0 (bitwise-and byte-address 3))) (error "unaligned address error" address) (+ (+ (arithmetic-shift (signed-code-vector-ref vector byte-address) 24) (arithmetic-shift (code-vector-ref vector (+ byte-address 1)) 16)) (+ (arithmetic-shift (code-vector-ref vector (+ byte-address 2)) 8) (code-vector-ref vector (+ byte-address 3))))))) (define (unsigned-byte-set! address value) (code-vector-set! (address->vector address) (address->vector-index address) (bitwise-and 255 value))) (define (word-set! address value) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (if (not (= 0 (bitwise-and byte-address 3))) (error "unaligned address error" address)) (code-vector-set! vector byte-address (bitwise-and 255 (arithmetic-shift value -24))) (code-vector-set! vector (+ byte-address 1) (bitwise-and 255 (arithmetic-shift value -16))) (code-vector-set! vector (+ byte-address 2) (bitwise-and 255 (arithmetic-shift value -8))) (code-vector-set! vector (+ byte-address 3) (bitwise-and 255 value)))) (define (write-block port address count) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (do ((i 0 (+ i 1))) ((>= i count)) (write-char (ascii->char (code-vector-ref vector (+ i byte-address))) port)) (values count (enum errors no-errors)))) (define (read-block port address count) (cond ((not (char-ready? port)) (values 0 #f (enum errors no-errors))) ((eof-object? (s-peek-char port)) (values 0 #t (enum errors no-errors))) (else (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (let loop ((i 0)) (if (or (= i count) (not (char-ready? port))) (values i #f (enum errors no-errors)) (let ((c (s-read-char port))) (cond ((eof-object? c) (values i #f (enum errors no-errors))) (else (code-vector-set! vector (+ i byte-address) (char->ascii c)) (loop (+ i 1))))))))))) (define (copy-memory! from to count) (let ((from-vector (address->vector from)) (from-address (address->vector-index from)) (to-vector (address->vector to)) (to-address (address->vector-index to))) (do ((i 0 (+ i 1))) ((>= i count)) (code-vector-set! to-vector (+ i to-address) (code-vector-ref from-vector (+ i from-address)))))) (define (memory-equal? from to count) (let ((from-vector (address->vector from)) (from-address (address->vector-index from)) (to-vector (address->vector to)) (to-address (address->vector-index to))) (let loop ((i 0)) (cond ((>= i count) #t) ((= (code-vector-ref to-vector (+ i to-address)) (code-vector-ref from-vector (+ i from-address))) (loop (+ i 1))) (else #f))))) (define (char-pointer->string address length) (let ((vector (address->vector address)) (byte-address (address->vector-index address)) (string (make-string length))) (do ((i 0 (+ i 1))) ((= i length)) (string-set! string i (ascii->char (code-vector-ref vector (+ byte-address i))))) string)) (define (char-pointer->nul-terminated-string address) (let ((vector (address->vector address)) (byte-address (address->vector-index address))) (char-pointer->string address (index-of-first-nul vector byte-address)))) (define (index-of-first-nul vector address) (let loop ((i address)) (cond ((= i (code-vector-length vector)) (error "CHAR-POINTER->STRING called on pointer with no nul termination")) ((= 0 (code-vector-ref vector i)) (- i address)) (else (loop (+ i 1)))))) (define address+ +) (define address- -) (define address-difference -) (define address->integer identity) (define integer->address identity) (define ...)
0ff4e82a11d283c56b4b33771476e79dca78dabaf3fdc20beb04e1db49d8b456
csabahruska/jhc-components
Supply.hs
module Fixer.Supply( Supply(), newSupply, supplyReadValues, sValue, readSValue, supplyValue ) where import Control.Monad.Trans import Data.IORef import Data.Typeable import Fixer.Fixer import qualified Data.Map as Map -- maps b's to values of a's, creating them as needed. data Supply b a = Supply Fixer {-# UNPACK #-} !(IORef (Map.Map b (Value a))) deriving(Typeable) newSupply :: MonadIO m => Fixer -> m (Supply b a) newSupply fixer = liftIO $ do ref <- newIORef Map.empty return $ Supply fixer ref supplyValue :: (MonadIO m, Ord b, Fixable a) => Supply b a -> b -> m (Value a) supplyValue (Supply fixer ref) b = liftIO $ do mp <- readIORef ref case Map.lookup b mp of Just v -> return v Nothing -> do v <- newValue fixer bottom modifyIORef ref (Map.insert b v) return v sValue :: (Ord b, Fixable a) => Supply b a -> b -> (Value a) sValue s b = ioValue (supplyValue s b) supplyReadValues :: (Fixable a,MonadIO m) => Supply b a -> m [(b,a)] supplyReadValues (Supply _fixer ref) = liftIO $ do mp <- readIORef ref flip mapM (Map.toList mp) $ \ (b,va) -> do a <- readValue va return (b,a) readSValue :: (MonadIO m, Ord b, Fixable a) => Supply b a -> b -> m a readSValue s b = do v <- supplyValue s b readValue v
null
https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/jhc-common/src/Fixer/Supply.hs
haskell
maps b's to values of a's, creating them as needed. # UNPACK #
module Fixer.Supply( Supply(), newSupply, supplyReadValues, sValue, readSValue, supplyValue ) where import Control.Monad.Trans import Data.IORef import Data.Typeable import Fixer.Fixer import qualified Data.Map as Map deriving(Typeable) newSupply :: MonadIO m => Fixer -> m (Supply b a) newSupply fixer = liftIO $ do ref <- newIORef Map.empty return $ Supply fixer ref supplyValue :: (MonadIO m, Ord b, Fixable a) => Supply b a -> b -> m (Value a) supplyValue (Supply fixer ref) b = liftIO $ do mp <- readIORef ref case Map.lookup b mp of Just v -> return v Nothing -> do v <- newValue fixer bottom modifyIORef ref (Map.insert b v) return v sValue :: (Ord b, Fixable a) => Supply b a -> b -> (Value a) sValue s b = ioValue (supplyValue s b) supplyReadValues :: (Fixable a,MonadIO m) => Supply b a -> m [(b,a)] supplyReadValues (Supply _fixer ref) = liftIO $ do mp <- readIORef ref flip mapM (Map.toList mp) $ \ (b,va) -> do a <- readValue va return (b,a) readSValue :: (MonadIO m, Ord b, Fixable a) => Supply b a -> b -> m a readSValue s b = do v <- supplyValue s b readValue v
d8d7260d4710ebbc878ad03dde2b77efbe4535dcd48029943afd2dd758a48443
cedlemo/OCaml-GObject-Introspection
Property_info.mli
* Copyright 2017 - 2019 , * This file is part of OCaml - GObject - Introspection . * * OCaml - GObject - Introspection 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 * any later version . * * OCaml - GObject - Introspection is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with . If not , see < / > . * Copyright 2017-2019 Cedric LE MOIGNE, * This file is part of OCaml-GObject-Introspection. * * OCaml-GObject-Introspection 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 * any later version. * * OCaml-GObject-Introspection 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 OCaml-GObject-Introspection. If not, see </>. *) (** Property_info — Struct representing a property *) open Ctypes * Property_info represents a property . A property belongs to either a Object_info or a Interface_info . Object_info or a Interface_info.*) type t val propertyinfo : t structure typ * Obtain the ownership transfer for this property . See for more information about transfer values . information about transfer values. *) val get_ownership_transfer: t structure ptr -> Bindings.Arg_info.transfer (** Obtain the type information for the property info . *) val get_type: t structure ptr -> Type_info.t structure ptr (** Obtain the flags for this property info. See GParamFlags for more information about possible flag values. *) val get_flags: t structure ptr -> Bindings.GParam.flags list * Just cast base info to property info . val cast_from_baseinfo: Base_info.t structure ptr -> t structure ptr * Just cast property info to base info val cast_to_baseinfo: t structure ptr -> Base_info.t structure ptr (** Add unref of the C underlying structure whith Gc.finalise. *) val add_unref_finaliser: t structure ptr -> t structure ptr (** Return a Property_info.t from a Base_info.t, the underlying C structure ref count is increased and the value is Gc.finalis"ed" with Base_info.baseinfo_unref. *) val from_baseinfo: Base_info.t structure ptr -> t structure ptr (** Return a Base_info.t from a Property_info, the underlying C structure ref count is increased and the value is Gc.finalis"ed" with Base_info.baseinfo_unref. *) val to_baseinfo: t structure ptr -> Base_info.t structure ptr
null
https://raw.githubusercontent.com/cedlemo/OCaml-GObject-Introspection/261c76d9e5d90f706edff1121a63bf5eb611399b/lib/Property_info.mli
ocaml
* Property_info — Struct representing a property * Obtain the type information for the property info . * Obtain the flags for this property info. See GParamFlags for more information about possible flag values. * Add unref of the C underlying structure whith Gc.finalise. * Return a Property_info.t from a Base_info.t, the underlying C structure ref count is increased and the value is Gc.finalis"ed" with Base_info.baseinfo_unref. * Return a Base_info.t from a Property_info, the underlying C structure ref count is increased and the value is Gc.finalis"ed" with Base_info.baseinfo_unref.
* Copyright 2017 - 2019 , * This file is part of OCaml - GObject - Introspection . * * OCaml - GObject - Introspection 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 * any later version . * * OCaml - GObject - Introspection is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with . If not , see < / > . * Copyright 2017-2019 Cedric LE MOIGNE, * This file is part of OCaml-GObject-Introspection. * * OCaml-GObject-Introspection 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 * any later version. * * OCaml-GObject-Introspection 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 OCaml-GObject-Introspection. If not, see </>. *) open Ctypes * Property_info represents a property . A property belongs to either a Object_info or a Interface_info . Object_info or a Interface_info.*) type t val propertyinfo : t structure typ * Obtain the ownership transfer for this property . See for more information about transfer values . information about transfer values. *) val get_ownership_transfer: t structure ptr -> Bindings.Arg_info.transfer val get_type: t structure ptr -> Type_info.t structure ptr val get_flags: t structure ptr -> Bindings.GParam.flags list * Just cast base info to property info . val cast_from_baseinfo: Base_info.t structure ptr -> t structure ptr * Just cast property info to base info val cast_to_baseinfo: t structure ptr -> Base_info.t structure ptr val add_unref_finaliser: t structure ptr -> t structure ptr val from_baseinfo: Base_info.t structure ptr -> t structure ptr val to_baseinfo: t structure ptr -> Base_info.t structure ptr
8f1493688344474ee6e179ecdceba81ea0235bbe36141bdd99ad9ff8eaf903ed
onedata/op-worker
qos_entry_audit_log.erl
%%%------------------------------------------------------------------- @author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%% @end %%%------------------------------------------------------------------- %%% @doc This module is responsible for storing audit log of QoS operations on files . The audit log stores logs concerning all files affected by a specific QoS entry . %%% @end %%%------------------------------------------------------------------- -module(qos_entry_audit_log). -author("Michal Stanisz"). -include_lib("ctool/include/errors.hrl"). -include_lib("ctool/include/logging.hrl"). -include_lib("cluster_worker/include/audit_log.hrl"). -include_lib("cluster_worker/include/modules/datastore/infinite_log.hrl"). %% API -export([ report_synchronization_started/3, report_file_synchronized/3, report_file_synchronization_skipped/4, report_file_synchronization_failed/4, destroy/1, browse_content/2 ]). -type id() :: qos_entry:id(). -type skip_reason() :: file_deleted_locally | reconciliation_already_in_progress. -export_type([id/0]). -define(LOG_OPTS, #{ size_pruning_threshold => op_worker:get_env(qos_entry_audit_log_max_size, 10000) defaults are used for age pruning and expiration ; @see audit_log.erl }). %%%=================================================================== %%% API %%%=================================================================== -spec report_synchronization_started(id(), file_id:file_guid(), file_meta:path()) -> ok | {error, term()}. report_synchronization_started(Id, FileGuid, FilePath) -> audit_log:append(Id, ?LOG_OPTS, #audit_log_append_request{ severity = ?INFO_AUDIT_LOG_SEVERITY, content = #{ <<"status">> => <<"scheduled">>, <<"fileId">> => file_guid_to_object_id(FileGuid), <<"description">> => <<"Remote replica differs, reconciliation started.">>, <<"path">> => FilePath } }). -spec report_file_synchronized(id(), file_id:file_guid(), file_meta:path()) -> ok | {error, term()}. report_file_synchronized(Id, FileGuid, FilePath) -> audit_log:append(Id, ?LOG_OPTS, #audit_log_append_request{ severity = ?INFO_AUDIT_LOG_SEVERITY, content = #{ <<"status">> => <<"completed">>, <<"fileId">> => file_guid_to_object_id(FileGuid), <<"description">> => <<"Local replica reconciled.">>, <<"path">> => FilePath } }). -spec report_file_synchronization_skipped(id(), file_id:file_guid(), file_meta:path(), skip_reason()) -> ok | {error, term()}. report_file_synchronization_skipped(Id, FileGuid, FilePath, Reason) -> audit_log:append(Id, ?LOG_OPTS, #audit_log_append_request{ severity = ?INFO_AUDIT_LOG_SEVERITY, content = #{ <<"status">> => <<"skipped">>, <<"fileId">> => file_guid_to_object_id(FileGuid), <<"description">> => skip_reason_to_description(Reason), <<"path">> => FilePath } }). -spec report_file_synchronization_failed(id(), file_id:file_guid(), file_meta:path(), {error, term()}) -> ok | {error, term()}. report_file_synchronization_failed(Id, FileGuid, FilePath, Error) -> ErrorJson = errors:to_json(Error), audit_log:append(Id, ?LOG_OPTS, #audit_log_append_request{ severity = ?ERROR_AUDIT_LOG_SEVERITY, content = #{ <<"status">> => <<"failed">>, <<"fileId">> => file_guid_to_object_id(FileGuid), <<"description">> => str_utils:format_bin( "Failed to reconcile local replica: ~s", [maps:get(<<"description">>, ErrorJson)] ), <<"reason">> => ErrorJson, <<"path">> => FilePath } }). -spec destroy(id()) -> ok | {error, term()}. destroy(Id) -> audit_log:delete(Id). -spec browse_content(id(), audit_log_browse_opts:opts()) -> {ok, audit_log:browse_result()} | errors:error(). browse_content(Id, Opts) -> audit_log:browse(Id, Opts). %%%=================================================================== Internal functions %%%=================================================================== @private -spec file_guid_to_object_id(file_id:file_guid()) -> file_id:objectid(). file_guid_to_object_id(FileGuid) -> {ok, ObjectId} = file_id:guid_to_objectid(FileGuid), ObjectId. @private -spec skip_reason_to_description(skip_reason()) -> binary(). skip_reason_to_description(file_deleted_locally) -> <<"Remote replica differs, ignoring since the file has been deleted locally.">>; skip_reason_to_description(reconciliation_already_in_progress) -> <<"Remote replica differs, reconciliation already in progress.">>.
null
https://raw.githubusercontent.com/onedata/op-worker/34607258e1b3fca71a1b0da2a0bc5f0134fe878e/src/modules/datastore/models/qos/qos_entry_audit_log.erl
erlang
------------------------------------------------------------------- @end ------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API =================================================================== API =================================================================== =================================================================== ===================================================================
@author ( C ) 2021 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . This module is responsible for storing audit log of QoS operations on files . The audit log stores logs concerning all files affected by a specific QoS entry . -module(qos_entry_audit_log). -author("Michal Stanisz"). -include_lib("ctool/include/errors.hrl"). -include_lib("ctool/include/logging.hrl"). -include_lib("cluster_worker/include/audit_log.hrl"). -include_lib("cluster_worker/include/modules/datastore/infinite_log.hrl"). -export([ report_synchronization_started/3, report_file_synchronized/3, report_file_synchronization_skipped/4, report_file_synchronization_failed/4, destroy/1, browse_content/2 ]). -type id() :: qos_entry:id(). -type skip_reason() :: file_deleted_locally | reconciliation_already_in_progress. -export_type([id/0]). -define(LOG_OPTS, #{ size_pruning_threshold => op_worker:get_env(qos_entry_audit_log_max_size, 10000) defaults are used for age pruning and expiration ; @see audit_log.erl }). -spec report_synchronization_started(id(), file_id:file_guid(), file_meta:path()) -> ok | {error, term()}. report_synchronization_started(Id, FileGuid, FilePath) -> audit_log:append(Id, ?LOG_OPTS, #audit_log_append_request{ severity = ?INFO_AUDIT_LOG_SEVERITY, content = #{ <<"status">> => <<"scheduled">>, <<"fileId">> => file_guid_to_object_id(FileGuid), <<"description">> => <<"Remote replica differs, reconciliation started.">>, <<"path">> => FilePath } }). -spec report_file_synchronized(id(), file_id:file_guid(), file_meta:path()) -> ok | {error, term()}. report_file_synchronized(Id, FileGuid, FilePath) -> audit_log:append(Id, ?LOG_OPTS, #audit_log_append_request{ severity = ?INFO_AUDIT_LOG_SEVERITY, content = #{ <<"status">> => <<"completed">>, <<"fileId">> => file_guid_to_object_id(FileGuid), <<"description">> => <<"Local replica reconciled.">>, <<"path">> => FilePath } }). -spec report_file_synchronization_skipped(id(), file_id:file_guid(), file_meta:path(), skip_reason()) -> ok | {error, term()}. report_file_synchronization_skipped(Id, FileGuid, FilePath, Reason) -> audit_log:append(Id, ?LOG_OPTS, #audit_log_append_request{ severity = ?INFO_AUDIT_LOG_SEVERITY, content = #{ <<"status">> => <<"skipped">>, <<"fileId">> => file_guid_to_object_id(FileGuid), <<"description">> => skip_reason_to_description(Reason), <<"path">> => FilePath } }). -spec report_file_synchronization_failed(id(), file_id:file_guid(), file_meta:path(), {error, term()}) -> ok | {error, term()}. report_file_synchronization_failed(Id, FileGuid, FilePath, Error) -> ErrorJson = errors:to_json(Error), audit_log:append(Id, ?LOG_OPTS, #audit_log_append_request{ severity = ?ERROR_AUDIT_LOG_SEVERITY, content = #{ <<"status">> => <<"failed">>, <<"fileId">> => file_guid_to_object_id(FileGuid), <<"description">> => str_utils:format_bin( "Failed to reconcile local replica: ~s", [maps:get(<<"description">>, ErrorJson)] ), <<"reason">> => ErrorJson, <<"path">> => FilePath } }). -spec destroy(id()) -> ok | {error, term()}. destroy(Id) -> audit_log:delete(Id). -spec browse_content(id(), audit_log_browse_opts:opts()) -> {ok, audit_log:browse_result()} | errors:error(). browse_content(Id, Opts) -> audit_log:browse(Id, Opts). Internal functions @private -spec file_guid_to_object_id(file_id:file_guid()) -> file_id:objectid(). file_guid_to_object_id(FileGuid) -> {ok, ObjectId} = file_id:guid_to_objectid(FileGuid), ObjectId. @private -spec skip_reason_to_description(skip_reason()) -> binary(). skip_reason_to_description(file_deleted_locally) -> <<"Remote replica differs, ignoring since the file has been deleted locally.">>; skip_reason_to_description(reconciliation_already_in_progress) -> <<"Remote replica differs, reconciliation already in progress.">>.
7c303bc72b6bcb492856f02d5a8d7a72098580cc10612d3c1077420588ff5772
metosin/reitit
middleware.clj
(ns example.middleware (:require [muuntaja.middleware] [ring.middleware.params] [reitit.middleware :as middleware] [reitit.ring.coercion :as rrc])) unlift Middleware Record into vanilla Ring middleware (defn wrap-coercion [handler resource] (middleware/chain [rrc/coerce-exceptions-middleware rrc/coerce-request-middleware rrc/coerce-response-middleware] handler resource))
null
https://raw.githubusercontent.com/metosin/reitit/1ab075bd353966636f154ac36ae9b7990efeb008/examples/just-coercion-with-ring/src/example/middleware.clj
clojure
(ns example.middleware (:require [muuntaja.middleware] [ring.middleware.params] [reitit.middleware :as middleware] [reitit.ring.coercion :as rrc])) unlift Middleware Record into vanilla Ring middleware (defn wrap-coercion [handler resource] (middleware/chain [rrc/coerce-exceptions-middleware rrc/coerce-request-middleware rrc/coerce-response-middleware] handler resource))
da364c7672e5c6900e4b1ede79b71ea0adfa1c63213273c93f6e9cfb6512da9e
arsalan0c/cdp-hs
CDP.hs
# LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # module CDP ( Error (..) , ProtocolError (..) , EPBrowserVersion (..) , EPAllTargets (..) , EPCurrentProtocol (..) , EPOpenNewTab (..) , EPActivateTarget (..) , EPCloseTarget (..) , EPFrontend (..) , Endpoint , EndpointResponse , SomeEndpoint (..) , BrowserVersion (..) , TargetInfo (..) , TargetId , parseUri , fromSomeEndpoint , endpoint , connectToTab , ClientApp , Handle , Config(..) , runClient , Subscription , subscribe , subscribeForSession , unsubscribe , Command (..) , SomeCommand (..) , Promise (..) , fromSomeCommand , readPromise , sendCommand , sendCommandForSession , sendCommandWait , sendCommandForSessionWait , module CDP.Domains ) where import Data.Proxy (Proxy) import CDP.Domains import CDP.Runtime
null
https://raw.githubusercontent.com/arsalan0c/cdp-hs/7aca1d366ad63d81d5d681220e0637a8551034de/src/CDP.hs
haskell
# LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # module CDP ( Error (..) , ProtocolError (..) , EPBrowserVersion (..) , EPAllTargets (..) , EPCurrentProtocol (..) , EPOpenNewTab (..) , EPActivateTarget (..) , EPCloseTarget (..) , EPFrontend (..) , Endpoint , EndpointResponse , SomeEndpoint (..) , BrowserVersion (..) , TargetInfo (..) , TargetId , parseUri , fromSomeEndpoint , endpoint , connectToTab , ClientApp , Handle , Config(..) , runClient , Subscription , subscribe , subscribeForSession , unsubscribe , Command (..) , SomeCommand (..) , Promise (..) , fromSomeCommand , readPromise , sendCommand , sendCommandForSession , sendCommandWait , sendCommandForSessionWait , module CDP.Domains ) where import Data.Proxy (Proxy) import CDP.Domains import CDP.Runtime
ed76be40b70b7534d4769c0927014a7fc8c5a63e4997db53da1fcb4d6ec1180e
mikeizbicki/HLearn
example0003-classification.hs
# LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE RebindableSyntax # # LANGUAGE DataKinds # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE RankNTypes #-} import SubHask import SubHask.Algebra.Array import SubHask.Algebra.Vector import SubHask.Algebra.Container import HLearn.Data.LoadData import HLearn.Classifiers.Linear import HLearn.History import qualified Prelude as P import System.IO -------------------------------------------------------------------------------- main = do xs :: BArray (Labeled' (SVector "dyn" Double) (Lexical String)) <- loadCSVLabeled' 0 "datasets/csv/uci/wine.csv" < - loadCSVLabeled ' 8 " datasets / csv / uci / pima - indians - diabetes.csv " glm <- runHistory ( (displayFilter (maxReportLevel 2) dispIteration) + summaryTable ) $ trainLogisticRegression 1e-3 xs putStrLn $ "loss_01 = "++show (validate loss_01 (toList xs) glm) putStrLn $ "loss_logistic = "++show (validate loss_logistic (toList xs) glm) putStrLn $ "loss_hinge = "++show (validate loss_hinge (toList xs) glm) -- putStrLn "" print $ show $ weights glm!Lexical " 1 " print $ show $ weights glm!Lexical " 2 " print $ show $ weights glm!Lexical " 3 " putStrLn "done."
null
https://raw.githubusercontent.com/mikeizbicki/HLearn/c6c0f5e7593be3867f20c56c79b998e7d7ded9fc/examples/example0003-classification.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE RankNTypes # ------------------------------------------------------------------------------ putStrLn ""
# LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE RebindableSyntax # # LANGUAGE DataKinds # import SubHask import SubHask.Algebra.Array import SubHask.Algebra.Vector import SubHask.Algebra.Container import HLearn.Data.LoadData import HLearn.Classifiers.Linear import HLearn.History import qualified Prelude as P import System.IO main = do xs :: BArray (Labeled' (SVector "dyn" Double) (Lexical String)) <- loadCSVLabeled' 0 "datasets/csv/uci/wine.csv" < - loadCSVLabeled ' 8 " datasets / csv / uci / pima - indians - diabetes.csv " glm <- runHistory ( (displayFilter (maxReportLevel 2) dispIteration) + summaryTable ) $ trainLogisticRegression 1e-3 xs putStrLn $ "loss_01 = "++show (validate loss_01 (toList xs) glm) putStrLn $ "loss_logistic = "++show (validate loss_logistic (toList xs) glm) putStrLn $ "loss_hinge = "++show (validate loss_hinge (toList xs) glm) print $ show $ weights glm!Lexical " 1 " print $ show $ weights glm!Lexical " 2 " print $ show $ weights glm!Lexical " 3 " putStrLn "done."
e5207fc88a7f118783c5ad21560165508e344b179a2215a584e1d124ba88c9f8
shayne-fletcher/zen
ml_lexer.ml
# 1 "ml_lexer.mll" (**The lexical analyzer*) open Lexing open Ml_parser * { 2 Utilities } (**Update the current location with file name and line number. [absolute] if [false] means add [line] to the current line number, if [true], replace it with [line] entirely*) let update_loc (lexbuf : lexbuf) (file : string option) (line : int) (absolute : bool) (chars :int) : unit = let pos = lexbuf.lex_curr_p in let new_file = match file with | None -> pos.pos_fname | Some s -> s in lexbuf.lex_curr_p <- { pos with pos_fname = new_file; pos_lnum = if absolute then line else pos.pos_lnum + line; pos_bol = pos.pos_cnum - chars; } (**[create_hashtable size init] creates a hashtable with [size] buckets with initial contents [init]*) let create_hashtable (size : int) (init : ('a * 'b) list ): ('a, 'b) Hashtbl.t = let tbl = Hashtbl.create size in List.iter (fun (key, data) -> Hashtbl.add tbl key data) init; tbl (**[keyword_table] associates keywords with their tokens*) let keyword_table = create_hashtable 149 [ "and", T_and; "else", T_else; "false", T_false; "fun", T_fun; "function", T_function; "if", T_if; "in", T_in; "let", T_let; "match", T_match; "rec", T_rec; "then", T_then; "true", T_true; "when", T_when; "with", T_with; ] * An allocation of 256 bytes let initial_string_buffer : bytes = Bytes.create 256 (**A string buffer reference*) let string_buf : bytes ref = ref initial_string_buffer (**The next unused index in the buffer*) let string_index : int ref = ref 0 (**Reset the string buffer contents to the original allocation*) let reset_string_buffer () = string_buf := initial_string_buffer; string_index := 0 (**Write a char [c] into the string buffer at the position indicated by the current [string_index], creating more space as neccessary. Increment [string_index]*) let store_string_char (c : char) : unit = if !string_index >= Bytes.length !string_buf then begin let new_buf = Bytes.create (Bytes.length (!string_buf) * 2) in Bytes.blit !string_buf 0 new_buf 0 (Bytes.length !string_buf); string_buf := new_buf end; Bytes.unsafe_set !string_buf !string_index c; incr string_index (**[store_string s] writes [s] into [string_buf] by way of [store_string_char]*) let store_string (s : string) : unit = for i = 0 to String.length s - 1 do store_string_char s.[i]; done * Called from the semantic actions of lexer definitions , [ Lexing.lexeme lexubf ] returns the string corresponding to the the matched regular expression . [ store_lexeme lexbuf ] stores this string in [ string_buf ] by way of [ store_string ] [Lexing.lexeme lexubf] returns the string corresponding to the the matched regular expression. [store_lexeme lexbuf] stores this string in [string_buf] by way of [store_string]*) let store_lexeme lexbuf = store_string (Lexing.lexeme lexbuf) (**Gets the contents of [string_buff], from 0 to the current [string_index], resets the [string_buff] back to it's original allocation; does not modify [string_index]*) let get_stored_string () = let s = Bytes.sub_string !string_buf 0 !string_index in string_buf := initial_string_buffer; s (*Comments*) (**A mutuable list of start locations of comments*) let comment_start_loc = ref [] (**[in_comment ()] evaluates to [true] between the time a comment has been started and not ended, [false] at all other times*) let in_comment () = !comment_start_loc <> [] (**A list of all comments accumulated during lexing*) let comment_list : (string * Ml_location.t) list ref = ref [] (**Add a comment to the list*) let add_comment (com : string * Ml_location.t) : unit = comment_list := com :: !comment_list (**Retrieve the list of comments*) let comments () : (string * Ml_location.t) list = List.rev !comment_list (**[with_comment_buffer comment lexbuf] uses the string buffer [comment_start_loc] and the [comment] rule*) let with_comment_buffer (comment : lexbuf -> Ml_location.t) (lexbuf : lexbuf) : string * Ml_location.t = let start_loc = Ml_location.curr lexbuf in comment_start_loc := [start_loc]; reset_string_buffer (); let end_loc : Ml_location.t = comment lexbuf in let s = get_stored_string () in reset_string_buffer (); let loc = { start_loc with Ml_location.loc_end = end_loc.Ml_location.loc_end } in s, loc * { 2 Error reporting } (**The type of errors that can come up in this module*) type error = | Illegal_character of char (**Unrecognizable token*) | Unterminated_comment of Ml_location.t (**An unterimated comment*) (**The type of exceptions that contain those errors*) exception Error of error * Ml_location.t (**This function takes a formatter and an instance of type [error] and writes a message to the formatter explaining the meaning. This is a "printer"*) let report_error (ppf : Format.formatter) : error -> unit = function | Illegal_character c -> Format.fprintf ppf "Illegal character (%s)" (Char.escaped c) | Unterminated_comment _ -> Format.fprintf ppf "Comment not terminated" (**Register an exception handler*) let () = Ml_location.register_error_of_exn (function | Error (err, loc) -> Some (Ml_location.error_of_printer loc report_error err) | _ -> None ) * { 2 Tables & rules } # 169 "ml_lexer.ml" let __ocaml_lex_tables = { Lexing.lex_base = "\000\000\222\255\223\255\084\000\192\000\159\000\026\001\061\001\ \096\001\131\001\166\001\201\001\237\255\238\255\236\001\015\002\ \050\002\243\255\034\000\085\002\246\255\004\000\120\002\155\002\ \251\255\190\002\220\002\002\000\255\255\005\000\006\000\054\003\ \089\003\124\003\224\255\159\003\244\255\194\003\229\003\008\004\ \135\000\251\255\252\255\007\000\253\255\055\000\083\000\255\255\ \254\255\011\000"; Lexing.lex_backtrk = "\255\255\255\255\255\255\030\000\029\000\028\000\026\000\024\000\ \023\000\033\000\020\000\019\000\255\255\255\255\016\000\023\000\ \013\000\255\255\033\000\010\000\255\255\008\000\007\000\005\000\ \255\255\006\000\002\000\001\000\255\255\033\000\255\255\025\000\ \003\000\026\000\255\255\021\000\255\255\014\000\015\000\022\000\ \255\255\255\255\255\255\004\000\255\255\004\000\004\000\255\255\ \255\255\255\255"; Lexing.lex_default = "\001\000\000\000\000\000\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\000\000\000\000\255\255\255\255\ \255\255\000\000\255\255\255\255\000\000\255\255\255\255\255\255\ \000\000\255\255\255\255\255\255\000\000\255\255\255\255\255\255\ \255\255\255\255\000\000\255\255\000\000\255\255\255\255\255\255\ \041\000\000\000\000\000\255\255\000\000\255\255\255\255\000\000\ \000\000\255\255"; Lexing.lex_trans = "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\027\000\028\000\027\000\027\000\029\000\027\000\028\000\ \028\000\042\000\030\000\030\000\049\000\042\000\000\000\000\000\ \049\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \027\000\019\000\027\000\000\000\008\000\006\000\015\000\000\000\ \021\000\020\000\022\000\023\000\024\000\025\000\034\000\006\000\ \005\000\005\000\005\000\005\000\005\000\005\000\005\000\005\000\ \005\000\005\000\018\000\017\000\011\000\014\000\010\000\009\000\ \007\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\013\000\036\000\012\000\007\000\026\000\ \048\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\003\000\016\000\047\000\009\000\000\000\ \000\000\000\000\000\000\000\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\000\000\000\000\ \000\000\042\000\000\000\000\000\043\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\046\000\ \000\000\045\000\000\000\003\000\000\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\005\000\ \005\000\005\000\005\000\005\000\005\000\005\000\005\000\005\000\ \005\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\004\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\000\000\000\000\000\000\000\000\005\000\000\000\ \002\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\000\000\000\000\000\000\000\000\004\000\ \000\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\006\000\000\000\000\000\006\000\006\000\ \006\000\000\000\000\000\000\000\006\000\006\000\000\000\006\000\ \006\000\006\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\006\000\000\000\006\000\006\000\ \006\000\006\000\006\000\000\000\000\000\000\000\007\000\000\000\ \000\000\007\000\007\000\007\000\000\000\000\000\000\000\007\000\ \007\000\000\000\007\000\007\000\007\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\007\000\ \006\000\007\000\007\000\007\000\007\000\007\000\000\000\000\000\ \000\000\008\000\000\000\000\000\008\000\008\000\008\000\044\000\ \000\000\000\000\008\000\008\000\000\000\008\000\008\000\008\000\ \000\000\000\000\000\000\000\000\000\000\000\000\006\000\000\000\ \006\000\000\000\008\000\007\000\008\000\008\000\008\000\008\000\ \008\000\000\000\000\000\000\000\039\000\000\000\000\000\039\000\ \039\000\039\000\000\000\000\000\000\000\039\000\039\000\000\000\ \039\000\039\000\039\000\000\000\000\000\000\000\000\000\000\000\ \000\000\007\000\000\000\007\000\000\000\039\000\008\000\039\000\ \039\000\039\000\039\000\039\000\000\000\000\000\000\000\008\000\ \000\000\000\000\008\000\008\000\008\000\000\000\000\000\000\000\ \008\000\008\000\000\000\008\000\008\000\008\000\000\000\000\000\ \000\000\000\000\000\000\000\000\008\000\000\000\008\000\000\000\ \008\000\039\000\008\000\008\000\008\000\008\000\008\000\000\000\ \000\000\000\000\008\000\000\000\000\000\008\000\008\000\008\000\ \000\000\000\000\000\000\008\000\008\000\000\000\008\000\008\000\ \008\000\000\000\000\000\000\000\000\000\000\000\000\000\039\000\ \000\000\039\000\000\000\008\000\008\000\008\000\008\000\008\000\ \008\000\008\000\000\000\000\000\000\000\008\000\000\000\000\000\ \008\000\008\000\008\000\000\000\000\000\000\000\008\000\008\000\ \000\000\008\000\008\000\008\000\000\000\000\000\000\000\000\000\ \000\000\000\000\008\000\000\000\008\000\000\000\008\000\008\000\ \008\000\008\000\008\000\008\000\008\000\000\000\000\000\000\000\ \008\000\000\000\000\000\008\000\008\000\038\000\000\000\000\000\ \000\000\008\000\008\000\000\000\008\000\008\000\008\000\000\000\ \000\000\000\000\000\000\000\000\000\000\008\000\000\000\008\000\ \000\000\008\000\008\000\008\000\008\000\008\000\008\000\008\000\ \000\000\000\000\000\000\008\000\000\000\000\000\008\000\008\000\ \008\000\000\000\000\000\000\000\008\000\008\000\000\000\008\000\ \008\000\008\000\000\000\000\000\000\000\000\000\000\000\000\000\ \008\000\000\000\008\000\000\000\008\000\008\000\008\000\008\000\ \008\000\008\000\008\000\000\000\000\000\000\000\035\000\000\000\ \000\000\035\000\035\000\035\000\000\000\000\000\000\000\035\000\ \035\000\000\000\035\000\035\000\035\000\000\000\000\000\000\000\ \000\000\000\000\000\000\008\000\000\000\008\000\000\000\035\000\ \008\000\035\000\035\000\035\000\035\000\035\000\000\000\000\000\ \000\000\006\000\000\000\000\000\006\000\006\000\006\000\000\000\ \000\000\000\000\033\000\006\000\000\000\006\000\006\000\006\000\ \000\000\000\000\000\000\000\000\000\000\000\000\037\000\000\000\ \008\000\000\000\006\000\035\000\006\000\006\000\006\000\006\000\ \006\000\000\000\000\000\000\000\031\000\000\000\000\000\031\000\ \031\000\031\000\000\000\000\000\000\000\031\000\031\000\000\000\ \031\000\031\000\031\000\000\000\000\000\000\000\000\000\000\000\ \000\000\035\000\000\000\035\000\000\000\031\000\006\000\031\000\ \031\000\031\000\031\000\031\000\000\000\000\000\000\000\031\000\ \000\000\000\000\031\000\031\000\031\000\000\000\000\000\000\000\ \031\000\031\000\000\000\031\000\031\000\031\000\000\000\000\000\ \000\000\000\000\000\000\000\000\006\000\000\000\006\000\000\000\ \031\000\031\000\031\000\031\000\032\000\031\000\031\000\000\000\ \000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\000\000\031\000\ \000\000\031\000\000\000\000\000\031\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\000\000\ \000\000\000\000\031\000\004\000\031\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\031\000\ \000\000\000\000\031\000\031\000\031\000\000\000\000\000\000\000\ \031\000\031\000\000\000\031\000\031\000\031\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \031\000\000\000\031\000\031\000\031\000\031\000\031\000\000\000\ \000\000\000\000\031\000\000\000\000\000\031\000\031\000\031\000\ \000\000\000\000\000\000\031\000\031\000\000\000\031\000\031\000\ \031\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\031\000\031\000\031\000\031\000\031\000\ \031\000\031\000\000\000\000\000\000\000\033\000\000\000\000\000\ \033\000\033\000\033\000\000\000\000\000\000\000\033\000\033\000\ \000\000\033\000\033\000\033\000\000\000\000\000\000\000\000\000\ \000\000\000\000\031\000\000\000\031\000\000\000\033\000\031\000\ \033\000\033\000\033\000\033\000\033\000\000\000\000\000\000\000\ \035\000\000\000\000\000\035\000\035\000\035\000\000\000\000\000\ \000\000\035\000\035\000\000\000\035\000\035\000\035\000\000\000\ \000\000\000\000\000\000\000\000\000\000\031\000\000\000\031\000\ \000\000\035\000\033\000\035\000\035\000\035\000\035\000\035\000\ \000\000\000\000\000\000\008\000\000\000\000\000\008\000\008\000\ \008\000\000\000\000\000\000\000\008\000\008\000\000\000\008\000\ \008\000\008\000\000\000\000\000\000\000\000\000\000\000\000\000\ \033\000\000\000\033\000\000\000\008\000\035\000\008\000\008\000\ \008\000\008\000\008\000\000\000\000\000\000\000\008\000\000\000\ \000\000\008\000\008\000\008\000\000\000\000\000\000\000\008\000\ \008\000\000\000\008\000\008\000\008\000\000\000\000\000\000\000\ \000\000\000\000\000\000\035\000\000\000\035\000\000\000\008\000\ \008\000\008\000\008\000\008\000\008\000\008\000\000\000\000\000\ \000\000\039\000\000\000\000\000\039\000\039\000\039\000\000\000\ \000\000\000\000\039\000\039\000\000\000\039\000\039\000\039\000\ \000\000\000\000\000\000\000\000\000\000\000\000\008\000\000\000\ \008\000\000\000\039\000\008\000\039\000\039\000\039\000\039\000\ \039\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\008\000\000\000\008\000\000\000\000\000\039\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\039\000\000\000\039\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000"; Lexing.lex_check = "\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\000\000\000\000\027\000\000\000\000\000\027\000\029\000\ \030\000\043\000\029\000\030\000\043\000\049\000\255\255\255\255\ \049\000\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \000\000\000\000\027\000\255\255\000\000\000\000\000\000\255\255\ \000\000\000\000\000\000\000\000\000\000\000\000\021\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\018\000\000\000\000\000\000\000\ \045\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\003\000\000\000\046\000\000\000\255\255\ \255\255\255\255\255\255\255\255\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\255\255\255\255\ \255\255\040\000\255\255\255\255\040\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\040\000\ \255\255\040\000\255\255\003\000\255\255\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\005\000\ \005\000\005\000\005\000\005\000\005\000\005\000\005\000\005\000\ \005\000\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\004\000\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\255\255\255\255\255\255\255\255\005\000\255\255\ \000\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\255\255\255\255\255\255\255\255\004\000\ \255\255\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\006\000\255\255\255\255\006\000\006\000\ \006\000\255\255\255\255\255\255\006\000\006\000\255\255\006\000\ \006\000\006\000\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\006\000\255\255\006\000\006\000\ \006\000\006\000\006\000\255\255\255\255\255\255\007\000\255\255\ \255\255\007\000\007\000\007\000\255\255\255\255\255\255\007\000\ \007\000\255\255\007\000\007\000\007\000\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\007\000\ \006\000\007\000\007\000\007\000\007\000\007\000\255\255\255\255\ \255\255\008\000\255\255\255\255\008\000\008\000\008\000\040\000\ \255\255\255\255\008\000\008\000\255\255\008\000\008\000\008\000\ \255\255\255\255\255\255\255\255\255\255\255\255\006\000\255\255\ \006\000\255\255\008\000\007\000\008\000\008\000\008\000\008\000\ \008\000\255\255\255\255\255\255\009\000\255\255\255\255\009\000\ \009\000\009\000\255\255\255\255\255\255\009\000\009\000\255\255\ \009\000\009\000\009\000\255\255\255\255\255\255\255\255\255\255\ \255\255\007\000\255\255\007\000\255\255\009\000\008\000\009\000\ \009\000\009\000\009\000\009\000\255\255\255\255\255\255\010\000\ \255\255\255\255\010\000\010\000\010\000\255\255\255\255\255\255\ \010\000\010\000\255\255\010\000\010\000\010\000\255\255\255\255\ \255\255\255\255\255\255\255\255\008\000\255\255\008\000\255\255\ \010\000\009\000\010\000\010\000\010\000\010\000\010\000\255\255\ \255\255\255\255\011\000\255\255\255\255\011\000\011\000\011\000\ \255\255\255\255\255\255\011\000\011\000\255\255\011\000\011\000\ \011\000\255\255\255\255\255\255\255\255\255\255\255\255\009\000\ \255\255\009\000\255\255\011\000\010\000\011\000\011\000\011\000\ \011\000\011\000\255\255\255\255\255\255\014\000\255\255\255\255\ \014\000\014\000\014\000\255\255\255\255\255\255\014\000\014\000\ \255\255\014\000\014\000\014\000\255\255\255\255\255\255\255\255\ \255\255\255\255\010\000\255\255\010\000\255\255\014\000\011\000\ \014\000\014\000\014\000\014\000\014\000\255\255\255\255\255\255\ \015\000\255\255\255\255\015\000\015\000\015\000\255\255\255\255\ \255\255\015\000\015\000\255\255\015\000\015\000\015\000\255\255\ \255\255\255\255\255\255\255\255\255\255\011\000\255\255\011\000\ \255\255\015\000\014\000\015\000\015\000\015\000\015\000\015\000\ \255\255\255\255\255\255\016\000\255\255\255\255\016\000\016\000\ \016\000\255\255\255\255\255\255\016\000\016\000\255\255\016\000\ \016\000\016\000\255\255\255\255\255\255\255\255\255\255\255\255\ \014\000\255\255\014\000\255\255\016\000\015\000\016\000\016\000\ \016\000\016\000\016\000\255\255\255\255\255\255\019\000\255\255\ \255\255\019\000\019\000\019\000\255\255\255\255\255\255\019\000\ \019\000\255\255\019\000\019\000\019\000\255\255\255\255\255\255\ \255\255\255\255\255\255\015\000\255\255\015\000\255\255\019\000\ \016\000\019\000\019\000\019\000\019\000\019\000\255\255\255\255\ \255\255\022\000\255\255\255\255\022\000\022\000\022\000\255\255\ \255\255\255\255\022\000\022\000\255\255\022\000\022\000\022\000\ \255\255\255\255\255\255\255\255\255\255\255\255\016\000\255\255\ \016\000\255\255\022\000\019\000\022\000\022\000\022\000\022\000\ \022\000\255\255\255\255\255\255\023\000\255\255\255\255\023\000\ \023\000\023\000\255\255\255\255\255\255\023\000\023\000\255\255\ \023\000\023\000\023\000\255\255\255\255\255\255\255\255\255\255\ \255\255\019\000\255\255\019\000\255\255\023\000\022\000\023\000\ \023\000\023\000\023\000\023\000\255\255\255\255\255\255\025\000\ \255\255\255\255\025\000\025\000\025\000\255\255\255\255\255\255\ \025\000\025\000\255\255\025\000\025\000\025\000\255\255\255\255\ \255\255\255\255\255\255\255\255\022\000\255\255\022\000\255\255\ \025\000\023\000\025\000\025\000\025\000\025\000\025\000\255\255\ \255\255\255\255\255\255\026\000\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\255\255\023\000\ \255\255\023\000\255\255\255\255\025\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\255\255\ \255\255\255\255\025\000\026\000\025\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\031\000\ \255\255\255\255\031\000\031\000\031\000\255\255\255\255\255\255\ \031\000\031\000\255\255\031\000\031\000\031\000\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \031\000\255\255\031\000\031\000\031\000\031\000\031\000\255\255\ \255\255\255\255\032\000\255\255\255\255\032\000\032\000\032\000\ \255\255\255\255\255\255\032\000\032\000\255\255\032\000\032\000\ \032\000\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\032\000\031\000\032\000\032\000\032\000\ \032\000\032\000\255\255\255\255\255\255\033\000\255\255\255\255\ \033\000\033\000\033\000\255\255\255\255\255\255\033\000\033\000\ \255\255\033\000\033\000\033\000\255\255\255\255\255\255\255\255\ \255\255\255\255\031\000\255\255\031\000\255\255\033\000\032\000\ \033\000\033\000\033\000\033\000\033\000\255\255\255\255\255\255\ \035\000\255\255\255\255\035\000\035\000\035\000\255\255\255\255\ \255\255\035\000\035\000\255\255\035\000\035\000\035\000\255\255\ \255\255\255\255\255\255\255\255\255\255\032\000\255\255\032\000\ \255\255\035\000\033\000\035\000\035\000\035\000\035\000\035\000\ \255\255\255\255\255\255\037\000\255\255\255\255\037\000\037\000\ \037\000\255\255\255\255\255\255\037\000\037\000\255\255\037\000\ \037\000\037\000\255\255\255\255\255\255\255\255\255\255\255\255\ \033\000\255\255\033\000\255\255\037\000\035\000\037\000\037\000\ \037\000\037\000\037\000\255\255\255\255\255\255\038\000\255\255\ \255\255\038\000\038\000\038\000\255\255\255\255\255\255\038\000\ \038\000\255\255\038\000\038\000\038\000\255\255\255\255\255\255\ \255\255\255\255\255\255\035\000\255\255\035\000\255\255\038\000\ \037\000\038\000\038\000\038\000\038\000\038\000\255\255\255\255\ \255\255\039\000\255\255\255\255\039\000\039\000\039\000\255\255\ \255\255\255\255\039\000\039\000\255\255\039\000\039\000\039\000\ \255\255\255\255\255\255\255\255\255\255\255\255\037\000\255\255\ \037\000\255\255\039\000\038\000\039\000\039\000\039\000\039\000\ \039\000\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\038\000\255\255\038\000\255\255\255\255\039\000\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\039\000\255\255\039\000\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255"; Lexing.lex_base_code = ""; Lexing.lex_backtrk_code = ""; Lexing.lex_default_code = ""; Lexing.lex_trans_code = ""; Lexing.lex_check_code = ""; Lexing.lex_code = ""; } let rec token lexbuf = __ocaml_lex_token_rec lexbuf 0 and __ocaml_lex_token_rec lexbuf __ocaml_lex_state = match Lexing.engine __ocaml_lex_tables __ocaml_lex_state lexbuf with | 0 -> # 178 "ml_lexer.mll" ( update_loc lexbuf None 1 false 0; T_eol ) # 542 "ml_lexer.ml" | 1 -> # 179 "ml_lexer.mll" ( token lexbuf ) # 547 "ml_lexer.ml" | 2 -> # 180 "ml_lexer.mll" ( T_underscore ) # 552 "ml_lexer.ml" | 3 -> # 181 "ml_lexer.mll" ( T_arrow ) # 557 "ml_lexer.ml" | 4 -> # 182 "ml_lexer.mll" ( T_comma ) # 562 "ml_lexer.ml" | 5 -> # 183 "ml_lexer.mll" ( T_plus ) # 567 "ml_lexer.ml" | 6 -> # 184 "ml_lexer.mll" ( T_minus ) # 572 "ml_lexer.ml" | 7 -> # 185 "ml_lexer.mll" ( T_star ) # 577 "ml_lexer.ml" | 8 -> # 186 "ml_lexer.mll" ( T_lparen ) # 582 "ml_lexer.ml" | 9 -> # 187 "ml_lexer.mll" ( T_rparen ) # 587 "ml_lexer.ml" | 10 -> # 188 "ml_lexer.mll" ( T_bang ) # 592 "ml_lexer.ml" | 11 -> # 189 "ml_lexer.mll" ( T_coloncolon ) # 597 "ml_lexer.ml" | 12 -> # 190 "ml_lexer.mll" ( T_semi ) # 602 "ml_lexer.ml" | 13 -> # 191 "ml_lexer.mll" ( T_bar ) # 607 "ml_lexer.ml" | 14 -> # 192 "ml_lexer.mll" ( T_barbar ) # 612 "ml_lexer.ml" | 15 -> # 193 "ml_lexer.mll" ( T_amperamper ) # 617 "ml_lexer.ml" | 16 -> # 194 "ml_lexer.mll" ( T_eq ) # 622 "ml_lexer.ml" | 17 -> # 195 "ml_lexer.mll" ( T_lbracket ) # 627 "ml_lexer.ml" | 18 -> # 196 "ml_lexer.mll" ( T_rbracket ) # 632 "ml_lexer.ml" | 19 -> # 197 "ml_lexer.mll" ( T_lt ) # 637 "ml_lexer.ml" | 20 -> # 198 "ml_lexer.mll" ( T_gt ) # 642 "ml_lexer.ml" | 21 -> # 199 "ml_lexer.mll" ( T_prefix_op (Lexing.lexeme lexbuf) ) # 647 "ml_lexer.ml" | 22 -> # 200 "ml_lexer.mll" ( T_prefix_op (Lexing.lexeme lexbuf) ) # 652 "ml_lexer.ml" | 23 -> # 201 "ml_lexer.mll" ( T_infixop0 (Lexing.lexeme lexbuf) ) # 657 "ml_lexer.ml" | 24 -> # 202 "ml_lexer.mll" ( T_infixop1 (Lexing.lexeme lexbuf) ) # 662 "ml_lexer.ml" | 25 -> # 203 "ml_lexer.mll" ( T_infixop2 (Lexing.lexeme lexbuf) ) # 667 "ml_lexer.ml" | 26 -> # 204 "ml_lexer.mll" ( T_infixop3 (Lexing.lexeme lexbuf) ) # 672 "ml_lexer.ml" | 27 -> # 205 "ml_lexer.mll" ( T_infixop4 (Lexing.lexeme lexbuf) ) # 677 "ml_lexer.ml" | 28 -> let # 206 "ml_lexer.mll" i # 683 "ml_lexer.ml" = Lexing.sub_lexeme lexbuf lexbuf.Lexing.lex_start_pos lexbuf.Lexing.lex_curr_pos in # 206 "ml_lexer.mll" ( T_int i ) # 687 "ml_lexer.ml" | 29 -> # 208 "ml_lexer.mll" ( let s = Lexing.lexeme lexbuf in try (*If its a keyword, look it up and return the associated token*) Hashtbl.find keyword_table s with Not_found -> T_ident s (*Else, treat as identifier*) ) # 698 "ml_lexer.ml" | 30 -> # 215 "ml_lexer.mll" ( let s = Lexing.lexeme lexbuf in T_uident s ) # 704 "ml_lexer.ml" | 31 -> # 217 "ml_lexer.mll" ( let s, loc = with_comment_buffer comment lexbuf in T_comment (s, loc) ) # 710 "ml_lexer.ml" | 32 -> # 219 "ml_lexer.mll" ( T_eof ) # 715 "ml_lexer.ml" | 33 -> # 221 "ml_lexer.mll" (raise (Error (Illegal_character (Lexing.lexeme_char lexbuf 0) , Ml_location.curr lexbuf)) ) # 721 "ml_lexer.ml" | __ocaml_lex_state -> lexbuf.Lexing.refill_buff lexbuf; __ocaml_lex_token_rec lexbuf __ocaml_lex_state and comment lexbuf = __ocaml_lex_comment_rec lexbuf 40 and __ocaml_lex_comment_rec lexbuf __ocaml_lex_state = match Lexing.engine __ocaml_lex_tables __ocaml_lex_state lexbuf with | 0 -> # 225 "ml_lexer.mll" ( comment_start_loc := (Ml_location.curr lexbuf) :: !comment_start_loc; store_lexeme lexbuf; comment lexbuf ) # 738 "ml_lexer.ml" | 1 -> # 232 "ml_lexer.mll" ( match !comment_start_loc with | [] -> assert false | [_] -> comment_start_loc := []; Ml_location.curr lexbuf | _ :: l -> comment_start_loc := l; store_lexeme lexbuf; comment lexbuf ) # 751 "ml_lexer.ml" | 2 -> # 242 "ml_lexer.mll" ( match !comment_start_loc with | [] -> assert false | loc :: _ -> let start = List.hd (List.rev !comment_start_loc) in comment_start_loc := []; raise (Error (Unterminated_comment start, loc)) ) # 763 "ml_lexer.ml" | 3 -> # 251 "ml_lexer.mll" ( update_loc lexbuf None 1 false 0; store_lexeme lexbuf; comment lexbuf ) # 772 "ml_lexer.ml" | 4 -> # 257 "ml_lexer.mll" ( store_lexeme lexbuf; comment lexbuf ) # 777 "ml_lexer.ml" | __ocaml_lex_state -> lexbuf.Lexing.refill_buff lexbuf; __ocaml_lex_comment_rec lexbuf __ocaml_lex_state ;; # 259 "ml_lexer.mll" * { 2 Postscript } (**A wrapper around the token rule that collects comment strings encountered during lexing and discards comment and end of line tokens*) let token (lexbuf : lexbuf) : token = let rec loop lexbuf = match token lexbuf with | T_comment (s, loc) -> add_comment (s, loc); loop lexbuf | T_eol -> loop lexbuf | tok -> tok in loop lexbuf # 799 "ml_lexer.ml"
null
https://raw.githubusercontent.com/shayne-fletcher/zen/10a1d0b9bf261bb133918dd62fb1593c3d4d21cb/ocaml/cos/src/parsing/ml_lexer.ml
ocaml
*The lexical analyzer *Update the current location with file name and line number. [absolute] if [false] means add [line] to the current line number, if [true], replace it with [line] entirely *[create_hashtable size init] creates a hashtable with [size] buckets with initial contents [init] *[keyword_table] associates keywords with their tokens *A string buffer reference *The next unused index in the buffer *Reset the string buffer contents to the original allocation *Write a char [c] into the string buffer at the position indicated by the current [string_index], creating more space as neccessary. Increment [string_index] *[store_string s] writes [s] into [string_buf] by way of [store_string_char] *Gets the contents of [string_buff], from 0 to the current [string_index], resets the [string_buff] back to it's original allocation; does not modify [string_index] Comments *A mutuable list of start locations of comments *[in_comment ()] evaluates to [true] between the time a comment has been started and not ended, [false] at all other times *A list of all comments accumulated during lexing *Add a comment to the list *Retrieve the list of comments *[with_comment_buffer comment lexbuf] uses the string buffer [comment_start_loc] and the [comment] rule *The type of errors that can come up in this module *Unrecognizable token *An unterimated comment *The type of exceptions that contain those errors *This function takes a formatter and an instance of type [error] and writes a message to the formatter explaining the meaning. This is a "printer" *Register an exception handler If its a keyword, look it up and return the associated token Else, treat as identifier *A wrapper around the token rule that collects comment strings encountered during lexing and discards comment and end of line tokens
# 1 "ml_lexer.mll" open Lexing open Ml_parser * { 2 Utilities } let update_loc (lexbuf : lexbuf) (file : string option) (line : int) (absolute : bool) (chars :int) : unit = let pos = lexbuf.lex_curr_p in let new_file = match file with | None -> pos.pos_fname | Some s -> s in lexbuf.lex_curr_p <- { pos with pos_fname = new_file; pos_lnum = if absolute then line else pos.pos_lnum + line; pos_bol = pos.pos_cnum - chars; } let create_hashtable (size : int) (init : ('a * 'b) list ): ('a, 'b) Hashtbl.t = let tbl = Hashtbl.create size in List.iter (fun (key, data) -> Hashtbl.add tbl key data) init; tbl let keyword_table = create_hashtable 149 [ "and", T_and; "else", T_else; "false", T_false; "fun", T_fun; "function", T_function; "if", T_if; "in", T_in; "let", T_let; "match", T_match; "rec", T_rec; "then", T_then; "true", T_true; "when", T_when; "with", T_with; ] * An allocation of 256 bytes let initial_string_buffer : bytes = Bytes.create 256 let string_buf : bytes ref = ref initial_string_buffer let string_index : int ref = ref 0 let reset_string_buffer () = string_buf := initial_string_buffer; string_index := 0 let store_string_char (c : char) : unit = if !string_index >= Bytes.length !string_buf then begin let new_buf = Bytes.create (Bytes.length (!string_buf) * 2) in Bytes.blit !string_buf 0 new_buf 0 (Bytes.length !string_buf); string_buf := new_buf end; Bytes.unsafe_set !string_buf !string_index c; incr string_index let store_string (s : string) : unit = for i = 0 to String.length s - 1 do store_string_char s.[i]; done * Called from the semantic actions of lexer definitions , [ Lexing.lexeme lexubf ] returns the string corresponding to the the matched regular expression . [ store_lexeme lexbuf ] stores this string in [ string_buf ] by way of [ store_string ] [Lexing.lexeme lexubf] returns the string corresponding to the the matched regular expression. [store_lexeme lexbuf] stores this string in [string_buf] by way of [store_string]*) let store_lexeme lexbuf = store_string (Lexing.lexeme lexbuf) let get_stored_string () = let s = Bytes.sub_string !string_buf 0 !string_index in string_buf := initial_string_buffer; s let comment_start_loc = ref [] let in_comment () = !comment_start_loc <> [] let comment_list : (string * Ml_location.t) list ref = ref [] let add_comment (com : string * Ml_location.t) : unit = comment_list := com :: !comment_list let comments () : (string * Ml_location.t) list = List.rev !comment_list let with_comment_buffer (comment : lexbuf -> Ml_location.t) (lexbuf : lexbuf) : string * Ml_location.t = let start_loc = Ml_location.curr lexbuf in comment_start_loc := [start_loc]; reset_string_buffer (); let end_loc : Ml_location.t = comment lexbuf in let s = get_stored_string () in reset_string_buffer (); let loc = { start_loc with Ml_location.loc_end = end_loc.Ml_location.loc_end } in s, loc * { 2 Error reporting } type error = exception Error of error * Ml_location.t let report_error (ppf : Format.formatter) : error -> unit = function | Illegal_character c -> Format.fprintf ppf "Illegal character (%s)" (Char.escaped c) | Unterminated_comment _ -> Format.fprintf ppf "Comment not terminated" let () = Ml_location.register_error_of_exn (function | Error (err, loc) -> Some (Ml_location.error_of_printer loc report_error err) | _ -> None ) * { 2 Tables & rules } # 169 "ml_lexer.ml" let __ocaml_lex_tables = { Lexing.lex_base = "\000\000\222\255\223\255\084\000\192\000\159\000\026\001\061\001\ \096\001\131\001\166\001\201\001\237\255\238\255\236\001\015\002\ \050\002\243\255\034\000\085\002\246\255\004\000\120\002\155\002\ \251\255\190\002\220\002\002\000\255\255\005\000\006\000\054\003\ \089\003\124\003\224\255\159\003\244\255\194\003\229\003\008\004\ \135\000\251\255\252\255\007\000\253\255\055\000\083\000\255\255\ \254\255\011\000"; Lexing.lex_backtrk = "\255\255\255\255\255\255\030\000\029\000\028\000\026\000\024\000\ \023\000\033\000\020\000\019\000\255\255\255\255\016\000\023\000\ \013\000\255\255\033\000\010\000\255\255\008\000\007\000\005\000\ \255\255\006\000\002\000\001\000\255\255\033\000\255\255\025\000\ \003\000\026\000\255\255\021\000\255\255\014\000\015\000\022\000\ \255\255\255\255\255\255\004\000\255\255\004\000\004\000\255\255\ \255\255\255\255"; Lexing.lex_default = "\001\000\000\000\000\000\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\000\000\000\000\255\255\255\255\ \255\255\000\000\255\255\255\255\000\000\255\255\255\255\255\255\ \000\000\255\255\255\255\255\255\000\000\255\255\255\255\255\255\ \255\255\255\255\000\000\255\255\000\000\255\255\255\255\255\255\ \041\000\000\000\000\000\255\255\000\000\255\255\255\255\000\000\ \000\000\255\255"; Lexing.lex_trans = "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\027\000\028\000\027\000\027\000\029\000\027\000\028\000\ \028\000\042\000\030\000\030\000\049\000\042\000\000\000\000\000\ \049\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \027\000\019\000\027\000\000\000\008\000\006\000\015\000\000\000\ \021\000\020\000\022\000\023\000\024\000\025\000\034\000\006\000\ \005\000\005\000\005\000\005\000\005\000\005\000\005\000\005\000\ \005\000\005\000\018\000\017\000\011\000\014\000\010\000\009\000\ \007\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\013\000\036\000\012\000\007\000\026\000\ \048\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\003\000\016\000\047\000\009\000\000\000\ \000\000\000\000\000\000\000\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\000\000\000\000\ \000\000\042\000\000\000\000\000\043\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\046\000\ \000\000\045\000\000\000\003\000\000\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\005\000\ \005\000\005\000\005\000\005\000\005\000\005\000\005\000\005\000\ \005\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\004\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\000\000\000\000\000\000\000\000\005\000\000\000\ \002\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\000\000\000\000\000\000\000\000\004\000\ \000\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\006\000\000\000\000\000\006\000\006\000\ \006\000\000\000\000\000\000\000\006\000\006\000\000\000\006\000\ \006\000\006\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\006\000\000\000\006\000\006\000\ \006\000\006\000\006\000\000\000\000\000\000\000\007\000\000\000\ \000\000\007\000\007\000\007\000\000\000\000\000\000\000\007\000\ \007\000\000\000\007\000\007\000\007\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\007\000\ \006\000\007\000\007\000\007\000\007\000\007\000\000\000\000\000\ \000\000\008\000\000\000\000\000\008\000\008\000\008\000\044\000\ \000\000\000\000\008\000\008\000\000\000\008\000\008\000\008\000\ \000\000\000\000\000\000\000\000\000\000\000\000\006\000\000\000\ \006\000\000\000\008\000\007\000\008\000\008\000\008\000\008\000\ \008\000\000\000\000\000\000\000\039\000\000\000\000\000\039\000\ \039\000\039\000\000\000\000\000\000\000\039\000\039\000\000\000\ \039\000\039\000\039\000\000\000\000\000\000\000\000\000\000\000\ \000\000\007\000\000\000\007\000\000\000\039\000\008\000\039\000\ \039\000\039\000\039\000\039\000\000\000\000\000\000\000\008\000\ \000\000\000\000\008\000\008\000\008\000\000\000\000\000\000\000\ \008\000\008\000\000\000\008\000\008\000\008\000\000\000\000\000\ \000\000\000\000\000\000\000\000\008\000\000\000\008\000\000\000\ \008\000\039\000\008\000\008\000\008\000\008\000\008\000\000\000\ \000\000\000\000\008\000\000\000\000\000\008\000\008\000\008\000\ \000\000\000\000\000\000\008\000\008\000\000\000\008\000\008\000\ \008\000\000\000\000\000\000\000\000\000\000\000\000\000\039\000\ \000\000\039\000\000\000\008\000\008\000\008\000\008\000\008\000\ \008\000\008\000\000\000\000\000\000\000\008\000\000\000\000\000\ \008\000\008\000\008\000\000\000\000\000\000\000\008\000\008\000\ \000\000\008\000\008\000\008\000\000\000\000\000\000\000\000\000\ \000\000\000\000\008\000\000\000\008\000\000\000\008\000\008\000\ \008\000\008\000\008\000\008\000\008\000\000\000\000\000\000\000\ \008\000\000\000\000\000\008\000\008\000\038\000\000\000\000\000\ \000\000\008\000\008\000\000\000\008\000\008\000\008\000\000\000\ \000\000\000\000\000\000\000\000\000\000\008\000\000\000\008\000\ \000\000\008\000\008\000\008\000\008\000\008\000\008\000\008\000\ \000\000\000\000\000\000\008\000\000\000\000\000\008\000\008\000\ \008\000\000\000\000\000\000\000\008\000\008\000\000\000\008\000\ \008\000\008\000\000\000\000\000\000\000\000\000\000\000\000\000\ \008\000\000\000\008\000\000\000\008\000\008\000\008\000\008\000\ \008\000\008\000\008\000\000\000\000\000\000\000\035\000\000\000\ \000\000\035\000\035\000\035\000\000\000\000\000\000\000\035\000\ \035\000\000\000\035\000\035\000\035\000\000\000\000\000\000\000\ \000\000\000\000\000\000\008\000\000\000\008\000\000\000\035\000\ \008\000\035\000\035\000\035\000\035\000\035\000\000\000\000\000\ \000\000\006\000\000\000\000\000\006\000\006\000\006\000\000\000\ \000\000\000\000\033\000\006\000\000\000\006\000\006\000\006\000\ \000\000\000\000\000\000\000\000\000\000\000\000\037\000\000\000\ \008\000\000\000\006\000\035\000\006\000\006\000\006\000\006\000\ \006\000\000\000\000\000\000\000\031\000\000\000\000\000\031\000\ \031\000\031\000\000\000\000\000\000\000\031\000\031\000\000\000\ \031\000\031\000\031\000\000\000\000\000\000\000\000\000\000\000\ \000\000\035\000\000\000\035\000\000\000\031\000\006\000\031\000\ \031\000\031\000\031\000\031\000\000\000\000\000\000\000\031\000\ \000\000\000\000\031\000\031\000\031\000\000\000\000\000\000\000\ \031\000\031\000\000\000\031\000\031\000\031\000\000\000\000\000\ \000\000\000\000\000\000\000\000\006\000\000\000\006\000\000\000\ \031\000\031\000\031\000\031\000\032\000\031\000\031\000\000\000\ \000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\000\000\031\000\ \000\000\031\000\000\000\000\000\031\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\000\000\ \000\000\000\000\031\000\004\000\031\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\031\000\ \000\000\000\000\031\000\031\000\031\000\000\000\000\000\000\000\ \031\000\031\000\000\000\031\000\031\000\031\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \031\000\000\000\031\000\031\000\031\000\031\000\031\000\000\000\ \000\000\000\000\031\000\000\000\000\000\031\000\031\000\031\000\ \000\000\000\000\000\000\031\000\031\000\000\000\031\000\031\000\ \031\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\031\000\031\000\031\000\031\000\031\000\ \031\000\031\000\000\000\000\000\000\000\033\000\000\000\000\000\ \033\000\033\000\033\000\000\000\000\000\000\000\033\000\033\000\ \000\000\033\000\033\000\033\000\000\000\000\000\000\000\000\000\ \000\000\000\000\031\000\000\000\031\000\000\000\033\000\031\000\ \033\000\033\000\033\000\033\000\033\000\000\000\000\000\000\000\ \035\000\000\000\000\000\035\000\035\000\035\000\000\000\000\000\ \000\000\035\000\035\000\000\000\035\000\035\000\035\000\000\000\ \000\000\000\000\000\000\000\000\000\000\031\000\000\000\031\000\ \000\000\035\000\033\000\035\000\035\000\035\000\035\000\035\000\ \000\000\000\000\000\000\008\000\000\000\000\000\008\000\008\000\ \008\000\000\000\000\000\000\000\008\000\008\000\000\000\008\000\ \008\000\008\000\000\000\000\000\000\000\000\000\000\000\000\000\ \033\000\000\000\033\000\000\000\008\000\035\000\008\000\008\000\ \008\000\008\000\008\000\000\000\000\000\000\000\008\000\000\000\ \000\000\008\000\008\000\008\000\000\000\000\000\000\000\008\000\ \008\000\000\000\008\000\008\000\008\000\000\000\000\000\000\000\ \000\000\000\000\000\000\035\000\000\000\035\000\000\000\008\000\ \008\000\008\000\008\000\008\000\008\000\008\000\000\000\000\000\ \000\000\039\000\000\000\000\000\039\000\039\000\039\000\000\000\ \000\000\000\000\039\000\039\000\000\000\039\000\039\000\039\000\ \000\000\000\000\000\000\000\000\000\000\000\000\008\000\000\000\ \008\000\000\000\039\000\008\000\039\000\039\000\039\000\039\000\ \039\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\008\000\000\000\008\000\000\000\000\000\039\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\039\000\000\000\039\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000"; Lexing.lex_check = "\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\000\000\000\000\027\000\000\000\000\000\027\000\029\000\ \030\000\043\000\029\000\030\000\043\000\049\000\255\255\255\255\ \049\000\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \000\000\000\000\027\000\255\255\000\000\000\000\000\000\255\255\ \000\000\000\000\000\000\000\000\000\000\000\000\021\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\018\000\000\000\000\000\000\000\ \045\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\ \000\000\000\000\000\000\003\000\000\000\046\000\000\000\255\255\ \255\255\255\255\255\255\255\255\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\255\255\255\255\ \255\255\040\000\255\255\255\255\040\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\040\000\ \255\255\040\000\255\255\003\000\255\255\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\003\000\ \003\000\003\000\003\000\003\000\003\000\003\000\003\000\005\000\ \005\000\005\000\005\000\005\000\005\000\005\000\005\000\005\000\ \005\000\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\004\000\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\255\255\255\255\255\255\255\255\005\000\255\255\ \000\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\255\255\255\255\255\255\255\255\004\000\ \255\255\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\004\000\004\000\004\000\004\000\004\000\ \004\000\004\000\004\000\006\000\255\255\255\255\006\000\006\000\ \006\000\255\255\255\255\255\255\006\000\006\000\255\255\006\000\ \006\000\006\000\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\006\000\255\255\006\000\006\000\ \006\000\006\000\006\000\255\255\255\255\255\255\007\000\255\255\ \255\255\007\000\007\000\007\000\255\255\255\255\255\255\007\000\ \007\000\255\255\007\000\007\000\007\000\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\007\000\ \006\000\007\000\007\000\007\000\007\000\007\000\255\255\255\255\ \255\255\008\000\255\255\255\255\008\000\008\000\008\000\040\000\ \255\255\255\255\008\000\008\000\255\255\008\000\008\000\008\000\ \255\255\255\255\255\255\255\255\255\255\255\255\006\000\255\255\ \006\000\255\255\008\000\007\000\008\000\008\000\008\000\008\000\ \008\000\255\255\255\255\255\255\009\000\255\255\255\255\009\000\ \009\000\009\000\255\255\255\255\255\255\009\000\009\000\255\255\ \009\000\009\000\009\000\255\255\255\255\255\255\255\255\255\255\ \255\255\007\000\255\255\007\000\255\255\009\000\008\000\009\000\ \009\000\009\000\009\000\009\000\255\255\255\255\255\255\010\000\ \255\255\255\255\010\000\010\000\010\000\255\255\255\255\255\255\ \010\000\010\000\255\255\010\000\010\000\010\000\255\255\255\255\ \255\255\255\255\255\255\255\255\008\000\255\255\008\000\255\255\ \010\000\009\000\010\000\010\000\010\000\010\000\010\000\255\255\ \255\255\255\255\011\000\255\255\255\255\011\000\011\000\011\000\ \255\255\255\255\255\255\011\000\011\000\255\255\011\000\011\000\ \011\000\255\255\255\255\255\255\255\255\255\255\255\255\009\000\ \255\255\009\000\255\255\011\000\010\000\011\000\011\000\011\000\ \011\000\011\000\255\255\255\255\255\255\014\000\255\255\255\255\ \014\000\014\000\014\000\255\255\255\255\255\255\014\000\014\000\ \255\255\014\000\014\000\014\000\255\255\255\255\255\255\255\255\ \255\255\255\255\010\000\255\255\010\000\255\255\014\000\011\000\ \014\000\014\000\014\000\014\000\014\000\255\255\255\255\255\255\ \015\000\255\255\255\255\015\000\015\000\015\000\255\255\255\255\ \255\255\015\000\015\000\255\255\015\000\015\000\015\000\255\255\ \255\255\255\255\255\255\255\255\255\255\011\000\255\255\011\000\ \255\255\015\000\014\000\015\000\015\000\015\000\015\000\015\000\ \255\255\255\255\255\255\016\000\255\255\255\255\016\000\016\000\ \016\000\255\255\255\255\255\255\016\000\016\000\255\255\016\000\ \016\000\016\000\255\255\255\255\255\255\255\255\255\255\255\255\ \014\000\255\255\014\000\255\255\016\000\015\000\016\000\016\000\ \016\000\016\000\016\000\255\255\255\255\255\255\019\000\255\255\ \255\255\019\000\019\000\019\000\255\255\255\255\255\255\019\000\ \019\000\255\255\019\000\019\000\019\000\255\255\255\255\255\255\ \255\255\255\255\255\255\015\000\255\255\015\000\255\255\019\000\ \016\000\019\000\019\000\019\000\019\000\019\000\255\255\255\255\ \255\255\022\000\255\255\255\255\022\000\022\000\022\000\255\255\ \255\255\255\255\022\000\022\000\255\255\022\000\022\000\022\000\ \255\255\255\255\255\255\255\255\255\255\255\255\016\000\255\255\ \016\000\255\255\022\000\019\000\022\000\022\000\022\000\022\000\ \022\000\255\255\255\255\255\255\023\000\255\255\255\255\023\000\ \023\000\023\000\255\255\255\255\255\255\023\000\023\000\255\255\ \023\000\023\000\023\000\255\255\255\255\255\255\255\255\255\255\ \255\255\019\000\255\255\019\000\255\255\023\000\022\000\023\000\ \023\000\023\000\023\000\023\000\255\255\255\255\255\255\025\000\ \255\255\255\255\025\000\025\000\025\000\255\255\255\255\255\255\ \025\000\025\000\255\255\025\000\025\000\025\000\255\255\255\255\ \255\255\255\255\255\255\255\255\022\000\255\255\022\000\255\255\ \025\000\023\000\025\000\025\000\025\000\025\000\025\000\255\255\ \255\255\255\255\255\255\026\000\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\255\255\023\000\ \255\255\023\000\255\255\255\255\025\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\255\255\ \255\255\255\255\025\000\026\000\025\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\026\000\ \026\000\026\000\026\000\026\000\026\000\026\000\026\000\031\000\ \255\255\255\255\031\000\031\000\031\000\255\255\255\255\255\255\ \031\000\031\000\255\255\031\000\031\000\031\000\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \031\000\255\255\031\000\031\000\031\000\031\000\031\000\255\255\ \255\255\255\255\032\000\255\255\255\255\032\000\032\000\032\000\ \255\255\255\255\255\255\032\000\032\000\255\255\032\000\032\000\ \032\000\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\032\000\031\000\032\000\032\000\032\000\ \032\000\032\000\255\255\255\255\255\255\033\000\255\255\255\255\ \033\000\033\000\033\000\255\255\255\255\255\255\033\000\033\000\ \255\255\033\000\033\000\033\000\255\255\255\255\255\255\255\255\ \255\255\255\255\031\000\255\255\031\000\255\255\033\000\032\000\ \033\000\033\000\033\000\033\000\033\000\255\255\255\255\255\255\ \035\000\255\255\255\255\035\000\035\000\035\000\255\255\255\255\ \255\255\035\000\035\000\255\255\035\000\035\000\035\000\255\255\ \255\255\255\255\255\255\255\255\255\255\032\000\255\255\032\000\ \255\255\035\000\033\000\035\000\035\000\035\000\035\000\035\000\ \255\255\255\255\255\255\037\000\255\255\255\255\037\000\037\000\ \037\000\255\255\255\255\255\255\037\000\037\000\255\255\037\000\ \037\000\037\000\255\255\255\255\255\255\255\255\255\255\255\255\ \033\000\255\255\033\000\255\255\037\000\035\000\037\000\037\000\ \037\000\037\000\037\000\255\255\255\255\255\255\038\000\255\255\ \255\255\038\000\038\000\038\000\255\255\255\255\255\255\038\000\ \038\000\255\255\038\000\038\000\038\000\255\255\255\255\255\255\ \255\255\255\255\255\255\035\000\255\255\035\000\255\255\038\000\ \037\000\038\000\038\000\038\000\038\000\038\000\255\255\255\255\ \255\255\039\000\255\255\255\255\039\000\039\000\039\000\255\255\ \255\255\255\255\039\000\039\000\255\255\039\000\039\000\039\000\ \255\255\255\255\255\255\255\255\255\255\255\255\037\000\255\255\ \037\000\255\255\039\000\038\000\039\000\039\000\039\000\039\000\ \039\000\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\038\000\255\255\038\000\255\255\255\255\039\000\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\039\000\255\255\039\000\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\255\ \255\255"; Lexing.lex_base_code = ""; Lexing.lex_backtrk_code = ""; Lexing.lex_default_code = ""; Lexing.lex_trans_code = ""; Lexing.lex_check_code = ""; Lexing.lex_code = ""; } let rec token lexbuf = __ocaml_lex_token_rec lexbuf 0 and __ocaml_lex_token_rec lexbuf __ocaml_lex_state = match Lexing.engine __ocaml_lex_tables __ocaml_lex_state lexbuf with | 0 -> # 178 "ml_lexer.mll" ( update_loc lexbuf None 1 false 0; T_eol ) # 542 "ml_lexer.ml" | 1 -> # 179 "ml_lexer.mll" ( token lexbuf ) # 547 "ml_lexer.ml" | 2 -> # 180 "ml_lexer.mll" ( T_underscore ) # 552 "ml_lexer.ml" | 3 -> # 181 "ml_lexer.mll" ( T_arrow ) # 557 "ml_lexer.ml" | 4 -> # 182 "ml_lexer.mll" ( T_comma ) # 562 "ml_lexer.ml" | 5 -> # 183 "ml_lexer.mll" ( T_plus ) # 567 "ml_lexer.ml" | 6 -> # 184 "ml_lexer.mll" ( T_minus ) # 572 "ml_lexer.ml" | 7 -> # 185 "ml_lexer.mll" ( T_star ) # 577 "ml_lexer.ml" | 8 -> # 186 "ml_lexer.mll" ( T_lparen ) # 582 "ml_lexer.ml" | 9 -> # 187 "ml_lexer.mll" ( T_rparen ) # 587 "ml_lexer.ml" | 10 -> # 188 "ml_lexer.mll" ( T_bang ) # 592 "ml_lexer.ml" | 11 -> # 189 "ml_lexer.mll" ( T_coloncolon ) # 597 "ml_lexer.ml" | 12 -> # 190 "ml_lexer.mll" ( T_semi ) # 602 "ml_lexer.ml" | 13 -> # 191 "ml_lexer.mll" ( T_bar ) # 607 "ml_lexer.ml" | 14 -> # 192 "ml_lexer.mll" ( T_barbar ) # 612 "ml_lexer.ml" | 15 -> # 193 "ml_lexer.mll" ( T_amperamper ) # 617 "ml_lexer.ml" | 16 -> # 194 "ml_lexer.mll" ( T_eq ) # 622 "ml_lexer.ml" | 17 -> # 195 "ml_lexer.mll" ( T_lbracket ) # 627 "ml_lexer.ml" | 18 -> # 196 "ml_lexer.mll" ( T_rbracket ) # 632 "ml_lexer.ml" | 19 -> # 197 "ml_lexer.mll" ( T_lt ) # 637 "ml_lexer.ml" | 20 -> # 198 "ml_lexer.mll" ( T_gt ) # 642 "ml_lexer.ml" | 21 -> # 199 "ml_lexer.mll" ( T_prefix_op (Lexing.lexeme lexbuf) ) # 647 "ml_lexer.ml" | 22 -> # 200 "ml_lexer.mll" ( T_prefix_op (Lexing.lexeme lexbuf) ) # 652 "ml_lexer.ml" | 23 -> # 201 "ml_lexer.mll" ( T_infixop0 (Lexing.lexeme lexbuf) ) # 657 "ml_lexer.ml" | 24 -> # 202 "ml_lexer.mll" ( T_infixop1 (Lexing.lexeme lexbuf) ) # 662 "ml_lexer.ml" | 25 -> # 203 "ml_lexer.mll" ( T_infixop2 (Lexing.lexeme lexbuf) ) # 667 "ml_lexer.ml" | 26 -> # 204 "ml_lexer.mll" ( T_infixop3 (Lexing.lexeme lexbuf) ) # 672 "ml_lexer.ml" | 27 -> # 205 "ml_lexer.mll" ( T_infixop4 (Lexing.lexeme lexbuf) ) # 677 "ml_lexer.ml" | 28 -> let # 206 "ml_lexer.mll" i # 683 "ml_lexer.ml" = Lexing.sub_lexeme lexbuf lexbuf.Lexing.lex_start_pos lexbuf.Lexing.lex_curr_pos in # 206 "ml_lexer.mll" ( T_int i ) # 687 "ml_lexer.ml" | 29 -> # 208 "ml_lexer.mll" ( let s = Lexing.lexeme lexbuf in try Hashtbl.find keyword_table s ) # 698 "ml_lexer.ml" | 30 -> # 215 "ml_lexer.mll" ( let s = Lexing.lexeme lexbuf in T_uident s ) # 704 "ml_lexer.ml" | 31 -> # 217 "ml_lexer.mll" ( let s, loc = with_comment_buffer comment lexbuf in T_comment (s, loc) ) # 710 "ml_lexer.ml" | 32 -> # 219 "ml_lexer.mll" ( T_eof ) # 715 "ml_lexer.ml" | 33 -> # 221 "ml_lexer.mll" (raise (Error (Illegal_character (Lexing.lexeme_char lexbuf 0) , Ml_location.curr lexbuf)) ) # 721 "ml_lexer.ml" | __ocaml_lex_state -> lexbuf.Lexing.refill_buff lexbuf; __ocaml_lex_token_rec lexbuf __ocaml_lex_state and comment lexbuf = __ocaml_lex_comment_rec lexbuf 40 and __ocaml_lex_comment_rec lexbuf __ocaml_lex_state = match Lexing.engine __ocaml_lex_tables __ocaml_lex_state lexbuf with | 0 -> # 225 "ml_lexer.mll" ( comment_start_loc := (Ml_location.curr lexbuf) :: !comment_start_loc; store_lexeme lexbuf; comment lexbuf ) # 738 "ml_lexer.ml" | 1 -> # 232 "ml_lexer.mll" ( match !comment_start_loc with | [] -> assert false | [_] -> comment_start_loc := []; Ml_location.curr lexbuf | _ :: l -> comment_start_loc := l; store_lexeme lexbuf; comment lexbuf ) # 751 "ml_lexer.ml" | 2 -> # 242 "ml_lexer.mll" ( match !comment_start_loc with | [] -> assert false | loc :: _ -> let start = List.hd (List.rev !comment_start_loc) in comment_start_loc := []; raise (Error (Unterminated_comment start, loc)) ) # 763 "ml_lexer.ml" | 3 -> # 251 "ml_lexer.mll" ( update_loc lexbuf None 1 false 0; store_lexeme lexbuf; comment lexbuf ) # 772 "ml_lexer.ml" | 4 -> # 257 "ml_lexer.mll" ( store_lexeme lexbuf; comment lexbuf ) # 777 "ml_lexer.ml" | __ocaml_lex_state -> lexbuf.Lexing.refill_buff lexbuf; __ocaml_lex_comment_rec lexbuf __ocaml_lex_state ;; # 259 "ml_lexer.mll" * { 2 Postscript } let token (lexbuf : lexbuf) : token = let rec loop lexbuf = match token lexbuf with | T_comment (s, loc) -> add_comment (s, loc); loop lexbuf | T_eol -> loop lexbuf | tok -> tok in loop lexbuf # 799 "ml_lexer.ml"
2d1c6fab685ff65d3ebe2ea48b4f350cc4d11255f3e849475a1986bc46f75845
bzuilhof/AdventOfCode
day12.hs
module Day12 where import Data.List import Data.Char import Data.Maybe import Data.Array type Pot = Char inputData, iD :: [Pot] inputData = "#...#..###.#.###.####.####.#..#.##..#..##..#.....#.#.#.##.#...###.#..##..#.##..###..#..##.#..##..." iD = replicate (length inputData) '.' ++ inputData ++ replicate (length inputData * 2) '.' match :: [Pot] -> Pot match "...#." = '#' match "#..##" = '#' match "....." = '.' match "##.##" = '.' match ".##.." = '#' match ".##.#" = '.' match "####." = '#' match ".#.#." = '.' match "..#.#" = '.' match ".#.##" = '.' match ".#..#" = '.' match "##..." = '#' match "#...#" = '#' match "#####" = '.' match "#.###" = '#' match "..###" = '#' match "###.." = '.' match "#.#.#" = '#' match "##..#" = '#' match "..#.." = '#' match ".####" = '.' match "#.##." = '.' match "....#" = '.' match "...##" = '.' match "#...." = '.' match "#..#." = '.' match "..##." = '.' match "###.#" = '#' match "#.#.." = '#' match "##.#." = '#' match ".###." = '.' match ".#..." = '.' match _ = '.' subString :: [Pot]-> Int -> [Pot] subString str i = (take 5 . drop (i - 2 + length inputData)) str evolveRow :: [Pot] -> [Pot] evolveRow row = map (match . subString row) [(negate l) .. (l*3)] where l = length inputData evolver :: [Pot] -> Int -> [Pot] evolver row 0 = row evolver row i = evolver (evolveRow row) (i - 1) --failed attempt in finding a loop findFixedPoint :: [Pot] -> [[Pot]] -> [Pot] findFixedPoint row seen | evolved `elem` seen = evolved | otherwise = findFixedPoint evolved (evolved:seen) where evolved = evolveRow row plantSum :: [Pot] -> Int -> Int plantSum [] _ = 0 plantSum (x:xs) i | x == '#' = i + plantSum xs (i+1) | otherwise = plantSum xs (i+1) At 100 there is an steady increase of 22 per evolve results 2675 2697 2719 2741 Value at 100 + ( 50000000000 - 100 ) left iterations * increase per evolve resultP1 :: Int resultP1 = plantSum (evolver iD 20) ((negate . length) inputData) resultP2 = 2675 + (50000000000 - 100) * 22
null
https://raw.githubusercontent.com/bzuilhof/AdventOfCode/e6ff762c1c766e028fb90ef62b8f4dc4adf9ecc1/2018/day12.hs
haskell
failed attempt in finding a loop
module Day12 where import Data.List import Data.Char import Data.Maybe import Data.Array type Pot = Char inputData, iD :: [Pot] inputData = "#...#..###.#.###.####.####.#..#.##..#..##..#.....#.#.#.##.#...###.#..##..#.##..###..#..##.#..##..." iD = replicate (length inputData) '.' ++ inputData ++ replicate (length inputData * 2) '.' match :: [Pot] -> Pot match "...#." = '#' match "#..##" = '#' match "....." = '.' match "##.##" = '.' match ".##.." = '#' match ".##.#" = '.' match "####." = '#' match ".#.#." = '.' match "..#.#" = '.' match ".#.##" = '.' match ".#..#" = '.' match "##..." = '#' match "#...#" = '#' match "#####" = '.' match "#.###" = '#' match "..###" = '#' match "###.." = '.' match "#.#.#" = '#' match "##..#" = '#' match "..#.." = '#' match ".####" = '.' match "#.##." = '.' match "....#" = '.' match "...##" = '.' match "#...." = '.' match "#..#." = '.' match "..##." = '.' match "###.#" = '#' match "#.#.." = '#' match "##.#." = '#' match ".###." = '.' match ".#..." = '.' match _ = '.' subString :: [Pot]-> Int -> [Pot] subString str i = (take 5 . drop (i - 2 + length inputData)) str evolveRow :: [Pot] -> [Pot] evolveRow row = map (match . subString row) [(negate l) .. (l*3)] where l = length inputData evolver :: [Pot] -> Int -> [Pot] evolver row 0 = row evolver row i = evolver (evolveRow row) (i - 1) findFixedPoint :: [Pot] -> [[Pot]] -> [Pot] findFixedPoint row seen | evolved `elem` seen = evolved | otherwise = findFixedPoint evolved (evolved:seen) where evolved = evolveRow row plantSum :: [Pot] -> Int -> Int plantSum [] _ = 0 plantSum (x:xs) i | x == '#' = i + plantSum xs (i+1) | otherwise = plantSum xs (i+1) At 100 there is an steady increase of 22 per evolve results 2675 2697 2719 2741 Value at 100 + ( 50000000000 - 100 ) left iterations * increase per evolve resultP1 :: Int resultP1 = plantSum (evolver iD 20) ((negate . length) inputData) resultP2 = 2675 + (50000000000 - 100) * 22
d27b68037d304e581660323e20e04e5e6c287c00593d33391503bb2994797f4d
jscl-project/jscl
closette.lisp
-*-Mode : LISP ; Package : ( CLOSETTE : USE LISP ) ; ; Syntax : Common - lisp -*- ;;; Closette Version 1.0 ( February 10 , 1991 ) ;;; Minor revisions of September 27 , 1991 by : ;;; - remove spurious "&key" in header of initialize-instance method ;;; for standard-class (bottom of pg.310 of AMOP) ;;; - add recommendation about not compiling this file - change comment to reflect PARC ftp server name change - add a BOA constructor to std - instance to please AKCL ;;; - by default, efunctuate methods rather than compile them ;;; - also make minor changes to newcl.lisp ;;; Copyright ( c ) 1990 , 1991 Xerox Corporation . ;;; All rights reserved. ;;; ;;; Use and copying of this software and preparation of derivative works ;;; based upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United ;;; States export control laws. ;;; This software is made available AS IS , and Xerox Corporation makes no ;;; warranty about the software, its performance or its conformity to any ;;; specification. ;;; ;;; Closette is an implementation of a subset of CLOS with a metaobject protocol as described in " The Art of The Metaobject Protocol " , MIT Press , 1991 . ;;; This program is available by anonymous FTP , from the /pub / pcl / mop ;;; directory on parcftp.xerox.com. ;;; This is the file closette.lisp ;;; N.B. Load this source file directly, rather than trying to compile it. (in-package 'closette :use '(lisp)) ;;; When running in a Common Lisp that doesn't yet support function names like ( setf foo ) , you should first load the file newcl.lisp . This next little ;;; bit imports stuff from there as needed. #-Genera (import '(newcl:print-unreadable-object)) #-Genera (shadowing-import '(newcl:defun newcl:fboundp newcl:fmakunbound newcl:fdefinition)) #-Genera (export '(newcl:defun newcl:fboundp newcl:fmakunbound newcl:fdefinition)) #+Genera (shadowing-import '(future-common-lisp:setf future-common-lisp:fboundp future-common-lisp:fmakunbound future-common-lisp:fdefinition future-common-lisp:print-unreadable-object)) #+Genera (export '(future-common-lisp:setf future-common-lisp:fboundp future-common-lisp:fmakunbound future-common-lisp:fdefinition future-common-lisp:print-unreadable-object)) (defvar exports '(defclass defgeneric defmethod find-class class-of call-next-method next-method-p slot-value slot-boundp slot-exists-p slot-makunbound make-instance change-class initialize-instance reinitialize-instance shared-initialize update-instance-for-different-class print-object standard-object standard-class standard-generic-function standard-method class-name class-direct-superclasses class-direct-slots class-precedence-list class-slots class-direct-subclasses class-direct-methods generic-function-name generic-function-lambda-list generic-function-methods generic-function-discriminating-function generic-function-method-class method-lambda-list method-qualifiers method-specializers method-body method-environment method-generic-function method-function slot-definition-name slot-definition-initfunction slot-definition-initform slot-definition-initargs slot-definition-readers slot-definition-writers slot-definition-allocation ;; ;; Class-related metaobject protocol ;; compute-class-precedence-list compute-slots compute-effective-slot-definition finalize-inheritance allocate-instance slot-value-using-class slot-boundp-using-class slot-exists-p-using-class slot-makunbound-using-class ;; Generic function related metaobject protocol ;; compute-discriminating-function compute-applicable-methods-using-classes method-more-specific-p compute-effective-method-function compute-method-function apply-methods apply-method find-generic-function ; Necessary artifact of this implementation )) (export exports) ;;; Utilities ;;; ;;; push-on-end is like push except it uses the other end: (defmacro push-on-end (value location) `(setf ,location (nconc ,location (list ,value)))) ( setf getf * ) is like ( setf getf ) except that it always changes the list , ;;; which must be non-nil. (defun (setf getf*) (new-value plist key) (block body (do ((x plist (cddr x))) ((null x)) (when (eq (car x) key) (setf (car (cdr x)) new-value) (return-from body new-value))) (push-on-end key plist) (push-on-end new-value plist) new-value)) ;;; mapappend is like mapcar except that the results are appended together: (defun mapappend (fun &rest args) (if (some #'null args) () (append (apply fun (mapcar #'car args)) (apply #'mapappend fun (mapcar #'cdr args))))) ;;; mapplist is mapcar for property lists: (defun mapplist (fun x) (if (null x) () (cons (funcall fun (car x) (cadr x)) (mapplist fun (cddr x))))) ;;; ;;; Standard instances ;;; ;;; This implementation uses structures for instances, because they're the only ;;; kind of Lisp object that can be easily made to print whatever way we want. (defstruct (std-instance (:constructor allocate-std-instance (class slots)) #+kcl (:constructor make-std-instance-for-sharp-s) (:predicate std-instance-p) (:print-function print-std-instance)) class slots) (defun print-std-instance (instance stream depth) (declare (ignore depth)) (print-object instance stream)) ;;; Standard instance allocation (defparameter secret-unbound-value (list "slot unbound")) (defun instance-slot-p (slot) (eq (slot-definition-allocation slot) ':instance)) (defun std-allocate-instance (class) (allocate-std-instance class (allocate-slot-storage (count-if #'instance-slot-p (class-slots class)) secret-unbound-value))) ;;; Simple vectors are used for slot storage. (defun allocate-slot-storage (size initial-value) (make-array size :initial-element initial-value)) ;;; Standard instance slot access ;;; N.B. The location of the effective-slots slots in the class metaobject for ;;; standard-class must be determined without making any further slot ;;; references. (defvar the-slots-of-standard-class) ;standard-class's class-slots standard - class 's class metaobject (defun slot-location (class slot-name) (if (and (eq slot-name 'effective-slots) (eq class the-class-standard-class)) (position 'effective-slots the-slots-of-standard-class :key #'slot-definition-name) (let ((slot (find slot-name (class-slots class) :key #'slot-definition-name))) (if (null slot) (error "The slot ~S is missing from the class ~S." slot-name class) (let ((pos (position slot (remove-if-not #'instance-slot-p (class-slots class))))) (if (null pos) (error "The slot ~S is not an instance~@ slot in the class ~S." slot-name class) pos)))))) (defun slot-contents (slots location) (svref slots location)) (defun (setf slot-contents) (new-value slots location) (setf (svref slots location) new-value)) (defun std-slot-value (instance slot-name) (let* ((location (slot-location (class-of instance) slot-name)) (slots (std-instance-slots instance)) (val (slot-contents slots location))) (if (eq secret-unbound-value val) (error "The slot ~S is unbound in the object ~S." slot-name instance) val))) (defun slot-value (object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (std-slot-value object slot-name) (slot-value-using-class (class-of object) object slot-name))) (defun (setf std-slot-value) (new-value instance slot-name) (let ((location (slot-location (class-of instance) slot-name)) (slots (std-instance-slots instance))) (setf (slot-contents slots location) new-value))) (defun (setf slot-value) (new-value object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (setf (std-slot-value object slot-name) new-value) (setf-slot-value-using-class new-value (class-of object) object slot-name))) (defun std-slot-boundp (instance slot-name) (let ((location (slot-location (class-of instance) slot-name)) (slots (std-instance-slots instance))) (not (eq secret-unbound-value (slot-contents slots location))))) (defun slot-boundp (object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (std-slot-boundp object slot-name) (slot-boundp-using-class (class-of object) object slot-name))) (defun std-slot-makunbound (instance slot-name) (let ((location (slot-location (class-of instance) slot-name)) (slots (std-instance-slots instance))) (setf (slot-contents slots location) secret-unbound-value)) instance) (defun slot-makunbound (object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (std-slot-makunbound object slot-name) (slot-makunbound-using-class (class-of object) object slot-name))) (defun std-slot-exists-p (instance slot-name) (not (null (find slot-name (class-slots (class-of instance)) :key #'slot-definition-name)))) (defun slot-exists-p (object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (std-slot-exists-p object slot-name) (slot-exists-p-using-class (class-of object) object slot-name))) ;;; class-of (defun class-of (x) (if (std-instance-p x) (std-instance-class x) (built-in-class-of x))) ;;; N.B. This version of built-in-class-of is straightforward but very slow. (defun built-in-class-of (x) (typecase x (null (find-class 'null)) ((and symbol (not null)) (find-class 'symbol)) ((complex *) (find-class 'complex)) ((integer * *) (find-class 'integer)) ((float * *) (find-class 'float)) (cons (find-class 'cons)) (character (find-class 'character)) (hash-table (find-class 'hash-table)) (package (find-class 'package)) (pathname (find-class 'pathname)) (readtable (find-class 'readtable)) (stream (find-class 'stream)) ((and number (not (or integer complex float))) (find-class 'number)) ((string *) (find-class 'string)) ((bit-vector *) (find-class 'bit-vector)) ((and (vector * *) (not (or string vector))) (find-class 'vector)) ((and (array * *) (not vector)) (find-class 'array)) ((and sequence (not (or vector list))) (find-class 'sequence)) (function (find-class 'function)) (t (find-class 't)))) ;;; subclassp and sub-specializer-p (defun subclassp (c1 c2) (not (null (find c2 (class-precedence-list c1))))) (defun sub-specializer-p (c1 c2 c-arg) (let ((cpl (class-precedence-list c-arg))) (not (null (find c2 (cdr (member c1 cpl))))))) ;;; ;;; Class metaobjects and standard-class ;;; (defparameter the-defclass-standard-class ;standard-class's defclass form '(defclass standard-class () ((name :initarg :name) ; :accessor class-name : accessor class - direct - superclasses :initarg :direct-superclasses) (direct-slots) ; :accessor class-direct-slots (class-precedence-list) ; :accessor class-precedence-list (effective-slots) ; :accessor class-slots (direct-subclasses :initform ()) ; :accessor class-direct-subclasses (direct-methods :initform ())))) ; :accessor class-direct-methods Defining the metaobject slot accessor function as regular functions ;;; greatly simplifies the implementation without removing functionality. (defun class-name (class) (std-slot-value class 'name)) (defun (setf class-name) (new-value class) (setf (slot-value class 'name) new-value)) (defun class-direct-superclasses (class) (slot-value class 'direct-superclasses)) (defun (setf class-direct-superclasses) (new-value class) (setf (slot-value class 'direct-superclasses) new-value)) (defun class-direct-slots (class) (slot-value class 'direct-slots)) (defun (setf class-direct-slots) (new-value class) (setf (slot-value class 'direct-slots) new-value)) (defun class-precedence-list (class) (slot-value class 'class-precedence-list)) (defun (setf class-precedence-list) (new-value class) (setf (slot-value class 'class-precedence-list) new-value)) (defun class-slots (class) (slot-value class 'effective-slots)) (defun (setf class-slots) (new-value class) (setf (slot-value class 'effective-slots) new-value)) (defun class-direct-subclasses (class) (slot-value class 'direct-subclasses)) (defun (setf class-direct-subclasses) (new-value class) (setf (slot-value class 'direct-subclasses) new-value)) (defun class-direct-methods (class) (slot-value class 'direct-methods)) (defun (setf class-direct-methods) (new-value class) (setf (slot-value class 'direct-methods) new-value)) ;;; defclass (defmacro defclass (name direct-superclasses direct-slots &rest options) `(ensure-class ',name :direct-superclasses ,(canonicalize-direct-superclasses direct-superclasses) :direct-slots ,(canonicalize-direct-slots direct-slots) ,@(canonicalize-defclass-options options))) (defun canonicalize-direct-slots (direct-slots) `(list ,@(mapcar #'canonicalize-direct-slot direct-slots))) (defun canonicalize-direct-slot (spec) (if (symbolp spec) `(list :name ',spec) (let ((name (car spec)) (initfunction nil) (initform nil) (initargs ()) (readers ()) (writers ()) (other-options ())) (do ((olist (cdr spec) (cddr olist))) ((null olist)) (case (car olist) (:initform (setq initfunction `(function (lambda () ,(cadr olist)))) (setq initform `',(cadr olist))) (:initarg (push-on-end (cadr olist) initargs)) (:reader (push-on-end (cadr olist) readers)) (:writer (push-on-end (cadr olist) writers)) (:accessor (push-on-end (cadr olist) readers) (push-on-end `(setf ,(cadr olist)) writers)) (otherwise (push-on-end `',(car olist) other-options) (push-on-end `',(cadr olist) other-options)))) `(list :name ',name ,@(when initfunction `(:initform ,initform :initfunction ,initfunction)) ,@(when initargs `(:initargs ',initargs)) ,@(when readers `(:readers ',readers)) ,@(when writers `(:writers ',writers)) ,@other-options)))) (defun canonicalize-direct-superclasses (direct-superclasses) `(list ,@(mapcar #'canonicalize-direct-superclass direct-superclasses))) (defun canonicalize-direct-superclass (class-name) `(find-class ',class-name)) (defun canonicalize-defclass-options (options) (mapappend #'canonicalize-defclass-option options)) (defun canonicalize-defclass-option (option) (case (car option) (:metaclass (list ':metaclass `(find-class ',(cadr option)))) (:default-initargs (list ':direct-default-initargs `(list ,@(mapappend #'(lambda (x) x) (mapplist #'(lambda (key value) `(',key ,value)) (cdr option)))))) (t (list `',(car option) `',(cadr option))))) ;;; find-class (let ((class-table (make-hash-table :test #'eq))) (defun find-class (symbol &optional (errorp t)) (let ((class (gethash symbol class-table nil))) (if (and (null class) errorp) (error "No class named ~S." symbol) class))) (defun (setf find-class) (new-value symbol) (setf (gethash symbol class-table) new-value)) (defun forget-all-classes () (clrhash class-table) (values)) ) ;end let class-table ;;; Ensure class (defun ensure-class (name &rest all-keys &key (metaclass the-class-standard-class) &allow-other-keys) (if (find-class name nil) (error "Can't redefine the class named ~S." name) (let ((class (apply (if (eq metaclass the-class-standard-class) #'make-instance-standard-class #'make-instance) metaclass :name name all-keys))) (setf (find-class name) class) class))) ;;; make-instance-standard-class creates and initializes an instance of ;;; standard-class without falling into method lookup. However, it cannot be ;;; called until standard-class itself exists. (defun make-instance-standard-class (metaclass &key name direct-superclasses direct-slots &allow-other-keys) (declare (ignore metaclass)) (let ((class (std-allocate-instance the-class-standard-class))) (setf (class-name class) name) (setf (class-direct-subclasses class) ()) (setf (class-direct-methods class) ()) (std-after-initialization-for-classes class :direct-slots direct-slots :direct-superclasses direct-superclasses) class)) (defun std-after-initialization-for-classes (class &key direct-superclasses direct-slots &allow-other-keys) (let ((supers (or direct-superclasses (list (find-class 'standard-object))))) (setf (class-direct-superclasses class) supers) (dolist (superclass supers) (push class (class-direct-subclasses superclass)))) (let ((slots (mapcar #'(lambda (slot-properties) (apply #'make-direct-slot-definition slot-properties)) direct-slots))) (setf (class-direct-slots class) slots) (dolist (direct-slot slots) (dolist (reader (slot-definition-readers direct-slot)) (add-reader-method class reader (slot-definition-name direct-slot))) (dolist (writer (slot-definition-writers direct-slot)) (add-writer-method class writer (slot-definition-name direct-slot))))) (funcall (if (eq (class-of class) the-class-standard-class) #'std-finalize-inheritance #'finalize-inheritance) class) (values)) Slot definition retain all unknown slot options ( rather than signaling an ;;; error), so that it's easy to add new ones. (defun make-direct-slot-definition (&rest properties &key name (initargs ()) (initform nil) (initfunction nil) (readers ()) (writers ()) (allocation :instance) &allow-other-keys) (let ((slot (copy-list properties))) ; Don't want to side effect &rest list (setf (getf* slot ':name) name) (setf (getf* slot ':initargs) initargs) (setf (getf* slot ':initform) initform) (setf (getf* slot ':initfunction) initfunction) (setf (getf* slot ':readers) readers) (setf (getf* slot ':writers) writers) (setf (getf* slot ':allocation) allocation) slot)) (defun make-effective-slot-definition (&rest properties &key name (initargs ()) (initform nil) (initfunction nil) (allocation :instance) &allow-other-keys) (let ((slot (copy-list properties))) ; Don't want to side effect &rest list (setf (getf* slot ':name) name) (setf (getf* slot ':initargs) initargs) (setf (getf* slot ':initform) initform) (setf (getf* slot ':initfunction) initfunction) (setf (getf* slot ':allocation) allocation) slot)) (defun slot-definition-name (slot) (getf slot ':name)) (defun (setf slot-definition-name) (new-value slot) (setf (getf* slot ':name) new-value)) (defun slot-definition-initfunction (slot) (getf slot ':initfunction)) (defun (setf slot-definition-initfunction) (new-value slot) (setf (getf* slot ':initfunction) new-value)) (defun slot-definition-initform (slot) (getf slot ':initform)) (defun (setf slot-definition-initform) (new-value slot) (setf (getf* slot ':initform) new-value)) (defun slot-definition-initargs (slot) (getf slot ':initargs)) (defun (setf slot-definition-initargs) (new-value slot) (setf (getf* slot ':initargs) new-value)) (defun slot-definition-readers (slot) (getf slot ':readers)) (defun (setf slot-definition-readers) (new-value slot) (setf (getf* slot ':readers) new-value)) (defun slot-definition-writers (slot) (getf slot ':writers)) (defun (setf slot-definition-writers) (new-value slot) (setf (getf* slot ':writers) new-value)) (defun slot-definition-allocation (slot) (getf slot ':allocation)) (defun (setf slot-definition-allocation) (new-value slot) (setf (getf* slot ':allocation) new-value)) ;;; finalize-inheritance (defun std-finalize-inheritance (class) (setf (class-precedence-list class) (funcall (if (eq (class-of class) the-class-standard-class) #'std-compute-class-precedence-list #'compute-class-precedence-list) class)) (setf (class-slots class) (funcall (if (eq (class-of class) the-class-standard-class) #'std-compute-slots #'compute-slots) class)) (values)) ;;; Class precedence lists (defun std-compute-class-precedence-list (class) (let ((classes-to-order (collect-superclasses* class))) (topological-sort classes-to-order (remove-duplicates (mapappend #'local-precedence-ordering classes-to-order)) #'std-tie-breaker-rule))) ;;; topological-sort implements the standard algorithm for topologically ;;; sorting an arbitrary set of elements while honoring the precedence ;;; constraints given by a set of (X,Y) pairs that indicate that element ;;; X must precede element Y. The tie-breaker procedure is called when it ;;; is necessary to choose from multiple minimal elements; both a list of ;;; candidates and the ordering so far are provided as arguments. (defun topological-sort (elements constraints tie-breaker) (let ((remaining-constraints constraints) (remaining-elements elements) (result ())) (loop (let ((minimal-elements (remove-if #'(lambda (class) (member class remaining-constraints :key #'cadr)) remaining-elements))) (when (null minimal-elements) (if (null remaining-elements) (return-from topological-sort result) (error "Inconsistent precedence graph."))) (let ((choice (if (null (cdr minimal-elements)) (car minimal-elements) (funcall tie-breaker minimal-elements result)))) (setq result (append result (list choice))) (setq remaining-elements (remove choice remaining-elements)) (setq remaining-constraints (remove choice remaining-constraints :test #'member))))))) ;;; In the event of a tie while topologically sorting class precedence lists, the CLOS Specification says to " select the one that has a direct subclass ;;; rightmost in the class precedence list computed so far." The same result ;;; is obtained by inspecting the partially constructed class precedence list from right to left , looking for the first minimal element to show up among the direct superclasses of the class precedence list constituent . ;;; (There's a lemma that shows that this rule yields a unique result.) (defun std-tie-breaker-rule (minimal-elements cpl-so-far) (dolist (cpl-constituent (reverse cpl-so-far)) (let* ((supers (class-direct-superclasses cpl-constituent)) (common (intersection minimal-elements supers))) (when (not (null common)) (return-from std-tie-breaker-rule (car common)))))) ;;; This version of collect-superclasses* isn't bothered by cycles in the class ;;; hierarchy, which sometimes happen by accident. (defun collect-superclasses* (class) (labels ((all-superclasses-loop (seen superclasses) (let ((to-be-processed (set-difference superclasses seen))) (if (null to-be-processed) superclasses (let ((class-to-process (car to-be-processed))) (all-superclasses-loop (cons class-to-process seen) (union (class-direct-superclasses class-to-process) superclasses))))))) (all-superclasses-loop () (list class)))) The local precedence ordering of a class C with direct superclasses C_1 , ;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)). (defun local-precedence-ordering (class) (mapcar #'list (cons class (butlast (class-direct-superclasses class))) (class-direct-superclasses class))) ;;; Slot inheritance (defun std-compute-slots (class) (let* ((all-slots (mapappend #'class-direct-slots (class-precedence-list class))) (all-names (remove-duplicates (mapcar #'slot-definition-name all-slots)))) (mapcar #'(lambda (name) (funcall (if (eq (class-of class) the-class-standard-class) #'std-compute-effective-slot-definition #'compute-effective-slot-definition) class (remove name all-slots :key #'slot-definition-name :test-not #'eq))) all-names))) (defun std-compute-effective-slot-definition (class direct-slots) (declare (ignore class)) (let ((initer (find-if-not #'null direct-slots :key #'slot-definition-initfunction))) (make-effective-slot-definition :name (slot-definition-name (car direct-slots)) :initform (if initer (slot-definition-initform initer) nil) :initfunction (if initer (slot-definition-initfunction initer) nil) :initargs (remove-duplicates (mapappend #'slot-definition-initargs direct-slots)) :allocation (slot-definition-allocation (car direct-slots))))) ;;; Generic function metaobjects and standard - generic - function ;;; (defparameter the-defclass-standard-generic-function '(defclass standard-generic-function () ((name :initarg :name) ; :accessor generic-function-name (lambda-list ; :accessor generic-function-lambda-list :initarg :lambda-list) (methods :initform ()) ; :accessor generic-function-methods (method-class ; :accessor generic-function-method-class :initarg :method-class) (discriminating-function) ; :accessor generic-function- ; -discriminating-function (classes-to-emf-table ; :accessor classes-to-emf-table :initform (make-hash-table :test #'equal))))) standard - generic - function 's class metaobject (defun generic-function-name (gf) (slot-value gf 'name)) (defun (setf generic-function-name) (new-value gf) (setf (slot-value gf 'name) new-value)) (defun generic-function-lambda-list (gf) (slot-value gf 'lambda-list)) (defun (setf generic-function-lambda-list) (new-value gf) (setf (slot-value gf 'lambda-list) new-value)) (defun generic-function-methods (gf) (slot-value gf 'methods)) (defun (setf generic-function-methods) (new-value gf) (setf (slot-value gf 'methods) new-value)) (defun generic-function-discriminating-function (gf) (slot-value gf 'discriminating-function)) (defun (setf generic-function-discriminating-function) (new-value gf) (setf (slot-value gf 'discriminating-function) new-value)) (defun generic-function-method-class (gf) (slot-value gf 'method-class)) (defun (setf generic-function-method-class) (new-value gf) (setf (slot-value gf 'method-class) new-value)) Internal accessor for effective method function table (defun classes-to-emf-table (gf) (slot-value gf 'classes-to-emf-table)) (defun (setf classes-to-emf-table) (new-value gf) (setf (slot-value gf 'classes-to-emf-table) new-value)) ;;; ;;; Method metaobjects and standard-method ;;; (defparameter the-defclass-standard-method '(defclass standard-method () ((lambda-list :initarg :lambda-list) ; :accessor method-lambda-list (qualifiers :initarg :qualifiers) ; :accessor method-qualifiers (specializers :initarg :specializers) ; :accessor method-specializers (body :initarg :body) ; :accessor method-body (environment :initarg :environment) ; :accessor method-environment (generic-function :initform nil) ; :accessor method-generic-function (function)))) ; :accessor method-function standard - method 's class metaobject (defun method-lambda-list (method) (slot-value method 'lambda-list)) (defun (setf method-lambda-list) (new-value method) (setf (slot-value method 'lambda-list) new-value)) (defun method-qualifiers (method) (slot-value method 'qualifiers)) (defun (setf method-qualifiers) (new-value method) (setf (slot-value method 'qualifiers) new-value)) (defun method-specializers (method) (slot-value method 'specializers)) (defun (setf method-specializers) (new-value method) (setf (slot-value method 'specializers) new-value)) (defun method-body (method) (slot-value method 'body)) (defun (setf method-body) (new-value method) (setf (slot-value method 'body) new-value)) (defun method-environment (method) (slot-value method 'environment)) (defun (setf method-environment) (new-value method) (setf (slot-value method 'environment) new-value)) (defun method-generic-function (method) (slot-value method 'generic-function)) (defun (setf method-generic-function) (new-value method) (setf (slot-value method 'generic-function) new-value)) (defun method-function (method) (slot-value method 'function)) (defun (setf method-function) (new-value method) (setf (slot-value method 'function) new-value)) ;;; defgeneric (defmacro defgeneric (function-name lambda-list &rest options) `(ensure-generic-function ',function-name :lambda-list ',lambda-list ,@(canonicalize-defgeneric-options options))) (defun canonicalize-defgeneric-options (options) (mapappend #'canonicalize-defgeneric-option options)) (defun canonicalize-defgeneric-option (option) (case (car option) (:generic-function-class (list ':generic-function-class `(find-class ',(cadr option)))) (:method-class (list ':method-class `(find-class ',(cadr option)))) (t (list `',(car option) `',(cadr option))))) ;;; find-generic-function looks up a generic function by name. It's an ;;; artifact of the fact that our generic function metaobjects can't legally ;;; be stored a symbol's function value. (let ((generic-function-table (make-hash-table :test #'equal))) (defun find-generic-function (symbol &optional (errorp t)) (let ((gf (gethash symbol generic-function-table nil))) (if (and (null gf) errorp) (error "No generic function named ~S." symbol) gf))) (defun (setf find-generic-function) (new-value symbol) (setf (gethash symbol generic-function-table) new-value)) (defun forget-all-generic-functions () (clrhash generic-function-table) (values)) ) ;end let generic-function-table ;;; ensure-generic-function (defun ensure-generic-function (function-name &rest all-keys &key (generic-function-class the-class-standard-gf) (method-class the-class-standard-method) &allow-other-keys) (if (find-generic-function function-name nil) (find-generic-function function-name) (let ((gf (apply (if (eq generic-function-class the-class-standard-gf) #'make-instance-standard-generic-function #'make-instance) generic-function-class :name function-name :method-class method-class all-keys))) (setf (find-generic-function function-name) gf) gf))) ;;; finalize-generic-function ;;; N.B. Same basic idea as finalize-inheritance. Takes care of recomputing ;;; and storing the discriminating function, and clearing the effective method ;;; function table. (defun finalize-generic-function (gf) (setf (generic-function-discriminating-function gf) (funcall (if (eq (class-of gf) the-class-standard-gf) #'std-compute-discriminating-function #'compute-discriminating-function) gf)) (setf (fdefinition (generic-function-name gf)) (generic-function-discriminating-function gf)) (clrhash (classes-to-emf-table gf)) (values)) ;;; make-instance-standard-generic-function creates and initializes an ;;; instance of standard-generic-function without falling into method lookup. ;;; However, it cannot be called until standard-generic-function exists. (defun make-instance-standard-generic-function (generic-function-class &key name lambda-list method-class) (declare (ignore generic-function-class)) (let ((gf (std-allocate-instance the-class-standard-gf))) (setf (generic-function-name gf) name) (setf (generic-function-lambda-list gf) lambda-list) (setf (generic-function-methods gf) ()) (setf (generic-function-method-class gf) method-class) (setf (classes-to-emf-table gf) (make-hash-table :test #'equal)) (finalize-generic-function gf) gf)) ;;; defmethod (defmacro defmethod (&rest args) (multiple-value-bind (function-name qualifiers lambda-list specializers body) (parse-defmethod args) `(ensure-method (find-generic-function ',function-name) :lambda-list ',lambda-list :qualifiers ',qualifiers :specializers ,(canonicalize-specializers specializers) :body ',body :environment (top-level-environment)))) (defun canonicalize-specializers (specializers) `(list ,@(mapcar #'canonicalize-specializer specializers))) (defun canonicalize-specializer (specializer) `(find-class ',specializer)) (defun parse-defmethod (args) (let ((fn-spec (car args)) (qualifiers ()) (specialized-lambda-list nil) (body ()) (parse-state :qualifiers)) (dolist (arg (cdr args)) (ecase parse-state (:qualifiers (if (and (atom arg) (not (null arg))) (push-on-end arg qualifiers) (progn (setq specialized-lambda-list arg) (setq parse-state :body)))) (:body (push-on-end arg body)))) (values fn-spec qualifiers (extract-lambda-list specialized-lambda-list) (extract-specializers specialized-lambda-list) (list* 'block (if (consp fn-spec) (cadr fn-spec) fn-spec) body)))) ;;; Several tedious functions for analyzing lambda lists (defun required-portion (gf args) (let ((number-required (length (gf-required-arglist gf)))) (when (< (length args) number-required) (error "Too few arguments to generic function ~S." gf)) (subseq args 0 number-required))) (defun gf-required-arglist (gf) (let ((plist (analyze-lambda-list (generic-function-lambda-list gf)))) (getf plist ':required-args))) (defun extract-lambda-list (specialized-lambda-list) (let* ((plist (analyze-lambda-list specialized-lambda-list)) (requireds (getf plist ':required-names)) (rv (getf plist ':rest-var)) (ks (getf plist ':key-args)) (aok (getf plist ':allow-other-keys)) (opts (getf plist ':optional-args)) (auxs (getf plist ':auxiliary-args))) `(,@requireds ,@(if rv `(&rest ,rv) ()) ,@(if (or ks aok) `(&key ,@ks) ()) ,@(if aok '(&allow-other-keys) ()) ,@(if opts `(&optional ,@opts) ()) ,@(if auxs `(&aux ,@auxs) ())))) (defun extract-specializers (specialized-lambda-list) (let ((plist (analyze-lambda-list specialized-lambda-list))) (getf plist ':specializers))) (defun analyze-lambda-list (lambda-list) (labels ((make-keyword (symbol) (intern (symbol-name symbol) (find-package 'keyword))) (get-keyword-from-arg (arg) (if (listp arg) (if (listp (car arg)) (caar arg) (make-keyword (car arg))) (make-keyword arg)))) (let ((keys ()) ; Just the keywords Keywords argument specs (required-names ()) ; Just the variable names (required-args ()) ; Variable names & specializers (specializers ()) ; Just the specializers (rest-var nil) (optionals ()) (auxs ()) (allow-other-keys nil) (state :parsing-required)) (dolist (arg lambda-list) (if (member arg lambda-list-keywords) (ecase arg (&optional (setq state :parsing-optional)) (&rest (setq state :parsing-rest)) (&key (setq state :parsing-key)) (&allow-other-keys (setq allow-other-keys 't)) (&aux (setq state :parsing-aux))) (case state (:parsing-required (push-on-end arg required-args) (if (listp arg) (progn (push-on-end (car arg) required-names) (push-on-end (cadr arg) specializers)) (progn (push-on-end arg required-names) (push-on-end 't specializers)))) (:parsing-optional (push-on-end arg optionals)) (:parsing-rest (setq rest-var arg)) (:parsing-key (push-on-end (get-keyword-from-arg arg) keys) (push-on-end arg key-args)) (:parsing-aux (push-on-end arg auxs))))) (list :required-names required-names :required-args required-args :specializers specializers :rest-var rest-var :keywords keys :key-args key-args :auxiliary-args auxs :optional-args optionals :allow-other-keys allow-other-keys)))) ;;; ensure method (defun ensure-method (gf &rest all-keys) (let ((new-method (apply (if (eq (generic-function-method-class gf) the-class-standard-method) #'make-instance-standard-method #'make-instance) (generic-function-method-class gf) all-keys))) (add-method gf new-method) new-method)) ;;; make-instance-standard-method creates and initializes an instance of ;;; standard-method without falling into method lookup. However, it cannot ;;; be called until standard-method exists. (defun make-instance-standard-method (method-class &key lambda-list qualifiers specializers body environment) (declare (ignore method-class)) (let ((method (std-allocate-instance the-class-standard-method))) (setf (method-lambda-list method) lambda-list) (setf (method-qualifiers method) qualifiers) (setf (method-specializers method) specializers) (setf (method-body method) body) (setf (method-environment method) environment) (setf (method-generic-function method) nil) (setf (method-function method) (std-compute-method-function method)) method)) ;;; add-method ;;; N.B. This version first removes any existing method on the generic function with the same qualifiers and specializers . It 's a pain to develop programs without this feature of full CLOS . (defun add-method (gf method) (let ((old-method (find-method gf (method-qualifiers method) (method-specializers method) nil))) (when old-method (remove-method gf old-method))) (setf (method-generic-function method) gf) (push method (generic-function-methods gf)) (dolist (specializer (method-specializers method)) (pushnew method (class-direct-methods specializer))) (finalize-generic-function gf) method) (defun remove-method (gf method) (setf (generic-function-methods gf) (remove method (generic-function-methods gf))) (setf (method-generic-function method) nil) (dolist (class (method-specializers method)) (setf (class-direct-methods class) (remove method (class-direct-methods class)))) (finalize-generic-function gf) method) (defun find-method (gf qualifiers specializers &optional (errorp t)) (let ((method (find-if #'(lambda (method) (and (equal qualifiers (method-qualifiers method)) (equal specializers (method-specializers method)))) (generic-function-methods gf)))) (if (and (null method) errorp) (error "No such method for ~S." (generic-function-name gf)) method))) ;;; Reader and write methods (defun add-reader-method (class fn-name slot-name) (ensure-method (ensure-generic-function fn-name :lambda-list '(object)) :lambda-list '(object) :qualifiers () :specializers (list class) :body `(slot-value object ',slot-name) :environment (top-level-environment)) (values)) (defun add-writer-method (class fn-name slot-name) (ensure-method (ensure-generic-function fn-name :lambda-list '(new-value object)) :lambda-list '(new-value object) :qualifiers () :specializers (list (find-class 't) class) :body `(setf (slot-value object ',slot-name) new-value) :environment (top-level-environment)) (values)) ;;; Generic function invocation ;;; ;;; apply-generic-function (defun apply-generic-function (gf args) (apply (generic-function-discriminating-function gf) args)) ;;; compute-discriminating-function (defun std-compute-discriminating-function (gf) #'(lambda (&rest args) (let* ((classes (mapcar #'class-of (required-portion gf args))) (emfun (gethash classes (classes-to-emf-table gf) nil))) (if emfun (funcall emfun args) (slow-method-lookup gf args classes))))) (defun slow-method-lookup (gf args classes) (let* ((applicable-methods (compute-applicable-methods-using-classes gf classes)) (emfun (funcall (if (eq (class-of gf) the-class-standard-gf) #'std-compute-effective-method-function #'compute-effective-method-function) gf applicable-methods))) (setf (gethash classes (classes-to-emf-table gf)) emfun) (funcall emfun args))) ;;; compute-applicable-methods-using-classes (defun compute-applicable-methods-using-classes (gf required-classes) (sort (copy-list (remove-if-not #'(lambda (method) (every #'subclassp required-classes (method-specializers method))) (generic-function-methods gf))) #'(lambda (m1 m2) (funcall (if (eq (class-of gf) the-class-standard-gf) #'std-method-more-specific-p #'method-more-specific-p) gf m1 m2 required-classes)))) ;;; method-more-specific-p (defun std-method-more-specific-p (gf method1 method2 required-classes) (declare (ignore gf)) (mapc #'(lambda (spec1 spec2 arg-class) (unless (eq spec1 spec2) (return-from std-method-more-specific-p (sub-specializer-p spec1 spec2 arg-class)))) (method-specializers method1) (method-specializers method2) required-classes) nil) ;;; apply-methods and compute-effective-method-function (defun apply-methods (gf args methods) (funcall (compute-effective-method-function gf methods) args)) (defun primary-method-p (method) (null (method-qualifiers method))) (defun before-method-p (method) (equal '(:before) (method-qualifiers method))) (defun after-method-p (method) (equal '(:after) (method-qualifiers method))) (defun around-method-p (method) (equal '(:around) (method-qualifiers method))) (defun std-compute-effective-method-function (gf methods) (let ((primaries (remove-if-not #'primary-method-p methods)) (around (find-if #'around-method-p methods))) (when (null primaries) (error "No primary methods for the~@ generic function ~S." gf)) (if around (let ((next-emfun (funcall (if (eq (class-of gf) the-class-standard-gf) #'std-compute-effective-method-function #'compute-effective-method-function) gf (remove around methods)))) #'(lambda (args) (funcall (method-function around) args next-emfun))) (let ((next-emfun (compute-primary-emfun (cdr primaries))) (befores (remove-if-not #'before-method-p methods)) (reverse-afters (reverse (remove-if-not #'after-method-p methods)))) #'(lambda (args) (dolist (before befores) (funcall (method-function before) args nil)) (multiple-value-prog1 (funcall (method-function (car primaries)) args next-emfun) (dolist (after reverse-afters) (funcall (method-function after) args nil)))))))) ;;; compute an effective method function from a list of primary methods: (defun compute-primary-emfun (methods) (if (null methods) nil (let ((next-emfun (compute-primary-emfun (cdr methods)))) #'(lambda (args) (funcall (method-function (car methods)) args next-emfun))))) ;;; apply-method and compute-method-function (defun apply-method (method args next-methods) (funcall (method-function method) args (if (null next-methods) nil (compute-effective-method-function (method-generic-function method) next-methods)))) (defun std-compute-method-function (method) (let ((form (method-body method)) (lambda-list (method-lambda-list method))) (compile-in-lexical-environment (method-environment method) `(lambda (args next-emfun) (flet ((call-next-method (&rest cnm-args) (if (null next-emfun) (error "No next method for the~@ generic function ~S." (method-generic-function ',method)) (funcall next-emfun (or cnm-args args)))) (next-method-p () (not (null next-emfun)))) (apply #'(lambda ,(kludge-arglist lambda-list) ,form) args)))))) ;;; N.B. The function kludge-arglist is used to pave over the differences ;;; between argument keyword compatibility for regular functions versus ;;; generic functions. (defun kludge-arglist (lambda-list) (if (and (member '&key lambda-list) (not (member '&allow-other-keys lambda-list))) (append lambda-list '(&allow-other-keys)) (if (and (not (member '&rest lambda-list)) (not (member '&key lambda-list))) (append lambda-list '(&key &allow-other-keys)) lambda-list))) ;;; Run-time environment hacking (Common Lisp ain't got 'em). (defun top-level-environment () nil) ; Bogus top level lexical environment (defvar compile-methods nil) ; by default, run everything interpreted (defun compile-in-lexical-environment (env lambda-expr) (declare (ignore env)) (if compile-methods (compile nil lambda-expr) (eval `(function ,lambda-expr)))) ;;; ;;; Bootstrap ;;; (progn ; Extends to end-of-file (to avoid printing intermediate results). (format t "Beginning to bootstrap Closette...") (forget-all-classes) (forget-all-generic-functions) How to create the class hierarchy in 10 easy steps : 1 . Figure out standard - class 's slots . (setq the-slots-of-standard-class (mapcar #'(lambda (slotd) (make-effective-slot-definition :name (car slotd) :initargs (let ((a (getf (cdr slotd) ':initarg))) (if a (list a) ())) :initform (getf (cdr slotd) ':initform) :initfunction (let ((a (getf (cdr slotd) ':initform))) (if a #'(lambda () (eval a)) nil)) :allocation ':instance)) (nth 3 the-defclass-standard-class))) 2 . Create the standard - class metaobject by hand . (setq the-class-standard-class (allocate-std-instance 'tba (make-array (length the-slots-of-standard-class) :initial-element secret-unbound-value))) 3 . Install standard - class 's ( circular ) class - of link . (setf (std-instance-class the-class-standard-class) the-class-standard-class) ;; (It's now okay to use class-... accessor). 4 . Fill in standard - class 's class - slots . (setf (class-slots the-class-standard-class) the-slots-of-standard-class) ( Skeleton built ; it 's now okay to call make - instance - standard - class . ) 5 . Hand build the class t so that it has no direct superclasses . (setf (find-class 't) (let ((class (std-allocate-instance the-class-standard-class))) (setf (class-name class) 't) (setf (class-direct-subclasses class) ()) (setf (class-direct-superclasses class) ()) (setf (class-direct-methods class) ()) (setf (class-direct-slots class) ()) (setf (class-precedence-list class) (list class)) (setf (class-slots class) ()) class)) ;; (It's now okay to define subclasses of t.) 6 . Create the other superclass of standard - class ( i.e. , standard - object ) . (defclass standard-object (t) ()) 7 . Define the full - blown version of standard - class . (setq the-class-standard-class (eval the-defclass-standard-class)) 8 . Replace all ( 3 ) existing pointers to the skeleton with real one . (setf (std-instance-class (find-class 't)) the-class-standard-class) (setf (std-instance-class (find-class 'standard-object)) the-class-standard-class) (setf (std-instance-class the-class-standard-class) the-class-standard-class) ;; (Clear sailing from here on in). 9 . Define the other built - in classes . (defclass symbol (t) ()) (defclass sequence (t) ()) (defclass array (t) ()) (defclass number (t) ()) (defclass character (t) ()) (defclass function (t) ()) (defclass hash-table (t) ()) (defclass package (t) ()) (defclass pathname (t) ()) (defclass readtable (t) ()) (defclass stream (t) ()) (defclass list (sequence) ()) (defclass null (symbol list) ()) (defclass cons (list) ()) (defclass vector (array sequence) ()) (defclass bit-vector (vector) ()) (defclass string (vector) ()) (defclass complex (number) ()) (defclass integer (number) ()) (defclass float (number) ()) 10 . Define the other standard metaobject classes . (setq the-class-standard-gf (eval the-defclass-standard-generic-function)) (setq the-class-standard-method (eval the-defclass-standard-method)) ;; Voila! The class hierarchy is in place. (format t "Class hierarchy created.") ;; (It's now okay to define generic functions and methods.) (defgeneric print-object (instance stream)) (defmethod print-object ((instance standard-object) stream) (print-unreadable-object (instance stream :identity t) (format stream "~:(~S~)" (class-name (class-of instance)))) instance) ;;; Slot access (defgeneric slot-value-using-class (class instance slot-name)) (defmethod slot-value-using-class ((class standard-class) instance slot-name) (std-slot-value instance slot-name)) (defgeneric (setf slot-value-using-class) (new-value class instance slot-name)) (defmethod (setf slot-value-using-class) (new-value (class standard-class) instance slot-name) (setf (std-slot-value instance slot-name) new-value)) N.B. To avoid making a forward reference to a ( setf xxx ) generic function : (defun setf-slot-value-using-class (new-value class object slot-name) (setf (slot-value-using-class class object slot-name) new-value)) (defgeneric slot-exists-p-using-class (class instance slot-name)) (defmethod slot-exists-p-using-class ((class standard-class) instance slot-name) (std-slot-exists-p instance slot-name)) (defgeneric slot-boundp-using-class (class instance slot-name)) (defmethod slot-boundp-using-class ((class standard-class) instance slot-name) (std-slot-boundp instance slot-name)) (defgeneric slot-makunbound-using-class (class instance slot-name)) (defmethod slot-makunbound-using-class ((class standard-class) instance slot-name) (std-slot-makunbound instance slot-name)) ;;; Instance creation and initialization (defgeneric allocate-instance (class)) (defmethod allocate-instance ((class standard-class)) (std-allocate-instance class)) (defgeneric make-instance (class &key)) (defmethod make-instance ((class standard-class) &rest initargs) (let ((instance (allocate-instance class))) (apply #'initialize-instance instance initargs) instance)) (defmethod make-instance ((class symbol) &rest initargs) (apply #'make-instance (find-class class) initargs)) (defgeneric initialize-instance (instance &key)) (defmethod initialize-instance ((instance standard-object) &rest initargs) (apply #'shared-initialize instance t initargs)) (defgeneric reinitialize-instance (instance &key)) (defmethod reinitialize-instance ((instance standard-object) &rest initargs) (apply #'shared-initialize instance () initargs)) (defgeneric shared-initialize (instance slot-names &key)) (defmethod shared-initialize ((instance standard-object) slot-names &rest all-keys) (dolist (slot (class-slots (class-of instance))) (let ((slot-name (slot-definition-name slot))) (multiple-value-bind (init-key init-value foundp) (get-properties all-keys (slot-definition-initargs slot)) (declare (ignore init-key)) (if foundp (setf (slot-value instance slot-name) init-value) (when (and (not (slot-boundp instance slot-name)) (not (null (slot-definition-initfunction slot))) (or (eq slot-names t) (member slot-name slot-names))) (setf (slot-value instance slot-name) (funcall (slot-definition-initfunction slot)))))))) instance) ;;; change-class (defgeneric change-class (instance new-class &key)) (defmethod change-class ((old-instance standard-object) (new-class standard-class) &rest initargs) (let ((new-instance (allocate-instance new-class))) (dolist (slot-name (mapcar #'slot-definition-name (class-slots new-class))) (when (and (slot-exists-p old-instance slot-name) (slot-boundp old-instance slot-name)) (setf (slot-value new-instance slot-name) (slot-value old-instance slot-name)))) (rotatef (std-instance-slots new-instance) (std-instance-slots old-instance)) (rotatef (std-instance-class new-instance) (std-instance-class old-instance)) (apply #'update-instance-for-different-class new-instance old-instance initargs) old-instance)) (defmethod change-class ((instance standard-object) (new-class symbol) &rest initargs) (apply #'change-class instance (find-class new-class) initargs)) (defgeneric update-instance-for-different-class (old new &key)) (defmethod update-instance-for-different-class ((old standard-object) (new standard-object) &rest initargs) (let ((added-slots (remove-if #'(lambda (slot-name) (slot-exists-p old slot-name)) (mapcar #'slot-definition-name (class-slots (class-of new)))))) (apply #'shared-initialize new added-slots initargs))) ;;; ;;; Methods having to do with class metaobjects. ;;; (defmethod print-object ((class standard-class) stream) (print-unreadable-object (class stream :identity t) (format stream "~:(~S~) ~S" (class-name (class-of class)) (class-name class))) class) (defmethod initialize-instance :after ((class standard-class) &rest args) (apply #'std-after-initialization-for-classes class args)) Finalize inheritance (defgeneric finalize-inheritance (class)) (defmethod finalize-inheritance ((class standard-class)) (std-finalize-inheritance class) (values)) ;;; Class precedence lists (defgeneric compute-class-precedence-list (class)) (defmethod compute-class-precedence-list ((class standard-class)) (std-compute-class-precedence-list class)) ;;; Slot inheritance (defgeneric compute-slots (class)) (defmethod compute-slots ((class standard-class)) (std-compute-slots class)) (defgeneric compute-effective-slot-definition (class direct-slots)) (defmethod compute-effective-slot-definition ((class standard-class) direct-slots) (std-compute-effective-slot-definition class direct-slots)) ;;; ;;; Methods having to do with generic function metaobjects. ;;; (defmethod print-object ((gf standard-generic-function) stream) (print-unreadable-object (gf stream :identity t) (format stream "~:(~S~) ~S" (class-name (class-of gf)) (generic-function-name gf))) gf) (defmethod initialize-instance :after ((gf standard-generic-function) &key) (finalize-generic-function gf)) ;;; ;;; Methods having to do with method metaobjects. ;;; (defmethod print-object ((method standard-method) stream) (print-unreadable-object (method stream :identity t) (format stream "~:(~S~) ~S~{ ~S~} ~S" (class-name (class-of method)) (generic-function-name (method-generic-function method)) (method-qualifiers method) (mapcar #'class-name (method-specializers method)))) method) (defmethod initialize-instance :after ((method standard-method) &key) (setf (method-function method) (compute-method-function method))) ;;; ;;; Methods having to do with generic function invocation. ;;; (defgeneric compute-discriminating-function (gf)) (defmethod compute-discriminating-function ((gf standard-generic-function)) (std-compute-discriminating-function gf)) (defgeneric method-more-specific-p (gf method1 method2 required-classes)) (defmethod method-more-specific-p ((gf standard-generic-function) method1 method2 required-classes) (std-method-more-specific-p gf method1 method2 required-classes)) (defgeneric compute-effective-method-function (gf methods)) (defmethod compute-effective-method-function ((gf standard-generic-function) methods) (std-compute-effective-method-function gf methods)) (defgeneric compute-method-function (method)) (defmethod compute-method-function ((method standard-method)) (std-compute-method-function method)) ;;; describe-object is a handy tool for enquiring minds: (defgeneric describe-object (object stream)) (defmethod describe-object ((object standard-object) stream) (format t "A Closette object~ ~%Printed representation: ~S~ ~%Class: ~S~ ~%Structure " object (class-of object)) (dolist (sn (mapcar #'slot-definition-name (class-slots (class-of object)))) (format t "~% ~S <- ~:[not bound~;~S~]" sn (slot-boundp object sn) (and (slot-boundp object sn) (slot-value object sn)))) (values)) (defmethod describe-object ((object t) stream) (lisp:describe object) (values)) (format t "~%Closette is a Knights of the Lambda Calculus production.") (values)) ;end progn
null
https://raw.githubusercontent.com/jscl-project/jscl/d38eec2aeb47d04f1caf3d1cda82dc968d67c305/src/clos/closette/closette.lisp
lisp
Package : ( CLOSETTE : USE LISP ) ; ; Syntax : Common - lisp -*- - remove spurious "&key" in header of initialize-instance method for standard-class (bottom of pg.310 of AMOP) - add recommendation about not compiling this file - by default, efunctuate methods rather than compile them - also make minor changes to newcl.lisp All rights reserved. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this States export control laws. warranty about the software, its performance or its conformity to any specification. directory on parcftp.xerox.com. This is the file closette.lisp N.B. Load this source file directly, rather than trying to compile it. When running in a Common Lisp that doesn't yet support function names like bit imports stuff from there as needed. Class-related metaobject protocol Necessary artifact of this implementation push-on-end is like push except it uses the other end: which must be non-nil. mapappend is like mapcar except that the results are appended together: mapplist is mapcar for property lists: Standard instances This implementation uses structures for instances, because they're the only kind of Lisp object that can be easily made to print whatever way we want. Standard instance allocation Simple vectors are used for slot storage. Standard instance slot access N.B. The location of the effective-slots slots in the class metaobject for standard-class must be determined without making any further slot references. standard-class's class-slots class-of N.B. This version of built-in-class-of is straightforward but very slow. subclassp and sub-specializer-p Class metaobjects and standard-class standard-class's defclass form :accessor class-name :accessor class-direct-slots :accessor class-precedence-list :accessor class-slots :accessor class-direct-subclasses :accessor class-direct-methods greatly simplifies the implementation without removing functionality. defclass find-class end let class-table Ensure class make-instance-standard-class creates and initializes an instance of standard-class without falling into method lookup. However, it cannot be called until standard-class itself exists. error), so that it's easy to add new ones. Don't want to side effect &rest list Don't want to side effect &rest list finalize-inheritance Class precedence lists topological-sort implements the standard algorithm for topologically sorting an arbitrary set of elements while honoring the precedence constraints given by a set of (X,Y) pairs that indicate that element X must precede element Y. The tie-breaker procedure is called when it is necessary to choose from multiple minimal elements; both a list of candidates and the ordering so far are provided as arguments. In the event of a tie while topologically sorting class precedence lists, rightmost in the class precedence list computed so far." The same result is obtained by inspecting the partially constructed class precedence list (There's a lemma that shows that this rule yields a unique result.) This version of collect-superclasses* isn't bothered by cycles in the class hierarchy, which sometimes happen by accident. C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)). Slot inheritance :accessor generic-function-name :accessor generic-function-lambda-list :accessor generic-function-methods :accessor generic-function-method-class :accessor generic-function- -discriminating-function :accessor classes-to-emf-table Method metaobjects and standard-method :accessor method-lambda-list :accessor method-qualifiers :accessor method-specializers :accessor method-body :accessor method-environment :accessor method-generic-function :accessor method-function defgeneric find-generic-function looks up a generic function by name. It's an artifact of the fact that our generic function metaobjects can't legally be stored a symbol's function value. end let generic-function-table ensure-generic-function finalize-generic-function N.B. Same basic idea as finalize-inheritance. Takes care of recomputing and storing the discriminating function, and clearing the effective method function table. make-instance-standard-generic-function creates and initializes an instance of standard-generic-function without falling into method lookup. However, it cannot be called until standard-generic-function exists. defmethod Several tedious functions for analyzing lambda lists Just the keywords Just the variable names Variable names & specializers Just the specializers ensure method make-instance-standard-method creates and initializes an instance of standard-method without falling into method lookup. However, it cannot be called until standard-method exists. add-method N.B. This version first removes any existing method on the generic function Reader and write methods apply-generic-function compute-discriminating-function compute-applicable-methods-using-classes method-more-specific-p apply-methods and compute-effective-method-function compute an effective method function from a list of primary methods: apply-method and compute-method-function N.B. The function kludge-arglist is used to pave over the differences between argument keyword compatibility for regular functions versus generic functions. Run-time environment hacking (Common Lisp ain't got 'em). Bogus top level lexical environment by default, run everything interpreted Bootstrap Extends to end-of-file (to avoid printing intermediate results). (It's now okay to use class-... accessor). it 's now okay to call make - instance - standard - class . ) (It's now okay to define subclasses of t.) (Clear sailing from here on in). Voila! The class hierarchy is in place. (It's now okay to define generic functions and methods.) Slot access Instance creation and initialization change-class Methods having to do with class metaobjects. Class precedence lists Slot inheritance Methods having to do with generic function metaobjects. Methods having to do with method metaobjects. Methods having to do with generic function invocation. describe-object is a handy tool for enquiring minds: end progn
Closette Version 1.0 ( February 10 , 1991 ) Minor revisions of September 27 , 1991 by : - change comment to reflect PARC ftp server name change - add a BOA constructor to std - instance to please AKCL Copyright ( c ) 1990 , 1991 Xerox Corporation . software or derivative works must comply with all applicable United This software is made available AS IS , and Xerox Corporation makes no Closette is an implementation of a subset of CLOS with a metaobject protocol as described in " The Art of The Metaobject Protocol " , MIT Press , 1991 . This program is available by anonymous FTP , from the /pub / pcl / mop (in-package 'closette :use '(lisp)) ( setf foo ) , you should first load the file newcl.lisp . This next little #-Genera (import '(newcl:print-unreadable-object)) #-Genera (shadowing-import '(newcl:defun newcl:fboundp newcl:fmakunbound newcl:fdefinition)) #-Genera (export '(newcl:defun newcl:fboundp newcl:fmakunbound newcl:fdefinition)) #+Genera (shadowing-import '(future-common-lisp:setf future-common-lisp:fboundp future-common-lisp:fmakunbound future-common-lisp:fdefinition future-common-lisp:print-unreadable-object)) #+Genera (export '(future-common-lisp:setf future-common-lisp:fboundp future-common-lisp:fmakunbound future-common-lisp:fdefinition future-common-lisp:print-unreadable-object)) (defvar exports '(defclass defgeneric defmethod find-class class-of call-next-method next-method-p slot-value slot-boundp slot-exists-p slot-makunbound make-instance change-class initialize-instance reinitialize-instance shared-initialize update-instance-for-different-class print-object standard-object standard-class standard-generic-function standard-method class-name class-direct-superclasses class-direct-slots class-precedence-list class-slots class-direct-subclasses class-direct-methods generic-function-name generic-function-lambda-list generic-function-methods generic-function-discriminating-function generic-function-method-class method-lambda-list method-qualifiers method-specializers method-body method-environment method-generic-function method-function slot-definition-name slot-definition-initfunction slot-definition-initform slot-definition-initargs slot-definition-readers slot-definition-writers slot-definition-allocation compute-class-precedence-list compute-slots compute-effective-slot-definition finalize-inheritance allocate-instance slot-value-using-class slot-boundp-using-class slot-exists-p-using-class slot-makunbound-using-class Generic function related metaobject protocol compute-discriminating-function compute-applicable-methods-using-classes method-more-specific-p compute-effective-method-function compute-method-function apply-methods apply-method )) (export exports) Utilities (defmacro push-on-end (value location) `(setf ,location (nconc ,location (list ,value)))) ( setf getf * ) is like ( setf getf ) except that it always changes the list , (defun (setf getf*) (new-value plist key) (block body (do ((x plist (cddr x))) ((null x)) (when (eq (car x) key) (setf (car (cdr x)) new-value) (return-from body new-value))) (push-on-end key plist) (push-on-end new-value plist) new-value)) (defun mapappend (fun &rest args) (if (some #'null args) () (append (apply fun (mapcar #'car args)) (apply #'mapappend fun (mapcar #'cdr args))))) (defun mapplist (fun x) (if (null x) () (cons (funcall fun (car x) (cadr x)) (mapplist fun (cddr x))))) (defstruct (std-instance (:constructor allocate-std-instance (class slots)) #+kcl (:constructor make-std-instance-for-sharp-s) (:predicate std-instance-p) (:print-function print-std-instance)) class slots) (defun print-std-instance (instance stream depth) (declare (ignore depth)) (print-object instance stream)) (defparameter secret-unbound-value (list "slot unbound")) (defun instance-slot-p (slot) (eq (slot-definition-allocation slot) ':instance)) (defun std-allocate-instance (class) (allocate-std-instance class (allocate-slot-storage (count-if #'instance-slot-p (class-slots class)) secret-unbound-value))) (defun allocate-slot-storage (size initial-value) (make-array size :initial-element initial-value)) standard - class 's class metaobject (defun slot-location (class slot-name) (if (and (eq slot-name 'effective-slots) (eq class the-class-standard-class)) (position 'effective-slots the-slots-of-standard-class :key #'slot-definition-name) (let ((slot (find slot-name (class-slots class) :key #'slot-definition-name))) (if (null slot) (error "The slot ~S is missing from the class ~S." slot-name class) (let ((pos (position slot (remove-if-not #'instance-slot-p (class-slots class))))) (if (null pos) (error "The slot ~S is not an instance~@ slot in the class ~S." slot-name class) pos)))))) (defun slot-contents (slots location) (svref slots location)) (defun (setf slot-contents) (new-value slots location) (setf (svref slots location) new-value)) (defun std-slot-value (instance slot-name) (let* ((location (slot-location (class-of instance) slot-name)) (slots (std-instance-slots instance)) (val (slot-contents slots location))) (if (eq secret-unbound-value val) (error "The slot ~S is unbound in the object ~S." slot-name instance) val))) (defun slot-value (object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (std-slot-value object slot-name) (slot-value-using-class (class-of object) object slot-name))) (defun (setf std-slot-value) (new-value instance slot-name) (let ((location (slot-location (class-of instance) slot-name)) (slots (std-instance-slots instance))) (setf (slot-contents slots location) new-value))) (defun (setf slot-value) (new-value object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (setf (std-slot-value object slot-name) new-value) (setf-slot-value-using-class new-value (class-of object) object slot-name))) (defun std-slot-boundp (instance slot-name) (let ((location (slot-location (class-of instance) slot-name)) (slots (std-instance-slots instance))) (not (eq secret-unbound-value (slot-contents slots location))))) (defun slot-boundp (object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (std-slot-boundp object slot-name) (slot-boundp-using-class (class-of object) object slot-name))) (defun std-slot-makunbound (instance slot-name) (let ((location (slot-location (class-of instance) slot-name)) (slots (std-instance-slots instance))) (setf (slot-contents slots location) secret-unbound-value)) instance) (defun slot-makunbound (object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (std-slot-makunbound object slot-name) (slot-makunbound-using-class (class-of object) object slot-name))) (defun std-slot-exists-p (instance slot-name) (not (null (find slot-name (class-slots (class-of instance)) :key #'slot-definition-name)))) (defun slot-exists-p (object slot-name) (if (eq (class-of (class-of object)) the-class-standard-class) (std-slot-exists-p object slot-name) (slot-exists-p-using-class (class-of object) object slot-name))) (defun class-of (x) (if (std-instance-p x) (std-instance-class x) (built-in-class-of x))) (defun built-in-class-of (x) (typecase x (null (find-class 'null)) ((and symbol (not null)) (find-class 'symbol)) ((complex *) (find-class 'complex)) ((integer * *) (find-class 'integer)) ((float * *) (find-class 'float)) (cons (find-class 'cons)) (character (find-class 'character)) (hash-table (find-class 'hash-table)) (package (find-class 'package)) (pathname (find-class 'pathname)) (readtable (find-class 'readtable)) (stream (find-class 'stream)) ((and number (not (or integer complex float))) (find-class 'number)) ((string *) (find-class 'string)) ((bit-vector *) (find-class 'bit-vector)) ((and (vector * *) (not (or string vector))) (find-class 'vector)) ((and (array * *) (not vector)) (find-class 'array)) ((and sequence (not (or vector list))) (find-class 'sequence)) (function (find-class 'function)) (t (find-class 't)))) (defun subclassp (c1 c2) (not (null (find c2 (class-precedence-list c1))))) (defun sub-specializer-p (c1 c2 c-arg) (let ((cpl (class-precedence-list c-arg))) (not (null (find c2 (cdr (member c1 cpl))))))) '(defclass standard-class () : accessor class - direct - superclasses :initarg :direct-superclasses) Defining the metaobject slot accessor function as regular functions (defun class-name (class) (std-slot-value class 'name)) (defun (setf class-name) (new-value class) (setf (slot-value class 'name) new-value)) (defun class-direct-superclasses (class) (slot-value class 'direct-superclasses)) (defun (setf class-direct-superclasses) (new-value class) (setf (slot-value class 'direct-superclasses) new-value)) (defun class-direct-slots (class) (slot-value class 'direct-slots)) (defun (setf class-direct-slots) (new-value class) (setf (slot-value class 'direct-slots) new-value)) (defun class-precedence-list (class) (slot-value class 'class-precedence-list)) (defun (setf class-precedence-list) (new-value class) (setf (slot-value class 'class-precedence-list) new-value)) (defun class-slots (class) (slot-value class 'effective-slots)) (defun (setf class-slots) (new-value class) (setf (slot-value class 'effective-slots) new-value)) (defun class-direct-subclasses (class) (slot-value class 'direct-subclasses)) (defun (setf class-direct-subclasses) (new-value class) (setf (slot-value class 'direct-subclasses) new-value)) (defun class-direct-methods (class) (slot-value class 'direct-methods)) (defun (setf class-direct-methods) (new-value class) (setf (slot-value class 'direct-methods) new-value)) (defmacro defclass (name direct-superclasses direct-slots &rest options) `(ensure-class ',name :direct-superclasses ,(canonicalize-direct-superclasses direct-superclasses) :direct-slots ,(canonicalize-direct-slots direct-slots) ,@(canonicalize-defclass-options options))) (defun canonicalize-direct-slots (direct-slots) `(list ,@(mapcar #'canonicalize-direct-slot direct-slots))) (defun canonicalize-direct-slot (spec) (if (symbolp spec) `(list :name ',spec) (let ((name (car spec)) (initfunction nil) (initform nil) (initargs ()) (readers ()) (writers ()) (other-options ())) (do ((olist (cdr spec) (cddr olist))) ((null olist)) (case (car olist) (:initform (setq initfunction `(function (lambda () ,(cadr olist)))) (setq initform `',(cadr olist))) (:initarg (push-on-end (cadr olist) initargs)) (:reader (push-on-end (cadr olist) readers)) (:writer (push-on-end (cadr olist) writers)) (:accessor (push-on-end (cadr olist) readers) (push-on-end `(setf ,(cadr olist)) writers)) (otherwise (push-on-end `',(car olist) other-options) (push-on-end `',(cadr olist) other-options)))) `(list :name ',name ,@(when initfunction `(:initform ,initform :initfunction ,initfunction)) ,@(when initargs `(:initargs ',initargs)) ,@(when readers `(:readers ',readers)) ,@(when writers `(:writers ',writers)) ,@other-options)))) (defun canonicalize-direct-superclasses (direct-superclasses) `(list ,@(mapcar #'canonicalize-direct-superclass direct-superclasses))) (defun canonicalize-direct-superclass (class-name) `(find-class ',class-name)) (defun canonicalize-defclass-options (options) (mapappend #'canonicalize-defclass-option options)) (defun canonicalize-defclass-option (option) (case (car option) (:metaclass (list ':metaclass `(find-class ',(cadr option)))) (:default-initargs (list ':direct-default-initargs `(list ,@(mapappend #'(lambda (x) x) (mapplist #'(lambda (key value) `(',key ,value)) (cdr option)))))) (t (list `',(car option) `',(cadr option))))) (let ((class-table (make-hash-table :test #'eq))) (defun find-class (symbol &optional (errorp t)) (let ((class (gethash symbol class-table nil))) (if (and (null class) errorp) (error "No class named ~S." symbol) class))) (defun (setf find-class) (new-value symbol) (setf (gethash symbol class-table) new-value)) (defun forget-all-classes () (clrhash class-table) (values)) (defun ensure-class (name &rest all-keys &key (metaclass the-class-standard-class) &allow-other-keys) (if (find-class name nil) (error "Can't redefine the class named ~S." name) (let ((class (apply (if (eq metaclass the-class-standard-class) #'make-instance-standard-class #'make-instance) metaclass :name name all-keys))) (setf (find-class name) class) class))) (defun make-instance-standard-class (metaclass &key name direct-superclasses direct-slots &allow-other-keys) (declare (ignore metaclass)) (let ((class (std-allocate-instance the-class-standard-class))) (setf (class-name class) name) (setf (class-direct-subclasses class) ()) (setf (class-direct-methods class) ()) (std-after-initialization-for-classes class :direct-slots direct-slots :direct-superclasses direct-superclasses) class)) (defun std-after-initialization-for-classes (class &key direct-superclasses direct-slots &allow-other-keys) (let ((supers (or direct-superclasses (list (find-class 'standard-object))))) (setf (class-direct-superclasses class) supers) (dolist (superclass supers) (push class (class-direct-subclasses superclass)))) (let ((slots (mapcar #'(lambda (slot-properties) (apply #'make-direct-slot-definition slot-properties)) direct-slots))) (setf (class-direct-slots class) slots) (dolist (direct-slot slots) (dolist (reader (slot-definition-readers direct-slot)) (add-reader-method class reader (slot-definition-name direct-slot))) (dolist (writer (slot-definition-writers direct-slot)) (add-writer-method class writer (slot-definition-name direct-slot))))) (funcall (if (eq (class-of class) the-class-standard-class) #'std-finalize-inheritance #'finalize-inheritance) class) (values)) Slot definition retain all unknown slot options ( rather than signaling an (defun make-direct-slot-definition (&rest properties &key name (initargs ()) (initform nil) (initfunction nil) (readers ()) (writers ()) (allocation :instance) &allow-other-keys) (setf (getf* slot ':name) name) (setf (getf* slot ':initargs) initargs) (setf (getf* slot ':initform) initform) (setf (getf* slot ':initfunction) initfunction) (setf (getf* slot ':readers) readers) (setf (getf* slot ':writers) writers) (setf (getf* slot ':allocation) allocation) slot)) (defun make-effective-slot-definition (&rest properties &key name (initargs ()) (initform nil) (initfunction nil) (allocation :instance) &allow-other-keys) (setf (getf* slot ':name) name) (setf (getf* slot ':initargs) initargs) (setf (getf* slot ':initform) initform) (setf (getf* slot ':initfunction) initfunction) (setf (getf* slot ':allocation) allocation) slot)) (defun slot-definition-name (slot) (getf slot ':name)) (defun (setf slot-definition-name) (new-value slot) (setf (getf* slot ':name) new-value)) (defun slot-definition-initfunction (slot) (getf slot ':initfunction)) (defun (setf slot-definition-initfunction) (new-value slot) (setf (getf* slot ':initfunction) new-value)) (defun slot-definition-initform (slot) (getf slot ':initform)) (defun (setf slot-definition-initform) (new-value slot) (setf (getf* slot ':initform) new-value)) (defun slot-definition-initargs (slot) (getf slot ':initargs)) (defun (setf slot-definition-initargs) (new-value slot) (setf (getf* slot ':initargs) new-value)) (defun slot-definition-readers (slot) (getf slot ':readers)) (defun (setf slot-definition-readers) (new-value slot) (setf (getf* slot ':readers) new-value)) (defun slot-definition-writers (slot) (getf slot ':writers)) (defun (setf slot-definition-writers) (new-value slot) (setf (getf* slot ':writers) new-value)) (defun slot-definition-allocation (slot) (getf slot ':allocation)) (defun (setf slot-definition-allocation) (new-value slot) (setf (getf* slot ':allocation) new-value)) (defun std-finalize-inheritance (class) (setf (class-precedence-list class) (funcall (if (eq (class-of class) the-class-standard-class) #'std-compute-class-precedence-list #'compute-class-precedence-list) class)) (setf (class-slots class) (funcall (if (eq (class-of class) the-class-standard-class) #'std-compute-slots #'compute-slots) class)) (values)) (defun std-compute-class-precedence-list (class) (let ((classes-to-order (collect-superclasses* class))) (topological-sort classes-to-order (remove-duplicates (mapappend #'local-precedence-ordering classes-to-order)) #'std-tie-breaker-rule))) (defun topological-sort (elements constraints tie-breaker) (let ((remaining-constraints constraints) (remaining-elements elements) (result ())) (loop (let ((minimal-elements (remove-if #'(lambda (class) (member class remaining-constraints :key #'cadr)) remaining-elements))) (when (null minimal-elements) (if (null remaining-elements) (return-from topological-sort result) (error "Inconsistent precedence graph."))) (let ((choice (if (null (cdr minimal-elements)) (car minimal-elements) (funcall tie-breaker minimal-elements result)))) (setq result (append result (list choice))) (setq remaining-elements (remove choice remaining-elements)) (setq remaining-constraints (remove choice remaining-constraints :test #'member))))))) the CLOS Specification says to " select the one that has a direct subclass from right to left , looking for the first minimal element to show up among the direct superclasses of the class precedence list constituent . (defun std-tie-breaker-rule (minimal-elements cpl-so-far) (dolist (cpl-constituent (reverse cpl-so-far)) (let* ((supers (class-direct-superclasses cpl-constituent)) (common (intersection minimal-elements supers))) (when (not (null common)) (return-from std-tie-breaker-rule (car common)))))) (defun collect-superclasses* (class) (labels ((all-superclasses-loop (seen superclasses) (let ((to-be-processed (set-difference superclasses seen))) (if (null to-be-processed) superclasses (let ((class-to-process (car to-be-processed))) (all-superclasses-loop (cons class-to-process seen) (union (class-direct-superclasses class-to-process) superclasses))))))) (all-superclasses-loop () (list class)))) The local precedence ordering of a class C with direct superclasses C_1 , (defun local-precedence-ordering (class) (mapcar #'list (cons class (butlast (class-direct-superclasses class))) (class-direct-superclasses class))) (defun std-compute-slots (class) (let* ((all-slots (mapappend #'class-direct-slots (class-precedence-list class))) (all-names (remove-duplicates (mapcar #'slot-definition-name all-slots)))) (mapcar #'(lambda (name) (funcall (if (eq (class-of class) the-class-standard-class) #'std-compute-effective-slot-definition #'compute-effective-slot-definition) class (remove name all-slots :key #'slot-definition-name :test-not #'eq))) all-names))) (defun std-compute-effective-slot-definition (class direct-slots) (declare (ignore class)) (let ((initer (find-if-not #'null direct-slots :key #'slot-definition-initfunction))) (make-effective-slot-definition :name (slot-definition-name (car direct-slots)) :initform (if initer (slot-definition-initform initer) nil) :initfunction (if initer (slot-definition-initfunction initer) nil) :initargs (remove-duplicates (mapappend #'slot-definition-initargs direct-slots)) :allocation (slot-definition-allocation (car direct-slots))))) Generic function metaobjects and standard - generic - function (defparameter the-defclass-standard-generic-function '(defclass standard-generic-function () :initarg :lambda-list) :initarg :method-class) :initform (make-hash-table :test #'equal))))) standard - generic - function 's class metaobject (defun generic-function-name (gf) (slot-value gf 'name)) (defun (setf generic-function-name) (new-value gf) (setf (slot-value gf 'name) new-value)) (defun generic-function-lambda-list (gf) (slot-value gf 'lambda-list)) (defun (setf generic-function-lambda-list) (new-value gf) (setf (slot-value gf 'lambda-list) new-value)) (defun generic-function-methods (gf) (slot-value gf 'methods)) (defun (setf generic-function-methods) (new-value gf) (setf (slot-value gf 'methods) new-value)) (defun generic-function-discriminating-function (gf) (slot-value gf 'discriminating-function)) (defun (setf generic-function-discriminating-function) (new-value gf) (setf (slot-value gf 'discriminating-function) new-value)) (defun generic-function-method-class (gf) (slot-value gf 'method-class)) (defun (setf generic-function-method-class) (new-value gf) (setf (slot-value gf 'method-class) new-value)) Internal accessor for effective method function table (defun classes-to-emf-table (gf) (slot-value gf 'classes-to-emf-table)) (defun (setf classes-to-emf-table) (new-value gf) (setf (slot-value gf 'classes-to-emf-table) new-value)) (defparameter the-defclass-standard-method '(defclass standard-method () standard - method 's class metaobject (defun method-lambda-list (method) (slot-value method 'lambda-list)) (defun (setf method-lambda-list) (new-value method) (setf (slot-value method 'lambda-list) new-value)) (defun method-qualifiers (method) (slot-value method 'qualifiers)) (defun (setf method-qualifiers) (new-value method) (setf (slot-value method 'qualifiers) new-value)) (defun method-specializers (method) (slot-value method 'specializers)) (defun (setf method-specializers) (new-value method) (setf (slot-value method 'specializers) new-value)) (defun method-body (method) (slot-value method 'body)) (defun (setf method-body) (new-value method) (setf (slot-value method 'body) new-value)) (defun method-environment (method) (slot-value method 'environment)) (defun (setf method-environment) (new-value method) (setf (slot-value method 'environment) new-value)) (defun method-generic-function (method) (slot-value method 'generic-function)) (defun (setf method-generic-function) (new-value method) (setf (slot-value method 'generic-function) new-value)) (defun method-function (method) (slot-value method 'function)) (defun (setf method-function) (new-value method) (setf (slot-value method 'function) new-value)) (defmacro defgeneric (function-name lambda-list &rest options) `(ensure-generic-function ',function-name :lambda-list ',lambda-list ,@(canonicalize-defgeneric-options options))) (defun canonicalize-defgeneric-options (options) (mapappend #'canonicalize-defgeneric-option options)) (defun canonicalize-defgeneric-option (option) (case (car option) (:generic-function-class (list ':generic-function-class `(find-class ',(cadr option)))) (:method-class (list ':method-class `(find-class ',(cadr option)))) (t (list `',(car option) `',(cadr option))))) (let ((generic-function-table (make-hash-table :test #'equal))) (defun find-generic-function (symbol &optional (errorp t)) (let ((gf (gethash symbol generic-function-table nil))) (if (and (null gf) errorp) (error "No generic function named ~S." symbol) gf))) (defun (setf find-generic-function) (new-value symbol) (setf (gethash symbol generic-function-table) new-value)) (defun forget-all-generic-functions () (clrhash generic-function-table) (values)) (defun ensure-generic-function (function-name &rest all-keys &key (generic-function-class the-class-standard-gf) (method-class the-class-standard-method) &allow-other-keys) (if (find-generic-function function-name nil) (find-generic-function function-name) (let ((gf (apply (if (eq generic-function-class the-class-standard-gf) #'make-instance-standard-generic-function #'make-instance) generic-function-class :name function-name :method-class method-class all-keys))) (setf (find-generic-function function-name) gf) gf))) (defun finalize-generic-function (gf) (setf (generic-function-discriminating-function gf) (funcall (if (eq (class-of gf) the-class-standard-gf) #'std-compute-discriminating-function #'compute-discriminating-function) gf)) (setf (fdefinition (generic-function-name gf)) (generic-function-discriminating-function gf)) (clrhash (classes-to-emf-table gf)) (values)) (defun make-instance-standard-generic-function (generic-function-class &key name lambda-list method-class) (declare (ignore generic-function-class)) (let ((gf (std-allocate-instance the-class-standard-gf))) (setf (generic-function-name gf) name) (setf (generic-function-lambda-list gf) lambda-list) (setf (generic-function-methods gf) ()) (setf (generic-function-method-class gf) method-class) (setf (classes-to-emf-table gf) (make-hash-table :test #'equal)) (finalize-generic-function gf) gf)) (defmacro defmethod (&rest args) (multiple-value-bind (function-name qualifiers lambda-list specializers body) (parse-defmethod args) `(ensure-method (find-generic-function ',function-name) :lambda-list ',lambda-list :qualifiers ',qualifiers :specializers ,(canonicalize-specializers specializers) :body ',body :environment (top-level-environment)))) (defun canonicalize-specializers (specializers) `(list ,@(mapcar #'canonicalize-specializer specializers))) (defun canonicalize-specializer (specializer) `(find-class ',specializer)) (defun parse-defmethod (args) (let ((fn-spec (car args)) (qualifiers ()) (specialized-lambda-list nil) (body ()) (parse-state :qualifiers)) (dolist (arg (cdr args)) (ecase parse-state (:qualifiers (if (and (atom arg) (not (null arg))) (push-on-end arg qualifiers) (progn (setq specialized-lambda-list arg) (setq parse-state :body)))) (:body (push-on-end arg body)))) (values fn-spec qualifiers (extract-lambda-list specialized-lambda-list) (extract-specializers specialized-lambda-list) (list* 'block (if (consp fn-spec) (cadr fn-spec) fn-spec) body)))) (defun required-portion (gf args) (let ((number-required (length (gf-required-arglist gf)))) (when (< (length args) number-required) (error "Too few arguments to generic function ~S." gf)) (subseq args 0 number-required))) (defun gf-required-arglist (gf) (let ((plist (analyze-lambda-list (generic-function-lambda-list gf)))) (getf plist ':required-args))) (defun extract-lambda-list (specialized-lambda-list) (let* ((plist (analyze-lambda-list specialized-lambda-list)) (requireds (getf plist ':required-names)) (rv (getf plist ':rest-var)) (ks (getf plist ':key-args)) (aok (getf plist ':allow-other-keys)) (opts (getf plist ':optional-args)) (auxs (getf plist ':auxiliary-args))) `(,@requireds ,@(if rv `(&rest ,rv) ()) ,@(if (or ks aok) `(&key ,@ks) ()) ,@(if aok '(&allow-other-keys) ()) ,@(if opts `(&optional ,@opts) ()) ,@(if auxs `(&aux ,@auxs) ())))) (defun extract-specializers (specialized-lambda-list) (let ((plist (analyze-lambda-list specialized-lambda-list))) (getf plist ':specializers))) (defun analyze-lambda-list (lambda-list) (labels ((make-keyword (symbol) (intern (symbol-name symbol) (find-package 'keyword))) (get-keyword-from-arg (arg) (if (listp arg) (if (listp (car arg)) (caar arg) (make-keyword (car arg))) (make-keyword arg)))) Keywords argument specs (rest-var nil) (optionals ()) (auxs ()) (allow-other-keys nil) (state :parsing-required)) (dolist (arg lambda-list) (if (member arg lambda-list-keywords) (ecase arg (&optional (setq state :parsing-optional)) (&rest (setq state :parsing-rest)) (&key (setq state :parsing-key)) (&allow-other-keys (setq allow-other-keys 't)) (&aux (setq state :parsing-aux))) (case state (:parsing-required (push-on-end arg required-args) (if (listp arg) (progn (push-on-end (car arg) required-names) (push-on-end (cadr arg) specializers)) (progn (push-on-end arg required-names) (push-on-end 't specializers)))) (:parsing-optional (push-on-end arg optionals)) (:parsing-rest (setq rest-var arg)) (:parsing-key (push-on-end (get-keyword-from-arg arg) keys) (push-on-end arg key-args)) (:parsing-aux (push-on-end arg auxs))))) (list :required-names required-names :required-args required-args :specializers specializers :rest-var rest-var :keywords keys :key-args key-args :auxiliary-args auxs :optional-args optionals :allow-other-keys allow-other-keys)))) (defun ensure-method (gf &rest all-keys) (let ((new-method (apply (if (eq (generic-function-method-class gf) the-class-standard-method) #'make-instance-standard-method #'make-instance) (generic-function-method-class gf) all-keys))) (add-method gf new-method) new-method)) (defun make-instance-standard-method (method-class &key lambda-list qualifiers specializers body environment) (declare (ignore method-class)) (let ((method (std-allocate-instance the-class-standard-method))) (setf (method-lambda-list method) lambda-list) (setf (method-qualifiers method) qualifiers) (setf (method-specializers method) specializers) (setf (method-body method) body) (setf (method-environment method) environment) (setf (method-generic-function method) nil) (setf (method-function method) (std-compute-method-function method)) method)) with the same qualifiers and specializers . It 's a pain to develop programs without this feature of full CLOS . (defun add-method (gf method) (let ((old-method (find-method gf (method-qualifiers method) (method-specializers method) nil))) (when old-method (remove-method gf old-method))) (setf (method-generic-function method) gf) (push method (generic-function-methods gf)) (dolist (specializer (method-specializers method)) (pushnew method (class-direct-methods specializer))) (finalize-generic-function gf) method) (defun remove-method (gf method) (setf (generic-function-methods gf) (remove method (generic-function-methods gf))) (setf (method-generic-function method) nil) (dolist (class (method-specializers method)) (setf (class-direct-methods class) (remove method (class-direct-methods class)))) (finalize-generic-function gf) method) (defun find-method (gf qualifiers specializers &optional (errorp t)) (let ((method (find-if #'(lambda (method) (and (equal qualifiers (method-qualifiers method)) (equal specializers (method-specializers method)))) (generic-function-methods gf)))) (if (and (null method) errorp) (error "No such method for ~S." (generic-function-name gf)) method))) (defun add-reader-method (class fn-name slot-name) (ensure-method (ensure-generic-function fn-name :lambda-list '(object)) :lambda-list '(object) :qualifiers () :specializers (list class) :body `(slot-value object ',slot-name) :environment (top-level-environment)) (values)) (defun add-writer-method (class fn-name slot-name) (ensure-method (ensure-generic-function fn-name :lambda-list '(new-value object)) :lambda-list '(new-value object) :qualifiers () :specializers (list (find-class 't) class) :body `(setf (slot-value object ',slot-name) new-value) :environment (top-level-environment)) (values)) Generic function invocation (defun apply-generic-function (gf args) (apply (generic-function-discriminating-function gf) args)) (defun std-compute-discriminating-function (gf) #'(lambda (&rest args) (let* ((classes (mapcar #'class-of (required-portion gf args))) (emfun (gethash classes (classes-to-emf-table gf) nil))) (if emfun (funcall emfun args) (slow-method-lookup gf args classes))))) (defun slow-method-lookup (gf args classes) (let* ((applicable-methods (compute-applicable-methods-using-classes gf classes)) (emfun (funcall (if (eq (class-of gf) the-class-standard-gf) #'std-compute-effective-method-function #'compute-effective-method-function) gf applicable-methods))) (setf (gethash classes (classes-to-emf-table gf)) emfun) (funcall emfun args))) (defun compute-applicable-methods-using-classes (gf required-classes) (sort (copy-list (remove-if-not #'(lambda (method) (every #'subclassp required-classes (method-specializers method))) (generic-function-methods gf))) #'(lambda (m1 m2) (funcall (if (eq (class-of gf) the-class-standard-gf) #'std-method-more-specific-p #'method-more-specific-p) gf m1 m2 required-classes)))) (defun std-method-more-specific-p (gf method1 method2 required-classes) (declare (ignore gf)) (mapc #'(lambda (spec1 spec2 arg-class) (unless (eq spec1 spec2) (return-from std-method-more-specific-p (sub-specializer-p spec1 spec2 arg-class)))) (method-specializers method1) (method-specializers method2) required-classes) nil) (defun apply-methods (gf args methods) (funcall (compute-effective-method-function gf methods) args)) (defun primary-method-p (method) (null (method-qualifiers method))) (defun before-method-p (method) (equal '(:before) (method-qualifiers method))) (defun after-method-p (method) (equal '(:after) (method-qualifiers method))) (defun around-method-p (method) (equal '(:around) (method-qualifiers method))) (defun std-compute-effective-method-function (gf methods) (let ((primaries (remove-if-not #'primary-method-p methods)) (around (find-if #'around-method-p methods))) (when (null primaries) (error "No primary methods for the~@ generic function ~S." gf)) (if around (let ((next-emfun (funcall (if (eq (class-of gf) the-class-standard-gf) #'std-compute-effective-method-function #'compute-effective-method-function) gf (remove around methods)))) #'(lambda (args) (funcall (method-function around) args next-emfun))) (let ((next-emfun (compute-primary-emfun (cdr primaries))) (befores (remove-if-not #'before-method-p methods)) (reverse-afters (reverse (remove-if-not #'after-method-p methods)))) #'(lambda (args) (dolist (before befores) (funcall (method-function before) args nil)) (multiple-value-prog1 (funcall (method-function (car primaries)) args next-emfun) (dolist (after reverse-afters) (funcall (method-function after) args nil)))))))) (defun compute-primary-emfun (methods) (if (null methods) nil (let ((next-emfun (compute-primary-emfun (cdr methods)))) #'(lambda (args) (funcall (method-function (car methods)) args next-emfun))))) (defun apply-method (method args next-methods) (funcall (method-function method) args (if (null next-methods) nil (compute-effective-method-function (method-generic-function method) next-methods)))) (defun std-compute-method-function (method) (let ((form (method-body method)) (lambda-list (method-lambda-list method))) (compile-in-lexical-environment (method-environment method) `(lambda (args next-emfun) (flet ((call-next-method (&rest cnm-args) (if (null next-emfun) (error "No next method for the~@ generic function ~S." (method-generic-function ',method)) (funcall next-emfun (or cnm-args args)))) (next-method-p () (not (null next-emfun)))) (apply #'(lambda ,(kludge-arglist lambda-list) ,form) args)))))) (defun kludge-arglist (lambda-list) (if (and (member '&key lambda-list) (not (member '&allow-other-keys lambda-list))) (append lambda-list '(&allow-other-keys)) (if (and (not (member '&rest lambda-list)) (not (member '&key lambda-list))) (append lambda-list '(&key &allow-other-keys)) lambda-list))) (defun top-level-environment () (defun compile-in-lexical-environment (env lambda-expr) (declare (ignore env)) (if compile-methods (compile nil lambda-expr) (eval `(function ,lambda-expr)))) (format t "Beginning to bootstrap Closette...") (forget-all-classes) (forget-all-generic-functions) How to create the class hierarchy in 10 easy steps : 1 . Figure out standard - class 's slots . (setq the-slots-of-standard-class (mapcar #'(lambda (slotd) (make-effective-slot-definition :name (car slotd) :initargs (let ((a (getf (cdr slotd) ':initarg))) (if a (list a) ())) :initform (getf (cdr slotd) ':initform) :initfunction (let ((a (getf (cdr slotd) ':initform))) (if a #'(lambda () (eval a)) nil)) :allocation ':instance)) (nth 3 the-defclass-standard-class))) 2 . Create the standard - class metaobject by hand . (setq the-class-standard-class (allocate-std-instance 'tba (make-array (length the-slots-of-standard-class) :initial-element secret-unbound-value))) 3 . Install standard - class 's ( circular ) class - of link . (setf (std-instance-class the-class-standard-class) the-class-standard-class) 4 . Fill in standard - class 's class - slots . (setf (class-slots the-class-standard-class) the-slots-of-standard-class) 5 . Hand build the class t so that it has no direct superclasses . (setf (find-class 't) (let ((class (std-allocate-instance the-class-standard-class))) (setf (class-name class) 't) (setf (class-direct-subclasses class) ()) (setf (class-direct-superclasses class) ()) (setf (class-direct-methods class) ()) (setf (class-direct-slots class) ()) (setf (class-precedence-list class) (list class)) (setf (class-slots class) ()) class)) 6 . Create the other superclass of standard - class ( i.e. , standard - object ) . (defclass standard-object (t) ()) 7 . Define the full - blown version of standard - class . (setq the-class-standard-class (eval the-defclass-standard-class)) 8 . Replace all ( 3 ) existing pointers to the skeleton with real one . (setf (std-instance-class (find-class 't)) the-class-standard-class) (setf (std-instance-class (find-class 'standard-object)) the-class-standard-class) (setf (std-instance-class the-class-standard-class) the-class-standard-class) 9 . Define the other built - in classes . (defclass symbol (t) ()) (defclass sequence (t) ()) (defclass array (t) ()) (defclass number (t) ()) (defclass character (t) ()) (defclass function (t) ()) (defclass hash-table (t) ()) (defclass package (t) ()) (defclass pathname (t) ()) (defclass readtable (t) ()) (defclass stream (t) ()) (defclass list (sequence) ()) (defclass null (symbol list) ()) (defclass cons (list) ()) (defclass vector (array sequence) ()) (defclass bit-vector (vector) ()) (defclass string (vector) ()) (defclass complex (number) ()) (defclass integer (number) ()) (defclass float (number) ()) 10 . Define the other standard metaobject classes . (setq the-class-standard-gf (eval the-defclass-standard-generic-function)) (setq the-class-standard-method (eval the-defclass-standard-method)) (format t "Class hierarchy created.") (defgeneric print-object (instance stream)) (defmethod print-object ((instance standard-object) stream) (print-unreadable-object (instance stream :identity t) (format stream "~:(~S~)" (class-name (class-of instance)))) instance) (defgeneric slot-value-using-class (class instance slot-name)) (defmethod slot-value-using-class ((class standard-class) instance slot-name) (std-slot-value instance slot-name)) (defgeneric (setf slot-value-using-class) (new-value class instance slot-name)) (defmethod (setf slot-value-using-class) (new-value (class standard-class) instance slot-name) (setf (std-slot-value instance slot-name) new-value)) N.B. To avoid making a forward reference to a ( setf xxx ) generic function : (defun setf-slot-value-using-class (new-value class object slot-name) (setf (slot-value-using-class class object slot-name) new-value)) (defgeneric slot-exists-p-using-class (class instance slot-name)) (defmethod slot-exists-p-using-class ((class standard-class) instance slot-name) (std-slot-exists-p instance slot-name)) (defgeneric slot-boundp-using-class (class instance slot-name)) (defmethod slot-boundp-using-class ((class standard-class) instance slot-name) (std-slot-boundp instance slot-name)) (defgeneric slot-makunbound-using-class (class instance slot-name)) (defmethod slot-makunbound-using-class ((class standard-class) instance slot-name) (std-slot-makunbound instance slot-name)) (defgeneric allocate-instance (class)) (defmethod allocate-instance ((class standard-class)) (std-allocate-instance class)) (defgeneric make-instance (class &key)) (defmethod make-instance ((class standard-class) &rest initargs) (let ((instance (allocate-instance class))) (apply #'initialize-instance instance initargs) instance)) (defmethod make-instance ((class symbol) &rest initargs) (apply #'make-instance (find-class class) initargs)) (defgeneric initialize-instance (instance &key)) (defmethod initialize-instance ((instance standard-object) &rest initargs) (apply #'shared-initialize instance t initargs)) (defgeneric reinitialize-instance (instance &key)) (defmethod reinitialize-instance ((instance standard-object) &rest initargs) (apply #'shared-initialize instance () initargs)) (defgeneric shared-initialize (instance slot-names &key)) (defmethod shared-initialize ((instance standard-object) slot-names &rest all-keys) (dolist (slot (class-slots (class-of instance))) (let ((slot-name (slot-definition-name slot))) (multiple-value-bind (init-key init-value foundp) (get-properties all-keys (slot-definition-initargs slot)) (declare (ignore init-key)) (if foundp (setf (slot-value instance slot-name) init-value) (when (and (not (slot-boundp instance slot-name)) (not (null (slot-definition-initfunction slot))) (or (eq slot-names t) (member slot-name slot-names))) (setf (slot-value instance slot-name) (funcall (slot-definition-initfunction slot)))))))) instance) (defgeneric change-class (instance new-class &key)) (defmethod change-class ((old-instance standard-object) (new-class standard-class) &rest initargs) (let ((new-instance (allocate-instance new-class))) (dolist (slot-name (mapcar #'slot-definition-name (class-slots new-class))) (when (and (slot-exists-p old-instance slot-name) (slot-boundp old-instance slot-name)) (setf (slot-value new-instance slot-name) (slot-value old-instance slot-name)))) (rotatef (std-instance-slots new-instance) (std-instance-slots old-instance)) (rotatef (std-instance-class new-instance) (std-instance-class old-instance)) (apply #'update-instance-for-different-class new-instance old-instance initargs) old-instance)) (defmethod change-class ((instance standard-object) (new-class symbol) &rest initargs) (apply #'change-class instance (find-class new-class) initargs)) (defgeneric update-instance-for-different-class (old new &key)) (defmethod update-instance-for-different-class ((old standard-object) (new standard-object) &rest initargs) (let ((added-slots (remove-if #'(lambda (slot-name) (slot-exists-p old slot-name)) (mapcar #'slot-definition-name (class-slots (class-of new)))))) (apply #'shared-initialize new added-slots initargs))) (defmethod print-object ((class standard-class) stream) (print-unreadable-object (class stream :identity t) (format stream "~:(~S~) ~S" (class-name (class-of class)) (class-name class))) class) (defmethod initialize-instance :after ((class standard-class) &rest args) (apply #'std-after-initialization-for-classes class args)) Finalize inheritance (defgeneric finalize-inheritance (class)) (defmethod finalize-inheritance ((class standard-class)) (std-finalize-inheritance class) (values)) (defgeneric compute-class-precedence-list (class)) (defmethod compute-class-precedence-list ((class standard-class)) (std-compute-class-precedence-list class)) (defgeneric compute-slots (class)) (defmethod compute-slots ((class standard-class)) (std-compute-slots class)) (defgeneric compute-effective-slot-definition (class direct-slots)) (defmethod compute-effective-slot-definition ((class standard-class) direct-slots) (std-compute-effective-slot-definition class direct-slots)) (defmethod print-object ((gf standard-generic-function) stream) (print-unreadable-object (gf stream :identity t) (format stream "~:(~S~) ~S" (class-name (class-of gf)) (generic-function-name gf))) gf) (defmethod initialize-instance :after ((gf standard-generic-function) &key) (finalize-generic-function gf)) (defmethod print-object ((method standard-method) stream) (print-unreadable-object (method stream :identity t) (format stream "~:(~S~) ~S~{ ~S~} ~S" (class-name (class-of method)) (generic-function-name (method-generic-function method)) (method-qualifiers method) (mapcar #'class-name (method-specializers method)))) method) (defmethod initialize-instance :after ((method standard-method) &key) (setf (method-function method) (compute-method-function method))) (defgeneric compute-discriminating-function (gf)) (defmethod compute-discriminating-function ((gf standard-generic-function)) (std-compute-discriminating-function gf)) (defgeneric method-more-specific-p (gf method1 method2 required-classes)) (defmethod method-more-specific-p ((gf standard-generic-function) method1 method2 required-classes) (std-method-more-specific-p gf method1 method2 required-classes)) (defgeneric compute-effective-method-function (gf methods)) (defmethod compute-effective-method-function ((gf standard-generic-function) methods) (std-compute-effective-method-function gf methods)) (defgeneric compute-method-function (method)) (defmethod compute-method-function ((method standard-method)) (std-compute-method-function method)) (defgeneric describe-object (object stream)) (defmethod describe-object ((object standard-object) stream) (format t "A Closette object~ ~%Printed representation: ~S~ ~%Class: ~S~ ~%Structure " object (class-of object)) (dolist (sn (mapcar #'slot-definition-name (class-slots (class-of object)))) (format t "~% ~S <- ~:[not bound~;~S~]" sn (slot-boundp object sn) (and (slot-boundp object sn) (slot-value object sn)))) (values)) (defmethod describe-object ((object t) stream) (lisp:describe object) (values)) (format t "~%Closette is a Knights of the Lambda Calculus production.")
66c493612727f802309baf85b8d8b3dc5309256dd87c901e30e0b61d33d0ba45
mflatt/scope-sets
define-example.rkt
#lang scheme (require redex/reduction-semantics) (provide define-example-definer) (define-syntax-rule (define-example-definer define-example mini wrap parser empty-ctx) (begin (... (define-metafunction mini as-syntax : any -> val [(as-syntax nam) (Stx (Sym nam) empty-ctx)] [(as-syntax number) (Stx number empty-ctx)] [(as-syntax prim) (Stx prim empty-ctx)] [(as-syntax tprim) (Stx tprim empty-ctx)] [(as-syntax (any ...)) (Stx (List (as-syntax any) ...) empty-ctx)])) (define-syntax-rule (define-example id form expected) (begin (define id (lambda (mode) (let ([t (wrap (term (as-syntax form)))]) (case mode [(expand) t] [(parse) (term (parser ,t))] [else (error 'example "unknown mode: ~e" mode)])))) (test-equal (id 'parse) (term expected))))))
null
https://raw.githubusercontent.com/mflatt/scope-sets/4d3ae9d8a0f6ff83aa597612d280406cb6d82f5b/model/define-example.rkt
racket
#lang scheme (require redex/reduction-semantics) (provide define-example-definer) (define-syntax-rule (define-example-definer define-example mini wrap parser empty-ctx) (begin (... (define-metafunction mini as-syntax : any -> val [(as-syntax nam) (Stx (Sym nam) empty-ctx)] [(as-syntax number) (Stx number empty-ctx)] [(as-syntax prim) (Stx prim empty-ctx)] [(as-syntax tprim) (Stx tprim empty-ctx)] [(as-syntax (any ...)) (Stx (List (as-syntax any) ...) empty-ctx)])) (define-syntax-rule (define-example id form expected) (begin (define id (lambda (mode) (let ([t (wrap (term (as-syntax form)))]) (case mode [(expand) t] [(parse) (term (parser ,t))] [else (error 'example "unknown mode: ~e" mode)])))) (test-equal (id 'parse) (term expected))))))
d556fcb8789cfd3d75d6fe6e9440377f559bc9aa225e01c52a7a9947eec5ed95
re-ops/re-core
re_conf.clj
(ns re-mote.repl.re-conf "Running re-conf recpies on hosts" (:require [clojure.string :refer (join)] [re-mote.ssh.pipeline :refer (run-hosts)] [pallet.stevedore :refer (script)] re-mote.repl.base) (:import [re_mote.repl.base Hosts])) (defprotocol ReConf (apply-recipes [this path args] [this m path args])) (defn reconf-script [path args] (script ("cd" ~path) ("sudo" "/usr/bin/node" "main.js" ~args))) (extend-type Hosts ReConf (apply-recipes ([this path args] (apply-recipes this nil path args)) ([this _ path args] [this (run-hosts this (reconf-script path (join " " args)))]))) (defn refer-reconf [] (require '[re-mote.repl.re-conf :as reconf :refer (apply-recipes)]))
null
https://raw.githubusercontent.com/re-ops/re-core/93596efd4f3068d57e8140106da60011a6569310/src/re_mote/repl/re_conf.clj
clojure
(ns re-mote.repl.re-conf "Running re-conf recpies on hosts" (:require [clojure.string :refer (join)] [re-mote.ssh.pipeline :refer (run-hosts)] [pallet.stevedore :refer (script)] re-mote.repl.base) (:import [re_mote.repl.base Hosts])) (defprotocol ReConf (apply-recipes [this path args] [this m path args])) (defn reconf-script [path args] (script ("cd" ~path) ("sudo" "/usr/bin/node" "main.js" ~args))) (extend-type Hosts ReConf (apply-recipes ([this path args] (apply-recipes this nil path args)) ([this _ path args] [this (run-hosts this (reconf-script path (join " " args)))]))) (defn refer-reconf [] (require '[re-mote.repl.re-conf :as reconf :refer (apply-recipes)]))
660057972cf57921ae9d0b1fbcd9820e8f2e271cc00798e0fc7ae8ade725a4d5
hjcapple/reading-sicp
exercise_3_65.scm
#lang racket P235 - [ 练习 3.65 ] (require "stream.scm") (require "infinite_stream.scm") (require "stream_iterations.scm") (require "exercise_3_55.scm") ; for partial-sums (define (ln2-summands n) (cons-stream (/ 1.0 n) (stream-map - (ln2-summands (+ n 1))))) ; 原始流定义 (define ln2-stream (partial-sums (ln2-summands 1))) ; 欧拉加速 (define ln2-stream-2 (euler-transform ln2-stream)) ; 超级加速器 (define ln2-stream-3 (accelerated-sequence euler-transform ln2-stream)) ;;;;;;;;;;;;;;;; (define (display-stream-withmsg msg s n) (display msg) (newline) (display-stream-n s n) (display "============") (newline)) (display-stream-withmsg "ln2-stream" ln2-stream 100) (display-stream-withmsg "ln2-stream-2" ln2-stream-2 20) (display-stream-withmsg "ln2-stream-3" ln2-stream-3 10) ; ln2 的精确值为 0.693147180559945309417232121458176568075500134360255254120... 原始的 ln2 - stream 收敛很慢,就算取 100 项,计算结果为 0.688172179310195,才有 1 位小数相同 。 采用欧拉加速的 ln2 - stream-2 收敛快得多,取 20 项的计算结果为 0.6931346368409872,有 4 位小数相同 。 ; 采用超级加速的 ln2-stream-3 收敛速度更快,
null
https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_3/exercise_3_65.scm
scheme
for partial-sums 原始流定义 欧拉加速 超级加速器 ln2 的精确值为 0.693147180559945309417232121458176568075500134360255254120... 采用超级加速的 ln2-stream-3 收敛速度更快,
#lang racket P235 - [ 练习 3.65 ] (require "stream.scm") (require "infinite_stream.scm") (require "stream_iterations.scm") (define (ln2-summands n) (cons-stream (/ 1.0 n) (stream-map - (ln2-summands (+ n 1))))) (define ln2-stream (partial-sums (ln2-summands 1))) (define ln2-stream-2 (euler-transform ln2-stream)) (define ln2-stream-3 (accelerated-sequence euler-transform ln2-stream)) (define (display-stream-withmsg msg s n) (display msg) (newline) (display-stream-n s n) (display "============") (newline)) (display-stream-withmsg "ln2-stream" ln2-stream 100) (display-stream-withmsg "ln2-stream-2" ln2-stream-2 20) (display-stream-withmsg "ln2-stream-3" ln2-stream-3 10) 原始的 ln2 - stream 收敛很慢,就算取 100 项,计算结果为 0.688172179310195,才有 1 位小数相同 。 采用欧拉加速的 ln2 - stream-2 收敛快得多,取 20 项的计算结果为 0.6931346368409872,有 4 位小数相同 。
aa691e07f30e449c5f90b68e01b80107462c389fbc748ead26bf697a49788b82
lemenkov/rtplib
codec_speex_test.erl
%%%---------------------------------------------------------------------- Copyright ( c ) 2008 - 2012 < > %%% %%% All rights reserved. %%% %%% Redistribution and use in source and binary forms, with or without modification, %%% are permitted provided that the following conditions are met: %%% %%% * Redistributions of source code must retain the above copyright notice, this %%% list of conditions and the following disclaimer. %%% * Redistributions in binary form must reproduce the above copyright notice, %%% this list of conditions and the following disclaimer in the documentation %%% and/or other materials provided with the distribution. %%% * Neither the name of the authors nor the names of its contributors %%% may be used to endorse or promote products derived from this software %%% without specific prior written permission. %%% %%% THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY %%% EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED %%% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; %%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT %%% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS %%% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% %%%---------------------------------------------------------------------- -module(codec_speex_test). -include("rtp.hrl"). -include_lib("eunit/include/eunit.hrl"). codec_speex_test_() -> Padding = <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>, Padding2 = <<165,254,168,1,197,254,168,249,21,244,78,243,202,247, 131,252,190,2,153,8,174,5,85,1,34,9,178,17,115,18,152,5,195, 247,83,238,156,233,152,231,201,235,99,241,212,253,70,9,25,13, 159,11,61,13,68,19,230,19,23,10,115,4,190,2,229,255,101,2,114, 7,229,7,158,12,192,11,176,7,166,14,126,23,27,20,191,5,18,241, 238,226,250,220,2,218,204,221,240,231,51,246,219,4,234,3,231, 251,213,252,31,6,44,3,96,253,214,253,176,254,124,2,110,11,96, 10,138,14,105,24,214,24,202,19,88,29,2,42,39,36,207,17,50,254, 107,238,175,223,78,215,125,214,74,221,134,233,172,241,97,242,212,243>>, [ {"Test decoding from SPEEX to PCM", fun() -> ?assertEqual( true, (fun() -> {ok, BinIn} = file:read_file("../test/samples/speex/sample-speex-16-mono-8khz.raw"), {ok, PcmOut0} = file:read_file("../test/samples/speex/sample-pcm-16-mono-8khz.from_spx"), FIXME padding for the first decoded frame PcmOut = <<Padding/binary, PcmOut0/binary, Padding2/binary>>, {ok, Codec} = codec:start_link({'SPEEX',8000,1}), Ret = test_utils:decode("SPEEX", Codec, BinIn, PcmOut, 38), codec:close(Codec), Ret end)() % test_utils:codec_decode( " .. /test / samples / speex / sample - speex-16 - mono-8khz.raw " , " .. /test / samples / speex / sample - pcm-16 - mono-8khz.from_spx " , 38 , " SPEEX " , % {'SPEEX',8000,1} % ) ) end % }, { " Test encoding from PCM to SPEEX " , fun ( ) - > ? ( % true, % test_utils:codec_encode( " .. /test / samples / speex / sample - pcm-16 - mono-8khz.raw " , " .. /test / samples / speex / sample - speex-16 - mono-8khz.from_pcm " , 320 , " SPEEX " , % {'SPEEX',8000,1} % ) % ) end } ].
null
https://raw.githubusercontent.com/lemenkov/rtplib/b74a43b41fdb3dcdac6e33c5f2b9196780f7cbc8/test/codec_speex_test.erl
erlang
---------------------------------------------------------------------- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the authors nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- test_utils:codec_decode( {'SPEEX',8000,1} ) }, true, test_utils:codec_encode( {'SPEEX',8000,1} ) ) end
Copyright ( c ) 2008 - 2012 < > DISCLAIMED . IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT -module(codec_speex_test). -include("rtp.hrl"). -include_lib("eunit/include/eunit.hrl"). codec_speex_test_() -> Padding = <<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>, Padding2 = <<165,254,168,1,197,254,168,249,21,244,78,243,202,247, 131,252,190,2,153,8,174,5,85,1,34,9,178,17,115,18,152,5,195, 247,83,238,156,233,152,231,201,235,99,241,212,253,70,9,25,13, 159,11,61,13,68,19,230,19,23,10,115,4,190,2,229,255,101,2,114, 7,229,7,158,12,192,11,176,7,166,14,126,23,27,20,191,5,18,241, 238,226,250,220,2,218,204,221,240,231,51,246,219,4,234,3,231, 251,213,252,31,6,44,3,96,253,214,253,176,254,124,2,110,11,96, 10,138,14,105,24,214,24,202,19,88,29,2,42,39,36,207,17,50,254, 107,238,175,223,78,215,125,214,74,221,134,233,172,241,97,242,212,243>>, [ {"Test decoding from SPEEX to PCM", fun() -> ?assertEqual( true, (fun() -> {ok, BinIn} = file:read_file("../test/samples/speex/sample-speex-16-mono-8khz.raw"), {ok, PcmOut0} = file:read_file("../test/samples/speex/sample-pcm-16-mono-8khz.from_spx"), FIXME padding for the first decoded frame PcmOut = <<Padding/binary, PcmOut0/binary, Padding2/binary>>, {ok, Codec} = codec:start_link({'SPEEX',8000,1}), Ret = test_utils:decode("SPEEX", Codec, BinIn, PcmOut, 38), codec:close(Codec), Ret end)() " .. /test / samples / speex / sample - speex-16 - mono-8khz.raw " , " .. /test / samples / speex / sample - pcm-16 - mono-8khz.from_spx " , 38 , " SPEEX " , ) end { " Test encoding from PCM to SPEEX " , fun ( ) - > ? ( " .. /test / samples / speex / sample - pcm-16 - mono-8khz.raw " , " .. /test / samples / speex / sample - speex-16 - mono-8khz.from_pcm " , 320 , " SPEEX " , } ].
b1c9a8d383b93bdf371921083560e93315b565372f549536d3f3ce621446ba74
ctford/Idris-Elba-Dev
Delaborate.hs
# LANGUAGE PatternGuards # module Idris.Delaborate (bugaddr, delab, delab', delabMV, delabTy, delabTy', pshow, pprintErr) where Convert core TT back into high level syntax , primarily for display -- purposes. import Util.Pretty import Idris.AbsSyntax import Idris.Core.TT import Idris.Core.Evaluate import Idris.ErrReverse import Data.List (intersperse) import Debug.Trace bugaddr = "-lang/Idris-dev/issues" delab :: IState -> Term -> PTerm delab i tm = delab' i tm False False delabMV :: IState -> Term -> PTerm delabMV i tm = delab' i tm False True delabTy :: IState -> Name -> PTerm delabTy i n = case lookupTy n (tt_ctxt i) of (ty:_) -> case lookupCtxt n (idris_implicits i) of (imps:_) -> delabTy' i imps ty False False _ -> delabTy' i [] ty False False delab' :: IState -> Term -> Bool -> Bool -> PTerm delab' i t f mvs = delabTy' i [] t f mvs delabTy' :: IState -> [PArg] -- ^ implicit arguments to type, if any -> Term -> Bool -- ^ use full names -> Bool -- ^ Don't treat metavariables specially -> PTerm delabTy' ist imps tm fullname mvs = de [] imps tm where un = fileFC "(val)" de env _ (App f a) = deFn env f [a] de env _ (V i) | i < length env = PRef un (snd (env!!i)) | otherwise = PRef un (sUN ("v" ++ show i ++ "")) de env _ (P _ n _) | n == unitTy = PTrue un | n == unitCon = PTrue un | n == falseTy = PFalse un | Just n' <- lookup n env = PRef un n' | otherwise = case lookup n (idris_metavars ist) of Just (Just _, mi, _) -> mkMVApp n [] _ -> PRef un n de env _ (Bind n (Lam ty) sc) = PLam n (de env [] ty) (de ((n,n):env) [] sc) de env (PImp _ _ _ _ _ _:is) (Bind n (Pi ty) sc) = PPi impl n (de env [] ty) (de ((n,n):env) is sc) de env (PConstraint _ _ _ _:is) (Bind n (Pi ty) sc) = PPi constraint n (de env [] ty) (de ((n,n):env) is sc) de env (PTacImplicit _ _ _ tac _ _:is) (Bind n (Pi ty) sc) = PPi (tacimpl tac) n (de env [] ty) (de ((n,n):env) is sc) de env _ (Bind n (Pi ty) sc) = PPi expl n (de env [] ty) (de ((n,n):env) [] sc) de env _ (Bind n (Let ty val) sc) = PLet n (de env [] ty) (de env [] val) (de ((n,n):env) [] sc) de env _ (Bind n (Hole ty) sc) = de ((n, sUN "[__]"):env) [] sc de env _ (Bind n (Guess ty val) sc) = de ((n, sUN "[__]"):env) [] sc de env _ (Bind n _ sc) = de ((n,n):env) [] sc de env _ (Constant i) = PConstant i de env _ Erased = Placeholder de env _ Impossible = Placeholder de env _ (TType i) = PType dens x | fullname = x dens ns@(NS n _) = case lookupCtxt n (idris_implicits ist) of [_] -> n -- just one thing [] -> n -- metavariables have no implicits _ -> ns dens n = n deFn env (App f a) args = deFn env f (a:args) deFn env (P _ n _) [l,r] | n == pairTy = PPair un (de env [] l) (de env [] r) | n == eqCon = PRefl un (de env [] r) | n == sUN "lazy" = de env [] r deFn env (P _ n _) [ty, Bind x (Lam _) r] | n == sUN "Exists" = PDPair un (PRef un x) (de env [] ty) (de ((x,x):env) [] (instantiate (P Bound x ty) r)) deFn env (P _ n _) [_,_,l,r] | n == pairCon = PPair un (de env [] l) (de env [] r) | n == eqTy = PEq un (de env [] l) (de env [] r) | n == sUN "Ex_intro" = PDPair un (de env [] l) Placeholder (de env [] r) deFn env (P _ n _) args | not mvs = case lookup n (idris_metavars ist) of Just (Just _, mi, _) -> mkMVApp n (drop mi (map (de env []) args)) _ -> mkPApp n (map (de env []) args) | otherwise = mkPApp n (map (de env []) args) deFn env f args = PApp un (de env [] f) (map pexp (map (de env []) args)) mkMVApp n [] = PMetavar n mkMVApp n args = PApp un (PMetavar n) (map pexp args) mkPApp n args | [imps] <- lookupCtxt n (idris_implicits ist) = PApp un (PRef un n) (zipWith imp (imps ++ repeat (pexp undefined)) args) | otherwise = PApp un (PRef un n) (map pexp args) imp (PImp p m l n _ d) arg = PImp p m l n arg d imp (PExp p l _ d) arg = PExp p l arg d imp (PConstraint p l _ d) arg = PConstraint p l arg d imp (PTacImplicit p l n sc _ d) arg = PTacImplicit p l n sc arg d -- | How far to indent sub-errors errorIndent :: Int errorIndent = 8 -- | Actually indent a sub-error - no line at end because a newline can end -- multiple layers of indent indented :: Doc a -> Doc a indented = nest errorIndent . (line <>) pprintTerm :: IState -> PTerm -> Doc OutputAnnotation pprintTerm ist = prettyImp (opt_showimp (idris_options ist)) pshow :: IState -> Err -> String pshow ist err = displayDecorated (consoleDecorate ist) . renderPretty 1.0 80 . fmap (fancifyAnnots ist) $ pprintErr ist err pprintErr :: IState -> Err -> Doc OutputAnnotation pprintErr i err = pprintErr' i (fmap (errReverse i) err) pprintErr' i (Msg s) = text s pprintErr' i (InternalMsg s) = vsep [ text "INTERNAL ERROR:" <+> text s, text "This is probably a bug, or a missing error message.", text ("Please consider reporting at " ++ bugaddr) ] pprintErr' i (CantUnify _ x y e sc s) = text "Can't unify" <> indented (pprintTerm i (delab i x)) <$> text "with" <> indented (pprintTerm i (delab i y)) <> case e of Msg "" -> empty _ -> line <> line <> text "Specifically:" <> indented (pprintErr' i e) <> if (opt_errContext (idris_options i)) then text $ showSc i sc else empty pprintErr' i (CantConvert x y env) = text "Can't convert" <> indented (pprintTerm i (delab i x)) <> text "with" <> indented (pprintTerm i (delab i y)) <> if (opt_errContext (idris_options i)) then text (showSc i env) else empty pprintErr' i (CantSolveGoal x env) = text "Can't solve goal " <> indented (pprintTerm i (delab i x)) <> if (opt_errContext (idris_options i)) then text (showSc i env) else empty pprintErr' i (UnifyScope n out tm env) = text "Can't unify" <> indented (annName n) <+> text "with" <> indented (pprintTerm i (delab i tm)) <+> text "as" <> indented (annName out) <> text "is not in scope" <> if (opt_errContext (idris_options i)) then text (showSc i env) else empty pprintErr' i (CantInferType t) = text "Can't infer type for" <+> text t pprintErr' i (NonFunctionType f ty) = pprintTerm i (delab i f) <+> text "does not have a function type" <+> parens (pprintTerm i (delab i ty)) pprintErr' i (NotEquality tm ty) = pprintTerm i (delab i tm) <+> text "does not have an equality type" <+> parens (pprintTerm i (delab i ty)) pprintErr' i (TooManyArguments f) = text "Too many arguments for" <+> annName f pprintErr' i (CantIntroduce ty) = text "Can't use lambda here: type is" <+> pprintTerm i (delab i ty) pprintErr' i (InfiniteUnify x tm env) = text "Unifying" <+> annName' x (showbasic x) <+> text "and" <+> pprintTerm i (delab i tm) <+> text "would lead to infinite value" <> if (opt_errContext (idris_options i)) then text (showSc i env) else empty pprintErr' i (NotInjective p x y) = text "Can't verify injectivity of" <+> pprintTerm i (delab i p) <+> text " when unifying" <+> pprintTerm i (delab i x) <+> text "and" <+> pprintTerm i (delab i y) pprintErr' i (CantResolve c) = text "Can't resolve type class" <+> pprintTerm i (delab i c) pprintErr' i (CantResolveAlts as) = text "Can't disambiguate name:" <+> cat (punctuate (comma <> space) (map text as)) pprintErr' i (NoTypeDecl n) = text "No type declaration for" <+> annName n pprintErr' i (NoSuchVariable n) = text "No such variable" <+> annName n pprintErr' i (IncompleteTerm t) = text "Incomplete term" <+> pprintTerm i (delab i t) pprintErr' i UniverseError = text "Universe inconsistency" pprintErr' i ProgramLineComment = text "Program line next to comment" pprintErr' i (Inaccessible n) = annName n <+> text "is not an accessible pattern variable" pprintErr' i (NonCollapsiblePostulate n) = text "The return type of postulate" <+> annName n <+> text "is not collapsible" pprintErr' i (AlreadyDefined n) = annName n<+> text "is already defined" pprintErr' i (ProofSearchFail e) = pprintErr' i e pprintErr' i (NoRewriting tm) = text "rewrite did not change type" <+> pprintTerm i (delab i tm) pprintErr' i (At f e) = annotate (AnnFC f) (text (show f)) <> colon <> pprintErr' i e pprintErr' i (Elaborating s n e) = text "When elaborating" <+> text s <> annName' n (showqual i n) <> colon <$> pprintErr' i e pprintErr' i (ProviderError msg) = text ("Type provider error: " ++ msg) pprintErr' i (LoadingFailed fn e) = text "Loading" <+> text fn <+> text "failed:" <+> pprintErr' i e pprintErr' i (ReflectionError parts orig) = let parts' = map (hsep . map showPart) parts in vsep parts' <> if (opt_origerr (idris_options i)) then line <> line <> text "Original error:" <$> indented (pprintErr' i orig) else empty where showPart :: ErrorReportPart -> Doc OutputAnnotation showPart (TextPart str) = text str showPart (NamePart n) = annName n showPart (TermPart tm) = pprintTerm i (delab i tm) showPart (SubReport rs) = indented . hsep . map showPart $ rs pprintErr' i (ReflectionFailed msg err) = text "When attempting to perform error reflection, the following internal error occurred:" <> indented (pprintErr' i err) <> text ("This is probably a bug. Please consider reporting it at " ++ bugaddr) annName :: Name -> Doc OutputAnnotation annName n = annName' n (show n) annName' :: Name -> String -> Doc OutputAnnotation annName' n str = annotate (AnnName n Nothing Nothing) (text str) showSc i [] = "" showSc i xs = "\n\nIn context:\n" ++ showSep "\n" (map showVar (reverse xs)) where showVar (x, y) = "\t" ++ showbasic x ++ " : " ++ show (delab i y) showqual :: IState -> Name -> String showqual i n = showName (Just i) [] False False (dens n) where dens ns@(NS n _) = case lookupCtxt n (idris_implicits i) of [_] -> n -- just one thing _ -> ns dens n = n showbasic n@(UN _) = show n showbasic (MN _ s) = str s showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n showbasic (SN s) = show s
null
https://raw.githubusercontent.com/ctford/Idris-Elba-Dev/e915e1d6b7a5921ba43d2572a9ad9b980619b8ee/src/Idris/Delaborate.hs
haskell
purposes. ^ implicit arguments to type, if any ^ use full names ^ Don't treat metavariables specially just one thing metavariables have no implicits | How far to indent sub-errors | Actually indent a sub-error - no line at end because a newline can end multiple layers of indent just one thing
# LANGUAGE PatternGuards # module Idris.Delaborate (bugaddr, delab, delab', delabMV, delabTy, delabTy', pshow, pprintErr) where Convert core TT back into high level syntax , primarily for display import Util.Pretty import Idris.AbsSyntax import Idris.Core.TT import Idris.Core.Evaluate import Idris.ErrReverse import Data.List (intersperse) import Debug.Trace bugaddr = "-lang/Idris-dev/issues" delab :: IState -> Term -> PTerm delab i tm = delab' i tm False False delabMV :: IState -> Term -> PTerm delabMV i tm = delab' i tm False True delabTy :: IState -> Name -> PTerm delabTy i n = case lookupTy n (tt_ctxt i) of (ty:_) -> case lookupCtxt n (idris_implicits i) of (imps:_) -> delabTy' i imps ty False False _ -> delabTy' i [] ty False False delab' :: IState -> Term -> Bool -> Bool -> PTerm delab' i t f mvs = delabTy' i [] t f mvs -> Term -> PTerm delabTy' ist imps tm fullname mvs = de [] imps tm where un = fileFC "(val)" de env _ (App f a) = deFn env f [a] de env _ (V i) | i < length env = PRef un (snd (env!!i)) | otherwise = PRef un (sUN ("v" ++ show i ++ "")) de env _ (P _ n _) | n == unitTy = PTrue un | n == unitCon = PTrue un | n == falseTy = PFalse un | Just n' <- lookup n env = PRef un n' | otherwise = case lookup n (idris_metavars ist) of Just (Just _, mi, _) -> mkMVApp n [] _ -> PRef un n de env _ (Bind n (Lam ty) sc) = PLam n (de env [] ty) (de ((n,n):env) [] sc) de env (PImp _ _ _ _ _ _:is) (Bind n (Pi ty) sc) = PPi impl n (de env [] ty) (de ((n,n):env) is sc) de env (PConstraint _ _ _ _:is) (Bind n (Pi ty) sc) = PPi constraint n (de env [] ty) (de ((n,n):env) is sc) de env (PTacImplicit _ _ _ tac _ _:is) (Bind n (Pi ty) sc) = PPi (tacimpl tac) n (de env [] ty) (de ((n,n):env) is sc) de env _ (Bind n (Pi ty) sc) = PPi expl n (de env [] ty) (de ((n,n):env) [] sc) de env _ (Bind n (Let ty val) sc) = PLet n (de env [] ty) (de env [] val) (de ((n,n):env) [] sc) de env _ (Bind n (Hole ty) sc) = de ((n, sUN "[__]"):env) [] sc de env _ (Bind n (Guess ty val) sc) = de ((n, sUN "[__]"):env) [] sc de env _ (Bind n _ sc) = de ((n,n):env) [] sc de env _ (Constant i) = PConstant i de env _ Erased = Placeholder de env _ Impossible = Placeholder de env _ (TType i) = PType dens x | fullname = x dens ns@(NS n _) = case lookupCtxt n (idris_implicits ist) of _ -> ns dens n = n deFn env (App f a) args = deFn env f (a:args) deFn env (P _ n _) [l,r] | n == pairTy = PPair un (de env [] l) (de env [] r) | n == eqCon = PRefl un (de env [] r) | n == sUN "lazy" = de env [] r deFn env (P _ n _) [ty, Bind x (Lam _) r] | n == sUN "Exists" = PDPair un (PRef un x) (de env [] ty) (de ((x,x):env) [] (instantiate (P Bound x ty) r)) deFn env (P _ n _) [_,_,l,r] | n == pairCon = PPair un (de env [] l) (de env [] r) | n == eqTy = PEq un (de env [] l) (de env [] r) | n == sUN "Ex_intro" = PDPair un (de env [] l) Placeholder (de env [] r) deFn env (P _ n _) args | not mvs = case lookup n (idris_metavars ist) of Just (Just _, mi, _) -> mkMVApp n (drop mi (map (de env []) args)) _ -> mkPApp n (map (de env []) args) | otherwise = mkPApp n (map (de env []) args) deFn env f args = PApp un (de env [] f) (map pexp (map (de env []) args)) mkMVApp n [] = PMetavar n mkMVApp n args = PApp un (PMetavar n) (map pexp args) mkPApp n args | [imps] <- lookupCtxt n (idris_implicits ist) = PApp un (PRef un n) (zipWith imp (imps ++ repeat (pexp undefined)) args) | otherwise = PApp un (PRef un n) (map pexp args) imp (PImp p m l n _ d) arg = PImp p m l n arg d imp (PExp p l _ d) arg = PExp p l arg d imp (PConstraint p l _ d) arg = PConstraint p l arg d imp (PTacImplicit p l n sc _ d) arg = PTacImplicit p l n sc arg d errorIndent :: Int errorIndent = 8 indented :: Doc a -> Doc a indented = nest errorIndent . (line <>) pprintTerm :: IState -> PTerm -> Doc OutputAnnotation pprintTerm ist = prettyImp (opt_showimp (idris_options ist)) pshow :: IState -> Err -> String pshow ist err = displayDecorated (consoleDecorate ist) . renderPretty 1.0 80 . fmap (fancifyAnnots ist) $ pprintErr ist err pprintErr :: IState -> Err -> Doc OutputAnnotation pprintErr i err = pprintErr' i (fmap (errReverse i) err) pprintErr' i (Msg s) = text s pprintErr' i (InternalMsg s) = vsep [ text "INTERNAL ERROR:" <+> text s, text "This is probably a bug, or a missing error message.", text ("Please consider reporting at " ++ bugaddr) ] pprintErr' i (CantUnify _ x y e sc s) = text "Can't unify" <> indented (pprintTerm i (delab i x)) <$> text "with" <> indented (pprintTerm i (delab i y)) <> case e of Msg "" -> empty _ -> line <> line <> text "Specifically:" <> indented (pprintErr' i e) <> if (opt_errContext (idris_options i)) then text $ showSc i sc else empty pprintErr' i (CantConvert x y env) = text "Can't convert" <> indented (pprintTerm i (delab i x)) <> text "with" <> indented (pprintTerm i (delab i y)) <> if (opt_errContext (idris_options i)) then text (showSc i env) else empty pprintErr' i (CantSolveGoal x env) = text "Can't solve goal " <> indented (pprintTerm i (delab i x)) <> if (opt_errContext (idris_options i)) then text (showSc i env) else empty pprintErr' i (UnifyScope n out tm env) = text "Can't unify" <> indented (annName n) <+> text "with" <> indented (pprintTerm i (delab i tm)) <+> text "as" <> indented (annName out) <> text "is not in scope" <> if (opt_errContext (idris_options i)) then text (showSc i env) else empty pprintErr' i (CantInferType t) = text "Can't infer type for" <+> text t pprintErr' i (NonFunctionType f ty) = pprintTerm i (delab i f) <+> text "does not have a function type" <+> parens (pprintTerm i (delab i ty)) pprintErr' i (NotEquality tm ty) = pprintTerm i (delab i tm) <+> text "does not have an equality type" <+> parens (pprintTerm i (delab i ty)) pprintErr' i (TooManyArguments f) = text "Too many arguments for" <+> annName f pprintErr' i (CantIntroduce ty) = text "Can't use lambda here: type is" <+> pprintTerm i (delab i ty) pprintErr' i (InfiniteUnify x tm env) = text "Unifying" <+> annName' x (showbasic x) <+> text "and" <+> pprintTerm i (delab i tm) <+> text "would lead to infinite value" <> if (opt_errContext (idris_options i)) then text (showSc i env) else empty pprintErr' i (NotInjective p x y) = text "Can't verify injectivity of" <+> pprintTerm i (delab i p) <+> text " when unifying" <+> pprintTerm i (delab i x) <+> text "and" <+> pprintTerm i (delab i y) pprintErr' i (CantResolve c) = text "Can't resolve type class" <+> pprintTerm i (delab i c) pprintErr' i (CantResolveAlts as) = text "Can't disambiguate name:" <+> cat (punctuate (comma <> space) (map text as)) pprintErr' i (NoTypeDecl n) = text "No type declaration for" <+> annName n pprintErr' i (NoSuchVariable n) = text "No such variable" <+> annName n pprintErr' i (IncompleteTerm t) = text "Incomplete term" <+> pprintTerm i (delab i t) pprintErr' i UniverseError = text "Universe inconsistency" pprintErr' i ProgramLineComment = text "Program line next to comment" pprintErr' i (Inaccessible n) = annName n <+> text "is not an accessible pattern variable" pprintErr' i (NonCollapsiblePostulate n) = text "The return type of postulate" <+> annName n <+> text "is not collapsible" pprintErr' i (AlreadyDefined n) = annName n<+> text "is already defined" pprintErr' i (ProofSearchFail e) = pprintErr' i e pprintErr' i (NoRewriting tm) = text "rewrite did not change type" <+> pprintTerm i (delab i tm) pprintErr' i (At f e) = annotate (AnnFC f) (text (show f)) <> colon <> pprintErr' i e pprintErr' i (Elaborating s n e) = text "When elaborating" <+> text s <> annName' n (showqual i n) <> colon <$> pprintErr' i e pprintErr' i (ProviderError msg) = text ("Type provider error: " ++ msg) pprintErr' i (LoadingFailed fn e) = text "Loading" <+> text fn <+> text "failed:" <+> pprintErr' i e pprintErr' i (ReflectionError parts orig) = let parts' = map (hsep . map showPart) parts in vsep parts' <> if (opt_origerr (idris_options i)) then line <> line <> text "Original error:" <$> indented (pprintErr' i orig) else empty where showPart :: ErrorReportPart -> Doc OutputAnnotation showPart (TextPart str) = text str showPart (NamePart n) = annName n showPart (TermPart tm) = pprintTerm i (delab i tm) showPart (SubReport rs) = indented . hsep . map showPart $ rs pprintErr' i (ReflectionFailed msg err) = text "When attempting to perform error reflection, the following internal error occurred:" <> indented (pprintErr' i err) <> text ("This is probably a bug. Please consider reporting it at " ++ bugaddr) annName :: Name -> Doc OutputAnnotation annName n = annName' n (show n) annName' :: Name -> String -> Doc OutputAnnotation annName' n str = annotate (AnnName n Nothing Nothing) (text str) showSc i [] = "" showSc i xs = "\n\nIn context:\n" ++ showSep "\n" (map showVar (reverse xs)) where showVar (x, y) = "\t" ++ showbasic x ++ " : " ++ show (delab i y) showqual :: IState -> Name -> String showqual i n = showName (Just i) [] False False (dens n) where dens ns@(NS n _) = case lookupCtxt n (idris_implicits i) of _ -> ns dens n = n showbasic n@(UN _) = show n showbasic (MN _ s) = str s showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n showbasic (SN s) = show s