code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Memo( module Hugs.Memo, ) where import Hugs.Memo
OS2World/DEV-UTIL-HUGS
oldlib/Memo.hs
bsd-3-clause
62
2
5
14
20
13
7
3
0
{-# LANGUAGE ScopedTypeVariables #-} -- © 2001 Peter Thiemann module WASH.Utility.Unique (inventStdKey, inventKey, inventFilePath) where import Control.Exception import System.Random import System.IO import System.IO.Error import System.Directory import WASH.Utility.Auxiliary import Data.List import Control.Monad import WASH.Utility.Locking registryDir = "/tmp/Unique/" -- |Creates a random string of 20 letters and digits. inventStdKey :: IO String inventStdKey = inventKey 20 stdKeyChars stdKeyChars = ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] -- |Creates a unique string from a given length and alphabet. inventKey :: Int -> String -> IO String inventKey len chars = do g <- newStdGen let candidate = take len $ map (chars !!) $ randomRs (0, length chars - 1) g dirname = registryDir ++ candidate catch (do createDirectory dirname return candidate) (\ (ioe :: IOException) -> if isAlreadyExistsError ioe then -- might want to check here for timeout inventKey len chars else if isDoesNotExistError ioe then do assertDirectoryExists registryDir (return ()) setPermissions registryDir (emptyPermissions { readable = True, writable = True, executable = True, searchable = True }) inventKey len chars else do hPutStrLn stderr ("inventKey could not create " ++ show dirname) ioError ioe) -- |Create a unique temporary file name inventFilePath :: IO String inventFilePath = do key <- inventStdKey return (registryDir ++ key ++ "/f") -- obsolete. registryFile is a bottleneck. registryFile = registryDir ++ "REGISTRY" inventKey' :: Int -> String -> IO String inventKey' len chars = do g <- newStdGen let candidate = take len $ map (chars !!) $ randomRs (0, length chars - 1) g obtainLock registryFile registry <- readRegistry let passwords = lines registry if candidate `elem` passwords then do releaseLock registryFile inventKey' len chars else do appendFile registryFile (candidate ++ "\n") releaseLock registryFile return candidate readRegistry :: IO String readRegistry = let registryPath = init registryDir in do assertDirectoryExists registryPath (return ()) readFileNonExistent registryFile ""
nh2/WashNGo
WASH/Utility/Unique.hs
bsd-3-clause
2,255
17
17
460
627
322
305
54
3
{-# LANGUAGE GeneralizedNewtypeDeriving, TypeFamilies, DeriveDataTypeable #-} module Arrays where import Control.Monad import Data.Typeable import Test.QuickCheck import Term import System.Random instance Arbitrary Index where arbitrary = choose (0, 15) instance Arbitrary Array where arbitrary = fmap Array (replicateM 16 arbitrary) instance Classify Array where type Value Array = Array evaluate = return instance Classify Index where type Value Index = Index evaluate = return newtype Array = Array [Int] deriving (Eq, Ord, CoArbitrary, Typeable) newtype Index = Index Int deriving (Eq, Ord, Random, CoArbitrary, Num, Show, Typeable) new :: Array new = Array (replicate 16 0) get :: Index -> Array -> Int get (Index i) (Array xs) = xs !! i set :: Index -> Int -> Array -> Array set (Index i) v (Array xs) = Array (take i xs ++ [v] ++ drop (i+1) xs)
jystic/QuickSpec
qs1/Arrays.hs
bsd-3-clause
872
0
10
157
324
174
150
25
1
module Main where import System (getArgs) import IO import List (isSuffixOf) import Maybe (fromJust) import Text.XML.HaXml.Types (Document(..),Content(..)) import Text.XML.HaXml.Parse (xmlParse,dtdParse) import Text.XML.HaXml.Validate (validate) import Text.XML.HaXml.Wrappers (fix2Args) -- This is a fairly trivial application that reads a DTD from a file, -- an XML document from another file (or stdin), and writes any validation -- errors to stdout. main = do (dtdf,xmlf) <- fix2Args dtdtext <- ( if dtdf=="-" then error "Usage: validate dtdfile [xmlfile]" else readFile dtdf ) content <- ( if xmlf=="-" then getContents else readFile xmlf ) let dtd = dtdParse dtdf dtdtext Document _ _ xml _ = xmlParse xmlf content errs = validate (fromJust dtd) xml mapM_ putStrLn errs hFlush stdout
FranklinChen/hugs98-plus-Sep2006
packages/HaXml/src/tools/Validate.hs
bsd-3-clause
861
0
12
186
231
130
101
19
3
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Hints -- Copyright : (c) Sven Panne 2003 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : sven_panne@yahoo.com -- Stability : provisional -- Portability : portable -- -- This module corresponds to section 5.6 (Hints) of the OpenGL 1.4 specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Hints ( HintTarget(..), HintMode(..), hint ) where import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum ) import Graphics.Rendering.OpenGL.GL.QueryUtils ( GetPName(GetPerspectiveCorrectionHint,GetPointSmoothHint,GetLineSmoothHint, GetPolygonSmoothHint,GetFogHint,GetGenerateMipmapHint, GetTextureCompressionHint,GetPackCMYKHint,GetUnpackCMYKHint), getEnum1 ) import Graphics.Rendering.OpenGL.GL.StateVar ( StateVar, makeStateVar ) -------------------------------------------------------------------------------- data HintTarget = PerspectiveCorrection | PointSmooth | LineSmooth | PolygonSmooth | Fog | GenerateMipmap | TextureCompression | PackCMYK | UnpackCMYK deriving ( Eq, Ord, Show ) marshalHintTarget :: HintTarget -> GLenum marshalHintTarget x = case x of PerspectiveCorrection -> 0xc50 PointSmooth -> 0xc51 LineSmooth -> 0xc52 PolygonSmooth -> 0xc53 Fog -> 0xc54 GenerateMipmap -> 0x8192 TextureCompression -> 0x84ef PackCMYK -> 0x800e UnpackCMYK -> 0x800f hintTargetToGetPName :: HintTarget -> GetPName hintTargetToGetPName x = case x of PerspectiveCorrection -> GetPerspectiveCorrectionHint PointSmooth -> GetPointSmoothHint LineSmooth -> GetLineSmoothHint PolygonSmooth -> GetPolygonSmoothHint Fog -> GetFogHint GenerateMipmap -> GetGenerateMipmapHint TextureCompression -> GetTextureCompressionHint PackCMYK -> GetPackCMYKHint UnpackCMYK -> GetUnpackCMYKHint -------------------------------------------------------------------------------- data HintMode = DontCare | Fastest | Nicest deriving ( Eq, Ord, Show ) marshalHintMode :: HintMode -> GLenum marshalHintMode x = case x of DontCare -> 0x1100 Fastest -> 0x1101 Nicest -> 0x1102 unmarshalHintMode :: GLenum -> HintMode unmarshalHintMode x | x == 0x1100 = DontCare | x == 0x1101 = Fastest | x == 0x1102 = Nicest | otherwise = error ("unmarshalHintMode: illegal value " ++ show x) -------------------------------------------------------------------------------- hint :: HintTarget -> StateVar HintMode hint t = makeStateVar (getEnum1 unmarshalHintMode (hintTargetToGetPName t)) (glHint (marshalHintTarget t) . marshalHintMode) foreign import stdcall unsafe "HsOpenGL.h glHint" glHint :: GLenum -> GLenum -> IO ()
OS2World/DEV-UTIL-HUGS
libraries/Graphics/Rendering/OpenGL/GL/Hints.hs
bsd-3-clause
2,907
0
10
490
529
302
227
64
9
{-# LANGUAGE CPP #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE FlexibleContexts #-} #include "inline.hs" -- | -- Module : Streamly.Memory.Malloc -- Copyright : (c) 2019 Composewell Technologies -- -- License : BSD3 -- Maintainer : streamly@composewell.com -- Stability : experimental -- Portability : GHC -- module Streamly.Memory.Malloc ( mallocForeignPtrAlignedBytes , mallocForeignPtrAlignedUnmanagedBytes ) where #define USE_GHC_MALLOC import Foreign.ForeignPtr (ForeignPtr, newForeignPtr_) import Foreign.Marshal.Alloc (mallocBytes) #ifndef USE_GHC_MALLOC import Foreign.ForeignPtr (newForeignPtr) import Foreign.Marshal.Alloc (finalizerFree) #endif import qualified GHC.ForeignPtr as GHC {-# INLINE mallocForeignPtrAlignedBytes #-} mallocForeignPtrAlignedBytes :: Int -> Int -> IO (GHC.ForeignPtr a) #ifdef USE_GHC_MALLOC mallocForeignPtrAlignedBytes size alignment = do GHC.mallocPlainForeignPtrAlignedBytes size alignment #else mallocForeignPtrAlignedBytes size _alignment = do p <- mallocBytes size newForeignPtr finalizerFree p #endif -- memalign alignment size -- foreign import ccall unsafe "stdlib.h posix_memalign" _memalign :: CSize -> CSize -> IO (Ptr a) mallocForeignPtrAlignedUnmanagedBytes :: Int -> Int -> IO (ForeignPtr a) mallocForeignPtrAlignedUnmanagedBytes size _alignment = do -- XXX use posix_memalign/aligned_alloc for aligned allocation p <- mallocBytes size newForeignPtr_ p
harendra-kumar/asyncly
src/Streamly/Memory/Malloc.hs
bsd-3-clause
1,671
0
10
248
189
116
73
24
1
module TypeInference1 where f:: Num a=>a->a->a f x y = x + y + 3
dhaneshkk/haskell-programming
typeInference1.hs
bsd-3-clause
67
0
7
17
42
22
20
3
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE UndecidableInstances #-} module Language.Rsc.Typecheck.Subst ( -- * Substitutions RSubst , RSubstQ (..) , Subst , toList , fromList , toSubst -- * Free Type Variables , Free (..) -- * Type-class with operations , Substitutable , SubstitutableQ (..) ) where import qualified Data.HashMap.Strict as HM import qualified Data.HashSet as S import qualified Language.Fixpoint.Types as F import Language.Rsc.Annotations import Language.Rsc.AST import Language.Rsc.Locations import Language.Rsc.Misc (mapSnd) import Language.Rsc.Names import Language.Rsc.Typecheck.Types import Language.Rsc.Types -- import Debug.Trace --------------------------------------------------------------------------- -- | Substitutions --------------------------------------------------------------------------- -- | Type alias for Map from @TVar@ to @Type@. Hidden data RSubstQ q r = Su (HM.HashMap TVar (RTypeQ q r)) type RSubst r = RSubstQ AK r type Subst = RSubst () toSubst :: RSubst r -> Subst toSubst (Su m) = Su $ HM.map toType m toList :: RSubst r -> [(TVar, RType r)] toList (Su m) = HM.toList m fromList :: [(TVar, RTypeQ q r)] -> RSubstQ q r fromList = Su . HM.fromList -- | Substitutions form a monoid; not commutative instance (F.Reftable r, SubstitutableQ q r (RType r)) => Monoid (RSubstQ q r) where mempty = Su HM.empty mappend (Su m) θ'@(Su m') = Su $ (apply θ' <$> m) `HM.union` m' class Free a where free :: a -> S.HashSet TVar instance Free (RType r) where free (TPrim _ _) = S.empty free (TVar α _) = S.singleton α free (TOr ts _) = free ts free (TAnd ts) = free $ snd <$> ts free (TRef n _) = free n free (TObj _ es _) = free es free (TClass t) = free t free (TMod _) = S.empty free (TAll α t) = S.delete (btvToTV α) $ free t free (TFun xts t _) = free $ [t] ++ (b_type <$> xts) free (TExp _) = error "free should not be applied to TExp" instance Free (TGen r) where free (Gen _ ts) = free ts instance Free (TypeMembers r) where free (TM ms sms cl ct s n) = S.unions [free ms, free sms, free cl, free ct, free s, free n] instance Free t => Free (F.SEnv t) where free = free . map snd . F.toListSEnv instance Free (TypeMember r) where free (FI _ _ m t) = free [m, t] free (MI _ _ mts) = free $ map snd mts instance Free a => Free [a] where free = S.unions . map free instance Free (Fact r) where -- free (PhiVarTy (_,t)) = free t free (TypInst _ _ ts) = free ts free (EltOverload _ t t') = free [t, t'] free (VarAnn _ _ _ t ) = free t free (MemberAnn f) = free f free (CtorAnn c) = free c free (UserCast t) = free t free (SigAnn _ _ c) = free c free (ClassAnn _ t) = free t -- foldr S.delete (free $ e ++ i) vs free (InterfaceAnn t) = free t -- foldr S.delete (free $ e ++ i) vs -- TODO: TypeCast free _ = S.empty instance Free (TypeSig r) where free (TS _ n h) = S.unions [free n, free h] instance Free (TypeDecl r) where free (TD s _ m) = S.unions [free s, free m] instance Free (BTGen r) where free (BGen n ts) = S.unions [free n, free ts] instance Free (BTVar r) where free (BTV _ _ t) = free t instance Free a => Free (RelName, a) where free (_, a) = free a instance Free a => Free (Maybe a) where free Nothing = S.empty free (Just a) = free a instance (Free a, Free b) => Free (a,b) where free (a,b) = free a `S.union` free b instance Free (QN l) where free _ = S.empty type Substitutable = SubstitutableQ AK class SubstitutableQ q r a where apply :: (RSubstQ q r) -> a -> a instance SubstitutableQ q r a => SubstitutableQ q r [a] where apply = map . apply instance (SubstitutableQ q r a, SubstitutableQ q r b) => SubstitutableQ q r (a,b) where apply f (x,y) = (apply f x, apply f y) instance F.Reftable r => SubstitutableQ q r (RTypeQ q r) where apply θ t = appTy θ t instance F.Reftable r => SubstitutableQ q r (BindQ q r) where apply θ (B z o t) = B z o $ appTy θ t instance SubstitutableQ q r t => SubstitutableQ q r (Located t) where apply θ (Loc s v) = Loc s $ apply θ v instance F.Reftable r => SubstitutableQ q r (FactQ q r) where -- apply θ (PhiVarTy (v,t)) = PhiVarTy . (v,) $ apply θ t apply θ (TypInst i ξ ts) = TypInst i ξ $ apply θ ts apply θ (EltOverload ξ t t') = EltOverload ξ (apply θ t) (apply θ t') apply θ (VarAnn x l a t) = VarAnn x l a $ apply θ t apply θ (MemberAnn f) = MemberAnn $ apply θ f apply θ (CtorAnn t) = CtorAnn $ apply θ t apply θ (UserCast t) = UserCast $ apply θ t apply θ (SigAnn x l t) = SigAnn x l $ apply θ t apply θ (ClassAnn l t) = ClassAnn l $ apply θ t apply θ (InterfaceAnn t) = InterfaceAnn $ apply θ t -- TODO: TypeCast apply _ a = a instance F.Reftable r => SubstitutableQ q r (TypeMemberQ q r) where apply θ (FI s ms m t) = FI s ms (apply θ m) (apply θ t) apply θ (MI s o mts) = MI s o (mapSnd (apply θ) <$> mts) instance SubstitutableQ q r a => SubstitutableQ q r (Maybe a) where apply θ (Just a) = Just $ apply θ a apply _ Nothing = Nothing instance F.Reftable r => SubstitutableQ q r (TGenQ q r) where apply θ (Gen n ts) = Gen n $ apply θ ts instance F.Reftable r => SubstitutableQ q r (BTGenQ q r) where apply θ (BGen n ts) = BGen n $ apply θ ts instance F.Reftable r => SubstitutableQ q r (BTVarQ q r) where apply θ (BTV s l c) = BTV s l $ apply θ c instance F.Reftable r => SubstitutableQ q r (TypeMembersQ q r) where apply θ (TM ms sms cl ct s n) = TM (apply θ ms) (apply θ sms) (apply θ cl) (apply θ ct) (apply θ s) (apply θ n) instance SubstitutableQ q r a => SubstitutableQ q r (F.SEnv a) where apply = fmap . apply instance SubstitutableQ q r (Id a) where apply _ i = i instance F.Reftable r => SubstitutableQ q r (Annot (FactQ q r) z) where apply θ (Ann i z fs) = Ann i z $ apply θ fs instance SubstitutableQ q r F.Symbol where apply _ s = s instance SubstitutableQ q r (QN l) where apply _ s = s instance SubstitutableQ q r (QP l) where apply _ s = s instance F.Reftable r => SubstitutableQ q r (TypeSigQ q r) where apply θ (TS k n h) = TS k n (apply θ h) instance F.Reftable r => SubstitutableQ q r (TypeDeclQ q r) where apply θ (TD s p m) = TD (apply θ s) p (apply θ m) instance (F.Reftable r, SubstitutableQ q r a) => SubstitutableQ q r (Statement a) where apply θ s = fmap (apply θ) s instance SubstitutableQ q r Assignability where apply _ s = s instance SubstitutableQ q r Locality where apply _ s = s instance (SubstitutableQ q r a, SubstitutableQ q r b, SubstitutableQ q r c) => SubstitutableQ q r (a,b,c) where apply θ (a,b,c) = (apply θ a, apply θ b, apply θ c) instance F.Reftable r => SubstitutableQ q r (FAnnQ q r) where apply θ (FA i s fs) = FA i s $ apply θ fs --------------------------------------------------------------------------------- appTy :: F.Reftable r => RSubstQ q r -> RTypeQ q r -> RTypeQ q r --------------------------------------------------------------------------------- appTy _ (TPrim p r) = TPrim p r appTy (Su m) t@(TVar α r) = (HM.lookupDefault t α m) `strengthen` r appTy θ (TOr ts r) = tOrR (apply θ ts) r appTy θ (TAnd ts) = TAnd (mapSnd (apply θ) <$> ts) appTy θ (TRef n r) = TRef (apply θ n) r appTy θ (TObj m es r) = TObj (appTy θ m) (apply θ es) r appTy θ (TClass t) = TClass (apply θ t) appTy _ (TMod n) = TMod n appTy (Su m) (TAll α t) = TAll α $ apply (Su $ HM.delete (btvToTV α) m) t appTy θ (TFun ts t r) = TFun (apply θ ts) (apply θ t) r appTy _ (TExp _) = error "appTy should not be applied to TExp" --------------------------------------------------------------------------------- -- | Type equality (modulo α-renaming) --------------------------------------------------------------------------------- instance (F.Reftable r, Eq q) => Eq (TGenQ q r) where Gen n ts == Gen n' ts' = n == n' && ts == ts' instance (F.Reftable r, Eq q) => Eq (TypeMembersQ q r) where TM m sm c k s n == TM m' sm' c' k' s' n' = m == m' && sm == sm' && c == c' && k == k' && s == s' && n == n' instance (F.Reftable r, Eq q) => Eq (TypeMemberQ q r) where FI n o a t == FI n' o' a' t' = n == n' && o == o' && a == a' && t == t' MI m k mt == MI m' k' mt' = m == m' && k == k' && mt == mt' _ == _ = False instance (F.Reftable r, Eq q) => Eq (BindQ q r) where B x o t == B x' o' t' = (x, o, t) == (x', o', t') instance (F.Reftable r, Eq q) => Eq (BTGenQ q r) where BGen n1 b1s == BGen n2 b2s = n1 == n2 && b1s == b2s instance (F.Reftable r, Eq q) => Eq (BTVarQ q r) where BTV _ _ c1 == BTV _ _ c2 = c1 == c2 instance (F.Reftable r, Eq q) => Eq (RTypeQ q r) where TPrim p _ == TPrim p' _ = p == p' TVar α _ == TVar α' _ = α == α' TOr ts _ == TOr ts' _ = ts == ts' TAnd ts == TAnd ts' = ts == ts' TRef g _ == TRef g' _ = g == g' TObj m ms _ == TObj m' ms' _ = m == m' && ms == ms' TClass g == TClass g' = g == g' TMod n == TMod n' = n == n' TAll v@(BTV _ b _) t == TAll v'@(BTV _ b' _) t' = b == b' && t == appTy θ t' where θ = fromList [(btvToTV v', tVar $ btvToTV v)] TFun bs o _ == TFun bs' o' _ = bs == bs' && o == o' _ == _ = False
UCSD-PL/RefScript
src/Language/Rsc/Typecheck/Subst.hs
bsd-3-clause
10,679
0
16
3,537
4,553
2,271
2,282
201
1
{-# LANGUAGE DeriveGeneric #-} module UnitTests (ioTests, tests) where import Control.Monad (forM) import Data.Aeson (eitherDecode, encode, genericToJSON, genericToEncoding) import Data.Aeson.Encode (encodeToTextBuilder) import Data.Aeson.Types (ToJSON(..), Value, camelTo, defaultOptions) import Data.Char (toUpper) import GHC.Generics (Generic) import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, assertFailure, assertEqual) import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.Text.Lazy.Builder as TLB import qualified Data.Text.Lazy.Encoding as TLE tests :: Test tests = testGroup "unit" [ testGroup "camelCase" [ testCase "camelTo" $ roundTripCamel "aName" , testCase "camelTo" $ roundTripCamel "another" , testCase "camelTo" $ roundTripCamel "someOtherName" ] , testGroup "encoding" [ testCase "goodProducer" $ goodProducer ] ] roundTripCamel :: String -> Assertion roundTripCamel name = assertEqual "" name (camelFrom '_' $ camelTo '_' name) where camelFrom c s = let (p:ps) = split c s in concat $ p : map capitalize ps split c s = map L.unpack $ L.split c $ L.pack s capitalize t = toUpper (head t) : tail t data Wibble = Wibble { wibbleString :: String , wibbleInt :: Int } deriving (Generic, Show) instance ToJSON Wibble where toJSON = genericToJSON defaultOptions toEncoding = genericToEncoding defaultOptions -- Test that if we put a bomb in a data structure, but only demand -- part of it via lazy encoding, we do not unexpectedly fail. goodProducer :: Assertion goodProducer = assertEqual "partial encoding should not explode on undefined" '{' (L.head (encode wibble)) where wibble = Wibble { wibbleString = replicate 4030 'a' , wibbleInt = undefined } ------------------------------------------------------------------------------ -- Comparison between bytestring and text encoders ------------------------------------------------------------------------------ ioTests :: IO [Test] ioTests = do enc <- encoderComparisonTests return [enc] encoderComparisonTests :: IO Test encoderComparisonTests = do encoderTests <- forM testFiles $ \file0 -> do let file = "benchmarks/json-data/" ++ file0 return $ testCase file $ do inp <- L.readFile file case eitherDecode inp of Left err -> assertFailure $ "Decoding failure: " ++ err Right val -> assertEqual "" (encode val) (encodeViaText val) return $ testGroup "encoders" encoderTests where encodeViaText :: Value -> L.ByteString encodeViaText = TLE.encodeUtf8 . TLB.toLazyText . encodeToTextBuilder . toJSON testFiles = [ "example.json" , "integers.json" , "jp100.json" , "numbers.json" , "twitter10.json" , "twitter20.json" , "geometry.json" , "jp10.json" , "jp50.json" , "twitter1.json" , "twitter100.json" , "twitter50.json" ]
nurpax/aeson
tests/UnitTests.hs
bsd-3-clause
3,086
0
20
678
756
410
346
71
2
-- | -- Module : Test.MiniUnit -- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley -- License : BSD-style -- Maintainer : oleg@pobox.com, alistair@abayley.org -- Stability : experimental -- Portability : portable -- -- This is just a simple one-module unit test framework, with the same -- API as "Test.HUnit" (albeit with a lot of stuff missing). -- We use it because it works in 'Control.Exception.MonadIO.CaughtMonadIO' -- instead of IO -- (and also because I couldn't convert "Test.HUnit" -- to use 'Control.Exception.MonadIO.CaughtMonadIO'). {-# LANGUAGE CPP #-} module Test.MiniUnit ( -- ** Primary API runTestTT, assertFailure, assertBool, assertString, assertEqual -- ** Exposed for self-testing only; see "Test.MiniUnitTest" , TestResult(..), throwUserError, runSingleTest, reportResults ) where import Control.Exception.MonadIO import Control.Exception.Extensible import Control.Monad import Control.Monad.Trans (liftIO) import System.IO.Error (ioeGetErrorString) import System.IO import Data.List import Data.IORef data TestResult = TestSuccess | TestFailure String | TestException String deriving (Show, Eq) -- We'll use HUnit's trick of throwing an IOError when an assertion fails. -- This will terminate the test case, obviously, but we catch the exception -- and record that it haa failed so that we can continue with other -- test cases. -- Unlike HUnit, we catch all exceptions; any that are not thrown by -- failed assertions are recorded as test errors (as opposed to test failures), -- and the testing continues... -- When an assertion fails, we throw an IOException with a special -- text prefix, which the exception handler will detect. assertFailure :: CaughtMonadIO m => String -> m () assertFailure msg = throwUserError (exceptionPrefix ++ msg) exceptionPrefix = "MiniUnit:" hugsPrefix = "IO Error: User error\nReason: " nhc98Prefix = "I/O error (user-defined), call to function `userError':\n " ghcPrefix = "" -- We don't use this; it's just documentation... dropPrefix p s = if isPrefixOf p s then drop (length p) s else s trimCompilerPrefixes = dropPrefix hugsPrefix . dropPrefix nhc98Prefix throwUserError :: CaughtMonadIO m => String -> m () throwUserError msg = liftIO (throwIO (userError msg)) runSingleTest :: CaughtMonadIO m => m () -> m TestResult runSingleTest action = do let iohandler :: CaughtMonadIO m =>IOException -> m TestResult iohandler e = let errText = trimCompilerPrefixes (ioeGetErrorString e) in if isPrefixOf exceptionPrefix errText then return (TestFailure (dropPrefix exceptionPrefix errText)) else return (TestException (show e)) errhandler :: CaughtMonadIO m => SomeException -> m TestResult errhandler e = return (TestException (show e)) (action >> return TestSuccess) `gcatch` iohandler `gcatch` errhandler -- Predicates for list filtering isSuccess TestSuccess = True isSuccess _ = False isFailure (TestFailure _) = True isFailure _ = False isError (TestException _) = True isError _ = False -- Make function composition look more like Unix pipes. -- This first definition requires a Point-Free Style. -- I prefer the PFS, as you can use it in (for example) predicate -- functions passed as arguments (see filter example below). infixl 9 |> (|>) = flip (.) -- This second definition affords a more pointed style... -- We can use this operator to inject an argument into a pipe -- defined using |>; it has lower precedence, so will bind last. -- e.g. ... = mylist |>> zip [1..] |> filter (snd |> pred) |> map show |> concat infixl 8 |>> (|>>) = flip ($) --reportFilter pred = zip [1..] |> filter (snd |> pred) |> map testReporter |> concat testReporter (n, TestSuccess) = "" testReporter (n, TestException s) = "Test " ++ show n ++ " failed with exception:\n" ++ s ++ "\n" testReporter (n, TestFailure s) = "Test " ++ show n ++ " failed with message:\n" ++ s ++ "\n" reportResults list = let s = list |>> filter isSuccess |> length e = list |>> filter isError |> length f = list |>> filter isFailure |> length in "Test cases: " ++ show (length list) ++ " Failures: " ++ show f ++ " Errors: " ++ show e -- ++ reportFilter isFailure list -- ++ reportFilter isError list -- 2 defns for same result; which is better? --contains pred = filter pred |> null |> not contains p l = maybe False (const True) (find p l) -- | Return 0 if everything is rosy, -- 1 if there were assertion failures (but no exceptions), -- 2 if there were any exceptions. -- You could use this return code as the return code from -- your program, if you're driving from the command line. runTestTT :: CaughtMonadIO m => String -> [m ()] -> m Int runTestTT desc list = do liftIO (putStrLn "") when (desc /= "") (liftIO (putStr (desc ++ " - "))) liftIO (putStrLn ("Test case count: " ++ show (length list))) r <- mapM (\(n, t) -> liftIO (putStr "." >> hFlush stdout) >> runSingleTestTT n t) (zip [1..] list) liftIO (putStrLn "") liftIO (putStrLn (reportResults r)) if contains isError r then return 2 else if contains isFailure r then return 1 else return 0 -- Could use this instead of runSingleTest - it will output -- failures and exceptions as they occur, rather than all -- at the end. runSingleTestTT :: CaughtMonadIO m => Int -> m () -> m TestResult runSingleTestTT n test = do r <- runSingleTest test case r of TestSuccess -> return r TestFailure _ -> liftIO (putStrLn ('\n':(testReporter (n ,r)))) >> return r TestException _ -> liftIO (putStrLn ('\n':(testReporter (n, r)))) >> return r --------------------------------------------- -- That's the basic framework; now for some sugar... -- ... stolen straight from Dean Herrington's HUnit code. -- Shall we steal his infix operators, too? assertBool :: CaughtMonadIO m => String -> Bool -> m () assertBool msg b = unless b (assertFailure msg) assertString :: CaughtMonadIO m => String -> m () assertString s = unless (null s) (assertFailure s) assertEqual :: (Eq a, Show a, CaughtMonadIO m) => String -- ^ message preface -> a -- ^ expected -> a -- ^ actual -> m () assertEqual preface expected actual = do let msg = (if null preface then "" else preface ++ "\n") ++ "expect: " ++ show expected ++ "\nactual: " ++ show actual unless (actual == expected) (assertFailure msg) --p @? msg = assertBool msg p
necrobious/takusen
Test/MiniUnit.hs
bsd-3-clause
6,619
0
18
1,448
1,447
756
691
96
3
module Board where import Data.Bits import Data.Bool.Extras import BitBoard import FEN import Index data Board = Board { bitBoard :: {-# UNPACK #-} !BitBoard, turn :: !Turn, castling :: {-# UNPACK #-} !Castling, enPassant :: !(Maybe Index), halfMoveClock :: {-# UNPACK #-} !HalfMoveClock, fullMoveClock :: {-# UNPACK #-} !FullMoveClock, wKing :: {-# UNPACK #-} !Index, bKing :: {-# UNPACK #-} !Index } instance Show Board where show = show . toFEN startingBoard :: Board startingBoard = fromFEN startingFEN --TODO: Two options: 1 We move throwing an error to the parsing function -- 2 Change the type sig to FEN -> Maybe Board fromFEN :: FEN -> Board fromFEN (FEN bb t crs ep hc fc) = Board bb t crs ep hc fc (initKings white) (initKings black) where initKings color = bool ((countTrailingZeros . color . kingsB) bb) (error "King not placed in FEN") (((== 0) . color . kingsB) bb) toFEN :: Board -> FEN toFEN (Board bb t c ep hc fc _ _) = FEN bb t c ep hc fc
mckeankylej/hchess
src/Board.hs
bsd-3-clause
1,177
0
13
392
306
168
138
30
1
{-# LANGUAGE QuasiQuotes, TypeFamilies #-} module File.Binary.ICCProfile.TagTypes_yet where import File.Binary import File.Binary.Instances () import File.Binary.Instances.BigEndian () [binary| NDIN2 deriving Show arg :: Int replicate 9 4{[Int]}: hoge_NDIN2 replicate 3 4{[Int]}: hage_NDIN2 replicate 3 2{[Int]}: hige_NDIN2 replicate ((arg - 58) `div` 2) 2{[Int]}: body_NDIN2 {- (4, Just 9){[Int]}: hoge_NDIN2 (4, Just 3){[Int]}: hage_NDIN2 (2, Just 3){[Int]}: hige_NDIN2 (2, Just ((arg - 58) `div` 2)){[Int]}: body_NDIN2 -} |] [binary| VCGT2 deriving Show arg :: Int 4: 0 2: hoge_VCGT2 2: hage_VCGT2 2: hige_VCGT2 replicate (arg - 10) 1{[Int]}: body_VCGT2 -- (2, Just (arg `div` 2 - 7)){[Int]}: body_VCGT2 -- {Int}: some -- (arg - ((arg `div` 2) * 2)): some -- 1: 0 |] [binary| Text2 arg :: Int replicate arg (){String}: text |] instance Show Text2 where show = text [binary| XYZ2 deriving Show arg :: Int {XYZ}: xyz -- 4: xyz_X -- 4: xyz_Y -- 4: xyz_Z |] [binary| Desc deriving Show arg :: Int replicate arg (){String}: body_desc |] [binary| CHAD2 deriving Show arg :: Int 4: chad2_a0 4: chad2_a1 4: chad2_a2 4: chad2_a3 4: chad2_a4 4: chad2_a5 4: chad2_a6 4: chad2_a7 4: chad2_a8 |] {- [binary| MLUC2 deriving Show arg :: Int 4: num_MLUC2 4: 12 ((), Just num_MLUC2){[MLUC_RECORD2]}: record_MLUC2 ((), Just (arg - 12 * num_MLUC2 - 8)){String}: body_MLUC2 |] [binary| MLUC_RECORD2 deriving Show ((), Just 2){String}: lang_MLUC2 ((), Just 2){String}: country_MLUC2 4: len_MLUC2 4: offset_MLUC2 |] -} [binary| MMOD2 arg :: Int replicate arg (){String}: body_MMOD2 |] instance Show MMOD2 where show mmod = "(MMOD2 " ++ show (body_MMOD2 mmod) ++ ")" [binary| Para2 arg :: Int 2: functype_Para2 2: 0 4: g_Para2 4: a_Para2 4: b_Para2 4: c_Para2 4: d_Para2 |] instance Show Para2 where show para = "(Para2 " ++ show (functype_Para2 para) ++ " " ++ show (g_Para2 para) ++ " " ++ show (a_Para2 para) ++ " " ++ show (b_Para2 para) ++ " " ++ show (c_Para2 para) ++ " " ++ show (d_Para2 para) ++ ")" [binary| XYZ deriving Show 4: xyz_X 4: xyz_Y 4: xyz_Z |]
YoshikuniJujo/iccp-file
src/File/Binary/ICCProfile/TagTypes_yet.hs
bsd-3-clause
2,122
14
20
413
275
155
120
27
0
-- ff.hs module Math.FF where import Math.NumberTheoryFundamentals (extendedEuclid) import Bits ( (.&.), xor ) data FF = F Integer Integer -- deriving Show instance Eq FF where F p x == F q y | p == q = x == y | p == 0 && q == 0 = False -- because we already know x /= y | p == 0 = x `mod` q == y | q == 0 = x == y `mod` p instance Ord FF where compare (F _ x) (F _ y) = compare x y instance Show FF where show (F p x) = show x -- | p == 0 = show x -- | x <= p `div` 2 = show x -- | otherwise = show (x-p) toFp p x = F p (x `mod` p) -- finds the representative from 0..p-1 instance Num FF where F 0 x + F 0 y = F 0 (x+y) F p x + F q y | p == q = toFp p (x+y) F p x + F 0 y = toFp p (x+y) F 0 x + F q y = toFp q (x+y) negate (F p 0) = F p 0 negate (F p x) = F p (p-x) F 0 x * F 0 y = F 0 (x*y) F p x * F q y | p == q = toFp p (x*y) F p x * F 0 y = toFp p (x*y) F 0 x * F q y = toFp q (x*y) fromInteger n = F 0 n instance Fractional FF where recip (F 0 _) = error "FF.recip: F 0 _" recip (F p x) | x == 0 = error "FF.recip: F p 0" | x == 1 = F p 1 | otherwise = toFp p u where (u,v,1) = extendedEuclid x p -- this has consequence that F p x / F 0 y results in error, whereas we could evaluate to F p (x/y) x % p = toFp p x -- F2 newtype F2 = F2 Int deriving (Eq, Ord) instance Show F2 where show (F2 x) = show x instance Num F2 where F2 x + F2 y = F2 (x `xor` y) negate (F2 x) = F2 x F2 x * F2 y = F2 (x .&. y) fromInteger n = if even n then F2 0 else F2 1 instance Fractional F2 where recip (F2 1) = F2 1 recip (F2 0) = error "F2.recip: division by zero"
nfjinjing/bench-euler
src/Math/FF.hs
bsd-3-clause
1,813
0
11
685
921
446
475
45
1
module Parser ( defaultAppState, AppState(..), parseString ) where import Text.Parsec import Text.Parsec.String import Data.Functor.Identity (runIdentity) data AppState = AppState { appId :: Int, universe :: Int, name :: String, stateFlags :: Int, installDir :: String, lastUpdated :: Int, updateResult :: Int, sizeOnDisk :: Int, buildId :: Int, lastOwner :: Int, bytesToDownload :: Int, bytesDownloaded :: Int, autoUpdateBehavior :: Int, allowOtherDownloadsWhileRunning :: Int, userConfig :: UserConfig, mountedDepots :: MountedDepots } deriving (Eq, Show) data UserConfig = UserConfig {language :: String} deriving (Eq, Show) data MountedDepots = MountedDepots [MountedDepot] deriving (Eq, Show) type MountedDepot = (Int,Int) type AppParser = Parsec String AppState type StateModifier k = k -> AppState -> AppState defaultAppState = AppState 0 0 "" 0 "" 0 0 0 0 0 0 0 0 0 (UserConfig "") (MountedDepots []) stringStateModifiers :: [(String, StateModifier String)] stringStateModifiers = [("name", (\x u -> u {name = x})), ("installdir",(\x u -> u {installDir = x})) ] intStateModifiers :: [(String,StateModifier Int)] intStateModifiers = [ ("appid", (\x u -> u {appId = x})), ("Universe",(\x u -> u {universe = x})), ("StateFlags",(\x u -> u {stateFlags = x})), ("LastUpdated",(\x u -> u {lastUpdated = x})), ("UpdateResult",(\x u -> u {updateResult = x})), ("SizeOnDisk",(\x u -> u {sizeOnDisk = x})), ("buildid",(\x u -> u {buildId = x})), ("LastOwner",(\x u -> u {lastOwner = x})), ("BytesToDownload",(\x u -> u {bytesToDownload = x})), ("BytesDownloaded",(\x u -> u {bytesDownloaded = x})), ("AutoUpdateBehavior",(\x u -> u {autoUpdateBehavior = x})), ("AllowOtherDownloadsWhileRunning",(\x u -> u {allowOtherDownloadsWhileRunning = x})) ] quotation = char '"' quotedWord :: AppParser String quotedWord = many $ satisfy (/='"') parseQuote :: AppParser a -> AppParser a parseQuote u = between quotation quotation u parseLine :: AppParser () parseLine = do label <- phrase value <- phrase modifyState $ case lookup label stringStateModifiers of Just f -> f value Nothing -> case lookup label intStateModifiers of Just f -> f (read value :: Int) Nothing -> id where phrase = spaces >> parseQuote quotedWord parseLoop :: AppParser () parseLoop = (try parseLine) <|> nextLine where nextLine = manyTill anyToken newline >> return () parseBlock :: AppParser AppState parseBlock = manyTill parseLoop eof >> getState parseString :: AppState -> String -> (Either ParseError AppState) parseString u = runIdentity . runParserT parseBlock u "parsing steam app string"
hherman1/Steam-Browser
Parser.hs
mit
2,688
72
16
502
1,073
617
456
69
3
module Wallet.Inductive.Validation ( ValidatedInductive(..) , InductiveValidationError(..) , inductiveIsValid ) where import Universum import qualified Data.List as List import qualified Data.Set as Set import Formatting (bprint, build, (%)) import qualified Formatting.Buildable import Pos.Core.Chrono import Data.Validated import UTxO.DSL import UTxO.Util import Wallet.Inductive {------------------------------------------------------------------------------- Successful validation result -------------------------------------------------------------------------------} -- | Result of validating an inductive wallet data ValidatedInductive h a = ValidatedInductive { -- | Bootstrap transaction used viBoot :: Transaction h a -- | Final ledger (including bootstrap) , viLedger :: Ledger h a -- | Validated events , viEvents :: NewestFirst [] (WalletEvent h a) -- | Final chain (split into blocks, not including bootstrap) , viChain :: NewestFirst [] (Block h a) -- | UTxO after each block , viUtxos :: NewestFirst NonEmpty (Utxo h a) } {------------------------------------------------------------------------------- Validation errors -------------------------------------------------------------------------------} data InductiveValidationError h a = -- | Bootstrap transaction is invalid -- InductiveInvalidBoot -- inductiveInvalidBoot = The bootstrap transaction -- inductiveInvalidError = The error message InductiveInvalidBoot !(Transaction h a) !Text -- | Invalid transaction in the given block -- InductiveInvalidApplyBlock -- inductiveInvalidEvents = The events leading up to the error -- inductiveInvalidBlockPrefix = The transactions in the block we -- successfully validated -- inductiveInvalidTransaction = The transaction that was invalid -- inductiveInvalidError = The error message | InductiveInvalidApplyBlock !(OldestFirst [] (WalletEvent h a)) !(OldestFirst [] (Transaction h a)) !(Transaction h a) !Text -- | A 'NewPending' call was invalid because the input was already spent -- InductiveInvalidNewPendingAlreadySpent -- inductiveInvalidEvents = The events leading up to the error -- inductiveInvalidTransaction = The transaction that was invalid -- inductiveInvalidInput = The specific input that was not valid | InductiveInvalidNewPendingAlreadySpent !(OldestFirst [] (WalletEvent h a)) !(Transaction h a) !(Input h a) -- | A 'NewPending' call was invalid because the input was not @ours@ -- InductiveInvalidNewPendingNotOurs -- inductiveInvalidEvents = The events leading up to the error -- inductiveInvalidTransaction = The transaction that was invalid -- inductiveInvalidInput = The specific input that was not valid -- inductiveInvalidAddress = The address this input belonged to | InductiveInvalidNewPendingNotOurs !(OldestFirst [] (WalletEvent h a)) !(Transaction h a) !(Input h a) !a {------------------------------------------------------------------------------- Validation proper -------------------------------------------------------------------------------} -- | Lift ledger validity to 'Inductive' inductiveIsValid :: forall h a. (Hash h a, Buildable a, Ord a) => Inductive h a -> Validated (InductiveValidationError h a) (ValidatedInductive h a) inductiveIsValid Inductive{..} = do goBoot inductiveBoot where goBoot :: Transaction h a -> Validated (InductiveValidationError h a) (ValidatedInductive h a) goBoot boot = do let ledger = ledgerEmpty validatedMapErrors (InductiveInvalidBoot boot) $ trIsAcceptable boot ledger goEvents (getOldestFirst inductiveEvents) ValidatedInductive { viBoot = boot , viLedger = ledgerAdd boot ledger , viEvents = NewestFirst [] , viChain = NewestFirst [] , viUtxos = NewestFirst (trUtxo boot :| []) } goEvents :: [WalletEvent h a] -> ValidatedInductive h a -- accumulator -> Validated (InductiveValidationError h a) (ValidatedInductive h a) goEvents [] acc = return acc goEvents (ApplyBlock b:es) ValidatedInductive{..} = do ledger' <- goBlock (toOldestFirst viEvents) (OldestFirst []) viLedger b goEvents es ValidatedInductive { viBoot = viBoot , viLedger = ledger' , viEvents = liftNewestFirst (ApplyBlock b :) viEvents , viChain = liftNewestFirst ( b :) viChain , viUtxos = newCheckpoint b viUtxos } goEvents (Rollback:es) ValidatedInductive{..} = do -- TODO: We don't deal with rollback quite correctly. We assume that -- transactions become available for newPending immediately after a -- rollback, but actually they won't become available until we have -- seen a sufficient number of blocks (i.e., when we switched to the -- new fork). let chain' = liftNewestFirst List.tail viChain goEvents es ValidatedInductive { viBoot = viBoot , viLedger = revChainToLedger chain' , viEvents = liftNewestFirst (Rollback :) viEvents , viChain = chain' , viUtxos = prevCheckpoint viUtxos } goEvents (NewPending t:es) vi@ValidatedInductive{..} = do let utxo = let NewestFirst (u :| _) = viUtxos in u inputs = Set.toList (trIns t) resolved = map (`utxoAddressForInput` utxo) inputs forM_ (zip inputs resolved) $ \(input, mAddr) -> case mAddr of Nothing -> throwError $ InductiveInvalidNewPendingAlreadySpent (toOldestFirst viEvents) t input Just addr -> unless (addr `Set.member` inductiveOurs) $ throwError $ InductiveInvalidNewPendingNotOurs (toOldestFirst viEvents) t input addr goEvents es vi goBlock :: OldestFirst [] (WalletEvent h a) -- Events leading to this point (for err msgs) -> Block h a -- Prefix of the block already validated (for err msgs) -> Ledger h a -- Ledger so far -> Block h a -- Suffix of the block yet to validate -> Validated (InductiveValidationError h a) (Ledger h a) goBlock events = go where go _ ledger (OldestFirst []) = return ledger go (OldestFirst done) ledger (OldestFirst (t:todo)) = do validatedMapErrors (InductiveInvalidApplyBlock events (OldestFirst done) t) $ trIsAcceptable t ledger go (OldestFirst (done ++ [t])) (ledgerAdd t ledger) (OldestFirst todo) revChainToLedger :: NewestFirst [] (Block h a) -> Ledger h a revChainToLedger = Ledger . NewestFirst . (inductiveBoot :) . concatMap toList . toList newCheckpoint :: Block h a -> NewestFirst NonEmpty (Utxo h a) -> NewestFirst NonEmpty (Utxo h a) newCheckpoint b = liftNewestFirst $ \(u :| us) -> utxoApplyBlock b u :| (u:us) prevCheckpoint :: NewestFirst NonEmpty (Utxo h a) -> NewestFirst NonEmpty (Utxo h a) prevCheckpoint = liftNewestFirst $ \(_u :| (u':us)) -> u' :| us {------------------------------------------------------------------------------- Pretty-printing -------------------------------------------------------------------------------} instance (Hash h a, Buildable a) => Buildable (InductiveValidationError h a) where build (InductiveInvalidBoot inductiveInvalidBoot inductiveInvalidError) = bprint ( "InductiveInvalidBoot" % "{ boot: " % build % ", error: " % build % "}" ) inductiveInvalidBoot inductiveInvalidError build (InductiveInvalidApplyBlock inductiveInvalidEvents inductiveInvalidBlockPrefix inductiveInvalidTransaction inductiveInvalidError) = bprint ( "InductiveInvalidApplyBlock" % "{ events: " % build % ", blockPrefix: " % build % ", transaction: " % build % ", error: " % build % "}") inductiveInvalidEvents inductiveInvalidBlockPrefix inductiveInvalidTransaction inductiveInvalidError build (InductiveInvalidNewPendingAlreadySpent inductiveInvalidEvents inductiveInvalidTransaction inductiveInvalidInput) = bprint ( "InductiveInvalidNewPendingAlreadySpent" % "{ events: " % build % ", transaction: " % build % ", input: " % build % "}" ) inductiveInvalidEvents inductiveInvalidTransaction inductiveInvalidInput build (InductiveInvalidNewPendingNotOurs inductiveInvalidEvents inductiveInvalidTransaction inductiveInvalidInput inductiveInvalidAddress) = bprint ( "InductiveInvalidNewPendingNotOurs" % "{ events: " % build % ", transaction: " % build % ", input: " % build % ", address: " % build % "}" ) inductiveInvalidEvents inductiveInvalidTransaction inductiveInvalidInput inductiveInvalidAddress
input-output-hk/pos-haskell-prototype
wallet/test/unit/Wallet/Inductive/Validation.hs
mit
9,785
0
18
2,900
1,814
949
865
-1
-1
{- | Module : ./Common/PrintLaTeX.hs Description : functions for LaTeX pretty printing Copyright : (c) Klaus Luettich, Christian Maeder and Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable Functions for LaTeX pretty printing -} module Common.PrintLaTeX ( renderLatex , latexHeader , latexFooter ) where import Data.Char (isSpace, isDigit) import Common.Lib.State import Data.List (isPrefixOf, isSuffixOf) import Data.Maybe (fromMaybe) import Common.Lib.Pretty import Common.LaTeX_funs -- the header of the LaTeX-file that will be processed by pdflatex latexHeader :: String latexHeader = unlines [ "\\documentclass{article}" , "\\usepackage{hetcasl}" , "\\usepackage{textcomp}" , "\\usepackage[T1]{fontenc}" , "\\begin{document}" ] -- the ending document string latexFooter :: String latexFooter = "\n\\end{document}\n" -- a style for formatting (Standard is Style PageMode 50 1.19) latexStyle :: Style latexStyle = style { ribbonsPerLine = 1.1 , lineLength = calcLineLen 345 } -- for svmono you need 336.0pt {- a LatexRenderingState field indentTabs : for the number of tab stops set those need to be rendererd after every newline. field recentlySet : number of setTab makros indentTabs is only increased if recentlySet is 0 -} data LRState = LRS { indentTabs :: ![Int] , recentlySet , totalTabStops , setTabsThisLine , indentTabsWritten :: !Int , onlyTabs :: !Bool , isSetLine :: !Bool , collSpaceIndents :: ![Int] , insideAnno :: Bool } deriving Show -- the initial state for using the state based rendering via LRState initialLRState :: LRState initialLRState = LRS { indentTabs = [] , recentlySet = 0 , totalTabStops = 0 , setTabsThisLine = 0 , indentTabsWritten = 0 , onlyTabs = False , isSetLine = False , collSpaceIndents = [] , insideAnno = False } showTextDetails :: TextDetails -> String showTextDetails t = case t of Chr c -> [c] Str s -> s PStr s -> s maxTabs :: Int maxTabs = 12 -- a function that knows how to print LaTeX TextDetails latexTxt :: TextDetails -> State LRState ShowS -> State LRState ShowS latexTxt td cont = let s1 = showTextDetails td in case s1 of "" -> cont "\n" -> do annoBrace <- endOfLine indent <- getIndent s <- cont return $ annoBrace . showString "\\\\\n" . indent . s _ | all isSpace s1 -> do s2 <- cont return $ showChar ' ' . s2 | s1 == startTab -> do indent <- addTabStop s2 <- cont return $ indent . s2 | s1 == endTab -> do subTabStop cont | s1 == setTab -> do s <- get setTabStop s2 <- cont let (eAn, sAn) = if insideAnno s then (showChar '}', showString startAnno) else (id, id) return $ eAn . (if indentTabsWritten s + setTabsThisLine s > maxTabs || onlyTabs s then id else showString s1) . sAn . s2 | setTabWSp `isPrefixOf` s1 -> do addTabWithSpaces s1 cont | s1 == startAnno -> do setInsideAnno True s2 <- cont return $ showString s1 . s2 | s1 == endAnno -> do setInsideAnno False s2 <- cont return $ showChar '}' . s2 | "\\kill\n" `isSuffixOf` s1 -> do indent <- getIndent s2 <- cont return $ showString s1 . indent . s2 _ -> do setOnlyTabs False s2 <- cont return $ showString s1 . s2 setOnlyTabs :: Bool -> State LRState () setOnlyTabs b = modify $ \ s -> s { onlyTabs = b } setInsideAnno :: Bool -> State LRState () setInsideAnno b = modify $ \ s -> s { insideAnno = b } -- a function to produce a String containing the actual tab stops in use getIndent :: State LRState ShowS getIndent = do s <- get let indentTabsSum = min (succ maxTabs) $ sum $ indentTabs s collSpcInds = collSpaceIndents s put $ s { indentTabsWritten = indentTabsSum , collSpaceIndents = [] , onlyTabs = True , totalTabStops = max (totalTabStops s) $ indentTabsSum + length collSpcInds } let indent_fun = tabIndent indentTabsSum space_format sf1 i = sf1 . showString (replicate i '~') . showString "\\=" new_tab_line = foldl space_format id (collSpaceIndents s) . showString "\\kill\n" sAnno = if insideAnno s then showString startAnno else id return $ (if null collSpcInds then indent_fun else indent_fun . new_tab_line . indent_fun) . sAnno tabIndent :: Int -> ShowS tabIndent n = foldl (.) id $ replicate n $ showString "\\>" endOfLine :: State LRState ShowS endOfLine = do s <- get put s { isSetLine = False , setTabsThisLine = 0 } return $ if insideAnno s then showChar '}' else id setTabStop :: State LRState () setTabStop = modify $ \ s -> let new_setTabsThisLine = succ $ setTabsThisLine s in if onlyTabs s then s { isSetLine = True } else s { recentlySet = succ $ recentlySet s , setTabsThisLine = new_setTabsThisLine , totalTabStops = max (totalTabStops s) (new_setTabsThisLine + indentTabsWritten s) , isSetLine = True } addTabWithSpaces :: String -> State LRState () addTabWithSpaces str = let delay :: Int delay = read . reverse . takeWhile isDigit . tail $ reverse str in modify $ \ s -> s { collSpaceIndents = collSpaceIndents s ++ [delay] } -- increase the indentTabs in the state by 1 addTabStop :: State LRState ShowS addTabStop = state $ \ s -> let lineSet = isSetLine s recent = recentlySet s newTabs = if lineSet then recent else 1 new_indentTabs = let iTabs = indentTabs s in if newTabs + sum iTabs > totalTabStops s then iTabs else iTabs ++ [newTabs] new_recentlySet = if lineSet then 0 else recent inTabs = tabIndent newTabs (indent_fun, new_indentTabsWritten) = let writtenTabs = indentTabsWritten s in if sum new_indentTabs > writtenTabs && not lineSet && onlyTabs s then (inTabs, newTabs + writtenTabs) else (id, writtenTabs) in (indent_fun, s { recentlySet = new_recentlySet , indentTabs = new_indentTabs , indentTabsWritten = new_indentTabsWritten }) -- decrease the indentTabs in the state by 1 subTabStop :: State LRState () subTabStop = modify $ \ s -> s { indentTabs = case indentTabs s of [] -> [] itabs -> init itabs } -- functions for producing IO printable Strings renderLatexCore :: Style -> Doc -> ShowS renderLatexCore latexStyle' d = evalState (fullRender (mode latexStyle') (lineLength latexStyle') (ribbonsPerLine latexStyle') latexTxt (return id) d) initialLRState renderLatex :: Maybe Int -> Doc -> String renderLatex mi d = showString "\\begin{hetcasl}\n" $ renderLatexCore latexStyle' d "\n\\end{hetcasl}\n" where latexStyle' = latexStyle { lineLength = fromMaybe (lineLength latexStyle) mi }
spechub/Hets
Common/PrintLaTeX.hs
gpl-2.0
7,137
2
21
1,931
1,794
945
849
204
6
{-# LANGUAGE TemplateHaskell #-} module Lamdu.Annotations ( Mode(..), _Evaluation, _Types, _None ) where import qualified Control.Lens as Lens import qualified Data.Aeson.TH.Extended as JsonTH import Lamdu.Prelude data Mode = Evaluation | Types | None deriving (Generic, Eq, Ord, Show) JsonTH.derivePrefixed "" ''Mode Lens.makePrisms ''Mode
lamdu/lamdu
src/Lamdu/Annotations.hs
gpl-3.0
367
0
6
69
102
61
41
10
0
{- Infrastructure for typechecking. -} {-# LANGUAGE RecordWildCards #-} module Checker where import IOEnv import JavaUtils import qualified JvmTypeQuery import Src import SrcLoc import TypeErrors import Control.Monad.Except import qualified Data.Map as Map import qualified Data.Set as Set type Checker a = ExceptT (Located TypeError) (IOEnv CheckerState) a getCheckerState :: Checker CheckerState getCheckerState = lift getEnv setCheckerState :: CheckerState -> Checker () setCheckerState tc_env = lift $ setEnv tc_env getTypeContext :: Checker TypeContext getTypeContext = liftM checkerTypeContext getCheckerState getValueContext :: Checker ValueContext getValueContext = liftM checkerValueContext getCheckerState getTypeServer :: Checker JvmTypeQuery.Connection getTypeServer = liftM checkerTypeServer getCheckerState getMemoizedJavaClasses :: Checker (Set.Set ClassName) getMemoizedJavaClasses = liftM checkerMemoizedJavaClasses getCheckerState memoizeJavaClass :: ClassName -> Checker () memoizeJavaClass c = do CheckerState{..} <- getCheckerState memoized_java_classes <- getMemoizedJavaClasses setCheckerState CheckerState{ checkerMemoizedJavaClasses = c `Set.insert` memoized_java_classes, ..} withLocalTVars :: [(Name, Kind)] -> Checker a -> Checker a withLocalTVars tvars do_this = do delta <- getTypeContext let delta' = addTVarToContext tvars delta CheckerState {..} <- getCheckerState setCheckerState CheckerState { checkerTypeContext = delta', ..} r <- do_this CheckerState {..} <- getCheckerState setCheckerState CheckerState { checkerTypeContext = delta, ..} return r withLocalConstrainedTVars :: [(Name, Maybe Type)] -> Checker a -> Checker a withLocalConstrainedTVars tvars do_this = do delta <- getTypeContext let delta' = addConstrainedTVarToContext tvars delta CheckerState {..} <- getCheckerState setCheckerState CheckerState { checkerTypeContext = delta', ..} r <- do_this CheckerState {..} <- getCheckerState setCheckerState CheckerState { checkerTypeContext = delta, ..} return r withTypeSynonym :: [(Name, Type, Kind)] -> Checker a -> Checker a withTypeSynonym tvars do_this = do delta <- getTypeContext let delta' = addTypeSynonym tvars delta CheckerState {..} <- getCheckerState setCheckerState CheckerState { checkerTypeContext = delta', ..} r <- do_this CheckerState {..} <- getCheckerState setCheckerState CheckerState { checkerTypeContext = delta, ..} return r withLocalVars :: [(Name, Type)]-> Checker a -> Checker a withLocalVars vars do_this = do gamma <- getValueContext let gamma' = addVarToContext vars gamma CheckerState {..} <- getCheckerState setCheckerState CheckerState { checkerValueContext = gamma', ..} r <- do_this CheckerState {..} <- getCheckerState setCheckerState CheckerState { checkerValueContext = gamma, ..} return r data CheckerState = CheckerState { checkerTypeContext :: TypeContext , checkerValueContext :: ValueContext , checkerTypeServer :: JvmTypeQuery.Connection , checkerMemoizedJavaClasses :: Set.Set ClassName -- Memoized Java class names } mkInitCheckerState :: JvmTypeQuery.Connection -> CheckerState mkInitCheckerState type_server = CheckerState { checkerTypeContext = Map.empty , checkerValueContext = Map.empty , checkerTypeServer = type_server , checkerMemoizedJavaClasses = Set.empty } -- Temporary hack for REPL mkInitCheckerStateWithEnv :: ValueContext -> JvmTypeQuery.Connection -> CheckerState mkInitCheckerStateWithEnv value_ctxt type_server = CheckerState { checkerTypeContext = Map.empty , checkerValueContext = value_ctxt , checkerTypeServer = type_server , checkerMemoizedJavaClasses = Set.empty } lookupVar :: Name -> Checker (Maybe Type) lookupVar x = do valueCtxt <- getValueContext return (Map.lookup x valueCtxt) lookupTVarKind :: Name -> Checker (Maybe Kind) lookupTVarKind a = do typeCtxt <- getTypeContext return (fmap (\(kind,_,_) -> kind) (Map.lookup a typeCtxt)) subtype :: Type -> Type -> Checker Bool subtype t1 t2 = do typeCtxt <- getTypeContext return (Src.subtype typeCtxt t1 t2)
zhiyuanshi/fcore
frontend/typecheck/Checker.hs
bsd-2-clause
4,352
0
12
856
1,123
577
546
101
1
module Propellor.Property.Apache where import Propellor import qualified Propellor.Property.File as File import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.Service as Service type ConfigFile = [String] siteEnabled :: HostName -> ConfigFile -> RevertableProperty siteEnabled hn cf = enable <!> disable where enable = combineProperties ("apache site enabled " ++ hn) [ siteAvailable hn cf `requires` installed `onChange` reloaded , check (not <$> isenabled) $ cmdProperty "a2ensite" ["--quiet", hn] `requires` installed `onChange` reloaded ] disable = combineProperties ("apache site disabled " ++ hn) (map File.notPresent (siteCfg hn)) `onChange` cmdProperty "a2dissite" ["--quiet", hn] `requires` installed `onChange` reloaded isenabled = boolSystem "a2query" [Param "-q", Param "-s", Param hn] siteAvailable :: HostName -> ConfigFile -> Property NoInfo siteAvailable hn cf = combineProperties ("apache site available " ++ hn) $ map (`File.hasContent` (comment:cf)) (siteCfg hn) where comment = "# deployed with propellor, do not modify" modEnabled :: String -> RevertableProperty modEnabled modname = enable <!> disable where enable = check (not <$> isenabled) $ cmdProperty "a2enmod" ["--quiet", modname] `describe` ("apache module enabled " ++ modname) `requires` installed `onChange` reloaded disable = check isenabled $ cmdProperty "a2dismod" ["--quiet", modname] `describe` ("apache module disabled " ++ modname) `requires` installed `onChange` reloaded isenabled = boolSystem "a2query" [Param "-q", Param "-m", Param modname] -- This is a list of config files because different versions of apache -- use different filenames. Propellor simply writes them all. siteCfg :: HostName -> [FilePath] siteCfg hn = -- Debian pre-2.4 [ "/etc/apache2/sites-available/" ++ hn -- Debian 2.4+ , "/etc/apache2/sites-available/" ++ hn ++ ".conf" ] installed :: Property NoInfo installed = Apt.installed ["apache2"] restarted :: Property NoInfo restarted = Service.restarted "apache2" reloaded :: Property NoInfo reloaded = Service.reloaded "apache2" -- | Configure apache to use SNI to differentiate between -- https hosts. -- -- This was off by default in apache 2.2.22. Newver versions enable -- it by default. This property uses the filename used by the old version. multiSSL :: Property NoInfo multiSSL = check (doesDirectoryExist "/etc/apache2/conf.d") $ "/etc/apache2/conf.d/ssl" `File.hasContent` [ "NameVirtualHost *:443" , "SSLStrictSNIVHostCheck off" ] `describe` "apache SNI enabled" `onChange` reloaded -- | Config file fragment that can be inserted into a <Directory> -- stanza to allow global read access to the directory. -- -- Works with multiple versions of apache that have different ways to do -- it. allowAll :: String allowAll = unlines [ "<IfVersion < 2.4>" , "Order allow,deny" , "allow from all" , "</IfVersion>" , "<IfVersion >= 2.4>" , "Require all granted" , "</IfVersion>" ]
sjfloat/propellor
src/Propellor/Property/Apache.hs
bsd-2-clause
3,033
60
14
513
724
412
312
66
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.BuildPaths -- Copyright : Isaac Jones 2003-2004, -- Duncan Coutts 2008 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- A bunch of dirs, paths and file names used for intermediate build steps. -- module Distribution.Simple.BuildPaths ( defaultDistPref, srcPref, haddockDirName, hscolourPref, haddockPref, autogenModulesDir, autogenPackageModulesDir, autogenComponentModulesDir, autogenModuleName, autogenPathsModuleName, cppHeaderName, haddockName, mkLibName, mkProfLibName, mkSharedLibName, mkStaticLibName, exeExtension, objExtension, dllExtension, staticLibExtension, -- * Source files & build directories getSourceFiles, getLibSourceFiles, getExeSourceFiles, getFLibSourceFiles, exeBuildDir, flibBuildDir, ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Types.ForeignLib import Distribution.Types.UnqualComponentName (unUnqualComponentName) import Distribution.Package import Distribution.ModuleName as ModuleName import Distribution.Compiler import Distribution.PackageDescription import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Setup import Distribution.Text import Distribution.System import Distribution.Verbosity import Distribution.Simple.Utils import System.FilePath ((</>), (<.>), normalise) -- --------------------------------------------------------------------------- -- Build directories and files srcPref :: FilePath -> FilePath srcPref distPref = distPref </> "src" hscolourPref :: HaddockTarget -> FilePath -> PackageDescription -> FilePath hscolourPref = haddockPref -- | This is the name of the directory in which the generated haddocks -- should be stored. It does not include the @<dist>/doc/html@ prefix. haddockDirName :: HaddockTarget -> PackageDescription -> FilePath haddockDirName ForDevelopment = display . packageName haddockDirName ForHackage = (++ "-docs") . display . packageId -- | The directory to which generated haddock documentation should be written. haddockPref :: HaddockTarget -> FilePath -> PackageDescription -> FilePath haddockPref haddockTarget distPref pkg_descr = distPref </> "doc" </> "html" </> haddockDirName haddockTarget pkg_descr -- | The directory in which we put auto-generated modules for EVERY -- component in the package. See deprecation notice. {-# DEPRECATED autogenModulesDir "If you can, use 'autogenComponentModulesDir' instead, but if you really wanted package-global generated modules, use 'autogenPackageModulesDir'. In Cabal 2.0, we avoid using autogenerated files which apply to all components, because the information you often want in these files, e.g., dependency information, is best specified per component, so that reconfiguring a different component (e.g., enabling tests) doesn't force the entire to be rebuilt. 'autogenPackageModulesDir' still provides a place to put files you want to apply to the entire package, but most users of 'autogenModulesDir' should seriously consider 'autogenComponentModulesDir' if you really wanted the module to apply to one component." #-} autogenModulesDir :: LocalBuildInfo -> String autogenModulesDir = autogenPackageModulesDir -- | The directory in which we put auto-generated modules for EVERY -- component in the package. autogenPackageModulesDir :: LocalBuildInfo -> String autogenPackageModulesDir lbi = buildDir lbi </> "global-autogen" -- | The directory in which we put auto-generated modules for a -- particular component. autogenComponentModulesDir :: LocalBuildInfo -> ComponentLocalBuildInfo -> String autogenComponentModulesDir lbi clbi = componentBuildDir lbi clbi </> "autogen" -- NB: Look at 'checkForeignDeps' for where a simplified version of this -- has been copy-pasted. cppHeaderName :: String cppHeaderName = "cabal_macros.h" {-# DEPRECATED autogenModuleName "Use autogenPathsModuleName instead" #-} -- |The name of the auto-generated module associated with a package autogenModuleName :: PackageDescription -> ModuleName autogenModuleName = autogenPathsModuleName -- | The name of the auto-generated Paths_* module associated with a package autogenPathsModuleName :: PackageDescription -> ModuleName autogenPathsModuleName pkg_descr = ModuleName.fromString $ "Paths_" ++ map fixchar (display (packageName pkg_descr)) where fixchar '-' = '_' fixchar c = c haddockName :: PackageDescription -> FilePath haddockName pkg_descr = display (packageName pkg_descr) <.> "haddock" -- ----------------------------------------------------------------------------- -- Source File helper getLibSourceFiles :: Verbosity -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo -> IO [(ModuleName.ModuleName, FilePath)] getLibSourceFiles verbosity lbi lib clbi = getSourceFiles verbosity searchpaths modules where bi = libBuildInfo lib modules = allLibModules lib clbi searchpaths = componentBuildDir lbi clbi : hsSourceDirs bi ++ [ autogenComponentModulesDir lbi clbi , autogenPackageModulesDir lbi ] getExeSourceFiles :: Verbosity -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo -> IO [(ModuleName.ModuleName, FilePath)] getExeSourceFiles verbosity lbi exe clbi = do moduleFiles <- getSourceFiles verbosity searchpaths modules srcMainPath <- findFile (hsSourceDirs bi) (modulePath exe) return ((ModuleName.main, srcMainPath) : moduleFiles) where bi = buildInfo exe modules = otherModules bi searchpaths = autogenComponentModulesDir lbi clbi : autogenPackageModulesDir lbi : exeBuildDir lbi exe : hsSourceDirs bi getFLibSourceFiles :: Verbosity -> LocalBuildInfo -> ForeignLib -> ComponentLocalBuildInfo -> IO [(ModuleName.ModuleName, FilePath)] getFLibSourceFiles verbosity lbi flib clbi = getSourceFiles verbosity searchpaths modules where bi = foreignLibBuildInfo flib modules = otherModules bi searchpaths = autogenComponentModulesDir lbi clbi : autogenPackageModulesDir lbi : flibBuildDir lbi flib : hsSourceDirs bi getSourceFiles :: Verbosity -> [FilePath] -> [ModuleName.ModuleName] -> IO [(ModuleName.ModuleName, FilePath)] getSourceFiles verbosity dirs modules = flip traverse modules $ \m -> fmap ((,) m) $ findFileWithExtension ["hs", "lhs", "hsig", "lhsig"] dirs (ModuleName.toFilePath m) >>= maybe (notFound m) (return . normalise) where notFound module_ = die' verbosity $ "can't find source for module " ++ display module_ -- | The directory where we put build results for an executable exeBuildDir :: LocalBuildInfo -> Executable -> FilePath exeBuildDir lbi exe = buildDir lbi </> nm </> nm ++ "-tmp" where nm = unUnqualComponentName $ exeName exe -- | The directory where we put build results for a foreign library flibBuildDir :: LocalBuildInfo -> ForeignLib -> FilePath flibBuildDir lbi flib = buildDir lbi </> nm </> nm ++ "-tmp" where nm = unUnqualComponentName $ foreignLibName flib -- --------------------------------------------------------------------------- -- Library file names -- TODO: Should this use staticLibExtension? mkLibName :: UnitId -> String mkLibName lib = "lib" ++ getHSLibraryName lib <.> "a" -- TODO: Should this use staticLibExtension? mkProfLibName :: UnitId -> String mkProfLibName lib = "lib" ++ getHSLibraryName lib ++ "_p" <.> "a" -- Implement proper name mangling for dynamical shared objects -- libHS<packagename>-<compilerFlavour><compilerVersion> -- e.g. libHSbase-2.1-ghc6.6.1.so mkSharedLibName :: CompilerId -> UnitId -> String mkSharedLibName (CompilerId compilerFlavor compilerVersion) lib = "lib" ++ getHSLibraryName lib ++ "-" ++ comp <.> dllExtension where comp = display compilerFlavor ++ display compilerVersion -- Static libs are named the same as shared libraries, only with -- a different extension. mkStaticLibName :: CompilerId -> UnitId -> String mkStaticLibName (CompilerId compilerFlavor compilerVersion) lib = "lib" ++ getHSLibraryName lib ++ "-" ++ comp <.> staticLibExtension where comp = display compilerFlavor ++ display compilerVersion -- ------------------------------------------------------------ -- * Platform file extensions -- ------------------------------------------------------------ -- | Default extension for executable files on the current platform. -- (typically @\"\"@ on Unix and @\"exe\"@ on Windows or OS\/2) exeExtension :: String exeExtension = case buildOS of Windows -> "exe" _ -> "" -- | Extension for object files. For GHC the extension is @\"o\"@. objExtension :: String objExtension = "o" -- | Extension for dynamically linked (or shared) libraries -- (typically @\"so\"@ on Unix and @\"dll\"@ on Windows) dllExtension :: String dllExtension = case buildOS of Windows -> "dll" OSX -> "dylib" _ -> "so" -- | Extension for static libraries -- -- TODO: Here, as well as in dllExtension, it's really the target OS that we're -- interested in, not the build OS. staticLibExtension :: String staticLibExtension = case buildOS of Windows -> "lib" _ -> "a"
themoritz/cabal
Cabal/Distribution/Simple/BuildPaths.hs
bsd-3-clause
9,833
0
12
1,984
1,492
816
676
143
3
-- | -- Copyright : (c) Sam Truzjan 2013 -- License : BSD3 -- Maintainer : pxqr.sta@gmail.com -- Stability : experimental -- Portability : portable -- -- This module provides message datatypes which is used for /Node to -- Node/ communication. Bittorrent DHT is based on Kademlia -- specification, but have a slightly different set of messages -- which have been adopted for /peer/ discovery mechanism. Messages -- are sent over "Network.KRPC" protocol, but normally you should -- use "Network.BitTorrent.DHT.Session" to send and receive -- messages. -- -- DHT queries are not /recursive/, they are /iterative/. This means -- that /querying/ node . While original specification (namely BEP5) -- do not impose any restrictions for /quered/ node behaviour, a -- good DHT implementation should follow some rules to guarantee -- that unlimit recursion will never happen. The following set of -- restrictions: -- -- * 'Ping' query must not trigger any message. -- -- * 'FindNode' query /may/ trigger 'Ping' query to check if a -- list of nodes to return is /good/. See -- 'Network.BitTorrent.DHT.Routing.Routing' for further explanation. -- -- * 'GetPeers' query may trigger 'Ping' query for the same reason. -- -- * 'Announce' query must trigger 'Ping' query for the same reason. -- -- It is easy to see that the most long RPC chain is: -- -- @ -- | | | -- Node_A | | -- | FindNode or GetPeers or Announce | | -- | ------------------------------------> Node_B | -- | | Ping | -- | | -----------> | -- | | Node_C -- | | Pong | -- | NodeFound or GotPeers or Announced | <----------- | -- | <------------------------------------- Node_B | -- Node_A | | -- | | | -- @ -- -- where in some cases 'Node_C' is 'Node_A'. -- -- For more info see: -- <http://www.bittorrent.org/beps/bep_0005.html#dht-queries> -- -- For Kamelia messages see original Kademlia paper: -- <http://pdos.csail.mit.edu/~petar/papers/maymounkov-kademlia-lncs.pdf> -- {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} module Network.BitTorrent.DHT.Message ( -- * Envelopes Query (..) , Response (..) -- * Queries -- ** ping , Ping (..) -- ** find_node , FindNode (..) , NodeFound (..) -- ** get_peers , PeerList , GetPeers (..) , GotPeers (..) -- ** announce_peer , Announce (..) , Announced (..) ) where import Control.Applicative import Data.BEncode as BE import Data.BEncode.BDict import Data.List as L import Data.Monoid import Data.Serialize as S import Data.Typeable import Network import Network.KRPC import Data.Torrent import Network.BitTorrent.Address import Network.BitTorrent.DHT.Token import Network.KRPC () {----------------------------------------------------------------------- -- envelopes -----------------------------------------------------------------------} node_id_key :: BKey node_id_key = "id" -- | All queries have an \"id\" key and value containing the node ID -- of the querying node. data Query a = Query { queringNodeId :: NodeId -- ^ node id of /quering/ node; , queryParams :: a -- ^ query parameters. } deriving (Show, Eq, Typeable) instance BEncode a => BEncode (Query a) where toBEncode Query {..} = toDict $ node_id_key .=! queringNodeId .: endDict <> dict (toBEncode queryParams) where dict (BDict d) = d dict _ = error "impossible: instance BEncode (Query a)" fromBEncode v = do Query <$> fromDict (field (req node_id_key)) v <*> fromBEncode v -- | All responses have an \"id\" key and value containing the node ID -- of the responding node. data Response a = Response { queredNodeId :: NodeId -- ^ node id of /quered/ node; , responseVals :: a -- ^ query result. } deriving (Show, Eq, Typeable) instance BEncode a => BEncode (Response a) where toBEncode = toBEncode . toQuery where toQuery (Response nid a) = Query nid a fromBEncode b = fromQuery <$> fromBEncode b where fromQuery (Query nid a) = Response nid a {----------------------------------------------------------------------- -- ping method -----------------------------------------------------------------------} -- | The most basic query is a ping. Ping query is used to check if a -- quered node is still alive. data Ping = Ping deriving (Show, Eq, Typeable) instance BEncode Ping where toBEncode Ping = toDict endDict fromBEncode _ = pure Ping -- | \"q\" = \"ping\" instance KRPC (Query Ping) (Response Ping) where method = "ping" {----------------------------------------------------------------------- -- find_node method -----------------------------------------------------------------------} -- | Find node is used to find the contact information for a node -- given its ID. newtype FindNode = FindNode NodeId deriving (Show, Eq, Typeable) target_key :: BKey target_key = "target" instance BEncode FindNode where toBEncode (FindNode nid) = toDict $ target_key .=! nid .: endDict fromBEncode = fromDict $ FindNode <$>! target_key -- | When a node receives a 'FindNode' query, it should respond with a -- the compact node info for the target node or the K (8) closest good -- nodes in its own routing table. -- newtype NodeFound ip = NodeFound [NodeInfo ip] deriving (Show, Eq, Typeable) nodes_key :: BKey nodes_key = "nodes" binary :: Serialize a => BKey -> BE.Get [a] binary k = field (req k) >>= either (fail . format) return . runGet (many get) where format str = "fail to deserialize " ++ show k ++ " field: " ++ str instance (Typeable ip, Serialize ip) => BEncode (NodeFound ip) where toBEncode (NodeFound ns) = toDict $ nodes_key .=! runPut (mapM_ put ns) .: endDict fromBEncode = fromDict $ NodeFound <$> binary nodes_key -- | \"q\" == \"find_node\" instance (Serialize ip, Typeable ip) => KRPC (Query FindNode) (Response (NodeFound ip)) where method = "find_node" {----------------------------------------------------------------------- -- get_peers method -----------------------------------------------------------------------} -- | Get peers associated with a torrent infohash. newtype GetPeers = GetPeers InfoHash deriving (Show, Eq, Typeable) info_hash_key :: BKey info_hash_key = "info_hash" instance BEncode GetPeers where toBEncode (GetPeers ih) = toDict $ info_hash_key .=! ih .: endDict fromBEncode = fromDict $ GetPeers <$>! info_hash_key type PeerList ip = Either [NodeInfo ip] [PeerAddr ip] data GotPeers ip = GotPeers { -- | If the queried node has no peers for the infohash, returned -- the K nodes in the queried nodes routing table closest to the -- infohash supplied in the query. peers :: PeerList ip -- | The token value is a required argument for a future -- announce_peer query. , grantedToken :: Token } deriving (Show, Eq, Typeable) peers_key :: BKey peers_key = "values" token_key :: BKey token_key = "token" instance (Typeable ip, Serialize ip) => BEncode (GotPeers ip) where toBEncode GotPeers {..} = toDict $ case peers of Left ns -> nodes_key .=! runPut (mapM_ put ns) .: token_key .=! grantedToken .: endDict Right ps -> token_key .=! grantedToken .: peers_key .=! L.map S.encode ps .: endDict fromBEncode = fromDict $ do mns <- optional (binary nodes_key) -- "nodes" tok <- field (req token_key) -- "token" mps <- optional (field (req peers_key) >>= decodePeers) -- "values" case (Right <$> mps) <|> (Left <$> mns) of Nothing -> fail "get_peers: neihter peers nor nodes key is valid" Just xs -> pure $ GotPeers xs tok where decodePeers = either fail pure . mapM S.decode -- | \"q" = \"get_peers\" instance (Typeable ip, Serialize ip) => KRPC (Query GetPeers) (Response (GotPeers ip)) where method = "get_peers" {----------------------------------------------------------------------- -- announce method -----------------------------------------------------------------------} -- | Announce that the peer, controlling the querying node, is -- downloading a torrent on a port. data Announce = Announce { -- | If set, the 'port' field should be ignored and the source -- port of the UDP packet should be used as the peer's port -- instead. This is useful for peers behind a NAT that may not -- know their external port, and supporting uTP, they accept -- incoming connections on the same port as the DHT port. impliedPort :: Bool -- | infohash of the torrent; , topic :: InfoHash -- | the port /this/ peer is listening; , port :: PortNumber -- | received in response to a previous get_peers query. , sessionToken :: Token } deriving (Show, Eq, Typeable) port_key :: BKey port_key = "port" implied_port_key :: BKey implied_port_key = "implied_port" instance BEncode Announce where toBEncode Announce {..} = toDict $ implied_port_key .=? flagField impliedPort .: info_hash_key .=! topic .: port_key .=! port .: token_key .=! sessionToken .: endDict where flagField flag = if flag then Just (1 :: Int) else Nothing fromBEncode = fromDict $ do Announce <$> (boolField <$> optional (field (req implied_port_key))) <*>! info_hash_key <*>! port_key <*>! token_key where boolField = maybe False (/= (0 :: Int)) -- | The queried node must verify that the token was previously sent -- to the same IP address as the querying node. Then the queried node -- should store the IP address of the querying node and the supplied -- port number under the infohash in its store of peer contact -- information. data Announced = Announced deriving (Show, Eq, Typeable) instance BEncode Announced where toBEncode _ = toBEncode Ping fromBEncode _ = pure Announced -- | \"q" = \"announce\" instance KRPC (Query Announce) (Response Announced) where method = "announce_peer"
DavidAlphaFox/bittorrent
src/Network/BitTorrent/DHT/Message.hs
bsd-3-clause
10,841
0
19
2,857
1,773
997
776
-1
-1
{-# OPTIONS #-} ----------------------------------------------------------------------------- -- | -- Module : Language.JavaScript.ParserMonad -- Based on language-python version by Bernie Pope -- Copyright : (c) 2009 Bernie Pope -- License : BSD-style -- Stability : experimental -- Portability : ghc -- -- Monad support for JavaScript parser and lexer. ----------------------------------------------------------------------------- module Language.JavaScript.Parser.ParserMonad ( P , execParser , execParserKeepComments , runParser , thenP , returnP , alexSetInput , alexGetInput , setLocation , getLocation , getInput , setInput , getLastToken , setLastToken -- , setLastEOL -- , getLastEOL , ParseError (..) , ParseState (..) , initialState , addComment , getComments , spanError , AlexInput , Byte ) where import Control.Applicative ((<$>)) import Control.Monad.Error as Error import Control.Monad.State.Class import Control.Monad.State.Strict as State import Language.JavaScript.Parser.ParseError (ParseError (..)) import Language.JavaScript.Parser.SrcLocation (AlexPosn (..), alexStartPos, alexSpanEmpty, Span (..)) import Language.JavaScript.Parser.Token (Token (..)) import Prelude hiding (span) import Data.Word (Word8) internalError :: String -> P a internalError = throwError . StrError spanError :: Span a => a -> String -> P b --spanError x str = throwError $ StrError $ unwords [prettyText $ getSpan x, str] spanError x str = throwError $ StrError $ show ([show (getSpan x), str]) type Byte = Word8 type AlexInput = (AlexPosn, -- current position, Char, -- previous char [Byte], -- pending bytes on current char String) -- current input string data ParseState = ParseState { alex_pos :: !AlexPosn, -- position at current input location alex_inp :: String, -- the current input alex_chr :: !Char, -- the character before the input alex_bytes :: [Byte], alex_scd :: !Int -- the current startcode , previousToken :: !Token -- the previous token , comments :: [Token] -- accumulated comments } initialState :: String -> ParseState initialState inp = ParseState { alex_pos = alexStartPos , alex_inp = inp , alex_chr = '\n' , alex_bytes = [] , alex_scd = 0 , previousToken = initToken , comments = [] } {- data ParseState = ParseState { location :: !SrcLocation -- position at current input location -- , input :: !String -- the current input , input :: !AlexInput -- the current input , previousToken :: !Token -- the previous token -- , lastEOL :: !SrcSpan -- location of the most recent end-of-line encountered , comments :: [Token] -- accumulated comments } deriving Show -} initToken :: Token --initToken = NewlineToken SpanEmpty initToken = CommentToken alexSpanEmpty "" type P a = StateT ParseState (Either ParseError) a execParser :: P a -> ParseState -> Either ParseError a execParser = evalStateT execParserKeepComments :: P a -> ParseState -> Either ParseError (a, [Token]) execParserKeepComments parser astate = evalStateT (parser >>= \x -> getComments >>= \c -> return (x, c)) astate runParser :: P a -> ParseState -> Either ParseError (a, ParseState) runParser = runStateT {-# INLINE returnP #-} returnP :: a -> P a returnP = return {-# INLINE thenP #-} thenP :: P a -> (a -> P b) -> P b thenP = (>>=) {- failP :: SrcSpan -> [String] -> P a failP span strs = throwError (prettyText span ++ ": " ++ unwords strs) -} {- setLastEOL :: SrcSpan -> P () setLastEOL span = modify $ \s -> s { lastEOL = span } getLastEOL :: P SrcSpan getLastEOL = gets lastEOL -} alexGetInput :: P AlexInput alexGetInput -- = P $ \s@ParseState{alex_pos=pos,alex_chr=c,alex_bytes=bs,alex_inp=inp} -> -- Right (s, (pos,c,bs,inp)) = do pos <- gets alex_pos c <- gets alex_chr bs <- gets alex_bytes inp <- gets alex_inp return (pos,c,bs,inp) alexSetInput :: AlexInput -> P () alexSetInput (pos,c,bs,inp) -- = P $ \s -> case s{alex_pos=pos,alex_chr=c,alex_bytes=bs,alex_inp=inp} of -- s@(ParseState{}) -> Right (s, ()) = modify $ \s -> s{alex_pos=pos,alex_chr=c,alex_bytes=bs,alex_inp=inp} setLocation :: AlexPosn -> P () setLocation loc = modify $ \s -> s { alex_pos = loc } getLocation :: P AlexPosn getLocation = gets alex_pos getInput :: P String getInput = gets alex_inp setInput :: String -> P () setInput inp = modify $ \s -> s { alex_inp = inp } getLastToken :: P Token getLastToken = gets previousToken setLastToken :: Token -> P () setLastToken tok = modify $ \s -> s { previousToken = tok } addComment :: Token -> P () addComment c = do oldComments <- gets comments modify $ \s -> s { comments = c : oldComments } getComments :: P [Token] getComments = reverse <$> gets comments
thdtjsdn/language-javascript
src/Language/JavaScript/Parser/ParserMonad.hs
bsd-3-clause
5,075
0
12
1,207
1,076
627
449
113
1
-- | -- a utility module module CPU.Utils where import Data.List (group, sort) -- | -- replicate operation and chain it replicateMChain :: Monad m => Int -> (a -> m a) -> a -> m a replicateMChain n f x | n <= 0 = return x | otherwise = f x >>= replicateMChain (n-1) f -- | -- if Maybe b is nothing, replace it with Left a. otherwise: Right b maybeToEither :: a -> Maybe b -> Either a b maybeToEither _ (Just y) = Right y maybeToEither x Nothing = Left x -- | -- returns the duplicates of a list duplicates :: Ord a => [a] -> [a] duplicates = map head . filter ((>1) . length) . group . sort -- | -- split arguments by element splitBy :: Eq a => a -> [a] -> [[a]] splitBy v vs = map reverse $ go [] vs where go xs [] = [xs] go xs (y:ys) | y == v = xs : go [] ys | otherwise = go (y:xs) ys supplyBoth :: (a -> b -> c) -> (b -> a) -> b -> c supplyBoth = (=<<) mapLeft :: (a -> b) -> Either a c -> Either b c mapLeft f (Left x) = Left (f x) mapLeft _ (Right x) = Right x map2 :: (a -> b) -> (a, a) -> (b, b) map2 f (x,y) = (f x, f y) ---------------- -- Formatting --------------- displayCommands :: String -> [(String, String)] -> [String] displayCommands opener cmds = fmap (displayCommand opener (cmdWithSpaces n)) cmds where n = 8 + foldr (\str acc -> max (length (fst str)) acc) 0 cmds cmdWithSpaces :: Int -> String -> String cmdWithSpaces n str = str ++ replicate (n - length str) ' ' displayCommand :: String -> (String -> String) -> (String, String) -> String displayCommand opener paddCmd (cmd, desc) = opener ++ paddCmd cmd ++ desc dashOpener, spaceOpener :: String dashOpener = " - " spaceOpener = " "
bitemyapp/chip-8
src/CPU/Utils.hs
bsd-3-clause
1,672
0
15
399
753
396
357
34
2
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcMatches: Typecheck some @Matches@ -} {-# LANGUAGE CPP, RankNTypes #-} module TcMatches ( tcMatchesFun, tcGRHS, tcGRHSsPat, tcMatchesCase, tcMatchLambda, TcMatchCtxt(..), TcStmtChecker, TcExprStmtChecker, TcCmdStmtChecker, tcStmts, tcStmtsAndThen, tcDoStmts, tcBody, tcDoStmt, tcGuardStmt ) where import {-# SOURCE #-} TcExpr( tcSyntaxOp, tcInferRhoNC, tcInferRho, tcCheckId, tcMonoExpr, tcMonoExprNC, tcPolyExpr ) import HsSyn import BasicTypes import TcRnMonad import TcEnv import TcPat import TcMType import TcType import TcBinds import TcUnify import Name import TysWiredIn import Id import TyCon import TysPrim import TcEvidence import Outputable import Util import SrcLoc import FastString -- Create chunkified tuple tybes for monad comprehensions import MkCore import Control.Monad #include "HsVersions.h" {- ************************************************************************ * * \subsection{tcMatchesFun, tcMatchesCase} * * ************************************************************************ @tcMatchesFun@ typechecks a @[Match]@ list which occurs in a @FunMonoBind@. The second argument is the name of the function, which is used in error messages. It checks that all the equations have the same number of arguments before using @tcMatches@ to do the work. Note [Polymorphic expected type for tcMatchesFun] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tcMatchesFun may be given a *sigma* (polymorphic) type so it must be prepared to use tcGen to skolemise it. See Note [sig_tau may be polymorphic] in TcPat. -} tcMatchesFun :: Name -> Bool -> MatchGroup Name (LHsExpr Name) -> TcSigmaType -- Expected type of function -> TcM (HsWrapper, MatchGroup TcId (LHsExpr TcId)) -- Returns type of body tcMatchesFun fun_name inf matches exp_ty = do { -- Check that they all have the same no of arguments -- Location is in the monad, set the caller so that -- any inter-equation error messages get some vaguely -- sensible location. Note: we have to do this odd -- ann-grabbing, because we don't always have annotations in -- hand when we call tcMatchesFun... traceTc "tcMatchesFun" (ppr fun_name $$ ppr exp_ty) ; checkArgs fun_name matches ; (wrap_gen, (wrap_fun, group)) <- tcGen (FunSigCtxt fun_name) exp_ty $ \ _ exp_rho -> -- Note [Polymorphic expected type for tcMatchesFun] matchFunTys herald arity exp_rho $ \ pat_tys rhs_ty -> tcMatches match_ctxt pat_tys rhs_ty matches ; return (wrap_gen <.> wrap_fun, group) } where arity = matchGroupArity matches herald = ptext (sLit "The equation(s) for") <+> quotes (ppr fun_name) <+> ptext (sLit "have") match_ctxt = MC { mc_what = FunRhs fun_name inf, mc_body = tcBody } {- @tcMatchesCase@ doesn't do the argument-count check because the parser guarantees that each equation has exactly one argument. -} tcMatchesCase :: (Outputable (body Name)) => TcMatchCtxt body -- Case context -> TcRhoType -- Type of scrutinee -> MatchGroup Name (Located (body Name)) -- The case alternatives -> TcRhoType -- Type of whole case expressions -> TcM (MatchGroup TcId (Located (body TcId))) -- Translated alternatives tcMatchesCase ctxt scrut_ty matches res_ty | isEmptyMatchGroup matches -- Allow empty case expressions = return (MG { mg_alts = [], mg_arg_tys = [scrut_ty], mg_res_ty = res_ty, mg_origin = mg_origin matches }) | otherwise = tcMatches ctxt [scrut_ty] res_ty matches tcMatchLambda :: MatchGroup Name (LHsExpr Name) -> TcRhoType -> TcM (HsWrapper, MatchGroup TcId (LHsExpr TcId)) tcMatchLambda match res_ty = matchFunTys herald n_pats res_ty $ \ pat_tys rhs_ty -> tcMatches match_ctxt pat_tys rhs_ty match where n_pats = matchGroupArity match herald = sep [ ptext (sLit "The lambda expression") <+> quotes (pprSetDepth (PartWay 1) $ pprMatches (LambdaExpr :: HsMatchContext Name) match), -- The pprSetDepth makes the abstraction print briefly ptext (sLit "has")] match_ctxt = MC { mc_what = LambdaExpr, mc_body = tcBody } -- @tcGRHSsPat@ typechecks @[GRHSs]@ that occur in a @PatMonoBind@. tcGRHSsPat :: GRHSs Name (LHsExpr Name) -> TcRhoType -> TcM (GRHSs TcId (LHsExpr TcId)) -- Used for pattern bindings tcGRHSsPat grhss res_ty = tcGRHSs match_ctxt grhss res_ty where match_ctxt = MC { mc_what = PatBindRhs, mc_body = tcBody } matchFunTys :: SDoc -- See Note [Herald for matchExpecteFunTys] in TcUnify -> Arity -> TcRhoType -> ([TcSigmaType] -> TcRhoType -> TcM a) -> TcM (HsWrapper, a) -- Written in CPS style for historical reasons; -- could probably be un-CPSd, like matchExpectedTyConApp matchFunTys herald arity res_ty thing_inside = do { (co, pat_tys, res_ty) <- matchExpectedFunTys herald arity res_ty ; res <- thing_inside pat_tys res_ty ; return (coToHsWrapper (mkTcSymCo co), res) } {- ************************************************************************ * * \subsection{tcMatch} * * ************************************************************************ -} tcMatches :: (Outputable (body Name)) => TcMatchCtxt body -> [TcSigmaType] -- Expected pattern types -> TcRhoType -- Expected result-type of the Match. -> MatchGroup Name (Located (body Name)) -> TcM (MatchGroup TcId (Located (body TcId))) data TcMatchCtxt body -- c.f. TcStmtCtxt, also in this module = MC { mc_what :: HsMatchContext Name, -- What kind of thing this is mc_body :: Located (body Name) -- Type checker for a body of -- an alternative -> TcRhoType -> TcM (Located (body TcId)) } tcMatches ctxt pat_tys rhs_ty (MG { mg_alts = matches, mg_origin = origin }) = ASSERT( not (null matches) ) -- Ensure that rhs_ty is filled in do { matches' <- mapM (tcMatch ctxt pat_tys rhs_ty) matches ; return (MG { mg_alts = matches', mg_arg_tys = pat_tys, mg_res_ty = rhs_ty, mg_origin = origin }) } ------------- tcMatch :: (Outputable (body Name)) => TcMatchCtxt body -> [TcSigmaType] -- Expected pattern types -> TcRhoType -- Expected result-type of the Match. -> LMatch Name (Located (body Name)) -> TcM (LMatch TcId (Located (body TcId))) tcMatch ctxt pat_tys rhs_ty match = wrapLocM (tc_match ctxt pat_tys rhs_ty) match where tc_match ctxt pat_tys rhs_ty match@(Match _ pats maybe_rhs_sig grhss) = add_match_ctxt match $ do { (pats', grhss') <- tcPats (mc_what ctxt) pats pat_tys $ tc_grhss ctxt maybe_rhs_sig grhss rhs_ty ; return (Match Nothing pats' Nothing grhss') } tc_grhss ctxt Nothing grhss rhs_ty = tcGRHSs ctxt grhss rhs_ty -- No result signature -- Result type sigs are no longer supported tc_grhss _ (Just {}) _ _ = panic "tc_ghrss" -- Rejected by renamer -- For (\x -> e), tcExpr has already said "In the expresssion \x->e" -- so we don't want to add "In the lambda abstraction \x->e" add_match_ctxt match thing_inside = case mc_what ctxt of LambdaExpr -> thing_inside m_ctxt -> addErrCtxt (pprMatchInCtxt m_ctxt match) thing_inside ------------- tcGRHSs :: TcMatchCtxt body -> GRHSs Name (Located (body Name)) -> TcRhoType -> TcM (GRHSs TcId (Located (body TcId))) -- Notice that we pass in the full res_ty, so that we get -- good inference from simple things like -- f = \(x::forall a.a->a) -> <stuff> -- We used to force it to be a monotype when there was more than one guard -- but we don't need to do that any more tcGRHSs ctxt (GRHSs grhss binds) res_ty = do { (binds', grhss') <- tcLocalBinds binds $ mapM (wrapLocM (tcGRHS ctxt res_ty)) grhss ; return (GRHSs grhss' binds') } ------------- tcGRHS :: TcMatchCtxt body -> TcRhoType -> GRHS Name (Located (body Name)) -> TcM (GRHS TcId (Located (body TcId))) tcGRHS ctxt res_ty (GRHS guards rhs) = do { (guards', rhs') <- tcStmtsAndThen stmt_ctxt tcGuardStmt guards res_ty $ mc_body ctxt rhs ; return (GRHS guards' rhs') } where stmt_ctxt = PatGuard (mc_what ctxt) {- ************************************************************************ * * \subsection{@tcDoStmts@ typechecks a {\em list} of do statements} * * ************************************************************************ -} tcDoStmts :: HsStmtContext Name -> [LStmt Name (LHsExpr Name)] -> TcRhoType -> TcM (HsExpr TcId) -- Returns a HsDo tcDoStmts ListComp stmts res_ty = do { (co, elt_ty) <- matchExpectedListTy res_ty ; let list_ty = mkListTy elt_ty ; stmts' <- tcStmts ListComp (tcLcStmt listTyCon) stmts elt_ty ; return $ mkHsWrapCo co (HsDo ListComp stmts' list_ty) } tcDoStmts PArrComp stmts res_ty = do { (co, elt_ty) <- matchExpectedPArrTy res_ty ; let parr_ty = mkPArrTy elt_ty ; stmts' <- tcStmts PArrComp (tcLcStmt parrTyCon) stmts elt_ty ; return $ mkHsWrapCo co (HsDo PArrComp stmts' parr_ty) } tcDoStmts DoExpr stmts res_ty = do { stmts' <- tcStmts DoExpr tcDoStmt stmts res_ty ; return (HsDo DoExpr stmts' res_ty) } tcDoStmts MDoExpr stmts res_ty = do { stmts' <- tcStmts MDoExpr tcDoStmt stmts res_ty ; return (HsDo MDoExpr stmts' res_ty) } tcDoStmts MonadComp stmts res_ty = do { stmts' <- tcStmts MonadComp tcMcStmt stmts res_ty ; return (HsDo MonadComp stmts' res_ty) } tcDoStmts ctxt _ _ = pprPanic "tcDoStmts" (pprStmtContext ctxt) tcBody :: LHsExpr Name -> TcRhoType -> TcM (LHsExpr TcId) tcBody body res_ty = do { traceTc "tcBody" (ppr res_ty) ; body' <- tcMonoExpr body res_ty ; return body' } {- ************************************************************************ * * \subsection{tcStmts} * * ************************************************************************ -} type TcExprStmtChecker = TcStmtChecker HsExpr type TcCmdStmtChecker = TcStmtChecker HsCmd type TcStmtChecker body = forall thing. HsStmtContext Name -> Stmt Name (Located (body Name)) -> TcRhoType -- Result type for comprehension -> (TcRhoType -> TcM thing) -- Checker for what follows the stmt -> TcM (Stmt TcId (Located (body TcId)), thing) tcStmts :: (Outputable (body Name)) => HsStmtContext Name -> TcStmtChecker body -- NB: higher-rank type -> [LStmt Name (Located (body Name))] -> TcRhoType -> TcM [LStmt TcId (Located (body TcId))] tcStmts ctxt stmt_chk stmts res_ty = do { (stmts', _) <- tcStmtsAndThen ctxt stmt_chk stmts res_ty $ const (return ()) ; return stmts' } tcStmtsAndThen :: (Outputable (body Name)) => HsStmtContext Name -> TcStmtChecker body -- NB: higher-rank type -> [LStmt Name (Located (body Name))] -> TcRhoType -> (TcRhoType -> TcM thing) -> TcM ([LStmt TcId (Located (body TcId))], thing) -- Note the higher-rank type. stmt_chk is applied at different -- types in the equations for tcStmts tcStmtsAndThen _ _ [] res_ty thing_inside = do { thing <- thing_inside res_ty ; return ([], thing) } -- LetStmts are handled uniformly, regardless of context tcStmtsAndThen ctxt stmt_chk (L loc (LetStmt binds) : stmts) res_ty thing_inside = do { (binds', (stmts',thing)) <- tcLocalBinds binds $ tcStmtsAndThen ctxt stmt_chk stmts res_ty thing_inside ; return (L loc (LetStmt binds') : stmts', thing) } -- For the vanilla case, handle the location-setting part tcStmtsAndThen ctxt stmt_chk (L loc stmt : stmts) res_ty thing_inside = do { (stmt', (stmts', thing)) <- setSrcSpan loc $ addErrCtxt (pprStmtInCtxt ctxt stmt) $ stmt_chk ctxt stmt res_ty $ \ res_ty' -> popErrCtxt $ tcStmtsAndThen ctxt stmt_chk stmts res_ty' $ thing_inside ; return (L loc stmt' : stmts', thing) } --------------------------------------------------- -- Pattern guards --------------------------------------------------- tcGuardStmt :: TcExprStmtChecker tcGuardStmt _ (BodyStmt guard _ _ _) res_ty thing_inside = do { guard' <- tcMonoExpr guard boolTy ; thing <- thing_inside res_ty ; return (BodyStmt guard' noSyntaxExpr noSyntaxExpr boolTy, thing) } tcGuardStmt ctxt (BindStmt pat rhs _ _) res_ty thing_inside = do { (rhs', rhs_ty) <- tcInferRhoNC rhs -- Stmt has a context already ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat rhs_ty $ thing_inside res_ty ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) } tcGuardStmt _ stmt _ _ = pprPanic "tcGuardStmt: unexpected Stmt" (ppr stmt) --------------------------------------------------- -- List comprehensions and PArrays -- (no rebindable syntax) --------------------------------------------------- -- Dealt with separately, rather than by tcMcStmt, because -- a) PArr isn't (yet) an instance of Monad, so the generality seems overkill -- b) We have special desugaring rules for list comprehensions, -- which avoid creating intermediate lists. They in turn -- assume that the bind/return operations are the regular -- polymorphic ones, and in particular don't have any -- coercion matching stuff in them. It's hard to avoid the -- potential for non-trivial coercions in tcMcStmt tcLcStmt :: TyCon -- The list/Parray type constructor ([] or PArray) -> TcExprStmtChecker tcLcStmt _ _ (LastStmt body _) elt_ty thing_inside = do { body' <- tcMonoExprNC body elt_ty ; thing <- thing_inside (panic "tcLcStmt: thing_inside") ; return (LastStmt body' noSyntaxExpr, thing) } -- A generator, pat <- rhs tcLcStmt m_tc ctxt (BindStmt pat rhs _ _) elt_ty thing_inside = do { pat_ty <- newFlexiTyVarTy liftedTypeKind ; rhs' <- tcMonoExpr rhs (mkTyConApp m_tc [pat_ty]) ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $ thing_inside elt_ty ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) } -- A boolean guard tcLcStmt _ _ (BodyStmt rhs _ _ _) elt_ty thing_inside = do { rhs' <- tcMonoExpr rhs boolTy ; thing <- thing_inside elt_ty ; return (BodyStmt rhs' noSyntaxExpr noSyntaxExpr boolTy, thing) } -- ParStmt: See notes with tcMcStmt tcLcStmt m_tc ctxt (ParStmt bndr_stmts_s _ _) elt_ty thing_inside = do { (pairs', thing) <- loop bndr_stmts_s ; return (ParStmt pairs' noSyntaxExpr noSyntaxExpr, thing) } where -- loop :: [([LStmt Name], [Name])] -> TcM ([([LStmt TcId], [TcId])], thing) loop [] = do { thing <- thing_inside elt_ty ; return ([], thing) } -- matching in the branches loop (ParStmtBlock stmts names _ : pairs) = do { (stmts', (ids, pairs', thing)) <- tcStmtsAndThen ctxt (tcLcStmt m_tc) stmts elt_ty $ \ _elt_ty' -> do { ids <- tcLookupLocalIds names ; (pairs', thing) <- loop pairs ; return (ids, pairs', thing) } ; return ( ParStmtBlock stmts' ids noSyntaxExpr : pairs', thing ) } tcLcStmt m_tc ctxt (TransStmt { trS_form = form, trS_stmts = stmts , trS_bndrs = bindersMap , trS_by = by, trS_using = using }) elt_ty thing_inside = do { let (bndr_names, n_bndr_names) = unzip bindersMap unused_ty = pprPanic "tcLcStmt: inner ty" (ppr bindersMap) -- The inner 'stmts' lack a LastStmt, so the element type -- passed in to tcStmtsAndThen is never looked at ; (stmts', (bndr_ids, by')) <- tcStmtsAndThen (TransStmtCtxt ctxt) (tcLcStmt m_tc) stmts unused_ty $ \_ -> do { by' <- case by of Nothing -> return Nothing Just e -> do { e_ty <- tcInferRho e; return (Just e_ty) } ; bndr_ids <- tcLookupLocalIds bndr_names ; return (bndr_ids, by') } ; let m_app ty = mkTyConApp m_tc [ty] --------------- Typecheck the 'using' function ------------- -- using :: ((a,b,c)->t) -> m (a,b,c) -> m (a,b,c)m (ThenForm) -- :: ((a,b,c)->t) -> m (a,b,c) -> m (m (a,b,c))) (GroupForm) -- n_app :: Type -> Type -- Wraps a 'ty' into '[ty]' for GroupForm ; let n_app = case form of ThenForm -> (\ty -> ty) _ -> m_app by_arrow :: Type -> Type -- Wraps 'ty' to '(a->t) -> ty' if the By is present by_arrow = case by' of Nothing -> \ty -> ty Just (_,e_ty) -> \ty -> (alphaTy `mkFunTy` e_ty) `mkFunTy` ty tup_ty = mkBigCoreVarTupTy bndr_ids poly_arg_ty = m_app alphaTy poly_res_ty = m_app (n_app alphaTy) using_poly_ty = mkForAllTy alphaTyVar $ by_arrow $ poly_arg_ty `mkFunTy` poly_res_ty ; using' <- tcPolyExpr using using_poly_ty ; let final_using = fmap (HsWrap (WpTyApp tup_ty)) using' -- 'stmts' returns a result of type (m1_ty tuple_ty), -- typically something like [(Int,Bool,Int)] -- We don't know what tuple_ty is yet, so we use a variable ; let mk_n_bndr :: Name -> TcId -> TcId mk_n_bndr n_bndr_name bndr_id = mkLocalId n_bndr_name (n_app (idType bndr_id)) -- Ensure that every old binder of type `b` is linked up with its -- new binder which should have type `n b` -- See Note [GroupStmt binder map] in HsExpr n_bndr_ids = zipWith mk_n_bndr n_bndr_names bndr_ids bindersMap' = bndr_ids `zip` n_bndr_ids -- Type check the thing in the environment with -- these new binders and return the result ; thing <- tcExtendIdEnv n_bndr_ids (thing_inside elt_ty) ; return (emptyTransStmt { trS_stmts = stmts', trS_bndrs = bindersMap' , trS_by = fmap fst by', trS_using = final_using , trS_form = form }, thing) } tcLcStmt _ _ stmt _ _ = pprPanic "tcLcStmt: unexpected Stmt" (ppr stmt) --------------------------------------------------- -- Monad comprehensions -- (supports rebindable syntax) --------------------------------------------------- tcMcStmt :: TcExprStmtChecker tcMcStmt _ (LastStmt body return_op) res_ty thing_inside = do { a_ty <- newFlexiTyVarTy liftedTypeKind ; return_op' <- tcSyntaxOp MCompOrigin return_op (a_ty `mkFunTy` res_ty) ; body' <- tcMonoExprNC body a_ty ; thing <- thing_inside (panic "tcMcStmt: thing_inside") ; return (LastStmt body' return_op', thing) } -- Generators for monad comprehensions ( pat <- rhs ) -- -- [ body | q <- gen ] -> gen :: m a -- q :: a -- tcMcStmt ctxt (BindStmt pat rhs bind_op fail_op) res_ty thing_inside = do { rhs_ty <- newFlexiTyVarTy liftedTypeKind ; pat_ty <- newFlexiTyVarTy liftedTypeKind ; new_res_ty <- newFlexiTyVarTy liftedTypeKind -- (>>=) :: rhs_ty -> (pat_ty -> new_res_ty) -> res_ty ; bind_op' <- tcSyntaxOp MCompOrigin bind_op (mkFunTys [rhs_ty, mkFunTy pat_ty new_res_ty] res_ty) -- If (but only if) the pattern can fail, typecheck the 'fail' operator ; fail_op' <- if isIrrefutableHsPat pat then return noSyntaxExpr else tcSyntaxOp MCompOrigin fail_op (mkFunTy stringTy new_res_ty) ; rhs' <- tcMonoExprNC rhs rhs_ty ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $ thing_inside new_res_ty ; return (BindStmt pat' rhs' bind_op' fail_op', thing) } -- Boolean expressions. -- -- [ body | stmts, expr ] -> expr :: m Bool -- tcMcStmt _ (BodyStmt rhs then_op guard_op _) res_ty thing_inside = do { -- Deal with rebindable syntax: -- guard_op :: test_ty -> rhs_ty -- then_op :: rhs_ty -> new_res_ty -> res_ty -- Where test_ty is, for example, Bool test_ty <- newFlexiTyVarTy liftedTypeKind ; rhs_ty <- newFlexiTyVarTy liftedTypeKind ; new_res_ty <- newFlexiTyVarTy liftedTypeKind ; rhs' <- tcMonoExpr rhs test_ty ; guard_op' <- tcSyntaxOp MCompOrigin guard_op (mkFunTy test_ty rhs_ty) ; then_op' <- tcSyntaxOp MCompOrigin then_op (mkFunTys [rhs_ty, new_res_ty] res_ty) ; thing <- thing_inside new_res_ty ; return (BodyStmt rhs' then_op' guard_op' rhs_ty, thing) } -- Grouping statements -- -- [ body | stmts, then group by e using f ] -- -> e :: t -- f :: forall a. (a -> t) -> m a -> m (m a) -- [ body | stmts, then group using f ] -- -> f :: forall a. m a -> m (m a) -- We type [ body | (stmts, group by e using f), ... ] -- f <optional by> [ (a,b,c) | stmts ] >>= \(a,b,c) -> ...body.... -- -- We type the functions as follows: -- f <optional by> :: m1 (a,b,c) -> m2 (a,b,c) (ThenForm) -- :: m1 (a,b,c) -> m2 (n (a,b,c)) (GroupForm) -- (>>=) :: m2 (a,b,c) -> ((a,b,c) -> res) -> res (ThenForm) -- :: m2 (n (a,b,c)) -> (n (a,b,c) -> res) -> res (GroupForm) -- tcMcStmt ctxt (TransStmt { trS_stmts = stmts, trS_bndrs = bindersMap , trS_by = by, trS_using = using, trS_form = form , trS_ret = return_op, trS_bind = bind_op , trS_fmap = fmap_op }) res_ty thing_inside = do { let star_star_kind = liftedTypeKind `mkArrowKind` liftedTypeKind ; m1_ty <- newFlexiTyVarTy star_star_kind ; m2_ty <- newFlexiTyVarTy star_star_kind ; tup_ty <- newFlexiTyVarTy liftedTypeKind ; by_e_ty <- newFlexiTyVarTy liftedTypeKind -- The type of the 'by' expression (if any) -- n_app :: Type -> Type -- Wraps a 'ty' into '(n ty)' for GroupForm ; n_app <- case form of ThenForm -> return (\ty -> ty) _ -> do { n_ty <- newFlexiTyVarTy star_star_kind ; return (n_ty `mkAppTy`) } ; let by_arrow :: Type -> Type -- (by_arrow res) produces ((alpha->e_ty) -> res) ('by' present) -- or res ('by' absent) by_arrow = case by of Nothing -> \res -> res Just {} -> \res -> (alphaTy `mkFunTy` by_e_ty) `mkFunTy` res poly_arg_ty = m1_ty `mkAppTy` alphaTy using_arg_ty = m1_ty `mkAppTy` tup_ty poly_res_ty = m2_ty `mkAppTy` n_app alphaTy using_res_ty = m2_ty `mkAppTy` n_app tup_ty using_poly_ty = mkForAllTy alphaTyVar $ by_arrow $ poly_arg_ty `mkFunTy` poly_res_ty -- 'stmts' returns a result of type (m1_ty tuple_ty), -- typically something like [(Int,Bool,Int)] -- We don't know what tuple_ty is yet, so we use a variable ; let (bndr_names, n_bndr_names) = unzip bindersMap ; (stmts', (bndr_ids, by', return_op')) <- tcStmtsAndThen (TransStmtCtxt ctxt) tcMcStmt stmts using_arg_ty $ \res_ty' -> do { by' <- case by of Nothing -> return Nothing Just e -> do { e' <- tcMonoExpr e by_e_ty; return (Just e') } -- Find the Ids (and hence types) of all old binders ; bndr_ids <- tcLookupLocalIds bndr_names -- 'return' is only used for the binders, so we know its type. -- return :: (a,b,c,..) -> m (a,b,c,..) ; return_op' <- tcSyntaxOp MCompOrigin return_op $ (mkBigCoreVarTupTy bndr_ids) `mkFunTy` res_ty' ; return (bndr_ids, by', return_op') } --------------- Typecheck the 'bind' function ------------- -- (>>=) :: m2 (n (a,b,c)) -> ( n (a,b,c) -> new_res_ty ) -> res_ty ; new_res_ty <- newFlexiTyVarTy liftedTypeKind ; bind_op' <- tcSyntaxOp MCompOrigin bind_op $ using_res_ty `mkFunTy` (n_app tup_ty `mkFunTy` new_res_ty) `mkFunTy` res_ty --------------- Typecheck the 'fmap' function ------------- ; fmap_op' <- case form of ThenForm -> return noSyntaxExpr _ -> fmap unLoc . tcPolyExpr (noLoc fmap_op) $ mkForAllTy alphaTyVar $ mkForAllTy betaTyVar $ (alphaTy `mkFunTy` betaTy) `mkFunTy` (n_app alphaTy) `mkFunTy` (n_app betaTy) --------------- Typecheck the 'using' function ------------- -- using :: ((a,b,c)->t) -> m1 (a,b,c) -> m2 (n (a,b,c)) ; using' <- tcPolyExpr using using_poly_ty ; let final_using = fmap (HsWrap (WpTyApp tup_ty)) using' --------------- Bulding the bindersMap ---------------- ; let mk_n_bndr :: Name -> TcId -> TcId mk_n_bndr n_bndr_name bndr_id = mkLocalId n_bndr_name (n_app (idType bndr_id)) -- Ensure that every old binder of type `b` is linked up with its -- new binder which should have type `n b` -- See Note [GroupStmt binder map] in HsExpr n_bndr_ids = zipWith mk_n_bndr n_bndr_names bndr_ids bindersMap' = bndr_ids `zip` n_bndr_ids -- Type check the thing in the environment with -- these new binders and return the result ; thing <- tcExtendIdEnv n_bndr_ids (thing_inside new_res_ty) ; return (TransStmt { trS_stmts = stmts', trS_bndrs = bindersMap' , trS_by = by', trS_using = final_using , trS_ret = return_op', trS_bind = bind_op' , trS_fmap = fmap_op', trS_form = form }, thing) } -- A parallel set of comprehensions -- [ (g x, h x) | ... ; let g v = ... -- | ... ; let h v = ... ] -- -- It's possible that g,h are overloaded, so we need to feed the LIE from the -- (g x, h x) up through both lots of bindings (so we get the bindLocalMethods). -- Similarly if we had an existential pattern match: -- -- data T = forall a. Show a => C a -- -- [ (show x, show y) | ... ; C x <- ... -- | ... ; C y <- ... ] -- -- Then we need the LIE from (show x, show y) to be simplified against -- the bindings for x and y. -- -- It's difficult to do this in parallel, so we rely on the renamer to -- ensure that g,h and x,y don't duplicate, and simply grow the environment. -- So the binders of the first parallel group will be in scope in the second -- group. But that's fine; there's no shadowing to worry about. -- -- Note: The `mzip` function will get typechecked via: -- -- ParStmt [st1::t1, st2::t2, st3::t3] -- -- mzip :: m st1 -- -> (m st2 -> m st3 -> m (st2, st3)) -- recursive call -- -> m (st1, (st2, st3)) -- tcMcStmt ctxt (ParStmt bndr_stmts_s mzip_op bind_op) res_ty thing_inside = do { let star_star_kind = liftedTypeKind `mkArrowKind` liftedTypeKind ; m_ty <- newFlexiTyVarTy star_star_kind ; let mzip_ty = mkForAllTys [alphaTyVar, betaTyVar] $ (m_ty `mkAppTy` alphaTy) `mkFunTy` (m_ty `mkAppTy` betaTy) `mkFunTy` (m_ty `mkAppTy` mkBoxedTupleTy [alphaTy, betaTy]) ; mzip_op' <- unLoc `fmap` tcPolyExpr (noLoc mzip_op) mzip_ty ; (blocks', thing) <- loop m_ty bndr_stmts_s -- Typecheck bind: ; let tys = [ mkBigCoreVarTupTy bs | ParStmtBlock _ bs _ <- blocks'] tuple_ty = mk_tuple_ty tys ; bind_op' <- tcSyntaxOp MCompOrigin bind_op $ (m_ty `mkAppTy` tuple_ty) `mkFunTy` (tuple_ty `mkFunTy` res_ty) `mkFunTy` res_ty ; return (ParStmt blocks' mzip_op' bind_op', thing) } where mk_tuple_ty tys = foldr1 (\tn tm -> mkBoxedTupleTy [tn, tm]) tys -- loop :: Type -- m_ty -- -> [([LStmt Name], [Name])] -- -> TcM ([([LStmt TcId], [TcId])], thing) loop _ [] = do { thing <- thing_inside res_ty ; return ([], thing) } -- matching in the branches loop m_ty (ParStmtBlock stmts names return_op : pairs) = do { -- type dummy since we don't know all binder types yet id_tys <- mapM (const (newFlexiTyVarTy liftedTypeKind)) names ; let m_tup_ty = m_ty `mkAppTy` mkBigCoreTupTy id_tys ; (stmts', (ids, return_op', pairs', thing)) <- tcStmtsAndThen ctxt tcMcStmt stmts m_tup_ty $ \m_tup_ty' -> do { ids <- tcLookupLocalIds names ; let tup_ty = mkBigCoreVarTupTy ids ; return_op' <- tcSyntaxOp MCompOrigin return_op (tup_ty `mkFunTy` m_tup_ty') ; (pairs', thing) <- loop m_ty pairs ; return (ids, return_op', pairs', thing) } ; return (ParStmtBlock stmts' ids return_op' : pairs', thing) } tcMcStmt _ stmt _ _ = pprPanic "tcMcStmt: unexpected Stmt" (ppr stmt) --------------------------------------------------- -- Do-notation -- (supports rebindable syntax) --------------------------------------------------- tcDoStmt :: TcExprStmtChecker tcDoStmt _ (LastStmt body _) res_ty thing_inside = do { body' <- tcMonoExprNC body res_ty ; thing <- thing_inside (panic "tcDoStmt: thing_inside") ; return (LastStmt body' noSyntaxExpr, thing) } tcDoStmt ctxt (BindStmt pat rhs bind_op fail_op) res_ty thing_inside = do { -- Deal with rebindable syntax: -- (>>=) :: rhs_ty -> (pat_ty -> new_res_ty) -> res_ty -- This level of generality is needed for using do-notation -- in full generality; see Trac #1537 -- I'd like to put this *after* the tcSyntaxOp -- (see Note [Treat rebindable syntax first], but that breaks -- the rigidity info for GADTs. When we move to the new story -- for GADTs, we can move this after tcSyntaxOp rhs_ty <- newFlexiTyVarTy liftedTypeKind ; pat_ty <- newFlexiTyVarTy liftedTypeKind ; new_res_ty <- newFlexiTyVarTy liftedTypeKind ; bind_op' <- tcSyntaxOp DoOrigin bind_op (mkFunTys [rhs_ty, mkFunTy pat_ty new_res_ty] res_ty) -- If (but only if) the pattern can fail, -- typecheck the 'fail' operator ; fail_op' <- if isIrrefutableHsPat pat then return noSyntaxExpr else tcSyntaxOp DoOrigin fail_op (mkFunTy stringTy new_res_ty) ; rhs' <- tcMonoExprNC rhs rhs_ty ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $ thing_inside new_res_ty ; return (BindStmt pat' rhs' bind_op' fail_op', thing) } tcDoStmt _ (BodyStmt rhs then_op _ _) res_ty thing_inside = do { -- Deal with rebindable syntax; -- (>>) :: rhs_ty -> new_res_ty -> res_ty -- See also Note [Treat rebindable syntax first] rhs_ty <- newFlexiTyVarTy liftedTypeKind ; new_res_ty <- newFlexiTyVarTy liftedTypeKind ; then_op' <- tcSyntaxOp DoOrigin then_op (mkFunTys [rhs_ty, new_res_ty] res_ty) ; rhs' <- tcMonoExprNC rhs rhs_ty ; thing <- thing_inside new_res_ty ; return (BodyStmt rhs' then_op' noSyntaxExpr rhs_ty, thing) } tcDoStmt ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = later_names , recS_rec_ids = rec_names, recS_ret_fn = ret_op , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op }) res_ty thing_inside = do { let tup_names = rec_names ++ filterOut (`elem` rec_names) later_names ; tup_elt_tys <- newFlexiTyVarTys (length tup_names) liftedTypeKind ; let tup_ids = zipWith mkLocalId tup_names tup_elt_tys tup_ty = mkBigCoreTupTy tup_elt_tys ; tcExtendIdEnv tup_ids $ do { stmts_ty <- newFlexiTyVarTy liftedTypeKind ; (stmts', (ret_op', tup_rets)) <- tcStmtsAndThen ctxt tcDoStmt stmts stmts_ty $ \ inner_res_ty -> do { tup_rets <- zipWithM tcCheckId tup_names tup_elt_tys -- Unify the types of the "final" Ids (which may -- be polymorphic) with those of "knot-tied" Ids ; ret_op' <- tcSyntaxOp DoOrigin ret_op (mkFunTy tup_ty inner_res_ty) ; return (ret_op', tup_rets) } ; mfix_res_ty <- newFlexiTyVarTy liftedTypeKind ; mfix_op' <- tcSyntaxOp DoOrigin mfix_op (mkFunTy (mkFunTy tup_ty stmts_ty) mfix_res_ty) ; new_res_ty <- newFlexiTyVarTy liftedTypeKind ; bind_op' <- tcSyntaxOp DoOrigin bind_op (mkFunTys [mfix_res_ty, mkFunTy tup_ty new_res_ty] res_ty) ; thing <- thing_inside new_res_ty ; let rec_ids = takeList rec_names tup_ids ; later_ids <- tcLookupLocalIds later_names ; traceTc "tcdo" $ vcat [ppr rec_ids <+> ppr (map idType rec_ids), ppr later_ids <+> ppr (map idType later_ids)] ; return (RecStmt { recS_stmts = stmts', recS_later_ids = later_ids , recS_rec_ids = rec_ids, recS_ret_fn = ret_op' , recS_mfix_fn = mfix_op', recS_bind_fn = bind_op' , recS_later_rets = [], recS_rec_rets = tup_rets , recS_ret_ty = stmts_ty }, thing) }} tcDoStmt _ stmt _ _ = pprPanic "tcDoStmt: unexpected Stmt" (ppr stmt) {- Note [Treat rebindable syntax first] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When typechecking do { bar; ... } :: IO () we want to typecheck 'bar' in the knowledge that it should be an IO thing, pushing info from the context into the RHS. To do this, we check the rebindable syntax first, and push that information into (tcMonoExprNC rhs). Otherwise the error shows up when cheking the rebindable syntax, and the expected/inferred stuff is back to front (see Trac #3613). ************************************************************************ * * \subsection{Errors and contexts} * * ************************************************************************ @sameNoOfArgs@ takes a @[RenamedMatch]@ and decides whether the same number of args are used in each equation. -} checkArgs :: Name -> MatchGroup Name body -> TcM () checkArgs _ (MG { mg_alts = [] }) = return () checkArgs fun (MG { mg_alts = match1:matches }) | null bad_matches = return () | otherwise = failWithTc (vcat [ptext (sLit "Equations for") <+> quotes (ppr fun) <+> ptext (sLit "have different numbers of arguments"), nest 2 (ppr (getLoc match1)), nest 2 (ppr (getLoc (head bad_matches)))]) where n_args1 = args_in_match match1 bad_matches = [m | m <- matches, args_in_match m /= n_args1] args_in_match :: LMatch Name body -> Int args_in_match (L _ (Match _ pats _ _)) = length pats
DavidAlphaFox/ghc
compiler/typecheck/TcMatches.hs
bsd-3-clause
37,842
2
20
12,258
7,467
3,955
3,512
-1
-1
data Nat = Z | S Nat deriving (Eq, Show)
batterseapower/supercompilation-by-evaluation
examples/toys/AckermannPeano.hs
bsd-3-clause
49
0
6
18
24
13
11
2
0
----------------------------------------------------------------------------- -- | -- Module : Hadrian.Builder.Tar -- Copyright : (c) Andrey Mokhov 2014-2017 -- License : MIT (see the file LICENSE) -- Maintainer : andrey.mokhov@gmail.com -- Stability : experimental -- -- Support for invoking the archiving utility @tar@. ----------------------------------------------------------------------------- module Hadrian.Builder.Tar (TarMode (..), args) where import Development.Shake import Development.Shake.Classes import GHC.Generics import Hadrian.Expression -- | Tar can be used to 'Create' an archive or 'Extract' from it. data TarMode = Create | Extract deriving (Eq, Generic, Show) instance Binary TarMode instance Hashable TarMode instance NFData TarMode -- | Default command line arguments for invoking the archiving utility @tar@. args :: (ShakeValue c, ShakeValue b) => TarMode -> Args c b args Create = mconcat [ arg "-c" , output "//*.gz" ? arg "--gzip" , output "//*.bz2" ? arg "--bzip2" , output "//*.xz" ? arg "--xz" , arg "-f", arg =<< getOutput , getInputs ] args Extract = mconcat [ arg "-x" , input "*.gz" ? arg "--gzip" , input "*.bz2" ? arg "--bzip2" , input "*.xz" ? arg "--xz" , arg "-f", arg =<< getInput , arg "-C", arg =<< getOutput ]
bgamari/shaking-up-ghc
src/Hadrian/Builder/Tar.hs
bsd-3-clause
1,328
0
8
253
281
151
130
24
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sr-CS"> <title>Active Scan Rules | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/ascanrules/src/main/javahelp/org/zaproxy/zap/extension/ascanrules/resources/help_sr_CS/helpset_sr_CS.hs
apache-2.0
978
78
66
160
415
210
205
-1
-1
{-# Language DataKinds #-} {-# Language TypeApplications #-} {-# Language PolyKinds #-} module T12045e where import Data.Kind data Nat = Zero | Succ Nat data T (n :: k) = MkT data D1 n = T @Nat n :! () data D2 n = () :!! T @Nat n data D3 n = T @Nat n :!!! T @Nat n
sdiehl/ghc
testsuite/tests/parser/should_compile/T12045e.hs
bsd-3-clause
300
5
8
95
93
58
35
-1
-1
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable #-} -------------------------------------------------------------------------------- -- | Boolean formulas without quantifiers and without negation. -- Such a formula consists of variables, conjunctions (and), and disjunctions (or). -- -- This module is used to represent minimal complete definitions for classes. -- module BooleanFormula ( BooleanFormula(..), LBooleanFormula, mkFalse, mkTrue, mkAnd, mkOr, mkVar, isFalse, isTrue, eval, simplify, isUnsatisfied, implies, impliesAtom, pprBooleanFormula, pprBooleanFormulaNice ) where import Data.List ( nub, intersperse ) import Data.Data import MonadUtils import Outputable import Binary import SrcLoc ---------------------------------------------------------------------- -- Boolean formula type and smart constructors ---------------------------------------------------------------------- type LBooleanFormula a = Located (BooleanFormula a) data BooleanFormula a = Var a | And [LBooleanFormula a] | Or [LBooleanFormula a] | Parens (LBooleanFormula a) deriving (Eq, Data, Functor, Foldable, Traversable) mkVar :: a -> BooleanFormula a mkVar = Var mkFalse, mkTrue :: BooleanFormula a mkFalse = Or [] mkTrue = And [] -- Convert a Bool to a BooleanFormula mkBool :: Bool -> BooleanFormula a mkBool False = mkFalse mkBool True = mkTrue -- Make a conjunction, and try to simplify mkAnd :: Eq a => [LBooleanFormula a] -> BooleanFormula a mkAnd = maybe mkFalse (mkAnd' . nub) . concatMapM fromAnd where -- See Note [Simplification of BooleanFormulas] fromAnd :: LBooleanFormula a -> Maybe [LBooleanFormula a] fromAnd (L _ (And xs)) = Just xs -- assume that xs are already simplified -- otherwise we would need: fromAnd (And xs) = concat <$> traverse fromAnd xs fromAnd (L _ (Or [])) = Nothing -- in case of False we bail out, And [..,mkFalse,..] == mkFalse fromAnd x = Just [x] mkAnd' [x] = unLoc x mkAnd' xs = And xs mkOr :: Eq a => [LBooleanFormula a] -> BooleanFormula a mkOr = maybe mkTrue (mkOr' . nub) . concatMapM fromOr where -- See Note [Simplification of BooleanFormulas] fromOr (L _ (Or xs)) = Just xs fromOr (L _ (And [])) = Nothing fromOr x = Just [x] mkOr' [x] = unLoc x mkOr' xs = Or xs {- Note [Simplification of BooleanFormulas] ~~~~~~~~~~~~~~~~~~~~~~ The smart constructors (`mkAnd` and `mkOr`) do some attempt to simplify expressions. In particular, 1. Collapsing nested ands and ors, so `(mkAnd [x, And [y,z]]` is represented as `And [x,y,z]` Implemented by `fromAnd`/`fromOr` 2. Collapsing trivial ands and ors, so `mkAnd [x]` becomes just `x`. Implemented by mkAnd' / mkOr' 3. Conjunction with false, disjunction with true is simplified, i.e. `mkAnd [mkFalse,x]` becomes `mkFalse`. 4. Common subexpresion elimination: `mkAnd [x,x,y]` is reduced to just `mkAnd [x,y]`. This simplification is not exhaustive, in the sense that it will not produce the smallest possible equivalent expression. For example, `Or [And [x,y], And [x]]` could be simplified to `And [x]`, but it currently is not. A general simplifier would need to use something like BDDs. The reason behind the (crude) simplifier is to make for more user friendly error messages. E.g. for the code > class Foo a where > {-# MINIMAL bar, (foo, baq | foo, quux) #-} > instance Foo Int where > bar = ... > baz = ... > quux = ... We don't show a ridiculous error message like Implement () and (either (`foo' and ()) or (`foo' and ())) -} ---------------------------------------------------------------------- -- Evaluation and simplification ---------------------------------------------------------------------- isFalse :: BooleanFormula a -> Bool isFalse (Or []) = True isFalse _ = False isTrue :: BooleanFormula a -> Bool isTrue (And []) = True isTrue _ = False eval :: (a -> Bool) -> BooleanFormula a -> Bool eval f (Var x) = f x eval f (And xs) = all (eval f . unLoc) xs eval f (Or xs) = any (eval f . unLoc) xs eval f (Parens x) = eval f (unLoc x) -- Simplify a boolean formula. -- The argument function should give the truth of the atoms, or Nothing if undecided. simplify :: Eq a => (a -> Maybe Bool) -> BooleanFormula a -> BooleanFormula a simplify f (Var a) = case f a of Nothing -> Var a Just b -> mkBool b simplify f (And xs) = mkAnd (map (\(L l x) -> L l (simplify f x)) xs) simplify f (Or xs) = mkOr (map (\(L l x) -> L l (simplify f x)) xs) simplify f (Parens x) = simplify f (unLoc x) -- Test if a boolean formula is satisfied when the given values are assigned to the atoms -- if it is, returns Nothing -- if it is not, return (Just remainder) isUnsatisfied :: Eq a => (a -> Bool) -> BooleanFormula a -> Maybe (BooleanFormula a) isUnsatisfied f bf | isTrue bf' = Nothing | otherwise = Just bf' where f' x = if f x then Just True else Nothing bf' = simplify f' bf -- prop_simplify: -- eval f x == True <==> isTrue (simplify (Just . f) x) -- eval f x == False <==> isFalse (simplify (Just . f) x) -- If the boolean formula holds, does that mean that the given atom is always true? impliesAtom :: Eq a => BooleanFormula a -> a -> Bool Var x `impliesAtom` y = x == y And xs `impliesAtom` y = any (\x -> (unLoc x) `impliesAtom` y) xs -- we have all of xs, so one of them implying y is enough Or xs `impliesAtom` y = all (\x -> (unLoc x) `impliesAtom` y) xs Parens x `impliesAtom` y = (unLoc x) `impliesAtom` y implies :: Eq a => BooleanFormula a -> BooleanFormula a -> Bool x `implies` Var y = x `impliesAtom` y x `implies` And ys = all (implies x . unLoc) ys x `implies` Or ys = any (implies x . unLoc) ys x `implies` Parens y = x `implies` (unLoc y) ---------------------------------------------------------------------- -- Pretty printing ---------------------------------------------------------------------- -- Pretty print a BooleanFormula, -- using the arguments as pretty printers for Var, And and Or respectively pprBooleanFormula' :: (Rational -> a -> SDoc) -> (Rational -> [SDoc] -> SDoc) -> (Rational -> [SDoc] -> SDoc) -> Rational -> BooleanFormula a -> SDoc pprBooleanFormula' pprVar pprAnd pprOr = go where go p (Var x) = pprVar p x go p (And []) = cparen (p > 0) $ empty go p (And xs) = pprAnd p (map (go 3 . unLoc) xs) go _ (Or []) = keyword $ text "FALSE" go p (Or xs) = pprOr p (map (go 2 . unLoc) xs) go p (Parens x) = go p (unLoc x) -- Pretty print in source syntax, "a | b | c,d,e" pprBooleanFormula :: (Rational -> a -> SDoc) -> Rational -> BooleanFormula a -> SDoc pprBooleanFormula pprVar = pprBooleanFormula' pprVar pprAnd pprOr where pprAnd p = cparen (p > 3) . fsep . punctuate comma pprOr p = cparen (p > 2) . fsep . intersperse vbar -- Pretty print human in readable format, "either `a' or `b' or (`c', `d' and `e')"? pprBooleanFormulaNice :: Outputable a => BooleanFormula a -> SDoc pprBooleanFormulaNice = pprBooleanFormula' pprVar pprAnd pprOr 0 where pprVar _ = quotes . ppr pprAnd p = cparen (p > 1) . pprAnd' pprAnd' [] = empty pprAnd' [x,y] = x <+> text "and" <+> y pprAnd' xs@(_:_) = fsep (punctuate comma (init xs)) <> text ", and" <+> last xs pprOr p xs = cparen (p > 1) $ text "either" <+> sep (intersperse (text "or") xs) instance Outputable a => Outputable (BooleanFormula a) where pprPrec = pprBooleanFormula pprPrec ---------------------------------------------------------------------- -- Binary ---------------------------------------------------------------------- instance Binary a => Binary (BooleanFormula a) where put_ bh (Var x) = putByte bh 0 >> put_ bh x put_ bh (And xs) = putByte bh 1 >> put_ bh xs put_ bh (Or xs) = putByte bh 2 >> put_ bh xs put_ bh (Parens x) = putByte bh 3 >> put_ bh x get bh = do h <- getByte bh case h of 0 -> Var <$> get bh 1 -> And <$> get bh 2 -> Or <$> get bh _ -> Parens <$> get bh
snoyberg/ghc
compiler/utils/BooleanFormula.hs
bsd-3-clause
8,127
0
13
1,763
2,220
1,131
1,089
113
6
-- |If a message type's first field is of type Header, its sequence -- number is automatically incremented by the ROS Topic machinery. module Ros.Internal.Msg.HeaderSupport where import Data.Binary (Put) import Data.Word (Word32) import Ros.Internal.RosBinary (RosBinary, put) import Ros.Internal.RosTypes (ROSTime) class HasHeader a where getSequence :: a -> Word32 getFrame :: a -> String getStamp :: a -> ROSTime setSequence :: Word32 -> a -> a -- |Serialize a message after setting the sequence number in its -- header. putStampedMsg :: (HasHeader a, RosBinary a) => Word32 -> a -> Put putStampedMsg n v = put $ setSequence n v
bitemyapp/roshask
src/Ros/Internal/Msg/HeaderSupport.hs
bsd-3-clause
655
0
8
122
153
88
65
12
1
module Blank where {-@ type ListN a N = {v:[a] | (len v) = N} @-} -- TODO: extend parser to allow expressions, at the very least, -- literals as arguments! Currently, the below is rejected by the parser. {-@ xs :: (ListN Int 2) @-} xs :: [Int] xs = [1,2]
mightymoose/liquidhaskell
tests/todo/err9.hs
bsd-3-clause
267
0
5
64
27
19
8
3
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE CPP #-} import Control.Exception import Control.Monad.IO.Class import System.Environment import System.FilePath import System.IO.Error #ifndef mingw32_HOST_OS import System.Posix (readSymbolicLink) #endif /* mingw32_HOST_OS */ import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Program.Db import Distribution.Simple.Program.Builtin import Distribution.Simple.Program.Types import Distribution.System import Distribution.Verbosity import Distribution.Version import Test.Cabal.Prelude -- Test that foreign libraries work -- Recording is turned off because versionedlib will or will not -- be installed depending on if we're on Linux or not. main = setupAndCabalTest . recordMode DoNotRecord $ do -- Foreign libraries don't work with GHC 7.6 and earlier skipUnless =<< ghcVersionIs (>= mkVersion [7,8]) withPackageDb $ do setup_install [] setup "copy" [] -- regression test #4156 dist_dir <- fmap testDistDir getTestEnv lbi <- getLocalBuildInfoM let installDirs = absoluteInstallDirs (localPkgDescr lbi) lbi NoCopyDest -- Link a C program against the library _ <- runProgramM gccProgram [ "-o", "uselib" , "UseLib.c" , "-l", "myforeignlib" , "-L", flibdir installDirs ] -- Run the C program let ldPath = case hostPlatform lbi of Platform _ OSX -> "DYLD_LIBRARY_PATH" Platform _ Windows -> "PATH" Platform _ _other -> "LD_LIBRARY_PATH" oldLdPath <- liftIO $ getEnv' ldPath withEnv [ (ldPath, Just $ flibdir installDirs ++ [searchPathSeparator] ++ oldLdPath) ] $ do cwd <- fmap testCurrentDir getTestEnv result <- runM (cwd </> "uselib") [] assertOutputContains "5678" result assertOutputContains "189" result -- If we're on Linux, we should have built a library with a -- version. We will now check that it was installed correctly. #ifndef mingw32_HOST_OS case hostPlatform lbi of Platform _ Linux -> do let libraryName = "libversionedlib.so.5.4.3" libdir = flibdir installDirs objdumpProgram = simpleProgram "objdump" (objdump, _) <- liftIO $ requireProgram normal objdumpProgram (withPrograms lbi) path1 <- liftIO $ readSymbolicLink $ libdir </> "libversionedlib.so" path2 <- liftIO $ readSymbolicLink $ libdir </> "libversionedlib.so.5" assertEqual "Symbolic link 'libversionedlib.so' incorrect" path1 libraryName assertEqual "Symbolic link 'libversionedlib.so.5' incorrect" path2 libraryName objInfo <- runM (programPath objdump) [ "-x" , libdir </> libraryName ] assertBool "SONAME of 'libversionedlib.so.5.4.3' incorrect" $ elem "libversionedlib.so.5" $ words $ resultOutput objInfo _ -> return () #endif /* mingw32_HOST_OS */ getEnv' :: String -> IO String getEnv' = handle handler . getEnv where handler e = if isDoesNotExistError e then return "" else throw e
themoritz/cabal
cabal-testsuite/PackageTests/ForeignLibs/setup.test.hs
bsd-3-clause
3,396
0
20
1,026
640
323
317
62
4
-- | Contains an @sdist@ like function which computes the source files -- that we should track to determine if a rebuild is necessary. -- Unlike @sdist@, we can operate directly on the true -- 'PackageDescription' (not flattened). -- -- The naming convention, roughly, is that to declare we need the -- source for some type T, you use the function needT; some functions -- need auxiliary information. -- -- We can only use this code for non-Custom scripts; Custom scripts -- may have arbitrary extra dependencies (esp. new preprocessors) which -- we cannot "see" easily. module Distribution.Client.SourceFiles (needElaboratedConfiguredPackage) where import Distribution.Client.ProjectPlanning.Types import Distribution.Client.RebuildMonad import Distribution.Solver.Types.OptionalStanza import Distribution.Simple.PreProcess import Distribution.Types.PackageDescription import Distribution.Types.Component import Distribution.Types.ComponentRequestedSpec import Distribution.Types.Library import Distribution.Types.Executable import Distribution.Types.Benchmark import Distribution.Types.BenchmarkInterface import Distribution.Types.TestSuite import Distribution.Types.TestSuiteInterface import Distribution.Types.BuildInfo import Distribution.Types.ForeignLib import Distribution.ModuleName import Prelude () import Distribution.Client.Compat.Prelude import System.FilePath import Control.Monad import qualified Data.Set as Set needElaboratedConfiguredPackage :: ElaboratedConfiguredPackage -> Rebuild () needElaboratedConfiguredPackage elab = case elabPkgOrComp elab of ElabComponent ecomp -> needElaboratedComponent elab ecomp ElabPackage epkg -> needElaboratedPackage elab epkg needElaboratedPackage :: ElaboratedConfiguredPackage -> ElaboratedPackage -> Rebuild () needElaboratedPackage elab epkg = mapM_ (needComponent pkg_descr) (enabledComponents pkg_descr enabled) where pkg_descr = elabPkgDescription elab enabled_stanzas = pkgStanzasEnabled epkg -- TODO: turn this into a helper function somewhere enabled = ComponentRequestedSpec { testsRequested = TestStanzas `Set.member` enabled_stanzas, benchmarksRequested = BenchStanzas `Set.member` enabled_stanzas } needElaboratedComponent :: ElaboratedConfiguredPackage -> ElaboratedComponent -> Rebuild () needElaboratedComponent elab ecomp = case mb_comp of Nothing -> needSetup Just comp -> needComponent pkg_descr comp where pkg_descr = elabPkgDescription elab mb_comp = fmap (getComponent pkg_descr) (compComponentName ecomp) needComponent :: PackageDescription -> Component -> Rebuild () needComponent pkg_descr comp = case comp of CLib lib -> needLibrary pkg_descr lib CFLib flib -> needForeignLib pkg_descr flib CExe exe -> needExecutable pkg_descr exe CTest test -> needTestSuite pkg_descr test CBench bench -> needBenchmark pkg_descr bench needSetup :: Rebuild () needSetup = findFirstFileMonitored id ["Setup.hs", "Setup.lhs"] >> return () needLibrary :: PackageDescription -> Library -> Rebuild () needLibrary pkg_descr (Library { exposedModules = modules , signatures = sigs , libBuildInfo = bi }) = needBuildInfo pkg_descr bi (modules ++ sigs) needForeignLib :: PackageDescription -> ForeignLib -> Rebuild () needForeignLib pkg_descr (ForeignLib { foreignLibModDefFile = fs , foreignLibBuildInfo = bi }) = do mapM_ needIfExists fs needBuildInfo pkg_descr bi [] needExecutable :: PackageDescription -> Executable -> Rebuild () needExecutable pkg_descr (Executable { modulePath = mainPath , buildInfo = bi }) = do needBuildInfo pkg_descr bi [] needMainFile bi mainPath needTestSuite :: PackageDescription -> TestSuite -> Rebuild () needTestSuite pkg_descr t = case testInterface t of TestSuiteExeV10 _ mainPath -> do needBuildInfo pkg_descr bi [] needMainFile bi mainPath TestSuiteLibV09 _ m -> needBuildInfo pkg_descr bi [m] TestSuiteUnsupported _ -> return () -- soft fail where bi = testBuildInfo t needMainFile :: BuildInfo -> FilePath -> Rebuild () needMainFile bi mainPath = do -- The matter here is subtle. It might *seem* that we -- should just search for mainPath, but as per -- b61cb051f63ed5869b8f4a6af996ff7e833e4b39 'main-is' -- will actually be the source file AFTER preprocessing, -- whereas we need to get the file *prior* to preprocessing. ppFile <- findFileWithExtensionMonitored (ppSuffixes knownSuffixHandlers) (hsSourceDirs bi) (dropExtension mainPath) case ppFile of -- But check the original path in the end, because -- maybe it's a non-preprocessed file with a non-traditional -- extension. Nothing -> findFileMonitored (hsSourceDirs bi) mainPath >>= maybe (return ()) need Just pp -> need pp needBenchmark :: PackageDescription -> Benchmark -> Rebuild () needBenchmark pkg_descr bm = case benchmarkInterface bm of BenchmarkExeV10 _ mainPath -> do needBuildInfo pkg_descr bi [] needMainFile bi mainPath BenchmarkUnsupported _ -> return () -- soft fail where bi = benchmarkBuildInfo bm needBuildInfo :: PackageDescription -> BuildInfo -> [ModuleName] -> Rebuild () needBuildInfo pkg_descr bi modules = do -- NB: These are separate because there may be both A.hs and -- A.hs-boot; need to track both. findNeededModules ["hs", "lhs", "hsig", "lhsig"] findNeededModules ["hs-boot", "lhs-boot"] mapM_ needIfExists (cSources bi ++ jsSources bi) -- A MASSIVE HACK to (1) make sure we rebuild when header -- files change, but (2) not have to rebuild when anything -- in extra-src-files changes (most of these won't affect -- compilation). It would be even better if we knew on a -- per-component basis which headers would be used but that -- seems to be too difficult. mapM_ needIfExists (filter ((==".h").takeExtension) (extraSrcFiles pkg_descr)) forM_ (installIncludes bi) $ \f -> findFileMonitored ("." : includeDirs bi) f >>= maybe (return ()) need where findNeededModules exts = mapM_ (findNeededModule exts) (modules ++ otherModules bi) findNeededModule exts m = findFileWithExtensionMonitored (ppSuffixes knownSuffixHandlers ++ exts) (hsSourceDirs bi) (toFilePath m) >>= maybe (return ()) need
mydaum/cabal
cabal-install/Distribution/Client/SourceFiles.hs
bsd-3-clause
6,728
0
14
1,506
1,320
684
636
114
5
----------------------------------------------------------------------------- -- -- Module : Network.Google.OAuth2 -- Copyright : (c) 2012-13 Brian W Bush, Ryan Newton -- License : MIT -- -- Maintainer : Brian W Bush <b.w.bush@acm.org>, Ryan Newton <rrnewton@indiana.edu> -- Stability : Stable -- Portability : Portable -- -- | Functions for OAuth 2.0 authentication for Google APIs. -- -- If you are new to Google web API's, bear in mind that there are /three/ different -- methods for accessing APIs (installed applications, web apps, service-to-service), -- and this library is most useful for \"installed applications\". -- -- Installed applications need the user to grant permission in a browser at least -- once (see `formUrl`). However, while the resulting `accessToken` expires quickly, -- the `refreshToken` can be used indefinitely for retrieving new access tokens. -- Thus this approach can be suitable for long running or periodic programs that -- access Google data. -- -- Below is a quick-start program which will list any Google Fusion tables the user -- possesses. It requires the client ID and secret retrieved from -- <https://code.google.com/apis/console>. -- -- @ -- import Control.Monad (unless) -- import System.Info (os) -- import System.Process (system, rawSystem) -- import System.Exit (ExitCode(..)) -- import System.Directory (doesFileExist) -- import Network.Google.OAuth2 (formUrl, exchangeCode, refreshTokens, -- OAuth2Client(..), OAuth2Tokens(..)) -- import Network.Google (makeRequest, doRequest) -- import Network.HTTP.Conduit (simpleHttp) -- -- -- cid = \"INSTALLED_APP_CLIENT_ID\" -- secret = \"INSTALLED_APP_SECRET_HERE\" -- file = \"./tokens.txt\" -- -- -- main = do -- -- Ask for permission to read/write your fusion tables: -- let client = OAuth2Client { clientId = cid, clientSecret = secret } -- permissionUrl = formUrl client [\"https://www.googleapis.com/auth/fusiontables\"] -- b <- doesFileExist file -- unless b $ do -- putStrLn$ \"Load this URL: \"++show permissionUrl -- case os of -- \"linux\" -> rawSystem \"gnome-open\" [permissionUrl] -- \"darwin\" -> rawSystem \"open\" [permissionUrl] -- _ -> return ExitSuccess -- putStrLn \"Please paste the verification code: \" -- authcode <- getLine -- tokens <- exchangeCode client authcode -- putStrLn$ \"Received access token: \"++show (accessToken tokens) -- tokens2 <- refreshTokens client tokens -- putStrLn$ \"As a test, refreshed token: \"++show (accessToken tokens2) -- writeFile file (show tokens2) -- accessTok <- fmap (accessToken . read) (readFile file) -- putStrLn \"As a test, list the users tables:\" -- response <- simpleHttp (\"https://www.googleapis.com/fusiontables/v1/tables?access_token=\"++accessTok) -- putStrLn$ BL.unpack response -- @ ----------------------------------------------------------------------------- module Network.Google.OAuth2 ( -- * Types OAuth2Client(..) , OAuth2Scope , OAuth2Tokens(..) -- * Functions , googleScopes , formUrl , exchangeCode , refreshTokens , validateTokens , getCachedTokens ) where import Control.Monad (unless) import Data.ByteString.Char8 as BS8 (ByteString, pack) import Data.ByteString.Lazy.UTF8 (toString) import Data.Default (def) import Data.List (intercalate) import Data.Time.Clock (getCurrentTime) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Data.Word (Word64) import Network.Google (makeHeaderName) import Network.HTTP.Base (urlEncode) import Network.HTTP.Conduit (Request(..), RequestBody(..), Response(..), defaultRequest, httpLbs, responseBody, withManager) import Text.JSON (JSObject, JSValue(JSRational), Result(Ok), decode, valFromObj) import System.Info (os) import System.Process (rawSystem) import System.Exit (ExitCode(..)) import System.Directory (doesFileExist, doesDirectoryExist, getAppUserDataDirectory, createDirectory, renameFile, removeFile) import System.FilePath ((</>),(<.>), splitExtension) import System.Random (randomIO) -- An OAuth 2.0 client for an installed application, see <https://developers.google.com/accounts/docs/OAuth2InstalledApp>. data OAuth2Client = OAuth2Client { clientId :: String -- ^ The client ID. , clientSecret :: String -- ^ The client secret. } deriving (Read, Show) -- | An OAuth 2.0 code. type OAuth2Code = String -- | OAuth 2.0 tokens. data OAuth2Tokens = OAuth2Tokens { accessToken :: String -- ^ The access token. , refreshToken :: String -- ^ The refresh token. , expiresIn :: Rational -- ^ The number of seconds until the access token expires. , tokenType :: String -- ^ The token type. } deriving (Read, Show) -- | An OAuth 2.0 scope. type OAuth2Scope = String -- | The OAuth 2.0 scopes for Google APIs, see <https://developers.google.com/oauthplayground/>. googleScopes :: [(String, OAuth2Scope)] -- ^ List of names and the corresponding scopes. googleScopes = [ ("Adsense Management", "https://www.googleapis.com/auth/adsense") , ("Google Affiliate Network", "https://www.googleapis.com/auth/gan") , ("Analytics", "https://www.googleapis.com/auth/analytics.readonly") , ("Google Books", "https://www.googleapis.com/auth/books") , ("Blogger", "https://www.googleapis.com/auth/blogger") , ("Calendar", "https://www.googleapis.com/auth/calendar") , ("Google Cloud Storage", "https://www.googleapis.com/auth/devstorage.read_write") , ("Contacts", "https://www.google.com/m8/feeds/") , ("Content API for Shopping", "https://www.googleapis.com/auth/structuredcontent") , ("Chrome Web Store", "https://www.googleapis.com/auth/chromewebstore.readonly") , ("Fusion Tables", "https://www.googleapis.com/auth/fusiontables") , ("Documents List", "https://docs.google.com/feeds/") , ("Google Drive", "https://www.googleapis.com/auth/drive") , ("Google Drive Files", "Files https://www.googleapis.com/auth/drive.file") , ("Gmail", "https://mail.google.com/mail/feed/atom") , ("Google+", "https://www.googleapis.com/auth/plus.me") , ("Groups Provisioning", "https://apps-apis.google.com/a/feeds/groups/") , ("Google Latitude", "https://www.googleapis.com/auth/latitude.all.best https://www.googleapis.com/auth/latitude.all.city") , ("Moderator", "https://www.googleapis.com/auth/moderator") , ("Nicknames", "Provisioning https://apps-apis.google.com/a/feeds/alias/") , ("Orkut", "https://www.googleapis.com/auth/orkut") , ("Picasa Web", "https://picasaweb.google.com/data/") , ("Sites", "https://sites.google.com/feeds/") , ("Spreadsheets", "https://spreadsheets.google.com/feeds/") , ("Tasks", "https://www.googleapis.com/auth/tasks") , ("URL Shortener", "https://www.googleapis.com/auth/urlshortener") , ("Userinfo - Email", "https://www.googleapis.com/auth/userinfo.email") , ("Userinfo - Profile", "https://www.googleapis.com/auth/userinfo.profile") , ("User Provisioning", "https://apps-apis.google.com/a/feeds/user/") , ("Webmaster Tools", "https://www.google.com/webmasters/tools/feeds/") , ("YouTube", "https://gdata.youtube.com") ] -- | The redirect URI for an installed application, see <https://developers.google.com/accounts/docs/OAuth2InstalledApp#choosingredirecturi>. redirectUri :: String redirectUri = "urn:ietf:wg:oauth:2.0:oob" -- | Form a URL for authorizing an installed application, see <https://developers.google.com/accounts/docs/OAuth2InstalledApp#formingtheurl>. formUrl :: OAuth2Client -- ^ The OAuth 2.0 client. -> [OAuth2Scope] -- ^ The OAuth 2.0 scopes to be authorized. -> String -- ^ The URL for authorization. formUrl client scopes = "https://accounts.google.com/o/oauth2/auth" ++ "?response_type=code" ++ "&client_id=" ++ clientId client ++ "&redirect_uri=" ++ redirectUri ++ "&scope=" ++ intercalate "+" (map urlEncode scopes) -- | Exchange an authorization code for tokens, see <https://developers.google.com/accounts/docs/OAuth2InstalledApp#handlingtheresponse>. exchangeCode :: OAuth2Client -- ^ The OAuth 2.0 client. -> OAuth2Code -- ^ The authorization code. -> IO OAuth2Tokens -- ^ The action for obtaining the tokens. exchangeCode client code = do result <- doOAuth2 client "authorization_code" ("&redirect_uri=" ++ redirectUri ++ "&code=" ++ code) let (Ok result') = decodeTokens Nothing result return result' -- | Refresh OAuth 2.0 tokens from JSON data. decodeTokens :: Maybe OAuth2Tokens -- ^ The original tokens, if any. -> JSObject JSValue -- ^ The JSON value. -> Result OAuth2Tokens -- ^ The refreshed tokens. decodeTokens tokens value = do let (!) = flip valFromObj -- TODO: There should be a more straightforward way to do this. expiresIn' :: Rational (Ok (JSRational _ expiresIn')) = valFromObj "expires_in" value accessToken <- value ! "access_token" refreshToken <- maybe (value ! "refresh_token") (Ok . refreshToken) tokens tokenType <- value ! "token_type" return OAuth2Tokens { accessToken = accessToken , refreshToken = refreshToken , expiresIn = expiresIn' , tokenType = tokenType } -- | Refresh OAuth 2.0 tokens, see <https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh>. refreshTokens :: OAuth2Client -- ^ The client. -> OAuth2Tokens -- ^ The tokens. -> IO OAuth2Tokens -- ^ The action to refresh the tokens. refreshTokens client tokens = do result <- doOAuth2 client "refresh_token" ("&refresh_token=" ++ refreshToken tokens) let (Ok result') = decodeTokens (Just tokens) result return result' -- | Peform OAuth 2.0 authentication, see <https://developers.google.com/accounts/docs/OAuth2InstalledApp#handlingtheresponse>. doOAuth2 :: OAuth2Client -- ^ The client. -> String -- ^ The grant type. -> String -- ^ The -> IO (JSObject JSValue) -- ^ The action returing the JSON response from making the request. doOAuth2 client grantType extraBody = do let -- TODO: In principle, we should UTF-8 encode the bytestrings packed below. request = defaultRequest { method = BS8.pack "POST" , secure = True , host = BS8.pack "accounts.google.com" , port = 443 , path = BS8.pack "/o/oauth2/token" , requestHeaders = [ (makeHeaderName "Content-Type", BS8.pack "application/x-www-form-urlencoded") ] , requestBody = RequestBodyBS . BS8.pack $ "client_id=" ++ clientId client ++ "&client_secret=" ++ clientSecret client ++ "&grant_type=" ++ grantType ++ extraBody } response <- withManager $ httpLbs request let (Ok result) = decode . toString $ responseBody response return result -- | Validate OAuth 2.0 tokens, see <https://developers.google.com/accounts/docs/OAuth2Login#validatingtoken>. validateTokens :: OAuth2Tokens -- ^ The tokens. -> IO Rational -- ^ The number of seconds until the access token expires. validateTokens tokens = do let request = defaultRequest { method = BS8.pack "GET" , secure = True , host = BS8.pack "www.googleapis.com" , port = 443 , path = BS8.pack "/oauth2/v1/tokeninfo" , queryString = BS8.pack ("?access_token=" ++ accessToken tokens) } response <- withManager $ httpLbs request let (Ok result) = decode . toString $ responseBody response expiresIn' :: Rational (Ok (JSRational _ expiresIn')) = valFromObj "expires_in" result return expiresIn' -- | Provide a hassle-free way to retrieve and refresh tokens from a user's home -- directory, OR ask the user for permission. -- -- The first time it is called, this may open a web-browser, and/or request the user -- enter data on the command line. Subsequently, invocations on the same machine -- should not communicate with the user. -- -- If the tokens do not expire until more than 15 minutes in the future, this -- procedure will skip the refresh step. Whether or not it refreshes should be -- immaterial to the clients subsequent actions, because all clients should handle -- authentication errors (and all 5xx errors) and call `refreshToken` as necessary. getCachedTokens :: OAuth2Client -- ^ The client is the \"key\" for token lookup. -> IO OAuth2Tokens getCachedTokens client = do cabalD <- getAppUserDataDirectory "cabal" let tokenD = cabalD </> "googleAuthTokens" tokenF = tokenD </> clientId client <.> "token" d1 <- doesDirectoryExist cabalD unless d1 $ createDirectory cabalD -- Race. d2 <- doesDirectoryExist tokenD unless d2 $ createDirectory tokenD -- Race. f1 <- doesFileExist tokenF if f1 then do str <- readFile tokenF case reads str of -- Here's our approach to versioning! If we can't read it, we remove it. ((oldtime,toks),_):_ -> do tagged <- checkExpiry tokenF (oldtime,toks) return (snd tagged) [] -> do putStrLn$" [getCachedTokens] Could not read tokens from file: "++ tokenF putStrLn$" [getCachedTokens] Removing tokens and re-authenticating..." removeFile tokenF getCachedTokens client else do toks <- askUser fmap snd$ timeStampAndWrite tokenF toks where -- Tokens store a relative time, which is rather silly (relative to what?). This -- routine tags a token with the time it was issued, so as to enable figuring out -- the absolute expiration time. Also, as a side effect, this is where we refresh -- the token if it is already expired or expiring soon. checkExpiry :: FilePath -> (Rational, OAuth2Tokens) -> IO (Rational, OAuth2Tokens) checkExpiry tokenF orig@(start1,toks1) = do t <- getCurrentTime let nowsecs = toRational (utcTimeToPOSIXSeconds t) expire1 = start1 + expiresIn toks1 tolerance = 15 * 60 -- Skip refresh if token is good for at least 15 min. if expire1 < tolerance + nowsecs then do toks2 <- refreshTokens client toks1 timeStampAndWrite tokenF toks2 else return orig timeStampAndWrite :: FilePath -> OAuth2Tokens -> IO (Rational, OAuth2Tokens) timeStampAndWrite tokenF toks = do t2 <- getCurrentTime let tagged = (toRational (utcTimeToPOSIXSeconds t2), toks) atomicWriteFile tokenF (show tagged) return tagged -- This is the part where we require user interaction: askUser = do putStrLn$ " [getCachedTokens] Load this URL: "++show permissionUrl -- BJS: This crash on my machine. -- runBrowser putStrLn " [getCachedTokens] Then please paste the verification code and press enter:\n$ " authcode <- getLine tokens <- exchangeCode client authcode putStrLn$ " [getCachedTokens] Received access token: "++show (accessToken tokens) return tokens permissionUrl = formUrl client ["https://www.googleapis.com/auth/fusiontables"] -- This is hackish and incomplete runBrowser = case os of "linux" -> rawSystem "gnome-open" [permissionUrl] "darwin" -> rawSystem "open" [permissionUrl] _ -> return ExitSuccess atomicWriteFile file str = do suff <- randomIO :: IO Word64 let (root,ext) = splitExtension file tmp = root ++ show suff <.> ext writeFile tmp str -- RenameFile makes this atomic: renameFile tmp file
rrnewton/hgdata
src/Network/Google/OAuth2.hs
mit
15,686
0
20
3,180
2,301
1,298
1,003
232
6
module ViewPortTransformSpec (testZoom) where import Test.HUnit import Test.HUnit.Approx import Graphics.Gloss.Data.ViewPort import ViewPortTransform errorMargin :: Float errorMargin = 1e-6 testZoom :: Test testZoom = TestList [ TestLabel "Zoom In" zoomInTestCase , TestLabel "Zoom Out" zoomOutTestCase , TestLabel "Zoom Out Saturation" zoomOutSaturationTestCase ] where zoomInTestCase = generalTestCase 1.0 0.5 1.5 zoomOutTestCase = generalTestCase 1.0 (-0.5) 0.5 zoomOutSaturationTestCase = generalTestCase 0.1 (-0.5) 0.0 generalTestCase initialScale zoomStep expectedScale = let viewPort = viewPortInit { viewPortScale = initialScale } zoomedScale = viewPortScale $ zoom zoomStep viewPort message = "Unexpected result scale" in TestCase (assertApproxEqual message errorMargin expectedScale zoomedScale)
tsoding/boids
test/ViewPortTransformSpec.hs
mit
968
0
12
255
190
103
87
19
1
module Field where import Attribute import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString as B import Data.Word import Data.Binary.Get data Field = Field { f_access_flags :: Word16, name_index :: Word16, descriptor_index :: Word16, attributes :: [Attribute] } deriving Show getField = do access_flags <- getWord16be name_index <- getWord16be descriptor_index <- getWord16be attributes_count <- getWord16be attributes <- getAttributes (fromIntegral attributes_count) return (Field access_flags name_index descriptor_index attributes) getFields 0 = return [] getFields n = do field <- getField rest <- getFields (n - 1) return (field:rest)
cwgreene/javaclassreader
src/Field.hs
mit
738
0
10
162
199
107
92
24
1
module Aut_COMP_HW1_NFA(accept) where delta :: Int -> Char -> Int delta 0 c |c=='e' = 1|c=='a' = 3|c=='b' = 2 delta 1 c |c=='f' = 4 delta 2 c |c=='b' = 2 delta 3 c |c=='a' = 3|c=='b' = 5 delta 5 c |c=='c' = 6|c=='b' = 2 delta 6 c |c=='c' = 6 delta _ _ = -1 initialState::Int initialState = 0 finalStates::[Int] finalStates = [2,4,5,6] accept::String -> Bool accept str = foldl delta initialState str `elem` finalStates
migulorama/AutoAnalyze
dot_dfa_examples/COMP_HW1_NFA.hs
mit
423
0
8
83
271
135
136
15
1
module Collide.Internal where import Data.Foldable import Data.Monoid import Linear import Prelude hiding (minimum, maximum, sum) -- | Project normal along each of the given vectors. projectVS :: (Functor t, Foldable v, Metric v, Floating a) => t (v a) -> v a -> t a projectVS vs n = fmap (sum . project n) vs -- | Do the given sets of points overlap? overlapping :: (Foldable t1, Foldable t2, Ord a) => t1 a -> t2 a -> All overlapping as bs = All $ not (maximum as < minimum bs || maximum bs < minimum as) positionAtTime :: (Num (v a), Num a, Functor v) => v a -> v a -> a -> v a positionAtTime origin direction t = origin + (direction ^* t) roots :: (Ord a, Floating a) => a -> a -> a -> [a] roots a b c | discriminant < 0 = [] | otherwise = [0.5 * (-b + sqrt discriminant), 0.5 * (-b - sqrt discriminant)] where discriminant = b^^(2::Int) - 4*a*c
tcsavage/collide
src/Collide/Internal.hs
mit
864
0
11
187
411
211
200
16
1
{-# LANGUAGE NoImplicitPrelude, DeriveFunctor #-} module IHaskell.Flags ( IHaskellMode(..), Argument(..), Args(..), LhsStyle(..), lhsStyleBird, NotebookFormat(..), parseFlags, help, ) where import ClassyPrelude import System.Console.CmdArgs.Explicit import System.Console.CmdArgs.Text import Data.List (findIndex) import IHaskell.Types -- Command line arguments to IHaskell. A set of aruments is annotated with -- the mode being invoked. data Args = Args IHaskellMode [Argument] deriving Show data Argument = ServeFrom String -- ^ Which directory to serve notebooks from. | Extension String -- ^ An extension to load at startup. | ConfFile String -- ^ A file with commands to load at startup. | IPythonFrom String -- ^ Which executable to use for IPython. | IPythonPort String -- ^ Which port number should IPython serve on. | IPythonIP String -- ^ On what IP address should IPython serve. | OverwriteFiles -- ^ Present when output should overwrite existing files. | ConvertFrom String | ConvertTo String | ConvertFromFormat NotebookFormat | ConvertToFormat NotebookFormat | ConvertLhsStyle (LhsStyle String) | Help -- ^ Display help text. deriving (Eq, Show) data LhsStyle string = LhsStyle { lhsCodePrefix :: string, -- ^ @>@ lhsOutputPrefix :: string, -- ^ @<<@ lhsBeginCode :: string, -- ^ @\\begin{code}@ lhsEndCode :: string, -- ^ @\\end{code}@ lhsBeginOutput :: string, -- ^ @\\begin{verbatim}@ lhsEndOutput :: string -- ^ @\\end{verbatim}@ } deriving (Eq, Functor, Show) data NotebookFormat = LhsMarkdown | IpynbFile deriving (Eq,Show) -- Which mode IHaskell is being invoked in. -- `None` means no mode was specified. data IHaskellMode = ShowHelp String | Notebook | Console | ConvertLhs | Kernel (Maybe String) | View (Maybe ViewFormat) (Maybe String) deriving (Eq, Show) -- | Given a list of command-line arguments, return the IHaskell mode and -- arguments to process. parseFlags :: [String] -> Either String Args parseFlags flags = let modeIndex = findIndex (`elem` modeFlags) flags in case modeIndex of Nothing -> Left $ "No mode provided. Modes available are: " ++ show modeFlags ++ "\n" ++ pack (showText (Wrap 100) $ helpText [] HelpFormatAll ihaskellArgs) Just 0 -> process ihaskellArgs flags -- If mode not first, move it to be first. Just idx -> let (start, first:end) = splitAt idx flags in process ihaskellArgs $ first:start ++ end where modeFlags = concatMap modeNames allModes allModes :: [Mode Args] allModes = [console, notebook, view, kernel, convert] -- | Get help text for a given IHaskell ode. help :: IHaskellMode -> String help mode = showText (Wrap 100) $ helpText [] HelpFormatAll $ chooseMode mode where chooseMode Console = console chooseMode Notebook = notebook chooseMode (Kernel _) = kernel chooseMode ConvertLhs = convert ipythonFlag :: Flag Args ipythonFlag = flagReq ["ipython", "i"] (store IPythonFrom) "<path>" "Executable for IPython." universalFlags :: [Flag Args] universalFlags = [ flagReq ["extension","e", "X"] (store Extension) "<ghc-extension>" "Extension to enable at start.", flagReq ["conf","c"] (store ConfFile) "<file.hs>" "File with commands to execute at start.", flagHelpSimple (add Help) ] where add flag (Args mode flags) = Args mode $ flag : flags store :: (String -> Argument) -> String -> Args -> Either String Args store constructor str (Args mode prev) = Right $ Args mode $ constructor str : prev notebook :: Mode Args notebook = mode "notebook" (Args Notebook []) "Browser-based notebook interface." noArgs $ flagReq ["ip"] (store IPythonIP) "<address>" "Set the kernel's IP address.": flagReq ["port"] (store IPythonPort) "<port>" "Port on which to serve the notebook.": flagReq ["serve","s"] (store ServeFrom) "<dir>" "Directory to serve notebooks from.": ipythonFlag: universalFlags console :: Mode Args console = mode "console" (Args Console []) "Console-based interactive repl." noArgs $ ipythonFlag:universalFlags kernel :: Mode Args kernel = mode "kernel" (Args (Kernel Nothing) []) "Invoke the IHaskell kernel." kernelArg [] where kernelArg = flagArg update "<json-kernel-file>" update filename (Args _ flags) = Right $ Args (Kernel $ Just filename) flags convert :: Mode Args convert = mode "convert" (Args ConvertLhs []) description unnamedArg convertFlags where description = "Convert between Literate Haskell (*.lhs) and Ipython notebooks (*.ipynb)." convertFlags = universalFlags ++ [ flagReq ["input","i"] (store ConvertFrom) "<file>" "File to read." , flagReq ["output","o"] (store ConvertTo) "<file>" "File to write." , flagReq ["from","f"] (storeFormat ConvertFromFormat) "lhs|ipynb" "Format of the file to read." , flagReq ["to","t"] (storeFormat ConvertToFormat) "lhs|ipynb" "Format of the file to write." , flagNone ["force"] consForce "Overwrite existing files with output." , flagReq ["style","s"] storeLhs "bird|tex" "Type of markup used for the literate haskell file" , flagNone ["bird"] (consStyle lhsStyleBird) "Literate haskell uses >" , flagNone ["tex"] (consStyle lhsStyleTex ) "Literate haskell uses \\begin{code}" ] consForce (Args mode prev) = Args mode (OverwriteFiles : prev) unnamedArg = Arg (store ConvertFrom) "<file>" False consStyle style (Args mode prev) = Args mode (ConvertLhsStyle style : prev) storeFormat constructor str (Args mode prev) = case toLower str of "lhs" -> Right $ Args mode $ constructor LhsMarkdown : prev "ipynb" -> Right $ Args mode $ constructor IpynbFile : prev _ -> Left $ "Unknown format requested: " ++ str storeLhs str previousArgs = case toLower str of "bird" -> success lhsStyleBird "tex" -> success lhsStyleTex _ -> Left $ "Unknown lhs style: " ++ str where success lhsStyle = Right $ consStyle lhsStyle previousArgs lhsStyleBird, lhsStyleTex :: LhsStyle String lhsStyleBird = LhsStyle "> " "\n<< " "" "" "" "" lhsStyleTex = LhsStyle "" "" "\\begin{code}" "\\end{code}" "\\begin{verbatim}" "\\end{verbatim}" view :: Mode Args view = let empty = mode "view" (Args (View Nothing Nothing) []) "View IHaskell notebook." noArgs flags in empty { modeNames = ["view"], modeCheck = \a@(Args (View fmt file) _) -> if not (isJust fmt && isJust file) then Left "Syntax: IHaskell view <format> <name>[.ipynb]" else Right a, modeHelp = concat [ "Convert an IHaskell notebook to another format.\n", "Notebooks are searched in the IHaskell directory and the current directory.\n", "Available formats are " ++ intercalate ", " (map show ["pdf", "html", "ipynb", "markdown", "latex"]), "." ], modeArgs = ([formatArg, filenameArg] ++ fst (modeArgs empty), snd $ modeArgs empty) } where flags = [ipythonFlag, flagHelpSimple (add Help)] formatArg = flagArg updateFmt "<format>" filenameArg = flagArg updateFile "<name>[.ipynb]" updateFmt fmtStr (Args (View _ s) flags) = case readMay fmtStr of Just fmt -> Right $ Args (View (Just fmt) s) flags Nothing -> Left $ "Invalid format '" ++ fmtStr ++ "'." updateFile name (Args (View f _) flags) = Right $ Args (View f (Just name)) flags add flag (Args mode flags) = Args mode $ flag : flags ihaskellArgs :: Mode Args ihaskellArgs = let descr = "Haskell for Interactive Computing." helpStr = showText (Wrap 100) $ helpText [] HelpFormatAll ihaskellArgs onlyHelp = [flagHelpSimple (add Help)] noMode = mode "IHaskell" (Args (ShowHelp helpStr) []) descr noArgs onlyHelp in noMode { modeGroupModes = toGroup allModes } where add flag (Args mode flags) = Args mode $ flag : flags noArgs = flagArg unexpected "" where unexpected a = error $ "Unexpected argument: " ++ a
aostiles/LiveHaskell
src/IHaskell/Flags.hs
mit
8,216
0
16
1,908
2,180
1,152
1,028
160
5
{-# LANGUAGE RecordWildCards #-} module Language.Plover.Compile ( writeProgram , generateLib , generateMain , testWithGcc , printExpr , printType , runM ) where import Control.Monad.Trans.Either import Control.Monad.State import Data.Char import System.Process import Language.Plover.Types import Language.Plover.Reduce import Language.Plover.Print import Language.Plover.Macros (externs, seqList) runM :: M a -> (Either Error a, Context) runM m = runState (runEitherT m) initialState wrapExterns :: M CExpr -> M CExpr wrapExterns e = do e' <- e return (externs :> e') compileProgram :: [String] -> M CExpr -> Either Error String compileProgram includes expr = do expr' <- fst . runM $ compile =<< wrapExterns expr program <- flatten expr' return $ ppProgram $ Block (map Include includes ++ [program]) printFailure :: String -> IO () printFailure err = putStrLn (err ++ "\nCOMPILATION FAILED") printOutput :: Either String String -> IO () printOutput mp = case mp of Left err -> printFailure err Right p -> do putStrLn p printExpr :: CExpr -> IO () printExpr expr = printOutput (compileProgram [] (return expr)) printType :: CExpr -> IO () printType expr = printOutput (fmap show $ fst $ runM $ typeCheck expr) writeProgram :: FilePath -> [String] -> M CExpr -> IO () writeProgram fn includes expr = let mp = compileProgram includes expr in case mp of Left err -> printFailure err Right p -> do putStrLn p writeFile fn p data TestingError = CompileError String | GCCError String deriving (Eq) instance Show TestingError where show (GCCError str) = "gcc error:\n" ++ str show (CompileError str) = "rewrite compiler error:\n" ++ str execGcc :: FilePath -> IO (Maybe String) execGcc fp = do out <- readProcess "gcc" [fp, "-w"] "" case out of "" -> return Nothing _ -> return $ Just out -- See test/Main.hs for primary tests testWithGcc :: M CExpr -> IO (Maybe TestingError) testWithGcc expr = case compileProgram ["extern_defs.c"] expr of Left err -> return $ Just (CompileError err) Right p -> do let fp = "testing/compiler_output.c" writeFile fp p code <- execGcc fp case code of Nothing -> return $ Nothing Just output -> return $ Just (GCCError output) -- Wrap header file in guards to prevent inclusion loops headerGuards :: String -> String -> String headerGuards name body = unlines [ "#ifndef " ++ headerName , "#define " ++ headerName , "" , body , "" , "#endif /* " ++ headerName ++ " */" ] where uName = map toUpper name headerName = "PLOVER_GENERATED_" ++ uName ++ "_H" -- Generates .h and .c file as text generateLib :: CompilationUnit -> Either Error (String, String) generateLib CU{..} = let (decls, defs) = unzip $ map splitDef sourceDefs headerTerm = seqList headerDefs cfileExpr = Extension headerTerm :> seqList defs forwardDecls = ppProgram (Block decls) in do cfile <- compileProgram sourceIncs (return cfileExpr) header <- compileProgram headerIncs (return headerTerm) return (headerGuards unitName (header ++ forwardDecls), cfile) where splitDef (name, fntype, def) = (ForwardDecl name fntype, FunctionDef name fntype def) -- Generates .h and .c file and writes them to given filepaths generateMain :: FilePath -> FilePath -> CompilationUnit -> IO () generateMain hdir cdir cu = case generateLib cu of Right (hout, cout) -> do let hfile = hdir ++ "/" ++ unitName cu ++ ".h" let cfile = cdir ++ "/" ++ unitName cu ++ ".c" writeFile hfile hout putStrLn $ "generated file " ++ show hfile writeFile cfile cout putStrLn $ "generated file " ++ show cfile Left err -> putStrLn $ "error: " ++ err
imh/plover
src/Language/Plover/Compile.hs
mit
3,780
0
16
846
1,265
626
639
103
3
import B main = interact (printWavefront.read)
ducis/haskell-wavefront-parser
printWavefront.hs
mit
49
0
7
8
17
9
8
2
1
{-| Module : Control.Monad.Bayes.Prior Description : Probability monad that ignores conditioning Copyright : (c) Adam Scibior, 2016 License : MIT Maintainer : ams240@cam.ac.uk Stability : experimental Portability : GHC -} module Control.Monad.Bayes.Prior ( Prior, prior, hoist ) where import Control.Monad.Trans import Control.Monad.Trans.Identity import Control.Monad.Bayes.Class -- | A simple wrapper around 'MonadDist' types that discards conditoning. newtype Prior m a = Prior {runPrior :: IdentityT m a} deriving(Functor, Applicative, Monad, MonadTrans, MonadIO) type instance CustomReal (Prior m) = CustomReal m instance MonadDist m => MonadDist (Prior m) where primitive = lift . primitive instance MonadDist m => MonadBayes (Prior m) where factor _ = return () -- | Discard conditioning and just use the prior. prior :: Prior m a -> m a prior = runIdentityT . runPrior -- | Apply a transformation to the inner monad. hoist :: (forall x. m x -> n x) -> Prior m a -> Prior n a hoist f = Prior . IdentityT . f . runIdentityT . runPrior
ocramz/monad-bayes
src/Control/Monad/Bayes/Prior.hs
mit
1,101
0
9
225
260
142
118
-1
-1
{-# htermination elemIndices :: Eq a => a -> [a] -> [Int] #-} import List
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/List_elemIndices_2.hs
mit
74
0
3
15
5
3
2
1
0
module Main (main) where import Control.Monad (when) import qualified Data.List as List import System.Directory import System.FilePath main :: IO () main = do cwd <- getCurrentDirectory rootDir <- findRootDir cwd putStrLn $ "Root dir: " ++ rootDir mkReplModules (rootDir </> "base-compat") ["Repl"] mkReplModules (rootDir </> "base-compat-batteries") ["Repl", "Batteries"] -- Go up until there is 'cabal.project' findRootDir :: FilePath -> IO FilePath findRootDir fp | isDrive fp = return fp | otherwise = do exists <- doesFileExist $ fp </> "cabal.project" if exists then return fp else findRootDir (takeDirectory fp) mkReplModules :: FilePath -> [String] -> IO () mkReplModules dir suffixes = do preprocessPathRecursive mkReplModule (dir </> "src") where mkReplModule :: FilePath -> IO () mkReplModule entry = when (takeFileName entry == "Compat.hs") $ do let parentDir = takeDirectory entry sepStr = [pathSeparator] Just modPrefix = List.stripPrefix (dir </> "src" ++ sepStr) parentDir modName = replace sepStr "." modPrefix <.> "Compat" replFileName = parentDir </> "Compat" </> List.intercalate sepStr suffixes <.> "hs" replFileDir = takeDirectory replFileName createDirectoryIfMissing True replFileDir writeFile replFileName $ fileTemplate modName suffixes fileTemplate :: String -> [String] -> String fileTemplate modName suffixes = unlines [ "{-# LANGUAGE PackageImports #-}" , "{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}" , "-- | Reexports \"" ++ modName ++ "\"" , "-- from a globally unique namespace." , "module " ++ modName ++ "." ++ List.intercalate "." suffixes ++ " (" , " module " ++ modName , ") where" , "import \"this\" " ++ modName ] -- | Replace a subsequence everywhere it occurs. The first argument must -- not be the empty list. -- -- Taken from the @extra@ library. replace :: Eq a => [a] -> [a] -> [a] -> [a] replace [] _ _ = error "replace: first argument cannot be empty" replace from to xs | Just xs <- List.stripPrefix from xs = to ++ replace from to xs replace from to (x:xs) = x : replace from to xs replace from to [] = [] -- | Traverse the directory tree in preorder. -- -- Taken from the @directory@ test suite. preprocessPathRecursive :: (FilePath -> IO ()) -> FilePath -> IO () preprocessPathRecursive f path = do dirExists <- doesDirectoryExist path if dirExists then do f path names <- listDirectory path mapM_ (preprocessPathRecursive f) (fmap (path </>) names) else f path
haskell-compat/base-compat
mk-repl-modules/MkReplModules.hs
mit
2,741
0
16
684
751
377
374
60
2
module Main where -- import Haq import Test.Hspec main :: IO () main = hspec $ do describe "Validate haqify function" $ do it "haqify is supposed to prefix Haq! to things" $ do True `shouldBe` True
akimichi/functionaljs
src/test/haskell/HSpecTests.hs
mit
224
0
14
63
58
30
28
7
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.ValidityState ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.ValidityState #else module Graphics.UI.Gtk.WebKit.DOM.ValidityState #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.ValidityState #else import Graphics.UI.Gtk.WebKit.DOM.ValidityState #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/ValidityState.hs
mit
450
0
5
39
33
26
7
4
0
{-| Module : Types Description : Simple module defining basic types License : MIT Maintainer : jester.nf@gmail.com Stability : stable Portability : portable -} module Types( LispVal(..), unwordsList, Env, LispError(..), ThrowsError, IOThrowsError, liftThrows, runIOThrows ) where import Control.Monad.Error() import Data.IORef import Text.ParserCombinators.Parsec (ParseError) import Control.Monad.Error import System.IO (Handle) -- |Represents an error occured during the evaluation of a Lisp expression data LispError = NumArgs Integer [LispVal] -- ^ Wrong number of arguments | TypeMismatch String LispVal -- ^ Wrong type | Parser ParseError -- ^ Parser error | BadSpecialForm String LispVal | NotFunction String String -- ^ Function was expected | UnboundVar String String -- ^ Unknown variable | Default String -- ^ Any other error message instance Show LispError where show = showError instance Error LispError where noMsg = Default "An unknown error has occurred..." strMsg = Default -- |Partially applied 'Either' monad, with 'LispError' as first argument type ThrowsError = Either LispError -- |Shows the error as string showError :: LispError -> String showError (UnboundVar message varname) = message ++ ": " ++ varname showError (BadSpecialForm message form) = message ++ ": " ++ show form showError (NotFunction message func) = message ++ ": " ++ show func showError (NumArgs expected found) = "Expected " ++ show expected ++ " args; found values " ++ unwordsList found showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found showError (Parser parseErr) = "Parse error at " ++ show parseErr showError (Default err) = err -- |Takes any error value and converts it to it's 'String' representation trapError :: (Show e, MonadError e m) => m String -> m String trapError action = catchError action $ return . show -- |Extracts the value wrapped in 'Right' extractValue :: ThrowsError a -> a extractValue (Right x) = x type IOThrowsError = ErrorT LispError IO liftThrows :: ThrowsError a -> IOThrowsError a liftThrows (Left err) = throwError err liftThrows (Right val) = return val runIOThrows :: IOThrowsError String -> IO String runIOThrows action = runErrorT (trapError action) >>= return . extractValue -- |Represents a Lisp value data LispVal = Atom String | List [LispVal] | DottedList [LispVal] LispVal | Number Integer | String String | Bool Bool | PrimitiveFunc ([LispVal] -> ThrowsError LispVal) | Func { parameters :: [String], vararg :: (Maybe String), body :: [LispVal], closue :: Env } | IOFunc ([LispVal] -> IOThrowsError LispVal) | Port Handle instance Show LispVal where show = showVal -- |Returns the 'LispVal' as 'String' showVal :: LispVal -> String showVal (String contents) = "\"" ++ contents ++ "\"" showVal (Atom name) = name showVal (Number contents) = show contents showVal (Bool True) = "#t" showVal (Bool False) = "#f" showVal (List contents) = "(" ++ unwordsList contents ++ ")" showVal (DottedList h t) = "(" ++ unwordsList h ++ " . " ++ showVal t ++ ")" showVal (PrimitiveFunc _) = "<primitive>" showVal (Func ps v _ _) = "(lambda (" ++ unwords (map show ps) ++ (case v of Nothing -> "" Just val -> " . " ++ val) ++ ")" showVal (Port _) = "<IO port>" showVal (IOFunc _) = "<IO primitive>" -- |Prints every 'LispVal', and concatenates it to a 'String' unwordsList :: [LispVal] -> String unwordsList = unwords . map showVal -- |Represents an Environment which stores the lisp variables type Env = IORef [(String, IORef LispVal)]
nagyf/wyas
src/Types.hs
mit
3,873
0
11
921
1,000
534
466
81
2
module Q12 where import Q11 decodeModified :: (Eq a) => [Entry a] -> [a] decodeModified x = let expand :: (Eq a) => (Entry a) -> [a] expand (Single x) = [x] expand (Multiple 0 x) = [] expand (Multiple c x) = x:(expand (Multiple (c-1) x)) in foldr (++) [] $ map expand x
cshung/MiscLab
Haskell99/q12.hs
mit
297
0
15
82
169
89
80
10
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module ZoomHub.Types.ContentBaseURI ( ContentBaseURI, unContentBaseURI, mkContentBaseURI, ) where import Data.Aeson (ToJSON, object, toJSON, (.=)) import Data.List (isSuffixOf) import Network.URI (URI, uriIsAbsolute, uriPath) newtype ContentBaseURI = ContentBaseURI {unContentBaseURI :: URI} deriving (Eq) instance ToJSON ContentBaseURI where toJSON ContentBaseURI {..} = object [ "unContentBaseURI" .= show unContentBaseURI ] mkContentBaseURI :: URI -> Maybe ContentBaseURI mkContentBaseURI uri | uriIsAbsolute uri = pure $ ContentBaseURI $ ensureTrailingSlash uri | otherwise = Nothing where ensureTrailingSlash url = let path = uriPath url in if path == "" || "/" `isSuffixOf` path then url else url {uriPath = path <> "/"}
zoomhub/zoomhub
src/ZoomHub/Types/ContentBaseURI.hs
mit
877
0
12
185
230
128
102
23
2
module Demi.Parser where --import Text.Show.Functions import qualified Data.Map.Strict as Map type VarMap = Map.Map String VariableValue data StdFn = Fn (VarMap -> [VariableValue] -> IO VarMap) identity :: VarMap -> [VariableValue] -> IO VarMap identity v _ = return v instance Show StdFn where show (Fn _) = show "<std>" instance Read StdFn where readsPrec _ _ = [(Fn identity, "<std>")] type Callable = Either StdFn Statement data VariableValue = IntVar Integer | DblVar Double | StrVar String | BoolVar Bool | FnVar [String] VarMap Callable | Nil deriving (Show, Read) data BinaryOperator = Add | Subtract | Multiply | Divide | And | Or | GreaterThan | LesserThan | GreaterEqualThan | LesserEqualThan | EqualTo | NotEqualTo deriving (Show, Read) data UnaryOperator = Negative | Not deriving (Show, Read) data Expression = Var String | IntConst Integer | DblConst Double | StrConst String | BoolConst Bool | NilConst | FnConst [String] Statement | UnaryExpression UnaryOperator Expression | BinaryExpression BinaryOperator Expression Expression | CallExpression Expression [Expression] deriving (Show, Read) data Statement = Sequence [Statement] | Assign String Expression | When Expression Statement Statement | While Expression Statement | Skip | Bare Expression | Import String String | ImportLib String deriving (Show, Read)
oakfang/DemiLang
src/Demi/Parser.hs
mit
2,037
0
10
907
420
240
180
54
1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE Arrows #-} module Document.Pipeline where -- Modules import Document.Phase.Parameters import Latex.Parser as P import Logic.Names import Logic.Expr import UnitB.Syntax -- Libraries import Control.Applicative import Control.Arrow hiding (left) import qualified Control.Category as C import Control.Lens import Control.Monad.Fix import Control.Monad.RWS import Control.Monad.Trans.Maybe import Control.Monad.Writer import Data.DList (DList) import qualified Data.DList as D import Data.Hashable import Data.List as L import qualified Data.Map as M import Data.String import Data.Tuple.Generics import GHC.Generics.Instances import Text.Printf.TH import Utilities.Syntactic newtype MM' a b = MM (MaybeT (RWS a [Error] ()) b) deriving ( Functor,Applicative,MonadPlus , MonadWriter [Error],MonadReader a , Alternative, MonadFix ) type MM = MM' Input instance Monad (MM' a) where {-# INLINE (>>=) #-} MM x >>= f = MM $ x >>= run . f where run (MM x) = x data DocSpec = DocSpec { getEnvSpec :: M.Map String ArgumentSpec , getCommandSpec :: M.Map String ArgumentSpec } data ArgumentSpec = forall a. IsTuple LatexArg a => ArgumentSpec Int (Proxy a) type Input = InputRaw InputMap type InputBuilder = InputRaw InputMapBuilder data InputRaw f = Input { getMachineInput :: M.Map MachineId (DocBlocksRaw f) , getContextInput :: M.Map ContextId (DocBlocksRaw f) } deriving Show convertInput :: InputBuilder -> Input convertInput (Input mch ctx) = Input (M.map convertBlocks mch) (M.map convertBlocks ctx) newtype ContextId = CId { getCId :: String } deriving (Eq,Ord,Hashable) instance IsLabel ContextId where as_label (CId x) = label x instance Show ContextId where show = getCId instance IsString ContextId where fromString = CId liftEither :: Either [Error] a -> MM' c a liftEither (Left xs) = MM $ tell xs >> mzero liftEither (Right r) = return r argCount :: ArgumentSpec -> Int argCount (ArgumentSpec n _) = n {-# INLINE runMM #-} runMM :: MM' a b -> a -> Either [Error] b runMM (MM cmd) input = case r of Nothing -> Left es Just x | L.null es -> Right x | otherwise -> Left es where (r,(),es) = runRWS (runMaybeT cmd) input () empty_spec :: DocSpec empty_spec = DocSpec M.empty M.empty instance Monoid DocSpec where mappend (DocSpec xs0 ys0) (DocSpec xs1 ys1) = DocSpec (xs0 `unionM` xs1) (ys0 `unionM` ys1) where unionM = M.unionWithKey (\k _ -> error $ "command name clash: " ++ k) mempty = empty_spec data Pipeline m a b = Pipeline DocSpec DocSpec (a -> m b) instance Monad m => C.Category (Pipeline m) where id = Pipeline empty_spec empty_spec return {-# INLINE (.) #-} Pipeline xs0 xs1 f . Pipeline ys0 ys1 g = Pipeline (xs0 `mappend` ys0) (xs1 `mappend` ys1) $ (>>= f) . g instance Monad m => Arrow (Pipeline m) where {-# INLINE arr #-} arr f = Pipeline empty_spec empty_spec $ return . f {-# INLINE first #-} first (Pipeline xs ys f) = Pipeline xs ys $ \(x,y) -> f x >>= \z -> return (z,y) instance Monad m => ArrowApply (Pipeline m) where app = Pipeline empty_spec empty_spec $ \(Pipeline _ _ f, x) -> f x data Env = BlockEnv { getEnvArgs :: ([LatexDoc],LineInfo) , getEnvContent :: LatexDoc , envLI :: LineInfo } deriving (Show) data Cmd = BlockCmd { getCmdArgs :: ([LatexDoc],LineInfo) , cmdLI :: LineInfo } deriving (Show) type DocBlocks = DocBlocksRaw InputMap type DocBlocksBuilder = DocBlocksRaw InputMapBuilder newtype InputMap a = InputMap { getInputMap :: M.Map String [a] } newtype InputMapBuilder a = InputMapBuilder { getInputMapBuilder :: DList (String,DList a) } data DocBlocksRaw f = DocBlocks { getEnv :: OnFunctor f Env , getCmd :: OnFunctor f Cmd } deriving (Show) instance Monoid1 InputMapBuilder where mempty1 = InputMapBuilder mempty mconcat1 = InputMapBuilder . mconcat1 . L.map getInputMapBuilder mappend1 (InputMapBuilder x) (InputMapBuilder y) = InputMapBuilder $ x `mappend` y buildInputMap :: InputMapBuilder a -> InputMap a buildInputMap (InputMapBuilder xs) = InputMap $ M.map D.toList $ M.fromListWith (<>) $ D.toList xs convertBlocks :: DocBlocksBuilder -> DocBlocks convertBlocks (DocBlocks env cmd) = DocBlocks (env & _Wrapped %~ buildInputMap) (cmd & _Wrapped %~ buildInputMap) instance Monoid1 f => Monoid (DocBlocksRaw f) where mempty = DocBlocks mempty mempty mappend (DocBlocks xs0 xs1) (DocBlocks ys0 ys1) = DocBlocks (xs0 <> ys0) (xs1 <> ys1) machine_spec :: Pipeline m a b -> DocSpec machine_spec (Pipeline m _ _) = m context_spec :: Pipeline m a b -> DocSpec context_spec (Pipeline _ c _) = c item :: String -> a -> OnFunctor InputMapBuilder a item n x = OnFunctor $ InputMapBuilder $ pure (n,pure x) getLatexBlocks :: DocSpec -> LatexDoc -> DocBlocksBuilder getLatexBlocks (DocSpec envs cmds) xs = execWriter (f $ unconsTex xs) where f :: Maybe (LatexNode,LatexDoc) -> Writer DocBlocksBuilder () f (Just ((EnvNode (Env _ name li ys _),xs))) = do case name `M.lookup` envs of Just nargs -> do let (args,rest) = brackets (argCount nargs) ys li' = line_info rest tell (DocBlocks (item name $ BlockEnv (args,li') rest li) mempty) Nothing -> f $ unconsTex ys f $ unconsTex xs f (Just ((BracketNode (Bracket _ _ ys _),xs))) = do f $ unconsTex ys f $ unconsTex xs f (Just (Text (Command name li),xs)) = do case argCount <$> name `M.lookup` cmds of Just nargs | nargs == 0 -> do tell (DocBlocks mempty (item name $ BlockCmd ([],li) li)) f $ unconsTex xs | otherwise -> do let (args,rest) = brackets nargs xs li' = line_info rest tell (DocBlocks mempty (item name $ BlockCmd (args,li') li)) f $ unconsTex rest Nothing -> f $ unconsTex xs f (Just (Text _,xs)) = f $ unconsTex xs f Nothing = return () brackets :: Int -> LatexDoc -> ([LatexDoc],LatexDoc) brackets 0 xs = ([],xs) brackets n doc = case unconsTex doc of Just ((BracketNode (Bracket Curly _ ys _),xs)) -> (ys:args,r) where (args,r) = brackets (n-1) xs Just (Text (Blank _ _),ys) -> brackets n ys _ -> ([],doc) {-# INLINE withInput #-} withInput :: Pipeline MM Input b -> Pipeline MM a b withInput (Pipeline s0 s1 f) = Pipeline s0 s1 $ \_ -> ask >>= f isBlank :: LatexToken -> Bool isBlank (Blank _ _) = True isBlank _ = False {-# INLINE runPipeline' #-} runPipeline' :: M.Map Name [LatexDoc] -> M.Map String [LatexDoc] -> a -> Pipeline MM a b -> Either [Error] b runPipeline' ms cs arg p = runMM (f arg) input where input = Input (M.map convertBlocks mch) (M.map convertBlocks ctx) mch = M.mapKeys MId $ M.map (mconcat . map (getLatexBlocks m_spec)) ms ctx = M.mapKeys CId $ M.map (mconcat . map (getLatexBlocks c_spec)) cs Pipeline m_spec c_spec f = p latexArgProxy :: Proxy LatexArg latexArgProxy = Proxy machineSyntax :: Pipeline m a b -> [String] machineSyntax (Pipeline mch _ _) = M.foldMapWithKey cmd (getCommandSpec mch) ++ M.foldMapWithKey env (getEnvSpec mch) where argument p = [s|{%s}|] (argKind p) cmd x (ArgumentSpec _ xs) = [x ++ foldMapTupleType latexArgProxy argument xs] env x (ArgumentSpec _ xs) = [[s|\\begin{%s}%s .. \\end{%s}|] x (foldMapTupleType latexArgProxy argument xs :: String) x]
literate-unitb/literate-unitb
src/Document/Pipeline.hs
mit
8,595
0
22
2,690
2,913
1,526
1,387
-1
-1
{-# LANGUAGE PatternGuards, ExistentialQuantification, DeriveDataTypeable, Rank2Types, FlexibleContexts, FlexibleInstances, TemplateHaskell #-} -- Copyright (c) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons -- Copyright (c) 2007-8 JP Bernardy -- | 'Buffer' implementation, wrapping Rope module Yi.Buffer.Implementation ( UIUpdate (..) , Update (..) , updateIsDelete , Point , Mark, MarkValue(..) , Size , Direction (..) , BufferImpl , Overlay, OvlLayer (..) , mkOverlay , overlayUpdate , applyUpdateI , isValidUpdate , reverseUpdateI , nelemsBI , sizeBI , newBI , solPoint , solPoint' , charsFromSolBI , regexRegionBI , getMarkDefaultPosBI , modifyMarkBI , getMarkValueBI , getMarkBI , newMarkBI , deleteMarkValueBI , setSyntaxBI , addOverlayBI , delOverlayBI , delOverlayLayer , updateSyntax , getAst, focusAst , strokesRangesBI , getStream , getIndexedStream , lineAt , SearchExp ) where import Control.Monad import Data.Array import Data.Binary import Data.Rope (Rope) import Data.DeriveTH import Data.Derive.Binary import Data.List (groupBy, zip, takeWhile) import Data.Maybe import Data.Monoid import Data.Typeable import Prelude (takeWhile, dropWhile, map, filter) import Yi.Buffer.Basic import Yi.Prelude import Yi.Regex import Yi.Region import Yi.Style import Yi.Syntax import qualified Data.Rope as F import qualified Data.Map as M import qualified Data.Set as Set data MarkValue = MarkValue {markPoint :: !Point, markGravity :: !Direction} deriving (Ord, Eq, Show, Typeable) $(derive makeBinary ''MarkValue) type Marks = M.Map Mark MarkValue data HLState syntax = forall cache. HLState !(Highlighter cache syntax) !cache data OvlLayer = UserLayer | HintLayer deriving (Ord, Eq) data Overlay = Overlay { overlayLayer :: OvlLayer, overlayBegin :: MarkValue, overlayEnd :: MarkValue, overlayStyle :: StyleName } instance Eq Overlay where Overlay a b c _ == Overlay a' b' c' _ = a == a' && b == b' && c == c' instance Ord Overlay where compare (Overlay a b c _) (Overlay a' b' c' _) = compare a a' `mappend` compare b b' `mappend` compare c c' data BufferImpl syntax = FBufferData { mem :: !Rope -- ^ buffer text , marks :: !Marks -- ^ Marks for this buffer , markNames :: !(M.Map String Mark) , hlCache :: !(HLState syntax) -- ^ syntax highlighting state , overlays :: !(Set.Set Overlay) -- ^ set of (non overlapping) visual overlay regions , dirtyOffset :: !Point -- ^ Lowest modified offset since last recomputation of syntax } deriving Typeable dummyHlState :: HLState syntax dummyHlState = (HLState noHighlighter (hlStartState noHighlighter)) -- Atm we can't store overlays because stylenames are functions (can't be serialized) -- TODO: ideally I'd like to get rid of overlays entirely; although we could imagine them storing mere styles. instance Binary (BufferImpl ()) where put b = put (mem b) >> put (marks b) >> put (markNames b) get = pure FBufferData <*> get <*> get <*> get <*> pure dummyHlState <*> pure Set.empty <*> pure 0 -- | Mutation actions (also used the undo or redo list) -- -- For the undo/redo, we use the /partial checkpoint/ (Berlage, pg16) strategy to store -- just the components of the state that change. -- -- Note that the update direction is only a hint for moving the cursor -- (mainly for undo purposes); the insertions and deletions are always -- applied Forward. data Update = Insert {updatePoint :: !Point, updateDirection :: !Direction, insertUpdateString :: !Rope} | Delete {updatePoint :: !Point, updateDirection :: !Direction, deleteUpdateString :: !Rope} -- Note that keeping the text does not cost much: we keep the updates in the undo list; -- if it's a "Delete" it means we have just inserted the text in the buffer, so the update shares -- the data with the buffer. If it's an "Insert" we have to keep the data any way. deriving (Show, Typeable) $(derive makeBinary ''Update) updateIsDelete :: Update -> Bool updateIsDelete Delete {} = True updateIsDelete Insert {} = False updateString :: Update -> Rope updateString (Insert _ _ s) = s updateString (Delete _ _ s) = s updateSize :: Update -> Size updateSize = Size . fromIntegral . F.length . updateString data UIUpdate = TextUpdate !Update | StyleUpdate !Point !Size $(derive makeBinary ''UIUpdate) -------------------------------------------------- -- Low-level primitives. -- | New FBuffer filled from string. newBI :: Rope -> BufferImpl () newBI s = FBufferData s M.empty M.empty dummyHlState Set.empty 0 -- | read @n@ bytes from buffer @b@, starting at @i@ readChunk :: Rope -> Size -> Point -> Rope readChunk p (Size n) (Point i) = F.take n $ F.drop i $ p -- | Write string into buffer. insertChars :: Rope -> Rope -> Point -> Rope insertChars p cs (Point i) = left `F.append` cs `F.append` right where (left,right) = F.splitAt i p {-# INLINE insertChars #-} -- | Write string into buffer. deleteChars :: Rope -> Point -> Size -> Rope deleteChars p (Point i) (Size n) = left `F.append` right where (left,rest) = F.splitAt i p right = F.drop n rest {-# INLINE deleteChars #-} ------------------------------------------------------------------------ -- Mid-level insert/delete -- | Shift a mark position, supposing an update at a given point, by a given amount. -- Negative amount represent deletions. shiftMarkValue :: Point -> Size -> MarkValue -> MarkValue shiftMarkValue from by (MarkValue p gravity) = MarkValue shifted gravity where shifted | p < from = p | p == from = case gravity of Backward -> p Forward -> p' | otherwise {- p > from -} = p' where p' = max from (p +~ by) mapOvlMarks :: (MarkValue -> MarkValue) -> Overlay -> Overlay mapOvlMarks f (Overlay l s e v) = Overlay l (f s) (f e) v ------------------------------------- -- * "high-level" (exported) operations -- | Point of EOF sizeBI :: BufferImpl syntax -> Point sizeBI = Point . F.length . mem -- | Return @n@ Chars starting at @i@ of the buffer as a list nelemsBI :: Int -> Point -> BufferImpl syntax -> String nelemsBI n i fb = F.toString $ readChunk (mem fb) (Size n) i getStream :: Direction -> Point -> BufferImpl syntax -> Rope getStream Forward (Point i) fb = F.drop i $ mem $ fb getStream Backward (Point i) fb = F.reverse $ F.take i $ mem $ fb getIndexedStream :: Direction -> Point -> BufferImpl syntax -> [(Point,Char)] getIndexedStream Forward (Point p) fb = zip [Point p..] $ F.toString $ F.drop p $ mem $ fb getIndexedStream Backward (Point p) fb = zip (dF (pred (Point p))) $ F.toReverseString $ F.take p $ mem $ fb where dF n = n : dF (pred n) -- | Create an "overlay" for the style @sty@ between points @s@ and @e@ mkOverlay :: OvlLayer -> Region -> StyleName -> Overlay mkOverlay l r = Overlay l (MarkValue (regionStart r) Backward) (MarkValue (regionEnd r) Forward) -- | Obtain a style-update for a specific overlay overlayUpdate :: Overlay -> UIUpdate overlayUpdate (Overlay _l (MarkValue s _) (MarkValue e _) _) = StyleUpdate s (e ~- s) -- | Add a style "overlay" between the given points. addOverlayBI :: Overlay -> BufferImpl syntax -> BufferImpl syntax addOverlayBI ov fb = fb{overlays = Set.insert ov (overlays fb)} -- | Remove a previously added "overlay" delOverlayBI :: Overlay -> BufferImpl syntax -> BufferImpl syntax delOverlayBI ov fb = fb{overlays = Set.delete ov (overlays fb)} delOverlayLayer :: OvlLayer -> BufferImpl syntax -> BufferImpl syntax delOverlayLayer layer fb = fb{overlays = Set.filter ((/= layer) . overlayLayer) (overlays fb)} -- FIXME: this can be really inefficient. -- | Return style information for the range @(i,j)@ Style information -- is derived from syntax highlighting, active overlays and current regexp. The -- returned list contains tuples @(l,s,r)@ where every tuple is to -- be interpreted as apply the style @s@ from position @l@ to @r@ in -- the buffer. In each list, the strokes are guaranteed to be -- ordered and non-overlapping. The lists of strokes are ordered by -- decreasing priority: the 1st layer should be "painted" on top. strokesRangesBI :: (Point -> Point -> Point -> [Stroke]) -> Maybe SearchExp -> Region -> Point -> BufferImpl syntax -> [[Stroke]] strokesRangesBI getStrokes regex rgn point fb = result where i = regionStart rgn j = regionEnd rgn dropBefore = dropWhile (\s ->spanEnd s <= i) takeIn = takeWhile (\s -> spanBegin s <= j) groundLayer = [(Span i mempty j)] -- zero-length spans seem to break stroking in general, so filter them out! syntaxHlLayer = filter (\(Span b m a) -> b /= a) $ getStrokes point i j layers2 = map (map overlayStroke) $ groupBy ((==) `on` overlayLayer) $ Set.toList $ overlays fb layer3 = case regex of Just re -> takeIn $ map hintStroke $ regexRegionBI re (mkRegion i j) fb Nothing -> [] result = map (map clampStroke . takeIn . dropBefore) (layer3 : layers2 ++ [syntaxHlLayer, groundLayer]) overlayStroke (Overlay _ sm em a) = Span (markPoint sm) a (markPoint em) clampStroke (Span l x r) = Span (max i l) x (min j r) hintStroke r = Span (regionStart r) (if point `nearRegion` r then strongHintStyle else hintStyle) (regionEnd r) ------------------------------------------------------------------------ -- Point based editing -- | Checks if an Update is valid isValidUpdate :: Update -> BufferImpl syntax -> Bool isValidUpdate u b = case u of (Delete p _ _) -> check p && check (p +~ updateSize u) (Insert p _ _) -> check p where check (Point x) = x >= 0 && x <= F.length (mem b) -- | Apply a /valid/ update applyUpdateI :: Update -> BufferImpl syntax -> BufferImpl syntax applyUpdateI u fb = touchSyntax (updatePoint u) $ fb {mem = p', marks = M.map shift (marks fb), overlays = Set.map (mapOvlMarks shift) (overlays fb)} -- FIXME: this is inefficient; find a way to use mapMonotonic -- (problem is that marks can have different gravities) where (p', amount) = case u of Insert pnt _ cs -> (insertChars p cs pnt, sz) Delete pnt _ _ -> (deleteChars p pnt sz, negate sz) sz = updateSize u shift = shiftMarkValue (updatePoint u) amount p = mem fb -- FIXME: remove collapsed overlays -- | Reverse the given update reverseUpdateI :: Update -> Update reverseUpdateI (Delete p dir cs) = Insert p (reverseDir dir) cs reverseUpdateI (Insert p dir cs) = Delete p (reverseDir dir) cs ------------------------------------------------------------------------ -- Line based editing -- | Line at the given point. (Lines are indexed from 1) lineAt :: Point -> BufferImpl syntax -> Int lineAt (Point point) fb = 1 + (F.countNewLines $ F.take point (mem fb)) -- | Point that starts the given line (Lines are indexed from 1) solPoint :: Int -> BufferImpl syntax -> Point solPoint line fb = Point $ F.length $ fst $ F.splitAtLine (line - 1) (mem fb) -- | Get begin of the line relatively to @point@. solPoint' :: Point -> BufferImpl syntax -> Point solPoint' point fb = solPoint (lineAt point fb) fb charsFromSolBI :: Point -> BufferImpl syntax -> String charsFromSolBI pnt fb = nelemsBI (fromIntegral $ pnt - sol) sol fb where sol = solPoint' pnt fb -- | Return indices of all strings in buffer matching regex, inside the given region. regexRegionBI :: SearchExp -> Region -> forall syntax. BufferImpl syntax -> [Region] regexRegionBI se r fb = case dir of Forward -> fmap (fmapRegion addPoint . matchedRegion) $ matchAll' $ F.toString bufReg Backward -> fmap (fmapRegion subPoint . matchedRegion) $ matchAll' $ F.toReverseString bufReg where matchedRegion arr = let (off,len) = arr!0 in mkRegion (Point off) (Point (off+len)) addPoint (Point x) = Point (p + x) subPoint (Point x) = Point (q - x) matchAll' = matchAll (searchRegex dir se) dir = regionDirection r Point p = regionStart r Point q = regionEnd r Size s = regionSize r bufReg = F.take s $ F.drop p $ mem fb newMarkBI :: MarkValue -> BufferImpl syntax -> (BufferImpl syntax, Mark) newMarkBI initialValue fb = let maxId = fromMaybe 0 $ markId . fst . fst <$> M.maxViewWithKey (marks fb) newMark = Mark $ maxId + 1 fb' = fb { marks = M.insert newMark initialValue (marks fb)} in (fb', newMark) getMarkValueBI :: Mark -> BufferImpl syntax -> Maybe MarkValue getMarkValueBI m (FBufferData { marks = marksMap } ) = M.lookup m marksMap deleteMarkValueBI :: Mark -> BufferImpl syntax -> BufferImpl syntax deleteMarkValueBI m fb = fb { marks = M.delete m (marks fb) } getMarkBI :: String -> BufferImpl syntax -> Maybe Mark getMarkBI name FBufferData {markNames = nms} = M.lookup name nms -- | Modify a mark value. modifyMarkBI :: Mark -> (MarkValue -> MarkValue) -> (forall syntax. BufferImpl syntax -> BufferImpl syntax) modifyMarkBI m f fb = fb {marks = mapAdjust' f m (marks fb)} -- NOTE: we must insert the value strictly otherwise we can hold to whatever structure the value of the mark depends on. -- (often a whole buffer) setSyntaxBI :: ExtHL syntax -> BufferImpl oldSyntax -> BufferImpl syntax setSyntaxBI (ExtHL e) fb = touchSyntax 0 $ fb {hlCache = HLState e (hlStartState e)} touchSyntax :: Point -> BufferImpl syntax -> BufferImpl syntax touchSyntax touchedIndex fb = fb { dirtyOffset = min touchedIndex (dirtyOffset fb)} updateSyntax :: BufferImpl syntax -> BufferImpl syntax updateSyntax fb@FBufferData {dirtyOffset = touchedIndex, hlCache = HLState hl cache} | touchedIndex == maxBound = fb | otherwise = fb {dirtyOffset = maxBound, hlCache = HLState hl (hlRun hl getText touchedIndex cache) } where getText = Scanner 0 id (error "getText: no character beyond eof") (\idx -> getIndexedStream Forward idx fb) ------------------------------------------------------------------------ -- | Returns the requested mark, creating a new mark with that name (at the supplied position) if needed getMarkDefaultPosBI :: Maybe String -> Point -> BufferImpl syntax -> (BufferImpl syntax, Mark) getMarkDefaultPosBI name defaultPos fb@FBufferData {marks = mks, markNames = nms} = case flip M.lookup nms =<< name of Just m' -> (fb, m') Nothing -> let newMark = Mark (1 + max 1 (markId $ fst (M.findMax mks))) nms' = case name of Nothing -> nms Just nm -> M.insert nm newMark nms mks' = M.insert newMark (MarkValue defaultPos Forward) mks in (fb {marks = mks', markNames = nms'}, newMark) getAst :: Int -> BufferImpl syntax -> syntax getAst w b@FBufferData {hlCache = HLState s@(SynHL {hlGetTree = gt}) cache} = gt cache w focusAst :: M.Map Int Region -> BufferImpl syntax -> BufferImpl syntax focusAst r b@FBufferData {hlCache = HLState s@(SynHL {hlFocus = foc}) cache} = b {hlCache = HLState s (foc r cache)}
codemac/yi-editor
src/Yi/Buffer/Implementation.hs
gpl-2.0
15,756
0
21
3,858
4,427
2,322
2,105
285
3
{- pandoc-crossref is a pandoc filter for numbering figures, equations, tables and cross-references to them. Copyright (C) 2015 Nikolay Yakimov <root@livid.pp.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -} {-# LANGUAGE TemplateHaskellQuotes, OverloadedStrings #-} module ManData where import Language.Haskell.TH.Syntax import qualified Data.Text as T import qualified Data.Text.IO as T import System.IO import qualified Text.Pandoc as P import Control.DeepSeq import Data.String import Text.Pandoc.Highlighting (pygments) dataFile :: FilePath dataFile = "docs/index.md" readDataFile :: IO T.Text readDataFile = withFile dataFile ReadMode $ \h -> do hSetEncoding h utf8 cont <- T.replace "* TOC\n{:toc}\n" "" <$> T.hGetContents h return $!! cont embedManual :: (P.Pandoc -> P.PandocPure T.Text) -> Q Exp embedManual fmt = do qAddDependentFile dataFile d <- runIO readDataFile let pd = either (error . show) id $ P.runPure $ P.readMarkdown readerOpts d let txt = either (error . show) id $ P.runPure $ fmt pd strToExp $ T.unpack txt readerOpts :: P.ReaderOptions readerOpts = P.def{ P.readerExtensions = P.enableExtension P.Ext_yaml_metadata_block P.githubMarkdownExtensions , P.readerStandalone = True } embedManualText :: Q Exp embedManualText = embedManual $ P.writePlain P.def embedManualHtml :: Q Exp embedManualHtml = do tt <- fmap (either (error . show) id) . runIO . P.runIO $ P.compileDefaultTemplate "html5" embedManual $ P.writeHtml5String P.def{ P.writerTemplate = Just tt , P.writerHighlightStyle = Just pygments , P.writerTOCDepth = 6 , P.writerTableOfContents = True } strToExp :: String -> Q Exp strToExp s = return $ VarE 'fromString `AppE` LitE (StringL s)
lierdakil/pandoc-crossref
src/ManData.hs
gpl-2.0
2,392
0
15
422
498
260
238
-1
-1
-- | -- Module : Control.Concurrent.STM.TLQueue -- Copyright : 2013 kudah -- License : -- Maintainer : kudah <kudahkukarek@gmail.com> -- Stability : experimental -- Portability : stm >= 2.4 -- -- TQueue which keeps track of its length {-# OPTIONS_GHC -Wall #-} module Control.Concurrent.STM.TLQueue ( TLQueue , newTLQueue , readTLQueue , writeTLQueue , lengthTLQueue ) where import Prelude import Control.Concurrent.STM data TLQueue a = TLQueue {tq :: TQueue a ,ln :: TVar Int } newTLQueue :: STM (TLQueue a) newTLQueue = do x <- newTQueue y <- newTVar 0 return $ TLQueue x y readTLQueue :: TLQueue a -> STM a readTLQueue tlq = do modifyTVar' (ln tlq) (subtract 1) readTQueue $ tq tlq writeTLQueue :: TLQueue a -> a -> STM () writeTLQueue tlq a = do modifyTVar' (ln tlq) (+1) writeTQueue (tq tlq) a lengthTLQueue :: TLQueue a -> STM Int lengthTLQueue = do readTVar . ln
exbb2/BlastItWithPiss
src/Control/Concurrent/STM/TLQueue.hs
gpl-3.0
975
0
9
254
263
138
125
29
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} -- | Use of deriving strategies. -- -- See: -- - https://ryanglscott.github.io/2017/04/12/improvements-to-deriving-in-ghc-82/ -- - https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#default-deriving-strategy -- module Deriving.Strategies where newtype Foo a = MkFoo a deriving Show class Show a => Bar a where bar :: a -> String bar = show deriving newtype instance Bar a => Bar (Foo a) instance Bar Int
capitanbatata/sandbox
haskell-extensions/src/Deriving/Strategies.hs
gpl-3.0
625
0
7
112
88
51
37
11
0
{-# LANGUAGE OverloadedStrings #-} module NLP.Article.Analyze where import qualified Data.Text as T import NLP.LanguageModels.NGramm import NLP.Types import NLP.Types.Monad import qualified Data.Map as M import NLP.Index.Index handleAllArticles :: NLP () handleAllArticles = do articles <- getAll _ <- mapM handleArticle articles return () handleArticle :: Article -> NLP () handleArticle article@(Article {articleText = txt}) = do let txt' = T.words txt trigramms = getTrigramms txt' trigrammList = M.toList trigramms _ <- forkNLP $ mapM_ handleWord $ M.toList $ countOccurrence txt' _ <- forkNLP $ mapM_ handleTrigramm trigrammList return () where handleTrigramm (trigramm,count) = insertOrKey $ ArticleTrigramm article trigramm count handleWord (word,count) = insertOrKey $ ArticleWord article (Word word) count
azapps/nlp.hs
src/NLP/Article/Analyze.hs
gpl-3.0
854
0
11
147
267
139
128
23
1
import Control.Arrow import Data.Function import Data.List import System.Environment ( getArgs ) import Inputs checkSol :: [Int] -> Bool checkSol x = nub (sort x) == sort x && checkSol' x checkSol' :: [Int] -> Bool checkSol' s = and $ zipWith check s (tail s) check :: Int -> Int -> Bool check x y = (x `mod` y == 0 || y `mod` x == 0) && x /= y anotater = (id &&&) anotatel = (&&& id) increasingBy :: (a -> a -> Bool) -> [a] -> [a] increasingBy c = g where g (x:s) = x : g (dropWhile (not . c x) s) g s = s optsAll :: [a] -> [(a, [a])] optsAll = f id where f _ [] = [] f a (x:s) = (x,a s) : f (a . (x:)) s -- relevantPrimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] relevantPrimes :: [Int] relevantPrimes = takeWhile (<100) $ sieve [2..] where sieve (x:s) = x : sieve (filter ((/=) 0 . flip mod x) s) relevantFactors = f relevantPrimes where f _ 1 = [] f (p:s) n = if m == 0 then p : f (p:s) d else f s n where (d,m) = n `divMod` p magic :: (t -> (Int, Int, [Int]) -> [(Int, t)]) -> t -> (Int, Int, [Int]) -> [[Int]] -> [[Int]] magic f = solve where solve as (x,y,s) rest | y > x = solve as (y,x,reverse s) rest | otherwise = case f as (x,y,s) of [] -> s:rest t -> foldr (.) id (map (\ (x',as') -> solve as' (x',y,x':s)) t) rest magicOpts :: [Int] -> (Int, Int, [Int]) -> [(Int, [Int])] magicOpts s (x,_,_) = sortBy (compare `on` anotatel (length . relevantFactors . fst)) . filter (check x . fst) $ optsAll s main :: IO () main = do args <- getArgs case args of [] -> solPrinter . increasingBy ((<=) `on` length) $ magic magicOpts (inputs \\ [96]) (96,96,[96]) [] _ -> putStrLn "read source...." target :: Int target = 84 - 2 -- 51, 57, 69 ... choose one
xkollar/handy-haskell
other/js-2014-07/Main2.hs
gpl-3.0
1,867
0
18
525
997
545
452
49
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Model.EventScan ( EventScan (..) ) where import Data.Aeson import GHC.Generics import Test.QuickCheck import Model.Event import Model.Number import Model.RobotInfo data EventScan = EventScan { eventType :: Number , activationTime :: Float , direction :: Float , semiaperture :: Float , scanMaxDistance :: Float , robot :: RobotInfo , hitRobot :: RobotInfo } deriving (Show, Eq, Generic) instance FromJSON EventScan instance ToJSON EventScan instance Arbitrary EventScan where arbitrary = EventScan <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
massimo-zaniboni/netrobots
robot_examples/haskell-servant/rest_api/lib/Model/EventScan.hs
gpl-3.0
820
0
12
152
171
101
70
26
0
{-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : HEP.Automation.EventGeneration.Job -- Copyright : (c) 2013 Ian-Woo Kim -- -- License : GPL-3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- -- cmdargs type for pipeline-eventgen -- ----------------------------------------------------------------------------- module HEP.Automation.EventGeneration.ProgType where import Data.Data import Data.Typeable import System.Console.CmdArgs data EvGen = Work { config :: FilePath } | Upload { config :: FilePath } | Deploy { config :: FilePath , computername :: String , configout :: FilePath } | Remove { config :: FilePath , computername :: String } deriving (Show,Data,Typeable) work :: EvGen work = Work { config = "" &= typ "CONFIG" &= argPos 0 } upload :: EvGen upload = Upload { config = "" &= typ "CONFIG" &= argPos 0 } deploy :: EvGen deploy = Deploy { config = "deployconfig.txt" , computername = "" &= typ "COMPUTERNAME" &= argPos 0 , configout = "" &= typ "OUTPUTCONFIG" &= argPos 1 } remove :: EvGen remove = Remove { config = "deployconfig.txt" , computername = "" &= typ "COMPUTERNAME" &= argPos 0 } mode = modes [ work, upload, deploy, remove ]
wavewave/pipeline-eventgen
exe/HEP/Automation/EventGeneration/ProgType.hs
gpl-3.0
1,529
0
9
436
299
178
121
25
1
module He.Parser where import Control.Lens import Filesystem.Path.CurrentOS hiding (empty, null) import H.Prelude import Text.Parsec.Applicative hiding (Parser, parse) import qualified Text.Parsec.Applicative as P import He.Error import He.Lexer (TokenType(..), TokenData(..), IdClass(), Tokens, tokenData) type Parser s a = P.Parser s (TokenType a) (WithSourcePos TokenData) parseErrorText :: ParseError -> Text parseErrorText ParseError{..} = ty <> rest where ty = case peType of Nothing -> "Unknown error" Just ty -> case ty of EUnexpected -> "Unexpected token" EEnd -> "Unexpected end of input" ENotEnd -> "Expected end of input" rest = maybe "" (": " <>) peMessage parse :: (MonadError Error m, Eq a) => Parser s a b -> FilePath -> Tokens a -> m b parse file _ xs = case P.parse file xs of Left pe -> throwError $ err (peSourcePos pe) (parseErrorText pe) Right decl -> return decl delimit :: (IdClass a) => Text -> Text -> Parser s a b -> Parser s a b delimit ld rd = between (kw ld) (kw rd) kw :: (IdClass a) => Text -> Parser s a () kw = tok . Keyword litInt :: (IdClass a) => Parser s a Integer litInt = intData . tokenData <$> token LitInt litFloat :: (IdClass a) => Parser s a Rational litFloat = floatData . tokenData <$> token LitFloat litChar :: (IdClass a) => Parser s a Char litChar = charData . tokenData <$> token LitChar litBool :: (IdClass a) => Parser s a Bool litBool = boolData . tokenData <$> token LitBool identifier :: (IdClass a) => a -> Parser s a Text identifier = (textData . tokenData <$>) . token . Identifier anyIdentifier :: (IdClass a) => Parser s a (a, Text) anyIdentifier = fmap f . choice $ fmap (token . Identifier) [minBound .. maxBound] where f (Identifier cls, (^. wspValue) -> TextData name) = (cls, name) f _ = undefined tok :: (Eq a) => TokenType a -> Parser s a () tok = (f <$>) . token where f (_, (^. wspValue) -> NoData) = () f _ = undefined beginString :: (IdClass a) => Parser s a () beginString = tok BeginString endString :: (IdClass a) => Parser s a () endString = tok EndString stringContent :: (IdClass a) => Parser s a Text stringContent = textData . tokenData <$> token StringContent beginInterp :: (IdClass a) => Parser s a () beginInterp = tok BeginInterp endInterp :: (IdClass a) => Parser s a () endInterp = tok EndInterp beginComment :: (IdClass a) => Parser s a () beginComment = tok BeginComment commentContent :: (IdClass a) => Parser s a Text commentContent = textData . tokenData <$> token CommentContent endComment :: (IdClass a) => Parser s a () endComment = tok EndComment
ktvoelker/helium
src/He/Parser.hs
gpl-3.0
2,647
0
12
557
1,064
564
500
-1
-1
{-# LANGUAGE DeriveGeneric #-} module Data.Config.OutputConfig ( OutputConfig(..) ) where import Data.Aeson hiding (decode, encode) import Data.Text (Text) import GHC.Generics (Generic) import Prelude hiding (readFile, writeFile) data OutputConfig = Email { receiver :: Text , sender :: Text } | File Text | Std deriving (Generic, Eq, Show) instance ToJSON OutputConfig where toEncoding = genericToEncoding defaultOptions instance FromJSON OutputConfig where parseJSON = genericParseJSON defaultOptions
retep007/security-log
src/Data/Config/OutputConfig.hs
gpl-3.0
596
0
8
157
139
83
56
17
0
{- - Copyright (C) 2014 Alexander Berntsen <alexander@plaimi.net> - - This file is part of Virtual Tennis. - - Virtual Tennis 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. - - Virtual Tennis 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 Virtual Tennis. If not, see <http://www.gnu.org/licenses/>. -} module Time where -- | 'StepTime' is the amount of steps in a wall clock second. type StepTime = Float
alexander-b/master-fun
src/virtualtennis/Time.hs
gpl-3.0
856
0
4
153
12
9
3
2
0
-- eidolon -- A simple gallery in Haskell and Yesod -- Copyright (C) 2015 Amedeo Molnár -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published -- by the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module Foundation where import Prelude import Yesod import Yesod.Static import Yesod.Default.Util (addStaticContentExternal) import Network.HTTP.Client.Conduit (Manager, HasHttpManager (getHttpManager)) import Database.Persist.Sql -- (ConnectionPool, runSqlPool) import Settings.StaticFiles import Settings import Model import Text.Jasmine (minifym) import Text.Hamlet (hamletFile) import Yesod.Core.Types -- costom imports import Data.Text as T import Data.Text.Encoding import Network.Wai import Helper -- | The site argument for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { appSettings :: AppSettings , appStatic :: Static -- ^ Settings for static file serving. , appConnPool :: ConnectionPool -- ^ Database connection pool. , appHttpManager :: Manager , appLogger :: Logger } instance HasHttpManager App where getHttpManager = appHttpManager -- Set up i18n messages. See the message folder. mkMessage "App" "messages" "en" -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the linked documentation for an -- explanation for this split. mkYesodData "App" $(parseRoutesFile "config/routes") type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) renderLayout :: Widget -> Handler Html renderLayout widget = do master <- getYesod route <- getCurrentRoute mmsg <- getMessage msu <- lookupSession "userId" username <- case msu of Just a -> do uId <- return $ getUserIdFromText a user <- runDB $ getJust uId return $ userName user Nothing -> do return ("" :: T.Text) slug <- case msu of Just a -> do uId <- return $ getUserIdFromText a user <- runDB $ getJust uId return $ userSlug user Nothing -> do return ("" :: T.Text) block <- return $ appSignupBlocked $ appSettings master -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. wc <- widgetToPageContent widget pc <- widgetToPageContent $ do -- add parallelism js files $(combineScripts 'StaticR [ js_jquery_min_js , js_jquery_poptrox_min_js , js_skel_min_js , js_init_js ]) $(combineStylesheets 'StaticR [ -- css_normalize_css css_bootstrap_css ]) $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") formLayout :: Widget -> Handler Html formLayout widget = do renderLayout $(widgetFile "form-widget") approotRequest :: App -> Request -> T.Text approotRequest master req = case requestHeaderHost req of Just a -> prefix `T.append` decodeUtf8 a Nothing -> appRoot $ appSettings master where prefix = case isSecure req of True -> "https://" False -> (fst $ breakOn ":" $ appRoot $ appSettings master) `T.append` "://" -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where --approot = ApprootMaster $ appRoot . appSettings approot = ApprootRequest approotRequest -- change maximum content length maximumContentLength _ _ = Just $ 1024 ^ (5 :: Int) -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = fmap Just $ defaultClientSessionBackend 120 -- timeout in minutes "config/client_session_key.aes" defaultLayout widget = do renderLayout $(widgetFile "default-widget") -- This is done to provide an optimization for serving static files from -- a separate domain. Please see the staticRoot setting in Settings.hs -- urlRenderOverride y (StaticR s) = -- Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s -- urlRenderOverride _ _ = Nothing -- The page to be redirected to when authentication is required. -- authRoute _ = Just $ AuthR LoginR -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- Place Javascript at head so scripts become loaded before content jsLoader _ = BottomOfHeadBlocking -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB action = do master <- getYesod runSqlPool action $ appConnPool master instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool -- instance YesodAuth App where -- type AuthId App = UserId -- Where to send a user after successful login -- loginDest _ = HomeR -- Where to send a user after logout -- logoutDest _ = HomeR -- getAuthId creds = runDB $ do -- x <- getBy $ UniqueUser $ credsIdent creds -- case x of -- Just (Entity uid _) -> return $ Just uid -- Nothing -> do -- fmap Just $ insert User -- { userIdent = credsIdent creds -- , userPassword = Nothing -- } -- You can add other plugins like BrowserID, email or OAuth here -- authPlugins _ = [authBrowserId def] -- authHttpManager = httpManager -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage -- | Get the 'Extra' value, used to hold data from the settings.yml file. -- getExtra :: Handler Extra -- getExtra = fmap (appExtra . settings) getYesod -- Note: previous versions of the scaffolding included a deliver function to -- send emails. Unfortunately, there are too many different options for us to -- give a reasonable default. Instead, the information is available on the -- wiki: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email
Mic92/eidolon
Foundation.hs
agpl-3.0
8,379
0
15
2,060
1,072
581
491
-1
-1
func = \x -> abc describe "app" $ do
lspitzner/brittany
data/Test99.hs
agpl-3.0
37
1
5
9
20
10
10
-1
-1
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DataKinds #-} module Main ( main ) where import GHC.Generics ( Generic, Generic1 ) import Data.Vector ( Vector ) import Accessors ( Lookup ) import Linear ( Additive(..) ) import Dyno.Vectorize ( Vectorize, None(..), vpure, vapply ) import Dyno.View.View ( J, jfill, catJV ) import Dyno.Nlp ( NlpOut(..), Bounds ) import Dyno.Ocp import Dyno.Solvers ( Solver(..), GType(..), ipoptSolver ) import Dyno.NlpUtils ( solveNlp ) import Dyno.DirectCollocation.ActiveConstraints import Dyno.DirectCollocation.Formulate ( CollProblem(..), DirCollOptions(..), MapStrategy(..), makeCollProblem, def ) import Dyno.DirectCollocation.Types ( CollTraj' ) import Dyno.DirectCollocation.Dynamic ( toMeta ) import Dyno.DirectCollocation.Quadratures ( QuadratureRoots(..) ) import Dynoplot.Callback ( withCallback ) rocketOcp :: OcpPhase' RocketOcp rocketOcp = OcpPhase { ocpMayer = mayer , ocpLagrange = lagrange , ocpQuadratures = \_ _ _ _ _ _ _ _ -> None , ocpQuadratureOutputs = \_ _ _ _ _ _ _ _ -> None , ocpDae = dae , ocpBc = bc , ocpPathC = pathC , ocpPlotOutputs = \_ _ _ _ _ _ _ _ _ _ _ -> None , ocpObjScale = Nothing , ocpTScale = Nothing , ocpXScale = Nothing , ocpZScale = Nothing , ocpUScale = Nothing , ocpPScale = Nothing , ocpResidualScale = Nothing , ocpBcScale = Nothing , ocpPathCScale = Nothing } rocketOcpInputs :: OcpPhaseInputs' RocketOcp rocketOcpInputs = OcpPhaseInputs { ocpBcBnds = bcBnds , ocpPathCBnds = pathCBnds , ocpXbnd = RocketX { xPos = (Just 0, Nothing) , xVel = (Just (-10), Just 0) , xMass = (Just 0.01, Nothing) , xThrust = (Just (-200), Just 200) } , ocpZbnd = pure (Nothing, Nothing) , ocpUbnd = RocketU { uThrustDot = (Just (-100), Just 100) } , ocpPbnd = pure (Nothing, Nothing) , ocpTbnd = (Just 4, Just 4) , ocpFixedP = None } data RocketOcp type instance X RocketOcp = RocketX type instance O RocketOcp = RocketO type instance R RocketOcp = RocketX type instance U RocketOcp = RocketU type instance C RocketOcp = RocketBc type instance H RocketOcp = RocketPathC type instance P RocketOcp = None type instance Z RocketOcp = None type instance Q RocketOcp = None type instance QO RocketOcp = None type instance FP RocketOcp = None type instance PO RocketOcp = None data RocketX a = RocketX { xPos :: a , xVel :: a , xMass :: a , xThrust :: a } deriving (Functor, Generic, Generic1) data RocketU a = RocketU { uThrustDot :: a } deriving (Functor, Generic, Generic1) data RocketO a = RocketO { oForce :: a } deriving (Functor, Generic, Generic1) data RocketBc a = RocketBc { bcX0 :: RocketX a , bcXF :: RocketX a } deriving (Functor, Generic, Generic1) data RocketPathC a = RocketPathC a deriving (Functor, Generic, Generic1) instance Vectorize RocketX instance Vectorize RocketU instance Vectorize RocketO instance Vectorize RocketBc instance Vectorize RocketPathC instance Lookup a => Lookup (RocketX a) instance Lookup a => Lookup (RocketU a) instance Lookup a => Lookup (RocketO a) instance Lookup a => Lookup (RocketBc a) instance Lookup a => Lookup (RocketPathC a) instance Applicative RocketX where {pure = vpure; (<*>) = vapply} instance Applicative RocketU where {pure = vpure; (<*>) = vapply} instance Applicative RocketO where {pure = vpure; (<*>) = vapply} instance Applicative RocketPathC where {pure = vpure; (<*>) = vapply} instance Applicative RocketBc where {pure = vpure; (<*>) = vapply} instance Additive RocketX where zero = pure 0 instance Additive RocketU where zero = pure 0 instance Additive RocketPathC where zero = pure 0 instance Additive RocketBc where zero = pure 0 dae :: Floating a => RocketX a -> RocketX a -> None a -> RocketU a -> None a -> None a -> a -> (RocketX a, RocketO a) dae (RocketX p' v' m' thrust') (RocketX _ v m thrust) _ (RocketU uThrust') _ _ _ = (residual, outputs) where residual = RocketX { xPos = p' - v , xVel = v' - force/m , xMass = m' - (-1e-2*thrust**2) , xThrust = thrust' - uThrust' } outputs = RocketO { oForce = force } g = 9.8 force = thrust - m*g bc :: RocketX a -> RocketX a -> None a -> None a -> None a -> a -> RocketBc a bc x0 xf _ _ _ _ = RocketBc x0 xf bcBnds :: RocketBc Bounds bcBnds = RocketBc { bcX0 = RocketX (Just 1, Just 1) (Just 0, Just 0) (Just 10, Just 10) (Nothing, Nothing) , bcXF = RocketX (Just 0, Just 0) (Just 0, Just 0) (Nothing, Nothing) (Nothing, Nothing) } mayer :: Floating a => a -> RocketX a -> RocketX a -> None a -> None a -> None a -> a mayer _endTime _ (RocketX _ _ mf _) _ _ _ = -mf -- endTime pathC :: RocketX a -> None a -> RocketU a -> None a -> None a -> RocketO a -> a -> RocketPathC a pathC _ _ _ _ _ _ = RocketPathC pathCBnds :: RocketPathC Bounds pathCBnds = RocketPathC (Nothing, Just 4) lagrange :: Fractional a => RocketX a -> None a -> RocketU a -> None a -> None a -> RocketO a -> a -> a -> a lagrange _ _ (RocketU u') _ _ _ _ _ = 1e-4*u'*u' -- (1e-8*u*u + 1e-9*p*p + 1e-9*v*v + 1e-9*m*m) -- (1e-6*u*u + 1e-6*p*p + 1e-6*v*v + 1e-6*m*m) solver :: Solver solver = ipoptSolver { options = [("expand", GBool True)] } guess :: J (CollTraj' RocketOcp NCollStages CollDeg) (Vector Double) guess = jfill 1 type NCollStages = 100 type CollDeg = 3 dirCollOpts :: DirCollOptions dirCollOpts = def { collocationRoots = Legendre , mapStrategy = Unroll } main :: IO () main = withCallback $ \send -> do cp <- makeCollProblem dirCollOpts rocketOcp rocketOcpInputs guess let nlp = cpNlp cp meta = toMeta (cpMetaProxy cp) cb' traj _ _ = do plotPoints <- cpPlotPoints cp traj (catJV None) send (plotPoints, meta) (_, eopt) <- solveNlp "rocket" solver nlp (Just cb') case eopt of Left msg -> putStrLn $ "\nsolve failed with " ++ show msg Right opt -> do activeConstraints <- getActiveConstraints (cpConstraints cp) rocketOcp 1e-3 (xOpt opt) (catJV None) rocketOcpInputs putStrLn "\nactive constriants:" putStr $ summarizeActiveConstraints activeConstraints
ghorn/dynobud
dynobud/examples/Rocket.hs
lgpl-3.0
6,432
0
17
1,563
2,258
1,241
1,017
-1
-1
#!/usr/bin/env stack -- stack --resolver lts-8.5 runghc --package minio-hs --package optparse-applicative --package filepath -- -- Minio Haskell SDK, (C) 2017 Minio, Inc. -- -- 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 -- -- http://www.apache.org/licenses/LICENSE-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. -- {-# Language OverloadedStrings, ScopedTypeVariables #-} import Network.Minio import Control.Monad.Catch (catchIf) import Control.Monad.IO.Class (liftIO) import Data.Monoid ((<>)) import Data.Text (pack) import Options.Applicative import Prelude import System.FilePath.Posix -- | The following example uses minio's play server at -- https://play.minio.io:9000. The endpoint and associated -- credentials are provided via the libary constant, -- -- > minioPlayCI :: ConnectInfo -- -- optparse-applicative package based command-line parsing. fileNameArgs :: Parser FilePath fileNameArgs = strArgument (metavar "FILENAME" <> help "Name of file to upload to AWS S3 or a Minio server") cmdParser = info (helper <*> fileNameArgs) (fullDesc <> progDesc "FileUploader" <> header "FileUploader - a simple file-uploader program using minio-hs") ignoreMinioErr :: ServiceErr -> Minio () ignoreMinioErr = return . const () main :: IO () main = do let bucket = "my-bucket" -- Parse command line argument filepath <- execParser cmdParser let object = pack $ takeBaseName filepath res <- runMinio minioPlayCI $ do -- Make a bucket; catch bucket already exists exception if thrown. catchIf (== BucketAlreadyOwnedByYou) (makeBucket bucket Nothing) ignoreMinioErr -- Upload filepath to bucket; object is derived from filepath. fPutObject bucket object filepath case res of Left e -> putStrLn $ "file upload failed due to " ++ (show e) Right () -> putStrLn "file upload succeeded."
donatello/minio-hs
examples/FileUploader.hs
apache-2.0
2,339
0
13
468
324
178
146
32
2
module QuadraticEquationSpec where import Test.Hspec import QuadraticEquation main :: IO () main = hspec $ do describe "equationRoots" $ do context "when equation has non-complex solution" $ do it "returns two roots of equation" $ do equationRoots (QEquation 1.0 5.0 6.0) `shouldBe` [-2.0, -3.0] describe "substituteUnknown" $ do it "substitutes x with the specified value" $ do substituteUnknown (QEquation 1.0 5.0 6.0) (-3.0) `shouldBe` 0.0 describe "naturalRoots" $ do it "returns roots only if they are natural numbers" $ do naturalRoots (QEquation 0.5 0.5 (-40755.0)) `shouldBe` [285]
kliuchnikau/project-euler
lib/QuadraticEquationSpec.hs
apache-2.0
638
0
20
135
192
94
98
15
1
{-# LANGUAGE BangPatterns #-} module Data.MInfo.Operation.Connections where import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy as LBS import Data.ByteString.Lazy.Builder import Data.List ( sortBy ) import qualified Data.Map.Strict as M import Data.Monoid ( mempty ) import Data.Ord ( comparing ) import Data.MInfo.Types import Data.MInfo.Utils type ConnectionMap = M.Map BS.ByteString (Int, Int) connections :: [LogLine] -> LBS.ByteString connections ls = case ls of [] -> LBS.empty _ -> toLazyByteString $ header <> foldr go mempty (sort ls) where go (k, (o, c)) acc = pad 20 (BS.unpack k) <> pad 12 (show o) <> stringUtf8 (show c) <> nl <> acc header = pad 20 "IP:" <> pad 12 "CONN:" <> stringUtf8 "DISCONN:" <> nl sort = sortBy (flip (comparing byConn)) . M.toList . connections' byConn = fst . snd nl = charUtf8 '\n' connections' :: [LogLine] -> ConnectionMap connections' ls = M.fromListWith go $ concatMap conns ls where go (!o, !c) (!o', !c') = (o+o', c+c') conns (LogLine _ _ content) = case content of (LcAcceptConnection c) -> [(c, (1, 0))] (LcEndConnection c) -> [(c, (0, 1))] _ -> [] -- vim: set et sw=2 sts=2 tw=80:
kongo2002/minfo
Data/MInfo/Operation/Connections.hs
apache-2.0
1,295
0
14
320
478
264
214
35
3
module PCode( module PCode.Builtin, module PCode.Instruction, module PCode.Value) where import PCode.Builtin import PCode.Instruction import PCode.Value
lih/Alpha
src/PCode.hs
bsd-2-clause
161
0
5
23
39
25
14
7
0
{- | Module : Data.Set.Range Description : Data structure that stores a set of ranges of types that implement Eq, Ord and Enum typeclasses. Copyright : (c) 2017 Daniel Lovasko License : BSD2 Maintainer : Daniel Lovasko <daniel.lovasko@gmail.com> Stability : stable Portability : portable -} module Data.Set.Range ( Range , RangeSet -- general , empty , null , size -- list conversions , fromAscList , fromDescList , fromList , toList -- access , insertPoint , insertRange , removePoint , removeRange -- member testing , queryPoint , queryRange -- combinations , difference , intersect , union ) where import Prelude hiding (null) import Data.Set.Range.Combine import Data.Set.Range.General import Data.Set.Range.List import Data.Set.Range.Modify import Data.Set.Range.Query import Data.Set.Range.Types
lovasko/rset
src/Data/Set/Range.hs
bsd-2-clause
839
0
5
150
120
84
36
26
0
module FP.Prelude.Compat where import FP.Prelude.Core import qualified Prelude instance (Functor m) ⇒ Prelude.Functor m where { fmap = FP.Prelude.Core.map } instance (Monad m) ⇒ Prelude.Applicative m where { pure = FP.Prelude.Core.return ; (<*>) = FP.Prelude.Core.mapply } instance (Monad m) ⇒ Prelude.Monad m where { return = FP.Prelude.Core.return ; (>>=) = (FP.Prelude.Core.≫=) }
davdar/darailude
src/FP/Prelude/Compat.hs
bsd-3-clause
393
0
6
54
133
86
47
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. module Duckling.Ordinal.GA.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Ordinal.GA.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "GA Tests" [ makeCorpusTest [This Ordinal] corpus ]
rfranek/duckling
tests/Duckling/Ordinal/GA/Tests.hs
bsd-3-clause
602
0
9
98
80
51
29
11
1
{-# LANGUAGE UndecidableInstances #-} {-| Module : Servant.Server.Auth.Token Description : Implementation of token authorisation API Copyright : (c) Anton Gushcha, 2016 License : MIT Maintainer : ncrashed@gmail.com Stability : experimental Portability : Portable The module is server side implementation of "Servant.API.Auth.Token" API and intended to be used as drop in module for user servers or as external micro service. Use 'guardAuthToken' to check authorisation headers in endpoints of your server: @ -- | Read a single customer from DB customerGet :: CustomerId -- ^ Customer unique id -> MToken' '["customer-read"] -- ^ Required permissions for auth token -> ServerM Customer -- ^ Customer data customerGet i token = do guardAuthToken token guard404 "customer" $ getCustomer i @ -} module Servant.Server.Auth.Token( -- * Implementation authServer -- * Server API , HasStorage(..) , AuthHandler -- * Helpers , guardAuthToken , WithAuthToken(..) , ensureAdmin , authUserByToken -- * API methods , authSignin , authSigninGetCode , authSigninPostCode , authTouch , authToken , authSignout , authSignup , authUsersInfo , authUserInfo , authUserPatch , authUserPut , authUserDelete , authRestore , authGetSingleUseCodes , authGroupGet , authGroupPost , authGroupPut , authGroupPatch , authGroupDelete , authGroupList , authCheckPermissionsMethod , authGetUserIdMethod , authFindUserByLogin -- * Low-level API , getAuthToken , hashPassword , setUserPasswordHash , ensureAdminHash , signinByHashUnsafe ) where import Control.Monad import Control.Monad.Except import Crypto.PasswordStore import Data.Aeson.Unit import Data.Aeson.WithField import Data.Maybe import Data.Monoid import Data.Text (Text) import Data.Text.Encoding import Data.Time.Clock import Data.UUID import Data.UUID.V4 import Servant import Servant.API.Auth.Token import Servant.API.Auth.Token.Pagination import Servant.Server.Auth.Token.Common import Servant.Server.Auth.Token.Config import Servant.Server.Auth.Token.Model import Servant.Server.Auth.Token.Monad import Servant.Server.Auth.Token.Pagination import Servant.Server.Auth.Token.Restore import Servant.Server.Auth.Token.SingleUse import qualified Data.ByteString.Lazy as BS -- | Implementation of AuthAPI authServer :: AuthHandler m => ServerT AuthAPI m authServer = authSignin :<|> authSigninGetCode :<|> authSigninPostCode :<|> authTouch :<|> authToken :<|> authSignout :<|> authSignup :<|> authUsersInfo :<|> authUserInfo :<|> authUserPatch :<|> authUserPut :<|> authUserDelete :<|> authRestore :<|> authGetSingleUseCodes :<|> authGroupGet :<|> authGroupPost :<|> authGroupPut :<|> authGroupPatch :<|> authGroupDelete :<|> authGroupList :<|> authCheckPermissionsMethod :<|> authGetUserIdMethod :<|> authFindUserByLogin -- | Implementation of "signin" method authSignin :: AuthHandler m => Maybe Login -- ^ Login query parameter -> Maybe Password -- ^ Password query parameter -> Maybe Seconds -- ^ Expire query parameter, how many seconds the token is valid -> m (OnlyField "token" SimpleToken) -- ^ If everything is OK, return token authSignin mlogin mpass mexpire = do login <- require "login" mlogin pass <- require "pass" mpass WithField uid UserImpl{..} <- guardLogin login pass OnlyField <$> getAuthToken uid mexpire where guardLogin login pass = do -- check login and password, return passed user muser <- getUserImplByLogin login let err = throw401 "Cannot find user with given combination of login and pass" case muser of Nothing -> err Just user@(WithField _ UserImpl{..}) -> if passToByteString pass `verifyPassword` passToByteString userImplPassword then return user else err -- | Helper to get or generate new token for user getAuthToken :: AuthHandler m => UserImplId -- ^ User for whom we want token -> Maybe Seconds -- ^ Expiration duration, 'Nothing' means default -> m SimpleToken -- ^ Old token (if it doesn't expire) or new one getAuthToken uid mexpire = do expire <- calcExpire mexpire mt <- getExistingToken -- check whether there is already existing token case mt of Nothing -> createToken expire -- create new token Just t -> touchToken t expire -- prolong token expiration time where getExistingToken = do -- return active token for specified user id t <- liftIO getCurrentTime findAuthToken uid t createToken expire = do -- generate and save fresh token token <- toText <$> liftIO nextRandom _ <- insertAuthToken AuthToken { authTokenValue = token , authTokenUser = uid , authTokenExpire = expire } return token -- | Authorisation via code of single usage. -- -- Implementation of 'AuthSigninGetCodeMethod' endpoint. -- -- Logic of authorisation via this method is: -- -- * Client sends GET request to 'AuthSigninGetCodeMethod' endpoint -- -- * Server generates single use token and sends it via -- SMS or email, defined in configuration by 'singleUseCodeSender' field. -- -- * Client sends POST request to 'AuthSigninPostCodeMethod' endpoint -- -- * Server responds with auth token. -- -- * Client uses the token with other requests as authorisation -- header -- -- * Client can extend lifetime of token by periodically pinging -- of 'AuthTouchMethod' endpoint -- -- * Client can invalidate token instantly by 'AuthSignoutMethod' -- -- * Client can get info about user with 'AuthTokenInfoMethod' endpoint. -- -- See also: 'authSigninPostCode' authSigninGetCode :: AuthHandler m => Maybe Login -- ^ User login, required -> m Unit authSigninGetCode mlogin = do login <- require "login" mlogin uinfo <- guard404 "user" $ readUserInfoByLogin login let uid = toKey $ respUserId uinfo AuthConfig{..} <- getConfig code <- liftIO singleUseCodeGenerator expire <- makeSingleUseExpire singleUseCodeExpire registerSingleUseCode uid code (Just expire) liftIO $ singleUseCodeSender uinfo code return Unit -- | Authorisation via code of single usage. -- -- Logic of authorisation via this method is: -- -- * Client sends GET request to 'AuthSigninGetCodeMethod' endpoint -- -- * Server generates single use token and sends it via -- SMS or email, defined in configuration by 'singleUseCodeSender' field. -- -- * Client sends POST request to 'AuthSigninPostCodeMethod' endpoint -- -- * Server responds with auth token. -- -- * Client uses the token with other requests as authorisation -- header -- -- * Client can extend lifetime of token by periodically pinging -- of 'AuthTouchMethod' endpoint -- -- * Client can invalidate token instantly by 'AuthSignoutMethod' -- -- * Client can get info about user with 'AuthTokenInfoMethod' endpoint. -- -- See also: 'authSigninGetCode' authSigninPostCode :: AuthHandler m => Maybe Login -- ^ User login, required -> Maybe SingleUseCode -- ^ Received single usage code, required -> Maybe Seconds -- ^ Time interval after which the token expires, 'Nothing' means -- some default value -> m (OnlyField "token" SimpleToken) authSigninPostCode mlogin mcode mexpire = do login <- require "login" mlogin code <- require "code" mcode uinfo <- guard404 "user" $ readUserInfoByLogin login let uid = toKey $ respUserId uinfo isValid <- validateSingleUseCode uid code unless isValid $ throw401 "Single usage code doesn't match" OnlyField <$> getAuthToken uid mexpire -- | Calculate expiration timestamp for token calcExpire :: AuthHandler m => Maybe Seconds -> m UTCTime calcExpire mexpire = do t <- liftIO getCurrentTime AuthConfig{..} <- getConfig let requestedExpire = maybe defaultExpire fromIntegral mexpire let boundedExpire = maybe requestedExpire (min requestedExpire) maximumExpire return $ boundedExpire `addUTCTime` t -- prolong token with new timestamp touchToken :: AuthHandler m => WithId AuthTokenId AuthToken -> UTCTime -> m SimpleToken touchToken (WithField tid tok) expire = do replaceAuthToken tid tok { authTokenExpire = expire } return $ authTokenValue tok -- | Implementation of "touch" method authTouch :: AuthHandler m => Maybe Seconds -- ^ Expire query parameter, how many seconds the token should be valid by now. 'Nothing' means default value defined in server config. -> MToken '[] -- ^ Authorisation header with token -> m Unit authTouch mexpire token = do WithField i mt <- guardAuthToken' (fmap unToken token) [] expire <- calcExpire mexpire replaceAuthToken i mt { authTokenExpire = expire } return Unit -- | Implementation of "token" method, return -- info about user binded to the token authToken :: AuthHandler m => MToken '[] -- ^ Authorisation header with token -> m RespUserInfo authToken token = do i <- authUserByToken token guard404 "user" . readUserInfo . fromKey $ i -- | Getting user id by token authUserByToken :: AuthHandler m => MToken '[] -> m UserImplId authUserByToken token = do WithField _ mt <- guardAuthToken' (fmap unToken token) [] return $ authTokenUser mt -- | Implementation of "signout" method authSignout :: AuthHandler m => Maybe (Token '[]) -- ^ Authorisation header with token -> m Unit authSignout token = do WithField i mt <- guardAuthToken' (fmap unToken token) [] expire <- liftIO getCurrentTime replaceAuthToken i mt { authTokenExpire = expire } return Unit -- | Checks given password and if it is invalid in terms of config -- password validator, throws 400 error. guardPassword :: AuthHandler m => Password -> m () guardPassword p = do AuthConfig{..} <- getConfig whenJust (passwordValidator p) $ throw400 . BS.fromStrict . encodeUtf8 -- | Implementation of "signup" method authSignup :: AuthHandler m => ReqRegister -- ^ Registration info -> MToken' '["auth-register"] -- ^ Authorisation header with token -> m (OnlyField "user" UserId) authSignup ReqRegister{..} token = do guardAuthToken token guardUserInfo guardPassword reqRegPassword strength <- getsConfig passwordsStrength i <- createUser strength reqRegLogin reqRegPassword reqRegEmail reqRegPermissions whenJust reqRegGroups $ setUserGroups i return $ OnlyField . fromKey $ i where guardUserInfo = do mu <- getUserImplByLogin reqRegLogin whenJust mu $ const $ throw400 "User with specified id is already registered" -- | Implementation of get "users" method authUsersInfo :: AuthHandler m => Maybe Page -- ^ Page num parameter -> Maybe PageSize -- ^ Page size parameter -> MToken' '["auth-info"] -- ^ Authorisation header with token -> m RespUsersInfo authUsersInfo mp msize token = do guardAuthToken token pagination mp msize $ \page size -> do (users', total) <- listUsersPaged page size perms <- mapM (getUserPermissions . (\(WithField i _) -> i)) users' groups <- mapM (getUserGroups . (\(WithField i _) -> i)) users' let users = zip3 users' perms groups return RespUsersInfo { respUsersItems = (\(user, ps, grs) -> userToUserInfo user ps grs) <$> users , respUsersPages = ceiling $ (fromIntegral total :: Double) / fromIntegral size } -- | Implementation of get "user" method authUserInfo :: AuthHandler m => UserId -- ^ User id -> MToken' '["auth-info"] -- ^ Authorisation header with token -> m RespUserInfo authUserInfo uid' token = do guardAuthToken token guard404 "user" $ readUserInfo uid' -- | Implementation of patch "user" method authUserPatch :: AuthHandler m => UserId -- ^ User id -> PatchUser -- ^ JSON with fields for patching -> MToken' '["auth-update"] -- ^ Authorisation header with token -> m Unit authUserPatch uid' body token = do guardAuthToken token whenJust (patchUserPassword body) guardPassword let uid = toKey uid' user <- guardUser uid strength <- getsConfig passwordsStrength WithField _ user' <- patchUser strength body $ WithField uid user replaceUserImpl uid user' return Unit -- | Implementation of put "user" method authUserPut :: AuthHandler m => UserId -- ^ User id -> ReqRegister -- ^ New user -> MToken' '["auth-update"] -- ^ Authorisation header with token -> m Unit authUserPut uid' ReqRegister{..} token = do guardAuthToken token guardPassword reqRegPassword let uid = toKey uid' let user = UserImpl { userImplLogin = reqRegLogin , userImplPassword = "" , userImplEmail = reqRegEmail } user' <- setUserPassword reqRegPassword user replaceUserImpl uid user' setUserPermissions uid reqRegPermissions whenJust reqRegGroups $ setUserGroups uid return Unit -- | Implementation of patch "user" method authUserDelete :: AuthHandler m => UserId -- ^ User id -> MToken' '["auth-delete"] -- ^ Authorisation header with token -> m Unit authUserDelete uid' token = do guardAuthToken token deleteUserImpl $ toKey uid' return Unit -- Generate new password for user. There is two phases, first, the method -- is called without 'code' parameter. The system sends email with a restore code -- to email. After that a call of the method with the code is needed to -- change password. Need configured SMTP server. authRestore :: AuthHandler m => UserId -- ^ User id -> Maybe RestoreCode -> Maybe Password -> m Unit authRestore uid' mcode mpass = do let uid = toKey uid' user <- guardUser uid case mcode of Nothing -> do dt <- getsConfig restoreExpire t <- liftIO getCurrentTime AuthConfig{..} <- getConfig rc <- getRestoreCode restoreCodeGenerator uid $ addUTCTime dt t uinfo <- guard404 "user" $ readUserInfo uid' sendRestoreCode uinfo rc Just code -> do pass <- require "password" mpass guardPassword pass guardRestoreCode uid code user' <- setUserPassword pass user replaceUserImpl uid user' return Unit -- | Implementation of 'AuthGetSingleUseCodes' endpoint. authGetSingleUseCodes :: AuthHandler m => UserId -- ^ Id of user -> Maybe Word -- ^ Number of codes. 'Nothing' means that server generates some default count of codes. -- And server can define maximum count of codes that user can have at once. -> MToken' '["auth-single-codes"] -> m (OnlyField "codes" [SingleUseCode]) authGetSingleUseCodes uid mcount token = do guardAuthToken token let uid' = toKey uid _ <- guard404 "user" $ readUserInfo uid AuthConfig{..} <- getConfig let n = min singleUseCodePermamentMaximum $ fromMaybe singleUseCodeDefaultCount mcount OnlyField <$> generateSingleUsedCodes uid' singleUseCodeGenerator n -- | Getting user by id, throw 404 response if not found guardUser :: AuthHandler m => UserImplId -> m UserImpl guardUser uid = do muser <- getUserImpl uid case muser of Nothing -> throw404 "User not found" Just user -> return user -- | If the token is missing or the user of the token -- doesn't have needed permissions, throw 401 response guardAuthToken :: forall perms m . (PermsList perms, AuthHandler m) => MToken perms -> m () guardAuthToken mt = void $ guardAuthToken' (fmap unToken mt) $ unliftPerms (Proxy :: Proxy perms) class WithAuthToken a where -- | Authenticate an entire API rather than each individual -- endpoint. -- -- As such, for a given 'HasServer' instance @api@, if you have: -- -- @ -- f :: 'ServerT' api m -- @ -- -- then: -- -- @ -- withAuthToken f :: (AuthHandler m) => ServerT ('TokenHeader' perms :> api) m -- @ -- -- (Note that the types don't reflect this, as it isn't possible to -- guarantee what all possible @ServerT@ instances might be.) withAuthToken :: (PermsList perms) => a -> MToken perms -> a instance (AuthHandler m) => WithAuthToken (m a) where withAuthToken m mt = guardAuthToken mt *> m instance {-# OVERLAPPING #-} (WithAuthToken r) => WithAuthToken (a -> r) where withAuthToken f mt = (`withAuthToken` mt) . f instance (WithAuthToken a, WithAuthToken b) => WithAuthToken (a :<|> b) where withAuthToken (a :<|> b) mt = withAuthToken a mt :<|> withAuthToken b mt -- | Same as `guardAuthToken` but returns record about the token guardAuthToken' :: AuthHandler m => Maybe SimpleToken -> [Permission] -> m (WithId AuthTokenId AuthToken) guardAuthToken' Nothing _ = throw401 "Token required" guardAuthToken' (Just token) perms = do t <- liftIO getCurrentTime mt <- findAuthTokenByValue token case mt of Nothing -> throw401 "Token is not valid" Just et@(WithField _ AuthToken{..}) -> do when (t > authTokenExpire) $ throwError $ err401 { errBody = "Token expired" } mu <- getUserImpl authTokenUser case mu of Nothing -> throw500 "User of the token doesn't exist" Just UserImpl{..} -> do isAdmin <- hasPerm authTokenUser adminPerm hasAllPerms <- hasPerms authTokenUser perms unless (isAdmin || hasAllPerms) $ throw401 $ "User doesn't have all required permissions: " <> showb perms return et -- | Rehash password for user setUserPassword :: AuthHandler m => Password -> UserImpl -> m UserImpl setUserPassword pass user = do strength <- getsConfig passwordsStrength setUserPassword' strength pass user -- | Update password hash of user. Can be used to set direct hash for user password -- when it is taken from config file. setUserPasswordHash :: AuthHandler m => Text -> UserId -> m () setUserPasswordHash hashedPassword i = do let i' = toKey i user <- guard404 "user" $ getUserImpl i' let user' = user { userImplPassword = hashedPassword } replaceUserImpl i' user' -- | Getting info about user group, requires 'authInfoPerm' for token authGroupGet :: AuthHandler m => UserGroupId -> MToken' '["auth-info"] -- ^ Authorisation header with token -> m UserGroup authGroupGet i token = do guardAuthToken token guard404 "user group" $ readUserGroup i -- | Inserting new user group, requires 'authUpdatePerm' for token authGroupPost :: AuthHandler m => UserGroup -> MToken' '["auth-update"] -- ^ Authorisation header with token -> m (OnlyId UserGroupId) authGroupPost ug token = do guardAuthToken token OnlyField <$> insertUserGroup ug -- | Replace info about given user group, requires 'authUpdatePerm' for token authGroupPut :: AuthHandler m => UserGroupId -> UserGroup -> MToken' '["auth-update"] -- ^ Authorisation header with token -> m Unit authGroupPut i ug token = do guardAuthToken token updateUserGroup i ug return Unit -- | Patch info about given user group, requires 'authUpdatePerm' for token authGroupPatch :: AuthHandler m => UserGroupId -> PatchUserGroup -> MToken' '["auth-update"] -- ^ Authorisation header with token -> m Unit authGroupPatch i up token = do guardAuthToken token patchUserGroup i up return Unit -- | Delete all info about given user group, requires 'authDeletePerm' for token authGroupDelete :: AuthHandler m => UserGroupId -> MToken' '["auth-delete"] -- ^ Authorisation header with token -> m Unit authGroupDelete i token = do guardAuthToken token deleteUserGroup i return Unit -- | Get list of user groups, requires 'authInfoPerm' for token authGroupList :: AuthHandler m => Maybe Page -> Maybe PageSize -> MToken' '["auth-info"] -- ^ Authorisation header with token -> m (PagedList UserGroupId UserGroup) authGroupList mp msize token = do guardAuthToken token pagination mp msize $ \page size -> do (groups', total) <- listGroupsPaged page size groups <- forM groups' $ (\i -> fmap (WithField i) <$> readUserGroup i) . fromKey . (\(WithField i _) -> i) return PagedList { pagedListItems = catMaybes groups , pagedListPages = ceiling $ (fromIntegral total :: Double) / fromIntegral size } -- | Check that the token has required permissions and return 'False' if it doesn't. authCheckPermissionsMethod :: AuthHandler m => MToken' '["auth-check"] -- ^ Authorisation header with token -> OnlyField "permissions" [Permission] -- ^ Body with permissions to check -> m Bool -- ^ 'True' if all permissions are OK, 'False' if some permissions are not set for token and 401 error if the token doesn't have 'auth-check' permission. authCheckPermissionsMethod token (OnlyField perms) = do guardAuthToken token let check = const True <$> guardAuthToken' (unToken <$> token) perms check `catchError` (\e -> if errHTTPCode e == 401 then pure True else throwError e) -- | Get user ID for the owner of the speified token. authGetUserIdMethod :: AuthHandler m => MToken' '["auth-userid"] -- ^ Authorisation header with token -> m (OnlyId UserId) authGetUserIdMethod token = do guardAuthToken token OnlyField . respUserId <$> authToken (downgradeToken token) -- | Implementation of 'AuthFindUserByLogin'. Find user by login, throw 404 error -- if cannot find user by such login. authFindUserByLogin :: AuthHandler m => Maybe Login -- ^ Login, 'Nothing' will cause 400 error. -> MToken' '["auth-info"] -> m RespUserInfo authFindUserByLogin mlogin token = do login <- require "login" mlogin guardAuthToken token userWithId <- guard404 "user" $ getUserImplByLogin login makeUserInfo userWithId -- | Generate hash from given password and return it as text. May be useful if -- you don't like storing unencrypt passwords in config files. hashPassword :: AuthHandler m => Password -> m Text hashPassword pass = do strength <- getsConfig passwordsStrength hashed <- liftIO $ makePassword (passToByteString pass) strength return $ byteStringToPass hashed -- | Ensures that DB has at least one admin, if not, creates a new one -- with specified info and direct password hash. May be useful if -- you don't like storing unencrypt passwords in config files. ensureAdminHash :: AuthHandler m => Int -> Login -> Text -> Email -> m () ensureAdminHash strength login passHash email = do madmin <- getFirstUserByPerm adminPerm whenNothing madmin $ do i <- createAdmin strength login "" email setUserPasswordHash passHash $ fromKey i -- | If you use password hash in configs, you cannot use them in signin -- method. This helper allows to get token by password hash and the function -- is not available for remote call (no endpoint). -- -- Throws 401 if cannot find user or authorisation is failed. -- -- WARNING: Do not expose the function to end user, never! signinByHashUnsafe :: AuthHandler m => Login -- ^ User login -> Text -- ^ Hash of admin password -> Maybe Seconds -- ^ Expire -> m SimpleToken signinByHashUnsafe login pass mexpire = do WithField uid UserImpl{..} <- guardLogin login pass getAuthToken uid mexpire where guardLogin login pass = do -- check login and password, return passed user muser <- getUserImplByLogin login let err = throw401 "Cannot find user with given combination of login and pass" case muser of Nothing -> err Just user@(WithField _ UserImpl{..}) -> if pass == userImplPassword then return user else err
ivan-m/servant-auth-token
src/Servant/Server/Auth/Token.hs
bsd-3-clause
22,943
0
26
4,462
4,855
2,399
2,456
-1
-1
module Main (main) where import qualified Distribution.ModuleName as ModuleName import Distribution.PackageDescription import Distribution.PackageDescription.Check hiding (doesFileExist) import Distribution.PackageDescription.Configuration import Distribution.PackageDescription.Parse import Distribution.Package import Distribution.System import Distribution.Simple import Distribution.Simple.Configure import Distribution.Simple.LocalBuildInfo import Distribution.Simple.GHC import Distribution.Simple.Program import Distribution.Simple.Program.HcPkg import Distribution.Simple.Setup (ConfigFlags(configStripLibs), fromFlag, toFlag) import Distribution.Simple.Utils (defaultPackageDesc, writeFileAtomic, toUTF8) import Distribution.Simple.Build (writeAutogenFiles) import Distribution.Simple.Register import Distribution.Text import Distribution.Verbosity import qualified Distribution.InstalledPackageInfo as Installed import qualified Distribution.Simple.PackageIndex as PackageIndex import Control.Exception (bracket) import Control.Monad import qualified Data.ByteString.Lazy.Char8 as BS import Data.List import Data.Maybe import System.IO import System.Directory import System.Environment import System.Exit (exitWith, ExitCode(..)) import System.FilePath main :: IO () main = do hSetBuffering stdout LineBuffering args <- getArgs case args of "hscolour" : dir : distDir : args' -> runHsColour dir distDir args' "check" : dir : [] -> doCheck dir "copy" : dir : distDir : strip : myDestDir : myPrefix : myLibdir : myDocdir : ghcLibWays : args' -> doCopy dir distDir strip myDestDir myPrefix myLibdir myDocdir ("dyn" `elem` words ghcLibWays) args' "register" : dir : distDir : ghc : ghcpkg : topdir : myDestDir : myPrefix : myLibdir : myDocdir : relocatableBuild : args' -> doRegister dir distDir ghc ghcpkg topdir myDestDir myPrefix myLibdir myDocdir relocatableBuild args' "configure" : dir : distDir : dll0Modules : config_args -> generate dir distDir dll0Modules config_args "sdist" : dir : distDir : [] -> doSdist dir distDir ["--version"] -> defaultMainArgs ["--version"] _ -> die syntax_error syntax_error :: [String] syntax_error = ["syntax: ghc-cabal configure <configure-args> -- <distdir> <directory>...", " ghc-cabal install <ghc-pkg> <directory> <distdir> <destdir> <prefix> <args>...", " ghc-cabal hscolour <distdir> <directory> <args>..."] die :: [String] -> IO a die errs = do mapM_ (hPutStrLn stderr) errs exitWith (ExitFailure 1) withCurrentDirectory :: FilePath -> IO a -> IO a withCurrentDirectory directory io = bracket (getCurrentDirectory) (setCurrentDirectory) (const (setCurrentDirectory directory >> io)) -- We need to use the autoconfUserHooks, as the packages that use -- configure can create a .buildinfo file, and we need any info that -- ends up in it. userHooks :: UserHooks userHooks = autoconfUserHooks runDefaultMain :: IO () runDefaultMain = do let verbosity = normal gpdFile <- defaultPackageDesc verbosity gpd <- readPackageDescription verbosity gpdFile case buildType (flattenPackageDescription gpd) of Just Configure -> defaultMainWithHooks autoconfUserHooks -- time has a "Custom" Setup.hs, but it's actually Configure -- plus a "./Setup test" hook. However, Cabal is also -- "Custom", but doesn't have a configure script. Just Custom -> do configureExists <- doesFileExist "configure" if configureExists then defaultMainWithHooks autoconfUserHooks else defaultMain -- not quite right, but good enough for us: _ -> defaultMain doSdist :: FilePath -> FilePath -> IO () doSdist directory distDir = withCurrentDirectory directory $ withArgs (["sdist", "--builddir", distDir]) runDefaultMain doCheck :: FilePath -> IO () doCheck directory = withCurrentDirectory directory $ do let verbosity = normal gpdFile <- defaultPackageDesc verbosity gpd <- readPackageDescription verbosity gpdFile case filter isFailure $ checkPackage gpd Nothing of [] -> return () errs -> mapM_ print errs >> exitWith (ExitFailure 1) where isFailure (PackageDistSuspicious {}) = False isFailure (PackageDistSuspiciousWarn {}) = False isFailure _ = True runHsColour :: FilePath -> FilePath -> [String] -> IO () runHsColour directory distdir args = withCurrentDirectory directory $ defaultMainArgs ("hscolour" : "--builddir" : distdir : args) doCopy :: FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> Bool -> [String] -> IO () doCopy directory distDir strip myDestDir myPrefix myLibdir myDocdir withSharedLibs args = withCurrentDirectory directory $ do let copyArgs = ["copy", "--builddir", distDir] ++ (if null myDestDir then [] else ["--destdir", myDestDir]) ++ args copyHooks = userHooks { copyHook = noGhcPrimHook $ modHook False $ copyHook userHooks } defaultMainWithHooksArgs copyHooks copyArgs where noGhcPrimHook f pd lbi us flags = let pd' | packageName pd == PackageName "ghc-prim" = case library pd of Just lib -> let ghcPrim = fromJust (simpleParse "GHC.Prim") ems = filter (ghcPrim /=) (exposedModules lib) lib' = lib { exposedModules = ems } in pd { library = Just lib' } Nothing -> error "Expected a library, but none found" | otherwise = pd in f pd' lbi us flags modHook relocatableBuild f pd lbi us flags = do let verbosity = normal idts = updateInstallDirTemplates relocatableBuild myPrefix myLibdir myDocdir (installDirTemplates lbi) progs = withPrograms lbi stripProgram' = stripProgram { programFindLocation = \_ _ -> return (Just strip) } progs' <- configureProgram verbosity stripProgram' progs let lbi' = lbi { withPrograms = progs', installDirTemplates = idts, configFlags = cfg, stripLibs = fromFlag (configStripLibs cfg), withSharedLib = withSharedLibs } -- This hack allows to interpret the "strip" -- command-line argument being set to ':' to signify -- disabled library stripping cfg | strip == ":" = (configFlags lbi) { configStripLibs = toFlag False } | otherwise = configFlags lbi f pd lbi' us flags doRegister :: FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> FilePath -> String -> [String] -> IO () doRegister directory distDir ghc ghcpkg topdir myDestDir myPrefix myLibdir myDocdir relocatableBuildStr args = withCurrentDirectory directory $ do relocatableBuild <- case relocatableBuildStr of "YES" -> return True "NO" -> return False _ -> die ["Bad relocatableBuildStr: " ++ show relocatableBuildStr] let regArgs = "register" : "--builddir" : distDir : args regHooks = userHooks { regHook = modHook relocatableBuild $ regHook userHooks } defaultMainWithHooksArgs regHooks regArgs where modHook relocatableBuild f pd lbi us flags = do let verbosity = normal idts = updateInstallDirTemplates relocatableBuild myPrefix myLibdir myDocdir (installDirTemplates lbi) progs = withPrograms lbi ghcpkgconf = topdir </> "package.conf.d" ghcProgram' = ghcProgram { programPostConf = \_ cp -> return cp { programDefaultArgs = ["-B" ++ topdir] }, programFindLocation = \_ _ -> return (Just ghc) } ghcPkgProgram' = ghcPkgProgram { programPostConf = \_ cp -> return cp { programDefaultArgs = ["--global-package-db", ghcpkgconf] ++ ["--force" | not (null myDestDir) ] }, programFindLocation = \_ _ -> return (Just ghcpkg) } configurePrograms ps conf = foldM (flip (configureProgram verbosity)) conf ps progs' <- configurePrograms [ghcProgram', ghcPkgProgram'] progs instInfos <- dump (hcPkgInfo progs') verbosity GlobalPackageDB let installedPkgs' = PackageIndex.fromList instInfos let updateComponentConfig (cn, clbi, deps) = (cn, updateComponentLocalBuildInfo clbi, deps) updateComponentLocalBuildInfo clbi = clbi { componentPackageDeps = [ (fixupPackageId instInfos ipid, pid) | (ipid,pid) <- componentPackageDeps clbi ] } ccs' = map updateComponentConfig (componentsConfigs lbi) lbi' = lbi { componentsConfigs = ccs', installedPkgs = installedPkgs', installDirTemplates = idts, withPrograms = progs' } f pd lbi' us flags updateInstallDirTemplates :: Bool -> FilePath -> FilePath -> FilePath -> InstallDirTemplates -> InstallDirTemplates updateInstallDirTemplates relocatableBuild myPrefix myLibdir myDocdir idts = idts { prefix = toPathTemplate $ if relocatableBuild then "$topdir" else myPrefix, libdir = toPathTemplate $ if relocatableBuild then "$topdir" else myLibdir, libsubdir = toPathTemplate "$libname", docdir = toPathTemplate $ if relocatableBuild then "$topdir/../doc/html/libraries/$pkgid" else (myDocdir </> "$pkgid"), htmldir = toPathTemplate "$docdir" } -- The packages are built with the package ID ending in "-inplace", but -- when they're installed they get the package hash appended. We need to -- fix up the package deps so that they use the hash package IDs, not -- the inplace package IDs. fixupPackageId :: [Installed.InstalledPackageInfo] -> InstalledPackageId -> InstalledPackageId fixupPackageId _ x@(InstalledPackageId ipi) | "builtin_" `isPrefixOf` ipi = x fixupPackageId ipinfos (InstalledPackageId ipi) = case stripPrefix (reverse "-inplace") $ reverse ipi of Nothing -> error ("Installed package ID doesn't end in -inplace: " ++ show ipi) Just x -> let ipi' = reverse ('-' : x) f (ipinfo : ipinfos') = case Installed.installedPackageId ipinfo of y@(InstalledPackageId ipinfoid) | ipi' `isPrefixOf` ipinfoid -> y _ -> f ipinfos' f [] = error ("Installed package ID not registered: " ++ show ipi) in f ipinfos -- On Windows we need to split the ghc package into 2 pieces, or the -- DLL that it makes contains too many symbols (#5987). There are -- therefore 2 libraries, not just the 1 that Cabal assumes. mangleLbi :: FilePath -> FilePath -> LocalBuildInfo -> LocalBuildInfo mangleLbi "compiler" "stage2" lbi | isWindows = let ccs' = [ (cn, updateComponentLocalBuildInfo clbi, cns) | (cn, clbi, cns) <- componentsConfigs lbi ] updateComponentLocalBuildInfo clbi@(LibComponentLocalBuildInfo {}) = let cls' = concat [ [ LibraryName n, LibraryName (n ++ "-0") ] | LibraryName n <- componentLibraries clbi ] in clbi { componentLibraries = cls' } updateComponentLocalBuildInfo clbi = clbi in lbi { componentsConfigs = ccs' } where isWindows = case hostPlatform lbi of Platform _ Windows -> True _ -> False mangleLbi _ _ lbi = lbi generate :: FilePath -> FilePath -> String -> [String] -> IO () generate directory distdir dll0Modules config_args = withCurrentDirectory directory $ do let verbosity = normal -- XXX We shouldn't just configure with the default flags -- XXX And this, and thus the "getPersistBuildConfig distdir" below, -- aren't going to work when the deps aren't built yet withArgs (["configure", "--distdir", distdir] ++ config_args) runDefaultMain lbi0 <- getPersistBuildConfig distdir let lbi = mangleLbi directory distdir lbi0 pd0 = localPkgDescr lbi writePersistBuildConfig distdir lbi hooked_bi <- if (buildType pd0 == Just Configure) || (buildType pd0 == Just Custom) then do maybe_infoFile <- defaultHookedPackageDesc case maybe_infoFile of Nothing -> return emptyHookedBuildInfo Just infoFile -> readHookedBuildInfo verbosity infoFile else return emptyHookedBuildInfo let pd = updatePackageDescription hooked_bi pd0 -- generate Paths_<pkg>.hs and cabal-macros.h writeAutogenFiles verbosity pd lbi -- generate inplace-pkg-config withLibLBI pd lbi $ \lib clbi -> do cwd <- getCurrentDirectory let ipid = InstalledPackageId (display (packageId pd) ++ "-inplace") let installedPkgInfo = inplaceInstalledPackageInfo cwd distdir pd ipid lib lbi clbi final_ipi = installedPkgInfo { Installed.installedPackageId = ipid, Installed.haddockHTMLs = [] } content = Installed.showInstalledPackageInfo final_ipi ++ "\n" writeFileAtomic (distdir </> "inplace-pkg-config") (BS.pack $ toUTF8 content) let comp = compiler lbi libBiModules lib = (libBuildInfo lib, libModules lib) exeBiModules exe = (buildInfo exe, ModuleName.main : exeModules exe) biModuless = (maybeToList $ fmap libBiModules $ library pd) ++ (map exeBiModules $ executables pd) buildableBiModuless = filter isBuildable biModuless where isBuildable (bi', _) = buildable bi' (bi, modules) = case buildableBiModuless of [] -> error "No buildable component found" [biModules] -> biModules _ -> error ("XXX ghc-cabal can't handle " ++ "more than one buildinfo yet") -- XXX Another Just... Just ghcProg = lookupProgram ghcProgram (withPrograms lbi) dep_pkgs = PackageIndex.topologicalOrder (packageHacks (installedPkgs lbi)) forDeps f = concatMap f dep_pkgs -- copied from Distribution.Simple.PreProcess.ppHsc2Hs packageHacks = case compilerFlavor (compiler lbi) of GHC -> hackRtsPackage _ -> id -- We don't link in the actual Haskell libraries of our -- dependencies, so the -u flags in the ldOptions of the rts -- package mean linking fails on OS X (it's ld is a tad -- stricter than gnu ld). Thus we remove the ldOptions for -- GHC's rts package: hackRtsPackage index = case PackageIndex.lookupPackageName index (PackageName "rts") of [(_,[rts])] -> PackageIndex.insert rts{ Installed.ldOptions = [], Installed.libraryDirs = filter (not . ("gcc-lib" `isSuffixOf`)) (Installed.libraryDirs rts)} index -- GHC <= 6.12 had $topdir/gcc-lib in their -- library-dirs for the rts package, which causes -- problems when we try to use the in-tree mingw, -- due to accidentally picking up the incompatible -- libraries there. So we filter out gcc-lib from -- the RTS's library-dirs here. _ -> error "No (or multiple) ghc rts package is registered!!" dep_ids = map snd (externalPackageDeps lbi) deps = map display dep_ids dep_direct = map (fromMaybe (error "ghc-cabal: dep_keys failed") . PackageIndex.lookupInstalledPackageId (installedPkgs lbi) . fst) . externalPackageDeps $ lbi dep_ipids = map (display . Installed.installedPackageId) dep_direct depLibNames | packageKeySupported comp = map (\p -> packageKeyLibraryName (Installed.sourcePackageId p) (Installed.packageKey p)) dep_direct | otherwise = deps depNames = map (display . packageName) dep_ids transitive_dep_ids = map Installed.sourcePackageId dep_pkgs transitiveDeps = map display transitive_dep_ids transitiveDepLibNames | packageKeySupported comp = map (\p -> packageKeyLibraryName (Installed.sourcePackageId p) (Installed.packageKey p)) dep_pkgs | otherwise = transitiveDeps transitiveDepNames = map (display . packageName) transitive_dep_ids libraryDirs = forDeps Installed.libraryDirs -- The mkLibraryRelDir function is a bit of a hack. -- Ideally it should be handled in the makefiles instead. mkLibraryRelDir "rts" = "rts/dist/build" mkLibraryRelDir "ghc" = "compiler/stage2/build" mkLibraryRelDir "Cabal" = "libraries/Cabal/Cabal/dist-install/build" mkLibraryRelDir l = "libraries/" ++ l ++ "/dist-install/build" libraryRelDirs = map mkLibraryRelDir transitiveDepNames wrappedIncludeDirs <- wrap $ forDeps Installed.includeDirs wrappedLibraryDirs <- wrap libraryDirs let variablePrefix = directory ++ '_':distdir mods = map display modules otherMods = map display (otherModules bi) allMods = mods ++ otherMods let xs = [variablePrefix ++ "_VERSION = " ++ display (pkgVersion (package pd)), variablePrefix ++ "_PACKAGE_KEY = " ++ display (pkgKey lbi), -- copied from mkComponentsLocalBuildInfo variablePrefix ++ "_LIB_NAME = " ++ packageKeyLibraryName (package pd) (pkgKey lbi), variablePrefix ++ "_MODULES = " ++ unwords mods, variablePrefix ++ "_HIDDEN_MODULES = " ++ unwords otherMods, variablePrefix ++ "_SYNOPSIS =" ++ synopsis pd, variablePrefix ++ "_HS_SRC_DIRS = " ++ unwords (hsSourceDirs bi), variablePrefix ++ "_DEPS = " ++ unwords deps, variablePrefix ++ "_DEP_IPIDS = " ++ unwords dep_ipids, variablePrefix ++ "_DEP_NAMES = " ++ unwords depNames, variablePrefix ++ "_DEP_LIB_NAMES = " ++ unwords depLibNames, variablePrefix ++ "_TRANSITIVE_DEPS = " ++ unwords transitiveDeps, variablePrefix ++ "_TRANSITIVE_DEP_LIB_NAMES = " ++ unwords transitiveDepLibNames, variablePrefix ++ "_TRANSITIVE_DEP_NAMES = " ++ unwords transitiveDepNames, variablePrefix ++ "_INCLUDE_DIRS = " ++ unwords (includeDirs bi), variablePrefix ++ "_INCLUDES = " ++ unwords (includes bi), variablePrefix ++ "_INSTALL_INCLUDES = " ++ unwords (installIncludes bi), variablePrefix ++ "_EXTRA_LIBRARIES = " ++ unwords (extraLibs bi), variablePrefix ++ "_EXTRA_LIBDIRS = " ++ unwords (extraLibDirs bi), variablePrefix ++ "_C_SRCS = " ++ unwords (cSources bi), variablePrefix ++ "_CMM_SRCS := $(addprefix cbits/,$(notdir $(wildcard " ++ directory ++ "/cbits/*.cmm)))", variablePrefix ++ "_DATA_FILES = " ++ unwords (dataFiles pd), -- XXX This includes things it shouldn't, like: -- -odir dist-bootstrapping/build variablePrefix ++ "_HC_OPTS = " ++ escape (unwords ( programDefaultArgs ghcProg ++ hcOptions GHC bi ++ languageToFlags (compiler lbi) (defaultLanguage bi) ++ extensionsToFlags (compiler lbi) (usedExtensions bi) ++ programOverrideArgs ghcProg)), variablePrefix ++ "_CC_OPTS = " ++ unwords (ccOptions bi), variablePrefix ++ "_CPP_OPTS = " ++ unwords (cppOptions bi), variablePrefix ++ "_LD_OPTS = " ++ unwords (ldOptions bi), variablePrefix ++ "_DEP_INCLUDE_DIRS_SINGLE_QUOTED = " ++ unwords wrappedIncludeDirs, variablePrefix ++ "_DEP_CC_OPTS = " ++ unwords (forDeps Installed.ccOptions), variablePrefix ++ "_DEP_LIB_DIRS_SINGLE_QUOTED = " ++ unwords wrappedLibraryDirs, variablePrefix ++ "_DEP_LIB_DIRS_SEARCHPATH = " ++ mkSearchPath libraryDirs, variablePrefix ++ "_DEP_LIB_REL_DIRS = " ++ unwords libraryRelDirs, variablePrefix ++ "_DEP_LIB_REL_DIRS_SEARCHPATH = " ++ mkSearchPath libraryRelDirs, variablePrefix ++ "_DEP_EXTRA_LIBS = " ++ unwords (forDeps Installed.extraLibraries), variablePrefix ++ "_DEP_LD_OPTS = " ++ unwords (forDeps Installed.ldOptions), variablePrefix ++ "_BUILD_GHCI_LIB = " ++ boolToYesNo (withGHCiLib lbi), "", -- Sometimes we need to modify the automatically-generated package-data.mk -- bindings in a special way for the GHC build system, so allow that here: "$(eval $(" ++ directory ++ "_PACKAGE_MAGIC))" ] writeFile (distdir ++ "/package-data.mk") $ unlines xs writeFileUtf8 (distdir ++ "/haddock-prologue.txt") $ if null (description pd) then synopsis pd else description pd unless (null dll0Modules) $ do let dll0Mods = words dll0Modules dllMods = allMods \\ dll0Mods dllModSets = map unwords [dll0Mods, dllMods] writeFile (distdir ++ "/dll-split") $ unlines dllModSets where escape = foldr (\c xs -> if c == '#' then '\\':'#':xs else c:xs) [] wrap = mapM wrap1 wrap1 s | null s = die ["Wrapping empty value"] | '\'' `elem` s = die ["Single quote in value to be wrapped:", s] -- We want to be able to assume things like <space><quote> is the -- start of a value, so check there are no spaces in confusing -- positions | head s == ' ' = die ["Leading space in value to be wrapped:", s] | last s == ' ' = die ["Trailing space in value to be wrapped:", s] | otherwise = return ("\'" ++ s ++ "\'") mkSearchPath = intercalate [searchPathSeparator] boolToYesNo True = "YES" boolToYesNo False = "NO" -- | Version of 'writeFile' that always uses UTF8 encoding writeFileUtf8 f txt = withFile f WriteMode $ \hdl -> do hSetEncoding hdl utf8 hPutStr hdl txt
urbanslug/ghc
utils/ghc-cabal/Main.hs
bsd-3-clause
25,443
0
23
9,169
5,049
2,581
2,468
419
13
-- | This is a very simple project containing a few code style checks for use -- in git hooks for the Snap Framework. Hopefully we'll get some more -- sophisticated checks and automatic fixes implemented eventually. {-# LANGUAGE DeriveDataTypeable #-} module Main ( main ) where import Control.Applicative ((<$>)) import System.Exit (ExitCode (..), exitWith) import System.Console.CmdArgs import HStyle -- | CmdArgs-enabled data-type data HStyle = HStyle { fix :: Bool , quiet :: Bool , files :: [FilePath] } deriving (Show, Data, Typeable) -- | CmdArgs configuration hstyle :: HStyle hstyle = HStyle { fix = def &= help "Automatically fix (some) problems" , quiet = def &= help "Print less output" , files = def &= args } -- | Simple main that takes one command-line parameter of "check" or "fix" and -- a list of files to be checked. main :: IO () main = do config <- cmdArgs hstyle ok <- all fileOk <$> mapM (checkStyle $ quiet config) (files config) exitWith $ if ok then ExitSuccess else ExitFailure 1
mightybyte/hstyle
src/Main.hs
bsd-3-clause
1,070
0
12
237
226
130
96
22
2
-- !!! Testing (List.\\) and related functions module T where import List( deleteBy, delete, (\\) ) test1 :: [Int] test1 = deleteBy (==) 1 [0,1,1,2,3,4] test2 :: [Int] test2 = delete 1 [0,1,1,2,3,4] test3 :: [Int] test3 = [0,1,1,2,3,4] \\ [3,2,1]
FranklinChen/Hugs
tests/libs/list1.hs
bsd-3-clause
252
0
6
46
141
90
51
8
1
module Core ( -- * Vital datatypes Board(..), Player, Slot(..), SlotNr, Vitality, Field(..), Card(..), -- * Vital datatypes dead, alive, size, -- * Constants emptyBoard, initialSlot, deadSlot, -- * The Result monad Result, -- * Helper functions showIndexedSlot ) where import Control.Monad.Identity import Control.Monad.Error import Control.Monad.State import qualified Data.Vector as V data Board = Board { zombieMode :: Bool , applications :: Int , proponent :: Player , opponent :: Player } deriving Show type Player = V.Vector Slot data Slot = Slot { field :: Field, vitality :: Vitality } instance Show Slot where show (Slot f v) = show f ++ " {" ++ show v ++ "}" showIndexedSlot :: Int -> Slot -> String showIndexedSlot _ (Slot (Card I) 10000) = "" showIndexedSlot i slot = "[" ++ show i ++ "] " ++ show slot -- | Index of slot between 0 and 255 type SlotNr = Int type Vitality = Int type Result = StateT Board (ErrorT String Identity) data Field = Value Int | Card Card | Papp1 Card Field | Papp2 Card Field Field deriving Eq instance Show Field where show (Value x) = show x show (Card c) = show c show (Papp1 c x) = show c ++ " (" ++ show x ++ ")" show (Papp2 c x y) = show c ++ " (" ++ show x ++ ")" ++ " (" ++ show y ++ ")" data Card = I | Zero | Succ | Dbl | Get | Put | S | K | Inc | Dec | Attack | Help | Copy | Revive | Zombie deriving Eq instance Show Card where show I = "I" show Zero = "zero" show Succ = "succ" show Dbl = "dbl" show Get = "get" show Put = "put" show S = "S" show K = "K" show Inc = "inc" show Dec = "dec" show Attack = "attack" show Help = "help" show Copy = "copy" show Revive = "revive" show Zombie = "zombie" instance Read Card where readsPrec _ = f where f "I" = [(I, "")] f "zero" = [(Zero, "")] f "succ" = [(Succ, "")] f "dbl" = [(Dbl, "")] f "get" = [(Get, "")] f "put" = [(Put, "")] f "S" = [(S, "")] f "K" = [(K, "")] f "inc" = [(Inc, "")] f "dec" = [(Dec, "")] f "attack" = [(Attack, "")] f "help" = [(Help, "")] f "copy" = [(Copy, "")] f "revive" = [(Revive, "")] f "zombie" = [(Zombie, "")] f _ = [] dead :: Slot -> Bool dead (Slot _ x) = x == -1 || x == 0 alive :: Slot -> Bool alive = not . dead emptyBoard :: Board emptyBoard = Board { zombieMode = False, applications = 0, proponent = emptyPlayer, opponent = emptyPlayer } where emptyPlayer = V.replicate 256 initialSlot initialSlot :: Slot initialSlot = Slot (Card I) 10000 deadSlot :: Slot deadSlot = Slot (Card I) 0 size :: Field -> Int size (Value _) = 0 size (Card _) = 1 size (Papp1 _ f) = 1 + size f size (Papp2 _ f1 f2) = 1 + size f1 + size f2
sjoerdvisscher/icfp2011
src/Core.hs
bsd-3-clause
3,018
0
12
996
1,169
650
519
107
1
module LeastSquares ( VarName , LinExpr(..) , LinContr(..) , QuadExpr(..) , minimize ) where import Data.List (elemIndex, foldl1') import qualified Data.Map.Strict as M import Data.Maybe (fromJust) import qualified Data.Set as S import Numeric.LinearAlgebra type VarName = String type CanonicalMap = M.Map VarName (Matrix R) infix 4 :==: data LinExpr = Var VarName Int | Coeff R | Vec (Vector R) | Mat (Matrix R) | Neg LinExpr | Sum LinExpr LinExpr | Prod LinExpr LinExpr deriving (Show, Eq) instance Num LinExpr where (+) = Sum a - b = Sum a (Neg b) (*) = Prod negate = Neg signum = undefined abs = undefined fromInteger a = Coeff (fromInteger a) data LinContr = LinExpr :==: LinExpr data QuadExpr = SumSquares LinExpr | CoeffQuad R | ProdQuad QuadExpr QuadExpr | SumQuad QuadExpr QuadExpr instance Num QuadExpr where (+) = SumQuad (*) = ProdQuad (-) = undefined negate = undefined signum = undefined abs = undefined fromInteger a = CoeffQuad (fromInteger a) class CanonExpr e where varSet :: e -> S.Set (VarName, Int) canonicalize :: e -> CanonicalMap -- Canonicalize a generic expression -- The vector is stored as a column matrix under the variable "". instance CanonExpr LinExpr where varSet (Var v s) = S.singleton (v, s) varSet (Coeff _) = S.empty varSet (Vec _) = S.empty varSet (Mat _) = S.empty varSet (Neg e) = varSet e varSet (Prod _ e) = varSet e varSet (Sum e1 e2) = varSet e1 `S.union` varSet e2 canonicalize (Var v s) = M.singleton v (ident s) canonicalize (Vec v) = M.singleton "" (asColumn v) canonicalize (Neg e) = M.map negate $ canonicalize e canonicalize (Prod (Coeff c) e) = M.map (scale c) $ canonicalize e canonicalize (Prod (Mat m) e) = M.map (m <>) $ canonicalize e canonicalize (Sum e1 e2) = M.unionWith (+) (canonicalize e1) (canonicalize e2) canonicalize _ = error "Expression is not well-formed" -- Canonicalize an expression in the constraint instance CanonExpr LinContr where varSet (e1 :==: e2) = varSet e1 `S.union` varSet e2 canonicalize (e1 :==: e2) = canonicalize (e1 - e2) -- Canonicalize an expression in the objective, which consists of SumSquares. instance CanonExpr QuadExpr where varSet (SumSquares e) = varSet e varSet (CoeffQuad _) = S.empty varSet (ProdQuad _ e) = varSet e varSet (SumQuad e1 e2) = varSet e1 `S.union` varSet e2 canonicalize (SumSquares e) = canonicalize e canonicalize (ProdQuad (CoeffQuad c) e) = M.map (scale (sqrt c)) $ canonicalize e canonicalize (SumQuad e1 e2) = canonicalize e1 `vstack` canonicalize e2 canonicalize _ = error "Expression is not well-formed" -- Combine two canonical maps by stacking one on top of another. vstack :: CanonicalMap -> CanonicalMap -> CanonicalMap vstack m1 m2 = M.fromSet combine (M.keysSet m1 `S.union` M.keysSet m2) where combine k = lookupDefault k m1 === lookupDefault k m2 lookupDefault k m = M.findWithDefault (konst 0 (firstDim m, 1)) k m firstDim = rows . snd . fromJust . M.lookupGE "" :: CanonicalMap -> Int minimize :: QuadExpr -> [LinContr] -> M.Map VarName (Vector R) minimize obj [] = unpack vars $ a <\> (-b) where (a,b) = pack vars . canonicalize $ obj vars = varSet obj minimize obj constraints = unpack vars $ mat <\> (-vec) where mat = fromBlocks [[2 * tr a <> a, tr c], [c, 0]] vec = vjoin [2 * tr a #> b, d] (a,b) = pack vars . canonicalize $ obj (c,d) = pack vars $ foldl1' vstack cds cds = map canonicalize constraints vars = varSet obj `S.union` S.unions (map varSet constraints) pack :: S.Set (VarName, Int) -> CanonicalMap -> (Matrix R, Vector R) pack vars m = (a, b) where a = fromBlocks [map getCoefficient (S.toAscList vars)] b = flatten $ M.findWithDefault (konst 0 (rows a, 1)) "" m getCoefficient (varName,s) = M.findWithDefault (konst 0 (s, s)) varName m -- The vector given to unpack might be longer than the total size of the -- variables. It might contain the dual variable values, for example. unpack :: S.Set (VarName, Int) -> Vector R -> M.Map VarName (Vector R) unpack vars result = M.fromList $ zip varNames coefficients where coefficients = map getCoefficient varList getCoefficient (varName,s) = subVector (startIndex varName) s result startIndex varName = cumsum !! fromJust (elemIndex varName varNames) cumsum = scanl (+) 0 varSizes (varNames,varSizes) = unzip varList varList = S.toAscList vars
tridao/leastsquares
src/LeastSquares.hs
bsd-3-clause
4,685
0
12
1,162
1,730
905
825
104
1
{-# LANGUAGE RecursiveDo #-} module Main where import Game.GoreAndAsh.Core import Game.GoreAndAsh.Console import Data.Proxy import Control.Monad.IO.Class import Control.Monad.Except import Control.Monad.Catch type AppMonad = GMSpider app :: MonadGame t m => m () app = mdo e <- consolePromptForever' "Enter a string: " (void printedE) printedE <- consolePutLn $ fmap ("You entered: " ++) e pure () main :: IO () main = runGM (app :: AppMonad ())
Teaspot-Studio/gore-and-ash-logging
examples/Example02.hs
bsd-3-clause
456
0
10
76
146
80
66
16
1
module Set ( Set , all , isSubsetOf , empty , exists , insert , singleton , member , fromList , toList , intersection , union , null ) where import Prelude hiding (all, null) import qualified Data.Set data Set a = FiniteSet (Data.Set.Set a) | All deriving (Eq, Show) instance Ord a => Ord (Set a) where _ <= All = True (FiniteSet s1) <= (FiniteSet s2) = s1 <= s2 All <= (FiniteSet _) = False all :: Set a all = All member :: Ord a => a -> Set a -> Bool member _ All = True member x (FiniteSet s) = x `Data.Set.member` s singleton :: a -> Set a singleton x = FiniteSet (Data.Set.singleton x) isSubsetOf :: Ord a => Set a -> Set a -> Bool isSubsetOf (FiniteSet s1) (FiniteSet s2) = Data.Set.isSubsetOf s1 s2 isSubsetOf _ All = True isSubsetOf All (FiniteSet _) = False intersection :: Ord a => Set a -> Set a -> Set a intersection (FiniteSet s1) (FiniteSet s2) = FiniteSet (Data.Set.intersection s1 s2) intersection (FiniteSet s1) All = (FiniteSet s1) intersection All (FiniteSet s2) = (FiniteSet s2) intersection All All = All union :: Ord a => Set a -> Set a -> Set a union (FiniteSet s1) (FiniteSet s2) = FiniteSet (Data.Set.union s1 s2) union All _ = All union _ All = All empty :: Set a empty = FiniteSet Data.Set.empty exists :: Ord a => (a -> Bool) -> Set a -> Bool exists f All = True exists f (FiniteSet s) = any f (Data.Set.toList s) insert :: Ord a => a -> Set a -> Set a insert a (FiniteSet s) = FiniteSet (Data.Set.insert a s) insert a All = All fromList lst = (FiniteSet (Data.Set.fromList lst)) toList All = Nothing toList (FiniteSet s) = Just (Data.Set.toList s) null :: Set a -> Bool null All = False null (FiniteSet s) = Data.Set.null s
brownsys/pane
src/Set.hs
bsd-3-clause
1,759
0
9
428
813
415
398
59
1
module NAA.AI where import Data.Array.Diff import Data.List.Extras.Argmax import NAA.Data import NAA.Logic import NAA.State type Score = Integer -- The unbeatable AI ------------------------- -- Based on a simple mini-max algorithm. -- Scoring is based on the number of ways that a given a particular unbeatableAI :: GameState -> IO Move unbeatableAI gs@(GameState {computer=me,boardState=bs}) = return $ argmax (score me . apply bs) $ validMoves bs -- Minimax -- -------------- -- We don't know who our opponent is, but we assume the most pessimistic case: -- that he is very able, and has the capability of selecting (consistently) a -- move that would minimise the score for our player. -- -- nextPly computes all of the boards that can be reached from the current board -- state. If the Board is at an endgame, then no next board states are created. nextPly :: BoardState -> [BoardState] nextPly bs = zipWith apply (repeat bs) (validMoves bs) -- Returns all the valid moves from the given BoardState. validMoves :: BoardState -> [Move] validMoves (BoardState {board=brd,turn=plyr}) = zip (repeat plyr) (emptyCells brd) where emptyCells :: Board -> [Idx2D] emptyCells (Board brd) = map fst $ filter ((==Empty) . snd) $ assocs brd -- The 'score' of some Board b is simply the sum of 'scores' of child boards. -- It is a heuristic based on the immediate capability to win (scores 10^9), and -- if not, the indirect capability to win. Positive integers represent the -- possibility of winning and the negative integers represent the possibility of -- the opponent winning. -- -- The score of a winning board is MAXSCORE; the score of a losing board is -- MINSCORE. -- The score of a board that has no endgame judgement is the sum of the -- of the scores of the boards in the next ply NEGATED and NORMALISED by /9. score :: Player -> BoardState -> Score score p bs@(BoardState {board=theBoard,turn=p'}) = case judge theBoard of Nothing -> (`div` 9) . negate . sum $ map (score (other p)) (nextPly bs) Just Draw -> 0 Just (Win p') -> if p == p' then maxScore else -maxScore Just (Invalid _) -> error "score: Invalid board configuration" where maxScore = 9^9 -- Let's use the FGL to construct a graph of moves. Then we could write an -- inductive algorithm to find the branch with the most number of wins or -- something.
fatuhoku/haskell-noughts-and-crosses
src/NAA/AI.hs
bsd-3-clause
2,377
0
13
457
449
252
197
24
5
module CollisionSpec where import Test.Hspec import qualified Collision as Collision main :: IO () main = hspec spec spec :: Spec spec = do describe "all" $ do it "returns []" $ -- --.. -- ..-- Collision.all (0, 1) (2, 3) `shouldBe` [] it "returns [Arbl]" $ -- .--. -- ..-- Collision.all (1, 2) (2, 3) `shouldBe` [Collision.Arbl] it "returns [Arbl, Albr, Acbw, Awbc]" $ -- ..-- -- ..-- Collision.all (2, 3) (2, 3) `shouldBe` [Collision.Awbw] it "returns [Albr, Acbw]" $ -- ..--- -- ..--. Collision.all (2, 4) (2, 3) `shouldBe` [Collision.Albr, Collision.Acbw] it "returns [Arbl, Acbw]" $ -- ..--- -- ...-- Collision.all (2, 4) (3, 4) `shouldBe` [Collision.Arbl, Collision.Acbw] it "returns [Acbw]" $ -- ..---- -- ...--. Collision.all (2, 5) (3, 4) `shouldBe` [Collision.Acbw] it "returns [Awbc]" $ -- ...--. -- ..---- Collision.all (3, 4) (2, 5) `shouldBe` [Collision.Awbc] describe "first" $ do it "returns []" $ -- --.. -- ..-- Collision.first (0, 1) (2, 3) `shouldBe` [] it "returns [Arbl]" $ -- ..--- -- ...-- Collision.first (2, 4) (3, 4) `shouldBe` [Collision.Arbl] describe "any" $ do it "returns False" $ -- --.. -- ..-- Collision.any (0, 1) (2, 3) `shouldBe` False it "returns True" $ -- ..--- -- ...-- Collision.any (2, 4) (3, 4) `shouldBe` True
dariush-alipour/kanoon-hs
test/CollisionSpec.hs
bsd-3-clause
1,474
0
13
426
529
298
231
32
1
{-# OPTIONS_GHC -fno-warn-type-defaults #-} -- ExtendedDefaultRules lets us us the usual operators without having to specify the types of literal numbers. {-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTSyntax #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Tower.Examples where -- `Tower.Prelude` is a drop-in replacement for `Prelude`. Behind the scenes, it wraps `Protolude`. import Tower.Prelude -- * Integrals -- -- | -- >>> zero == 0 -- True -- -- prop \a -> a + 0 == a -- True -- prop \a -> 0 + a == a -- True -- -- | Additive -- -- >>> 1 + 1 -- 2 -- -- | -- >>> 1 - 1 -- 0 -- -- | -- >>> 1 * 1 -- 1 -- -- | -- >>> 1 / 1 -- 1.0 -- -- Integrals should error on application of (/) -- | -- >>> 1 / (1::Int) -- ... -- ... No instance for (MultiplicativeGroup Int) -- ... arising from a use of ‘/’ -- ... -- -- | -- >>> 1 `div` 2 -- 0 -- -- | -- >>> 1 `mod` 2 -- 1 -- -- * Rings -- -- | -- >>> zero == 0.0 -- True -- -- prop \a -> a + 0.0 == a -- True -- prop \a -> 0.0 + a == a -- True -- -- | -- -- >>> 1.0 + 1.0 -- 2.0 -- -- | -- >>> 1.0 - 1.0 -- 0.0 -- -- | -- checking unary minus is ok -- >>> :t - 1 -- - 1 :: Num a => a -- -- | -- >>> 1.0 * 1.0 -- 1.0 -- -- | -- >>> 1.0 / 1.0 -- 1.0 -- -- | Bounded Fields -- BoundedField ensures that divide by zero works. Having said this, actually printing one/zero as `Infinity` and -one/zero as `-Infinity` ain't coming from tower. -- -- >>> one/zero -- Infinity -- -- | -- >>> -one/zero -- -Infinity -- -- | -- >>> zero/zero+one -- NaN -- -- | -- >>> logBase 2 4 -- 2.0 -- -- | -- >>> 2 ** 2 -- 4.0 -- -- | -- >>> sqrt 4 -- 2.0 -- -- | -- >>> exp 2 -- 7.38905609893065 -- -- >>> log 2 -- 0.6931471805599453 -- -- * Vector Representable -- -- | note no wrapping -- >>> :set -XDataKinds -- >>> let a = toV [1..3] :: V 3 Int -- >>> a -- V {toVector = [1,2,3]} -- -- -- | -- -- >>> a+zero==a -- True -- >>> zero+a==a -- True -- >>> a+a -- V {toVector = [2,4,6]} -- -- | -- >>> a-a == zero -- True -- -- | -- >>> a * a -- V {toVector = [1,4,9]} -- -- | -- >>> a `divMod` a -- (V {toVector = [1,1,1]},V {toVector = [0,0,0]}) -- -- | -- >>> let b = toV [1.0,2.0,3.0] :: V 3 Float -- >>> b / b -- V {toVector = [1.0,1.0,1.0]} -- -- | -- todo: not sure why the type is needed here -- >>> :set -XFlexibleContexts -- >>> let a = toV [3.0,2.0,1.0] :: V 3 Float -- >>> size a :: Float -- 3.7416575 -- -- | -- >>> distance a b :: Float -- 2.828427 -- -- -- | -- >>> a >< b -- V {toVector = [V {toVector = [3.0,6.0,9.0]},V {toVector = [2.0,4.0,6.0]},V {toVector = [1.0,2.0,3.0]}]} -- -- -- | -- >>> a <.> b :: Float -- 10.0 -- -- * Matrix Double Representable - (r (r a)) -- -- | note no wrapping -- >>> :set -XDataKinds -- >>> let a = toV [1..3] :: V 3 Int -- >>> a -- V {toVector = [1,2,3]} -- -- -- | -- -- >>> a+zero==a -- True -- >>> zero+a==a -- True -- >>> a+a -- V {toVector = [2,4,6]} -- -- | -- >>> a-a == zero -- True -- -- | -- >>> a * a -- V {toVector = [1,4,9]} -- -- | -- >>> a `divMod` a -- (V {toVector = [1,1,1]},V {toVector = [0,0,0]}) -- -- | -- >>> let b = toV [1.0,2.0,3.0] :: V 3 Float -- >>> b / b -- V {toVector = [1.0,1.0,1.0]} -- -- | -- todo: not sure why the type is needed here -- >>> :set -XFlexibleContexts -- >>> let a = toV [3.0,2.0,1.0] :: V 3 Float -- >>> size a :: Float -- 3.7416575 -- -- | -- >>> distance a b :: Float -- 2.828427 -- -- -- | -- >>> a >< b -- V {toVector = [V {toVector = [3.0,6.0,9.0]},V {toVector = [2.0,4.0,6.0]},V {toVector = [1.0,2.0,3.0]}]} -- -- -- | -- >>> a <.> b :: Float -- 10.0 -- -- >>> (a >< b) >< (b >< a) -- V {toVector = [V {toVector = [V {toVector = [9.0,12.0,9.0]},V {toVector = [18.0,24.0,18.0]},V {toVector = [27.0,36.0,27.0]}]},V {toVector = [V {toVector = [6.0,8.0,6.0]},V {toVector = [12.0,16.0,12.0]},V {toVector = [18.0,24.0,18.0]}]},V {toVector = [V {toVector = [3.0,4.0,3.0]},V {toVector = [6.0,8.0,6.0]},V {toVector = [9.0,12.0,9.0]}]}]} --
tonyday567/tower
src/Tower/Examples.hs
bsd-3-clause
4,343
0
4
919
256
252
4
20
0
module Examples.ServerDouble ( -- * In which we define a server that the doubles the characters in incoming strings -- $example -- * Program -- $program -- ** Conduit version -- $conduit main ) where import Pipes.Network.TCP import qualified Data.ByteString as B import qualified Pipes.ByteString as Bytes import Pipes main :: IO () main = do putStrLn "Double server available on 4001" serve (Host "127.0.0.1") "4001" $ \(connectionSocket, remoteAddr) -> runEffect $ fromSocket connectionSocket 4096 >-> Bytes.concatMap (\x -> B.pack [x,x]) >-> toSocket connectionSocket {- $example This program sets up a service on 4001. We can start it thus: > terminal1$ pipes-network-tcp-examples ServerDouble > Double server available on 4001 and send it stuff with telnet: > terminal2$ telnet localhost 4001 > Trying 127.0.0.1... > Connected to localhost. > Escape character is '^]'. > hello > hheelllloo Our dedicated client in @Examples.ClientPipeline@ will link this server to the uppercasing server. -} {- $program > import Pipes.Network.TCP > import qualified Data.ByteString as B > import qualified Pipes.ByteString as Bytes > import Pipes > main :: IO () > main = do putStrLn "Double server available on 4001" > serve (Host "127.0.0.1") "4001" $ \(connectionSocket, remoteAddr) -> > runEffect $ fromSocket connectionSocket 4096 > >-> Bytes.concatMap (\x -> B.pack [x,x]) > >-> toSocket connectionSocket -} {- $conduit And, in the conduit version: > import Conduit > import Data.ByteString (pack) > import Data.Conduit.Network > main = runTCPServer (serverSettings 4001 "*") $ \appData -> > appSource appData > $$ concatMapCE (\w -> pack [w, w]) > =$ appSink appData > =$ appSink appData -}
michaelt/pipes-network-tcp-examples
Examples/ServerDouble.hs
bsd-3-clause
2,128
0
15
700
139
81
58
12
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} -- NB: this module contains tests for the GenProcess /and/ GenServer API. module Main where import Control.Concurrent.MVar import Control.Exception (SomeException) import Control.DeepSeq (NFData) import Control.Distributed.Process hiding (call, send) import Control.Distributed.Process.Node import Control.Distributed.Process.Extras hiding (__remoteTable) import Control.Distributed.Process.Async import Control.Distributed.Process.ManagedProcess import Control.Distributed.Process.Tests.Internal.Utils import Control.Distributed.Process.Extras.Time import Control.Distributed.Process.Extras.Timer import Control.Distributed.Process.Serializable() import Data.Binary import Data.Either (rights) import Data.Typeable (Typeable) #if ! MIN_VERSION_base(4,6,0) import Prelude hiding (catch) #endif import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import TestUtils import ManagedProcessCommon import qualified Network.Transport as NT import GHC.Generics (Generic) -- utilities server :: Process (ProcessId, (MVar ExitReason)) server = mkServer Terminate mkServer :: UnhandledMessagePolicy -> Process (ProcessId, (MVar ExitReason)) mkServer policy = let s = standardTestServer policy p = s `prioritised` ([] :: [DispatchPriority ()]) in do exitReason <- liftIO $ newEmptyMVar pid <- spawnLocal $ do catch ((pserve () (statelessInit Infinity) p >> stash exitReason ExitNormal) `catchesExit` [ (\_ msg -> do mEx <- unwrapMessage msg :: Process (Maybe ExitReason) case mEx of Nothing -> return Nothing Just r -> stash exitReason r >>= return . Just ) ]) (\(e :: SomeException) -> stash exitReason $ ExitOther (show e)) return (pid, exitReason) explodingServer :: ProcessId -> Process (ProcessId, MVar ExitReason) explodingServer pid = let srv = explodingTestProcess pid pSrv = srv `prioritised` ([] :: [DispatchPriority s]) in do exitReason <- liftIO $ newEmptyMVar spid <- spawnLocal $ do catch (pserve () (statelessInit Infinity) pSrv >> stash exitReason ExitNormal) (\(e :: SomeException) -> stash exitReason $ ExitOther (show e)) return (spid, exitReason) data GetState = GetState deriving (Typeable, Generic, Show, Eq) instance Binary GetState where instance NFData GetState where data MyAlarmSignal = MyAlarmSignal deriving (Typeable, Generic, Show, Eq) instance Binary MyAlarmSignal where instance NFData MyAlarmSignal where mkPrioritisedServer :: Process ProcessId mkPrioritisedServer = let p = procDef `prioritised` ([ prioritiseInfo_ (\MyAlarmSignal -> setPriority 10) , prioritiseCast_ (\(_ :: String) -> setPriority 2) , prioritiseCall_ (\(cmd :: String) -> (setPriority (length cmd)) :: Priority ()) ] :: [DispatchPriority [Either MyAlarmSignal String]] ) :: PrioritisedProcessDefinition [(Either MyAlarmSignal String)] in spawnLocal $ pserve () (initWait Infinity) p where initWait :: Delay -> InitHandler () [Either MyAlarmSignal String] initWait d () = do () <- expect return $ InitOk [] d procDef :: ProcessDefinition [(Either MyAlarmSignal String)] procDef = defaultProcess { apiHandlers = [ handleCall (\s GetState -> reply (reverse s) s) , handleCall (\s (cmd :: String) -> reply () ((Right cmd):s)) , handleCast (\s (cmd :: String) -> continue ((Right cmd):s)) ] , infoHandlers = [ handleInfo (\s (sig :: MyAlarmSignal) -> continue ((Left sig):s)) ] , unhandledMessagePolicy = Drop , timeoutHandler = \_ _ -> stop $ ExitOther "timeout" } :: ProcessDefinition [(Either MyAlarmSignal String)] -- test cases testInfoPrioritisation :: TestResult Bool -> Process () testInfoPrioritisation result = do pid <- mkPrioritisedServer -- the server (pid) is configured to wait for () during its init -- so we can fill up its mailbox with String messages, and verify -- that the alarm signal (which is prioritised *above* these) -- actually gets processed first despite the delivery order cast pid "hello" cast pid "prioritised" cast pid "world" -- note that these have to be a "bare send" send pid MyAlarmSignal -- tell the server it can move out of init and start processing messages send pid () st <- call pid GetState :: Process [Either MyAlarmSignal String] -- the result of GetState is a list of messages in reverse insertion order case head st of Left MyAlarmSignal -> stash result True _ -> stash result False testCallPrioritisation :: TestResult Bool -> Process () testCallPrioritisation result = do pid <- mkPrioritisedServer asyncRefs <- (mapM (callAsync pid) ["first", "the longest", "commands", "we do prioritise"]) :: Process [Async ()] -- NB: This sleep is really important - the `init' function is waiting -- (selectively) on the () signal to go, and if it receives this *before* -- the async worker has had a chance to deliver the longest string message, -- our test will fail. Such races are /normal/ given that the async worker -- runs in another process and delivery order between multiple processes -- is undefined (and in practise, paritally depenendent on the scheduler) sleep $ seconds 1 send pid () mapM wait asyncRefs :: Process [AsyncResult ()] st <- call pid GetState :: Process [Either MyAlarmSignal String] let ms = rights st stash result $ ms == ["we do prioritise", "the longest", "commands", "first"] tests :: NT.Transport -> IO [Test] tests transport = do localNode <- newLocalNode transport initRemoteTable return [ testGroup "basic server functionality matches un-prioritised processes" [ testCase "basic call with explicit server reply" (delayedAssertion "expected a response from the server" localNode (Just "foo") (testBasicCall $ wrap server)) , testCase "basic call with implicit server reply" (delayedAssertion "expected n * 2 back from the server" localNode (Just 4) (testBasicCall_ $ wrap server)) , testCase "basic cast with manual send and explicit server continue" (delayedAssertion "expected pong back from the server" localNode (Just "pong") (testBasicCast $ wrap server)) , testCase "cast and explicit server timeout" (delayedAssertion "expected the server to stop after the timeout" localNode (Just $ ExitOther "timeout") (testControlledTimeout $ wrap server)) , testCase "unhandled input when policy = Terminate" (delayedAssertion "expected the server to stop upon receiving unhandled input" localNode (Just $ ExitOther "UnhandledInput") (testTerminatePolicy $ wrap server)) , testCase "unhandled input when policy = Drop" (delayedAssertion "expected the server to ignore unhandled input and exit normally" localNode Nothing (testDropPolicy $ wrap (mkServer Drop))) , testCase "unhandled input when policy = DeadLetter" (delayedAssertion "expected the server to forward unhandled messages" localNode (Just ("UNSOLICITED_MAIL", 500 :: Int)) (testDeadLetterPolicy $ \p -> mkServer (DeadLetter p))) , testCase "incoming messages are ignored whilst hibernating" (delayedAssertion "expected the server to remain in hibernation" localNode True (testHibernation $ wrap server)) , testCase "long running call cancellation" (delayedAssertion "expected to get AsyncCancelled" localNode True (testKillMidCall $ wrap server)) , testCase "simple exit handling" (delayedAssertion "expected handler to catch exception and continue" localNode Nothing (testSimpleErrorHandling $ explodingServer)) , testCase "alternative exit handlers" (delayedAssertion "expected handler to catch exception and continue" localNode Nothing (testAlternativeErrorHandling $ explodingServer)) ] , testGroup "Prioritised Mailbox Handling" [ testCase "Info Message Prioritisation" (delayedAssertion "expected the info handler to be prioritised" localNode True testInfoPrioritisation) , testCase "Call Message Prioritisation" (delayedAssertion "expected the longest strings to be prioritised" localNode True testCallPrioritisation) ] ] main :: IO () main = testMain $ tests
qnikst/distributed-process-client-server
tests/TestPrioritisedProcess.hs
bsd-3-clause
9,177
0
26
2,383
2,044
1,073
971
172
2
{-# LANGUAGE FlexibleContexts #-} module Control.Concurrent.Timer.Lifted ( Timer , TimerIO , oneShotTimer , oneShotStart , oneShotRestart , repeatedTimer , repeatedStart , repeatedRestart , newTimer , stopTimer ) where ------------------------------------------------------------------------------ import Control.Applicative import Control.Concurrent.Lifted (ThreadId, fork, killThread) import Control.Concurrent.MVar.Lifted (newMVar, tryTakeMVar, putMVar, modifyMVar_) import Control.Concurrent.Suspend.Lifted (Delay, suspend) import Control.Monad import Control.Monad.Base (MonadBase) import Control.Monad.Trans.Control (MonadBaseControl) ------------------------------------------------------------------------------ import Control.Concurrent.Timer.Types (Timer(..), TimerImmutable(..)) ------------------------------------------------------------------------------ -- | Attempts to start a timer. -- The started timer will have the given delay and action associated and will be one-shot timer. -- -- If the timer was initialized before it will be stopped (killed) and started anew. -- -- Returns True if the start was successful, -- otherwise (e.g. other thread is attempting to manipulate the timer) returns False. oneShotStart :: MonadBaseControl IO m => Timer m -> m () -- ^ The action the timer will start with. -> Delay -- ^ The dealy the timer will start with. -> m Bool oneShotStart (Timer mvmtim) a d = do mtim <- tryTakeMVar mvmtim case mtim of Just (Just (TimerImmutable _ _ tid)) -> do killThread tid oneShotTimerImmutable a d >>= putMVar mvmtim . Just return True Just (Nothing) -> do oneShotTimerImmutable a d >>= putMVar mvmtim . Just return True Nothing -> return False {-# INLINEABLE oneShotStart #-} -- | Attempts to start a timer. -- The started timer will have the given delay and action associated and will be repeated timer. -- -- If the timer was initialized before it will be stopped (killed) and started anew. -- -- Returns True if the start was successful, -- otherwise (e.g. other thread is attempting to manipulate the timer) returns False. repeatedStart :: MonadBaseControl IO m => Timer m -> m () -- ^ The action the timer will start with. -> Delay -- ^ The dealy the timer will start with. -> m Bool repeatedStart (Timer mvmtim) a d = do mtim <- tryTakeMVar mvmtim case mtim of Just (Just (TimerImmutable _ _ tid)) -> do killThread tid repeatedTimerImmutable a d >>= putMVar mvmtim . Just return True Just (Nothing) -> do repeatedTimerImmutable a d >>= putMVar mvmtim . Just return True Nothing -> return False {-# INLINEABLE repeatedStart #-} -- | Attempts to restart already initialized timer. -- The restarted timer will have the same delay and action associated and will be one-shot timer. -- -- Returns True if the restart was successful, -- otherwise (e.g. other thread is attempting to manipulate the timer or the timer was not initialized) returns False. oneShotRestart :: MonadBaseControl IO m => Timer m -> m Bool oneShotRestart (Timer mvmtim) = do mtim <- tryTakeMVar mvmtim case mtim of Just (Just (TimerImmutable a d tid)) -> do killThread tid oneShotTimerImmutable a d >>= putMVar mvmtim . Just return True _ -> return False {-# INLINEABLE oneShotRestart #-} -- | Attempts to restart already initialized timer. -- The restarted timer will have the same delay and action associated and will be one-shot timer. -- -- Returns True if the restart was successful, -- otherwise (e.g. other thread is attempting to manipulate the timer or the timer was not initialized) returns False. repeatedRestart :: MonadBaseControl IO m => Timer m -> m Bool repeatedRestart (Timer mvmtim) = do mtim <- tryTakeMVar mvmtim case mtim of Just (Just (TimerImmutable a d tid)) -> do killThread tid repeatedTimerImmutable a d >>= putMVar mvmtim . Just return True _ -> return False {-# INLINEABLE repeatedRestart #-} -- | Executes the the given action once after the given delay elapsed, no sooner, maybe later. oneShotTimer :: MonadBaseControl IO m => m () -- ^ The action to be executed. -> Delay -- ^ The (minimal) time until the execution in microseconds. -> m (Timer m) oneShotTimer a d = Timer <$> (oneShotTimerImmutable a d >>= newMVar . Just) {-# INLINE oneShotTimer #-} -- | Executes the the given action repeatedly with at least the given delay between executions. repeatedTimer :: MonadBaseControl IO m => m () -- ^ The action to be executed. -> Delay -- ^ The (minimal) delay between executions. -> m (Timer m) repeatedTimer a d = Timer <$> (repeatedTimerImmutable a d >>= newMVar . Just) {-# INLINE repeatedTimer #-} -- | This function is blocking. It waits until it can stop the timer -- (until there is a value in the MVar), then it kills the timer's thread. -- -- After this action completes, the Timer is not innitialized anymore (the MVar contains Nothing). stopTimer :: MonadBaseControl IO m => Timer m -> m () stopTimer (Timer mvmtim) = modifyMVar_ mvmtim $ maybe (return Nothing) (\(TimerImmutable _ _ tid) -> killThread tid >> return Nothing) {-# INLINE stopTimer #-} -- | Creates a new timer. This does not start the timer. newTimer :: MonadBase IO m => m (Timer m) newTimer = Timer <$> newMVar Nothing {-# INLINE newTimer #-} ------------------------------------------------------------------------------ -- | Utility type TimerIO = Timer IO -- | Forks a new thread that runs the supplied action -- (at least) after the given delay and stores the action, -- delay and thread id in the immutable TimerImmutable value. oneShotTimerImmutable :: MonadBaseControl IO m => m () -- ^ The action to be executed. -> Delay -- ^ The (minimal) time until the execution in microseconds. -> m (TimerImmutable m) oneShotTimerImmutable a d = TimerImmutable a d <$> oneShotAction a d {-# INLINE oneShotTimerImmutable #-} -- | Forks a new thread that repeats the supplied action -- with (at least) the given delay between each execution and stores the action, -- delay and thread id in the immutable TimerImmutable value. repeatedTimerImmutable :: MonadBaseControl IO m => m () -- ^ The action to be executed. -> Delay -- ^ The (minimal) time until the execution in microseconds. -> m (TimerImmutable m) repeatedTimerImmutable a d = TimerImmutable a d <$> repeatedAction a d {-# INLINE repeatedTimerImmutable #-} -- | Forks a new thread that runs the supplied action -- (at least) after the given delay. oneShotAction :: MonadBaseControl IO m => m () -> Delay -> m ThreadId oneShotAction action delay = fork (suspend delay >> action) {-# INLINE oneShotAction #-} -- | Forks a new thread that repeats the supplied action -- with (at least) the given delay between each execution. repeatedAction :: MonadBaseControl IO m => m () -> Delay -> m ThreadId repeatedAction action delay = fork (forever $ suspend delay >> action) {-# INLINE repeatedAction #-}
Palmik/timers
src/Control/Concurrent/Timer/Lifted.hs
bsd-3-clause
7,779
0
14
2,069
1,300
665
635
122
3
module GHCJS.DOM.Document where {- module GHCJS.DOM.Document (ghcjs_dom_document_create_element, documentCreateElement, ghcjs_dom_document_create_document_fragment, documentCreateDocumentFragment, ghcjs_dom_document_create_text_node, documentCreateTextNode, ghcjs_dom_document_create_comment, documentCreateComment, ghcjs_dom_document_create_cdata_section, documentCreateCDATASection, ghcjs_dom_document_create_processing_instruction, documentCreateProcessingInstruction, ghcjs_dom_document_create_attribute, documentCreateAttribute, ghcjs_dom_document_create_entity_reference, documentCreateEntityReference, ghcjs_dom_document_get_elements_by_tag_name, documentGetElementsByTagName, ghcjs_dom_document_import_node, documentImportNode, ghcjs_dom_document_create_element_ns, documentCreateElementNS, ghcjs_dom_document_create_attribute_ns, documentCreateAttributeNS, ghcjs_dom_document_get_elements_by_tag_name_ns, documentGetElementsByTagNameNS, ghcjs_dom_document_get_element_by_id, documentGetElementById, ghcjs_dom_document_adopt_node, documentAdoptNode, ghcjs_dom_document_create_event, documentCreateEvent, ghcjs_dom_document_create_range, documentCreateRange, ghcjs_dom_document_create_node_iterator, documentCreateNodeIterator, ghcjs_dom_document_create_tree_walker, documentCreateTreeWalker, ghcjs_dom_document_get_override_style, documentGetOverrideStyle, ghcjs_dom_document_create_expression, documentCreateExpression, ghcjs_dom_document_create_ns_resolver, documentCreateNSResolver, ghcjs_dom_document_evaluate, documentEvaluate, ghcjs_dom_document_exec_command, documentExecCommand, ghcjs_dom_document_query_command_enabled, documentQueryCommandEnabled, ghcjs_dom_document_query_command_indeterm, documentQueryCommandIndeterm, ghcjs_dom_document_query_command_state, documentQueryCommandState, ghcjs_dom_document_query_command_supported, documentQueryCommandSupported, ghcjs_dom_document_query_command_value, documentQueryCommandValue, ghcjs_dom_document_get_elements_by_name, documentGetElementsByName, ghcjs_dom_document_element_from_point, documentElementFromPoint, ghcjs_dom_document_caret_range_from_point, documentCaretRangeFromPoint, ghcjs_dom_document_create_css_style_declaration, documentCreateCSSStyleDeclaration, ghcjs_dom_document_get_elements_by_class_name, documentGetElementsByClassName, ghcjs_dom_document_has_focus, documentHasFocus, ghcjs_dom_document_query_selector, documentQuerySelector, ghcjs_dom_document_query_selector_all, documentQuerySelectorAll, ghcjs_dom_document_exit_pointer_lock, documentExitPointerLock, ghcjs_dom_document_webkit_get_named_flows, documentWebkitGetNamedFlows, ghcjs_dom_document_get_doctype, documentGetDoctype, ghcjs_dom_document_get_implementation, documentGetImplementation, ghcjs_dom_document_get_document_element, documentGetDocumentElement, ghcjs_dom_document_get_input_encoding, documentGetInputEncoding, ghcjs_dom_document_get_xml_encoding, documentGetXmlEncoding, ghcjs_dom_document_set_xml_version, documentSetXmlVersion, ghcjs_dom_document_get_xml_version, documentGetXmlVersion, ghcjs_dom_document_set_xml_standalone, documentSetXmlStandalone, ghcjs_dom_document_get_xml_standalone, documentGetXmlStandalone, ghcjs_dom_document_set_document_uri, documentSetDocumentURI, ghcjs_dom_document_get_document_uri, documentGetDocumentURI, ghcjs_dom_document_get_default_view, documentGetDefaultView, ghcjs_dom_document_get_style_sheets, documentGetStyleSheets, ghcjs_dom_document_set_title, documentSetTitle, ghcjs_dom_document_get_title, documentGetTitle, ghcjs_dom_document_get_referrer, documentGetReferrer, ghcjs_dom_document_get_domain, documentGetDomain, ghcjs_dom_document_set_cookie, documentSetCookie, ghcjs_dom_document_get_cookie, documentGetCookie, ghcjs_dom_document_set_body, documentSetBody, ghcjs_dom_document_get_body, documentGetBody, ghcjs_dom_document_get_head, documentGetHead, ghcjs_dom_document_get_images, documentGetImages, ghcjs_dom_document_get_applets, documentGetApplets, ghcjs_dom_document_get_links, documentGetLinks, ghcjs_dom_document_get_forms, documentGetForms, ghcjs_dom_document_get_anchors, documentGetAnchors, ghcjs_dom_document_get_last_modified, documentGetLastModified, ghcjs_dom_document_set_charset, documentSetCharset, ghcjs_dom_document_get_charset, documentGetCharset, ghcjs_dom_document_get_default_charset, documentGetDefaultCharset, ghcjs_dom_document_get_ready_state, documentGetReadyState, ghcjs_dom_document_get_character_set, documentGetCharacterSet, ghcjs_dom_document_get_preferred_stylesheet_set, documentGetPreferredStylesheetSet, ghcjs_dom_document_set_selected_stylesheet_set, documentSetSelectedStylesheetSet, ghcjs_dom_document_get_selected_stylesheet_set, documentGetSelectedStylesheetSet, ghcjs_dom_document_get_active_element, documentGetActiveElement, ghcjs_dom_document_get_compat_mode, documentGetCompatMode, ghcjs_dom_document_get_pointer_lock_element, documentGetPointerLockElement, ghcjs_dom_document_get_visibility_state, documentGetVisibilityState, ghcjs_dom_document_get_hidden, documentGetHidden, ghcjs_dom_document_get_security_policy, documentGetSecurityPolicy, ghcjs_dom_document_get_current_script, documentGetCurrentScript, ghcjs_dom_document_get_origin, documentGetOrigin, Document, IsDocument, castToDocument, gTypeDocument, toDocument) where import GHCJS.Types import GHCJS.Foreign import GHCJS.Marshal import Data.Int import Data.Word import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventM foreign import javascript unsafe "$1[\"createElement\"]($2)" ghcjs_dom_document_create_element :: JSRef Document -> JSString -> IO (JSRef Element) documentCreateElement :: (IsDocument self, ToJSString tagName) => self -> tagName -> IO (Maybe Element) documentCreateElement self tagName = fmap Element . maybeJSNull <$> (ghcjs_dom_document_create_element (unDocument (toDocument self)) (toJSString tagName)) foreign import javascript unsafe "$1[\"createDocumentFragment\"]()" ghcjs_dom_document_create_document_fragment :: JSRef Document -> IO (JSRef DocumentFragment) documentCreateDocumentFragment :: (IsDocument self) => self -> IO (Maybe DocumentFragment) documentCreateDocumentFragment self = fmap DocumentFragment . maybeJSNull <$> (ghcjs_dom_document_create_document_fragment (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"createTextNode\"]($2)" ghcjs_dom_document_create_text_node :: JSRef Document -> JSString -> IO (JSRef Text) documentCreateTextNode :: (IsDocument self, ToJSString data') => self -> data' -> IO (Maybe Text) documentCreateTextNode self data' = fmap Text . maybeJSNull <$> (ghcjs_dom_document_create_text_node (unDocument (toDocument self)) (toJSString data')) foreign import javascript unsafe "$1[\"createComment\"]($2)" ghcjs_dom_document_create_comment :: JSRef Document -> JSString -> IO (JSRef Comment) documentCreateComment :: (IsDocument self, ToJSString data') => self -> data' -> IO (Maybe Comment) documentCreateComment self data' = fmap Comment . maybeJSNull <$> (ghcjs_dom_document_create_comment (unDocument (toDocument self)) (toJSString data')) foreign import javascript unsafe "$1[\"createCDATASection\"]($2)" ghcjs_dom_document_create_cdata_section :: JSRef Document -> JSString -> IO (JSRef CDATASection) documentCreateCDATASection :: (IsDocument self, ToJSString data') => self -> data' -> IO (Maybe CDATASection) documentCreateCDATASection self data' = fmap CDATASection . maybeJSNull <$> (ghcjs_dom_document_create_cdata_section (unDocument (toDocument self)) (toJSString data')) foreign import javascript unsafe "$1[\"createProcessingInstruction\"]($2,\n$3)" ghcjs_dom_document_create_processing_instruction :: JSRef Document -> JSString -> JSString -> IO (JSRef ProcessingInstruction) documentCreateProcessingInstruction :: (IsDocument self, ToJSString target, ToJSString data') => self -> target -> data' -> IO (Maybe ProcessingInstruction) documentCreateProcessingInstruction self target data' = fmap ProcessingInstruction . maybeJSNull <$> (ghcjs_dom_document_create_processing_instruction (unDocument (toDocument self)) (toJSString target) (toJSString data')) foreign import javascript unsafe "$1[\"createAttribute\"]($2)" ghcjs_dom_document_create_attribute :: JSRef Document -> JSString -> IO (JSRef DOMAttr) documentCreateAttribute :: (IsDocument self, ToJSString name) => self -> name -> IO (Maybe DOMAttr) documentCreateAttribute self name = fmap DOMAttr . maybeJSNull <$> (ghcjs_dom_document_create_attribute (unDocument (toDocument self)) (toJSString name)) foreign import javascript unsafe "$1[\"createEntityReference\"]($2)" ghcjs_dom_document_create_entity_reference :: JSRef Document -> JSString -> IO (JSRef EntityReference) documentCreateEntityReference :: (IsDocument self, ToJSString name) => self -> name -> IO (Maybe EntityReference) documentCreateEntityReference self name = fmap EntityReference . maybeJSNull <$> (ghcjs_dom_document_create_entity_reference (unDocument (toDocument self)) (toJSString name)) foreign import javascript unsafe "$1[\"getElementsByTagName\"]($2)" ghcjs_dom_document_get_elements_by_tag_name :: JSRef Document -> JSString -> IO (JSRef NodeList) documentGetElementsByTagName :: (IsDocument self, ToJSString tagname) => self -> tagname -> IO (Maybe NodeList) documentGetElementsByTagName self tagname = fmap NodeList . maybeJSNull <$> (ghcjs_dom_document_get_elements_by_tag_name (unDocument (toDocument self)) (toJSString tagname)) foreign import javascript unsafe "$1[\"importNode\"]($2, $3)" ghcjs_dom_document_import_node :: JSRef Document -> JSRef Node -> Bool -> IO (JSRef Node) documentImportNode :: (IsDocument self, IsNode importedNode) => self -> Maybe importedNode -> Bool -> IO (Maybe Node) documentImportNode self importedNode deep = fmap Node . maybeJSNull <$> (ghcjs_dom_document_import_node (unDocument (toDocument self)) (maybe jsNull (unNode . toNode) importedNode) deep) foreign import javascript unsafe "$1[\"createElementNS\"]($2, $3)" ghcjs_dom_document_create_element_ns :: JSRef Document -> JSString -> JSString -> IO (JSRef Element) documentCreateElementNS :: (IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> namespaceURI -> qualifiedName -> IO (Maybe Element) documentCreateElementNS self namespaceURI qualifiedName = fmap Element . maybeJSNull <$> (ghcjs_dom_document_create_element_ns (unDocument (toDocument self)) (toJSString namespaceURI) (toJSString qualifiedName)) foreign import javascript unsafe "$1[\"createAttributeNS\"]($2, $3)" ghcjs_dom_document_create_attribute_ns :: JSRef Document -> JSString -> JSString -> IO (JSRef DOMAttr) documentCreateAttributeNS :: (IsDocument self, ToJSString namespaceURI, ToJSString qualifiedName) => self -> namespaceURI -> qualifiedName -> IO (Maybe DOMAttr) documentCreateAttributeNS self namespaceURI qualifiedName = fmap DOMAttr . maybeJSNull <$> (ghcjs_dom_document_create_attribute_ns (unDocument (toDocument self)) (toJSString namespaceURI) (toJSString qualifiedName)) foreign import javascript unsafe "$1[\"getElementsByTagNameNS\"]($2,\n$3)" ghcjs_dom_document_get_elements_by_tag_name_ns :: JSRef Document -> JSString -> JSString -> IO (JSRef NodeList) documentGetElementsByTagNameNS :: (IsDocument self, ToJSString namespaceURI, ToJSString localName) => self -> namespaceURI -> localName -> IO (Maybe NodeList) documentGetElementsByTagNameNS self namespaceURI localName = fmap NodeList . maybeJSNull <$> (ghcjs_dom_document_get_elements_by_tag_name_ns (unDocument (toDocument self)) (toJSString namespaceURI) (toJSString localName)) foreign import javascript unsafe "$1[\"getElementById\"]($2)" ghcjs_dom_document_get_element_by_id :: JSRef Document -> JSString -> IO (JSRef Element) documentGetElementById :: (IsDocument self, ToJSString elementId) => self -> elementId -> IO (Maybe Element) documentGetElementById self elementId = fmap Element . maybeJSNull <$> (ghcjs_dom_document_get_element_by_id (unDocument (toDocument self)) (toJSString elementId)) foreign import javascript unsafe "$1[\"adoptNode\"]($2)" ghcjs_dom_document_adopt_node :: JSRef Document -> JSRef Node -> IO (JSRef Node) documentAdoptNode :: (IsDocument self, IsNode source) => self -> Maybe source -> IO (Maybe Node) documentAdoptNode self source = fmap Node . maybeJSNull <$> (ghcjs_dom_document_adopt_node (unDocument (toDocument self)) (maybe jsNull (unNode . toNode) source)) foreign import javascript unsafe "$1[\"createEvent\"]($2)" ghcjs_dom_document_create_event :: JSRef Document -> JSString -> IO (JSRef Event) documentCreateEvent :: (IsDocument self, ToJSString eventType) => self -> eventType -> IO (Maybe Event) documentCreateEvent self eventType = fmap Event . maybeJSNull <$> (ghcjs_dom_document_create_event (unDocument (toDocument self)) (toJSString eventType)) foreign import javascript unsafe "$1[\"createRange\"]()" ghcjs_dom_document_create_range :: JSRef Document -> IO (JSRef DOMRange) documentCreateRange :: (IsDocument self) => self -> IO (Maybe DOMRange) documentCreateRange self = fmap DOMRange . maybeJSNull <$> (ghcjs_dom_document_create_range (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"createNodeIterator\"]($2, $3,\n$4, $5)" ghcjs_dom_document_create_node_iterator :: JSRef Document -> JSRef Node -> Word -> JSRef NodeFilter -> Bool -> IO (JSRef NodeIterator) documentCreateNodeIterator :: (IsDocument self, IsNode root, IsNodeFilter filter) => self -> Maybe root -> Word -> Maybe filter -> Bool -> IO (Maybe NodeIterator) documentCreateNodeIterator self root whatToShow filter expandEntityReferences = fmap NodeIterator . maybeJSNull <$> (ghcjs_dom_document_create_node_iterator (unDocument (toDocument self)) (maybe jsNull (unNode . toNode) root) whatToShow (maybe jsNull (unNodeFilter . toNodeFilter) filter) expandEntityReferences) foreign import javascript unsafe "$1[\"createTreeWalker\"]($2, $3,\n$4, $5)" ghcjs_dom_document_create_tree_walker :: JSRef Document -> JSRef Node -> Word -> JSRef NodeFilter -> Bool -> IO (JSRef TreeWalker) documentCreateTreeWalker :: (IsDocument self, IsNode root, IsNodeFilter filter) => self -> Maybe root -> Word -> Maybe filter -> Bool -> IO (Maybe TreeWalker) documentCreateTreeWalker self root whatToShow filter expandEntityReferences = fmap TreeWalker . maybeJSNull <$> (ghcjs_dom_document_create_tree_walker (unDocument (toDocument self)) (maybe jsNull (unNode . toNode) root) whatToShow (maybe jsNull (unNodeFilter . toNodeFilter) filter) expandEntityReferences) foreign import javascript unsafe "$1[\"getOverrideStyle\"]($2, $3)" ghcjs_dom_document_get_override_style :: JSRef Document -> JSRef Element -> JSString -> IO (JSRef CSSStyleDeclaration) documentGetOverrideStyle :: (IsDocument self, IsElement element, ToJSString pseudoElement) => self -> Maybe element -> pseudoElement -> IO (Maybe CSSStyleDeclaration) documentGetOverrideStyle self element pseudoElement = fmap CSSStyleDeclaration . maybeJSNull <$> (ghcjs_dom_document_get_override_style (unDocument (toDocument self)) (maybe jsNull (unElement . toElement) element) (toJSString pseudoElement)) foreign import javascript unsafe "$1[\"createExpression\"]($2, $3)" ghcjs_dom_document_create_expression :: JSRef Document -> JSString -> JSRef XPathNSResolver -> IO (JSRef XPathExpression) documentCreateExpression :: (IsDocument self, ToJSString expression, IsXPathNSResolver resolver) => self -> expression -> Maybe resolver -> IO (Maybe XPathExpression) documentCreateExpression self expression resolver = fmap XPathExpression . maybeJSNull <$> (ghcjs_dom_document_create_expression (unDocument (toDocument self)) (toJSString expression) (maybe jsNull (unXPathNSResolver . toXPathNSResolver) resolver)) foreign import javascript unsafe "$1[\"createNSResolver\"]($2)" ghcjs_dom_document_create_ns_resolver :: JSRef Document -> JSRef Node -> IO (JSRef XPathNSResolver) documentCreateNSResolver :: (IsDocument self, IsNode nodeResolver) => self -> Maybe nodeResolver -> IO (Maybe XPathNSResolver) documentCreateNSResolver self nodeResolver = fmap XPathNSResolver . maybeJSNull <$> (ghcjs_dom_document_create_ns_resolver (unDocument (toDocument self)) (maybe jsNull (unNode . toNode) nodeResolver)) foreign import javascript unsafe "$1[\"evaluate\"]($2, $3, $4, $5,\n$6)" ghcjs_dom_document_evaluate :: JSRef Document -> JSString -> JSRef Node -> JSRef XPathNSResolver -> Word -> JSRef XPathResult -> IO (JSRef XPathResult) documentEvaluate :: (IsDocument self, ToJSString expression, IsNode contextNode, IsXPathNSResolver resolver, IsXPathResult inResult) => self -> expression -> Maybe contextNode -> Maybe resolver -> Word -> Maybe inResult -> IO (Maybe XPathResult) documentEvaluate self expression contextNode resolver type' inResult = fmap XPathResult . maybeJSNull <$> (ghcjs_dom_document_evaluate (unDocument (toDocument self)) (toJSString expression) (maybe jsNull (unNode . toNode) contextNode) (maybe jsNull (unXPathNSResolver . toXPathNSResolver) resolver) type' (maybe jsNull (unXPathResult . toXPathResult) inResult)) foreign import javascript unsafe "($1[\"execCommand\"]($2, $3,\n$4) ? 1 : 0)" ghcjs_dom_document_exec_command :: JSRef Document -> JSString -> Bool -> JSString -> IO Bool documentExecCommand :: (IsDocument self, ToJSString command, ToJSString value) => self -> command -> Bool -> value -> IO Bool documentExecCommand self command userInterface value = ghcjs_dom_document_exec_command (unDocument (toDocument self)) (toJSString command) userInterface (toJSString value) foreign import javascript unsafe "($1[\"queryCommandEnabled\"]($2) ? 1 : 0)" ghcjs_dom_document_query_command_enabled :: JSRef Document -> JSString -> IO Bool documentQueryCommandEnabled :: (IsDocument self, ToJSString command) => self -> command -> IO Bool documentQueryCommandEnabled self command = ghcjs_dom_document_query_command_enabled (unDocument (toDocument self)) (toJSString command) foreign import javascript unsafe "($1[\"queryCommandIndeterm\"]($2) ? 1 : 0)" ghcjs_dom_document_query_command_indeterm :: JSRef Document -> JSString -> IO Bool documentQueryCommandIndeterm :: (IsDocument self, ToJSString command) => self -> command -> IO Bool documentQueryCommandIndeterm self command = ghcjs_dom_document_query_command_indeterm (unDocument (toDocument self)) (toJSString command) foreign import javascript unsafe "($1[\"queryCommandState\"]($2) ? 1 : 0)" ghcjs_dom_document_query_command_state :: JSRef Document -> JSString -> IO Bool documentQueryCommandState :: (IsDocument self, ToJSString command) => self -> command -> IO Bool documentQueryCommandState self command = ghcjs_dom_document_query_command_state (unDocument (toDocument self)) (toJSString command) foreign import javascript unsafe "($1[\"queryCommandSupported\"]($2) ? 1 : 0)" ghcjs_dom_document_query_command_supported :: JSRef Document -> JSString -> IO Bool documentQueryCommandSupported :: (IsDocument self, ToJSString command) => self -> command -> IO Bool documentQueryCommandSupported self command = ghcjs_dom_document_query_command_supported (unDocument (toDocument self)) (toJSString command) foreign import javascript unsafe "$1[\"queryCommandValue\"]($2)" ghcjs_dom_document_query_command_value :: JSRef Document -> JSString -> IO JSString documentQueryCommandValue :: (IsDocument self, ToJSString command, FromJSString result) => self -> command -> IO result documentQueryCommandValue self command = fromJSString <$> (ghcjs_dom_document_query_command_value (unDocument (toDocument self)) (toJSString command)) foreign import javascript unsafe "$1[\"getElementsByName\"]($2)" ghcjs_dom_document_get_elements_by_name :: JSRef Document -> JSString -> IO (JSRef NodeList) documentGetElementsByName :: (IsDocument self, ToJSString elementName) => self -> elementName -> IO (Maybe NodeList) documentGetElementsByName self elementName = fmap NodeList . maybeJSNull <$> (ghcjs_dom_document_get_elements_by_name (unDocument (toDocument self)) (toJSString elementName)) foreign import javascript unsafe "$1[\"elementFromPoint\"]($2, $3)" ghcjs_dom_document_element_from_point :: JSRef Document -> Int -> Int -> IO (JSRef Element) documentElementFromPoint :: (IsDocument self) => self -> Int -> Int -> IO (Maybe Element) documentElementFromPoint self x y = fmap Element . maybeJSNull <$> (ghcjs_dom_document_element_from_point (unDocument (toDocument self)) x y) foreign import javascript unsafe "$1[\"caretRangeFromPoint\"]($2,\n$3)" ghcjs_dom_document_caret_range_from_point :: JSRef Document -> Int -> Int -> IO (JSRef DOMRange) documentCaretRangeFromPoint :: (IsDocument self) => self -> Int -> Int -> IO (Maybe DOMRange) documentCaretRangeFromPoint self x y = fmap DOMRange . maybeJSNull <$> (ghcjs_dom_document_caret_range_from_point (unDocument (toDocument self)) x y) foreign import javascript unsafe "$1[\"createCSSStyleDeclaration\"]()" ghcjs_dom_document_create_css_style_declaration :: JSRef Document -> IO (JSRef CSSStyleDeclaration) documentCreateCSSStyleDeclaration :: (IsDocument self) => self -> IO (Maybe CSSStyleDeclaration) documentCreateCSSStyleDeclaration self = fmap CSSStyleDeclaration . maybeJSNull <$> (ghcjs_dom_document_create_css_style_declaration (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"getElementsByClassName\"]($2)" ghcjs_dom_document_get_elements_by_class_name :: JSRef Document -> JSString -> IO (JSRef NodeList) documentGetElementsByClassName :: (IsDocument self, ToJSString tagname) => self -> tagname -> IO (Maybe NodeList) documentGetElementsByClassName self tagname = fmap NodeList . maybeJSNull <$> (ghcjs_dom_document_get_elements_by_class_name (unDocument (toDocument self)) (toJSString tagname)) foreign import javascript unsafe "($1[\"hasFocus\"]() ? 1 : 0)" ghcjs_dom_document_has_focus :: JSRef Document -> IO Bool documentHasFocus :: (IsDocument self) => self -> IO Bool documentHasFocus self = ghcjs_dom_document_has_focus (unDocument (toDocument self)) foreign import javascript unsafe "$1[\"querySelector\"]($2)" ghcjs_dom_document_query_selector :: JSRef Document -> JSString -> IO (JSRef Element) documentQuerySelector :: (IsDocument self, ToJSString selectors) => self -> selectors -> IO (Maybe Element) documentQuerySelector self selectors = fmap Element . maybeJSNull <$> (ghcjs_dom_document_query_selector (unDocument (toDocument self)) (toJSString selectors)) foreign import javascript unsafe "$1[\"querySelectorAll\"]($2)" ghcjs_dom_document_query_selector_all :: JSRef Document -> JSString -> IO (JSRef NodeList) documentQuerySelectorAll :: (IsDocument self, ToJSString selectors) => self -> selectors -> IO (Maybe NodeList) documentQuerySelectorAll self selectors = fmap NodeList . maybeJSNull <$> (ghcjs_dom_document_query_selector_all (unDocument (toDocument self)) (toJSString selectors)) foreign import javascript unsafe "$1[\"exitPointerLock\"]()" ghcjs_dom_document_exit_pointer_lock :: JSRef Document -> IO () documentExitPointerLock :: (IsDocument self) => self -> IO () documentExitPointerLock self = ghcjs_dom_document_exit_pointer_lock (unDocument (toDocument self)) foreign import javascript unsafe "$1[\"webkitGetNamedFlows\"]()" ghcjs_dom_document_webkit_get_named_flows :: JSRef Document -> IO (JSRef DOMNamedFlowCollection) documentWebkitGetNamedFlows :: (IsDocument self) => self -> IO (Maybe DOMNamedFlowCollection) documentWebkitGetNamedFlows self = fmap DOMNamedFlowCollection . maybeJSNull <$> (ghcjs_dom_document_webkit_get_named_flows (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"doctype\"]" ghcjs_dom_document_get_doctype :: JSRef Document -> IO (JSRef DocumentType) documentGetDoctype :: (IsDocument self) => self -> IO (Maybe DocumentType) documentGetDoctype self = fmap DocumentType . maybeJSNull <$> (ghcjs_dom_document_get_doctype (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"implementation\"]" ghcjs_dom_document_get_implementation :: JSRef Document -> IO (JSRef DOMImplementation) documentGetImplementation :: (IsDocument self) => self -> IO (Maybe DOMImplementation) documentGetImplementation self = fmap DOMImplementation . maybeJSNull <$> (ghcjs_dom_document_get_implementation (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"documentElement\"]" ghcjs_dom_document_get_document_element :: JSRef Document -> IO (JSRef Element) documentGetDocumentElement :: (IsDocument self) => self -> IO (Maybe Element) documentGetDocumentElement self = fmap Element . maybeJSNull <$> (ghcjs_dom_document_get_document_element (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"inputEncoding\"]" ghcjs_dom_document_get_input_encoding :: JSRef Document -> IO JSString documentGetInputEncoding :: (IsDocument self, FromJSString result) => self -> IO result documentGetInputEncoding self = fromJSString <$> (ghcjs_dom_document_get_input_encoding (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"xmlEncoding\"]" ghcjs_dom_document_get_xml_encoding :: JSRef Document -> IO JSString documentGetXmlEncoding :: (IsDocument self, FromJSString result) => self -> IO result documentGetXmlEncoding self = fromJSString <$> (ghcjs_dom_document_get_xml_encoding (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"xmlVersion\"] = $2;" ghcjs_dom_document_set_xml_version :: JSRef Document -> JSString -> IO () documentSetXmlVersion :: (IsDocument self, ToJSString val) => self -> val -> IO () documentSetXmlVersion self val = ghcjs_dom_document_set_xml_version (unDocument (toDocument self)) (toJSString val) foreign import javascript unsafe "$1[\"xmlVersion\"]" ghcjs_dom_document_get_xml_version :: JSRef Document -> IO JSString documentGetXmlVersion :: (IsDocument self, FromJSString result) => self -> IO result documentGetXmlVersion self = fromJSString <$> (ghcjs_dom_document_get_xml_version (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"xmlStandalone\"] = $2;" ghcjs_dom_document_set_xml_standalone :: JSRef Document -> Bool -> IO () documentSetXmlStandalone :: (IsDocument self) => self -> Bool -> IO () documentSetXmlStandalone self val = ghcjs_dom_document_set_xml_standalone (unDocument (toDocument self)) val foreign import javascript unsafe "($1[\"xmlStandalone\"] ? 1 : 0)" ghcjs_dom_document_get_xml_standalone :: JSRef Document -> IO Bool documentGetXmlStandalone :: (IsDocument self) => self -> IO Bool documentGetXmlStandalone self = ghcjs_dom_document_get_xml_standalone (unDocument (toDocument self)) foreign import javascript unsafe "$1[\"documentURI\"] = $2;" ghcjs_dom_document_set_document_uri :: JSRef Document -> JSString -> IO () documentSetDocumentURI :: (IsDocument self, ToJSString val) => self -> val -> IO () documentSetDocumentURI self val = ghcjs_dom_document_set_document_uri (unDocument (toDocument self)) (toJSString val) foreign import javascript unsafe "$1[\"documentURI\"]" ghcjs_dom_document_get_document_uri :: JSRef Document -> IO JSString documentGetDocumentURI :: (IsDocument self, FromJSString result) => self -> IO result documentGetDocumentURI self = fromJSString <$> (ghcjs_dom_document_get_document_uri (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"defaultView\"]" ghcjs_dom_document_get_default_view :: JSRef Document -> IO (JSRef DOMWindow) documentGetDefaultView :: (IsDocument self) => self -> IO (Maybe DOMWindow) documentGetDefaultView self = fmap DOMWindow . maybeJSNull <$> (ghcjs_dom_document_get_default_view (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"styleSheets\"]" ghcjs_dom_document_get_style_sheets :: JSRef Document -> IO (JSRef StyleSheetList) documentGetStyleSheets :: (IsDocument self) => self -> IO (Maybe StyleSheetList) documentGetStyleSheets self = fmap StyleSheetList . maybeJSNull <$> (ghcjs_dom_document_get_style_sheets (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"title\"] = $2;" ghcjs_dom_document_set_title :: JSRef Document -> JSString -> IO () documentSetTitle :: (IsDocument self, ToJSString val) => self -> val -> IO () documentSetTitle self val = ghcjs_dom_document_set_title (unDocument (toDocument self)) (toJSString val) foreign import javascript unsafe "$1[\"title\"]" ghcjs_dom_document_get_title :: JSRef Document -> IO JSString documentGetTitle :: (IsDocument self, FromJSString result) => self -> IO result documentGetTitle self = fromJSString <$> (ghcjs_dom_document_get_title (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"referrer\"]" ghcjs_dom_document_get_referrer :: JSRef Document -> IO JSString documentGetReferrer :: (IsDocument self, FromJSString result) => self -> IO result documentGetReferrer self = fromJSString <$> (ghcjs_dom_document_get_referrer (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"domain\"]" ghcjs_dom_document_get_domain :: JSRef Document -> IO JSString documentGetDomain :: (IsDocument self, FromJSString result) => self -> IO result documentGetDomain self = fromJSString <$> (ghcjs_dom_document_get_domain (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"cookie\"] = $2;" ghcjs_dom_document_set_cookie :: JSRef Document -> JSString -> IO () documentSetCookie :: (IsDocument self, ToJSString val) => self -> val -> IO () documentSetCookie self val = ghcjs_dom_document_set_cookie (unDocument (toDocument self)) (toJSString val) foreign import javascript unsafe "$1[\"cookie\"]" ghcjs_dom_document_get_cookie :: JSRef Document -> IO JSString documentGetCookie :: (IsDocument self, FromJSString result) => self -> IO result documentGetCookie self = fromJSString <$> (ghcjs_dom_document_get_cookie (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"body\"] = $2;" ghcjs_dom_document_set_body :: JSRef Document -> JSRef HTMLElement -> IO () documentSetBody :: (IsDocument self, IsHTMLElement val) => self -> Maybe val -> IO () documentSetBody self val = ghcjs_dom_document_set_body (unDocument (toDocument self)) (maybe jsNull (unHTMLElement . toHTMLElement) val) foreign import javascript unsafe "$1[\"body\"]" ghcjs_dom_document_get_body :: JSRef Document -> IO (JSRef HTMLElement) documentGetBody :: (IsDocument self) => self -> IO (Maybe HTMLElement) documentGetBody self = fmap HTMLElement . maybeJSNull <$> (ghcjs_dom_document_get_body (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"head\"]" ghcjs_dom_document_get_head :: JSRef Document -> IO (JSRef HTMLHeadElement) documentGetHead :: (IsDocument self) => self -> IO (Maybe HTMLHeadElement) documentGetHead self = fmap HTMLHeadElement . maybeJSNull <$> (ghcjs_dom_document_get_head (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"images\"]" ghcjs_dom_document_get_images :: JSRef Document -> IO (JSRef HTMLCollection) documentGetImages :: (IsDocument self) => self -> IO (Maybe HTMLCollection) documentGetImages self = fmap HTMLCollection . maybeJSNull <$> (ghcjs_dom_document_get_images (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"applets\"]" ghcjs_dom_document_get_applets :: JSRef Document -> IO (JSRef HTMLCollection) documentGetApplets :: (IsDocument self) => self -> IO (Maybe HTMLCollection) documentGetApplets self = fmap HTMLCollection . maybeJSNull <$> (ghcjs_dom_document_get_applets (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"links\"]" ghcjs_dom_document_get_links :: JSRef Document -> IO (JSRef HTMLCollection) documentGetLinks :: (IsDocument self) => self -> IO (Maybe HTMLCollection) documentGetLinks self = fmap HTMLCollection . maybeJSNull <$> (ghcjs_dom_document_get_links (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"forms\"]" ghcjs_dom_document_get_forms :: JSRef Document -> IO (JSRef HTMLCollection) documentGetForms :: (IsDocument self) => self -> IO (Maybe HTMLCollection) documentGetForms self = fmap HTMLCollection . maybeJSNull <$> (ghcjs_dom_document_get_forms (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"anchors\"]" ghcjs_dom_document_get_anchors :: JSRef Document -> IO (JSRef HTMLCollection) documentGetAnchors :: (IsDocument self) => self -> IO (Maybe HTMLCollection) documentGetAnchors self = fmap HTMLCollection . maybeJSNull <$> (ghcjs_dom_document_get_anchors (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"lastModified\"]" ghcjs_dom_document_get_last_modified :: JSRef Document -> IO JSString documentGetLastModified :: (IsDocument self, FromJSString result) => self -> IO result documentGetLastModified self = fromJSString <$> (ghcjs_dom_document_get_last_modified (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"charset\"] = $2;" ghcjs_dom_document_set_charset :: JSRef Document -> JSString -> IO () documentSetCharset :: (IsDocument self, ToJSString val) => self -> val -> IO () documentSetCharset self val = ghcjs_dom_document_set_charset (unDocument (toDocument self)) (toJSString val) foreign import javascript unsafe "$1[\"charset\"]" ghcjs_dom_document_get_charset :: JSRef Document -> IO JSString documentGetCharset :: (IsDocument self, FromJSString result) => self -> IO result documentGetCharset self = fromJSString <$> (ghcjs_dom_document_get_charset (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"defaultCharset\"]" ghcjs_dom_document_get_default_charset :: JSRef Document -> IO JSString documentGetDefaultCharset :: (IsDocument self, FromJSString result) => self -> IO result documentGetDefaultCharset self = fromJSString <$> (ghcjs_dom_document_get_default_charset (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"readyState\"]" ghcjs_dom_document_get_ready_state :: JSRef Document -> IO JSString documentGetReadyState :: (IsDocument self, FromJSString result) => self -> IO result documentGetReadyState self = fromJSString <$> (ghcjs_dom_document_get_ready_state (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"characterSet\"]" ghcjs_dom_document_get_character_set :: JSRef Document -> IO JSString documentGetCharacterSet :: (IsDocument self, FromJSString result) => self -> IO result documentGetCharacterSet self = fromJSString <$> (ghcjs_dom_document_get_character_set (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"preferredStylesheetSet\"]" ghcjs_dom_document_get_preferred_stylesheet_set :: JSRef Document -> IO JSString documentGetPreferredStylesheetSet :: (IsDocument self, FromJSString result) => self -> IO result documentGetPreferredStylesheetSet self = fromJSString <$> (ghcjs_dom_document_get_preferred_stylesheet_set (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"selectedStylesheetSet\"] = $2;" ghcjs_dom_document_set_selected_stylesheet_set :: JSRef Document -> JSString -> IO () documentSetSelectedStylesheetSet :: (IsDocument self, ToJSString val) => self -> val -> IO () documentSetSelectedStylesheetSet self val = ghcjs_dom_document_set_selected_stylesheet_set (unDocument (toDocument self)) (toJSString val) foreign import javascript unsafe "$1[\"selectedStylesheetSet\"]" ghcjs_dom_document_get_selected_stylesheet_set :: JSRef Document -> IO JSString documentGetSelectedStylesheetSet :: (IsDocument self, FromJSString result) => self -> IO result documentGetSelectedStylesheetSet self = fromJSString <$> (ghcjs_dom_document_get_selected_stylesheet_set (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"activeElement\"]" ghcjs_dom_document_get_active_element :: JSRef Document -> IO (JSRef Element) documentGetActiveElement :: (IsDocument self) => self -> IO (Maybe Element) documentGetActiveElement self = fmap Element . maybeJSNull <$> (ghcjs_dom_document_get_active_element (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"compatMode\"]" ghcjs_dom_document_get_compat_mode :: JSRef Document -> IO JSString documentGetCompatMode :: (IsDocument self, FromJSString result) => self -> IO result documentGetCompatMode self = fromJSString <$> (ghcjs_dom_document_get_compat_mode (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"pointerLockElement\"]" ghcjs_dom_document_get_pointer_lock_element :: JSRef Document -> IO (JSRef Element) documentGetPointerLockElement :: (IsDocument self) => self -> IO (Maybe Element) documentGetPointerLockElement self = fmap Element . maybeJSNull <$> (ghcjs_dom_document_get_pointer_lock_element (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"visibilityState\"]" ghcjs_dom_document_get_visibility_state :: JSRef Document -> IO JSString documentGetVisibilityState :: (IsDocument self, FromJSString result) => self -> IO result documentGetVisibilityState self = fromJSString <$> (ghcjs_dom_document_get_visibility_state (unDocument (toDocument self))) foreign import javascript unsafe "($1[\"hidden\"] ? 1 : 0)" ghcjs_dom_document_get_hidden :: JSRef Document -> IO Bool documentGetHidden :: (IsDocument self) => self -> IO Bool documentGetHidden self = ghcjs_dom_document_get_hidden (unDocument (toDocument self)) foreign import javascript unsafe "$1[\"securityPolicy\"]" ghcjs_dom_document_get_security_policy :: JSRef Document -> IO (JSRef DOMSecurityPolicy) documentGetSecurityPolicy :: (IsDocument self) => self -> IO (Maybe DOMSecurityPolicy) documentGetSecurityPolicy self = fmap DOMSecurityPolicy . maybeJSNull <$> (ghcjs_dom_document_get_security_policy (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"currentScript\"]" ghcjs_dom_document_get_current_script :: JSRef Document -> IO (JSRef HTMLScriptElement) documentGetCurrentScript :: (IsDocument self) => self -> IO (Maybe HTMLScriptElement) documentGetCurrentScript self = fmap HTMLScriptElement . maybeJSNull <$> (ghcjs_dom_document_get_current_script (unDocument (toDocument self))) foreign import javascript unsafe "$1[\"origin\"]" ghcjs_dom_document_get_origin :: JSRef Document -> IO JSString documentGetOrigin :: (IsDocument self, FromJSString result) => self -> IO result documentGetOrigin self = fromJSString <$> (ghcjs_dom_document_get_origin (unDocument (toDocument self))) #else module GHCJS.DOM.Document ( module Graphics.UI.Gtk.WebKit.DOM.Document ) where import Graphics.UI.Gtk.WebKit.DOM.Document #endif -}
mightybyte/reflex-dom-stubs
src/GHCJS/DOM/Document.hs
bsd-3-clause
45,128
0
3
10,588
8
6
2
-1
-1
module WorldGenerating where import qualified Data.IntMap as IM import qualified Data.IntSet as IS import qualified Data.Vector as V import Control.Lens import Control.Monad.State import AI import AIState import Building import Item import Terrain import Tile import Utils import World import Creature simpleWorld :: World simpleWorld = modifyWorld World { _worldTerrain = simpleTerrain , _worldCreatures = IM.empty , _worldMaxId = 0 , _worldItems = IM.empty , _worldJobs = [JobDig ((6, 1, 0), (7, 5, 0))] , _worldBuildings = IM.empty } where modifyWorld world = world & addCreature simpleCreature & addCreature simpleCreature & addItem (simpleItem (3, 3, 0)) & addItem (simpleItem (2, 6, 0)) & addItem (simpleItem (8, 1, 1)) & addItem (simpleItem (1, 1, 1)) & startBuilding BuildingField (6, 1, 1) & startBuilding BuildingBrewery (6, 2, 1) runSimpleWorld :: Int -> World runSimpleWorld n = execState (replicateM_ n stepWorld) simpleWorld simpleTerrain :: Terrain simpleTerrain = modifyTerrain Terrain { _terrainSize = (10, 10, 2) , _terrainTiles = tiles } where modifyTerrain terrain = terrain tiles = tileFloor0 V.++ tileFloor1 tileFloor0 = makeLevel [ "##########" , "#.....##.#" , "#.....##.#" , "#.....##.#" , "#.....##.#" , "####..##x#" , "#..#####.#" , "#..#...#.#" , "#....#.#.#" , "##########" ] tileFloor1 = makeLevel [ "##########" , "#........#" , "#........#" , "#..+.....#" , "#....+...#" , "####...#x#" , "#..#####.#" , "#..#...#.#" , "#....#...#" , "##########" ] makeLevel = V.fromList . concatMap (map (tile . tileTypeFromChar)) . reverse tile t = Tile { _tileCreatures = IS.empty , _tileItems = IS.empty , _tileType = t , _tileBuildings = IS.empty , _tileReserved = Nothing } simpleAI :: AI simpleAI = defaultAI & aiPlan .~ PlanPickUpItem (ObjId 4) -- & aiPlan .~ PlanDig (7, 3, 1) & aiPlanState .~ PlanStarted simpleAct :: Creature -> State World () simpleAct creature = do newCreature <- runAI creature objLens (creature ^. creatureId) ?= newCreature simpleCreature :: Creature simpleCreature = Creature { _creatureName = nameGenerator , _creatureType = CreatureNefle , _creatureId = ObjId 1 , _creaturePos = (5, 3, 1) , _creatureAct = simpleAct , _creatureState = simpleAI , _creatureItems = [] } simpleItem :: Point -> Item simpleItem pos = Item { _itemId = ObjId 0 , _itemType = Bed , _itemMaterial = Iron , _itemState = ItemPos pos }
skeskinen/neflEFortress
WorldGenerating.hs
mit
2,830
0
16
832
745
433
312
92
1
{-# OPTIONS_GHC -fno-warn-orphans #-} -- | Test code and properties for "Codec.Compression.Zlib.Stream" -- module Test.Codec.Compression.Zlib.Stream where import Codec.Compression.Zlib.Internal import Test.QuickCheck instance Arbitrary Format where -- GZipOrZlib omitted since it's not symmetric arbitrary = elements [gzipFormat, zlibFormat, rawFormat] instance Arbitrary Method where arbitrary = return deflateMethod instance Arbitrary CompressionLevel where arbitrary = elements $ [defaultCompression, noCompression, bestCompression, bestSpeed] ++ map compressionLevel [1..9] instance Arbitrary WindowBits where arbitrary = elements $ defaultWindowBits:map windowBits [9..15] instance Arbitrary MemoryLevel where arbitrary = elements $ [defaultMemoryLevel, minMemoryLevel, maxMemoryLevel] ++ [memoryLevel n | n <- [1..9]] instance Arbitrary CompressionStrategy where arbitrary = elements $ [defaultStrategy, filteredStrategy, huffmanOnlyStrategy] -- These are disabled by default in the package -- as they are only available with zlib >=1.2 -- ++ [RLE, Fixed]
CloudI/CloudI
src/api/haskell/external/zlib-0.6.2.1/test/Test/Codec/Compression/Zlib/Stream.hs
mit
1,219
0
10
280
218
126
92
19
0
-------------------------------------------------------------------------------- {-| Module : Seq Copyright : (c) Daan Leijen 2002 License : BSD-style Maintainer : daan@cs.uu.nl Stability : provisional Portability : portable An implementation of John Hughes's efficient catenable sequence type. A lazy sequence @Seq a@ can be concatenated in /O(1)/ time. After construction, the sequence in converted in /O(n)/ time into a list. Modified by John Meacham for use in jhc -} ---------------------------------------------------------------------------------} module Util.Seq( -- * Type Seq -- * Operators , (<>) -- * Construction , empty , single , singleton , cons , append -- * Conversion , toList , fromList ) where import Data.Monoid(Monoid(..)) import Control.Monad {-------------------------------------------------------------------- Operators --------------------------------------------------------------------} infixr 5 <> -- | /O(1)/. Append two sequences, see 'append'. (<>) :: Seq a -> Seq a -> Seq a s <> t = append s t {-------------------------------------------------------------------- Type --------------------------------------------------------------------} -- | Sequences of values @a@. newtype Seq a = Seq ([a] -> [a]) {-------------------------------------------------------------------- Construction --------------------------------------------------------------------} -- | /O(1)/. Create an empty sequence. empty :: Seq a empty = Seq (\ts -> ts) -- | /O(1)/. Create a sequence of one element. single :: a -> Seq a single x = Seq (\ts -> x:ts) -- | /O(1)/. Create a sequence of one element. singleton :: a -> Seq a singleton x = single x -- | /O(1)/. Put a value in front of a sequence. cons :: a -> Seq a -> Seq a cons x (Seq f) = Seq (\ts -> x:f ts) -- | /O(1)/. Append two sequences. append :: Seq a -> Seq a -> Seq a append (Seq f) (Seq g) = Seq (\ts -> f (g ts)) {-------------------------------------------------------------------- Conversion --------------------------------------------------------------------} -- | /O(n)/. Convert a sequence to a list. toList :: Seq a -> [a] toList (Seq f) = f [] -- | /O(n)/. Create a sequence from a list. fromList :: [a] -> Seq a fromList xs = Seq (\ts -> xs++ts) --tell x = W.tell (Util.Seq.singleton x) --tells xs = W.tell (Util.Seq.fromList xs) concat :: Seq (Seq a) -> Seq a concat (Seq f) = (foldr Util.Seq.append Util.Seq.empty (f [])) instance Functor Util.Seq.Seq where --fmap f xs = Seq.fromList (map f (Seq.toList xs)) fmap f (Seq xs) = Seq (\ts -> map f (xs []) ++ ts ) instance Monad Util.Seq.Seq where --a >>= b = mconcat ( fmap b (Seq.toList a)) a >>= b = Util.Seq.concat (fmap b a) return x = Util.Seq.single x fail _ = Util.Seq.empty instance MonadPlus Util.Seq.Seq where mplus = mappend mzero = Util.Seq.empty instance Monoid (Seq a) where mempty = empty mappend = append
dec9ue/jhc_copygc
src/Util/Seq.hs
gpl-2.0
3,135
0
13
703
641
349
292
51
1
-- | Simple linear regression example for the README. import Control.Monad (replicateM, replicateM_, zipWithM) import System.Random (randomIO) import Test.HUnit (assertBool) import qualified TensorFlow.Core as TF import qualified TensorFlow.GenOps.Core as TF import qualified TensorFlow.Gradient as TF import qualified TensorFlow.Ops as TF main :: IO () main = do -- Generate data where `y = x*3 + 8`. xData <- replicateM 100 randomIO let yData = [x*3 + 8 | x <- xData] -- Fit linear regression model. (w, b) <- fit xData yData assertBool "w == 3" (abs (3 - w) < 0.001) assertBool "b == 8" (abs (8 - b) < 0.001) fit :: [Float] -> [Float] -> IO (Float, Float) fit xData yData = TF.runSession $ do -- Create tensorflow constants for x and y. let x = TF.vector xData y = TF.vector yData -- Create scalar variables for slope and intercept. w <- TF.initializedVariable 0 b <- TF.initializedVariable 0 -- Define the loss function. let yHat = (x `TF.mul` w) `TF.add` b loss = TF.square (yHat `TF.sub` y) -- Optimize with gradient descent. trainStep <- gradientDescent 0.001 loss [w, b] replicateM_ 1000 (TF.run trainStep) -- Return the learned parameters. (TF.Scalar w', TF.Scalar b') <- TF.run (w, b) return (w', b') gradientDescent :: Float -> TF.Tensor TF.Build Float -> [TF.Tensor TF.Ref Float] -> TF.Session TF.ControlNode gradientDescent alpha loss params = do let applyGrad param grad = TF.assign param (param `TF.sub` (TF.scalar alpha `TF.mul` grad)) TF.group =<< zipWithM applyGrad params =<< TF.gradients loss params
cem3394/haskell
tensorflow-ops/tests/RegressionTest.hs
apache-2.0
1,689
0
16
413
554
292
262
34
1
{-# LANGUAGE EmptyDataDecls, RankNTypes, ScopedTypeVariables #-} module Network.IPTables.Generated(Int, Num, Nat, integer_of_nat, Word, Len, Iface(..), nat_of_integer, Bit0, Num1, Match_expr(..), Action(..), Rule(..), Protocol(..), Tcp_flag(..), Ctstate(..), Linord_helper, Set, Ipt_tcp_flags(..), Ipt_iprange(..), Ipt_l4_ports, Common_primitive(..), Ipv6addr_syntax(..), Prefix_match(..), Wordinterval, Negation_type(..), Simple_match_ext, Simple_action(..), Simple_rule, Routing_action_ext(..), Routing_rule_ext(..), Parts_connection_ext, ah, esp, gre, tcp, udp, icmp, sctp, mk_Set, ipassmt_diff, iPv6ICMP, map_of_ipassmt, to_ipassmt, sort_rtbl, alist_and, optimize_matches, upper_closure, word_to_nat, has_default_policy, word_less_eq, int_to_ipv6preferred, ipv6preferred_to_int, ipassmt_sanity_defined, debug_ipassmt_ipv4, debug_ipassmt_ipv6, no_spoofing_iface, nat_to_8word, mk_L4Ports_pre, ipv4addr_of_dotdecimal, empty_rr_hlp, sanity_wf_ruleset, routing_ipassmt, map_of_string, nat_to_16word, ipassmt_generic_ipv4, ipassmt_generic_ipv6, mk_ipv6addr, default_prefix, sanity_ip_route, fill_l4_protocol, integer_to_16word, rewrite_Goto_safe, simple_fw_valid, compress_parsed_extra, prefix_match_32_toString, routing_rule_32_toString, mk_parts_connection_TCP, to_simple_firewall, prefix_match_128_toString, routing_rule_128_toString, unfold_ruleset_CHAIN_safe, metric_update, access_matrix_pretty_ipv4, access_matrix_pretty_ipv6, action_toString, packet_assume_new, routing_action_oiface_update, simple_rule_ipv4_toString, simple_rule_ipv6_toString, routing_action_next_hop_update, abstract_for_simple_firewall, ipt_ipv4range_toString, ipt_ipv6range_toString, common_primitive_ipv4_toString, common_primitive_ipv6_toString, to_simple_firewall_without_interfaces, common_primitive_match_expr_ipv4_toString, common_primitive_match_expr_ipv6_toString) where { import Prelude ((==), (/=), (<), (<=), (>=), (>), (+), (-), (*), (/), (**), (>>=), (>>), (=<<), (&&), (||), (^), (^^), (.), ($), ($!), (++), (!!), Eq, error, id, return, not, fst, snd, map, filter, concat, concatMap, reverse, zip, null, takeWhile, dropWhile, all, any, Integer, negate, abs, divMod, String, Bool(True, False), Maybe(Nothing, Just)); import qualified Prelude; import qualified Data_Bits; newtype Int = Int_of_integer Integer; integer_of_int :: Int -> Integer; integer_of_int (Int_of_integer k) = k; equal_int :: Int -> Int -> Bool; equal_int k l = integer_of_int k == integer_of_int l; instance Eq Int where { a == b = equal_int a b; }; data Num = One | Bit0 Num | Bit1 Num; one_int :: Int; one_int = Int_of_integer (1 :: Integer); class One a where { one :: a; }; instance One Int where { one = one_int; }; times_int :: Int -> Int -> Int; times_int k l = Int_of_integer (integer_of_int k * integer_of_int l); class Times a where { times :: a -> a -> a; }; class (One a, Times a) => Power a where { }; instance Times Int where { times = times_int; }; instance Power Int where { }; less_eq_int :: Int -> Int -> Bool; less_eq_int k l = integer_of_int k <= integer_of_int l; class Ord a where { less_eq :: a -> a -> Bool; less :: a -> a -> Bool; }; less_int :: Int -> Int -> Bool; less_int k l = integer_of_int k < integer_of_int l; instance Ord Int where { less_eq = less_eq_int; less = less_int; }; class (Ord a) => Preorder a where { }; class (Preorder a) => Order a where { }; instance Preorder Int where { }; instance Order Int where { }; class (Order a) => Linorder a where { }; instance Linorder Int where { }; newtype Nat = Nat Integer; integer_of_nat :: Nat -> Integer; integer_of_nat (Nat x) = x; equal_nat :: Nat -> Nat -> Bool; equal_nat m n = integer_of_nat m == integer_of_nat n; instance Eq Nat where { a == b = equal_nat a b; }; zero_nat :: Nat; zero_nat = Nat (0 :: Integer); class Zero a where { zero :: a; }; instance Zero Nat where { zero = zero_nat; }; less_eq_nat :: Nat -> Nat -> Bool; less_eq_nat m n = integer_of_nat m <= integer_of_nat n; less_nat :: Nat -> Nat -> Bool; less_nat m n = integer_of_nat m < integer_of_nat n; instance Ord Nat where { less_eq = less_eq_nat; less = less_nat; }; instance Preorder Nat where { }; instance Order Nat where { }; instance Linorder Nat where { }; data Itself a = Type; class Len0 a where { len_of :: Itself a -> Nat; }; newtype Word a = Word Int; uint :: forall a. (Len0 a) => Word a -> Int; uint (Word x) = x; equal_word :: forall a. (Len0 a) => Word a -> Word a -> Bool; equal_word k l = equal_int (uint k) (uint l); instance (Len0 a) => Eq (Word a) where { a == b = equal_word a b; }; sgn_integer :: Integer -> Integer; sgn_integer k = (if k == (0 :: Integer) then (0 :: Integer) else (if k < (0 :: Integer) then (-1 :: Integer) else (1 :: Integer))); apsnd :: forall a b c. (a -> b) -> (c, a) -> (c, b); apsnd f (x, y) = (x, f y); divmod_integer :: Integer -> Integer -> (Integer, Integer); divmod_integer k l = (if k == (0 :: Integer) then ((0 :: Integer), (0 :: Integer)) else (if l == (0 :: Integer) then ((0 :: Integer), k) else ((apsnd . (\ a b -> a * b)) . sgn_integer) l (if sgn_integer k == sgn_integer l then divMod (abs k) (abs l) else let { (r, s) = divMod (abs k) (abs l); } in (if s == (0 :: Integer) then (negate r, (0 :: Integer)) else (negate r - (1 :: Integer), Prelude.abs l - s))))); modulo_integer :: Integer -> Integer -> Integer; modulo_integer k l = snd (divmod_integer k l); modulo_int :: Int -> Int -> Int; modulo_int k l = Int_of_integer (modulo_integer (integer_of_int k) (integer_of_int l)); max :: forall a. (Ord a) => a -> a -> a; max a b = (if less_eq a b then b else a); instance Ord Integer where { less_eq = (\ a b -> a <= b); less = (\ a b -> a < b); }; minus_nat :: Nat -> Nat -> Nat; minus_nat m n = Nat (max (0 :: Integer) (integer_of_nat m - integer_of_nat n)); one_nat :: Nat; one_nat = Nat (1 :: Integer); power :: forall a. (Power a) => a -> Nat -> a; power a n = (if equal_nat n zero_nat then one else times a (power a (minus_nat n one_nat))); word_of_int :: forall a. (Len0 a) => Int -> Word a; word_of_int k = Word (modulo_int k (power (Int_of_integer (2 :: Integer)) ((len_of :: Itself a -> Nat) Type))); one_word :: forall a. (Len0 a) => Word a; one_word = word_of_int (Int_of_integer (1 :: Integer)); instance (Len0 a) => One (Word a) where { one = one_word; }; plus_int :: Int -> Int -> Int; plus_int k l = Int_of_integer (integer_of_int k + integer_of_int l); plus_word :: forall a. (Len0 a) => Word a -> Word a -> Word a; plus_word a b = word_of_int (plus_int (uint a) (uint b)); class Plus a where { plus :: a -> a -> a; }; instance (Len0 a) => Plus (Word a) where { plus = plus_word; }; zero_int :: Int; zero_int = Int_of_integer (0 :: Integer); zero_word :: forall a. (Len0 a) => Word a; zero_word = word_of_int zero_int; instance (Len0 a) => Zero (Word a) where { zero = zero_word; }; class (Plus a) => Semigroup_add a where { }; class (One a, Semigroup_add a) => Numeral a where { }; instance (Len0 a) => Semigroup_add (Word a) where { }; instance (Len0 a) => Numeral (Word a) where { }; times_word :: forall a. (Len0 a) => Word a -> Word a -> Word a; times_word a b = word_of_int (times_int (uint a) (uint b)); instance (Len0 a) => Times (Word a) where { times = times_word; }; instance (Len0 a) => Power (Word a) where { }; less_eq_word :: forall a. (Len0 a) => Word a -> Word a -> Bool; less_eq_word a b = less_eq_int (uint a) (uint b); less_word :: forall a. (Len0 a) => Word a -> Word a -> Bool; less_word a b = less_int (uint a) (uint b); instance (Len0 a) => Ord (Word a) where { less_eq = less_eq_word; less = less_word; }; class (Semigroup_add a) => Ab_semigroup_add a where { }; class (Times a) => Semigroup_mult a where { }; class (Ab_semigroup_add a, Semigroup_mult a) => Semiring a where { }; instance (Len0 a) => Ab_semigroup_add (Word a) where { }; instance (Len0 a) => Semigroup_mult (Word a) where { }; instance (Len0 a) => Semiring (Word a) where { }; instance (Len0 a) => Preorder (Word a) where { }; instance (Len0 a) => Order (Word a) where { }; class (Times a, Zero a) => Mult_zero a where { }; instance (Len0 a) => Mult_zero (Word a) where { }; class (Semigroup_add a, Zero a) => Monoid_add a where { }; class (Ab_semigroup_add a, Monoid_add a) => Comm_monoid_add a where { }; class (Comm_monoid_add a, Mult_zero a, Semiring a) => Semiring_0 a where { }; instance (Len0 a) => Monoid_add (Word a) where { }; instance (Len0 a) => Comm_monoid_add (Word a) where { }; instance (Len0 a) => Semiring_0 (Word a) where { }; class (Semigroup_mult a, Power a) => Monoid_mult a where { }; class (Monoid_mult a, Numeral a, Semiring a) => Semiring_numeral a where { }; class (One a, Zero a) => Zero_neq_one a where { }; class (Semiring_numeral a, Semiring_0 a, Zero_neq_one a) => Semiring_1 a where { }; class (Len0 a) => Len a where { }; instance (Len0 a) => Monoid_mult (Word a) where { }; instance (Len a) => Semiring_numeral (Word a) where { }; instance (Len a) => Zero_neq_one (Word a) where { }; instance (Len a) => Semiring_1 (Word a) where { }; instance (Len0 a) => Linorder (Word a) where { }; newtype Iface = Iface [Prelude.Char]; equal_iface :: Iface -> Iface -> Bool; equal_iface (Iface x) (Iface ya) = x == ya; instance Eq Iface where { a == b = equal_iface a b; }; less_eq_iface :: Iface -> Iface -> Bool; less_eq_iface (Iface []) (Iface uu) = True; less_eq_iface (Iface (v : va)) (Iface []) = False; less_eq_iface (Iface (a : asa)) (Iface (b : bs)) = (if a == b then less_eq_iface (Iface asa) (Iface bs) else a <= b); less_iface :: Iface -> Iface -> Bool; less_iface (Iface []) (Iface []) = False; less_iface (Iface []) (Iface (v : va)) = True; less_iface (Iface (v : va)) (Iface []) = False; less_iface (Iface (a : asa)) (Iface (b : bs)) = (if a == b then less_iface (Iface asa) (Iface bs) else a < b); instance Ord Iface where { less_eq = less_eq_iface; less = less_iface; }; instance Preorder Iface where { }; instance Order Iface where { }; instance Linorder Iface where { }; times_nat :: Nat -> Nat -> Nat; times_nat m n = Nat (integer_of_nat m * integer_of_nat n); nat_of_integer :: Integer -> Nat; nat_of_integer k = Nat (max (0 :: Integer) k); class Finite a where { }; newtype Bit0 a = Abs_bit0 Int; len_of_bit0 :: forall a. (Len0 a) => Itself (Bit0 a) -> Nat; len_of_bit0 uu = times_nat (nat_of_integer (2 :: Integer)) ((len_of :: Itself a -> Nat) Type); instance (Len0 a) => Len0 (Bit0 a) where { len_of = len_of_bit0; }; instance (Len a) => Len (Bit0 a) where { }; data Num1 = One_num1; len_of_num1 :: Itself Num1 -> Nat; len_of_num1 uu = one_nat; instance Len0 Num1 where { len_of = len_of_num1; }; instance Len Num1 where { }; less_eq_prod :: forall a b. (Ord a, Ord b) => (a, b) -> (a, b) -> Bool; less_eq_prod (x1, y1) (x2, y2) = less x1 x2 || less_eq x1 x2 && less_eq y1 y2; less_prod :: forall a b. (Ord a, Ord b) => (a, b) -> (a, b) -> Bool; less_prod (x1, y1) (x2, y2) = less x1 x2 || less_eq x1 x2 && less y1 y2; instance (Ord a, Ord b) => Ord (a, b) where { less_eq = less_eq_prod; less = less_prod; }; instance (Preorder a, Preorder b) => Preorder (a, b) where { }; instance (Order a, Order b) => Order (a, b) where { }; instance (Linorder a, Linorder b) => Linorder (a, b) where { }; data Match_expr a = Match a | MatchNot (Match_expr a) | MatchAnd (Match_expr a) (Match_expr a) | MatchAny; equal_match_expr :: forall a. (Eq a) => Match_expr a -> Match_expr a -> Bool; equal_match_expr (MatchAnd x31 x32) MatchAny = False; equal_match_expr MatchAny (MatchAnd x31 x32) = False; equal_match_expr (MatchNot x2) MatchAny = False; equal_match_expr MatchAny (MatchNot x2) = False; equal_match_expr (MatchNot x2) (MatchAnd x31 x32) = False; equal_match_expr (MatchAnd x31 x32) (MatchNot x2) = False; equal_match_expr (Match x1) MatchAny = False; equal_match_expr MatchAny (Match x1) = False; equal_match_expr (Match x1) (MatchAnd x31 x32) = False; equal_match_expr (MatchAnd x31 x32) (Match x1) = False; equal_match_expr (Match x1) (MatchNot x2) = False; equal_match_expr (MatchNot x2) (Match x1) = False; equal_match_expr (MatchAnd x31 x32) (MatchAnd y31 y32) = equal_match_expr x31 y31 && equal_match_expr x32 y32; equal_match_expr (MatchNot x2) (MatchNot y2) = equal_match_expr x2 y2; equal_match_expr (Match x1) (Match y1) = x1 == y1; equal_match_expr MatchAny MatchAny = True; data Action = Accept | Drop | Log | Reject | Call [Prelude.Char] | Return | Goto [Prelude.Char] | Empty | Unknown; equal_action :: Action -> Action -> Bool; equal_action Empty Unknown = False; equal_action Unknown Empty = False; equal_action (Goto x7) Unknown = False; equal_action Unknown (Goto x7) = False; equal_action (Goto x7) Empty = False; equal_action Empty (Goto x7) = False; equal_action Return Unknown = False; equal_action Unknown Return = False; equal_action Return Empty = False; equal_action Empty Return = False; equal_action Return (Goto x7) = False; equal_action (Goto x7) Return = False; equal_action (Call x5) Unknown = False; equal_action Unknown (Call x5) = False; equal_action (Call x5) Empty = False; equal_action Empty (Call x5) = False; equal_action (Call x5) (Goto x7) = False; equal_action (Goto x7) (Call x5) = False; equal_action (Call x5) Return = False; equal_action Return (Call x5) = False; equal_action Reject Unknown = False; equal_action Unknown Reject = False; equal_action Reject Empty = False; equal_action Empty Reject = False; equal_action Reject (Goto x7) = False; equal_action (Goto x7) Reject = False; equal_action Reject Return = False; equal_action Return Reject = False; equal_action Reject (Call x5) = False; equal_action (Call x5) Reject = False; equal_action Log Unknown = False; equal_action Unknown Log = False; equal_action Log Empty = False; equal_action Empty Log = False; equal_action Log (Goto x7) = False; equal_action (Goto x7) Log = False; equal_action Log Return = False; equal_action Return Log = False; equal_action Log (Call x5) = False; equal_action (Call x5) Log = False; equal_action Log Reject = False; equal_action Reject Log = False; equal_action Drop Unknown = False; equal_action Unknown Drop = False; equal_action Drop Empty = False; equal_action Empty Drop = False; equal_action Drop (Goto x7) = False; equal_action (Goto x7) Drop = False; equal_action Drop Return = False; equal_action Return Drop = False; equal_action Drop (Call x5) = False; equal_action (Call x5) Drop = False; equal_action Drop Reject = False; equal_action Reject Drop = False; equal_action Drop Log = False; equal_action Log Drop = False; equal_action Accept Unknown = False; equal_action Unknown Accept = False; equal_action Accept Empty = False; equal_action Empty Accept = False; equal_action Accept (Goto x7) = False; equal_action (Goto x7) Accept = False; equal_action Accept Return = False; equal_action Return Accept = False; equal_action Accept (Call x5) = False; equal_action (Call x5) Accept = False; equal_action Accept Reject = False; equal_action Reject Accept = False; equal_action Accept Log = False; equal_action Log Accept = False; equal_action Accept Drop = False; equal_action Drop Accept = False; equal_action (Goto x7) (Goto y7) = x7 == y7; equal_action (Call x5) (Call y5) = x5 == y5; equal_action Unknown Unknown = True; equal_action Empty Empty = True; equal_action Return Return = True; equal_action Reject Reject = True; equal_action Log Log = True; equal_action Drop Drop = True; equal_action Accept Accept = True; data Rule a = Rule (Match_expr a) Action; equal_rule :: forall a. (Eq a) => Rule a -> Rule a -> Bool; equal_rule (Rule x1 x2) (Rule y1 y2) = equal_match_expr x1 y1 && equal_action x2 y2; instance (Eq a) => Eq (Rule a) where { a == b = equal_rule a b; }; data Protocol = ProtoAny | Proto (Word (Bit0 (Bit0 (Bit0 Num1)))); equal_protocol :: Protocol -> Protocol -> Bool; equal_protocol ProtoAny (Proto x2) = False; equal_protocol (Proto x2) ProtoAny = False; equal_protocol (Proto x2) (Proto y2) = equal_word x2 y2; equal_protocol ProtoAny ProtoAny = True; instance Eq Protocol where { a == b = equal_protocol a b; }; data Tcp_flag = TCP_SYN | TCP_ACK | TCP_FIN | TCP_RST | TCP_URG | TCP_PSH; enum_all_tcp_flag :: (Tcp_flag -> Bool) -> Bool; enum_all_tcp_flag p = p TCP_SYN && p TCP_ACK && p TCP_FIN && p TCP_RST && p TCP_URG && p TCP_PSH; enum_ex_tcp_flag :: (Tcp_flag -> Bool) -> Bool; enum_ex_tcp_flag p = p TCP_SYN || (p TCP_ACK || (p TCP_FIN || (p TCP_RST || (p TCP_URG || p TCP_PSH)))); enum_tcp_flag :: [Tcp_flag]; enum_tcp_flag = [TCP_SYN, TCP_ACK, TCP_FIN, TCP_RST, TCP_URG, TCP_PSH]; class (Finite a) => Enum a where { enum :: [a]; enum_all :: (a -> Bool) -> Bool; enum_ex :: (a -> Bool) -> Bool; }; instance Finite Tcp_flag where { }; instance Enum Tcp_flag where { enum = enum_tcp_flag; enum_all = enum_all_tcp_flag; enum_ex = enum_ex_tcp_flag; }; equal_tcp_flag :: Tcp_flag -> Tcp_flag -> Bool; equal_tcp_flag TCP_URG TCP_PSH = False; equal_tcp_flag TCP_PSH TCP_URG = False; equal_tcp_flag TCP_RST TCP_PSH = False; equal_tcp_flag TCP_PSH TCP_RST = False; equal_tcp_flag TCP_RST TCP_URG = False; equal_tcp_flag TCP_URG TCP_RST = False; equal_tcp_flag TCP_FIN TCP_PSH = False; equal_tcp_flag TCP_PSH TCP_FIN = False; equal_tcp_flag TCP_FIN TCP_URG = False; equal_tcp_flag TCP_URG TCP_FIN = False; equal_tcp_flag TCP_FIN TCP_RST = False; equal_tcp_flag TCP_RST TCP_FIN = False; equal_tcp_flag TCP_ACK TCP_PSH = False; equal_tcp_flag TCP_PSH TCP_ACK = False; equal_tcp_flag TCP_ACK TCP_URG = False; equal_tcp_flag TCP_URG TCP_ACK = False; equal_tcp_flag TCP_ACK TCP_RST = False; equal_tcp_flag TCP_RST TCP_ACK = False; equal_tcp_flag TCP_ACK TCP_FIN = False; equal_tcp_flag TCP_FIN TCP_ACK = False; equal_tcp_flag TCP_SYN TCP_PSH = False; equal_tcp_flag TCP_PSH TCP_SYN = False; equal_tcp_flag TCP_SYN TCP_URG = False; equal_tcp_flag TCP_URG TCP_SYN = False; equal_tcp_flag TCP_SYN TCP_RST = False; equal_tcp_flag TCP_RST TCP_SYN = False; equal_tcp_flag TCP_SYN TCP_FIN = False; equal_tcp_flag TCP_FIN TCP_SYN = False; equal_tcp_flag TCP_SYN TCP_ACK = False; equal_tcp_flag TCP_ACK TCP_SYN = False; equal_tcp_flag TCP_PSH TCP_PSH = True; equal_tcp_flag TCP_URG TCP_URG = True; equal_tcp_flag TCP_RST TCP_RST = True; equal_tcp_flag TCP_FIN TCP_FIN = True; equal_tcp_flag TCP_ACK TCP_ACK = True; equal_tcp_flag TCP_SYN TCP_SYN = True; instance Eq Tcp_flag where { a == b = equal_tcp_flag a b; }; data Ctstate = CT_New | CT_Established | CT_Related | CT_Untracked | CT_Invalid; enum_all_ctstate :: (Ctstate -> Bool) -> Bool; enum_all_ctstate p = p CT_New && p CT_Established && p CT_Related && p CT_Untracked && p CT_Invalid; enum_ex_ctstate :: (Ctstate -> Bool) -> Bool; enum_ex_ctstate p = p CT_New || (p CT_Established || (p CT_Related || (p CT_Untracked || p CT_Invalid))); enum_ctstate :: [Ctstate]; enum_ctstate = [CT_New, CT_Established, CT_Related, CT_Untracked, CT_Invalid]; instance Finite Ctstate where { }; instance Enum Ctstate where { enum = enum_ctstate; enum_all = enum_all_ctstate; enum_ex = enum_ex_ctstate; }; equal_ctstate :: Ctstate -> Ctstate -> Bool; equal_ctstate CT_Untracked CT_Invalid = False; equal_ctstate CT_Invalid CT_Untracked = False; equal_ctstate CT_Related CT_Invalid = False; equal_ctstate CT_Invalid CT_Related = False; equal_ctstate CT_Related CT_Untracked = False; equal_ctstate CT_Untracked CT_Related = False; equal_ctstate CT_Established CT_Invalid = False; equal_ctstate CT_Invalid CT_Established = False; equal_ctstate CT_Established CT_Untracked = False; equal_ctstate CT_Untracked CT_Established = False; equal_ctstate CT_Established CT_Related = False; equal_ctstate CT_Related CT_Established = False; equal_ctstate CT_New CT_Invalid = False; equal_ctstate CT_Invalid CT_New = False; equal_ctstate CT_New CT_Untracked = False; equal_ctstate CT_Untracked CT_New = False; equal_ctstate CT_New CT_Related = False; equal_ctstate CT_Related CT_New = False; equal_ctstate CT_New CT_Established = False; equal_ctstate CT_Established CT_New = False; equal_ctstate CT_Invalid CT_Invalid = True; equal_ctstate CT_Untracked CT_Untracked = True; equal_ctstate CT_Related CT_Related = True; equal_ctstate CT_Established CT_Established = True; equal_ctstate CT_New CT_New = True; instance Eq Ctstate where { a == b = equal_ctstate a b; }; instance (Eq a) => Eq (Match_expr a) where { a == b = equal_match_expr a b; }; data Linord_helper a b = LinordHelper a b; linord_helper_less_eq1 :: forall a b. (Eq a, Ord a, Ord b) => Linord_helper a b -> Linord_helper a b -> Bool; linord_helper_less_eq1 a b = let { (LinordHelper a1 a2) = a; (LinordHelper b1 b2) = b; } in less a1 b1 || a1 == b1 && less_eq a2 b2; less_eq_linord_helper :: forall a b. (Eq a, Linorder a, Linorder b) => Linord_helper a b -> Linord_helper a b -> Bool; less_eq_linord_helper a b = linord_helper_less_eq1 a b; equal_linord_helper :: forall a b. (Eq a, Eq b) => Linord_helper a b -> Linord_helper a b -> Bool; equal_linord_helper (LinordHelper x1 x2) (LinordHelper y1 y2) = x1 == y1 && x2 == y2; less_linord_helper :: forall a b. (Eq a, Linorder a, Eq b, Linorder b) => Linord_helper a b -> Linord_helper a b -> Bool; less_linord_helper a b = not (equal_linord_helper a b) && linord_helper_less_eq1 a b; instance (Eq a, Linorder a, Eq b, Linorder b) => Ord (Linord_helper a b) where { less_eq = less_eq_linord_helper; less = less_linord_helper; }; instance (Eq a, Linorder a, Eq b, Linorder b) => Preorder (Linord_helper a b) where { }; instance (Eq a, Linorder a, Eq b, Linorder b) => Order (Linord_helper a b) where { }; instance (Eq a, Linorder a, Eq b, Linorder b) => Linorder (Linord_helper a b) where { }; data Final_decision = FinalAllow | FinalDeny; equal_final_decision :: Final_decision -> Final_decision -> Bool; equal_final_decision FinalAllow FinalDeny = False; equal_final_decision FinalDeny FinalAllow = False; equal_final_decision FinalDeny FinalDeny = True; equal_final_decision FinalAllow FinalAllow = True; data State = Undecided | Decision Final_decision; equal_state :: State -> State -> Bool; equal_state Undecided (Decision x2) = False; equal_state (Decision x2) Undecided = False; equal_state (Decision x2) (Decision y2) = equal_final_decision x2 y2; equal_state Undecided Undecided = True; instance Eq State where { a == b = equal_state a b; }; data Set a = Set [a] | Coset [a]; data Ipt_tcp_flags = TCP_Flags (Set Tcp_flag) (Set Tcp_flag); membera :: forall a. (Eq a) => [a] -> a -> Bool; membera [] y = False; membera (x : xs) y = x == y || membera xs y; member :: forall a. (Eq a) => a -> Set a -> Bool; member x (Coset xs) = not (membera xs x); member x (Set xs) = membera xs x; less_eq_set :: forall a. (Eq a) => Set a -> Set a -> Bool; less_eq_set (Coset xs) (Set ys) = (if null xs && null ys then False else (error :: forall a. String -> (() -> a) -> a) "subset_eq (List.coset _) (List.set _) requires type class instance card_UNIV" (\ _ -> less_eq_set (Coset xs) (Set ys))); less_eq_set a (Coset ys) = all (\ y -> not (member y a)) ys; less_eq_set (Set xs) b = all (\ x -> member x b) xs; equal_set :: forall a. (Eq a) => Set a -> Set a -> Bool; equal_set a b = less_eq_set a b && less_eq_set b a; equal_ipt_tcp_flags :: Ipt_tcp_flags -> Ipt_tcp_flags -> Bool; equal_ipt_tcp_flags (TCP_Flags x1 x2) (TCP_Flags y1 y2) = equal_set x1 y1 && equal_set x2 y2; data Ipt_iprange a = IpAddr (Word a) | IpAddrNetmask (Word a) Nat | IpAddrRange (Word a) (Word a); data Ipt_l4_ports = L4Ports (Word (Bit0 (Bit0 (Bit0 Num1)))) [(Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))]; data Common_primitive a = Src (Ipt_iprange a) | Dst (Ipt_iprange a) | IIface Iface | OIface Iface | Prot Protocol | Src_Ports Ipt_l4_ports | Dst_Ports Ipt_l4_ports | MultiportPorts Ipt_l4_ports | L4_Flags Ipt_tcp_flags | CT_State (Set Ctstate) | Extra [Prelude.Char]; equal_ipt_iprange :: forall a. (Len a) => Ipt_iprange a -> Ipt_iprange a -> Bool; equal_ipt_iprange (IpAddrNetmask x21 x22) (IpAddrRange x31 x32) = False; equal_ipt_iprange (IpAddrRange x31 x32) (IpAddrNetmask x21 x22) = False; equal_ipt_iprange (IpAddr x1) (IpAddrRange x31 x32) = False; equal_ipt_iprange (IpAddrRange x31 x32) (IpAddr x1) = False; equal_ipt_iprange (IpAddr x1) (IpAddrNetmask x21 x22) = False; equal_ipt_iprange (IpAddrNetmask x21 x22) (IpAddr x1) = False; equal_ipt_iprange (IpAddrRange x31 x32) (IpAddrRange y31 y32) = equal_word x31 y31 && equal_word x32 y32; equal_ipt_iprange (IpAddrNetmask x21 x22) (IpAddrNetmask y21 y22) = equal_word x21 y21 && equal_nat x22 y22; equal_ipt_iprange (IpAddr x1) (IpAddr y1) = equal_word x1 y1; equal_ipt_l4_ports :: Ipt_l4_ports -> Ipt_l4_ports -> Bool; equal_ipt_l4_ports (L4Ports x1 x2) (L4Ports y1 y2) = equal_word x1 y1 && x2 == y2; equal_common_primitive :: forall a. (Len a) => Common_primitive a -> Common_primitive a -> Bool; equal_common_primitive (CT_State x10) (Extra x11) = False; equal_common_primitive (Extra x11) (CT_State x10) = False; equal_common_primitive (L4_Flags x9) (Extra x11) = False; equal_common_primitive (Extra x11) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (CT_State x10) = False; equal_common_primitive (CT_State x10) (L4_Flags x9) = False; equal_common_primitive (MultiportPorts x8) (Extra x11) = False; equal_common_primitive (Extra x11) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (CT_State x10) = False; equal_common_primitive (CT_State x10) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (MultiportPorts x8) = False; equal_common_primitive (Dst_Ports x7) (Extra x11) = False; equal_common_primitive (Extra x11) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (CT_State x10) = False; equal_common_primitive (CT_State x10) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (Dst_Ports x7) = False; equal_common_primitive (Src_Ports x6) (Extra x11) = False; equal_common_primitive (Extra x11) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (CT_State x10) = False; equal_common_primitive (CT_State x10) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (Src_Ports x6) = False; equal_common_primitive (Prot x5) (Extra x11) = False; equal_common_primitive (Extra x11) (Prot x5) = False; equal_common_primitive (Prot x5) (CT_State x10) = False; equal_common_primitive (CT_State x10) (Prot x5) = False; equal_common_primitive (Prot x5) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (Prot x5) = False; equal_common_primitive (Prot x5) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (Prot x5) = False; equal_common_primitive (Prot x5) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (Prot x5) = False; equal_common_primitive (Prot x5) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (Prot x5) = False; equal_common_primitive (OIface x4) (Extra x11) = False; equal_common_primitive (Extra x11) (OIface x4) = False; equal_common_primitive (OIface x4) (CT_State x10) = False; equal_common_primitive (CT_State x10) (OIface x4) = False; equal_common_primitive (OIface x4) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (OIface x4) = False; equal_common_primitive (OIface x4) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (OIface x4) = False; equal_common_primitive (OIface x4) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (OIface x4) = False; equal_common_primitive (OIface x4) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (OIface x4) = False; equal_common_primitive (OIface x4) (Prot x5) = False; equal_common_primitive (Prot x5) (OIface x4) = False; equal_common_primitive (IIface x3) (Extra x11) = False; equal_common_primitive (Extra x11) (IIface x3) = False; equal_common_primitive (IIface x3) (CT_State x10) = False; equal_common_primitive (CT_State x10) (IIface x3) = False; equal_common_primitive (IIface x3) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (IIface x3) = False; equal_common_primitive (IIface x3) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (IIface x3) = False; equal_common_primitive (IIface x3) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (IIface x3) = False; equal_common_primitive (IIface x3) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (IIface x3) = False; equal_common_primitive (IIface x3) (Prot x5) = False; equal_common_primitive (Prot x5) (IIface x3) = False; equal_common_primitive (IIface x3) (OIface x4) = False; equal_common_primitive (OIface x4) (IIface x3) = False; equal_common_primitive (Dst x2) (Extra x11) = False; equal_common_primitive (Extra x11) (Dst x2) = False; equal_common_primitive (Dst x2) (CT_State x10) = False; equal_common_primitive (CT_State x10) (Dst x2) = False; equal_common_primitive (Dst x2) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (Dst x2) = False; equal_common_primitive (Dst x2) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (Dst x2) = False; equal_common_primitive (Dst x2) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (Dst x2) = False; equal_common_primitive (Dst x2) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (Dst x2) = False; equal_common_primitive (Dst x2) (Prot x5) = False; equal_common_primitive (Prot x5) (Dst x2) = False; equal_common_primitive (Dst x2) (OIface x4) = False; equal_common_primitive (OIface x4) (Dst x2) = False; equal_common_primitive (Dst x2) (IIface x3) = False; equal_common_primitive (IIface x3) (Dst x2) = False; equal_common_primitive (Src x1) (Extra x11) = False; equal_common_primitive (Extra x11) (Src x1) = False; equal_common_primitive (Src x1) (CT_State x10) = False; equal_common_primitive (CT_State x10) (Src x1) = False; equal_common_primitive (Src x1) (L4_Flags x9) = False; equal_common_primitive (L4_Flags x9) (Src x1) = False; equal_common_primitive (Src x1) (MultiportPorts x8) = False; equal_common_primitive (MultiportPorts x8) (Src x1) = False; equal_common_primitive (Src x1) (Dst_Ports x7) = False; equal_common_primitive (Dst_Ports x7) (Src x1) = False; equal_common_primitive (Src x1) (Src_Ports x6) = False; equal_common_primitive (Src_Ports x6) (Src x1) = False; equal_common_primitive (Src x1) (Prot x5) = False; equal_common_primitive (Prot x5) (Src x1) = False; equal_common_primitive (Src x1) (OIface x4) = False; equal_common_primitive (OIface x4) (Src x1) = False; equal_common_primitive (Src x1) (IIface x3) = False; equal_common_primitive (IIface x3) (Src x1) = False; equal_common_primitive (Src x1) (Dst x2) = False; equal_common_primitive (Dst x2) (Src x1) = False; equal_common_primitive (Extra x11) (Extra y11) = x11 == y11; equal_common_primitive (CT_State x10) (CT_State y10) = equal_set x10 y10; equal_common_primitive (L4_Flags x9) (L4_Flags y9) = equal_ipt_tcp_flags x9 y9; equal_common_primitive (MultiportPorts x8) (MultiportPorts y8) = equal_ipt_l4_ports x8 y8; equal_common_primitive (Dst_Ports x7) (Dst_Ports y7) = equal_ipt_l4_ports x7 y7; equal_common_primitive (Src_Ports x6) (Src_Ports y6) = equal_ipt_l4_ports x6 y6; equal_common_primitive (Prot x5) (Prot y5) = equal_protocol x5 y5; equal_common_primitive (OIface x4) (OIface y4) = equal_iface x4 y4; equal_common_primitive (IIface x3) (IIface y3) = equal_iface x3 y3; equal_common_primitive (Dst x2) (Dst y2) = equal_ipt_iprange x2 y2; equal_common_primitive (Src x1) (Src y1) = equal_ipt_iprange x1 y1; instance (Len a) => Eq (Common_primitive a) where { a == b = equal_common_primitive a b; }; data Ipv6addr_syntax = IPv6AddrPreferred (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))); data Prefix_match a = PrefixMatch (Word a) Nat; data Wordinterval a = WordInterval (Word a) (Word a) | RangeUnion (Wordinterval a) (Wordinterval a); data Negation_type a = Pos a | Neg a; data Simple_match_ext a b = Simple_match_ext Iface Iface (Word a, Nat) (Word a, Nat) Protocol (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) b; data Simple_action = Accepta | Dropa; data Simple_rule a = SimpleRule (Simple_match_ext a ()) Simple_action; data Match_compress a = CannotMatch | MatchesAll | MatchExpr a; data Routing_action_ext a b = Routing_action_ext [Prelude.Char] (Maybe (Word a)) b; data Routing_rule_ext a b = Routing_rule_ext (Prefix_match a) Nat (Routing_action_ext a ()) b; data Simple_packet_ext a b = Simple_packet_ext [Prelude.Char] [Prelude.Char] (Word a) (Word a) (Word (Bit0 (Bit0 (Bit0 Num1)))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Set Tcp_flag) [Prelude.Char] b; data Parts_connection_ext a = Parts_connection_ext [Prelude.Char] [Prelude.Char] (Word (Bit0 (Bit0 (Bit0 Num1)))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) a; nat :: Int -> Nat; nat = nat_of_integer . integer_of_int; plus_nat :: Nat -> Nat -> Nat; plus_nat m n = Nat (integer_of_nat m + integer_of_nat n); suc :: Nat -> Nat; suc n = plus_nat n one_nat; nth :: forall a. [a] -> Nat -> a; nth (x : xs) n = (if equal_nat n zero_nat then x else nth xs (minus_nat n one_nat)); ball :: forall a. Set a -> (a -> Bool) -> Bool; ball (Set xs) p = all p xs; drop :: forall a. Nat -> [a] -> [a]; drop n [] = []; drop n (x : xs) = (if equal_nat n zero_nat then x : xs else drop (minus_nat n one_nat) xs); find :: forall a. (a -> Bool) -> [a] -> Maybe a; find uu [] = Nothing; find p (x : xs) = (if p x then Just x else find p xs); fold :: forall a b. (a -> b -> b) -> [a] -> b -> b; fold f (x : xs) s = fold f xs (f x s); fold f [] s = s; take :: forall a. Nat -> [a] -> [a]; take n [] = []; take n (x : xs) = (if equal_nat n zero_nat then [] else x : take (minus_nat n one_nat) xs); minus_int :: Int -> Int -> Int; minus_int k l = Int_of_integer (integer_of_int k - integer_of_int l); upto_aux :: Int -> Int -> [Int] -> [Int]; upto_aux i j js = (if less_int j i then js else upto_aux i (minus_int j (Int_of_integer (1 :: Integer))) (j : js)); upto :: Int -> Int -> [Int]; upto i j = upto_aux i j []; image :: forall a b. (a -> b) -> Set a -> Set b; image f (Set xs) = Set (map f xs); minus_word :: forall a. (Len0 a) => Word a -> Word a -> Word a; minus_word a b = word_of_int (minus_int (uint a) (uint b)); shiftl_integer :: Integer -> Nat -> Integer; shiftl_integer x n = (Data_Bits.shiftlUnbounded :: Integer -> Integer -> Integer) x (integer_of_nat n); bit_integer :: Integer -> Bool -> Integer; bit_integer i True = shiftl_integer i one_nat + (1 :: Integer); bit_integer i False = shiftl_integer i one_nat; bit :: Int -> Bool -> Int; bit (Int_of_integer i) b = Int_of_integer (bit_integer i b); shiftl1 :: forall a. (Len0 a) => Word a -> Word a; shiftl1 w = word_of_int (bit (uint w) False); funpow :: forall a. Nat -> (a -> a) -> a -> a; funpow n f = (if equal_nat n zero_nat then id else f . funpow (minus_nat n one_nat) f); shiftl_word :: forall a. (Len0 a) => Word a -> Nat -> Word a; shiftl_word w n = funpow n shiftl1 w; mask :: forall a. (Len a) => Nat -> Word a; mask n = minus_word (shiftl_word one_word n) one_word; unat :: forall a. (Len0 a) => Word a -> Nat; unat w = nat (uint w); foldr :: forall a b. (a -> b -> b) -> [a] -> b -> b; foldr f [] = id; foldr f (x : xs) = f x . foldr f xs; map_of :: forall a b. (Eq a) => [(a, b)] -> a -> Maybe b; map_of ((l, v) : ps) k = (if l == k then Just v else map_of ps k); map_of [] k = Nothing; merge :: forall a. (Eq a, Linorder a) => [a] -> [a] -> [a]; merge [] l2 = l2; merge (v : va) [] = v : va; merge (x1 : l1) (x2 : l2) = (if less x1 x2 then x1 : merge l1 (x2 : l2) else (if x1 == x2 then x1 : merge l1 l2 else x2 : merge (x1 : l1) l2)); removeAll :: forall a. (Eq a) => a -> [a] -> [a]; removeAll x [] = []; removeAll x (y : xs) = (if x == y then removeAll x xs else y : removeAll x xs); inserta :: forall a. (Eq a) => a -> [a] -> [a]; inserta x xs = (if membera xs x then xs else x : xs); insert :: forall a. (Eq a) => a -> Set a -> Set a; insert x (Coset xs) = Coset (removeAll x xs); insert x (Set xs) = Set (inserta x xs); remove :: forall a. (Eq a) => a -> Set a -> Set a; remove x (Coset xs) = Coset (inserta x xs); remove x (Set xs) = Set (removeAll x xs); ucast :: forall a b. (Len0 a, Len0 b) => Word a -> Word b; ucast w = word_of_int (uint w); splice :: forall a. [a] -> [a] -> [a]; splice (x : xs) (y : ys) = x : y : splice xs ys; splice [] ys = ys; splice xs [] = xs; butlast :: forall a. [a] -> [a]; butlast [] = []; butlast (x : xs) = (if null xs then [] else x : butlast xs); tl :: forall a. [a] -> [a]; tl [] = []; tl (x21 : x22) = x22; product :: forall a b. [a] -> [b] -> [(a, b)]; product [] uu = []; product (x : xs) ys = map (\ a -> (x, a)) ys ++ product xs ys; remdups :: forall a. (Eq a) => [a] -> [a]; remdups [] = []; remdups (x : xs) = (if membera xs x then remdups xs else x : remdups xs); is_empty :: forall a. Set a -> Bool; is_empty (Set xs) = null xs; bin_rest :: Int -> Int; bin_rest (Int_of_integer i) = Int_of_integer ((Data_Bits.shiftrUnbounded i 1 :: Integer)); shiftr1 :: forall a. (Len0 a) => Word a -> Word a; shiftr1 w = word_of_int (bin_rest (uint w)); select_p_tuple :: forall a. (a -> Bool) -> a -> ([a], [a]) -> ([a], [a]); select_p_tuple p x (ts, fs) = (if p x then (x : ts, fs) else (ts, x : fs)); partition_tailrec :: forall a. (a -> Bool) -> [a] -> ([a], [a]); partition_tailrec p xs = foldr (select_p_tuple p) xs ([], []); groupF_code :: forall a b. (Eq b) => (a -> b) -> [a] -> [[a]]; groupF_code f [] = []; groupF_code f (x : xs) = let { (ts, fs) = partition_tailrec (\ y -> f x == f y) xs; } in (x : ts) : groupF_code f fs; groupF :: forall a b. (Eq b) => (a -> b) -> [a] -> [[a]]; groupF f asa = groupF_code f asa; distinct :: forall a. (Eq a) => [a] -> Bool; distinct [] = True; distinct (x : xs) = not (membera xs x) && distinct xs; max_word :: forall a. (Len a) => Word a; max_word = word_of_int (minus_int (power (Int_of_integer (2 :: Integer)) ((len_of :: Itself a -> Nat) Type)) (Int_of_integer (1 :: Integer))); ifaceAny :: Iface; ifaceAny = Iface "+"; ah :: Word (Bit0 (Bit0 (Bit0 Num1))); ah = word_of_int (Int_of_integer (51 :: Integer)); replicate :: forall a. Nat -> a -> [a]; replicate n x = (if equal_nat n zero_nat then [] else x : replicate (minus_nat n one_nat) x); is_none :: forall a. Maybe a -> Bool; is_none (Just x) = False; is_none Nothing = True; esp :: Word (Bit0 (Bit0 (Bit0 Num1))); esp = word_of_int (Int_of_integer (50 :: Integer)); gre :: Word (Bit0 (Bit0 (Bit0 Num1))); gre = word_of_int (Int_of_integer (47 :: Integer)); tcp :: Word (Bit0 (Bit0 (Bit0 Num1))); tcp = word_of_int (Int_of_integer (6 :: Integer)); udp :: Word (Bit0 (Bit0 (Bit0 Num1))); udp = word_of_int (Int_of_integer (17 :: Integer)); gen_length :: forall a. Nat -> [a] -> Nat; gen_length n (x : xs) = gen_length (suc n) xs; gen_length n [] = n; map_filter :: forall a b. (a -> Maybe b) -> [a] -> [b]; map_filter f [] = []; map_filter f (x : xs) = (case f x of { Nothing -> map_filter f xs; Just y -> y : map_filter f xs; }); merge_list :: forall a. (Eq a, Linorder a) => [[a]] -> [[a]] -> [a]; merge_list [] [] = []; merge_list [] [l] = l; merge_list (la : acc2) [] = merge_list [] (la : acc2); merge_list (la : acc2) [l] = merge_list [] (l : la : acc2); merge_list acc2 (l1 : l2 : ls) = merge_list (merge l1 l2 : acc2) ls; int_of_nat :: Nat -> Int; int_of_nat n = Int_of_integer (integer_of_nat n); pfxes :: forall a. (Len0 a) => Itself a -> [Nat]; pfxes uu = map nat (upto zero_int (int_of_nat ((len_of :: Itself a -> Nat) Type))); icmp :: Word (Bit0 (Bit0 (Bit0 Num1))); icmp = one_word; igmp :: Word (Bit0 (Bit0 (Bit0 Num1))); igmp = word_of_int (Int_of_integer (2 :: Integer)); sctp :: Word (Bit0 (Bit0 (Bit0 Num1))); sctp = word_of_int (Int_of_integer (132 :: Integer)); uncurry :: forall a b c. (a -> b -> c) -> (a, b) -> c; uncurry f a = let { (aa, b) = a; } in f aa b; list_explode :: forall a. [[a]] -> [Maybe a]; list_explode [] = []; list_explode ([] : xs) = Nothing : list_explode xs; list_explode ((v : va) : xs2) = map Just (v : va) ++ list_explode xs2; internal_iface_name_match :: [Prelude.Char] -> [Prelude.Char] -> Bool; internal_iface_name_match [] [] = True; internal_iface_name_match (i : is) [] = i == '+' && null is; internal_iface_name_match [] (uu : uv) = False; internal_iface_name_match (i : is) (p_i : p_is) = (if i == '+' && null is then True else p_i == i && internal_iface_name_match is p_is); match_iface :: Iface -> [Prelude.Char] -> Bool; match_iface (Iface i) p_iface = internal_iface_name_match i p_iface; the :: forall a. Maybe a -> a; the (Just x2) = x2; empty_WordInterval :: forall a. (Len a) => Wordinterval a; empty_WordInterval = WordInterval one_word zero_word; l2wi :: forall a. (Len a) => [(Word a, Word a)] -> Wordinterval a; l2wi [] = empty_WordInterval; l2wi [(s, e)] = WordInterval s e; l2wi ((s, e) : v : va) = RangeUnion (WordInterval s e) (l2wi (v : va)); wi2l :: forall a. (Len0 a) => Wordinterval a -> [(Word a, Word a)]; wi2l (RangeUnion r1 r2) = wi2l r1 ++ wi2l r2; wi2l (WordInterval s e) = (if less_word e s then [] else [(s, e)]); modulo_nat :: Nat -> Nat -> Nat; modulo_nat m n = Nat (modulo_integer (integer_of_nat m) (integer_of_nat n)); divide_integer :: Integer -> Integer -> Integer; divide_integer k l = fst (divmod_integer k l); divide_nat :: Nat -> Nat -> Nat; divide_nat m n = Nat (divide_integer (integer_of_nat m) (integer_of_nat n)); divmod_nat :: Nat -> Nat -> (Nat, Nat); divmod_nat m n = (divide_nat m n, modulo_nat m n); list_replace1 :: forall a. (Eq a) => a -> a -> [a] -> [a]; list_replace1 uu uv [] = []; list_replace1 a b (x : xs) = (if a == x then b : xs else x : list_replace1 a b xs); goup_by_zeros :: [Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))] -> [[Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))]]; goup_by_zeros [] = []; goup_by_zeros (x : xs) = (if equal_word x zero_word then takeWhile (\ xa -> equal_word xa zero_word) (x : xs) : goup_by_zeros (dropWhile (\ xa -> equal_word xa zero_word) xs) else [x] : goup_by_zeros xs); size_list :: forall a. [a] -> Nat; size_list = gen_length zero_nat; iface_name_is_wildcard :: [Prelude.Char] -> Bool; iface_name_is_wildcard [] = False; iface_name_is_wildcard [s] = s == '+'; iface_name_is_wildcard (uu : v : va) = iface_name_is_wildcard (v : va); internal_iface_name_subset :: [Prelude.Char] -> [Prelude.Char] -> Bool; internal_iface_name_subset i1 i2 = (case (iface_name_is_wildcard i1, iface_name_is_wildcard i2) of { (True, True) -> less_eq_nat (size_list i2) (size_list i1) && take (minus_nat (size_list i2) one_nat) i1 == butlast i2; (True, False) -> False; (False, True) -> take (minus_nat (size_list i2) one_nat) i1 == butlast i2; (False, False) -> i1 == i2; }); iface_sel :: Iface -> [Prelude.Char]; iface_sel (Iface x) = x; iface_subset :: Iface -> Iface -> Bool; iface_subset i1 i2 = internal_iface_name_subset (iface_sel i1) (iface_sel i2); add_match :: forall a. Match_expr a -> [Rule a] -> [Rule a]; add_match m rs = map (\ (Rule ma a) -> Rule (MatchAnd m ma) a) rs; apfst :: forall a b c. (a -> b) -> (a, c) -> (b, c); apfst f (x, y) = (f x, y); char_of_nat :: Nat -> Prelude.Char; char_of_nat = (let chr k | (0 <= k && k < 256) = Prelude.toEnum k :: Prelude.Char in chr . Prelude.fromInteger) . integer_of_nat; mk_Set :: forall a. [a] -> Set a; mk_Set = Set; word_next :: forall a. (Len a) => Word a -> Word a; word_next a = (if equal_word a max_word then max_word else plus_word a one_word); word_prev :: forall a. (Len a) => Word a -> Word a; word_prev a = (if equal_word a zero_word then zero_word else minus_word a one_word); word_uptoa :: forall a. (Len0 a) => Word a -> Word a -> [Word a]; word_uptoa a b = (if equal_word a b then [a] else a : word_uptoa (plus_word a one_word) b); word_upto :: forall a. (Len0 a) => Word a -> Word a -> [Word a]; word_upto a b = word_uptoa a b; numeral :: forall a. (Numeral a) => Num -> a; numeral (Bit1 n) = let { m = numeral n; } in plus (plus m m) one; numeral (Bit0 n) = let { m = numeral n; } in plus m m; numeral One = one; of_nat :: forall a. (Semiring_1 a) => Nat -> a; of_nat n = (if equal_nat n zero_nat then zero else let { (m, q) = divmod_nat n (nat_of_integer (2 :: Integer)); ma = times (numeral (Bit0 One)) (of_nat m); } in (if equal_nat q zero_nat then ma else plus ma one)); ipv4addr_of_nat :: Nat -> Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))); ipv4addr_of_nat n = of_nat n; nat_of_ipv4addr :: Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> Nat; nat_of_ipv4addr a = unat a; min :: forall a. (Ord a) => a -> a -> a; min a b = (if less_eq a b then a else b); internal_iface_name_wildcard_longest :: [Prelude.Char] -> [Prelude.Char] -> Maybe [Prelude.Char]; internal_iface_name_wildcard_longest i1 i2 = (if take (min (minus_nat (size_list i1) one_nat) (minus_nat (size_list i2) one_nat)) i1 == take (min (minus_nat (size_list i1) one_nat) (minus_nat (size_list i2) one_nat)) i2 then Just (if less_eq_nat (size_list i1) (size_list i2) then i2 else i1) else Nothing); map_option :: forall a b. (a -> b) -> Maybe a -> Maybe b; map_option f Nothing = Nothing; map_option f (Just x2) = Just (f x2); iface_conjunct :: Iface -> Iface -> Maybe Iface; iface_conjunct (Iface i1) (Iface i2) = (case (iface_name_is_wildcard i1, iface_name_is_wildcard i2) of { (True, True) -> map_option Iface (internal_iface_name_wildcard_longest i1 i2); (True, False) -> (if match_iface (Iface i1) i2 then Just (Iface i2) else Nothing); (False, True) -> (if match_iface (Iface i2) i1 then Just (Iface i1) else Nothing); (False, False) -> (if i1 == i2 then Just (Iface i1) else Nothing); }); bitAND_int :: Int -> Int -> Int; bitAND_int (Int_of_integer i) (Int_of_integer j) = Int_of_integer (((Data_Bits..&.) :: Integer -> Integer -> Integer) i j); bitAND_word :: forall a. (Len0 a) => Word a -> Word a -> Word a; bitAND_word a b = word_of_int (bitAND_int (uint a) (uint b)); ipcidr_to_interval_start :: forall a. (Len a) => (Word a, Nat) -> Word a; ipcidr_to_interval_start (pre, len) = let { netmask = shiftl_word (mask len) (minus_nat ((len_of :: Itself a -> Nat) Type) len); network_prefix = bitAND_word pre netmask; } in network_prefix; bitNOT_int :: Int -> Int; bitNOT_int (Int_of_integer i) = Int_of_integer ((Data_Bits.complement :: Integer -> Integer) i); bitNOT_word :: forall a. (Len0 a) => Word a -> Word a; bitNOT_word a = word_of_int (bitNOT_int (uint a)); bitOR_int :: Int -> Int -> Int; bitOR_int (Int_of_integer i) (Int_of_integer j) = Int_of_integer (((Data_Bits..|.) :: Integer -> Integer -> Integer) i j); bitOR_word :: forall a. (Len0 a) => Word a -> Word a -> Word a; bitOR_word a b = word_of_int (bitOR_int (uint a) (uint b)); ipcidr_to_interval_end :: forall a. (Len a) => (Word a, Nat) -> Word a; ipcidr_to_interval_end (pre, len) = let { netmask = shiftl_word (mask len) (minus_nat ((len_of :: Itself a -> Nat) Type) len); network_prefix = bitAND_word pre netmask; } in bitOR_word network_prefix (bitNOT_word netmask); ipcidr_to_interval :: forall a. (Len a) => (Word a, Nat) -> (Word a, Word a); ipcidr_to_interval cidr = (ipcidr_to_interval_start cidr, ipcidr_to_interval_end cidr); iprange_interval :: forall a. (Len a) => (Word a, Word a) -> Wordinterval a; iprange_interval (ip_start, ip_end) = WordInterval ip_start ip_end; ipcidr_tuple_to_wordinterval :: forall a. (Len a) => (Word a, Nat) -> Wordinterval a; ipcidr_tuple_to_wordinterval iprng = iprange_interval (ipcidr_to_interval iprng); wordinterval_setminusa :: forall a. (Len a) => Wordinterval a -> Wordinterval a -> Wordinterval a; wordinterval_setminusa (WordInterval s e) (WordInterval ms me) = (if less_word e s || less_word me ms then WordInterval s e else (if less_eq_word e me then WordInterval (if equal_word ms zero_word then one_word else s) (min e (word_prev ms)) else (if less_eq_word ms s then WordInterval (max s (word_next me)) (if equal_word me max_word then zero_word else e) else RangeUnion (WordInterval (if equal_word ms zero_word then one_word else s) (word_prev ms)) (WordInterval (word_next me) (if equal_word me max_word then zero_word else e))))); wordinterval_setminusa (RangeUnion r1 r2) t = RangeUnion (wordinterval_setminusa r1 t) (wordinterval_setminusa r2 t); wordinterval_setminusa (WordInterval v va) (RangeUnion r1 r2) = wordinterval_setminusa (wordinterval_setminusa (WordInterval v va) r1) r2; wordinterval_empty_shallow :: forall a. (Len0 a) => Wordinterval a -> Bool; wordinterval_empty_shallow (WordInterval s e) = less_word e s; wordinterval_empty_shallow (RangeUnion uu uv) = False; wordinterval_optimize_empty2 :: forall a. (Len0 a) => Wordinterval a -> Wordinterval a; wordinterval_optimize_empty2 (RangeUnion r1 r2) = let { r1o = wordinterval_optimize_empty2 r1; r2o = wordinterval_optimize_empty2 r2; } in (if wordinterval_empty_shallow r1o then r2o else (if wordinterval_empty_shallow r2o then r1o else RangeUnion r1o r2o)); wordinterval_optimize_empty2 (WordInterval v va) = WordInterval v va; disjoint_intervals :: forall a. (Len0 a) => (Word a, Word a) -> (Word a, Word a) -> Bool; disjoint_intervals a b = let { (s, e) = a; (sa, ea) = b; } in less_word ea s || (less_word e sa || (less_word e s || less_word ea sa)); not_disjoint_intervals :: forall a. (Len0 a) => (Word a, Word a) -> (Word a, Word a) -> Bool; not_disjoint_intervals a b = let { (s, e) = a; (sa, ea) = b; } in less_eq_word s ea && less_eq_word sa e && less_eq_word s e && less_eq_word sa ea; merge_overlap :: forall a. (Len0 a) => (Word a, Word a) -> [(Word a, Word a)] -> [(Word a, Word a)]; merge_overlap s [] = [s]; merge_overlap (sa, ea) ((s, e) : ss) = (if not_disjoint_intervals (sa, ea) (s, e) then (min sa s, max ea e) : ss else (s, e) : merge_overlap (sa, ea) ss); listwordinterval_compress :: forall a. (Len0 a) => [(Word a, Word a)] -> [(Word a, Word a)]; listwordinterval_compress [] = []; listwordinterval_compress (s : ss) = (if all (disjoint_intervals s) ss then s : listwordinterval_compress ss else listwordinterval_compress (merge_overlap s ss)); merge_adjacent :: forall a. (Len a) => (Word a, Word a) -> [(Word a, Word a)] -> [(Word a, Word a)]; merge_adjacent s [] = [s]; merge_adjacent (sa, ea) ((s, e) : ss) = (if less_eq_word sa ea && less_eq_word s e && equal_word (word_next ea) s then (sa, e) : ss else (if less_eq_word sa ea && less_eq_word s e && equal_word (word_next e) sa then (s, ea) : ss else (s, e) : merge_adjacent (sa, ea) ss)); listwordinterval_adjacent :: forall a. (Len a) => [(Word a, Word a)] -> [(Word a, Word a)]; listwordinterval_adjacent [] = []; listwordinterval_adjacent ((s, e) : ss) = (if all (\ (sa, ea) -> not (less_eq_word s e && less_eq_word sa ea && (equal_word (word_next e) sa || equal_word (word_next ea) s))) ss then (s, e) : listwordinterval_adjacent ss else listwordinterval_adjacent (merge_adjacent (s, e) ss)); wordinterval_compress :: forall a. (Len a) => Wordinterval a -> Wordinterval a; wordinterval_compress r = l2wi (remdups (listwordinterval_adjacent (listwordinterval_compress (wi2l (wordinterval_optimize_empty2 r))))); wordinterval_setminus :: forall a. (Len a) => Wordinterval a -> Wordinterval a -> Wordinterval a; wordinterval_setminus r1 r2 = wordinterval_compress (wordinterval_setminusa r1 r2); wordinterval_union :: forall a. (Len0 a) => Wordinterval a -> Wordinterval a -> Wordinterval a; wordinterval_union r1 r2 = RangeUnion r1 r2; wordinterval_Union :: forall a. (Len a) => [Wordinterval a] -> Wordinterval a; wordinterval_Union ws = wordinterval_compress (foldr wordinterval_union ws empty_WordInterval); wordinterval_lowest_element :: forall a. (Len0 a) => Wordinterval a -> Maybe (Word a); wordinterval_lowest_element (WordInterval s e) = (if less_eq_word s e then Just s else Nothing); wordinterval_lowest_element (RangeUnion a b) = (case (wordinterval_lowest_element a, wordinterval_lowest_element b) of { (Nothing, Nothing) -> Nothing; (Nothing, Just aa) -> Just aa; (Just aa, Nothing) -> Just aa; (Just aa, Just ba) -> Just (if less_word aa ba then aa else ba); }); pfxm_prefix :: forall a. (Len a) => Prefix_match a -> Word a; pfxm_prefix (PrefixMatch x1 x2) = x1; pfxm_length :: forall a. (Len a) => Prefix_match a -> Nat; pfxm_length (PrefixMatch x1 x2) = x2; pfxm_mask :: forall a. (Len a) => Prefix_match a -> Word a; pfxm_mask x = mask (minus_nat ((len_of :: Itself a -> Nat) Type) (pfxm_length x)); prefix_to_wordinterval :: forall a. (Len a) => Prefix_match a -> Wordinterval a; prefix_to_wordinterval pfx = WordInterval (pfxm_prefix pfx) (bitOR_word (pfxm_prefix pfx) (pfxm_mask pfx)); wordinterval_empty :: forall a. (Len0 a) => Wordinterval a -> Bool; wordinterval_empty (WordInterval s e) = less_word e s; wordinterval_empty (RangeUnion r1 r2) = wordinterval_empty r1 && wordinterval_empty r2; wordinterval_subset :: forall a. (Len a) => Wordinterval a -> Wordinterval a -> Bool; wordinterval_subset r1 r2 = wordinterval_empty (wordinterval_setminus r1 r2); valid_prefix :: forall a. (Len a) => Prefix_match a -> Bool; valid_prefix pf = equal_word (bitAND_word (pfxm_mask pf) (pfxm_prefix pf)) zero_word; largest_contained_prefix :: forall a. (Len a) => Word a -> Wordinterval a -> Maybe (Prefix_match a); largest_contained_prefix a r = let { cs = map (PrefixMatch a) ((pfxes :: Itself a -> [Nat]) Type); cfs = find (\ s -> valid_prefix s && wordinterval_subset (prefix_to_wordinterval s) r) cs; } in cfs; wordinterval_CIDR_split1 :: forall a. (Len a) => Wordinterval a -> (Maybe (Prefix_match a), Wordinterval a); wordinterval_CIDR_split1 r = let { a = wordinterval_lowest_element r; } in (case a of { Nothing -> (Nothing, r); Just aa -> (case largest_contained_prefix aa r of { Nothing -> (Nothing, r); Just m -> (Just m, wordinterval_setminus r (prefix_to_wordinterval m)); }); }); wordinterval_CIDR_split_prefixmatch :: forall a. (Len a) => Wordinterval a -> [Prefix_match a]; wordinterval_CIDR_split_prefixmatch rs = (if not (wordinterval_empty rs) then (case wordinterval_CIDR_split1 rs of { (Nothing, _) -> []; (Just s, u) -> s : wordinterval_CIDR_split_prefixmatch u; }) else []); prefix_match_to_CIDR :: forall a. (Len a) => Prefix_match a -> (Word a, Nat); prefix_match_to_CIDR pfx = (pfxm_prefix pfx, pfxm_length pfx); cidr_split :: forall a. (Len a) => Wordinterval a -> [(Word a, Nat)]; cidr_split rs = map prefix_match_to_CIDR (wordinterval_CIDR_split_prefixmatch rs); ipassmt_diff :: forall a. (Len a) => [(Iface, [(Word a, Nat)])] -> [(Iface, [(Word a, Nat)])] -> [(Iface, ([(Word a, Nat)], [(Word a, Nat)]))]; ipassmt_diff a b = let { t = (\ aa -> (case aa of { Nothing -> empty_WordInterval; Just s -> wordinterval_Union (map ipcidr_tuple_to_wordinterval s); })); k = (\ x y d -> cidr_split (wordinterval_setminus (t (map_of x d)) (t (map_of y d)))); } in map (\ d -> (d, (k a b d, k b a d))) (remdups (map fst (a ++ b))); iPv6ICMP :: Word (Bit0 (Bit0 (Bit0 Num1))); iPv6ICMP = word_of_int (Int_of_integer (58 :: Integer)); getNeg :: forall a. [Negation_type a] -> [a]; getNeg [] = []; getNeg (Neg x : xs) = x : getNeg xs; getNeg (Pos v : xs) = getNeg xs; getPos :: forall a. [Negation_type a] -> [a]; getPos [] = []; getPos (Pos x : xs) = x : getPos xs; getPos (Neg v : xs) = getPos xs; pc_oiface :: forall a. Parts_connection_ext a -> [Prelude.Char]; pc_oiface (Parts_connection_ext pc_iiface pc_oiface pc_proto pc_sport pc_dport more) = pc_oiface; pc_iiface :: forall a. Parts_connection_ext a -> [Prelude.Char]; pc_iiface (Parts_connection_ext pc_iiface pc_oiface pc_proto pc_sport pc_dport more) = pc_iiface; pc_sport :: forall a. Parts_connection_ext a -> Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))); pc_sport (Parts_connection_ext pc_iiface pc_oiface pc_proto pc_sport pc_dport more) = pc_sport; pc_proto :: forall a. Parts_connection_ext a -> Word (Bit0 (Bit0 (Bit0 Num1))); pc_proto (Parts_connection_ext pc_iiface pc_oiface pc_proto pc_sport pc_dport more) = pc_proto; pc_dport :: forall a. Parts_connection_ext a -> Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))); pc_dport (Parts_connection_ext pc_iiface pc_oiface pc_proto pc_sport pc_dport more) = pc_dport; p_oiface :: forall a b. (Len a) => Simple_packet_ext a b -> [Prelude.Char]; p_oiface (Simple_packet_ext p_iiface p_oiface p_src p_dst p_proto p_sport p_dport p_tcp_flags p_payload more) = p_oiface; p_iiface :: forall a b. (Len a) => Simple_packet_ext a b -> [Prelude.Char]; p_iiface (Simple_packet_ext p_iiface p_oiface p_src p_dst p_proto p_sport p_dport p_tcp_flags p_payload more) = p_iiface; simple_match_port :: (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))) -> Bool; simple_match_port (s, e) p_p = less_eq_word s p_p && less_eq_word p_p e; p_sport :: forall a b. (Len a) => Simple_packet_ext a b -> Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))); p_sport (Simple_packet_ext p_iiface p_oiface p_src p_dst p_proto p_sport p_dport p_tcp_flags p_payload more) = p_sport; p_proto :: forall a b. (Len a) => Simple_packet_ext a b -> Word (Bit0 (Bit0 (Bit0 Num1))); p_proto (Simple_packet_ext p_iiface p_oiface p_src p_dst p_proto p_sport p_dport p_tcp_flags p_payload more) = p_proto; p_dport :: forall a b. (Len a) => Simple_packet_ext a b -> Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))); p_dport (Simple_packet_ext p_iiface p_oiface p_src p_dst p_proto p_sport p_dport p_tcp_flags p_payload more) = p_dport; sports :: forall a b. (Len a) => Simple_match_ext a b -> (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))); sports (Simple_match_ext iiface oiface src dst proto sports dports more) = sports; oiface :: forall a b. (Len a) => Simple_match_ext a b -> Iface; oiface (Simple_match_ext iiface oiface src dst proto sports dports more) = oiface; iiface :: forall a b. (Len a) => Simple_match_ext a b -> Iface; iiface (Simple_match_ext iiface oiface src dst proto sports dports more) = iiface; dports :: forall a b. (Len a) => Simple_match_ext a b -> (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))); dports (Simple_match_ext iiface oiface src dst proto sports dports more) = dports; proto :: forall a b. (Len a) => Simple_match_ext a b -> Protocol; proto (Simple_match_ext iiface oiface src dst proto sports dports more) = proto; simple_match_ip :: forall a. (Len a) => (Word a, Nat) -> Word a -> Bool; simple_match_ip (base, len) p_ip = less_eq_word (bitAND_word base (shiftl_word (mask len) (minus_nat ((len_of :: Itself a -> Nat) Type) len))) p_ip && less_eq_word p_ip (bitOR_word base (mask (minus_nat ((len_of :: Itself a -> Nat) Type) len))); p_src :: forall a b. (Len a) => Simple_packet_ext a b -> Word a; p_src (Simple_packet_ext p_iiface p_oiface p_src p_dst p_proto p_sport p_dport p_tcp_flags p_payload more) = p_src; p_dst :: forall a b. (Len a) => Simple_packet_ext a b -> Word a; p_dst (Simple_packet_ext p_iiface p_oiface p_src p_dst p_proto p_sport p_dport p_tcp_flags p_payload more) = p_dst; src :: forall a b. (Len a) => Simple_match_ext a b -> (Word a, Nat); src (Simple_match_ext iiface oiface src dst proto sports dports more) = src; dst :: forall a b. (Len a) => Simple_match_ext a b -> (Word a, Nat); dst (Simple_match_ext iiface oiface src dst proto sports dports more) = dst; match_proto :: Protocol -> Word (Bit0 (Bit0 (Bit0 Num1))) -> Bool; match_proto ProtoAny uu = True; match_proto (Proto p) p_p = equal_word p_p p; simple_matches :: forall a b. (Len a) => Simple_match_ext a () -> Simple_packet_ext a b -> Bool; simple_matches m p = match_iface (iiface m) (p_iiface p) && match_iface (oiface m) (p_oiface p) && simple_match_ip (src m) (p_src p) && simple_match_ip (dst m) (p_dst p) && match_proto (proto m) (p_proto p) && simple_match_port (sports m) (p_sport p) && simple_match_port (dports m) (p_dport p); simple_fw :: forall a b. (Len a) => [Simple_rule a] -> Simple_packet_ext a b -> State; simple_fw [] uu = Undecided; simple_fw (SimpleRule m Accepta : rs) p = (if simple_matches m p then Decision FinalAllow else simple_fw rs p); simple_fw (SimpleRule m Dropa : rs) p = (if simple_matches m p then Decision FinalDeny else simple_fw rs p); bot_set :: forall a. Set a; bot_set = Set []; runFw :: forall a b. (Len a) => Word a -> Word a -> Parts_connection_ext b -> [Simple_rule a] -> State; runFw s d c rs = simple_fw rs (Simple_packet_ext (pc_iiface c) (pc_oiface c) s d (pc_proto c) (pc_sport c) (pc_dport c) (insert TCP_SYN bot_set) [] ()); oiface_sel :: forall a. (Len a) => Common_primitive a -> Iface; oiface_sel (OIface x4) = x4; iiface_sel :: forall a. (Len a) => Common_primitive a -> Iface; iiface_sel (IIface x3) = x3; is_Oiface :: forall a. (Len a) => Common_primitive a -> Bool; is_Oiface (Src x1) = False; is_Oiface (Dst x2) = False; is_Oiface (IIface x3) = False; is_Oiface (OIface x4) = True; is_Oiface (Prot x5) = False; is_Oiface (Src_Ports x6) = False; is_Oiface (Dst_Ports x7) = False; is_Oiface (MultiportPorts x8) = False; is_Oiface (L4_Flags x9) = False; is_Oiface (CT_State x10) = False; is_Oiface (Extra x11) = False; is_Iiface :: forall a. (Len a) => Common_primitive a -> Bool; is_Iiface (Src x1) = False; is_Iiface (Dst x2) = False; is_Iiface (IIface x3) = True; is_Iiface (OIface x4) = False; is_Iiface (Prot x5) = False; is_Iiface (Src_Ports x6) = False; is_Iiface (Dst_Ports x7) = False; is_Iiface (MultiportPorts x8) = False; is_Iiface (L4_Flags x9) = False; is_Iiface (CT_State x10) = False; is_Iiface (Extra x11) = False; primitive_extractor :: forall a b. (a -> Bool, a -> b) -> Match_expr a -> ([Negation_type b], Match_expr a); primitive_extractor uu MatchAny = ([], MatchAny); primitive_extractor (disc, sel) (Match a) = (if disc a then ([Pos (sel a)], MatchAny) else ([], Match a)); primitive_extractor (disc, sel) (MatchNot (Match a)) = (if disc a then ([Neg (sel a)], MatchAny) else ([], MatchNot (Match a))); primitive_extractor c (MatchAnd ms1 ms2) = let { (a1, ms1a) = primitive_extractor c ms1; (a2, ms2a) = primitive_extractor c ms2; } in (a1 ++ a2, MatchAnd ms1a ms2a); primitive_extractor uv (MatchNot (MatchNot va)) = error "undefined"; primitive_extractor uv (MatchNot (MatchAnd va vb)) = error "undefined"; primitive_extractor uv (MatchNot MatchAny) = error "undefined"; collect_ifacesa :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Iface]; collect_ifacesa [] = []; collect_ifacesa (Rule m a : rs) = filter (\ iface -> not (equal_iface iface ifaceAny)) (map (\ aa -> (case aa of { Pos i -> i; Neg i -> i; })) (fst (primitive_extractor (is_Iiface, iiface_sel) m)) ++ map (\ aa -> (case aa of { Pos i -> i; Neg i -> i; })) (fst (primitive_extractor (is_Oiface, oiface_sel) m)) ++ collect_ifacesa rs); mergesort_remdups :: forall a. (Eq a, Linorder a) => [a] -> [a]; mergesort_remdups xs = merge_list [] (map (\ x -> [x]) xs); collect_ifaces :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Iface]; collect_ifaces rs = mergesort_remdups (collect_ifacesa rs); iface_is_wildcard :: Iface -> Bool; iface_is_wildcard ifce = iface_name_is_wildcard (iface_sel ifce); map_of_ipassmt :: forall a. [(Iface, [(Word a, Nat)])] -> Iface -> Maybe [(Word a, Nat)]; map_of_ipassmt ipassmt = (if distinct (map fst ipassmt) && ball (image fst (Set ipassmt)) (\ iface -> not (iface_is_wildcard iface)) then map_of ipassmt else error "undefined"); wordinterval_UNIV :: forall a. (Len a) => Wordinterval a; wordinterval_UNIV = WordInterval zero_word max_word; wordinterval_invert :: forall a. (Len a) => Wordinterval a -> Wordinterval a; wordinterval_invert r = wordinterval_setminus wordinterval_UNIV r; raw_ports_invert :: [(Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))] -> [(Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))]; raw_ports_invert ps = wi2l (wordinterval_invert (l2wi ps)); wordinterval_intersectiona :: forall a. (Len a) => Wordinterval a -> Wordinterval a -> Wordinterval a; wordinterval_intersectiona (WordInterval sa ea) (WordInterval s e) = (if less_word ea sa || (less_word e s || (less_word e sa || (less_word ea s || (less_word ea sa || less_word e s)))) then empty_WordInterval else WordInterval (max sa s) (min ea e)); wordinterval_intersectiona (RangeUnion r1 r2) t = RangeUnion (wordinterval_intersectiona r1 t) (wordinterval_intersectiona r2 t); wordinterval_intersectiona (WordInterval v va) (RangeUnion r1 r2) = RangeUnion (wordinterval_intersectiona (WordInterval v va) r1) (wordinterval_intersectiona (WordInterval v va) r2); wordinterval_intersection :: forall a. (Len a) => Wordinterval a -> Wordinterval a -> Wordinterval a; wordinterval_intersection r1 r2 = wordinterval_compress (wordinterval_intersectiona r1 r2); partIps :: forall a. (Len a) => Wordinterval a -> [Wordinterval a] -> [Wordinterval a]; partIps uu [] = []; partIps s (t : ts) = (if wordinterval_empty s then t : ts else (if wordinterval_empty (wordinterval_intersection s t) then t : partIps s ts else (if wordinterval_empty (wordinterval_setminus t s) then t : partIps (wordinterval_setminus s t) ts else wordinterval_intersection t s : wordinterval_setminus t s : partIps (wordinterval_setminus s t) ts))); ipt_iprange_to_interval :: forall a. (Len a) => Ipt_iprange a -> (Word a, Word a); ipt_iprange_to_interval (IpAddr addr) = (addr, addr); ipt_iprange_to_interval (IpAddrNetmask pre len) = ipcidr_to_interval (pre, len); ipt_iprange_to_interval (IpAddrRange ip1 ip2) = (ip1, ip2); ipt_iprange_to_cidr :: forall a. (Len a) => Ipt_iprange a -> [(Word a, Nat)]; ipt_iprange_to_cidr ips = cidr_split (iprange_interval (ipt_iprange_to_interval ips)); all_but_those_ips :: forall a. (Len a) => [(Word a, Nat)] -> [(Word a, Nat)]; all_but_those_ips cidrips = cidr_split (wordinterval_invert (l2wi (map ipcidr_to_interval cidrips))); ipassmt_iprange_translate :: forall a. (Len a) => Negation_type [Ipt_iprange a] -> [(Word a, Nat)]; ipassmt_iprange_translate (Pos ips) = concatMap ipt_iprange_to_cidr ips; ipassmt_iprange_translate (Neg ips) = all_but_those_ips (concatMap ipt_iprange_to_cidr ips); to_ipassmt :: forall a. (Len a) => [(Iface, Negation_type [Ipt_iprange a])] -> [(Iface, [(Word a, Nat)])]; to_ipassmt assmt = map (\ (ifce, ips) -> (ifce, ipassmt_iprange_translate ips)) assmt; matchOr :: forall a. Match_expr a -> Match_expr a -> Match_expr a; matchOr m1 m2 = MatchNot (MatchAnd (MatchNot m1) (MatchNot m2)); routing_match :: forall a b. (Len a) => Routing_rule_ext a b -> Prefix_match a; routing_match (Routing_rule_ext routing_match metric routing_action more) = routing_match; metric :: forall a b. (Len a) => Routing_rule_ext a b -> Nat; metric (Routing_rule_ext routing_match metric routing_action more) = metric; routing_rule_sort_key :: forall a b. (Len a) => Routing_rule_ext a b -> Linord_helper Int Nat; routing_rule_sort_key = (\ r -> LinordHelper (minus_int zero_int (int_of_nat (pfxm_length (routing_match r)))) (metric r)); part :: forall a b. (Linorder b) => (a -> b) -> b -> [a] -> ([a], ([a], [a])); part f pivot (x : xs) = let { (lts, (eqs, gts)) = part f pivot xs; xa = f x; } in (if less xa pivot then (x : lts, (eqs, gts)) else (if less pivot xa then (lts, (eqs, x : gts)) else (lts, (x : eqs, gts)))); part f pivot [] = ([], ([], [])); sort_key :: forall a b. (Linorder b) => (a -> b) -> [a] -> [a]; sort_key f xs = (case xs of { [] -> []; [_] -> xs; [x, y] -> (if less_eq (f x) (f y) then xs else [y, x]); _ : _ : _ : _ -> let { (lts, (eqs, gts)) = part f (f (nth xs (divide_nat (size_list xs) (nat_of_integer (2 :: Integer))))) xs; } in sort_key f lts ++ eqs ++ sort_key f gts; }); sort_rtbl :: forall a. (Len a) => [Routing_rule_ext a ()] -> [Routing_rule_ext a ()]; sort_rtbl = sort_key routing_rule_sort_key; getOneIp :: forall a. (Len a) => Wordinterval a -> Word a; getOneIp (WordInterval b uu) = b; getOneIp (RangeUnion r1 r2) = (if wordinterval_empty r1 then getOneIp r2 else getOneIp r1); partitioningIps :: forall a. (Len a) => [Wordinterval a] -> [Wordinterval a] -> [Wordinterval a]; partitioningIps [] ts = ts; partitioningIps (s : ss) ts = partIps s (partitioningIps ss ts); extract_src_dst_ips :: forall a. (Len a) => [Simple_rule a] -> [(Word a, Nat)] -> [(Word a, Nat)]; extract_src_dst_ips [] ts = ts; extract_src_dst_ips (SimpleRule m uu : ss) ts = extract_src_dst_ips ss (src m : dst m : ts); extract_IPSets :: forall a. (Len a) => [Simple_rule a] -> [Wordinterval a]; extract_IPSets rs = map ipcidr_tuple_to_wordinterval (mergesort_remdups (extract_src_dst_ips rs [])); getParts :: forall a. (Len a) => [Simple_rule a] -> [Wordinterval a]; getParts rs = partitioningIps (extract_IPSets rs) [wordinterval_UNIV]; upper_closure_matchexpr :: forall a. (Len a) => Action -> Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); upper_closure_matchexpr uu MatchAny = MatchAny; upper_closure_matchexpr Accept (Match (Extra uv)) = MatchAny; upper_closure_matchexpr Reject (Match (Extra uw)) = MatchNot MatchAny; upper_closure_matchexpr Drop (Match (Extra ux)) = MatchNot MatchAny; upper_closure_matchexpr Drop (Match (Src v)) = Match (Src v); upper_closure_matchexpr Drop (Match (Dst v)) = Match (Dst v); upper_closure_matchexpr Drop (Match (IIface v)) = Match (IIface v); upper_closure_matchexpr Drop (Match (OIface v)) = Match (OIface v); upper_closure_matchexpr Drop (Match (Prot v)) = Match (Prot v); upper_closure_matchexpr Drop (Match (Src_Ports v)) = Match (Src_Ports v); upper_closure_matchexpr Drop (Match (Dst_Ports v)) = Match (Dst_Ports v); upper_closure_matchexpr Drop (Match (MultiportPorts v)) = Match (MultiportPorts v); upper_closure_matchexpr Drop (Match (L4_Flags v)) = Match (L4_Flags v); upper_closure_matchexpr Drop (Match (CT_State v)) = Match (CT_State v); upper_closure_matchexpr Log (Match m) = Match m; upper_closure_matchexpr Reject (Match (Src v)) = Match (Src v); upper_closure_matchexpr Reject (Match (Dst v)) = Match (Dst v); upper_closure_matchexpr Reject (Match (IIface v)) = Match (IIface v); upper_closure_matchexpr Reject (Match (OIface v)) = Match (OIface v); upper_closure_matchexpr Reject (Match (Prot v)) = Match (Prot v); upper_closure_matchexpr Reject (Match (Src_Ports v)) = Match (Src_Ports v); upper_closure_matchexpr Reject (Match (Dst_Ports v)) = Match (Dst_Ports v); upper_closure_matchexpr Reject (Match (MultiportPorts v)) = Match (MultiportPorts v); upper_closure_matchexpr Reject (Match (L4_Flags v)) = Match (L4_Flags v); upper_closure_matchexpr Reject (Match (CT_State v)) = Match (CT_State v); upper_closure_matchexpr (Call v) (Match m) = Match m; upper_closure_matchexpr Return (Match m) = Match m; upper_closure_matchexpr (Goto v) (Match m) = Match m; upper_closure_matchexpr Empty (Match m) = Match m; upper_closure_matchexpr Unknown (Match m) = Match m; upper_closure_matchexpr uy (Match (Src v)) = Match (Src v); upper_closure_matchexpr uy (Match (Dst v)) = Match (Dst v); upper_closure_matchexpr uy (Match (IIface v)) = Match (IIface v); upper_closure_matchexpr uy (Match (OIface v)) = Match (OIface v); upper_closure_matchexpr uy (Match (Prot v)) = Match (Prot v); upper_closure_matchexpr uy (Match (Src_Ports v)) = Match (Src_Ports v); upper_closure_matchexpr uy (Match (Dst_Ports v)) = Match (Dst_Ports v); upper_closure_matchexpr uy (Match (MultiportPorts v)) = Match (MultiportPorts v); upper_closure_matchexpr uy (Match (L4_Flags v)) = Match (L4_Flags v); upper_closure_matchexpr uy (Match (CT_State v)) = Match (CT_State v); upper_closure_matchexpr Accept (MatchNot (Match (Extra uz))) = MatchAny; upper_closure_matchexpr Drop (MatchNot (Match (Extra va))) = MatchNot MatchAny; upper_closure_matchexpr Reject (MatchNot (Match (Extra vb))) = MatchNot MatchAny; upper_closure_matchexpr a (MatchNot (MatchNot m)) = upper_closure_matchexpr a m; upper_closure_matchexpr a (MatchNot (MatchAnd m1 m2)) = let { m1a = upper_closure_matchexpr a (MatchNot m1); m2a = upper_closure_matchexpr a (MatchNot m2); } in (if equal_match_expr m1a MatchAny || equal_match_expr m2a MatchAny then MatchAny else (if equal_match_expr m1a (MatchNot MatchAny) then m2a else (if equal_match_expr m2a (MatchNot MatchAny) then m1a else MatchNot (MatchAnd (MatchNot m1a) (MatchNot m2a))))); upper_closure_matchexpr Drop (MatchNot (Match (Src va))) = MatchNot (Match (Src va)); upper_closure_matchexpr Drop (MatchNot (Match (Dst va))) = MatchNot (Match (Dst va)); upper_closure_matchexpr Drop (MatchNot (Match (IIface va))) = MatchNot (Match (IIface va)); upper_closure_matchexpr Drop (MatchNot (Match (OIface va))) = MatchNot (Match (OIface va)); upper_closure_matchexpr Drop (MatchNot (Match (Prot va))) = MatchNot (Match (Prot va)); upper_closure_matchexpr Drop (MatchNot (Match (Src_Ports va))) = MatchNot (Match (Src_Ports va)); upper_closure_matchexpr Drop (MatchNot (Match (Dst_Ports va))) = MatchNot (Match (Dst_Ports va)); upper_closure_matchexpr Drop (MatchNot (Match (MultiportPorts va))) = MatchNot (Match (MultiportPorts va)); upper_closure_matchexpr Drop (MatchNot (Match (L4_Flags va))) = MatchNot (Match (L4_Flags va)); upper_closure_matchexpr Drop (MatchNot (Match (CT_State va))) = MatchNot (Match (CT_State va)); upper_closure_matchexpr Drop (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr Log (MatchNot (Match v)) = MatchNot (Match v); upper_closure_matchexpr Log (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr Reject (MatchNot (Match (Src va))) = MatchNot (Match (Src va)); upper_closure_matchexpr Reject (MatchNot (Match (Dst va))) = MatchNot (Match (Dst va)); upper_closure_matchexpr Reject (MatchNot (Match (IIface va))) = MatchNot (Match (IIface va)); upper_closure_matchexpr Reject (MatchNot (Match (OIface va))) = MatchNot (Match (OIface va)); upper_closure_matchexpr Reject (MatchNot (Match (Prot va))) = MatchNot (Match (Prot va)); upper_closure_matchexpr Reject (MatchNot (Match (Src_Ports va))) = MatchNot (Match (Src_Ports va)); upper_closure_matchexpr Reject (MatchNot (Match (Dst_Ports va))) = MatchNot (Match (Dst_Ports va)); upper_closure_matchexpr Reject (MatchNot (Match (MultiportPorts va))) = MatchNot (Match (MultiportPorts va)); upper_closure_matchexpr Reject (MatchNot (Match (L4_Flags va))) = MatchNot (Match (L4_Flags va)); upper_closure_matchexpr Reject (MatchNot (Match (CT_State va))) = MatchNot (Match (CT_State va)); upper_closure_matchexpr Reject (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr (Call v) (MatchNot (Match va)) = MatchNot (Match va); upper_closure_matchexpr (Call v) (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr Return (MatchNot (Match v)) = MatchNot (Match v); upper_closure_matchexpr Return (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr (Goto v) (MatchNot (Match va)) = MatchNot (Match va); upper_closure_matchexpr (Goto v) (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr Empty (MatchNot (Match v)) = MatchNot (Match v); upper_closure_matchexpr Empty (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr Unknown (MatchNot (Match v)) = MatchNot (Match v); upper_closure_matchexpr Unknown (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr vc (MatchNot (Match (Src va))) = MatchNot (Match (Src va)); upper_closure_matchexpr vc (MatchNot (Match (Dst va))) = MatchNot (Match (Dst va)); upper_closure_matchexpr vc (MatchNot (Match (IIface va))) = MatchNot (Match (IIface va)); upper_closure_matchexpr vc (MatchNot (Match (OIface va))) = MatchNot (Match (OIface va)); upper_closure_matchexpr vc (MatchNot (Match (Prot va))) = MatchNot (Match (Prot va)); upper_closure_matchexpr vc (MatchNot (Match (Src_Ports va))) = MatchNot (Match (Src_Ports va)); upper_closure_matchexpr vc (MatchNot (Match (Dst_Ports va))) = MatchNot (Match (Dst_Ports va)); upper_closure_matchexpr vc (MatchNot (Match (MultiportPorts va))) = MatchNot (Match (MultiportPorts va)); upper_closure_matchexpr vc (MatchNot (Match (L4_Flags va))) = MatchNot (Match (L4_Flags va)); upper_closure_matchexpr vc (MatchNot (Match (CT_State va))) = MatchNot (Match (CT_State va)); upper_closure_matchexpr vc (MatchNot MatchAny) = MatchNot MatchAny; upper_closure_matchexpr a (MatchAnd m1 m2) = MatchAnd (upper_closure_matchexpr a m1) (upper_closure_matchexpr a m2); compress_normalize_primitive_monad :: forall a. [Match_expr a -> Maybe (Match_expr a)] -> Match_expr a -> Maybe (Match_expr a); compress_normalize_primitive_monad [] m = Just m; compress_normalize_primitive_monad (f : fs) m = (case f m of { Nothing -> Nothing; Just a -> compress_normalize_primitive_monad fs a; }); alist_and :: forall a. [Negation_type a] -> Match_expr a; alist_and [] = MatchAny; alist_and [Pos e] = Match e; alist_and [Neg e] = MatchNot (Match e); alist_and (Pos e : v : va) = MatchAnd (Match e) (alist_and (v : va)); alist_and (Neg e : v : va) = MatchAnd (MatchNot (Match e)) (alist_and (v : va)); negPos_map :: forall a b. (a -> b) -> [Negation_type a] -> [Negation_type b]; negPos_map uu [] = []; negPos_map f (Pos a : asa) = Pos (f a) : negPos_map f asa; negPos_map f (Neg a : asa) = Neg (f a) : negPos_map f asa; compress_normalize_primitive :: forall a b. (a -> Bool, a -> b) -> (b -> a) -> ([Negation_type b] -> Maybe ([b], [b])) -> Match_expr a -> Maybe (Match_expr a); compress_normalize_primitive disc_sel c f m = let { (asa, rst) = primitive_extractor disc_sel m; } in map_option (\ (as_pos, as_neg) -> MatchAnd (alist_and (negPos_map c (map Pos as_pos ++ map Neg as_neg))) rst) (f asa); compress_pos_interfaces :: [Iface] -> Maybe Iface; compress_pos_interfaces [] = Just ifaceAny; compress_pos_interfaces [i] = Just i; compress_pos_interfaces (i1 : i2 : is) = (case iface_conjunct i1 i2 of { Nothing -> Nothing; Just i -> compress_pos_interfaces (i : is); }); compress_interfaces :: [Negation_type Iface] -> Maybe ([Iface], [Iface]); compress_interfaces ifces = (case compress_pos_interfaces (getPos ifces) of { Nothing -> Nothing; Just i -> (if any (iface_subset i) (getNeg ifces) then Nothing else (if not (iface_is_wildcard i) then Just ([i], []) else Just ((if equal_iface i ifaceAny then [] else [i]), getNeg ifces))); }); compress_normalize_output_interfaces :: forall a. (Len a) => Match_expr (Common_primitive a) -> Maybe (Match_expr (Common_primitive a)); compress_normalize_output_interfaces m = compress_normalize_primitive (is_Oiface, oiface_sel) OIface compress_interfaces m; compress_normalize_input_interfaces :: forall a. (Len a) => Match_expr (Common_primitive a) -> Maybe (Match_expr (Common_primitive a)); compress_normalize_input_interfaces m = compress_normalize_primitive (is_Iiface, iiface_sel) IIface compress_interfaces m; prot_sel :: forall a. (Len a) => Common_primitive a -> Protocol; prot_sel (Prot x5) = x5; is_Prot :: forall a. (Len a) => Common_primitive a -> Bool; is_Prot (Src x1) = False; is_Prot (Dst x2) = False; is_Prot (IIface x3) = False; is_Prot (OIface x4) = False; is_Prot (Prot x5) = True; is_Prot (Src_Ports x6) = False; is_Prot (Dst_Ports x7) = False; is_Prot (MultiportPorts x8) = False; is_Prot (L4_Flags x9) = False; is_Prot (CT_State x10) = False; is_Prot (Extra x11) = False; simple_proto_conjunct :: Protocol -> Protocol -> Maybe Protocol; simple_proto_conjunct ProtoAny proto = Just proto; simple_proto_conjunct (Proto v) ProtoAny = Just (Proto v); simple_proto_conjunct (Proto p1) (Proto p2) = (if equal_word p1 p2 then Just (Proto p1) else Nothing); compress_pos_protocols :: [Protocol] -> Maybe Protocol; compress_pos_protocols [] = Just ProtoAny; compress_pos_protocols [p] = Just p; compress_pos_protocols (p1 : p2 : ps) = (case simple_proto_conjunct p1 p2 of { Nothing -> Nothing; Just p -> compress_pos_protocols (p : ps); }); compress_protocols :: [Negation_type Protocol] -> Maybe ([Protocol], [Protocol]); compress_protocols ps = (case compress_pos_protocols (getPos ps) of { Nothing -> Nothing; Just proto -> (if membera (getNeg ps) ProtoAny || all (\ p -> membera (getNeg ps) (Proto p)) (word_upto zero_word (word_of_int (Int_of_integer (255 :: Integer)))) then Nothing else (if equal_protocol proto ProtoAny then Just ([], getNeg ps) else (if any (\ p -> not (is_none (simple_proto_conjunct proto p))) (getNeg ps) then Nothing else Just ([proto], [])))); }); compress_normalize_protocols_step :: forall a. (Len a) => Match_expr (Common_primitive a) -> Maybe (Match_expr (Common_primitive a)); compress_normalize_protocols_step m = compress_normalize_primitive (is_Prot, prot_sel) Prot compress_protocols m; src_ports_sel :: forall a. (Len a) => Common_primitive a -> Ipt_l4_ports; src_ports_sel (Src_Ports x6) = x6; dst_ports_sel :: forall a. (Len a) => Common_primitive a -> Ipt_l4_ports; dst_ports_sel (Dst_Ports x7) = x7; is_Src_Ports :: forall a. (Len a) => Common_primitive a -> Bool; is_Src_Ports (Src x1) = False; is_Src_Ports (Dst x2) = False; is_Src_Ports (IIface x3) = False; is_Src_Ports (OIface x4) = False; is_Src_Ports (Prot x5) = False; is_Src_Ports (Src_Ports x6) = True; is_Src_Ports (Dst_Ports x7) = False; is_Src_Ports (MultiportPorts x8) = False; is_Src_Ports (L4_Flags x9) = False; is_Src_Ports (CT_State x10) = False; is_Src_Ports (Extra x11) = False; is_Dst_Ports :: forall a. (Len a) => Common_primitive a -> Bool; is_Dst_Ports (Src x1) = False; is_Dst_Ports (Dst x2) = False; is_Dst_Ports (IIface x3) = False; is_Dst_Ports (OIface x4) = False; is_Dst_Ports (Prot x5) = False; is_Dst_Ports (Src_Ports x6) = False; is_Dst_Ports (Dst_Ports x7) = True; is_Dst_Ports (MultiportPorts x8) = False; is_Dst_Ports (L4_Flags x9) = False; is_Dst_Ports (CT_State x10) = False; is_Dst_Ports (Extra x11) = False; andfold_MatchExp :: forall a. [Match_expr a] -> Match_expr a; andfold_MatchExp [] = MatchAny; andfold_MatchExp [e] = e; andfold_MatchExp (e : v : va) = MatchAnd e (andfold_MatchExp (v : va)); import_protocols_from_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); import_protocols_from_ports m = let { (srcpts, rst1) = primitive_extractor (is_Src_Ports, src_ports_sel) m; (dstpts, a) = primitive_extractor (is_Dst_Ports, dst_ports_sel) rst1; } in MatchAnd (MatchAnd (MatchAnd (andfold_MatchExp (map (Match . Prot . (\ (L4Ports proto _) -> Proto proto)) (getPos srcpts))) (andfold_MatchExp (map (Match . Prot . (\ (L4Ports proto _) -> Proto proto)) (getPos dstpts)))) (alist_and (negPos_map Src_Ports srcpts ++ negPos_map Dst_Ports dstpts))) a; compress_normalize_protocols :: forall a. (Len a) => Match_expr (Common_primitive a) -> Maybe (Match_expr (Common_primitive a)); compress_normalize_protocols m = compress_normalize_protocols_step (import_protocols_from_ports m); compress_normalize_besteffort :: forall a. (Len a) => Match_expr (Common_primitive a) -> Maybe (Match_expr (Common_primitive a)); compress_normalize_besteffort m = compress_normalize_primitive_monad [compress_normalize_protocols, compress_normalize_input_interfaces, compress_normalize_output_interfaces] m; normalize_primitive_extract :: forall a b. (a -> Bool, a -> b) -> (b -> a) -> ([Negation_type b] -> [b]) -> Match_expr a -> [Match_expr a]; normalize_primitive_extract disc_sel c f m = let { (spts, rst) = primitive_extractor disc_sel m; } in map (\ spt -> MatchAnd (Match (c spt)) rst) (f spts); src_sel :: forall a. (Len a) => Common_primitive a -> Ipt_iprange a; src_sel (Src x1) = x1; is_Src :: forall a. (Len a) => Common_primitive a -> Bool; is_Src (Src x1) = True; is_Src (Dst x2) = False; is_Src (IIface x3) = False; is_Src (OIface x4) = False; is_Src (Prot x5) = False; is_Src (Src_Ports x6) = False; is_Src (Dst_Ports x7) = False; is_Src (MultiportPorts x8) = False; is_Src (L4_Flags x9) = False; is_Src (CT_State x10) = False; is_Src (Extra x11) = False; l2wi_negation_type_intersect :: forall a. (Len a) => [Negation_type (Word a, Word a)] -> Wordinterval a; l2wi_negation_type_intersect [] = wordinterval_UNIV; l2wi_negation_type_intersect (Pos (s, e) : ls) = wordinterval_intersection (WordInterval s e) (l2wi_negation_type_intersect ls); l2wi_negation_type_intersect (Neg (s, e) : ls) = wordinterval_intersection (wordinterval_invert (WordInterval s e)) (l2wi_negation_type_intersect ls); ipt_iprange_negation_type_to_br_intersect :: forall a. (Len a) => [Negation_type (Ipt_iprange a)] -> Wordinterval a; ipt_iprange_negation_type_to_br_intersect l = l2wi_negation_type_intersect (negPos_map ipt_iprange_to_interval l); wi_2_cidr_ipt_iprange_list :: forall a. (Len a) => Wordinterval a -> [Ipt_iprange a]; wi_2_cidr_ipt_iprange_list r = map (uncurry IpAddrNetmask) (cidr_split r); ipt_iprange_compress :: forall a. (Len a) => [Negation_type (Ipt_iprange a)] -> [Ipt_iprange a]; ipt_iprange_compress = wi_2_cidr_ipt_iprange_list . ipt_iprange_negation_type_to_br_intersect; normalize_src_ips :: forall a. (Len a) => Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; normalize_src_ips = normalize_primitive_extract (is_Src, src_sel) Src ipt_iprange_compress; dst_sel :: forall a. (Len a) => Common_primitive a -> Ipt_iprange a; dst_sel (Dst x2) = x2; is_Dst :: forall a. (Len a) => Common_primitive a -> Bool; is_Dst (Src x1) = False; is_Dst (Dst x2) = True; is_Dst (IIface x3) = False; is_Dst (OIface x4) = False; is_Dst (Prot x5) = False; is_Dst (Src_Ports x6) = False; is_Dst (Dst_Ports x7) = False; is_Dst (MultiportPorts x8) = False; is_Dst (L4_Flags x9) = False; is_Dst (CT_State x10) = False; is_Dst (Extra x11) = False; normalize_dst_ips :: forall a. (Len a) => Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; normalize_dst_ips = normalize_primitive_extract (is_Dst, dst_sel) Dst ipt_iprange_compress; optimize_matches_option :: forall a. (Match_expr a -> Maybe (Match_expr a)) -> [Rule a] -> [Rule a]; optimize_matches_option uu [] = []; optimize_matches_option f (Rule m a : rs) = (case f m of { Nothing -> optimize_matches_option f rs; Just ma -> Rule ma a : optimize_matches_option f rs; }); multiportports_sel :: forall a. (Len a) => Common_primitive a -> Ipt_l4_ports; multiportports_sel (MultiportPorts x8) = x8; is_MultiportPorts :: forall a. (Len a) => Common_primitive a -> Bool; is_MultiportPorts (Src x1) = False; is_MultiportPorts (Dst x2) = False; is_MultiportPorts (IIface x3) = False; is_MultiportPorts (OIface x4) = False; is_MultiportPorts (Prot x5) = False; is_MultiportPorts (Src_Ports x6) = False; is_MultiportPorts (Dst_Ports x7) = False; is_MultiportPorts (MultiportPorts x8) = True; is_MultiportPorts (L4_Flags x9) = False; is_MultiportPorts (CT_State x10) = False; is_MultiportPorts (Extra x11) = False; replace_primitive_matchexpr :: forall a b. (a -> Bool, a -> b) -> (Negation_type b -> Match_expr a) -> Match_expr a -> Match_expr a; replace_primitive_matchexpr disc_sel replace_f m = let { (asa, rst) = primitive_extractor disc_sel m; } in (if null asa then m else MatchAnd (andfold_MatchExp (map replace_f asa)) rst); rewrite_MultiportPorts_one :: forall a. (Len a) => Negation_type Ipt_l4_ports -> Match_expr (Common_primitive a); rewrite_MultiportPorts_one (Pos pts) = matchOr (Match (Src_Ports pts)) (Match (Dst_Ports pts)); rewrite_MultiportPorts_one (Neg pts) = MatchAnd (MatchNot (Match (Src_Ports pts))) (MatchNot (Match (Dst_Ports pts))); normalize_match :: forall a. Match_expr a -> [Match_expr a]; normalize_match MatchAny = [MatchAny]; normalize_match (Match m) = [Match m]; normalize_match (MatchAnd m1 m2) = concatMap (\ x -> map (MatchAnd x) (normalize_match m2)) (normalize_match m1); normalize_match (MatchNot (MatchAnd m1 m2)) = normalize_match (MatchNot m1) ++ normalize_match (MatchNot m2); normalize_match (MatchNot (MatchNot m)) = normalize_match m; normalize_match (MatchNot MatchAny) = []; normalize_match (MatchNot (Match m)) = [MatchNot (Match m)]; rewrite_MultiportPorts :: forall a. (Len a) => Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; rewrite_MultiportPorts m = normalize_match (replace_primitive_matchexpr (is_MultiportPorts, multiportports_sel) rewrite_MultiportPorts_one m); singletonize_L4Ports :: Ipt_l4_ports -> [Ipt_l4_ports]; singletonize_L4Ports (L4Ports proto pts) = map (\ p -> L4Ports proto [p]) pts; l4_ports_compress :: [Ipt_l4_ports] -> Match_compress Ipt_l4_ports; l4_ports_compress [] = MatchesAll; l4_ports_compress [L4Ports proto ps] = MatchExpr (L4Ports proto (wi2l (wordinterval_compress (l2wi ps)))); l4_ports_compress (L4Ports proto1 ps1 : L4Ports proto2 ps2 : pss) = (if not (equal_word proto1 proto2) then CannotMatch else l4_ports_compress (L4Ports proto1 (wi2l (wordinterval_intersection (l2wi ps1) (l2wi ps2))) : pss)); normalize_positive_ports_step :: forall a. (Len a) => (Common_primitive a -> Bool, Common_primitive a -> Ipt_l4_ports) -> (Ipt_l4_ports -> Common_primitive a) -> Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; normalize_positive_ports_step disc_sel c m = let { (spts, rst) = primitive_extractor disc_sel m; (pspts, []) = (getPos spts, getNeg spts); } in (case l4_ports_compress pspts of { CannotMatch -> []; MatchesAll -> [rst]; MatchExpr ma -> map (\ spt -> MatchAnd (Match (c spt)) rst) (singletonize_L4Ports ma); }); normalize_positive_src_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; normalize_positive_src_ports = normalize_positive_ports_step (is_Src_Ports, src_ports_sel) Src_Ports; rewrite_negated_primitives :: forall a b. (a -> Bool, a -> b) -> (b -> a) -> ((b -> a) -> b -> Match_expr a) -> Match_expr a -> Match_expr a; rewrite_negated_primitives disc_sel c negatea m = let { (spts, rst) = primitive_extractor disc_sel m; } in (if null (getNeg spts) then m else MatchAnd (andfold_MatchExp (map (negatea c) (getNeg spts))) (MatchAnd (andfold_MatchExp (map (Match . c) (getPos spts))) rst)); l4_ports_negate_one :: forall a. (Len a) => (Ipt_l4_ports -> Common_primitive a) -> Ipt_l4_ports -> Match_expr (Common_primitive a); l4_ports_negate_one c (L4Ports proto pts) = matchOr (MatchNot (Match (Prot (Proto proto)))) (Match (c (L4Ports proto (raw_ports_invert pts)))); rewrite_negated_src_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); rewrite_negated_src_ports m = rewrite_negated_primitives (is_Src_Ports, src_ports_sel) Src_Ports l4_ports_negate_one m; normalize_ports_generic :: forall a. (Len a) => (Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]) -> (Match_expr (Common_primitive a) -> Match_expr (Common_primitive a)) -> Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; normalize_ports_generic normalize_pos rewrite_neg m = concatMap normalize_pos (normalize_match (rewrite_neg m)); normalize_src_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; normalize_src_ports m = normalize_ports_generic normalize_positive_src_ports rewrite_negated_src_ports m; normalize_positive_dst_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; normalize_positive_dst_ports = normalize_positive_ports_step (is_Dst_Ports, dst_ports_sel) Dst_Ports; rewrite_negated_dst_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); rewrite_negated_dst_ports m = rewrite_negated_primitives (is_Dst_Ports, dst_ports_sel) Dst_Ports l4_ports_negate_one m; normalize_dst_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> [Match_expr (Common_primitive a)]; normalize_dst_ports m = normalize_ports_generic normalize_positive_dst_ports rewrite_negated_dst_ports m; normalize_rules :: forall a. (Match_expr a -> [Match_expr a]) -> [Rule a] -> [Rule a]; normalize_rules uu [] = []; normalize_rules f (Rule m a : rs) = map (\ ma -> Rule ma a) (f m) ++ normalize_rules f rs; transform_normalize_primitives :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Rule (Common_primitive a)]; transform_normalize_primitives = ((((optimize_matches_option compress_normalize_besteffort . normalize_rules normalize_dst_ips) . normalize_rules normalize_src_ips) . normalize_rules normalize_dst_ports) . normalize_rules normalize_src_ports) . normalize_rules rewrite_MultiportPorts; ctstate_is_UNIV :: Set Ctstate -> Bool; ctstate_is_UNIV c = member CT_New c && member CT_Established c && member CT_Related c && member CT_Untracked c && member CT_Invalid c; optimize_primitive_univ :: forall a. (Len a) => Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); optimize_primitive_univ (Match (IIface iface)) = (if equal_iface iface ifaceAny then MatchAny else Match (IIface iface)); optimize_primitive_univ (Match (OIface iface)) = (if equal_iface iface ifaceAny then MatchAny else Match (OIface iface)); optimize_primitive_univ (Match (Prot ProtoAny)) = MatchAny; optimize_primitive_univ (Match (L4_Flags (TCP_Flags m c))) = (if equal_set m bot_set && equal_set c bot_set then MatchAny else Match (L4_Flags (TCP_Flags m c))); optimize_primitive_univ (Match (CT_State ctstate)) = (if ctstate_is_UNIV ctstate then MatchAny else Match (CT_State ctstate)); optimize_primitive_univ (Match (Src (IpAddr va))) = Match (Src (IpAddr va)); optimize_primitive_univ (Match (Src (IpAddrRange va vb))) = Match (Src (IpAddrRange va vb)); optimize_primitive_univ (Match (Dst (IpAddr va))) = Match (Dst (IpAddr va)); optimize_primitive_univ (Match (Dst (IpAddrRange va vb))) = Match (Dst (IpAddrRange va vb)); optimize_primitive_univ (Match (Prot (Proto va))) = Match (Prot (Proto va)); optimize_primitive_univ (Match (Src_Ports v)) = Match (Src_Ports v); optimize_primitive_univ (Match (Dst_Ports v)) = Match (Dst_Ports v); optimize_primitive_univ (Match (MultiportPorts v)) = Match (MultiportPorts v); optimize_primitive_univ (Match (Extra v)) = Match (Extra v); optimize_primitive_univ (MatchNot m) = MatchNot (optimize_primitive_univ m); optimize_primitive_univ (MatchAnd m1 m2) = MatchAnd (optimize_primitive_univ m1) (optimize_primitive_univ m2); optimize_primitive_univ MatchAny = MatchAny; optimize_primitive_univ (Match (Src (IpAddrNetmask uu vc))) = (if equal_nat vc zero_nat then MatchAny else Match (Src (IpAddrNetmask uu (suc (minus_nat vc one_nat))))); optimize_primitive_univ (Match (Dst (IpAddrNetmask uv vc))) = (if equal_nat vc zero_nat then MatchAny else Match (Dst (IpAddrNetmask uv (suc (minus_nat vc one_nat))))); opt_MatchAny_match_expr_once :: forall a. Match_expr a -> Match_expr a; opt_MatchAny_match_expr_once MatchAny = MatchAny; opt_MatchAny_match_expr_once (Match a) = Match a; opt_MatchAny_match_expr_once (MatchNot (MatchNot m)) = opt_MatchAny_match_expr_once m; opt_MatchAny_match_expr_once (MatchNot (Match v)) = MatchNot (opt_MatchAny_match_expr_once (Match v)); opt_MatchAny_match_expr_once (MatchNot (MatchAnd v va)) = MatchNot (opt_MatchAny_match_expr_once (MatchAnd v va)); opt_MatchAny_match_expr_once (MatchNot MatchAny) = MatchNot (opt_MatchAny_match_expr_once MatchAny); opt_MatchAny_match_expr_once (MatchAnd MatchAny MatchAny) = MatchAny; opt_MatchAny_match_expr_once (MatchAnd MatchAny (Match v)) = opt_MatchAny_match_expr_once (Match v); opt_MatchAny_match_expr_once (MatchAnd MatchAny (MatchNot v)) = opt_MatchAny_match_expr_once (MatchNot v); opt_MatchAny_match_expr_once (MatchAnd MatchAny (MatchAnd v va)) = opt_MatchAny_match_expr_once (MatchAnd v va); opt_MatchAny_match_expr_once (MatchAnd (Match v) MatchAny) = opt_MatchAny_match_expr_once (Match v); opt_MatchAny_match_expr_once (MatchAnd (MatchNot v) MatchAny) = opt_MatchAny_match_expr_once (MatchNot v); opt_MatchAny_match_expr_once (MatchAnd (MatchAnd v va) MatchAny) = opt_MatchAny_match_expr_once (MatchAnd v va); opt_MatchAny_match_expr_once (MatchAnd (Match v) (MatchNot MatchAny)) = MatchNot MatchAny; opt_MatchAny_match_expr_once (MatchAnd (MatchNot v) (MatchNot MatchAny)) = MatchNot MatchAny; opt_MatchAny_match_expr_once (MatchAnd (MatchAnd v va) (MatchNot MatchAny)) = MatchNot MatchAny; opt_MatchAny_match_expr_once (MatchAnd (MatchNot MatchAny) (Match v)) = MatchNot MatchAny; opt_MatchAny_match_expr_once (MatchAnd (MatchNot MatchAny) (MatchNot (Match va))) = MatchNot MatchAny; opt_MatchAny_match_expr_once (MatchAnd (MatchNot MatchAny) (MatchNot (MatchNot va))) = MatchNot MatchAny; opt_MatchAny_match_expr_once (MatchAnd (MatchNot MatchAny) (MatchNot (MatchAnd va vb))) = MatchNot MatchAny; opt_MatchAny_match_expr_once (MatchAnd (MatchNot MatchAny) (MatchAnd v va)) = MatchNot MatchAny; opt_MatchAny_match_expr_once (MatchAnd (Match v) (Match va)) = MatchAnd (opt_MatchAny_match_expr_once (Match v)) (opt_MatchAny_match_expr_once (Match va)); opt_MatchAny_match_expr_once (MatchAnd (Match v) (MatchNot (Match vb))) = MatchAnd (opt_MatchAny_match_expr_once (Match v)) (opt_MatchAny_match_expr_once (MatchNot (Match vb))); opt_MatchAny_match_expr_once (MatchAnd (Match v) (MatchNot (MatchNot vb))) = MatchAnd (opt_MatchAny_match_expr_once (Match v)) (opt_MatchAny_match_expr_once (MatchNot (MatchNot vb))); opt_MatchAny_match_expr_once (MatchAnd (Match v) (MatchNot (MatchAnd vb vc))) = MatchAnd (opt_MatchAny_match_expr_once (Match v)) (opt_MatchAny_match_expr_once (MatchNot (MatchAnd vb vc))); opt_MatchAny_match_expr_once (MatchAnd (Match v) (MatchAnd va vb)) = MatchAnd (opt_MatchAny_match_expr_once (Match v)) (opt_MatchAny_match_expr_once (MatchAnd va vb)); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (Match vb)) (Match va)) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (Match vb))) (opt_MatchAny_match_expr_once (Match va)); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchNot vb)) (Match va)) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchNot vb))) (opt_MatchAny_match_expr_once (Match va)); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchAnd vb vc)) (Match va)) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchAnd vb vc))) (opt_MatchAny_match_expr_once (Match va)); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (Match va)) (MatchNot (Match vb))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (Match va))) (opt_MatchAny_match_expr_once (MatchNot (Match vb))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchNot va)) (MatchNot (Match vb))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchNot va))) (opt_MatchAny_match_expr_once (MatchNot (Match vb))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchAnd va vc)) (MatchNot (Match vb))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchAnd va vc))) (opt_MatchAny_match_expr_once (MatchNot (Match vb))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (Match va)) (MatchNot (MatchNot vb))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (Match va))) (opt_MatchAny_match_expr_once (MatchNot (MatchNot vb))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchNot va)) (MatchNot (MatchNot vb))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchNot va))) (opt_MatchAny_match_expr_once (MatchNot (MatchNot vb))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchAnd va vc)) (MatchNot (MatchNot vb))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchAnd va vc))) (opt_MatchAny_match_expr_once (MatchNot (MatchNot vb))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (Match va)) (MatchNot (MatchAnd vb vc))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (Match va))) (opt_MatchAny_match_expr_once (MatchNot (MatchAnd vb vc))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchNot va)) (MatchNot (MatchAnd vb vc))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchNot va))) (opt_MatchAny_match_expr_once (MatchNot (MatchAnd vb vc))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchAnd va vd)) (MatchNot (MatchAnd vb vc))) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchAnd va vd))) (opt_MatchAny_match_expr_once (MatchNot (MatchAnd vb vc))); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (Match vc)) (MatchAnd va vb)) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (Match vc))) (opt_MatchAny_match_expr_once (MatchAnd va vb)); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchNot vc)) (MatchAnd va vb)) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchNot vc))) (opt_MatchAny_match_expr_once (MatchAnd va vb)); opt_MatchAny_match_expr_once (MatchAnd (MatchNot (MatchAnd vc vd)) (MatchAnd va vb)) = MatchAnd (opt_MatchAny_match_expr_once (MatchNot (MatchAnd vc vd))) (opt_MatchAny_match_expr_once (MatchAnd va vb)); opt_MatchAny_match_expr_once (MatchAnd (MatchAnd v va) (Match vb)) = MatchAnd (opt_MatchAny_match_expr_once (MatchAnd v va)) (opt_MatchAny_match_expr_once (Match vb)); opt_MatchAny_match_expr_once (MatchAnd (MatchAnd v va) (MatchNot (Match vc))) = MatchAnd (opt_MatchAny_match_expr_once (MatchAnd v va)) (opt_MatchAny_match_expr_once (MatchNot (Match vc))); opt_MatchAny_match_expr_once (MatchAnd (MatchAnd v va) (MatchNot (MatchNot vc))) = MatchAnd (opt_MatchAny_match_expr_once (MatchAnd v va)) (opt_MatchAny_match_expr_once (MatchNot (MatchNot vc))); opt_MatchAny_match_expr_once (MatchAnd (MatchAnd v va) (MatchNot (MatchAnd vc vd))) = MatchAnd (opt_MatchAny_match_expr_once (MatchAnd v va)) (opt_MatchAny_match_expr_once (MatchNot (MatchAnd vc vd))); opt_MatchAny_match_expr_once (MatchAnd (MatchAnd v va) (MatchAnd vb vc)) = MatchAnd (opt_MatchAny_match_expr_once (MatchAnd v va)) (opt_MatchAny_match_expr_once (MatchAnd vb vc)); repeat_stabilize :: forall a. (Eq a) => Nat -> (a -> a) -> a -> a; repeat_stabilize n uu v = (if equal_nat n zero_nat then v else let { v_new = uu v; } in (if v == v_new then v else repeat_stabilize (minus_nat n one_nat) uu v_new)); opt_MatchAny_match_expr :: forall a. (Eq a) => Match_expr a -> Match_expr a; opt_MatchAny_match_expr m = repeat_stabilize (nat_of_integer (2 :: Integer)) opt_MatchAny_match_expr_once m; normalize_rules_dnf :: forall a. [Rule a] -> [Rule a]; normalize_rules_dnf [] = []; normalize_rules_dnf (Rule m a : rs) = map (\ ma -> Rule ma a) (normalize_match m) ++ normalize_rules_dnf rs; cut_off_after_match_any :: forall a. (Eq a) => [Rule a] -> [Rule a]; cut_off_after_match_any [] = []; cut_off_after_match_any (Rule m a : rs) = (if equal_match_expr m MatchAny && (equal_action a Accept || (equal_action a Drop || equal_action a Reject)) then [Rule m a] else Rule m a : cut_off_after_match_any rs); matcheq_matchNone :: forall a. Match_expr a -> Bool; matcheq_matchNone MatchAny = False; matcheq_matchNone (Match uu) = False; matcheq_matchNone (MatchNot MatchAny) = True; matcheq_matchNone (MatchNot (Match uv)) = False; matcheq_matchNone (MatchNot (MatchNot m)) = matcheq_matchNone m; matcheq_matchNone (MatchNot (MatchAnd m1 m2)) = matcheq_matchNone (MatchNot m1) && matcheq_matchNone (MatchNot m2); matcheq_matchNone (MatchAnd m1 m2) = matcheq_matchNone m1 || matcheq_matchNone m2; optimize_matches :: forall a. (Match_expr a -> Match_expr a) -> [Rule a] -> [Rule a]; optimize_matches f rs = optimize_matches_option (\ m -> (if matcheq_matchNone (f m) then Nothing else Just (f m))) rs; transform_optimize_dnf_strict :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Rule (Common_primitive a)]; transform_optimize_dnf_strict = cut_off_after_match_any . (optimize_matches opt_MatchAny_match_expr . normalize_rules_dnf) . optimize_matches (opt_MatchAny_match_expr . optimize_primitive_univ); get_action :: forall a. Rule a -> Action; get_action (Rule x1 x2) = x2; get_match :: forall a. Rule a -> Match_expr a; get_match (Rule x1 x2) = x1; optimize_matches_a :: forall a. (Action -> Match_expr a -> Match_expr a) -> [Rule a] -> [Rule a]; optimize_matches_a f rs = map (\ r -> Rule (f (get_action r) (get_match r)) (get_action r)) rs; remdups_rev_code :: forall a. (Eq a) => [a] -> [a] -> [a]; remdups_rev_code uu [] = []; remdups_rev_code ps (r : rs) = (if membera ps r then remdups_rev_code ps rs else r : remdups_rev_code (r : ps) rs); upper_closure :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Rule (Common_primitive a)]; upper_closure rs = remdups_rev_code [] (transform_optimize_dnf_strict (transform_normalize_primitives (transform_optimize_dnf_strict (optimize_matches_a upper_closure_matchexpr rs)))); word_to_nat :: forall a. (Len a) => Word a -> Nat; word_to_nat = unat; match_sel :: forall a. Simple_rule a -> Simple_match_ext a (); match_sel (SimpleRule x1 x2) = x1; simple_conn_matches :: forall a. (Len a) => Simple_match_ext a () -> Parts_connection_ext () -> Bool; simple_conn_matches m c = match_iface (iiface m) (pc_iiface c) && match_iface (oiface m) (pc_oiface c) && match_proto (proto m) (pc_proto c) && simple_match_port (sports m) (pc_sport c) && simple_match_port (dports m) (pc_dport c); groupWIs2 :: forall a. (Len a) => Parts_connection_ext () -> [Simple_rule a] -> [[Wordinterval a]]; groupWIs2 c rs = let { p = getParts rs; w = map getOneIp p; filterW = filter (\ r -> simple_conn_matches (match_sel r) c) rs; f = (\ wi -> (map (\ d -> runFw (getOneIp wi) d c filterW) w, map (\ s -> runFw s (getOneIp wi) c filterW) w)); } in map (map fst) (groupF snd (map (\ x -> (x, f x)) p)); wordinterval_element :: forall a. (Len0 a) => Word a -> Wordinterval a -> Bool; wordinterval_element el (WordInterval s e) = less_eq_word s el && less_eq_word el e; wordinterval_element el (RangeUnion r1 r2) = wordinterval_element el r1 || wordinterval_element el r2; matching_srcs :: forall a. (Len a) => Word a -> [Simple_rule a] -> Wordinterval a -> Wordinterval a; matching_srcs uu [] uv = empty_WordInterval; matching_srcs d (SimpleRule m Accepta : rs) acc_dropped = (if simple_match_ip (dst m) d then wordinterval_union (wordinterval_setminus (ipcidr_tuple_to_wordinterval (src m)) acc_dropped) (matching_srcs d rs acc_dropped) else matching_srcs d rs acc_dropped); matching_srcs d (SimpleRule m Dropa : rs) acc_dropped = (if simple_match_ip (dst m) d then matching_srcs d rs (wordinterval_union (ipcidr_tuple_to_wordinterval (src m)) acc_dropped) else matching_srcs d rs acc_dropped); matching_dsts :: forall a. (Len a) => Word a -> [Simple_rule a] -> Wordinterval a -> Wordinterval a; matching_dsts uu [] uv = empty_WordInterval; matching_dsts s (SimpleRule m Accepta : rs) acc_dropped = (if simple_match_ip (src m) s then wordinterval_union (wordinterval_setminus (ipcidr_tuple_to_wordinterval (dst m)) acc_dropped) (matching_dsts s rs acc_dropped) else matching_dsts s rs acc_dropped); matching_dsts s (SimpleRule m Dropa : rs) acc_dropped = (if simple_match_ip (src m) s then matching_dsts s rs (wordinterval_union (ipcidr_tuple_to_wordinterval (dst m)) acc_dropped) else matching_dsts s rs acc_dropped); groupWIs3_default_policy :: forall a. (Len a) => Parts_connection_ext () -> [Simple_rule a] -> [[Wordinterval a]]; groupWIs3_default_policy c rs = let { p = getParts rs; w = map getOneIp p; filterW = filter (\ r -> simple_conn_matches (match_sel r) c) rs; f = (\ wi -> let { mtch_dsts = matching_dsts (getOneIp wi) filterW empty_WordInterval; mtch_srcs = matching_srcs (getOneIp wi) filterW empty_WordInterval; } in (map (\ d -> wordinterval_element d mtch_dsts) w, map (\ s -> wordinterval_element s mtch_srcs) w)); } in map (map fst) (groupF snd (map (\ x -> (x, f x)) p)); equal_simple_match_ext :: forall a b. (Len a, Eq b) => Simple_match_ext a b -> Simple_match_ext a b -> Bool; equal_simple_match_ext (Simple_match_ext iifacea oifacea srca dsta protoa sportsa dportsa morea) (Simple_match_ext iiface oiface src dst proto sports dports more) = equal_iface iifacea iiface && equal_iface oifacea oiface && srca == src && dsta == dst && equal_protocol protoa proto && sportsa == sports && dportsa == dports && morea == more; simple_match_any :: forall a. (Len a) => Simple_match_ext a (); simple_match_any = Simple_match_ext ifaceAny ifaceAny (zero_word, zero_nat) (zero_word, zero_nat) ProtoAny (zero_word, word_of_int (Int_of_integer (65535 :: Integer))) (zero_word, word_of_int (Int_of_integer (65535 :: Integer))) (); has_default_policy :: forall a. (Len a) => [Simple_rule a] -> Bool; has_default_policy [] = False; has_default_policy [SimpleRule m uu] = equal_simple_match_ext m simple_match_any; has_default_policy (uv : v : va) = has_default_policy (v : va); groupWIs3 :: forall a. (Len a) => Parts_connection_ext () -> [Simple_rule a] -> [[Wordinterval a]]; groupWIs3 c rs = (if has_default_policy rs then groupWIs3_default_policy c rs else groupWIs2 c rs); inf_set :: forall a. (Eq a) => Set a -> Set a -> Set a; inf_set a (Coset xs) = fold remove xs a; inf_set a (Set xs) = Set (filter (\ x -> member x a) xs); sup_set :: forall a. (Eq a) => Set a -> Set a -> Set a; sup_set (Coset xs) a = Coset (filter (\ x -> not (member x a)) xs); sup_set (Set xs) a = fold insert xs a; word_less_eq :: forall a. (Len a) => Word a -> Word a -> Bool; word_less_eq a b = less_eq_word a b; rw_Reject :: forall a. [Rule a] -> [Rule a]; rw_Reject [] = []; rw_Reject (Rule m Reject : rs) = Rule m Drop : rw_Reject rs; rw_Reject (Rule v Accept : rs) = Rule v Accept : rw_Reject rs; rw_Reject (Rule v Drop : rs) = Rule v Drop : rw_Reject rs; rw_Reject (Rule v Log : rs) = Rule v Log : rw_Reject rs; rw_Reject (Rule v (Call vb) : rs) = Rule v (Call vb) : rw_Reject rs; rw_Reject (Rule v Return : rs) = Rule v Return : rw_Reject rs; rw_Reject (Rule v (Goto vb) : rs) = Rule v (Goto vb) : rw_Reject rs; rw_Reject (Rule v Empty : rs) = Rule v Empty : rw_Reject rs; rw_Reject (Rule v Unknown : rs) = Rule v Unknown : rw_Reject rs; shiftr_word :: forall a. (Len0 a) => Word a -> Nat -> Word a; shiftr_word w n = funpow n shiftr1 w; int_to_ipv6preferred :: Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))) -> Ipv6addr_syntax; int_to_ipv6preferred i = IPv6AddrPreferred (ucast (shiftr_word (bitAND_word i (word_of_int (Int_of_integer (340277174624079928635746076935438991360 :: Integer)))) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (7 :: Integer))))) (ucast (shiftr_word (bitAND_word i (word_of_int (Int_of_integer (5192217630372313364192902785269760 :: Integer)))) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (6 :: Integer))))) (ucast (shiftr_word (bitAND_word i (word_of_int (Int_of_integer (79226953588444722964369244160 :: Integer)))) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (5 :: Integer))))) (ucast (shiftr_word (bitAND_word i (word_of_int (Int_of_integer (1208907372870555465154560 :: Integer)))) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (4 :: Integer))))) (ucast (shiftr_word (bitAND_word i (word_of_int (Int_of_integer (18446462598732840960 :: Integer)))) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (3 :: Integer))))) (ucast (shiftr_word (bitAND_word i (word_of_int (Int_of_integer (281470681743360 :: Integer)))) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (2 :: Integer))))) (ucast (shiftr_word (bitAND_word i (word_of_int (Int_of_integer (4294901760 :: Integer)))) (times_nat (nat_of_integer (16 :: Integer)) one_nat))) (ucast (bitAND_word i (word_of_int (Int_of_integer (65535 :: Integer))))); ipv6preferred_to_int :: Ipv6addr_syntax -> Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))); ipv6preferred_to_int (IPv6AddrPreferred a b c d e f g h) = bitOR_word (shiftl_word (ucast a) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (7 :: Integer)))) (bitOR_word (shiftl_word (ucast b) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (6 :: Integer)))) (bitOR_word (shiftl_word (ucast c) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (5 :: Integer)))) (bitOR_word (shiftl_word (ucast d) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (4 :: Integer)))) (bitOR_word (shiftl_word (ucast e) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (3 :: Integer)))) (bitOR_word (shiftl_word (ucast f) (times_nat (nat_of_integer (16 :: Integer)) (nat_of_integer (2 :: Integer)))) (bitOR_word (shiftl_word (ucast g) (times_nat (nat_of_integer (16 :: Integer)) one_nat)) (shiftl_word (ucast h) (times_nat (nat_of_integer (16 :: Integer)) zero_nat)))))))); string_of_nat :: Nat -> [Prelude.Char]; string_of_nat n = (if less_nat n (nat_of_integer (10 :: Integer)) then [char_of_nat (plus_nat (nat_of_integer (48 :: Integer)) n)] else string_of_nat (divide_nat n (nat_of_integer (10 :: Integer))) ++ [char_of_nat (plus_nat (nat_of_integer (48 :: Integer)) (modulo_nat n (nat_of_integer (10 :: Integer))))]); dotteddecimal_toString :: (Nat, (Nat, (Nat, Nat))) -> [Prelude.Char]; dotteddecimal_toString (a, (b, (c, d))) = string_of_nat a ++ "." ++ string_of_nat b ++ "." ++ string_of_nat c ++ "." ++ string_of_nat d; dotdecimal_of_ipv4addr :: Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> (Nat, (Nat, (Nat, Nat))); dotdecimal_of_ipv4addr a = (nat_of_ipv4addr (bitAND_word (shiftr_word a (nat_of_integer (24 :: Integer))) (word_of_int (Int_of_integer (255 :: Integer)))), (nat_of_ipv4addr (bitAND_word (shiftr_word a (nat_of_integer (16 :: Integer))) (word_of_int (Int_of_integer (255 :: Integer)))), (nat_of_ipv4addr (bitAND_word (shiftr_word a (nat_of_integer (8 :: Integer))) (word_of_int (Int_of_integer (255 :: Integer)))), nat_of_ipv4addr (bitAND_word a (word_of_int (Int_of_integer (255 :: Integer))))))); ipv4addr_toString :: Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> [Prelude.Char]; ipv4addr_toString ip = dotteddecimal_toString (dotdecimal_of_ipv4addr ip); ipv4addr_wordinterval_toString :: Wordinterval (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> [Prelude.Char]; ipv4addr_wordinterval_toString (WordInterval s e) = (if equal_word s e then ipv4addr_toString s else "{" ++ ipv4addr_toString s ++ " .. " ++ ipv4addr_toString e ++ "}"); ipv4addr_wordinterval_toString (RangeUnion a b) = ipv4addr_wordinterval_toString a ++ " u " ++ ipv4addr_wordinterval_toString b; wordinterval_eq :: forall a. (Len a) => Wordinterval a -> Wordinterval a -> Bool; wordinterval_eq r1 r2 = wordinterval_subset r1 r2 && wordinterval_subset r2 r1; ipassmt_ignore_wildcard_list :: forall a. (Len a) => [(Iface, [(Word a, Nat)])] -> [(Iface, [(Word a, Nat)])]; ipassmt_ignore_wildcard_list ipassmt = filter (\ (_, ips) -> not (wordinterval_eq (l2wi (map ipcidr_to_interval ips)) wordinterval_UNIV)) ipassmt; list_separated_toString :: forall a. [Prelude.Char] -> (a -> [Prelude.Char]) -> [a] -> [Prelude.Char]; list_separated_toString sep toStr ls = concat (splice (map toStr ls) (replicate (minus_nat (size_list ls) one_nat) sep)); list_toString :: forall a. (a -> [Prelude.Char]) -> [a] -> [Prelude.Char]; list_toString toStr ls = "[" ++ list_separated_toString ", " toStr ls ++ "]"; ipassmt_sanity_defined :: forall a. (Len a) => [Rule (Common_primitive a)] -> (Iface -> Maybe [(Word a, Nat)]) -> Bool; ipassmt_sanity_defined rs ipassmt = all (\ iface -> not (is_none (ipassmt iface))) (collect_ifaces rs); debug_ipassmt_generic :: forall a. (Len a) => (Wordinterval a -> [Prelude.Char]) -> [(Iface, [(Word a, Nat)])] -> [Rule (Common_primitive a)] -> [[Prelude.Char]]; debug_ipassmt_generic toStr ipassmt rs = let { ifaces = map fst ipassmt; } in ["distinct: " ++ (if distinct ifaces then "passed" else "FAIL!"), "ipassmt_sanity_nowildcards: " ++ (if ball (image fst (Set ipassmt)) (\ iface -> not (iface_is_wildcard iface)) then "passed" else "fail: " ++ list_toString iface_sel (filter iface_is_wildcard ifaces)), "ipassmt_sanity_defined (interfaces defined in the ruleset are also in ipassmt): " ++ (if ipassmt_sanity_defined rs (map_of ipassmt) then "passed" else "fail: " ++ list_toString iface_sel (filter (\ i -> not (membera ifaces i)) (collect_ifaces rs))), "ipassmt_sanity_disjoint (no zone-spanning interfaces): " ++ (if let { is = image fst (Set ipassmt); } in ball is (\ i1 -> ball is (\ i2 -> (if not (equal_iface i1 i2) then wordinterval_empty (wordinterval_intersection (l2wi (map ipcidr_to_interval (the (map_of ipassmt i1)))) (l2wi (map ipcidr_to_interval (the (map_of ipassmt i2))))) else True))) then "passed" else "fail: " ++ list_toString (\ (i1, i2) -> "(" ++ iface_sel i1 ++ "," ++ iface_sel i2 ++ ")") (filter (\ (i1, i2) -> not (equal_iface i1 i2) && not (wordinterval_empty (wordinterval_intersection (l2wi (map ipcidr_to_interval (the (map_of ipassmt i1)))) (l2wi (map ipcidr_to_interval (the (map_of ipassmt i2))))))) (product ifaces ifaces))), "ipassmt_sanity_disjoint excluding UNIV interfaces: " ++ let { ipassmta = ipassmt_ignore_wildcard_list ipassmt; ifacesa = map fst ipassmta; } in (if let { is = image fst (Set ipassmta); } in ball is (\ i1 -> ball is (\ i2 -> (if not (equal_iface i1 i2) then wordinterval_empty (wordinterval_intersection (l2wi (map ipcidr_to_interval (the (map_of ipassmta i1)))) (l2wi (map ipcidr_to_interval (the (map_of ipassmta i2))))) else True))) then "passed" else "fail: " ++ list_toString (\ (i1, i2) -> "(" ++ iface_sel i1 ++ "," ++ iface_sel i2 ++ ")") (filter (\ (i1, i2) -> not (equal_iface i1 i2) && not (wordinterval_empty (wordinterval_intersection (l2wi (map ipcidr_to_interval (the (map_of ipassmta i1)))) (l2wi (map ipcidr_to_interval (the (map_of ipassmta i2))))))) (product ifacesa ifacesa))), "ipassmt_sanity_complete: " ++ (if distinct (map fst ipassmt) && let { range = map snd ipassmt; } in wordinterval_eq (wordinterval_Union (map (l2wi . map ipcidr_to_interval) range)) wordinterval_UNIV then "passed" else "the following is not covered: " ++ toStr (wordinterval_setminus wordinterval_UNIV (wordinterval_Union (map (l2wi . map ipcidr_to_interval) (map snd ipassmt))))), "ipassmt_sanity_complete excluding UNIV interfaces: " ++ let { ipassmta = ipassmt_ignore_wildcard_list ipassmt; } in (if distinct (map fst ipassmta) && let { range = map snd ipassmta; } in wordinterval_eq (wordinterval_Union (map (l2wi . map ipcidr_to_interval) range)) wordinterval_UNIV then "passed" else "the following is not covered: " ++ toStr (wordinterval_setminus wordinterval_UNIV (wordinterval_Union (map (l2wi . map ipcidr_to_interval) (map snd ipassmta)))))]; debug_ipassmt_ipv4 :: [(Iface, [(Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))), Nat)])] -> [Rule (Common_primitive (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))] -> [[Prelude.Char]]; debug_ipassmt_ipv4 = debug_ipassmt_generic ipv4addr_wordinterval_toString; string_of_word_single :: forall a. (Len a) => Bool -> Word a -> [Prelude.Char]; string_of_word_single lc w = (if less_word w (word_of_int (Int_of_integer (10 :: Integer))) then [char_of_nat (plus_nat (nat_of_integer (48 :: Integer)) (unat w))] else (if less_word w (word_of_int (Int_of_integer (36 :: Integer))) then [char_of_nat (plus_nat (if lc then nat_of_integer (87 :: Integer) else nat_of_integer (55 :: Integer)) (unat w))] else error "undefined")); modulo_word :: forall a. (Len0 a) => Word a -> Word a -> Word a; modulo_word a b = word_of_int (modulo_int (uint a) (uint b)); divide_int :: Int -> Int -> Int; divide_int k l = Int_of_integer (divide_integer (integer_of_int k) (integer_of_int l)); divide_word :: forall a. (Len0 a) => Word a -> Word a -> Word a; divide_word a b = word_of_int (divide_int (uint a) (uint b)); string_of_word :: forall a. (Len a) => Bool -> Word a -> Nat -> Word a -> [Prelude.Char]; string_of_word lc base ml w = (if less_word base (word_of_int (Int_of_integer (2 :: Integer))) || less_nat ((len_of :: Itself a -> Nat) Type) (nat_of_integer (2 :: Integer)) then error "undefined" else (if less_word w base && equal_nat ml zero_nat then string_of_word_single lc w else string_of_word lc base (minus_nat ml one_nat) (divide_word w base) ++ string_of_word_single lc (modulo_word w base))); hex_string_of_word :: forall a. (Len a) => Nat -> Word a -> [Prelude.Char]; hex_string_of_word l = string_of_word True (word_of_int (Int_of_integer (16 :: Integer))) l; hex_string_of_word0 :: forall a. (Len a) => Word a -> [Prelude.Char]; hex_string_of_word0 = hex_string_of_word zero_nat; ipv6_preferred_to_compressed :: Ipv6addr_syntax -> [Maybe (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))]; ipv6_preferred_to_compressed (IPv6AddrPreferred a b c d e f g h) = let { lss = goup_by_zeros [a, b, c, d, e, f, g, h]; max_zero_seq = foldr (\ xs -> max (size_list xs)) lss zero_nat; aa = (if less_nat one_nat max_zero_seq then list_replace1 (replicate max_zero_seq zero_word) [] lss else lss); } in list_explode aa; ipv6addr_toString :: Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))) -> [Prelude.Char]; ipv6addr_toString ip = let { partslist = ipv6_preferred_to_compressed (int_to_ipv6preferred ip); fix_start = (\ ps -> (case ps of { [] -> ps; Nothing : _ -> Nothing : ps; Just _ : _ -> ps; })); fix_end = (\ ps -> (case reverse ps of { [] -> ps; Nothing : _ -> ps ++ [Nothing]; Just _ : _ -> ps; })); } in list_separated_toString ":" (\ a -> (case a of { Nothing -> []; Just aa -> hex_string_of_word0 aa; })) ((fix_end . fix_start) partslist); ipv6addr_wordinterval_toString :: Wordinterval (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))) -> [Prelude.Char]; ipv6addr_wordinterval_toString (WordInterval s e) = (if equal_word s e then ipv6addr_toString s else "{" ++ ipv6addr_toString s ++ " .. " ++ ipv6addr_toString e ++ "}"); ipv6addr_wordinterval_toString (RangeUnion a b) = ipv6addr_wordinterval_toString a ++ " u " ++ ipv6addr_wordinterval_toString b; debug_ipassmt_ipv6 :: [(Iface, [(Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))), Nat)])] -> [Rule (Common_primitive (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))))] -> [[Prelude.Char]]; debug_ipassmt_ipv6 = debug_ipassmt_generic ipv6addr_wordinterval_toString; sorted :: forall a. (Linorder a) => [a] -> Bool; sorted [x] = True; sorted [] = True; sorted (x : y : zs) = less_eq x y && sorted (y : zs); get_exists_matching_src_ips_executable :: forall a. (Len a) => Iface -> Match_expr (Common_primitive a) -> Wordinterval a; get_exists_matching_src_ips_executable iface m = let { (i_matches, _) = primitive_extractor (is_Iiface, iiface_sel) m; } in (if all (\ a -> (case a of { Pos i -> match_iface i (iface_sel iface); Neg i -> not (match_iface i (iface_sel iface)); })) i_matches then let { (ip_matches, _) = primitive_extractor (is_Src, src_sel) m; } in (if null ip_matches then wordinterval_UNIV else l2wi_negation_type_intersect (negPos_map ipt_iprange_to_interval ip_matches)) else empty_WordInterval); matcheq_matchAny :: forall a. Match_expr a -> Bool; matcheq_matchAny MatchAny = True; matcheq_matchAny (MatchNot m) = not (matcheq_matchAny m); matcheq_matchAny (MatchAnd m1 m2) = matcheq_matchAny m1 && matcheq_matchAny m2; matcheq_matchAny (Match uu) = error "undefined"; has_primitive :: forall a. Match_expr a -> Bool; has_primitive MatchAny = False; has_primitive (Match a) = True; has_primitive (MatchNot m) = has_primitive m; has_primitive (MatchAnd m1 m2) = has_primitive m1 || has_primitive m2; get_all_matching_src_ips_executable :: forall a. (Len a) => Iface -> Match_expr (Common_primitive a) -> Wordinterval a; get_all_matching_src_ips_executable iface m = let { (i_matches, rest1) = primitive_extractor (is_Iiface, iiface_sel) m; } in (if all (\ a -> (case a of { Pos i -> match_iface i (iface_sel iface); Neg i -> not (match_iface i (iface_sel iface)); })) i_matches then let { (ip_matches, rest2) = primitive_extractor (is_Src, src_sel) rest1; } in (if not (has_primitive rest2) && matcheq_matchAny rest2 then (if null ip_matches then wordinterval_UNIV else l2wi_negation_type_intersect (negPos_map ipt_iprange_to_interval ip_matches)) else empty_WordInterval) else empty_WordInterval); no_spoofing_algorithm_executable :: forall a. (Len a) => Iface -> (Iface -> Maybe [(Word a, Nat)]) -> [Rule (Common_primitive a)] -> Wordinterval a -> Wordinterval a -> Bool; no_spoofing_algorithm_executable iface ipassmt [] allowed denied1 = wordinterval_subset (wordinterval_setminus allowed denied1) (l2wi (map ipcidr_to_interval (the (ipassmt iface)))); no_spoofing_algorithm_executable iface ipassmt (Rule m Accept : rs) allowed denied1 = no_spoofing_algorithm_executable iface ipassmt rs (wordinterval_union allowed (get_exists_matching_src_ips_executable iface m)) denied1; no_spoofing_algorithm_executable iface ipassmt (Rule m Drop : rs) allowed denied1 = no_spoofing_algorithm_executable iface ipassmt rs allowed (wordinterval_union denied1 (wordinterval_setminus (get_all_matching_src_ips_executable iface m) allowed)); no_spoofing_algorithm_executable uu uv (Rule vb Log : va) ux uy = error "undefined"; no_spoofing_algorithm_executable uu uv (Rule vb Reject : va) ux uy = error "undefined"; no_spoofing_algorithm_executable uu uv (Rule vb (Call vd) : va) ux uy = error "undefined"; no_spoofing_algorithm_executable uu uv (Rule vb Return : va) ux uy = error "undefined"; no_spoofing_algorithm_executable uu uv (Rule vb (Goto vd) : va) ux uy = error "undefined"; no_spoofing_algorithm_executable uu uv (Rule vb Empty : va) ux uy = error "undefined"; no_spoofing_algorithm_executable uu uv (Rule vb Unknown : va) ux uy = error "undefined"; no_spoofing_iface :: forall a. (Len a) => Iface -> (Iface -> Maybe [(Word a, Nat)]) -> [Rule (Common_primitive a)] -> Bool; no_spoofing_iface iface ipassmt rs = no_spoofing_algorithm_executable iface ipassmt rs empty_WordInterval empty_WordInterval; is_pos_Extra :: forall a. (Len a) => Negation_type (Common_primitive a) -> Bool; is_pos_Extra a = (case a of { Pos (Src _) -> False; Pos (Dst _) -> False; Pos (IIface _) -> False; Pos (OIface _) -> False; Pos (Prot _) -> False; Pos (Src_Ports _) -> False; Pos (Dst_Ports _) -> False; Pos (MultiportPorts _) -> False; Pos (L4_Flags _) -> False; Pos (CT_State _) -> False; Pos (Extra _) -> True; Neg _ -> False; }); nat_to_8word :: Nat -> Word (Bit0 (Bit0 (Bit0 Num1))); nat_to_8word i = of_nat i; mk_L4Ports_pre :: [(Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))] -> Ipt_l4_ports; mk_L4Ports_pre ports_raw = L4Ports zero_word ports_raw; rm_LogEmpty :: forall a. [Rule a] -> [Rule a]; rm_LogEmpty [] = []; rm_LogEmpty (Rule uu Empty : rs) = rm_LogEmpty rs; rm_LogEmpty (Rule uv Log : rs) = rm_LogEmpty rs; rm_LogEmpty (Rule v Accept : rs) = Rule v Accept : rm_LogEmpty rs; rm_LogEmpty (Rule v Drop : rs) = Rule v Drop : rm_LogEmpty rs; rm_LogEmpty (Rule v Reject : rs) = Rule v Reject : rm_LogEmpty rs; rm_LogEmpty (Rule v (Call vb) : rs) = Rule v (Call vb) : rm_LogEmpty rs; rm_LogEmpty (Rule v Return : rs) = Rule v Return : rm_LogEmpty rs; rm_LogEmpty (Rule v (Goto vb) : rs) = Rule v (Goto vb) : rm_LogEmpty rs; rm_LogEmpty (Rule v Unknown : rs) = Rule v Unknown : rm_LogEmpty rs; ipv4addr_of_dotdecimal :: (Nat, (Nat, (Nat, Nat))) -> Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))); ipv4addr_of_dotdecimal (a, (b, (c, d))) = ipv4addr_of_nat (plus_nat (plus_nat (plus_nat d (times_nat (nat_of_integer (256 :: Integer)) c)) (times_nat (nat_of_integer (65536 :: Integer)) b)) (times_nat (nat_of_integer (16777216 :: Integer)) a)); makea :: forall a. [Prelude.Char] -> Maybe (Word a) -> Routing_action_ext a (); makea output_iface next_hop = Routing_action_ext output_iface next_hop (); make :: forall a. (Len a) => Prefix_match a -> Nat -> Routing_action_ext a () -> Routing_rule_ext a (); make routing_match metric routing_action = Routing_rule_ext routing_match metric routing_action (); default_metric :: forall a. (Zero a) => a; default_metric = zero; empty_rr_hlp :: forall a. (Len a) => Prefix_match a -> Routing_rule_ext a (); empty_rr_hlp pm = make pm default_metric (makea [] Nothing); all_pairs :: forall a. [a] -> [(a, a)]; all_pairs xs = concatMap (\ x -> map (\ a -> (x, a)) xs) xs; sanity_wf_ruleset :: forall a. [([Prelude.Char], [Rule a])] -> Bool; sanity_wf_ruleset gamma = let { dom = map fst gamma; ran = map snd gamma; } in distinct dom && all (all (\ r -> (case get_action r of { Accept -> True; Drop -> True; Log -> True; Reject -> True; Call a -> membera dom a; Return -> True; Goto a -> membera dom a; Empty -> True; Unknown -> False; }))) ran; match_list_to_match_expr :: forall a. [Match_expr a] -> Match_expr a; match_list_to_match_expr [] = MatchNot MatchAny; match_list_to_match_expr (m : ms) = matchOr m (match_list_to_match_expr ms); ipassmt_iface_replace_dstip_mexpr :: forall a. (Len a) => (Iface -> Maybe [(Word a, Nat)]) -> Iface -> Match_expr (Common_primitive a); ipassmt_iface_replace_dstip_mexpr ipassmt ifce = (case ipassmt ifce of { Nothing -> Match (OIface ifce); Just ips -> match_list_to_match_expr (map (Match . Dst) (map (uncurry IpAddrNetmask) ips)); }); oiface_rewrite :: forall a. (Len a) => (Iface -> Maybe [(Word a, Nat)]) -> Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); oiface_rewrite uu MatchAny = MatchAny; oiface_rewrite ipassmt (Match (OIface ifce)) = ipassmt_iface_replace_dstip_mexpr ipassmt ifce; oiface_rewrite uv (Match (Src v)) = Match (Src v); oiface_rewrite uv (Match (Dst v)) = Match (Dst v); oiface_rewrite uv (Match (IIface v)) = Match (IIface v); oiface_rewrite uv (Match (Prot v)) = Match (Prot v); oiface_rewrite uv (Match (Src_Ports v)) = Match (Src_Ports v); oiface_rewrite uv (Match (Dst_Ports v)) = Match (Dst_Ports v); oiface_rewrite uv (Match (MultiportPorts v)) = Match (MultiportPorts v); oiface_rewrite uv (Match (L4_Flags v)) = Match (L4_Flags v); oiface_rewrite uv (Match (CT_State v)) = Match (CT_State v); oiface_rewrite uv (Match (Extra v)) = Match (Extra v); oiface_rewrite ipassmt (MatchNot m) = MatchNot (oiface_rewrite ipassmt m); oiface_rewrite ipassmt (MatchAnd m1 m2) = MatchAnd (oiface_rewrite ipassmt m1) (oiface_rewrite ipassmt m2); ipassmt_iface_constrain_srcip_mexpr :: forall a. (Len a) => (Iface -> Maybe [(Word a, Nat)]) -> Iface -> Match_expr (Common_primitive a); ipassmt_iface_constrain_srcip_mexpr ipassmt ifce = (case ipassmt ifce of { Nothing -> Match (IIface ifce); Just ips -> MatchAnd (Match (IIface ifce)) (match_list_to_match_expr (map (Match . Src) (map (uncurry IpAddrNetmask) ips))); }); iiface_constrain :: forall a. (Len a) => (Iface -> Maybe [(Word a, Nat)]) -> Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); iiface_constrain uu MatchAny = MatchAny; iiface_constrain ipassmt (Match (IIface ifce)) = ipassmt_iface_constrain_srcip_mexpr ipassmt ifce; iiface_constrain ipassmt (Match (Src v)) = Match (Src v); iiface_constrain ipassmt (Match (Dst v)) = Match (Dst v); iiface_constrain ipassmt (Match (OIface v)) = Match (OIface v); iiface_constrain ipassmt (Match (Prot v)) = Match (Prot v); iiface_constrain ipassmt (Match (Src_Ports v)) = Match (Src_Ports v); iiface_constrain ipassmt (Match (Dst_Ports v)) = Match (Dst_Ports v); iiface_constrain ipassmt (Match (MultiportPorts v)) = Match (MultiportPorts v); iiface_constrain ipassmt (Match (L4_Flags v)) = Match (L4_Flags v); iiface_constrain ipassmt (Match (CT_State v)) = Match (CT_State v); iiface_constrain ipassmt (Match (Extra v)) = Match (Extra v); iiface_constrain ipassmt (MatchNot m) = MatchNot (iiface_constrain ipassmt m); iiface_constrain ipassmt (MatchAnd m1 m2) = MatchAnd (iiface_constrain ipassmt m1) (iiface_constrain ipassmt m2); ipassmt_iface_replace_srcip_mexpr :: forall a. (Len a) => (Iface -> Maybe [(Word a, Nat)]) -> Iface -> Match_expr (Common_primitive a); ipassmt_iface_replace_srcip_mexpr ipassmt ifce = (case ipassmt ifce of { Nothing -> Match (IIface ifce); Just ips -> match_list_to_match_expr (map (Match . Src) (map (uncurry IpAddrNetmask) ips)); }); iiface_rewrite :: forall a. (Len a) => (Iface -> Maybe [(Word a, Nat)]) -> Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); iiface_rewrite uu MatchAny = MatchAny; iiface_rewrite ipassmt (Match (IIface ifce)) = ipassmt_iface_replace_srcip_mexpr ipassmt ifce; iiface_rewrite ipassmt (Match (Src v)) = Match (Src v); iiface_rewrite ipassmt (Match (Dst v)) = Match (Dst v); iiface_rewrite ipassmt (Match (OIface v)) = Match (OIface v); iiface_rewrite ipassmt (Match (Prot v)) = Match (Prot v); iiface_rewrite ipassmt (Match (Src_Ports v)) = Match (Src_Ports v); iiface_rewrite ipassmt (Match (Dst_Ports v)) = Match (Dst_Ports v); iiface_rewrite ipassmt (Match (MultiportPorts v)) = Match (MultiportPorts v); iiface_rewrite ipassmt (Match (L4_Flags v)) = Match (L4_Flags v); iiface_rewrite ipassmt (Match (CT_State v)) = Match (CT_State v); iiface_rewrite ipassmt (Match (Extra v)) = Match (Extra v); iiface_rewrite ipassmt (MatchNot m) = MatchNot (iiface_rewrite ipassmt m); iiface_rewrite ipassmt (MatchAnd m1 m2) = MatchAnd (iiface_rewrite ipassmt m1) (iiface_rewrite ipassmt m2); reduce_range_destination :: forall a b. (Eq a, Len b) => [(a, Wordinterval b)] -> [(a, Wordinterval b)]; reduce_range_destination l = let { ps = remdups (map fst l); c = (\ s -> ((wordinterval_Union . map snd) . filter ((\ a -> s == a) . fst)) l); } in map (\ p -> (p, c p)) ps; routing_action :: forall a b. (Len a) => Routing_rule_ext a b -> Routing_action_ext a (); routing_action (Routing_rule_ext routing_match metric routing_action more) = routing_action; output_iface :: forall a b. Routing_action_ext a b -> [Prelude.Char]; output_iface (Routing_action_ext output_iface next_hop more) = output_iface; range_prefix_match :: forall a. (Len a) => Prefix_match a -> Wordinterval a -> (Wordinterval a, Wordinterval a); range_prefix_match pfx rg = let { pfxrg = prefix_to_wordinterval pfx; } in (wordinterval_intersection rg pfxrg, wordinterval_setminus rg pfxrg); routing_port_ranges :: forall a. (Len a) => [Routing_rule_ext a ()] -> Wordinterval a -> [([Prelude.Char], Wordinterval a)]; routing_port_ranges [] lo = (if wordinterval_empty lo then [] else [(output_iface ((routing_action :: Routing_rule_ext a () -> Routing_action_ext a ()) (error "undefined")), lo)]); routing_port_ranges (a : asa) lo = let { rpm = range_prefix_match (routing_match a) lo; m = fst rpm; nm = snd rpm; } in (output_iface (routing_action a), m) : routing_port_ranges asa nm; routing_ipassmt_wi :: forall a. (Len a) => [Routing_rule_ext a ()] -> [([Prelude.Char], Wordinterval a)]; routing_ipassmt_wi tbl = reduce_range_destination (routing_port_ranges tbl wordinterval_UNIV); routing_ipassmt :: forall a. (Len a) => [Routing_rule_ext a ()] -> [(Iface, [(Word a, Nat)])]; routing_ipassmt rt = map (apfst Iface . apsnd cidr_split) (routing_ipassmt_wi rt); iface_try_rewrite :: forall a. (Len a) => [(Iface, [(Word a, Nat)])] -> Maybe [Routing_rule_ext a ()] -> [Rule (Common_primitive a)] -> [Rule (Common_primitive a)]; iface_try_rewrite ipassmt rtblo rs = let { o_rewrite = (case rtblo of { Nothing -> id; Just rtbl -> transform_optimize_dnf_strict . optimize_matches (oiface_rewrite (map_of_ipassmt (routing_ipassmt rtbl))); }); } in (if let { is = image fst (Set ipassmt); } in ball is (\ i1 -> ball is (\ i2 -> (if not (equal_iface i1 i2) then wordinterval_empty (wordinterval_intersection (l2wi (map ipcidr_to_interval (the (map_of ipassmt i1)))) (l2wi (map ipcidr_to_interval (the (map_of ipassmt i2))))) else True))) && ipassmt_sanity_defined rs (map_of ipassmt) then optimize_matches (iiface_rewrite (map_of_ipassmt ipassmt)) (o_rewrite rs) else optimize_matches (iiface_constrain (map_of_ipassmt ipassmt)) (o_rewrite rs)); get_pos_Extra :: forall a. (Len a) => Negation_type (Common_primitive a) -> [Prelude.Char]; get_pos_Extra a = let { (Pos (Extra e)) = a; } in e; map_of_string :: forall a. [([Prelude.Char], [Rule (Common_primitive a)])] -> [Prelude.Char] -> Maybe [Rule (Common_primitive a)]; map_of_string rs = map_of rs; nat_to_16word :: Nat -> Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))); nat_to_16word i = of_nat i; ipassmt_generic_ipv4 :: [(Iface, [(Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))), Nat)])]; ipassmt_generic_ipv4 = [(Iface "lo", [(ipv4addr_of_dotdecimal (nat_of_integer (127 :: Integer), (zero_nat, (zero_nat, zero_nat))), nat_of_integer (8 :: Integer))])]; ipassmt_generic_ipv6 :: [(Iface, [(Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))), Nat)])]; ipassmt_generic_ipv6 = [(Iface "lo", [(one_word, nat_of_integer (128 :: Integer))])]; valid_prefixes :: forall a b. (Len a) => [Routing_rule_ext a b] -> Bool; valid_prefixes r = foldr ((\ a b -> a && b) . (\ rr -> valid_prefix (routing_match rr))) r True; ipv6_unparsed_compressed_to_preferred :: [Maybe (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))] -> Maybe Ipv6addr_syntax; ipv6_unparsed_compressed_to_preferred ls = (if not (equal_nat (size_list (filter is_none ls)) one_nat) || less_nat (nat_of_integer (7 :: Integer)) (size_list (filter (\ p -> not (is_none p)) ls)) then Nothing else let { before_omission = map the (takeWhile (\ x -> not (is_none x)) ls); after_omission = map the (drop one_nat (dropWhile (\ x -> not (is_none x)) ls)); num_omissions = minus_nat (nat_of_integer (8 :: Integer)) (plus_nat (size_list before_omission) (size_list after_omission)); a = before_omission ++ replicate num_omissions zero_word ++ after_omission; } in (case a of { [] -> Nothing; aa : b -> (case b of { [] -> Nothing; ba : c -> (case c of { [] -> Nothing; ca : d -> (case d of { [] -> Nothing; da : e -> (case e of { [] -> Nothing; ea : f -> (case f of { [] -> Nothing; fa : g -> (case g of { [] -> Nothing; ga : h -> (case h of { [] -> Nothing; [ha] -> Just (IPv6AddrPreferred aa ba ca da ea fa ga ha); _ : _ : _ -> Nothing; }); }); }); }); }); }); }); })); mk_ipv6addr :: [Maybe (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))] -> Maybe Ipv6addr_syntax; mk_ipv6addr partslist = let { fix_start = (\ ps -> (case ps of { [] -> ps; [Nothing] -> ps; Nothing : Nothing : _ -> tl ps; Nothing : Just _ : _ -> ps; Just _ : _ -> ps; })); fix_end = (\ ps -> (case reverse ps of { [] -> ps; [Nothing] -> ps; Nothing : Nothing : _ -> butlast ps; Nothing : Just _ : _ -> ps; Just _ : _ -> ps; })); ps = (fix_end . fix_start) partslist; } in (if equal_nat (size_list (filter is_none ps)) one_nat then ipv6_unparsed_compressed_to_preferred ps else (case ps of { [] -> Nothing; Nothing : _ -> Nothing; [Just _] -> Nothing; Just _ : Nothing : _ -> Nothing; [Just _, Just _] -> Nothing; Just _ : Just _ : Nothing : _ -> Nothing; [Just _, Just _, Just _] -> Nothing; Just _ : Just _ : Just _ : Nothing : _ -> Nothing; [Just _, Just _, Just _, Just _] -> Nothing; Just _ : Just _ : Just _ : Just _ : Nothing : _ -> Nothing; [Just _, Just _, Just _, Just _, Just _] -> Nothing; Just _ : Just _ : Just _ : Just _ : Just _ : Nothing : _ -> Nothing; [Just _, Just _, Just _, Just _, Just _, Just _] -> Nothing; Just _ : Just _ : Just _ : Just _ : Just _ : Just _ : Nothing : _ -> Nothing; [Just _, Just _, Just _, Just _, Just _, Just _, Just _] -> Nothing; Just _ : Just _ : Just _ : Just _ : Just _ : Just _ : Just _ : Nothing : _ -> Nothing; [Just a, Just b, Just c, Just d, Just e, Just f, Just g, Just h] -> Just (IPv6AddrPreferred a b c d e f g h); Just _ : Just _ : Just _ : Just _ : Just _ : Just _ : Just _ : Just _ : _ : _ -> Nothing; })); default_prefix :: forall a. (Len a) => Prefix_match a; default_prefix = PrefixMatch zero_word zero_nat; tcp_flag_toString :: Tcp_flag -> [Prelude.Char]; tcp_flag_toString TCP_SYN = "TCP_SYN"; tcp_flag_toString TCP_ACK = "TCP_ACK"; tcp_flag_toString TCP_FIN = "TCP_FIN"; tcp_flag_toString TCP_RST = "TCP_RST"; tcp_flag_toString TCP_URG = "TCP_URG"; tcp_flag_toString TCP_PSH = "TCP_PSH"; ipt_tcp_syn :: Ipt_tcp_flags; ipt_tcp_syn = TCP_Flags (insert TCP_SYN (insert TCP_RST (insert TCP_ACK (insert TCP_FIN bot_set)))) (insert TCP_SYN bot_set); is_longest_prefix_routing :: forall a b. (Len a) => [Routing_rule_ext a b] -> Bool; is_longest_prefix_routing = sorted . map routing_rule_sort_key; correct_routing :: forall a. (Len a) => [Routing_rule_ext a ()] -> Bool; correct_routing r = is_longest_prefix_routing r && valid_prefixes r; terminal_chain :: forall a. [Rule a] -> Bool; terminal_chain [] = False; terminal_chain [Rule MatchAny Accept] = True; terminal_chain [Rule MatchAny Drop] = True; terminal_chain [Rule MatchAny Reject] = True; terminal_chain (Rule uu (Goto uv) : rs) = False; terminal_chain (Rule uw (Call ux) : rs) = False; terminal_chain (Rule uy Return : rs) = False; terminal_chain (Rule uz Unknown : rs) = False; terminal_chain (Rule (Match vc) Accept : rs) = terminal_chain rs; terminal_chain (Rule (Match vc) Drop : rs) = terminal_chain rs; terminal_chain (Rule (Match vc) Log : rs) = terminal_chain rs; terminal_chain (Rule (Match vc) Reject : rs) = terminal_chain rs; terminal_chain (Rule (Match vc) Empty : rs) = terminal_chain rs; terminal_chain (Rule (MatchNot vc) Accept : rs) = terminal_chain rs; terminal_chain (Rule (MatchNot vc) Drop : rs) = terminal_chain rs; terminal_chain (Rule (MatchNot vc) Log : rs) = terminal_chain rs; terminal_chain (Rule (MatchNot vc) Reject : rs) = terminal_chain rs; terminal_chain (Rule (MatchNot vc) Empty : rs) = terminal_chain rs; terminal_chain (Rule (MatchAnd vc vd) Accept : rs) = terminal_chain rs; terminal_chain (Rule (MatchAnd vc vd) Drop : rs) = terminal_chain rs; terminal_chain (Rule (MatchAnd vc vd) Log : rs) = terminal_chain rs; terminal_chain (Rule (MatchAnd vc vd) Reject : rs) = terminal_chain rs; terminal_chain (Rule (MatchAnd vc vd) Empty : rs) = terminal_chain rs; terminal_chain (Rule v Drop : va : vb) = terminal_chain (va : vb); terminal_chain (Rule v Log : rs) = terminal_chain rs; terminal_chain (Rule v Reject : va : vb) = terminal_chain (va : vb); terminal_chain (Rule v Empty : rs) = terminal_chain rs; terminal_chain (Rule vc Accept : v : vb) = terminal_chain (v : vb); simple_ruleset :: forall a. [Rule a] -> Bool; simple_ruleset rs = all (\ r -> equal_action (get_action r) Accept || equal_action (get_action r) Drop) rs; equal_prefix_match :: forall a. (Len a) => Prefix_match a -> Prefix_match a -> Bool; equal_prefix_match (PrefixMatch x1 x2) (PrefixMatch y1 y2) = equal_word x1 y1 && equal_nat x2 y2; unambiguous_routing_code :: forall a b. (Len a) => [Routing_rule_ext a b] -> Bool; unambiguous_routing_code [] = True; unambiguous_routing_code (rr : rtbl) = all (\ ra -> not (equal_prefix_match (routing_match rr) (routing_match ra)) || not (equal_linord_helper (routing_rule_sort_key rr) (routing_rule_sort_key ra))) rtbl && unambiguous_routing_code rtbl; sanity_ip_route :: forall a. (Len a) => [Routing_rule_ext a ()] -> Bool; sanity_ip_route r = correct_routing r && unambiguous_routing_code r && all ((\ y -> not (null y)) . (\ a -> output_iface (routing_action a))) r; fill_l4_protocol_raw :: forall a. (Len a) => Word (Bit0 (Bit0 (Bit0 Num1))) -> [Negation_type (Common_primitive a)] -> [Negation_type (Common_primitive a)]; fill_l4_protocol_raw protocol = negPos_map (\ a -> (case a of { Src aa -> Src aa; Dst aa -> Dst aa; IIface aa -> IIface aa; OIface aa -> OIface aa; Src_Ports (L4Ports x pts) -> (if not (equal_word x zero_word) then error "undefined" else Src_Ports (L4Ports protocol pts)); Dst_Ports (L4Ports x pts) -> (if not (equal_word x zero_word) then error "undefined" else Dst_Ports (L4Ports protocol pts)); MultiportPorts (L4Ports x pts) -> (if not (equal_word x zero_word) then error "undefined" else MultiportPorts (L4Ports protocol pts)); L4_Flags aa -> L4_Flags aa; CT_State aa -> CT_State aa; Extra aa -> Extra aa; })); fill_l4_protocol :: forall a. (Len a) => [Negation_type (Common_primitive a)] -> [Negation_type (Common_primitive a)]; fill_l4_protocol [] = []; fill_l4_protocol (Pos (Prot (Proto protocol)) : ms) = Pos (Prot (Proto protocol)) : fill_l4_protocol_raw protocol ms; fill_l4_protocol (Pos (Src_Ports uu) : uv) = error "undefined"; fill_l4_protocol (Pos (Dst_Ports uw) : ux) = error "undefined"; fill_l4_protocol (Pos (MultiportPorts uy) : uz) = error "undefined"; fill_l4_protocol (Neg (Src_Ports va) : vb) = error "undefined"; fill_l4_protocol (Neg (Dst_Ports vc) : vd) = error "undefined"; fill_l4_protocol (Neg (MultiportPorts ve) : vf) = error "undefined"; fill_l4_protocol (Pos (Src va) : ms) = Pos (Src va) : fill_l4_protocol ms; fill_l4_protocol (Pos (Dst va) : ms) = Pos (Dst va) : fill_l4_protocol ms; fill_l4_protocol (Pos (IIface va) : ms) = Pos (IIface va) : fill_l4_protocol ms; fill_l4_protocol (Pos (OIface va) : ms) = Pos (OIface va) : fill_l4_protocol ms; fill_l4_protocol (Pos (Prot ProtoAny) : ms) = Pos (Prot ProtoAny) : fill_l4_protocol ms; fill_l4_protocol (Pos (L4_Flags va) : ms) = Pos (L4_Flags va) : fill_l4_protocol ms; fill_l4_protocol (Pos (CT_State va) : ms) = Pos (CT_State va) : fill_l4_protocol ms; fill_l4_protocol (Pos (Extra va) : ms) = Pos (Extra va) : fill_l4_protocol ms; fill_l4_protocol (Neg (Src va) : ms) = Neg (Src va) : fill_l4_protocol ms; fill_l4_protocol (Neg (Dst va) : ms) = Neg (Dst va) : fill_l4_protocol ms; fill_l4_protocol (Neg (IIface va) : ms) = Neg (IIface va) : fill_l4_protocol ms; fill_l4_protocol (Neg (OIface va) : ms) = Neg (OIface va) : fill_l4_protocol ms; fill_l4_protocol (Neg (Prot va) : ms) = Neg (Prot va) : fill_l4_protocol ms; fill_l4_protocol (Neg (L4_Flags va) : ms) = Neg (L4_Flags va) : fill_l4_protocol ms; fill_l4_protocol (Neg (CT_State va) : ms) = Neg (CT_State va) : fill_l4_protocol ms; fill_l4_protocol (Neg (Extra va) : ms) = Neg (Extra va) : fill_l4_protocol ms; integer_to_16word :: Integer -> Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))); integer_to_16word i = nat_to_16word (nat_of_integer i); ctstate_toString :: Ctstate -> [Prelude.Char]; ctstate_toString CT_New = "NEW"; ctstate_toString CT_Established = "ESTABLISHED"; ctstate_toString CT_Related = "RELATED"; ctstate_toString CT_Untracked = "UNTRACKED"; ctstate_toString CT_Invalid = "INVALID"; has_disc :: forall a. (a -> Bool) -> Match_expr a -> Bool; has_disc uu MatchAny = False; has_disc disc (Match a) = disc a; has_disc disc (MatchNot m) = has_disc disc m; has_disc disc (MatchAnd m1 m2) = has_disc disc m1 || has_disc disc m2; rewrite_Goto_chain_safe :: forall a. ([Prelude.Char] -> Maybe [Rule a]) -> [Rule a] -> Maybe [Rule a]; rewrite_Goto_chain_safe uu [] = Just []; rewrite_Goto_chain_safe gamma (Rule m (Goto chain) : rs) = (case gamma chain of { Nothing -> Nothing; Just rsa -> (if not (terminal_chain rsa) then Nothing else map_option (\ a -> Rule m (Call chain) : a) (rewrite_Goto_chain_safe gamma rs)); }); rewrite_Goto_chain_safe gamma (Rule v Accept : rs) = map_option (\ a -> Rule v Accept : a) (rewrite_Goto_chain_safe gamma rs); rewrite_Goto_chain_safe gamma (Rule v Drop : rs) = map_option (\ a -> Rule v Drop : a) (rewrite_Goto_chain_safe gamma rs); rewrite_Goto_chain_safe gamma (Rule v Log : rs) = map_option (\ a -> Rule v Log : a) (rewrite_Goto_chain_safe gamma rs); rewrite_Goto_chain_safe gamma (Rule v Reject : rs) = map_option (\ a -> Rule v Reject : a) (rewrite_Goto_chain_safe gamma rs); rewrite_Goto_chain_safe gamma (Rule v (Call vb) : rs) = map_option (\ a -> Rule v (Call vb) : a) (rewrite_Goto_chain_safe gamma rs); rewrite_Goto_chain_safe gamma (Rule v Return : rs) = map_option (\ a -> Rule v Return : a) (rewrite_Goto_chain_safe gamma rs); rewrite_Goto_chain_safe gamma (Rule v Empty : rs) = map_option (\ a -> Rule v Empty : a) (rewrite_Goto_chain_safe gamma rs); rewrite_Goto_chain_safe gamma (Rule v Unknown : rs) = map_option (\ a -> Rule v Unknown : a) (rewrite_Goto_chain_safe gamma rs); rewrite_Goto_safe_internal :: forall a. [([Prelude.Char], [Rule a])] -> [([Prelude.Char], [Rule a])] -> Maybe [([Prelude.Char], [Rule a])]; rewrite_Goto_safe_internal uu [] = Just []; rewrite_Goto_safe_internal gamma ((chain_name, rs) : cs) = (case rewrite_Goto_chain_safe (map_of gamma) rs of { Nothing -> Nothing; Just rsa -> map_option (\ a -> (chain_name, rsa) : a) (rewrite_Goto_safe_internal gamma cs); }); rewrite_Goto_safe :: forall a. [([Prelude.Char], [Rule a])] -> Maybe [([Prelude.Char], [Rule a])]; rewrite_Goto_safe cs = rewrite_Goto_safe_internal cs cs; process_ret :: forall a. [Rule a] -> [Rule a]; process_ret [] = []; process_ret (Rule m Return : rs) = add_match (MatchNot m) (process_ret rs); process_ret (Rule v Accept : rs) = Rule v Accept : process_ret rs; process_ret (Rule v Drop : rs) = Rule v Drop : process_ret rs; process_ret (Rule v Log : rs) = Rule v Log : process_ret rs; process_ret (Rule v Reject : rs) = Rule v Reject : process_ret rs; process_ret (Rule v (Call vb) : rs) = Rule v (Call vb) : process_ret rs; process_ret (Rule v (Goto vb) : rs) = Rule v (Goto vb) : process_ret rs; process_ret (Rule v Empty : rs) = Rule v Empty : process_ret rs; process_ret (Rule v Unknown : rs) = Rule v Unknown : process_ret rs; dec_string_of_word0 :: forall a. (Len a) => Word a -> [Prelude.Char]; dec_string_of_word0 = string_of_word True (word_of_int (Int_of_integer (10 :: Integer))) zero_nat; port_toString :: Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))) -> [Prelude.Char]; port_toString p = dec_string_of_word0 p; wordinterval_sort :: forall a. (Len a) => Wordinterval a -> Wordinterval a; wordinterval_sort w = l2wi (mergesort_remdups (wi2l w)); build_ip_partition :: forall a. (Len a) => Parts_connection_ext () -> [Simple_rule a] -> [Wordinterval a]; build_ip_partition c rs = map (\ xs -> wordinterval_sort (wordinterval_compress (foldr wordinterval_union xs empty_WordInterval))) (groupWIs3 c rs); process_call :: forall a. ([Prelude.Char] -> Maybe [Rule a]) -> [Rule a] -> [Rule a]; process_call gamma [] = []; process_call gamma (Rule m (Call chain) : rs) = add_match m (process_ret (the (gamma chain))) ++ process_call gamma rs; process_call gamma (Rule v Accept : rs) = Rule v Accept : process_call gamma rs; process_call gamma (Rule v Drop : rs) = Rule v Drop : process_call gamma rs; process_call gamma (Rule v Log : rs) = Rule v Log : process_call gamma rs; process_call gamma (Rule v Reject : rs) = Rule v Reject : process_call gamma rs; process_call gamma (Rule v Return : rs) = Rule v Return : process_call gamma rs; process_call gamma (Rule v (Goto vb) : rs) = Rule v (Goto vb) : process_call gamma rs; process_call gamma (Rule v Empty : rs) = Rule v Empty : process_call gamma rs; process_call gamma (Rule v Unknown : rs) = Rule v Unknown : process_call gamma rs; enum_set_get_one :: forall a. (Eq a) => [a] -> Set a -> Maybe a; enum_set_get_one [] s = Nothing; enum_set_get_one (sa : ss) s = (if member sa s then Just sa else enum_set_get_one ss s); enum_set_to_list :: forall a. (Enum a, Eq a) => Set a -> [a]; enum_set_to_list s = (if is_empty s then [] else (case enum_set_get_one enum s of { Nothing -> []; Just a -> a : enum_set_to_list (remove a s); })); ipt_tcp_flags_toString :: Set Tcp_flag -> [Prelude.Char]; ipt_tcp_flags_toString flags = list_toString tcp_flag_toString (enum_set_to_list flags); iface_toString :: [Prelude.Char] -> Iface -> [Prelude.Char]; iface_toString descr iface = (if equal_iface iface ifaceAny then [] else let { (Iface a) = iface; } in descr ++ a); ports_toString :: [Prelude.Char] -> (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> [Prelude.Char]; ports_toString descr (s, e) = (if equal_word s zero_word && equal_word e max_word then [] else descr ++ (if equal_word s e then port_toString s else port_toString s ++ ":" ++ port_toString e)); valid_prefix_fw :: forall a. (Len a) => (Word a, Nat) -> Bool; valid_prefix_fw m = valid_prefix (uncurry PrefixMatch m); simple_fw_valid :: forall a. (Len a) => [Simple_rule a] -> Bool; simple_fw_valid = all ((\ m -> let { c = (\ (s, e) -> not (equal_word s zero_word) || not (equal_word e max_word)); } in (if c (sports m) || c (dports m) then equal_protocol (proto m) (Proto tcp) || (equal_protocol (proto m) (Proto udp) || equal_protocol (proto m) (Proto sctp)) else True) && valid_prefix_fw (src m) && valid_prefix_fw (dst m)) . match_sel); simpl_ports_conjunct :: (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))); simpl_ports_conjunct (p1s, p1e) (p2s, p2e) = (max p1s p2s, min p1e p2e); simple_match_and :: forall a. (Len a) => Simple_match_ext a () -> Simple_match_ext a () -> Maybe (Simple_match_ext a ()); simple_match_and (Simple_match_ext iif1 oif1 sip1 dip1 p1 sps1 dps1 ()) (Simple_match_ext iif2 oif2 sip2 dip2 p2 sps2 dps2 ()) = (case (if wordinterval_empty (wordinterval_intersection (ipcidr_tuple_to_wordinterval sip1) (ipcidr_tuple_to_wordinterval sip2)) then Nothing else (if wordinterval_subset (ipcidr_tuple_to_wordinterval sip1) (ipcidr_tuple_to_wordinterval sip2) then Just sip1 else Just sip2)) of { Nothing -> Nothing; Just sip -> (case (if wordinterval_empty (wordinterval_intersection (ipcidr_tuple_to_wordinterval dip1) (ipcidr_tuple_to_wordinterval dip2)) then Nothing else (if wordinterval_subset (ipcidr_tuple_to_wordinterval dip1) (ipcidr_tuple_to_wordinterval dip2) then Just dip1 else Just dip2)) of { Nothing -> Nothing; Just dip -> (case iface_conjunct iif1 iif2 of { Nothing -> Nothing; Just iif -> (case iface_conjunct oif1 oif2 of { Nothing -> Nothing; Just oif -> (case simple_proto_conjunct p1 p2 of { Nothing -> Nothing; Just p -> Just (Simple_match_ext iif oif sip dip p (simpl_ports_conjunct sps1 sps2) (simpl_ports_conjunct dps1 dps2) ()); }); }); }); }); }); compress_parsed_extra :: forall a. (Len a) => [Negation_type (Common_primitive a)] -> [Negation_type (Common_primitive a)]; compress_parsed_extra [] = []; compress_parsed_extra (a1 : a2 : asa) = (if is_pos_Extra a1 && is_pos_Extra a2 then compress_parsed_extra (Pos (Extra (get_pos_Extra a1 ++ " " ++ get_pos_Extra a2)) : asa) else a1 : compress_parsed_extra (a2 : asa)); compress_parsed_extra [a] = a : compress_parsed_extra []; ctstate_set_toString :: Set Ctstate -> [Prelude.Char]; ctstate_set_toString s = list_separated_toString "," ctstate_toString (enum_set_to_list s); normalized_dst_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> Bool; normalized_dst_ports MatchAny = True; normalized_dst_ports (Match (Dst_Ports (L4Ports uu []))) = True; normalized_dst_ports (Match (Dst_Ports (L4Ports uv [uw]))) = True; normalized_dst_ports (Match (Dst_Ports (L4Ports v (vb : va : vd)))) = False; normalized_dst_ports (Match (Src v)) = True; normalized_dst_ports (Match (Dst v)) = True; normalized_dst_ports (Match (IIface v)) = True; normalized_dst_ports (Match (OIface v)) = True; normalized_dst_ports (Match (Prot v)) = True; normalized_dst_ports (Match (Src_Ports v)) = True; normalized_dst_ports (Match (MultiportPorts v)) = True; normalized_dst_ports (Match (L4_Flags v)) = True; normalized_dst_ports (Match (CT_State v)) = True; normalized_dst_ports (Match (Extra v)) = True; normalized_dst_ports (MatchNot (Match (Dst_Ports uz))) = False; normalized_dst_ports (MatchNot (Match (Src v))) = True; normalized_dst_ports (MatchNot (Match (Dst v))) = True; normalized_dst_ports (MatchNot (Match (IIface v))) = True; normalized_dst_ports (MatchNot (Match (OIface v))) = True; normalized_dst_ports (MatchNot (Match (Prot v))) = True; normalized_dst_ports (MatchNot (Match (Src_Ports v))) = True; normalized_dst_ports (MatchNot (Match (MultiportPorts v))) = True; normalized_dst_ports (MatchNot (Match (L4_Flags v))) = True; normalized_dst_ports (MatchNot (Match (CT_State v))) = True; normalized_dst_ports (MatchNot (Match (Extra v))) = True; normalized_dst_ports (MatchAnd m1 m2) = normalized_dst_ports m1 && normalized_dst_ports m2; normalized_dst_ports (MatchNot (MatchAnd vb vc)) = False; normalized_dst_ports (MatchNot (MatchNot vd)) = False; normalized_dst_ports (MatchNot MatchAny) = True; normalized_src_ports :: forall a. (Len a) => Match_expr (Common_primitive a) -> Bool; normalized_src_ports MatchAny = True; normalized_src_ports (Match (Src_Ports (L4Ports uu []))) = True; normalized_src_ports (Match (Src_Ports (L4Ports uv [uw]))) = True; normalized_src_ports (Match (Src_Ports (L4Ports v (vb : va : vd)))) = False; normalized_src_ports (Match (Src v)) = True; normalized_src_ports (Match (Dst v)) = True; normalized_src_ports (Match (IIface v)) = True; normalized_src_ports (Match (OIface v)) = True; normalized_src_ports (Match (Prot v)) = True; normalized_src_ports (Match (Dst_Ports v)) = True; normalized_src_ports (Match (MultiportPorts v)) = True; normalized_src_ports (Match (L4_Flags v)) = True; normalized_src_ports (Match (CT_State v)) = True; normalized_src_ports (Match (Extra v)) = True; normalized_src_ports (MatchNot (Match (Src_Ports uz))) = False; normalized_src_ports (MatchNot (Match (Src v))) = True; normalized_src_ports (MatchNot (Match (Dst v))) = True; normalized_src_ports (MatchNot (Match (IIface v))) = True; normalized_src_ports (MatchNot (Match (OIface v))) = True; normalized_src_ports (MatchNot (Match (Prot v))) = True; normalized_src_ports (MatchNot (Match (Dst_Ports v))) = True; normalized_src_ports (MatchNot (Match (MultiportPorts v))) = True; normalized_src_ports (MatchNot (Match (L4_Flags v))) = True; normalized_src_ports (MatchNot (Match (CT_State v))) = True; normalized_src_ports (MatchNot (Match (Extra v))) = True; normalized_src_ports (MatchAnd m1 m2) = normalized_src_ports m1 && normalized_src_ports m2; normalized_src_ports (MatchNot (MatchAnd vb vc)) = False; normalized_src_ports (MatchNot (MatchNot vd)) = False; normalized_src_ports (MatchNot MatchAny) = True; ipt_tcp_flags_equal :: Ipt_tcp_flags -> Ipt_tcp_flags -> Bool; ipt_tcp_flags_equal (TCP_Flags fmask1 c1) (TCP_Flags fmask2 c2) = (if less_eq_set c1 fmask1 && less_eq_set c2 fmask2 then equal_set c1 c2 && equal_set fmask1 fmask2 else not (less_eq_set c1 fmask1) && not (less_eq_set c2 fmask2)); primitive_protocol_toString :: Word (Bit0 (Bit0 (Bit0 Num1))) -> [Prelude.Char]; primitive_protocol_toString protid = (if equal_word protid tcp then "tcp" else (if equal_word protid udp then "udp" else (if equal_word protid icmp then "icmp" else (if equal_word protid sctp then "sctp" else (if equal_word protid igmp then "igmp" else (if equal_word protid gre then "gre" else (if equal_word protid esp then "esp" else (if equal_word protid ah then "ah" else (if equal_word protid iPv6ICMP then "ipv6-icmp" else "protocolid:" ++ dec_string_of_word0 protid))))))))); protocol_toString :: Protocol -> [Prelude.Char]; protocol_toString ProtoAny = "all"; protocol_toString (Proto protid) = primitive_protocol_toString protid; common_primitive_toString :: forall a. (Len a) => (Word a -> [Prelude.Char]) -> Common_primitive a -> [Prelude.Char]; common_primitive_toString ipToStr (Src (IpAddr ip)) = "-s " ++ ipToStr ip; common_primitive_toString ipToStr (Dst (IpAddr ip)) = "-d " ++ ipToStr ip; common_primitive_toString ipToStr (Src (IpAddrNetmask ip n)) = "-s " ++ ipToStr ip ++ "/" ++ string_of_nat n; common_primitive_toString ipToStr (Dst (IpAddrNetmask ip n)) = "-d " ++ ipToStr ip ++ "/" ++ string_of_nat n; common_primitive_toString ipToStr (Src (IpAddrRange ip1 ip2)) = "-m iprange --src-range " ++ ipToStr ip1 ++ "-" ++ ipToStr ip2; common_primitive_toString ipToStr (Dst (IpAddrRange ip1 ip2)) = "-m iprange --dst-range " ++ ipToStr ip1 ++ "-" ++ ipToStr ip2; common_primitive_toString uu (IIface ifce) = iface_toString "-i " ifce; common_primitive_toString uv (OIface ifce) = iface_toString "-o " ifce; common_primitive_toString uw (Prot prot) = "-p " ++ protocol_toString prot; common_primitive_toString ux (Src_Ports (L4Ports prot pts)) = "-m " ++ primitive_protocol_toString prot ++ " --spts " ++ list_toString (ports_toString []) pts; common_primitive_toString uy (Dst_Ports (L4Ports prot pts)) = "-m " ++ primitive_protocol_toString prot ++ " --dpts " ++ list_toString (ports_toString []) pts; common_primitive_toString uz (MultiportPorts (L4Ports prot pts)) = "-p " ++ primitive_protocol_toString prot ++ " -m multiport --ports " ++ list_toString (ports_toString []) pts; common_primitive_toString va (CT_State s) = "-m state --state " ++ ctstate_set_toString s; common_primitive_toString vb (L4_Flags (TCP_Flags c m)) = "--tcp-flags " ++ ipt_tcp_flags_toString c ++ " " ++ ipt_tcp_flags_toString m; common_primitive_toString vc (Extra e) = "~~" ++ e ++ "~~"; ipaddr_generic_toString :: forall a. (Len a) => Word a -> [Prelude.Char]; ipaddr_generic_toString ip = "[IP address (" ++ string_of_nat ((len_of :: Itself a -> Nat) Type) ++ " bit): " ++ dec_string_of_word0 ip ++ "]"; abstract_primitive :: forall a. (Len a) => (Negation_type (Common_primitive a) -> Bool) -> Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); abstract_primitive uu MatchAny = MatchAny; abstract_primitive disc (Match a) = (if disc (Pos a) then Match (Extra (common_primitive_toString ipaddr_generic_toString a)) else Match a); abstract_primitive disc (MatchNot (Match a)) = (if disc (Neg a) then Match (Extra ("! " ++ common_primitive_toString ipaddr_generic_toString a)) else MatchNot (Match a)); abstract_primitive disc (MatchNot (MatchNot v)) = MatchNot (abstract_primitive disc (MatchNot v)); abstract_primitive disc (MatchNot (MatchAnd v va)) = MatchNot (abstract_primitive disc (MatchAnd v va)); abstract_primitive disc (MatchNot MatchAny) = MatchNot (abstract_primitive disc MatchAny); abstract_primitive disc (MatchAnd m1 m2) = MatchAnd (abstract_primitive disc m1) (abstract_primitive disc m2); next_hop :: forall a b. Routing_action_ext a b -> Maybe (Word a); next_hop (Routing_action_ext output_iface next_hop more) = next_hop; has_disc_negated :: forall a. (a -> Bool) -> Bool -> Match_expr a -> Bool; has_disc_negated uu uv MatchAny = False; has_disc_negated disc neg (Match a) = (if disc a then neg else False); has_disc_negated disc neg (MatchNot m) = has_disc_negated disc (not neg) m; has_disc_negated disc neg (MatchAnd m1 m2) = has_disc_negated disc neg m1 || has_disc_negated disc neg m2; normalized_ifaces :: forall a. (Len a) => Match_expr (Common_primitive a) -> Bool; normalized_ifaces m = not (has_disc_negated (\ a -> is_Iiface a || is_Oiface a) False m); ipv4_cidr_toString :: (Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))), Nat) -> [Prelude.Char]; ipv4_cidr_toString ip_n = let { (base, n) = ip_n; } in ipv4addr_toString base ++ "/" ++ string_of_nat n; ipv6_cidr_toString :: (Word (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))), Nat) -> [Prelude.Char]; ipv6_cidr_toString ip_n = let { (base, n) = ip_n; } in ipv6addr_toString base ++ "/" ++ string_of_nat n; prefix_match_32_toString :: Prefix_match (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> [Prelude.Char]; prefix_match_32_toString pfx = let { (PrefixMatch p l) = pfx; } in ipv4addr_toString p ++ (if not (equal_nat l (nat_of_integer (32 :: Integer))) then "/" ++ string_of_nat l else []); routing_rule_32_toString :: Routing_rule_ext (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) () -> [Prelude.Char]; routing_rule_32_toString rr = prefix_match_32_toString (routing_match rr) ++ (case next_hop (routing_action rr) of { Nothing -> []; Just nh -> " via " ++ ipv4addr_toString nh; }) ++ " dev " ++ output_iface (routing_action rr) ++ " metric " ++ string_of_nat (metric rr); mk_parts_connection_TCP :: Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))) -> Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))) -> Parts_connection_ext (); mk_parts_connection_TCP sport dport = Parts_connection_ext "1" "1" tcp sport dport (); sports_update :: forall a b. (Len a) => ((Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))) -> Simple_match_ext a b -> Simple_match_ext a b; sports_update sportsa (Simple_match_ext iiface oiface src dst proto sports dports more) = Simple_match_ext iiface oiface src dst proto (sportsa sports) dports more; oiface_update :: forall a b. (Len a) => (Iface -> Iface) -> Simple_match_ext a b -> Simple_match_ext a b; oiface_update oifacea (Simple_match_ext iiface oiface src dst proto sports dports more) = Simple_match_ext iiface (oifacea oiface) src dst proto sports dports more; iiface_update :: forall a b. (Len a) => (Iface -> Iface) -> Simple_match_ext a b -> Simple_match_ext a b; iiface_update iifacea (Simple_match_ext iiface oiface src dst proto sports dports more) = Simple_match_ext (iifacea iiface) oiface src dst proto sports dports more; dports_update :: forall a b. (Len a) => ((Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> (Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))), Word (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))) -> Simple_match_ext a b -> Simple_match_ext a b; dports_update dportsa (Simple_match_ext iiface oiface src dst proto sports dports more) = Simple_match_ext iiface oiface src dst proto sports (dportsa dports) more; proto_update :: forall a b. (Len a) => (Protocol -> Protocol) -> Simple_match_ext a b -> Simple_match_ext a b; proto_update protoa (Simple_match_ext iiface oiface src dst proto sports dports more) = Simple_match_ext iiface oiface src dst (protoa proto) sports dports more; src_update :: forall a b. (Len a) => ((Word a, Nat) -> (Word a, Nat)) -> Simple_match_ext a b -> Simple_match_ext a b; src_update srca (Simple_match_ext iiface oiface src dst proto sports dports more) = Simple_match_ext iiface oiface (srca src) dst proto sports dports more; dst_update :: forall a b. (Len a) => ((Word a, Nat) -> (Word a, Nat)) -> Simple_match_ext a b -> Simple_match_ext a b; dst_update dsta (Simple_match_ext iiface oiface src dst proto sports dports more) = Simple_match_ext iiface oiface src (dsta dst) proto sports dports more; common_primitive_match_to_simple_match :: forall a. (Len a) => Match_expr (Common_primitive a) -> Maybe (Simple_match_ext a ()); common_primitive_match_to_simple_match MatchAny = Just simple_match_any; common_primitive_match_to_simple_match (MatchNot MatchAny) = Nothing; common_primitive_match_to_simple_match (Match (IIface iif)) = Just (iiface_update (\ _ -> iif) simple_match_any); common_primitive_match_to_simple_match (Match (OIface oif)) = Just (oiface_update (\ _ -> oif) simple_match_any); common_primitive_match_to_simple_match (Match (Src (IpAddrNetmask pre len))) = Just (src_update (\ _ -> (pre, len)) simple_match_any); common_primitive_match_to_simple_match (Match (Dst (IpAddrNetmask pre len))) = Just (dst_update (\ _ -> (pre, len)) simple_match_any); common_primitive_match_to_simple_match (Match (Prot p)) = Just (proto_update (\ _ -> p) simple_match_any); common_primitive_match_to_simple_match (Match (Src_Ports (L4Ports p []))) = Nothing; common_primitive_match_to_simple_match (Match (Src_Ports (L4Ports p [(s, e)]))) = Just (sports_update (\ _ -> (s, e)) (proto_update (\ _ -> Proto p) simple_match_any)); common_primitive_match_to_simple_match (Match (Dst_Ports (L4Ports p []))) = Nothing; common_primitive_match_to_simple_match (Match (Dst_Ports (L4Ports p [(s, e)]))) = Just (dports_update (\ _ -> (s, e)) (proto_update (\ _ -> Proto p) simple_match_any)); common_primitive_match_to_simple_match (MatchNot (Match (Prot ProtoAny))) = Nothing; common_primitive_match_to_simple_match (MatchAnd m1 m2) = (case (common_primitive_match_to_simple_match m1, common_primitive_match_to_simple_match m2) of { (Nothing, _) -> Nothing; (Just _, Nothing) -> Nothing; (Just a, Just b) -> simple_match_and a b; }); common_primitive_match_to_simple_match (Match (Src (IpAddr uu))) = error "undefined"; common_primitive_match_to_simple_match (Match (Src (IpAddrRange uv uw))) = error "undefined"; common_primitive_match_to_simple_match (Match (Dst (IpAddr ux))) = error "undefined"; common_primitive_match_to_simple_match (Match (Dst (IpAddrRange uy uz))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (Prot (Proto v)))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (IIface vb))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (OIface vc))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (Src vd))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (Dst ve))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (MatchAnd vf vg)) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (MatchNot vh)) = error "undefined"; common_primitive_match_to_simple_match (Match (Src_Ports (L4Ports v (vb : va : vd)))) = error "undefined"; common_primitive_match_to_simple_match (Match (Dst_Ports (L4Ports v (vb : va : vd)))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (Src_Ports vk))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (Dst_Ports vl))) = error "undefined"; common_primitive_match_to_simple_match (Match (CT_State vm)) = error "undefined"; common_primitive_match_to_simple_match (Match (L4_Flags vn)) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (L4_Flags vo))) = error "undefined"; common_primitive_match_to_simple_match (Match (Extra vp)) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (Extra vq))) = error "undefined"; common_primitive_match_to_simple_match (MatchNot (Match (CT_State vr))) = error "undefined"; is_L4_Flags :: forall a. (Len a) => Common_primitive a -> Bool; is_L4_Flags (Src x1) = False; is_L4_Flags (Dst x2) = False; is_L4_Flags (IIface x3) = False; is_L4_Flags (OIface x4) = False; is_L4_Flags (Prot x5) = False; is_L4_Flags (Src_Ports x6) = False; is_L4_Flags (Dst_Ports x7) = False; is_L4_Flags (MultiportPorts x8) = False; is_L4_Flags (L4_Flags x9) = True; is_L4_Flags (CT_State x10) = False; is_L4_Flags (Extra x11) = False; is_CT_State :: forall a. (Len a) => Common_primitive a -> Bool; is_CT_State (Src x1) = False; is_CT_State (Dst x2) = False; is_CT_State (IIface x3) = False; is_CT_State (OIface x4) = False; is_CT_State (Prot x5) = False; is_CT_State (Src_Ports x6) = False; is_CT_State (Dst_Ports x7) = False; is_CT_State (MultiportPorts x8) = False; is_CT_State (L4_Flags x9) = False; is_CT_State (CT_State x10) = True; is_CT_State (Extra x11) = False; is_Extra :: forall a. (Len a) => Common_primitive a -> Bool; is_Extra (Src x1) = False; is_Extra (Dst x2) = False; is_Extra (IIface x3) = False; is_Extra (OIface x4) = False; is_Extra (Prot x5) = False; is_Extra (Src_Ports x6) = False; is_Extra (Dst_Ports x7) = False; is_Extra (MultiportPorts x8) = False; is_Extra (L4_Flags x9) = False; is_Extra (CT_State x10) = False; is_Extra (Extra x11) = True; normalized_protocols :: forall a. (Len a) => Match_expr (Common_primitive a) -> Bool; normalized_protocols m = not (has_disc_negated is_Prot False m); normalized_src_ips :: forall a. (Len a) => Match_expr (Common_primitive a) -> Bool; normalized_src_ips MatchAny = True; normalized_src_ips (Match (Src (IpAddrRange uu uv))) = False; normalized_src_ips (Match (Src (IpAddr uw))) = False; normalized_src_ips (Match (Src (IpAddrNetmask ux uy))) = True; normalized_src_ips (Match (Dst v)) = True; normalized_src_ips (Match (IIface v)) = True; normalized_src_ips (Match (OIface v)) = True; normalized_src_ips (Match (Prot v)) = True; normalized_src_ips (Match (Src_Ports v)) = True; normalized_src_ips (Match (Dst_Ports v)) = True; normalized_src_ips (Match (MultiportPorts v)) = True; normalized_src_ips (Match (L4_Flags v)) = True; normalized_src_ips (Match (CT_State v)) = True; normalized_src_ips (Match (Extra v)) = True; normalized_src_ips (MatchNot (Match (Src va))) = False; normalized_src_ips (MatchNot (Match (Dst v))) = True; normalized_src_ips (MatchNot (Match (IIface v))) = True; normalized_src_ips (MatchNot (Match (OIface v))) = True; normalized_src_ips (MatchNot (Match (Prot v))) = True; normalized_src_ips (MatchNot (Match (Src_Ports v))) = True; normalized_src_ips (MatchNot (Match (Dst_Ports v))) = True; normalized_src_ips (MatchNot (Match (MultiportPorts v))) = True; normalized_src_ips (MatchNot (Match (L4_Flags v))) = True; normalized_src_ips (MatchNot (Match (CT_State v))) = True; normalized_src_ips (MatchNot (Match (Extra v))) = True; normalized_src_ips (MatchAnd m1 m2) = normalized_src_ips m1 && normalized_src_ips m2; normalized_src_ips (MatchNot (MatchAnd vc vd)) = False; normalized_src_ips (MatchNot (MatchNot ve)) = False; normalized_src_ips (MatchNot MatchAny) = True; normalized_dst_ips :: forall a. (Len a) => Match_expr (Common_primitive a) -> Bool; normalized_dst_ips MatchAny = True; normalized_dst_ips (Match (Dst (IpAddrRange uu uv))) = False; normalized_dst_ips (Match (Dst (IpAddr uw))) = False; normalized_dst_ips (Match (Dst (IpAddrNetmask ux uy))) = True; normalized_dst_ips (Match (Src v)) = True; normalized_dst_ips (Match (IIface v)) = True; normalized_dst_ips (Match (OIface v)) = True; normalized_dst_ips (Match (Prot v)) = True; normalized_dst_ips (Match (Src_Ports v)) = True; normalized_dst_ips (Match (Dst_Ports v)) = True; normalized_dst_ips (Match (MultiportPorts v)) = True; normalized_dst_ips (Match (L4_Flags v)) = True; normalized_dst_ips (Match (CT_State v)) = True; normalized_dst_ips (Match (Extra v)) = True; normalized_dst_ips (MatchNot (Match (Dst va))) = False; normalized_dst_ips (MatchNot (Match (Src v))) = True; normalized_dst_ips (MatchNot (Match (IIface v))) = True; normalized_dst_ips (MatchNot (Match (OIface v))) = True; normalized_dst_ips (MatchNot (Match (Prot v))) = True; normalized_dst_ips (MatchNot (Match (Src_Ports v))) = True; normalized_dst_ips (MatchNot (Match (Dst_Ports v))) = True; normalized_dst_ips (MatchNot (Match (MultiportPorts v))) = True; normalized_dst_ips (MatchNot (Match (L4_Flags v))) = True; normalized_dst_ips (MatchNot (Match (CT_State v))) = True; normalized_dst_ips (MatchNot (Match (Extra v))) = True; normalized_dst_ips (MatchAnd m1 m2) = normalized_dst_ips m1 && normalized_dst_ips m2; normalized_dst_ips (MatchNot (MatchAnd vc vd)) = False; normalized_dst_ips (MatchNot (MatchNot ve)) = False; normalized_dst_ips (MatchNot MatchAny) = True; check_simple_fw_preconditions :: forall a. (Len a) => [Rule (Common_primitive a)] -> Bool; check_simple_fw_preconditions rs = all (\ (Rule m a) -> normalized_src_ports m && normalized_dst_ports m && normalized_src_ips m && normalized_dst_ips m && normalized_ifaces m && normalized_protocols m && not (has_disc is_L4_Flags m) && not (has_disc is_CT_State m) && not (has_disc is_MultiportPorts m) && not (has_disc is_Extra m) && (equal_action a Accept || equal_action a Drop)) rs; action_to_simple_action :: Action -> Simple_action; action_to_simple_action Accept = Accepta; action_to_simple_action Drop = Dropa; action_to_simple_action Log = error "undefined"; action_to_simple_action Reject = error "undefined"; action_to_simple_action (Call v) = error "undefined"; action_to_simple_action Return = error "undefined"; action_to_simple_action (Goto v) = error "undefined"; action_to_simple_action Empty = error "undefined"; action_to_simple_action Unknown = error "undefined"; to_simple_firewall :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Simple_rule a]; to_simple_firewall rs = (if check_simple_fw_preconditions rs then map_filter (\ (Rule m a) -> (case common_primitive_match_to_simple_match m of { Nothing -> Nothing; Just sm -> Just (SimpleRule sm (action_to_simple_action a)); })) rs else error "undefined"); ipt_tcp_flags_NoMatch :: Ipt_tcp_flags; ipt_tcp_flags_NoMatch = TCP_Flags bot_set (insert TCP_SYN bot_set); prefix_match_128_toString :: Prefix_match (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))) -> [Prelude.Char]; prefix_match_128_toString pfx = let { (PrefixMatch p l) = pfx; } in ipv6addr_toString p ++ (if not (equal_nat l (nat_of_integer (128 :: Integer))) then "/" ++ string_of_nat l else []); routing_rule_128_toString :: Routing_rule_ext (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))) () -> [Prelude.Char]; routing_rule_128_toString rr = prefix_match_128_toString (routing_match rr) ++ (case next_hop (routing_action rr) of { Nothing -> []; Just nh -> " via " ++ ipv6addr_toString nh; }) ++ " dev " ++ output_iface (routing_action rr) ++ " metric " ++ string_of_nat (metric rr); unfold_optimize_ruleset_CHAIN :: forall a. (Eq a) => (Match_expr a -> Match_expr a) -> [Prelude.Char] -> Action -> ([Prelude.Char] -> Maybe [Rule a]) -> Maybe [Rule a]; unfold_optimize_ruleset_CHAIN optimize chain_name default_action rs = let { rsa = repeat_stabilize (nat_of_integer (1000 :: Integer)) (optimize_matches opt_MatchAny_match_expr) (optimize_matches optimize (rw_Reject (rm_LogEmpty (repeat_stabilize (nat_of_integer (10000 :: Integer)) (process_call rs) [Rule MatchAny (Call chain_name), Rule MatchAny default_action])))); } in (if simple_ruleset rsa then Just rsa else Nothing); unfold_ruleset_CHAIN_safe :: forall a. (Len a) => [Prelude.Char] -> Action -> ([Prelude.Char] -> Maybe [Rule (Common_primitive a)]) -> Maybe [Rule (Common_primitive a)]; unfold_ruleset_CHAIN_safe = unfold_optimize_ruleset_CHAIN optimize_primitive_univ; metric_update :: forall a b. (Len a) => (Nat -> Nat) -> Routing_rule_ext a b -> Routing_rule_ext a b; metric_update metrica (Routing_rule_ext routing_match metric routing_action more) = Routing_rule_ext routing_match (metrica metric) routing_action more; access_matrix_pretty_ipv4_code :: Parts_connection_ext () -> [Simple_rule (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))] -> ([([Prelude.Char], [Prelude.Char])], [([Prelude.Char], [Prelude.Char])]); access_matrix_pretty_ipv4_code c rs = (if not (all (\ m -> equal_iface (iiface (match_sel m)) ifaceAny && equal_iface (oiface (match_sel m)) ifaceAny) rs) then error "undefined" else let { w = build_ip_partition c rs; r = map getOneIp w; _ = all_pairs r; } in (zip (map ipv4addr_toString r) (map ipv4addr_wordinterval_toString w), map_filter (\ x -> (if let { (s, d) = x; } in equal_state (runFw s d c rs) (Decision FinalAllow) then Just (let { (xa, y) = x; } in (ipv4addr_toString xa, ipv4addr_toString y)) else Nothing)) (all_pairs r))); access_matrix_pretty_ipv4 :: Parts_connection_ext () -> [Simple_rule (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))] -> ([([Prelude.Char], [Prelude.Char])], [([Prelude.Char], [Prelude.Char])]); access_matrix_pretty_ipv4 = access_matrix_pretty_ipv4_code; access_matrix_pretty_ipv6_code :: Parts_connection_ext () -> [Simple_rule (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))))] -> ([([Prelude.Char], [Prelude.Char])], [([Prelude.Char], [Prelude.Char])]); access_matrix_pretty_ipv6_code c rs = (if not (all (\ m -> equal_iface (iiface (match_sel m)) ifaceAny && equal_iface (oiface (match_sel m)) ifaceAny) rs) then error "undefined" else let { w = build_ip_partition c rs; r = map getOneIp w; _ = all_pairs r; } in (zip (map ipv6addr_toString r) (map ipv6addr_wordinterval_toString w), map_filter (\ x -> (if let { (s, d) = x; } in equal_state (runFw s d c rs) (Decision FinalAllow) then Just (let { (xa, y) = x; } in (ipv6addr_toString xa, ipv6addr_toString y)) else Nothing)) (all_pairs r))); access_matrix_pretty_ipv6 :: Parts_connection_ext () -> [Simple_rule (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))))] -> ([([Prelude.Char], [Prelude.Char])], [([Prelude.Char], [Prelude.Char])]); access_matrix_pretty_ipv6 = access_matrix_pretty_ipv6_code; simple_action_toString :: Simple_action -> [Prelude.Char]; simple_action_toString Accepta = "ACCEPT"; simple_action_toString Dropa = "DROP"; action_toString :: Action -> [Prelude.Char]; action_toString Accept = "-j ACCEPT"; action_toString Drop = "-j DROP"; action_toString Reject = "-j REJECT"; action_toString (Call target) = "-j " ++ target ++ " (call)"; action_toString (Goto target) = "-g " ++ target; action_toString Empty = []; action_toString Log = "-j LOG"; action_toString Return = "-j RETURN"; action_toString Unknown = "!!!!!!!!!!! UNKNOWN !!!!!!!!!!!"; match_tcp_flags_conjunct :: Ipt_tcp_flags -> Ipt_tcp_flags -> Ipt_tcp_flags; match_tcp_flags_conjunct (TCP_Flags fmask1 c1) (TCP_Flags fmask2 c2) = (if less_eq_set c1 fmask1 && less_eq_set c2 fmask2 && equal_set (inf_set (inf_set fmask1 fmask2) c1) (inf_set (inf_set fmask1 fmask2) c2) then TCP_Flags (sup_set fmask1 fmask2) (sup_set c1 c2) else ipt_tcp_flags_NoMatch); match_tcp_flags_conjunct_option :: Ipt_tcp_flags -> Ipt_tcp_flags -> Maybe Ipt_tcp_flags; match_tcp_flags_conjunct_option f1 f2 = let { (TCP_Flags fmask c) = match_tcp_flags_conjunct f1 f2; } in (if less_eq_set c fmask then Just (TCP_Flags fmask c) else Nothing); ipt_tcp_flags_assume_flag :: forall a. (Len a) => Ipt_tcp_flags -> Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); ipt_tcp_flags_assume_flag flg (Match (L4_Flags x)) = (if ipt_tcp_flags_equal x flg then MatchAny else (case match_tcp_flags_conjunct_option x flg of { Nothing -> MatchNot MatchAny; Just f3 -> Match (L4_Flags f3); })); ipt_tcp_flags_assume_flag flg (Match (Src v)) = Match (Src v); ipt_tcp_flags_assume_flag flg (Match (Dst v)) = Match (Dst v); ipt_tcp_flags_assume_flag flg (Match (IIface v)) = Match (IIface v); ipt_tcp_flags_assume_flag flg (Match (OIface v)) = Match (OIface v); ipt_tcp_flags_assume_flag flg (Match (Prot v)) = Match (Prot v); ipt_tcp_flags_assume_flag flg (Match (Src_Ports v)) = Match (Src_Ports v); ipt_tcp_flags_assume_flag flg (Match (Dst_Ports v)) = Match (Dst_Ports v); ipt_tcp_flags_assume_flag flg (Match (MultiportPorts v)) = Match (MultiportPorts v); ipt_tcp_flags_assume_flag flg (Match (CT_State v)) = Match (CT_State v); ipt_tcp_flags_assume_flag flg (Match (Extra v)) = Match (Extra v); ipt_tcp_flags_assume_flag flg (MatchNot m) = MatchNot (ipt_tcp_flags_assume_flag flg m); ipt_tcp_flags_assume_flag uu MatchAny = MatchAny; ipt_tcp_flags_assume_flag flg (MatchAnd m1 m2) = MatchAnd (ipt_tcp_flags_assume_flag flg m1) (ipt_tcp_flags_assume_flag flg m2); ipt_tcp_flags_assume_syn :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Rule (Common_primitive a)]; ipt_tcp_flags_assume_syn = optimize_matches (ipt_tcp_flags_assume_flag ipt_tcp_syn); ctstate_assume_state :: forall a. (Len a) => Ctstate -> Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); ctstate_assume_state s (Match (CT_State x)) = (if member s x then MatchAny else MatchNot MatchAny); ctstate_assume_state s (Match (Src v)) = Match (Src v); ctstate_assume_state s (Match (Dst v)) = Match (Dst v); ctstate_assume_state s (Match (IIface v)) = Match (IIface v); ctstate_assume_state s (Match (OIface v)) = Match (OIface v); ctstate_assume_state s (Match (Prot v)) = Match (Prot v); ctstate_assume_state s (Match (Src_Ports v)) = Match (Src_Ports v); ctstate_assume_state s (Match (Dst_Ports v)) = Match (Dst_Ports v); ctstate_assume_state s (Match (MultiportPorts v)) = Match (MultiportPorts v); ctstate_assume_state s (Match (L4_Flags v)) = Match (L4_Flags v); ctstate_assume_state s (Match (Extra v)) = Match (Extra v); ctstate_assume_state s (MatchNot m) = MatchNot (ctstate_assume_state s m); ctstate_assume_state uu MatchAny = MatchAny; ctstate_assume_state s (MatchAnd m1 m2) = MatchAnd (ctstate_assume_state s m1) (ctstate_assume_state s m2); ctstate_assume_new :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Rule (Common_primitive a)]; ctstate_assume_new = optimize_matches (ctstate_assume_state CT_New); packet_assume_new :: forall a. (Len a) => [Rule (Common_primitive a)] -> [Rule (Common_primitive a)]; packet_assume_new = ctstate_assume_new . ipt_tcp_flags_assume_syn; routing_action_update :: forall a b. (Len a) => (Routing_action_ext a () -> Routing_action_ext a ()) -> Routing_rule_ext a b -> Routing_rule_ext a b; routing_action_update routing_actiona (Routing_rule_ext routing_match metric routing_action more) = Routing_rule_ext routing_match metric (routing_actiona routing_action) more; output_iface_update :: forall a b. ([Prelude.Char] -> [Prelude.Char]) -> Routing_action_ext a b -> Routing_action_ext a b; output_iface_update output_ifacea (Routing_action_ext output_iface next_hop more) = Routing_action_ext (output_ifacea output_iface) next_hop more; routing_action_oiface_update :: forall a. (Len a) => [Prelude.Char] -> Routing_rule_ext a () -> Routing_rule_ext a (); routing_action_oiface_update h pk = routing_action_update (output_iface_update (\ _ -> h)) pk; simple_rule_ipv4_toString :: Simple_rule (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> [Prelude.Char]; simple_rule_ipv4_toString (SimpleRule (Simple_match_ext iif oif sip dip p sps dps ()) a) = simple_action_toString a ++ " " ++ protocol_toString p ++ " -- " ++ ipv4_cidr_toString sip ++ " " ++ ipv4_cidr_toString dip ++ " " ++ iface_toString "in: " iif ++ " " ++ iface_toString "out: " oif ++ " " ++ ports_toString "sports: " sps ++ " " ++ ports_toString "dports: " dps; simple_rule_ipv6_toString :: Simple_rule (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))) -> [Prelude.Char]; simple_rule_ipv6_toString (SimpleRule (Simple_match_ext iif oif sip dip p sps dps ()) a) = simple_action_toString a ++ " " ++ protocol_toString p ++ " -- " ++ ipv6_cidr_toString sip ++ " " ++ ipv6_cidr_toString dip ++ " " ++ iface_toString "in: " iif ++ " " ++ iface_toString "out: " oif ++ " " ++ ports_toString "sports: " sps ++ " " ++ ports_toString "dports: " dps; next_hop_update :: forall a b. (Maybe (Word a) -> Maybe (Word a)) -> Routing_action_ext a b -> Routing_action_ext a b; next_hop_update next_hopa (Routing_action_ext output_iface next_hop more) = Routing_action_ext output_iface (next_hopa next_hop) more; routing_action_next_hop_update :: forall a. (Len a) => Word a -> Routing_rule_ext a () -> Routing_rule_ext a (); routing_action_next_hop_update h pk = routing_action_update (\ _ -> next_hop_update (\ _ -> Just h) (routing_action pk)) pk; abstract_for_simple_firewall :: forall a. (Len a) => Match_expr (Common_primitive a) -> Match_expr (Common_primitive a); abstract_for_simple_firewall = abstract_primitive (\ a -> (case a of { Pos aa -> is_CT_State aa || is_L4_Flags aa; Neg aa -> is_Iiface aa || (is_Oiface aa || (is_Prot aa || (is_CT_State aa || is_L4_Flags aa))); })); ipt_ipv4range_toString :: Ipt_iprange (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> [Prelude.Char]; ipt_ipv4range_toString (IpAddr ip) = ipv4addr_toString ip; ipt_ipv4range_toString (IpAddrNetmask ip n) = ipv4addr_toString ip ++ "/" ++ string_of_nat n; ipt_ipv4range_toString (IpAddrRange ip1 ip2) = ipv4addr_toString ip1 ++ "-" ++ ipv4addr_toString ip2; ipt_ipv6range_toString :: Ipt_iprange (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))) -> [Prelude.Char]; ipt_ipv6range_toString (IpAddr ip) = ipv6addr_toString ip; ipt_ipv6range_toString (IpAddrNetmask ip n) = ipv6addr_toString ip ++ "/" ++ string_of_nat n; ipt_ipv6range_toString (IpAddrRange ip1 ip2) = ipv6addr_toString ip1 ++ "-" ++ ipv6addr_toString ip2; common_primitive_ipv4_toString :: Common_primitive (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))) -> [Prelude.Char]; common_primitive_ipv4_toString = common_primitive_toString ipv4addr_toString; common_primitive_ipv6_toString :: Common_primitive (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1))))))) -> [Prelude.Char]; common_primitive_ipv6_toString = common_primitive_toString ipv6addr_toString; to_simple_firewall_without_interfaces :: forall a. (Len a) => [(Iface, [(Word a, Nat)])] -> Maybe [Routing_rule_ext a ()] -> [Rule (Common_primitive a)] -> [Simple_rule a]; to_simple_firewall_without_interfaces ipassmt rtblo rs = to_simple_firewall (upper_closure (optimize_matches (abstract_primitive (\ a -> (case a of { Pos aa -> is_Iiface aa || is_Oiface aa; Neg aa -> is_Iiface aa || is_Oiface aa; }))) (optimize_matches abstract_for_simple_firewall (upper_closure (iface_try_rewrite ipassmt rtblo (upper_closure (packet_assume_new rs))))))); common_primitive_match_expr_toString :: forall a. (Common_primitive a -> [Prelude.Char]) -> Match_expr (Common_primitive a) -> [Prelude.Char]; common_primitive_match_expr_toString toStr MatchAny = []; common_primitive_match_expr_toString toStr (Match m) = toStr m; common_primitive_match_expr_toString toStr (MatchAnd m1 m2) = common_primitive_match_expr_toString toStr m1 ++ " " ++ common_primitive_match_expr_toString toStr m2; common_primitive_match_expr_toString toStr (MatchNot (Match m)) = "! " ++ toStr m; common_primitive_match_expr_toString toStr (MatchNot (MatchNot v)) = "NOT (" ++ common_primitive_match_expr_toString toStr (MatchNot v) ++ ")"; common_primitive_match_expr_toString toStr (MatchNot (MatchAnd v va)) = "NOT (" ++ common_primitive_match_expr_toString toStr (MatchAnd v va) ++ ")"; common_primitive_match_expr_toString toStr (MatchNot MatchAny) = "NOT (" ++ common_primitive_match_expr_toString toStr MatchAny ++ ")"; common_primitive_match_expr_ipv4_toString :: Match_expr (Common_primitive (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))) -> [Prelude.Char]; common_primitive_match_expr_ipv4_toString = common_primitive_match_expr_toString common_primitive_ipv4_toString; common_primitive_match_expr_ipv6_toString :: Match_expr (Common_primitive (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 (Bit0 Num1)))))))) -> [Prelude.Char]; common_primitive_match_expr_ipv6_toString = common_primitive_match_expr_toString common_primitive_ipv6_toString; }
diekmann/Iptables_Semantics
haskell_tool/lib/Network/IPTables/Generated.hs
bsd-2-clause
208,172
2
43
47,012
80,705
42,652
38,053
-1
-1
{-# LANGUAGE FlexibleContexts, TypeOperators #-} module Development.Shake.System ( system, system', systemStdout', copy, mkdir, readFileLines, quote ) where import Development.Shake import qualified Development.Shake.Core.Utilities as Utilities import Control.Monad.IO.Class import Data.List import qualified System.Process as Process import System.Exit import System.Directory import System.FilePath system' :: [String] -> Act n () system' prog = do ec <- system prog Utilities.checkExitCode prog ec system :: [String] -> Act n ExitCode system prog = do putStrLnAt VerboseVerbosity cmd reportCommand cmd $ Process.system cmd where cmd = intercalate " " prog systemStdout' :: [String] -> Act n String systemStdout' prog = do (ec, stdout) <- systemStdout prog Utilities.checkExitCode prog ec return stdout systemStdout :: [String] -> Act n (ExitCode, String) systemStdout prog = do putStrLnAt VerboseVerbosity cmd reportCommand cmd $ Utilities.systemStdout cmd where cmd = intercalate " " prog control_characters :: [Char] control_characters = ['$', '`'] --meta_characters :: [Char] --meta_characters = [' ', '\t', '|', '&', ';', '(', ')', '<', '>'] -- | Shell escaping by double-quoting the argument. -- -- See 3.1.2.3 of <http://www.gnu.org/software/bash/manual/bashref.html> quote :: String -> String quote x = "\"" ++ concatMap escape x ++ "\"" where must_escape = control_characters ++ ['\"', '\\'] escape c | c `elem` must_escape = ['\\', c] | otherwise = [c] -- TODO: I'm not using this at the moment -- -- -- | Shell escaping by backslash-encoding the argument. -- -- -- -- See 3.1.2.1 of <http://www.gnu.org/software/bash/manual/bashref.html#Definitions> -- escape :: String -> String -- escape x = concatMap escape x -- where must_escape = control_characters ++ meta_characters ++ ['\\', '\'', '\"'] -- escape c | c `elem` must_escape = ['\\', c] -- | otherwise = [c] readFileLines :: (CanonicalFilePath :< n, Namespace n) => FilePath -> Act n [String] readFileLines x = do need [x] liftIO $ fmap lines $ readFile x copy :: (CanonicalFilePath :< n, Namespace n) => FilePath -> FilePath -> Act n () copy from to = do mkdir $ takeDirectory to need [from] system' ["cp", quote from, quote to] mkdir :: FilePath -> Act n () mkdir fp = liftIO $ createDirectoryIfMissing True fp
beni55/openshake
Development/Shake/System.hs
bsd-3-clause
2,468
0
10
527
618
327
291
52
1
{-# LANGUAGE BangPatterns, CPP, GeneralizedNewtypeDeriving, MagicHash, Rank2Types, UnboxedTuples #-} #ifdef GENERICS {-# LANGUAGE DeriveGeneric, ScopedTypeVariables #-} #endif -- | QuickCheck tests for the 'Data.Hashable' module. We test -- functions by comparing the C and Haskell implementations. module Properties (properties) where import Data.Hashable (Hashable, hash, hashByteArray, hashPtr) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.List (nub) import Control.Monad (ap, liftM) import System.IO.Unsafe (unsafePerformIO) import Foreign.Marshal.Array (withArray) import GHC.Base (ByteArray#, Int(..), newByteArray#, unsafeCoerce#, writeWord8Array#) import GHC.ST (ST(..), runST) import GHC.Word (Word8(..)) import Test.QuickCheck hiding ((.&.)) import Test.Framework (Test, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) #ifdef GENERICS import GHC.Generics #endif #if MIN_VERSION_bytestring(0,10,4) import qualified Data.ByteString.Short as BS #endif ------------------------------------------------------------------------ -- * Properties instance Arbitrary T.Text where arbitrary = T.pack `fmap` arbitrary instance Arbitrary TL.Text where arbitrary = TL.pack `fmap` arbitrary instance Arbitrary B.ByteString where arbitrary = B.pack `fmap` arbitrary instance Arbitrary BL.ByteString where arbitrary = sized $ \n -> resize (round (sqrt (toEnum n :: Double))) ((BL.fromChunks . map (B.pack . nonEmpty)) `fmap` arbitrary) where nonEmpty (NonEmpty a) = a #if MIN_VERSION_bytestring(0,10,4) instance Arbitrary BS.ShortByteString where arbitrary = BS.pack `fmap` arbitrary #endif -- | Validate the implementation by comparing the C and Haskell -- versions. pHash :: [Word8] -> Bool pHash xs = unsafePerformIO $ withArray xs $ \ p -> (hashByteArray (fromList xs) 0 len ==) `fmap` hashPtr p len where len = length xs -- | Content equality implies hash equality. pText :: T.Text -> T.Text -> Bool pText a b = if (a == b) then (hash a == hash b) else True -- | Content equality implies hash equality. pTextLazy :: TL.Text -> TL.Text -> Bool pTextLazy a b = if (a == b) then (hash a == hash b) else True -- | A small positive integer. newtype ChunkSize = ChunkSize { unCS :: Int } deriving (Eq, Ord, Num, Integral, Real, Enum) instance Show ChunkSize where show = show . unCS instance Arbitrary ChunkSize where arbitrary = (ChunkSize . (`mod` maxChunkSize)) `fmap` (arbitrary `suchThat` ((/=0) . (`mod` maxChunkSize))) where maxChunkSize = 16 -- | Ensure that the rechunk function causes a rechunked string to -- still match its original form. pTextRechunk :: T.Text -> NonEmptyList ChunkSize -> Bool pTextRechunk t cs = TL.fromStrict t == rechunkText t cs -- | Lazy strings must hash to the same value no matter how they are -- chunked. pTextLazyRechunked :: T.Text -> NonEmptyList ChunkSize -> NonEmptyList ChunkSize -> Bool pTextLazyRechunked t cs0 cs1 = hash (rechunkText t cs0) == hash (rechunkText t cs1) -- | Break up a string into chunks of different sizes. rechunkText :: T.Text -> NonEmptyList ChunkSize -> TL.Text rechunkText t0 (NonEmpty cs0) = TL.fromChunks . go t0 . cycle $ cs0 where go t _ | T.null t = [] go t (c:cs) = a : go b cs where (a,b) = T.splitAt (unCS c) t go _ [] = error "Properties.rechunk - The 'impossible' happened!" #if MIN_VERSION_bytestring(0,10,4) -- | Content equality implies hash equality. pBSShort :: BS.ShortByteString -> BS.ShortByteString -> Bool pBSShort a b = if (a == b) then (hash a == hash b) else True #endif -- | Content equality implies hash equality. pBS :: B.ByteString -> B.ByteString -> Bool pBS a b = if (a == b) then (hash a == hash b) else True -- | Content equality implies hash equality. pBSLazy :: BL.ByteString -> BL.ByteString -> Bool pBSLazy a b = if (a == b) then (hash a == hash b) else True -- | Break up a string into chunks of different sizes. rechunkBS :: B.ByteString -> NonEmptyList ChunkSize -> BL.ByteString rechunkBS t0 (NonEmpty cs0) = BL.fromChunks . go t0 . cycle $ cs0 where go t _ | B.null t = [] go t (c:cs) = a : go b cs where (a,b) = B.splitAt (unCS c) t go _ [] = error "Properties.rechunkBS - The 'impossible' happened!" -- | Ensure that the rechunk function causes a rechunked string to -- still match its original form. pBSRechunk :: B.ByteString -> NonEmptyList ChunkSize -> Bool pBSRechunk t cs = fromStrict t == rechunkBS t cs -- | Lazy bytestrings must hash to the same value no matter how they -- are chunked. pBSLazyRechunked :: B.ByteString -> NonEmptyList ChunkSize -> NonEmptyList ChunkSize -> Bool pBSLazyRechunked t cs1 cs2 = hash (rechunkBS t cs1) == hash (rechunkBS t cs2) -- This wrapper is required by 'runST'. data ByteArray = BA { unBA :: ByteArray# } -- | Create a 'ByteArray#' from a list of 'Word8' values. fromList :: [Word8] -> ByteArray# fromList xs0 = unBA (runST $ ST $ \ s1# -> case newByteArray# len# s1# of (# s2#, marr# #) -> case go s2# 0 marr# xs0 of s3# -> (# s3#, BA (unsafeCoerce# marr#) #)) where !(I# len#) = length xs0 go s# _ _ [] = s# go s# i@(I# i#) marr# ((W8# x):xs) = case writeWord8Array# marr# i# x s# of s2# -> go s2# (i + 1) marr# xs -- Generics #ifdef GENERICS data Product2 a b = Product2 a b deriving (Generic) instance (Arbitrary a, Arbitrary b) => Arbitrary (Product2 a b) where arbitrary = Product2 `liftM` arbitrary `ap` arbitrary instance (Hashable a, Hashable b) => Hashable (Product2 a b) data Product3 a b c = Product3 a b c deriving (Generic) instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (Product3 a b c) where arbitrary = Product3 `liftM` arbitrary `ap` arbitrary `ap` arbitrary instance (Hashable a, Hashable b, Hashable c) => Hashable (Product3 a b c) -- Hashes of all product types of the same shapes should be the same. pProduct2 :: Int -> String -> Bool pProduct2 x y = hash (x, y) == hash (Product2 x y) pProduct3 :: Double -> Maybe Bool -> (Int, String) -> Bool pProduct3 x y z = hash (x, y, z) == hash (Product3 x y z) data Sum2 a b = S2a a | S2b b deriving (Eq, Ord, Show, Generic) instance (Hashable a, Hashable b) => Hashable (Sum2 a b) data Sum3 a b c = S3a a | S3b b | S3c c deriving (Eq, Ord, Show, Generic) instance (Hashable a, Hashable b, Hashable c) => Hashable (Sum3 a b c) -- Hashes of the same parameter, but with different sum constructors, -- should differ. (They might legitimately collide, but that's -- vanishingly unlikely.) pSum2_differ :: Int -> Bool pSum2_differ x = nub hs == hs where hs = [ hash (S2a x :: Sum2 Int Int) , hash (S2b x :: Sum2 Int Int) ] pSum3_differ :: Int -> Bool pSum3_differ x = nub hs == hs where hs = [ hash (S3a x :: Sum3 Int Int Int) , hash (S3b x :: Sum3 Int Int Int) , hash (S3c x :: Sum3 Int Int Int) ] #endif properties :: [Test] properties = [ testProperty "bernstein" pHash , testGroup "text" [ testProperty "text/strict" pText , testProperty "text/lazy" pTextLazy , testProperty "text/rechunk" pTextRechunk , testProperty "text/rechunked" pTextLazyRechunked ] , testGroup "bytestring" [ testProperty "bytestring/strict" pBS , testProperty "bytestring/lazy" pBSLazy #if MIN_VERSION_bytestring(0,10,4) , testProperty "bytestring/short" pBSShort #endif , testProperty "bytestring/rechunk" pBSRechunk , testProperty "bytestring/rechunked" pBSLazyRechunked ] #ifdef GENERICS , testGroup "generics" [ -- Note: "product2" and "product3" have been temporarily -- disabled until we have added a 'hash' method to the GHashable -- class. Until then (a,b) hashes to a different value than (a -- :*: b). While this is not incorrect, it would be nicer if -- they didn't. testProperty "product2" pProduct2 , testProperty -- "product3" pProduct3 testProperty "sum2_differ" pSum2_differ , testProperty "sum3_differ" pSum3_differ ] #endif ] ------------------------------------------------------------------------ -- Utilities fromStrict :: B.ByteString -> BL.ByteString #if MIN_VERSION_bytestring(0,10,0) fromStrict = BL.fromStrict #else fromStrict b = BL.fromChunks [b] #endif
ekmett/hashable
tests/Properties.hs
bsd-3-clause
8,663
0
18
1,924
2,445
1,335
1,110
97
3
{-# LANGUAGE OverloadedStrings, TypeSynonymInstances, DeriveGeneric, FlexibleInstances #-} module React.Events ( EventProperties(..) , Target(..) , ModifierKeys(..) , MouseEvent(..) , KeyboardEvent(..) , ChangeEvent(..) , FocusEvent(..) , BlurEvent(..) -- * Native Events , onBlur , onFocus , onChange , onKeyDown , onKeyPress , onKeyUp , onMouseEnter , onMouseLeave , onDoubleClick , onClick -- * Synthetic Events , onEnter ) where import Control.Applicative import Control.DeepSeq import Control.Monad import Data.Maybe import GHC.Generics import System.IO.Unsafe import React.GHCJS import React.Imports import React.Types mkEventHandler :: (FromJSRef evt, NFData evt) => EvtType -> (evt -> Maybe signal) -> AttrOrHandler signal mkEventHandler ty handle = let handle' raw = handle $!! fromJust $ unsafePerformIO $ fromJSRef $ castRef raw in Handler (EventHandler handle' ty) -- | Low level properties common to all events data EventProperties e = EventProperties { bubbles :: !Bool , cancelable :: !Bool , currentTarget :: !e -- NativeElem , defaultPrevented :: !Bool , eventPhase :: !Int , isTrusted :: !Bool -- , nativeEvent :: DOMEvent -- , preventDefault :: IO () -- , stopPropagation :: IO () , evtTarget :: !e -- NativeElem --, timeStamp :: Date , eventType :: !JSString -- type } instance NFData e => NFData (EventProperties e) where rnf (EventProperties a b c d e f g h) = a `seq` b `seq` c `seq` d `seq` e `seq` f `seq` g `seq` h `seq` () data ModifierKeys = ModifierKeys { altKey :: !Bool , ctrlKey :: !Bool , metaKey :: !Bool , shiftKey :: !Bool } deriving (Eq, Show, Generic) instance FromJSRef ModifierKeys where instance NFData ModifierKeys where rnf (ModifierKeys a b c d) = a `seq` b `seq` c `seq` d `seq` () data MouseEvent = MouseEvent { -- mouseEventProperties :: !(EventProperties e) -- mouseModifierKeys :: !ModifierKeys -- , buttonNum :: !Int -- "button" -- , buttons :: Int clientX :: !Double , clientY :: !Double , pageX :: !Double , pageY :: !Double -- , relatedTarget :: Unpacked , screenX :: !Double , screenY :: !Double } deriving (Show, Generic) instance FromJSRef MouseEvent where instance NFData MouseEvent where -- rnf (MouseEvent a b c d e f g h) = -- a `seq` b `seq` c `seq` d `seq` e `seq` f `seq` g `seq` h `seq` () rnf (MouseEvent a b c d e f) = a `seq` b `seq` c `seq` d `seq` e `seq` f `seq` () data KeyboardEvent = KeyboardEvent { -- keyboardEventProperties :: ! (EventProperties e) -- keyboardModifierKeys :: !ModifierKeys charCode :: !Int , key :: !JSString , keyCode :: !Int -- , locale :: !JSString , location :: !Int , repeat :: !Bool , which :: !Int } deriving (Show, Generic) instance FromJSRef KeyboardEvent where instance NFData KeyboardEvent where rnf (KeyboardEvent a b c d e f) = a `seq` b `seq` c `seq` d `seq` e `seq` f `seq` () data Target = Target { value :: !JSString , tagName :: !JSString -- XXX(joel) This is gross. Added a second field so that the generic -- FromJSRef instance does the right thing. Without a second field it -- uses the FromJSRef instance for `value`. } deriving (Show, Generic) instance FromJSRef Target where data ChangeEvent = ChangeEvent { target :: !Target , timeStamp :: !Int } deriving (Show, Generic) instance FromJSRef ChangeEvent where instance NFData ChangeEvent where rnf e@(ChangeEvent str stamp) = str `seq` stamp `seq` () -- data FocusEvent e = -- FocusEvent { -- focusEventProperties :: ! (EventProperties e) -- domEventTarget :: !e -- NativeElem -- , relatedTarget :: !e -- NativeElem -- } -- instance NFData e => NFData (FocusEvent e) where -- rnf (FocusEvent a b) = a `seq` b `seq` () data FocusEvent = FocusEvent deriving Generic instance NFData FocusEvent instance FromJSRef FocusEvent where data BlurEvent = BlurEvent deriving (Show, Generic) instance FromJSRef BlurEvent where instance NFData BlurEvent -- TODO: handle (a -> Maybe b) or (a -> b) onBlur :: (BlurEvent -> Maybe s) -> AttrOrHandler s onBlur = mkEventHandler BlurEvt onFocus :: (FocusEvent -> Maybe s) -> AttrOrHandler s onFocus = mkEventHandler FocusEvt onChange :: (ChangeEvent -> Maybe s) -> AttrOrHandler s onChange = mkEventHandler ChangeEvt onKeyDown :: (KeyboardEvent -> Maybe s) -> AttrOrHandler s onKeyDown = mkEventHandler KeyDownEvt onKeyPress :: (KeyboardEvent -> Maybe s) -> AttrOrHandler s onKeyPress = mkEventHandler KeyPressEvt onKeyUp :: (KeyboardEvent -> Maybe s) -> AttrOrHandler s onKeyUp = mkEventHandler KeyUpEvt onMouseEnter :: (MouseEvent -> Maybe s) -> AttrOrHandler s onMouseEnter = mkEventHandler MouseEnterEvt onMouseLeave :: (MouseEvent -> Maybe s) -> AttrOrHandler s onMouseLeave = mkEventHandler MouseLeaveEvt onDoubleClick :: (MouseEvent -> Maybe s) -> AttrOrHandler s onDoubleClick = mkEventHandler DoubleClickEvt onClick :: (MouseEvent -> Maybe s) -> AttrOrHandler s onClick = mkEventHandler ClickEvt onEnter :: s -> AttrOrHandler s onEnter s = onKeyPress handler where handler KeyboardEvent{key="Enter"} = Just s handler _ = Nothing
joelburget/react-haskell
src/React/Events.hs
mit
5,862
0
13
1,719
1,365
767
598
183
2
{-# LANGUAGE BangPatterns #-} module Util.BitSet( BitSet(), EnumBitSet(..), toWord, fromWord ) where import Data.List(foldl') import Data.Bits import Data.Word import Data.Monoid import Util.SetLike import Util.HasSize newtype BitSet = BitSet Word deriving(Eq,Ord) instance Monoid BitSet where mempty = BitSet 0 mappend (BitSet a) (BitSet b) = BitSet (a .|. b) mconcat ss = foldl' mappend mempty ss instance Unionize BitSet where BitSet a `difference` BitSet b = BitSet (a .&. complement b) BitSet a `intersection` BitSet b = BitSet (a .&. b) type instance Elem BitSet = Int instance Collection BitSet where -- type Elem BitSet = Int singleton i = BitSet (bit i) fromList ts = BitSet (foldl' setBit 0 ts) toList (BitSet w) = f w 0 where f 0 _ = [] f w n = if even w then f (w `shiftR` 1) (n + 1) else n:f (w `shiftR` 1) (n + 1) type instance Key BitSet = Elem BitSet instance SetLike BitSet where keys bs = toList bs delete i (BitSet v) = BitSet (clearBit v i) member i (BitSet v) = testBit v i insert i (BitSet v) = BitSet (v .|. bit i) sfilter fn (BitSet w) = f w 0 0 where f 0 _ r = BitSet r f w n r = if even w || not (fn n) then f w1 n1 r else f w1 n1 (setBit r n) where !n1 = n + 1 !w1 = w `shiftR` 1 spartition = error "BitSet.spartition: not impl." instance IsEmpty BitSet where isEmpty (BitSet n) = n == 0 instance HasSize BitSet where size (BitSet n) = f 0 n where f !c 0 = c f !c !v = f (c + 1) (v .&. (v - 1)) {- instance SetLike BitSet where BitSet a `difference` BitSet b = BitSet (a .&. complement b) BitSet a `intersection` BitSet b = BitSet (a .&. b) BitSet a `disjoint` BitSet b = ((a .&. b) == 0) BitSet a `isSubsetOf` BitSet b = (a .|. b) == b sempty = BitSet 0 union (BitSet a) (BitSet b) = BitSet (a .|. b) unions ss = foldl' union sempty ss instance BuildSet Int BitSet where insert i (BitSet v) = BitSet (v .|. bit i) singleton i = BitSet (bit i) fromList ts = BitSet (foldl' setBit 0 ts) instance ModifySet Int BitSet where delete i (BitSet v) = BitSet (clearBit v i) member i (BitSet v) = testBit v i toList (BitSet w) = f w 0 where f 0 _ = [] f w n = if even w then f (w `shiftR` 1) (n + 1) else n:f (w `shiftR` 1) (n + 1) sfilter fn (BitSet w) = f w 0 0 where f 0 _ r = BitSet r f w n r = if even w || not (fn n) then f w1 n1 r else f w1 n1 (setBit r n) where !n1 = n + 1 !w1 = w `shiftR` 1 -} instance Show BitSet where showsPrec n bs = showsPrec n (toList bs) newtype EnumBitSet a = EBS BitSet deriving(Monoid,Unionize,HasSize,Eq,Ord,IsEmpty) type instance Elem (EnumBitSet a) = a instance Enum a => Collection (EnumBitSet a) where singleton i = EBS $ singleton (fromEnum i) fromList ts = EBS $ fromList (map fromEnum ts) toList (EBS w) = map toEnum $ toList w type instance Key (EnumBitSet a) = Elem (EnumBitSet a) instance Enum a => SetLike (EnumBitSet a) where delete (fromEnum -> i) (EBS v) = EBS $ delete i v member (fromEnum -> i) (EBS v) = member i v insert (fromEnum -> i) (EBS v) = EBS $ insert i v sfilter f (EBS v) = EBS $ sfilter (f . toEnum) v keys = error "EnumBitSet.keys: not impl." spartition = error "EnumBitSet.spartition: not impl." {- instance Enum a => BuildSet a (EnumBitSet a) where fromList xs = EnumBitSet $ fromList (map fromEnum xs) insert x (EnumBitSet s) = EnumBitSet $ insert (fromEnum x) s singleton x = EnumBitSet $ singleton (fromEnum x) instance Enum a => ModifySet a (EnumBitSet a) where toList (EnumBitSet s) = map toEnum $ toList s member x (EnumBitSet s) = member (fromEnum x) s delete x (EnumBitSet s) = EnumBitSet $ delete (fromEnum x) s sfilter fn (EnumBitSet s) = EnumBitSet $ sfilter (fn . toEnum) s instance (Enum a,Show a) => Show (EnumBitSet a) where showsPrec n bs = showsPrec n (toList bs) -} toWord :: BitSet -> Word toWord (BitSet w) = w fromWord :: Word -> BitSet fromWord w = BitSet w
m-alvarez/jhc
src/Util/BitSet.hs
mit
4,150
0
12
1,140
1,117
567
550
-1
-1
{-# LANGUAGE PatternGuards #-} import Control.Concurrent import Control.Exception import Control.Monad import Text.Printf import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.ByteString.Char8 as B import System.Environment import Prelude hiding (catch) import BingTranslate as Bing main = do [text] <- fmap (fmap (B.unpack . UTF8.fromString)) getArgs languages <- Bing.getLanguages fromLang <- Bing.detectLanguage text printf "\"%s\" appears to be in language \"%s\"\n" text fromLang forM_ (filter (/= fromLang) languages) $ \toLang -> do str <- Bing.translateText text fromLang toLang printf "%s: %s\n" toLang str ----------------------------------------------------------------------------- -- Our Async API: data Async a = Async ThreadId (MVar (Either SomeException a)) async :: IO a -> IO (Async a) async action = do var <- newEmptyMVar t <- forkIO ((do r <- action; putMVar var (Right r)) `catch` \e -> putMVar var (Left e)) return (Async t var) wait :: Async a -> IO (Either SomeException a) wait (Async t var) = readMVar var cancel :: Async a -> IO () cancel (Async t var) = throwTo t ThreadKilled
prt2121/haskell-practice
parconc/other/bingtranslator.hs
apache-2.0
1,178
0
16
221
398
204
194
29
1
module Distribution.Client.Dependency.Modular.Log where import Control.Applicative import Data.List as L import Data.Set as S import Distribution.Client.Dependency.Types -- from Cabal import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Message import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.Tree (FailReason(..)) -- | The 'Log' datatype. -- -- Represents the progress of a computation lazily. -- -- Parameterized over the type of actual messages and the final result. type Log m a = Progress m () a -- | Turns a log into a list of messages paired with a final result. A final result -- of 'Nothing' indicates failure. A final result of 'Just' indicates success. -- Keep in mind that forcing the second component of the returned pair will force the -- entire log. runLog :: Log m a -> ([m], Maybe a) runLog (Done x) = ([], Just x) runLog (Fail _) = ([], Nothing) runLog (Step m p) = let (ms, r) = runLog p in (m : ms, r) -- | Postprocesses a log file. Takes as an argument a limit on allowed backjumps. -- If the limit is 'Nothing', then infinitely many backjumps are allowed. If the -- limit is 'Just 0', backtracking is completely disabled. logToProgress :: Maybe Int -> Log Message a -> Progress String String a logToProgress mbj l = let (ms, s) = runLog l -- 'Nothing' for 's' means search tree exhaustively searched and failed (es, e) = proc 0 ms -- catch first error (always) -- 'Nothing' in 'e' means no backjump found (ns, t) = case mbj of Nothing -> (ms, Nothing) Just n -> proc n ms -- 'Nothing' in 't' means backjump limit not reached -- prefer first error over later error (exh, r) = case t of -- backjump limit not reached Nothing -> case s of Nothing -> (True, e) -- failed after exhaustive search Just _ -> (True, Nothing) -- success -- backjump limit reached; prefer first error Just _ -> (False, e) -- failed after backjump limit was reached in go es es -- trace for first error (showMessages (const True) True ns) -- shortened run r s exh where -- Proc takes the allowed number of backjumps and a list of messages and explores the -- message list until the maximum number of backjumps has been reached. The log until -- that point as well as whether we have encountered an error or not are returned. proc :: Int -> [Message] -> ([Message], Maybe (ConflictSet QPN)) proc _ [] = ([], Nothing) proc n ( Failure cs Backjump : xs@(Leave : Failure cs' Backjump : _)) | cs == cs' = proc n xs -- repeated backjumps count as one proc 0 ( Failure cs Backjump : _ ) = ([], Just cs) proc n (x@(Failure _ Backjump) : xs) = (\ ~(ys, r) -> (x : ys, r)) (proc (n - 1) xs) proc n (x : xs) = (\ ~(ys, r) -> (x : ys, r)) (proc n xs) -- This function takes a lot of arguments. The first two are both supposed to be -- the log up to the first error. That's the error that will always be printed in -- case we do not find a solution. We pass this log twice, because we evaluate it -- in parallel with the full log, but we also want to retain the reference to its -- beginning for when we print it. This trick prevents a space leak! -- -- The third argument is the full log, the fifth and six error conditions. -- The seventh argument indicates whether the search was exhaustive. -- -- The order of arguments is important! In particular 's' must not be evaluated -- unless absolutely necessary. It contains the final result, and if we shortcut -- with an error due to backjumping, evaluating 's' would still require traversing -- the entire tree. go ms (_ : ns) (x : xs) r s exh = Step x (go ms ns xs r s exh) go ms [] (x : xs) r s exh = Step x (go ms [] xs r s exh) go ms _ [] (Just cs) _ exh = Fail $ "Could not resolve dependencies:\n" ++ unlines (showMessages (L.foldr (\ v _ -> v `S.member` cs) True) False ms) ++ (if exh then "Dependency tree exhaustively searched.\n" else "Backjump limit reached (" ++ currlimit mbj ++ "change with --max-backjumps or try to run with --reorder-goals).\n") where currlimit (Just n) = "currently " ++ show n ++ ", " currlimit Nothing = "" go _ _ [] _ (Just s) _ = Done s go _ _ [] _ _ _ = Fail ("Could not resolve dependencies; something strange happened.") -- should not happen logToProgress' :: Log Message a -> Progress String String a logToProgress' l = let (ms, r) = runLog l xs = showMessages (const True) True ms in go xs r where go [x] Nothing = Fail x go [] Nothing = Fail "" go [] (Just r) = Done r go (x:xs) r = Step x (go xs r) runLogIO :: Log Message a -> IO (Maybe a) runLogIO x = do let (ms, r) = runLog x putStr (unlines $ showMessages (const True) True ms) return r failWith :: m -> Log m a failWith m = Step m (Fail ()) succeedWith :: m -> a -> Log m a succeedWith m x = Step m (Done x) continueWith :: m -> Log m a -> Log m a continueWith = Step tryWith :: Message -> Log Message a -> Log Message a tryWith m x = Step m (Step Enter x) <|> failWith Leave
trskop/cabal
cabal-install/Distribution/Client/Dependency/Modular/Log.hs
bsd-3-clause
6,451
0
16
2,477
1,428
762
666
73
14
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Models where import Control.Monad.Reader (MonadIO, MonadReader, asks, liftIO) import Database.Persist.Sql (SqlPersistT, runMigration, runSqlPool) import Database.Persist.TH (mkMigrate, mkPersist, persistLowerCase, share, sqlSettings) import Control.Exception.Safe import Say import Config (Config, configPool) import Data.Text (Text) share [ mkPersist sqlSettings , mkMigrate "migrateAll" ] [persistLowerCase| User json name Text email Text deriving Show Eq |] doMigrations :: SqlPersistT IO () doMigrations = do liftIO $ say "in doMigrations, running?" runMigration migrateAll liftIO $ say "already run" runDb :: (MonadReader Config m, MonadIO m) => SqlPersistT IO b -> m b runDb query = do pool <- asks configPool liftIO $ runSqlPool query pool
parsonsmatt/servant-persistent
src/Models.hs
mit
1,209
0
8
204
237
135
102
34
1
module OutputProcessing where import Data -- TODO createOutput :: Grammar -> Output createOutput (Module _ c) = format c format :: [Statement] -> String format [] = "" format ((Rule l r):ss) = formatRule l r ++ "\n" ++ format ss format (s:ss) = show s ++ "\n" ++ format ss formatRule :: Element -> [[Element]] -> String formatRule l r = formatElement l ++ " -> " ++ formatRightsides r formatRightsides :: [[Element]] -> String formatRightsides [] = "" formatRightsides (x:xs) | xs /= [] = formatRightside x ++ "| " ++ formatRightsides xs | otherwise = formatRightside x formatRightside :: [Element] -> String formatRightside [] = "" formatRightside (e:es) = formatElement e ++ " " ++ formatRightside es formatElement :: Element -> String formatElement (Nonterminal nt) = nt formatElement (Terminal t) = "\"" ++ t ++ "\"" -- EOF
mkopta/fika-ha
src/OutputProcessing.hs
mit
860
0
9
173
344
175
169
20
1