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 Nonpalindromes.A252698Spec (main, spec) where import Test.Hspec import Nonpalindromes.A252698 (a252698) main :: IO () main = hspec spec spec :: Spec spec = describe "A252698" $ it "correctly computes the first 10 elements" $ take 10 (map a252698 [0..]) `shouldBe` expectedValue where expectedValue = [0,5,20,80,380,1820,9020,44720,223220,1114280]
peterokagey/haskellOEIS
test/Nonpalindromes/A252698Spec.hs
apache-2.0
368
0
10
59
130
75
55
10
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="ru-RU"> <title>Replacer | 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>
secdec/zap-extensions
addOns/replacer/src/main/javahelp/org/zaproxy/zap/extension/replacer/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
969
78
66
158
411
208
203
-1
-1
{-# OPTIONS_GHC -XTypeOperators #-} {-# OPTIONS_GHC -XKindSignatures #-} {-# OPTIONS_GHC -XRankNTypes #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Functor.HigherOrder -- Copyright : (C) 2008 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable (rank-2 polymorphism) -- -- Neil Ghani and Particia Johann''s higher order functors from -- <http://crab.rutgers.edu/~pjohann/tlca07-rev.pdf> ---------------------------------------------------------------------------- module Control.Functor.HigherOrder ( HFunctor(..) , HPointed(..) , HCopointed(..) , HAlgebra , HCoalgebra , FixH(..) , LowerH(..) ) where import Control.Functor import Control.Functor.Pointed import Control.Functor.Extras import Control.Monad.Reader import Control.Monad.State.Lazy import Control.Monad.Writer.Lazy import Control.Monad.List type HAlgebra f g = f g :~> g type HCoalgebra f g = g :~> f g class HFunctor f where ffmap :: Functor g => (a -> b) -> f g a -> f g b hfmap :: (g :~> h) -> f g :~> f h newtype FixH f a = InH { outH :: f (FixH f) a } class HFunctor m => HPointed m where hreturn :: Functor f => f a -> m f a class HFunctor w => HCopointed w where hextract :: Functor f => w f a -> f a newtype LowerH (h :: (* -> *) -> * -> *) (f :: * -> *) (a :: *) = LowerH { liftH :: h f a } instance (HFunctor h, Functor f) => Functor (LowerH h f) where fmap f = LowerH . ffmap f . liftH instance (HPointed h, Pointed f) => Pointed (LowerH h f) where point = LowerH . hreturn . point instance (HCopointed h, Copointed f) => Copointed (LowerH h f) where extract = extract . hextract . liftH instance HFunctor (ReaderT e) where ffmap f g = ReaderT (fmap f . runReaderT g) hfmap f g = ReaderT (f . runReaderT g) instance HPointed (ReaderT e) where hreturn = ReaderT . const instance HFunctor (StateT e) where ffmap f (StateT g) = StateT (fmap (first f) . g) hfmap f (StateT g) = StateT (f . g) instance HPointed (StateT e) where hreturn m = StateT (\s -> fmap (\a -> (a,s)) m) instance HFunctor (WriterT e) where ffmap f = WriterT . fmap (first f) . runWriterT hfmap f = WriterT . f . runWriterT instance Monoid e => HPointed (WriterT e) where hreturn = WriterT . fmap (\a -> (a,mempty)) instance HFunctor ListT where ffmap f = ListT . fmap (fmap f) . runListT hfmap f = ListT . f . runListT instance HPointed ListT where hreturn = ListT . fmap return {-# RULES "hextract/hreturn" hextract . hreturn = id #-}
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
Control/Functor/HigherOrder.hs
apache-2.0
2,633
10
12
513
908
491
417
-1
-1
------------------------------------------------------------------------------ -- | -- Module : Data.TokyoDystopia.QDB -- Copyright : 8c6794b6 <8c6794b6@gmail.com> -- License : BSD3 -- Maintainer : 8c6794b6 -- Stability : experimental -- Portability : non-portable -- -- Haskell binding for tokyodystopia TCQDB interface. -- module Database.TokyoDystopia.QDB ( -- * Type QDB() , RSET() , IDSET() -- * Basic functions , close , copy , del , ecode , fsiz , new , open , optimize , out , path , put , search , setcache , setfwmmax , sync , tnum , tune , vanish -- * Advanced functions , setdbgfd , getdbgfd , memsync , inode , mtime , opts , setsynccb , getfwmmax , cnum , resunion , resisect , resdiff , textnormalize , idsetnew , idsetdel , idsetmark , idsetcheck , idsetclear ) where import Data.ByteString (ByteString) import Data.Int (Int64) import Data.Time ( UTCTime ) import Data.Time.Clock.POSIX ( posixSecondsToUTCTime ) import Foreign (Ptr) import Database.TokyoCabinet (ECODE(..)) import Database.TokyoCabinet.Storable (Storable) import Database.TokyoDystopia.Internal (bitOr, toTuningOptions) import Database.TokyoDystopia.Types ( OpenMode(..) , TuningOption(..) , GetMode(..) ) import qualified Data.ByteString.Char8 as C8 import qualified Foreign.C.String as CS import qualified Database.TokyoCabinet.Error as TCE import qualified Database.TokyoCabinet.Storable as TCS import qualified Database.TokyoDystopia.FFI.QDB as FQ import qualified Database.TokyoDystopia.Internal as I -- | Wrapper for TCQDB. newtype QDB = QDB { unQDB :: Ptr FQ.TCQDB } -- | Wrapper for QDBRSET. newtype RSET = RSET { unRSET :: Ptr FQ.QDBRSET } -- | Wrapper for TCIDSET. newtype IDSET = IDSET { unIDSET :: Ptr FQ.TCIDSET } -- | Close database. close :: QDB -> IO Bool close = FQ.c_close . unQDB -- | Open database from given path and open modes. open :: QDB -> FilePath -> [OpenMode] -> IO Bool open = I.mkOpen FQ.c_open unQDB (FQ.unOpenMode . f) where f OREADER = FQ.omReader f OWRITER = FQ.omWriter f OCREAT = FQ.omCreat f OTRUNC = FQ.omTrunc f ONOLCK = FQ.omNolck f OLCKNB = FQ.omLcknb -- | Delete database from memory. del :: QDB -> IO () del = FQ.c_del . unQDB -- | Get the last happened error code of database. ecode :: QDB -> IO ECODE ecode db = fmap TCE.cintToError (FQ.c_ecode $ unQDB db) -- | Get file size. fsiz :: QDB -> IO Int64 fsiz = FQ.c_fsiz . unQDB -- | Creates new QDB. new :: IO QDB new = fmap QDB FQ.c_new -- | Optimize database. optimize :: QDB -> IO Bool optimize = FQ.c_optimize . unQDB -- | Removes record with given key. out :: (Storable k) => QDB -> k -> String -> IO Bool out db key val = do val' <- CS.newCString val FQ.c_out (unQDB db) (TCS.toInt64 key) val' -- | Get filepath of the database path :: QDB -> IO String path db = FQ.c_path (unQDB db) >>= CS.peekCString -- | Put data with given key and value. put :: (Storable k) => QDB -> k -> ByteString -> IO Bool put db k v = C8.useAsCString v (\str -> FQ.c_put (unQDB db) (TCS.toInt64 k) str) -- | Get the number of token from database. tnum :: QDB -> IO Int64 tnum = FQ.c_tnum . unQDB -- | Search phrase with given GetMode. search :: QDB -> String -> [GetMode] -> IO [Int64] search = I.mkSearch FQ.c_search unQDB g where g = bitOr . map (FQ.unGetMode . f) f GMSUBSTR = FQ.gmSubstr f GMPREFIX = FQ.gmPrefix f GMSUFFIX = FQ.gmSuffix f GMFULL = FQ.gmFull f _ = FQ.GetMode 0 -- | Set caching parameters. Must be used before opening database. setcache :: QDB -> Int64 -> Int -> IO Bool setcache db ic lc = FQ.c_setcache (unQDB db) ic (fromIntegral lc) -- | Set maximum number of forward matching expansion. Must be used before -- opening database. setfwmmax :: QDB -> Int -> IO Bool setfwmmax db fwm = FQ.c_setfwmmax (unQDB db) (fromIntegral fwm) -- | Sync database. sync :: QDB -> IO Bool sync = FQ.c_sync . unQDB -- | Tune the database. Must be used before opening database. tune :: QDB -> Int64 -> [TuningOption] -> IO Bool tune db etnum os = FQ.c_tune (unQDB db) etnum os' where os' = fromIntegral . bitOr . map (FQ.unTuningOption . f) $ os f TLARGE = FQ.toLarge f TDEFLATE = FQ.toDeflate f TBZIP = FQ.toBzip f TTCBS = FQ.toTcbs f _ = FQ.TuningOption 0 -- | Delete the database from disk. vanish :: QDB -> IO Bool vanish = FQ.c_vanish . unQDB -- | Copy the database to given filepath. copy :: QDB -> FilePath -> IO Bool copy db file = do file' <- CS.newCString file FQ.c_copy (unQDB db) file' -- -- Advanced features -- -- | Set file descriptor for debugging output. setdbgfd :: QDB -> Int -> IO () setdbgfd db dbg = FQ.c_setdbgfd (unQDB db) (fromIntegral dbg) -- | Get file descriptor for debugging output getdbgfd :: QDB -> IO Int getdbgfd = fmap fromIntegral . FQ.c_dbgfd . unQDB -- | Synchronize updating contents on memory of an indexed database object memsync :: QDB -> Int -> IO Bool memsync db level = FQ.c_memsync (unQDB db) (fromIntegral level) -- | Get the inode number of the database dictionary of an indexed database -- object. inode :: QDB -> IO Int64 inode = FQ.c_inode . unQDB -- | Get the modificatoin time of the database directory of an indexed database -- object. mtime :: QDB -> IO UTCTime mtime = fmap (posixSecondsToUTCTime . realToFrac) . FQ.c_mtime . unQDB -- | Get the options of an indexed database object. opts :: QDB -> IO [TuningOption] opts = fmap toTuningOptions . FQ.c_opts . unQDB -- | Set the callback function for sync progression. setsynccb :: QDB -> (Int -> Int -> String -> IO Bool) -> IO Bool setsynccb db cb = do cb' <- FQ.c_setsynccb_wrapper (\i1 i2 s -> do s' <- CS.peekCString s let i1' = fromIntegral i1 i2' = fromIntegral i2 cb i1' i2' s') FQ.c_setsynccb (unQDB db) cb' -- | Get maximum number of forward matching expansion. getfwmmax :: QDB -> IO Int getfwmmax = fmap fromIntegral . FQ.c_fwmmax . unQDB -- | Get the number of records in the cache. cnum :: QDB -> IO Int cnum = fmap fromIntegral . FQ.c_cnum . unQDB -- | Merge multiple result sets by union. resunion :: RSET -> IO RSET resunion _ = error "resunion not implemented yet" -- | Merge multiple result sets by intersection. resisect :: RSET -> IO RSET resisect _ = error "resisect not implemented yet" -- | Merge multiple result sets by difference. resdiff :: RSET -> IO RSET resdiff _ = error "resdiff not implemented yet" textnormalize :: String -> [FQ.TNOption] -> IO String textnormalize str os = do let os' = sum $ map FQ.unTNOption os str' <- CS.newCString str FQ.c_textnormalize str' (fromIntegral os') CS.peekCString str' -- | Create an ID set object. idsetnew :: Int -> IO IDSET idsetnew = fmap IDSET . FQ.c_tcidsetnew . fromIntegral -- | Delete an ID set object. idsetdel :: IDSET -> IO () idsetdel = FQ.c_tcidsetdel . unIDSET -- | Mark an ID number of an ID set object. idsetmark :: IDSET -> Int -> IO () idsetmark set i = FQ.c_tcidsetmark (unIDSET set) (fromIntegral i) -- | Check an ID of an ID set object. idsetcheck :: IDSET -> Int -> IO Bool idsetcheck set i = FQ.c_tcidsetcheck (unIDSET set) (fromIntegral i) -- | Clear an ID set object. idsetclear :: IDSET -> IO () idsetclear = FQ.c_tcidsetclear . unIDSET
8c6794b6/tokyodystopia-haskell
Database/TokyoDystopia/QDB.hs
bsd-3-clause
7,565
0
16
1,797
2,080
1,122
958
173
6
module Numeric.Physics.Particle where import Numeric.LinearAlgebra.Vector data Particle a = Particle { pPos :: !(Vec3 a) -- ^ Position of particle in the world , pVel :: !(Vec3 a) -- ^ Velocity of particle , pAcc :: !(Vec3 a) -- ^ Acceleration of particle , pDamp :: !a -- ^ damping factor for this particle , pInvMass :: !a -- ^ inverse mass (1/m) of this particle } deriving (Read,Show,Ord,Eq) -- | Takes a particle, a force, and a time duration -- and gives the particle updated for time slice integrate :: Floating a => Particle a -> Vec3 a -> a -> Particle a integrate p f dt = let pos = (dt *> pVel p) <+> pPos p acc' = (pInvMass p *> f) <+> pAcc p vel = (dt *> acc') <+> pVel p in p { pPos = pos , pVel = ((pDamp p)**dt) *> vel } {-# SPECIALIZE INLINE integrate :: Particle Double -> Vec3 Double -> Double -> Particle Double #-} {-# SPECIALIZE INLINE integrate :: Particle Float -> Vec3 Float -> Float -> Particle Float #-}
dagit/physics
src/Numeric/Physics/Particle.hs
bsd-3-clause
1,035
0
13
286
249
136
113
28
1
{-# LANGUAGE FlexibleInstances, NoMonomorphismRestriction, TemplateHaskell, GeneralizedNewtypeDeriving, FlexibleContexts, EmptyDataDecls, MultiParamTypeClasses, FunctionalDependencies, GADTs #-} --------------------------------------------------------------------------- -- | -- Module : HGene.HtmlWriterInternals -- License : http://www.gnu.org/copyleft/gpl.html -- -- Maintainer : mmirman@andrew.cmu.edu -- Stability : experimental -- Portability : probable -- -- Some tools for writing html in a pretty format in haskell. -- TODO: Use the module redirect tequnique to exclude items we don't want. module HGene.HtmlWriterInternals where import Language.Haskell.TH import Control.Monad.Trans import Control.Monad.Writer.Strict (WriterT, tell, execWriterT) import Control.Monad.Writer.Class (MonadWriter(..)) import HGene.JSCompiler.HaskellToJavaScript void a = a >> return () -- -------------------------------------------------------------------------- -- Type definition for the HtmlWriter newtype HtmlWriter a = HtmlWriter { getHtml :: WriterT String IO a} deriving (Monad, MonadWriter String) liftIO t = HtmlWriter $ lift t -- | @'writeString' s@ writes a string to the html writer monad writeString = tell -- | @'makeHtml' s@ currently just converts this into a string makeHtml = execWriterT . getHtml . printThis data End data Par data Param a b where Param :: Printable a b => [HtmlAttr] -> a -> Param a b data Elem a b where Elem :: Printable a b => String -> a -> Elem a b data HtmlAttr = Attr String String instance Show HtmlAttr where show (Attr a b) = a++"="++b -- -------------------------------------------------------------------------- -- Printable allows us to use tag for either a monad or a string or whatever -- just makes syntax better, and ideally in the future, everything better. class Printable a b | a -> b where printThis :: a -> HtmlWriter () instance Printable [Char] End where printThis = writeString instance Printable (HtmlWriter a) End where printThis = void instance Printable a Par => Printable (Elem a Par) End where printThis (Elem tg msg) = do writeString $ "<"++tg printThis msg writeString $ "</"++tg++">\n" instance Printable a End => Printable (Elem a End) End where printThis (Elem tg msg) = do writeString $ "<"++tg++">\n" printThis msg writeString $ "</"++tg++">\n" instance Printable a Par => Printable (Param a Par) Par where printThis (Param params msg) = do printThis $ showMiddle params printThis msg instance Printable a End => Printable (Param a End) Par where printThis (Param params msg) = do printThis $ showMiddle params++">\n" printThis msg showMiddle = concatMap (\x -> " "++show x) tag tg = printThis . Elem tg link lk params msg = anchor $ Param ([Attr "href" $ show lk]++params) msg href :: Printable a b => String -> a -> Param a b href ln = Param [Attr "href" (show ln)] name :: Printable a b => String -> a -> Param a b name ln = Param [Attr "id" (show ln)] script = appE [| tag "script" |] . hsToJs -- HTML tags address = tag "ADDRESS" anchor = tag "A" applet = tag "APPLET" big = tag "BIG" blockquote = tag "BLOCKQUOTE" body = tag "BODY" bold = tag "BOLD" caption = tag "CAPTION" center = tag "CENTER" cite = tag "CITE" ddef = tag "DD" define = tag "DFN" dlist = tag "DL" dterm = tag "DT" emphasize = tag "EM" fieldset = tag "FIELDSET" font = tag "FONT" form = tag "FORM" frame = tag "FRAME" frameset = tag "FRAMESET" h1 = tag "H1" h2 = tag "H2" h3 = tag "H3" h4 = tag "H4" h5 = tag "H5" h6 = tag "H6" header = tag "HEAD" html = tag "HTML" h_code = tag "CODE" h_div = tag "DIV" h_link = tag "LINK" h_map = tag "MAP" h_span = tag "SPAN" h_title = tag "TITLE" italics = tag "I" keyboard = tag "KBD" legend = tag "LEGEND" li = tag "LI" noframes = tag "NOFRAMES" olist = tag "OL" option = tag "OPTION" p = tag "P" pre = tag "PRE" sample = tag "SAMP" select = tag "SELECT" small = tag "SMALL" strong = tag "STRONG" style = tag "STYLE" sub = tag "SUB" sup = tag "SUP" table = tag "TABLE" td = tag "TD" textarea = tag "TEXTAREA" th = tag "TH" tr = tag "TR" tt = tag "TT" ulist = tag "UL" underline = tag "U" variable = tag "VAR"
mmirman/haskogeneous
src/HGene/HtmlWriterInternals.hs
bsd-3-clause
5,132
0
11
1,726
1,296
667
629
-1
-1
module Opaleye.TypeFamilies ( TF.TableField , TF.RecordField , (TF.:<*>) , (TF.:<$>) , TF.Id , TF.Pure , TF.IMap , TF.F , TF.O , TF.H , TF.W , TF.N , TF.NN , TF.Opt , TF.Req , TF.Nulls ) where import Opaleye.Internal.TypeFamilies as TF
WraithM/haskell-opaleye
src/Opaleye/TypeFamilies.hs
bsd-3-clause
271
0
5
75
100
63
37
18
0
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE UndecidableInstances #-} module Numeric.DataFrame.Internal.Backend.Family.DoubleX3 (DoubleX3 (..)) where import GHC.Base import Numeric.DataFrame.Internal.PrimArray import Numeric.PrimBytes import Numeric.ProductOrd import qualified Numeric.ProductOrd.NonTransitive as NonTransitive import qualified Numeric.ProductOrd.Partial as Partial data DoubleX3 = DoubleX3# Double# Double# Double# -- | Since @Bounded@ is not implemented for floating point types, this instance -- has an unresolvable constraint. -- Nevetheless, it is good to have it here for nicer error messages. instance Bounded Double => Bounded DoubleX3 where maxBound = case maxBound of D# x -> DoubleX3# x x x minBound = case minBound of D# x -> DoubleX3# x x x instance Eq DoubleX3 where DoubleX3# a1 a2 a3 == DoubleX3# b1 b2 b3 = isTrue# ( (a1 ==## b1) `andI#` (a2 ==## b2) `andI#` (a3 ==## b3) ) {-# INLINE (==) #-} DoubleX3# a1 a2 a3 /= DoubleX3# b1 b2 b3 = isTrue# ( (a1 /=## b1) `orI#` (a2 /=## b2) `orI#` (a3 /=## b3) ) {-# INLINE (/=) #-} cmp' :: Double# -> Double# -> PartialOrdering cmp' a b | isTrue# (a >## b) = PGT | isTrue# (a <## b) = PLT | otherwise = PEQ instance ProductOrder DoubleX3 where cmp (DoubleX3# a1 a2 a3) (DoubleX3# b1 b2 b3) = cmp' a1 b1 <> cmp' a2 b2 <> cmp' a3 b3 {-# INLINE cmp #-} instance Ord (NonTransitive.ProductOrd DoubleX3) where NonTransitive.ProductOrd x > NonTransitive.ProductOrd y = cmp x y == PGT {-# INLINE (>) #-} NonTransitive.ProductOrd x < NonTransitive.ProductOrd y = cmp x y == PLT {-# INLINE (<) #-} (>=) (NonTransitive.ProductOrd (DoubleX3# a1 a2 a3)) (NonTransitive.ProductOrd (DoubleX3# b1 b2 b3)) = isTrue# ((a1 >=## b1) `andI#` (a2 >=## b2) `andI#` (a3 >=## b3)) {-# INLINE (>=) #-} (<=) (NonTransitive.ProductOrd (DoubleX3# a1 a2 a3)) (NonTransitive.ProductOrd (DoubleX3# b1 b2 b3)) = isTrue# ((a1 <=## b1) `andI#` (a2 <=## b2) `andI#` (a3 <=## b3)) {-# INLINE (<=) #-} compare (NonTransitive.ProductOrd a) (NonTransitive.ProductOrd b) = NonTransitive.toOrdering $ cmp a b {-# INLINE compare #-} min (NonTransitive.ProductOrd (DoubleX3# a1 a2 a3)) (NonTransitive.ProductOrd (DoubleX3# b1 b2 b3)) = NonTransitive.ProductOrd ( DoubleX3# (if isTrue# (a1 >## b1) then b1 else a1) (if isTrue# (a2 >## b2) then b2 else a2) (if isTrue# (a3 >## b3) then b3 else a3) ) {-# INLINE min #-} max (NonTransitive.ProductOrd (DoubleX3# a1 a2 a3)) (NonTransitive.ProductOrd (DoubleX3# b1 b2 b3)) = NonTransitive.ProductOrd ( DoubleX3# (if isTrue# (a1 <## b1) then b1 else a1) (if isTrue# (a2 <## b2) then b2 else a2) (if isTrue# (a3 <## b3) then b3 else a3) ) {-# INLINE max #-} instance Ord (Partial.ProductOrd DoubleX3) where Partial.ProductOrd x > Partial.ProductOrd y = cmp x y == PGT {-# INLINE (>) #-} Partial.ProductOrd x < Partial.ProductOrd y = cmp x y == PLT {-# INLINE (<) #-} (>=) (Partial.ProductOrd (DoubleX3# a1 a2 a3)) (Partial.ProductOrd (DoubleX3# b1 b2 b3)) = isTrue# ((a1 >=## b1) `andI#` (a2 >=## b2) `andI#` (a3 >=## b3)) {-# INLINE (>=) #-} (<=) (Partial.ProductOrd (DoubleX3# a1 a2 a3)) (Partial.ProductOrd (DoubleX3# b1 b2 b3)) = isTrue# ((a1 <=## b1) `andI#` (a2 <=## b2) `andI#` (a3 <=## b3)) {-# INLINE (<=) #-} compare (Partial.ProductOrd a) (Partial.ProductOrd b) = Partial.toOrdering $ cmp a b {-# INLINE compare #-} min (Partial.ProductOrd (DoubleX3# a1 a2 a3)) (Partial.ProductOrd (DoubleX3# b1 b2 b3)) = Partial.ProductOrd ( DoubleX3# (if isTrue# (a1 >## b1) then b1 else a1) (if isTrue# (a2 >## b2) then b2 else a2) (if isTrue# (a3 >## b3) then b3 else a3) ) {-# INLINE min #-} max (Partial.ProductOrd (DoubleX3# a1 a2 a3)) (Partial.ProductOrd (DoubleX3# b1 b2 b3)) = Partial.ProductOrd ( DoubleX3# (if isTrue# (a1 <## b1) then b1 else a1) (if isTrue# (a2 <## b2) then b2 else a2) (if isTrue# (a3 <## b3) then b3 else a3) ) {-# INLINE max #-} instance Ord DoubleX3 where DoubleX3# a1 a2 a3 > DoubleX3# b1 b2 b3 | isTrue# (a1 >## b1) = True | isTrue# (a1 <## b1) = False | isTrue# (a2 >## b2) = True | isTrue# (a2 <## b2) = False | isTrue# (a3 >## b3) = True | otherwise = False {-# INLINE (>) #-} DoubleX3# a1 a2 a3 < DoubleX3# b1 b2 b3 | isTrue# (a1 <## b1) = True | isTrue# (a1 >## b1) = False | isTrue# (a2 <## b2) = True | isTrue# (a2 >## b2) = False | isTrue# (a3 <## b3) = True | otherwise = False {-# INLINE (<) #-} DoubleX3# a1 a2 a3 >= DoubleX3# b1 b2 b3 | isTrue# (a1 <## b1) = False | isTrue# (a1 >## b1) = True | isTrue# (a2 <## b2) = False | isTrue# (a2 >## b2) = True | isTrue# (a3 <## b3) = False | otherwise = True {-# INLINE (>=) #-} DoubleX3# a1 a2 a3 <= DoubleX3# b1 b2 b3 | isTrue# (a1 >## b1) = False | isTrue# (a1 <## b1) = True | isTrue# (a2 >## b2) = False | isTrue# (a2 <## b2) = True | isTrue# (a3 >## b3) = False | otherwise = True {-# INLINE (<=) #-} compare (DoubleX3# a1 a2 a3) (DoubleX3# b1 b2 b3) | isTrue# (a1 >## b1) = GT | isTrue# (a1 <## b1) = LT | isTrue# (a2 >## b2) = GT | isTrue# (a2 <## b2) = LT | isTrue# (a3 >## b3) = GT | isTrue# (a3 <## b3) = LT | otherwise = EQ {-# INLINE compare #-} -- | element-wise operations for vectors instance Num DoubleX3 where DoubleX3# a1 a2 a3 + DoubleX3# b1 b2 b3 = DoubleX3# ((+##) a1 b1) ((+##) a2 b2) ((+##) a3 b3) {-# INLINE (+) #-} DoubleX3# a1 a2 a3 - DoubleX3# b1 b2 b3 = DoubleX3# ((-##) a1 b1) ((-##) a2 b2) ((-##) a3 b3) {-# INLINE (-) #-} DoubleX3# a1 a2 a3 * DoubleX3# b1 b2 b3 = DoubleX3# ((*##) a1 b1) ((*##) a2 b2) ((*##) a3 b3) {-# INLINE (*) #-} negate (DoubleX3# a1 a2 a3) = DoubleX3# (negateDouble# a1) (negateDouble# a2) (negateDouble# a3) {-# INLINE negate #-} abs (DoubleX3# a1 a2 a3) = DoubleX3# (if isTrue# (a1 >=## 0.0##) then a1 else negateDouble# a1) (if isTrue# (a2 >=## 0.0##) then a2 else negateDouble# a2) (if isTrue# (a3 >=## 0.0##) then a3 else negateDouble# a3) {-# INLINE abs #-} signum (DoubleX3# a1 a2 a3) = DoubleX3# (if isTrue# (a1 >## 0.0##) then 1.0## else if isTrue# (a1 <## 0.0##) then -1.0## else 0.0## ) (if isTrue# (a2 >## 0.0##) then 1.0## else if isTrue# (a2 <## 0.0##) then -1.0## else 0.0## ) (if isTrue# (a3 >## 0.0##) then 1.0## else if isTrue# (a3 <## 0.0##) then -1.0## else 0.0## ) {-# INLINE signum #-} fromInteger n = case fromInteger n of D# x -> DoubleX3# x x x {-# INLINE fromInteger #-} instance Fractional DoubleX3 where DoubleX3# a1 a2 a3 / DoubleX3# b1 b2 b3 = DoubleX3# ((/##) a1 b1) ((/##) a2 b2) ((/##) a3 b3) {-# INLINE (/) #-} recip (DoubleX3# a1 a2 a3) = DoubleX3# ((/##) 1.0## a1) ((/##) 1.0## a2) ((/##) 1.0## a3) {-# INLINE recip #-} fromRational r = case fromRational r of D# x -> DoubleX3# x x x {-# INLINE fromRational #-} instance Floating DoubleX3 where pi = DoubleX3# 3.141592653589793238## 3.141592653589793238## 3.141592653589793238## {-# INLINE pi #-} exp (DoubleX3# a1 a2 a3) = DoubleX3# (expDouble# a1) (expDouble# a2) (expDouble# a3) {-# INLINE exp #-} log (DoubleX3# a1 a2 a3) = DoubleX3# (logDouble# a1) (logDouble# a2) (logDouble# a3) {-# INLINE log #-} sqrt (DoubleX3# a1 a2 a3) = DoubleX3# (sqrtDouble# a1) (sqrtDouble# a2) (sqrtDouble# a3) {-# INLINE sqrt #-} sin (DoubleX3# a1 a2 a3) = DoubleX3# (sinDouble# a1) (sinDouble# a2) (sinDouble# a3) {-# INLINE sin #-} cos (DoubleX3# a1 a2 a3) = DoubleX3# (cosDouble# a1) (cosDouble# a2) (cosDouble# a3) {-# INLINE cos #-} tan (DoubleX3# a1 a2 a3) = DoubleX3# (tanDouble# a1) (tanDouble# a2) (tanDouble# a3) {-# INLINE tan #-} asin (DoubleX3# a1 a2 a3) = DoubleX3# (asinDouble# a1) (asinDouble# a2) (asinDouble# a3) {-# INLINE asin #-} acos (DoubleX3# a1 a2 a3) = DoubleX3# (acosDouble# a1) (acosDouble# a2) (acosDouble# a3) {-# INLINE acos #-} atan (DoubleX3# a1 a2 a3) = DoubleX3# (atanDouble# a1) (atanDouble# a2) (atanDouble# a3) {-# INLINE atan #-} sinh (DoubleX3# a1 a2 a3) = DoubleX3# (sinhDouble# a1) (sinhDouble# a2) (sinhDouble# a3) {-# INLINE sinh #-} cosh (DoubleX3# a1 a2 a3) = DoubleX3# (coshDouble# a1) (coshDouble# a2) (coshDouble# a3) {-# INLINE cosh #-} tanh (DoubleX3# a1 a2 a3) = DoubleX3# (tanhDouble# a1) (tanhDouble# a2) (tanhDouble# a3) {-# INLINE tanh #-} DoubleX3# a1 a2 a3 ** DoubleX3# b1 b2 b3 = DoubleX3# ((**##) a1 b1) ((**##) a2 b2) ((**##) a3 b3) {-# INLINE (**) #-} logBase x y = log y / log x {-# INLINE logBase #-} asinh x = log (x + sqrt (1.0+x*x)) {-# INLINE asinh #-} acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0))) {-# INLINE acosh #-} atanh x = 0.5 * log ((1.0+x) / (1.0-x)) {-# INLINE atanh #-} -- offset in bytes is S times bigger than offset in prim elements, -- when S is power of two, this is equal to shift #define BOFF_TO_PRIMOFF(off) uncheckedIShiftRL# off 3# #define ELEM_N 3 instance PrimBytes DoubleX3 where getBytes (DoubleX3# a1 a2 a3) = case runRW# ( \s0 -> case newByteArray# (byteSize @DoubleX3 undefined) s0 of (# s1, marr #) -> case writeDoubleArray# marr 0# a1 s1 of s2 -> case writeDoubleArray# marr 1# a2 s2 of s3 -> case writeDoubleArray# marr 2# a3 s3 of s4 -> unsafeFreezeByteArray# marr s4 ) of (# _, a #) -> a {-# INLINE getBytes #-} fromBytes off arr | i <- BOFF_TO_PRIMOFF(off) = DoubleX3# (indexDoubleArray# arr i) (indexDoubleArray# arr (i +# 1#)) (indexDoubleArray# arr (i +# 2#)) {-# INLINE fromBytes #-} readBytes mba off s0 | i <- BOFF_TO_PRIMOFF(off) = case readDoubleArray# mba i s0 of (# s1, a1 #) -> case readDoubleArray# mba (i +# 1#) s1 of (# s2, a2 #) -> case readDoubleArray# mba (i +# 2#) s2 of (# s3, a3 #) -> (# s3, DoubleX3# a1 a2 a3 #) {-# INLINE readBytes #-} writeBytes mba off (DoubleX3# a1 a2 a3) s | i <- BOFF_TO_PRIMOFF(off) = writeDoubleArray# mba (i +# 2#) a3 ( writeDoubleArray# mba (i +# 1#) a2 ( writeDoubleArray# mba i a1 s )) {-# INLINE writeBytes #-} readAddr addr s0 = case readDoubleOffAddr# addr 0# s0 of (# s1, a1 #) -> case readDoubleOffAddr# addr 1# s1 of (# s2, a2 #) -> case readDoubleOffAddr# addr 2# s2 of (# s3, a3 #) -> (# s3, DoubleX3# a1 a2 a3 #) {-# INLINE readAddr #-} writeAddr (DoubleX3# a1 a2 a3) addr s = writeDoubleOffAddr# addr 2# a3 ( writeDoubleOffAddr# addr 1# a2 ( writeDoubleOffAddr# addr 0# a1 s )) {-# INLINE writeAddr #-} byteSize _ = byteSize @Double undefined *# ELEM_N# {-# INLINE byteSize #-} byteAlign _ = byteAlign @Double undefined {-# INLINE byteAlign #-} byteOffset _ = 0# {-# INLINE byteOffset #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba off | i <- off *# ELEM_N# = DoubleX3# (indexDoubleArray# ba i) (indexDoubleArray# ba (i +# 1#)) (indexDoubleArray# ba (i +# 2#)) {-# INLINE indexArray #-} readArray mba off s0 | i <- off *# ELEM_N# = case readDoubleArray# mba i s0 of (# s1, a1 #) -> case readDoubleArray# mba (i +# 1#) s1 of (# s2, a2 #) -> case readDoubleArray# mba (i +# 2#) s2 of (# s3, a3 #) -> (# s3, DoubleX3# a1 a2 a3 #) {-# INLINE readArray #-} writeArray mba off (DoubleX3# a1 a2 a3) s | i <- off *# ELEM_N# = writeDoubleArray# mba (i +# 2#) a3 ( writeDoubleArray# mba (i +# 1#) a2 ( writeDoubleArray# mba i a1 s )) {-# INLINE writeArray #-} instance PrimArray Double DoubleX3 where broadcast# (D# x) = DoubleX3# x x x {-# INLINE broadcast# #-} ix# 0# (DoubleX3# a1 _ _) = D# a1 ix# 1# (DoubleX3# _ a2 _) = D# a2 ix# 2# (DoubleX3# _ _ a3) = D# a3 ix# _ _ = undefined {-# INLINE ix# #-} gen# _ f s0 = case f s0 of (# s1, D# a1 #) -> case f s1 of (# s2, D# a2 #) -> case f s2 of (# s3, D# a3 #) -> (# s3, DoubleX3# a1 a2 a3 #) upd# _ 0# (D# q) (DoubleX3# _ y z) = DoubleX3# q y z upd# _ 1# (D# q) (DoubleX3# x _ z) = DoubleX3# x q z upd# _ 2# (D# q) (DoubleX3# x y _) = DoubleX3# x y q upd# _ _ _ x = x {-# INLINE upd# #-} withArrayContent# _ g x = g (CumulDims [ELEM_N, 1]) 0# (getBytes x) {-# INLINE withArrayContent# #-} offsetElems _ = 0# {-# INLINE offsetElems #-} uniqueOrCumulDims _ = Right (CumulDims [ELEM_N, 1]) {-# INLINE uniqueOrCumulDims #-} fromElems# _ off ba = DoubleX3# (indexDoubleArray# ba off) (indexDoubleArray# ba (off +# 1#)) (indexDoubleArray# ba (off +# 2#)) {-# INLINE fromElems# #-}
achirkin/easytensor
easytensor/src-base/Numeric/DataFrame/Internal/Backend/Family/DoubleX3.hs
bsd-3-clause
14,129
0
22
4,297
4,966
2,540
2,426
337
1
{-# LANGUAGE DeriveFunctor #-} module Database.Persist.File.Unique where import Data.Hashable import Data.Ratio import Data.Time.Calendar import Data.Time.Clock import Data.Time.LocalTime import Data.Fixed import Database.Persist.File.Base import Database.Persist.File.Directory -- Represents an entity with two information to avoid hash data UniqueHashPair = UniqueHashPair { first :: Int , second :: Int } deriving (Eq, Show) infixl 9 </>> type UniqueHashPath = FilePath -- Applies the hash after the given path: -- Eg: path/-59348937/764387 (</>>) :: FilePath -> UniqueHashPair -> UniqueHashPath (</>>) fp (UniqueHashPair p1 p2) = (fp </> show p1 </> show p2) -- Eg: path/-59348937/764387 -> path/-59348937 uniqueHashPathDir :: UniqueHashPath -> FilePath uniqueHashPathDir = dropFileName uniqueHashPair f (UniqueHashPair p1 p2) = f p1 p2 -- Returns the dbName for the given unique path uniqueDefToDBName = uniqueDef $ \_haskellName dbname fieldNames _attrs -> let name = getDBName dbname in name entityDefToUniqueRelPaths e = let entityDBName = getDBName $ entityDB e uniqueRelPaths = (entityDBName:) . map ((entityDBName </>) . uniqueDefToDBName) $ entityUniques e in uniqueRelPaths type Salt = Int saltOne, saltTwo :: Salt saltOne = 0 saltTwo = 1 -- Create a hash pair from the persist value hashPair :: (Hashable h) => h -> UniqueHashPair hashPair p = UniqueHashPair (hashWithSalt saltOne p) (hashWithSalt saltTwo p) instance Hashable PersistValue where hash = hashWithSalt saltOne hashWithSalt = hashPersistValue -- Converts a PersistValue and a given salt to a hash value value hashPersistValue s = persistValueAlg persistText persistByteString persistInt64 persistDouble persistRational persistBool persistDay persistTimeOfDay persistUTCTime persistNull persistList persistMap persistObjectId persistDbSpecific where persistText = hashWithSalt s persistByteString = hashWithSalt s persistInt64 = hashWithSalt s persistDouble = hashWithSalt s persistRational r = hashWithSalt s (numerator r, denominator r) persistBool = hashWithSalt s persistDay = hashWithSalt s . toModifiedJulianDay persistTimeOfDay t = hashWithSalt s (todHour t, todMin t, resolution $ todSec t) persistUTCTime t = hashWithSalt s (persistDay $ utctDay t, fromEnum $ utctDayTime t) persistNull = hashWithSalt s () persistList = hashWithSalt s persistMap = hashWithSalt s persistObjectId = hashWithSalt s persistDbSpecific = hashWithSalt s
andorp/file-persist
src/Database/Persist/File/Unique.hs
bsd-3-clause
2,546
0
14
453
608
328
280
66
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. {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE TypeFamilies #-} module Duckling.Regex.Types ( GroupMatch(..) ) where import Control.DeepSeq import Data.Hashable import Data.Text (Text) import GHC.Generics import Prelude import Duckling.Resolve (Resolve(..)) newtype GroupMatch = GroupMatch [Text] deriving (Eq, Generic, Hashable, Ord, Show, NFData) instance Resolve GroupMatch where type ResolvedValue GroupMatch = () resolve _ _ _ = Nothing
facebookincubator/duckling
Duckling/Regex/Types.hs
bsd-3-clause
728
0
6
114
136
83
53
17
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} module Del.Lib where import Control.Arrow (first) import Control.Applicative (liftA2) import Data.Function (fix) import Data.List (sortOn, groupBy) import Data.Monoid (Any(..)) import Data.Profunctor (dimap) import qualified Data.Set as S import qualified Data.MultiSet as MS import qualified Data.Map as M import Del.Syntax diffByT :: EOM -> EOM diffByT eom = map (\(Equation l r) -> Equation (d T l) (simplifyExp $ replace $ d T r)) eom where replace (Add e1 e2) = Add (replace e1) (replace e2) replace (Sub e1 e2) = Sub (replace e1) (replace e2) replace (Mul e1 e2) = Mul (replace e1) (replace e2) replace (Div e1 e2) = Div (replace e1) (replace e2) replace (Pow e1 e2) = Pow (replace e1) (replace e2) replace (Neg e) = Neg (replace e) replace e@(Sym n a ds) | d0 == ds = find e eom | T `MS.member` ds = let ds' = MS.toList (ds MS.\\ d0) in foldr d (find (Sym n a d0) eom) ds' | otherwise = e where d0 = MS.singleton T replace e = e find :: Exp -> EOM -> Exp find e = rhs . head . filter (\eq -> lhs eq == e) diffBy :: Coord -> EOM -> EOM diffBy i = map (\(Equation l r) -> Equation (d i l) (simplifyExp $ d i r)) d :: Coord -> Exp -> Exp d i (Num _) = Num 0.0 d i (Sym n a d) | i `S.member` a = Sym n a (MS.insert i d) | otherwise = Num 0.0 d i (Neg e) = Neg (d i e) d i (Mul e1 e2) = Add (Mul (d i e1) e2) (Mul e1 (d i e2)) d i (Div e1 e2) = Sub (Div (d i e1) e2) (Mul (Div e1 (Mul e2 e2)) (d i e2)) d i (Add e1 e2) = Add (d i e1) (d i e2) d i (Sub e1 e2) = Sub (d i e1) (d i e2) d i (Pow e1 (Num n)) | n /= 0 = Mul (Mul (Num n) (Pow e1 (Num $ n -1))) (d i e1) | otherwise = Num 0.0 d i (Pow e1 (Neg (Num n))) | n /= 0 = Mul (Mul (Neg (Num n)) (Pow e1 (Neg (Num $ n+1)))) (d i e1) | otherwise = Num 0.0 simplify :: EOM -> EOM simplify = map simplifyEquation simplifyEquation :: Equation -> Equation simplifyEquation (Equation l r) = Equation (simplifyExp l) (simplifyExp r) simplifyExp :: Exp -> Exp simplifyExp = buildup . compose . eval . flatten . expand . cleanup type Term = M.Map Exp Double travel :: (a -> (Bool, a)) -> a -> a travel worker = fix (\f e -> let (b,e') = worker e in if b then f e' else e) -- 無駄な項を消し, 構文要素を減らす cleanup :: Exp -- [Add, Sub, Mul, Div, Pow, Neg, Sym, Num] -> Exp -- [Add, Mul, Pow, Sym, Num] cleanup = travel worker where worker2 f = let g = first Any . worker in dimap (\(a,b)->(g a,g b)) (first getAny) (uncurry (liftA2 f)) m1 = Num (-1) worker (Add (Num 0) e) = (True, e) worker (Add e (Num 0)) = (True, e) worker (Add e1 e2) = worker2 Add (e1,e2) worker (Sub e1 e2) = (True, Add e1 (Mul m1 e2)) worker (Mul (Num 1) e) = (True, e) worker (Mul e (Num 1)) = (True, e) worker (Mul (Num 0) _) = (True, Num 0) worker (Mul _ (Num 0)) = (True, Num 0) worker (Mul e1 e2) = worker2 Mul (e1,e2) worker (Div e1 e2) = (True, Mul e1 (Pow e2 m1)) worker (Pow e1 (Num 1)) = (True, e1) worker (Pow _ (Num 0)) = (True, Num 1) worker (Pow e1 e2) = worker2 Pow (e1,e2) worker (Neg e) = (True, Mul m1 e) worker e = (False, e) -- 積の和の形にする expand :: Exp -> Exp expand = travel worker where worker2 f = let g = first Any . worker in dimap (\(a,b)->(g a,g b)) (first getAny) (uncurry (liftA2 f)) worker (Add e1 e2) = worker2 Add (e1,e2) worker (Mul e1 (Add e2 e3)) = (True, Add (Mul e1 e2) (Mul e1 e3)) worker (Mul (Add e1 e2) e3) = (True, Add (Mul e1 e3) (Mul e2 e3)) worker (Mul e1 e2) = worker2 Mul (e1,e2) worker (Pow (Mul e1 e2) e3) = (True, Mul (Pow e1 e3) (Pow e2 e3)) worker (Pow e1 (Add e2 e3)) = (True, Mul (Pow e1 e2) (Pow e1 e3)) worker (Pow e1 (Mul e2 e3)) = (True, Pow (Pow e1 e2) e3) worker (Pow e1 e2) = worker2 Pow (e1,e2) worker e = (False, e) flatten :: Exp -> [(Double, Term)] flatten (Add e1 e2) = flatten e1 ++ flatten e2 flatten (Mul e1 e2) = merge (flatten e1) (flatten e2) flatten (Pow e1@(Add _ _) (Num n)) = [(1, M.singleton e1 n)] flatten (Pow (Pow e1 (Num m)) (Num n)) = flatten $ Pow e1 (Num $ n * m) flatten (Pow e1 (Num n)) = [(1, M.singleton e1 n)] flatten s@Sym{} = [(1, M.singleton s 1.0)] flatten (Num x) = [(x, M.empty)] flatten _ = [] merge :: [(Double, Term)] -> [(Double, Term)] -> [(Double, Term)] merge e1 e2 = [foldr (\(a,t) (a',t')->(a*a', M.unionWith (+) t t')) (1,M.empty) $ e1++e2] -- 同じTermをまとめる eval :: [(Double,Term)] -> [(Double, Term)] eval = foldr (\xs acc -> eval' xs:acc) [] . groupBy (\x y -> snd x == snd y) . sortOn snd where eval' = (,) <$> sum . map fst <*> snd . head compose :: [(Double,Term)] -> Exp compose = foldl1 Add . map build where build (x,t) | x == 0 = Num 0 | M.null t = Num x | x == 1 = buildTerm t | otherwise = Mul (Num x) (buildTerm t) buildTerm = foldr1 Mul . M.foldrWithKey worker [] where worker e n acc | n == 0 = Num 1:acc | n == 1 = e:acc | otherwise = Pow e (Num n):acc buildup :: Exp -- [Add, Mul, Pow, Sym, Num] -> Exp -- [Add, Sub, Mul, Div, Pow, Neg, Sym, Num] buildup = travel worker where worker2 f = let g = first Any . worker in dimap (\(a,b)->(g a,g b)) (first getAny) (uncurry (liftA2 f)) worker (Add (Num 0) e) = (True, e) worker (Add e (Num 0)) = (True, e) worker (Add e1 (Neg e2)) = (True, Sub e1 e2) worker (Add e1 e2) = worker2 Add (e1,e2) worker (Sub e1 (Neg e2)) = (True, Add e1 e2) worker (Sub e1 e2) = worker2 Sub (e1,e2) worker (Mul (Num 1) e) = (True, e) worker (Mul e (Num 1)) = (True, e) worker (Mul (Num 0) _) = (True, Num 0) worker (Mul _ (Num 0)) = (True, Num 0) worker (Mul (Neg e1) e2) = (True, Neg (Mul e1 e2)) worker (Mul e1 (Neg e2)) = (True, Neg (Mul e1 e2)) worker (Mul e1 e2) = worker2 Mul (e1,e2) worker (Div (Neg e1) e2) = (True, Neg (Div e1 e2)) worker (Div e1 (Neg e2)) = (True, Neg (Div e1 e2)) worker (Div e1 e2) = worker2 Div (e1,e2) worker (Pow (Num 1) _) = (True, Num 1) worker (Pow _ (Num 0)) = (True, Num 1) worker (Pow (Num 0) _) = (True, Num 0) worker (Pow e1 e2) = worker2 Pow (e1,e2) worker (Neg (Neg e)) = (True, e) worker (Neg e) = Neg <$> worker e worker (Num n) | n < 0 = (True, Neg (Num $ negate n)) worker e = (False, e)
ishiy1993/mk-sode1
src/Del/Lib.hs
bsd-3-clause
6,647
0
15
1,903
3,855
1,986
1,869
141
24
----------------------------------------------------------------------------- -- | -- module : Control.Monad.Trans.State -- Copyright : (c) Evgeniy Permyakov 2010 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : permeakra@gmail.com -- Stability : experimental -- Portability : portable (haskell - 2010) -- this module implements lazy state monad: a monad, threading updateable state module Control.Monad.Trans.State.Lazy (StateT, runStateT, get, put) where import Control.Monad.Trans.Class import Control.Monad.IO.Class -- | threading state through computations newtype StateT s m a = StateT ( s -> m (s, a) ) stateT :: (s -> m (s,a) ) -> StateT s m a stateT = StateT -- | run stateful computation runStateT :: StateT s m a -> s -> m (s, a) runStateT (StateT f) s = f s instance Functor m => Functor (StateT s m) where fmap f (StateT c) = StateT $ \s -> fmap ( \(~(s',a)) -> (s', f a) ) $ c s instance Monad m => Monad (StateT s m) where return a = stateT $ \s -> return (s , a) m >>= k = stateT $ \s -> do ~(s',ma) <- runStateT m s runStateT (k ma) s' instance MonadTrans (StateT s) where lift m = stateT $ \s -> m >>= \a -> return (s,a) instance MonadIO m => MonadIO (StateT s m) where liftIO = lift . liftIO -- | extract value from context get :: Monad m => StateT s m s get = stateT $ \s -> return (s,s) -- | put value to context, overwriting previous one put :: Monad m => s -> StateT s m () put s = stateT $ \_ -> return (s, ())
permeakra/yamtl
Control/Monad/Trans/State/Lazy.hs
bsd-3-clause
1,525
0
14
329
525
286
239
23
1
{-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE Strict #-} module Graphics.Vulkan.MemoryManagement where import Graphics.Vulkan.Device( VkDevice(..) ) import Graphics.Vulkan.Buffer( VkBuffer(..) ) import Data.Word( Word64 , Word32 ) import Foreign.Ptr( Ptr , plusPtr ) import Foreign.Storable( Storable(..) ) import Data.Void( Void ) import Graphics.Vulkan.Memory( VkDeviceMemory(..) ) import Graphics.Vulkan.Image( VkImage(..) ) import Graphics.Vulkan.Core( VkResult(..) , VkDeviceSize(..) ) -- ** vkGetImageMemoryRequirements foreign import ccall "vkGetImageMemoryRequirements" vkGetImageMemoryRequirements :: VkDevice -> VkImage -> Ptr VkMemoryRequirements -> IO () data VkMemoryRequirements = VkMemoryRequirements{ vkSize :: VkDeviceSize , vkAlignment :: VkDeviceSize , vkMemoryTypeBits :: Word32 } deriving (Eq) instance Storable VkMemoryRequirements where sizeOf ~_ = 24 alignment ~_ = 8 peek ptr = VkMemoryRequirements <$> peek (ptr `plusPtr` 0) <*> peek (ptr `plusPtr` 8) <*> peek (ptr `plusPtr` 16) poke ptr poked = poke (ptr `plusPtr` 0) (vkSize (poked :: VkMemoryRequirements)) *> poke (ptr `plusPtr` 8) (vkAlignment (poked :: VkMemoryRequirements)) *> poke (ptr `plusPtr` 16) (vkMemoryTypeBits (poked :: VkMemoryRequirements)) -- ** vkGetBufferMemoryRequirements foreign import ccall "vkGetBufferMemoryRequirements" vkGetBufferMemoryRequirements :: VkDevice -> VkBuffer -> Ptr VkMemoryRequirements -> IO () -- ** vkBindBufferMemory foreign import ccall "vkBindBufferMemory" vkBindBufferMemory :: VkDevice -> VkBuffer -> VkDeviceMemory -> VkDeviceSize -> IO VkResult -- ** vkBindImageMemory foreign import ccall "vkBindImageMemory" vkBindImageMemory :: VkDevice -> VkImage -> VkDeviceMemory -> VkDeviceSize -> IO VkResult
oldmanmike/vulkan
src/Graphics/Vulkan/MemoryManagement.hs
bsd-3-clause
2,218
0
11
687
483
279
204
39
0
{-# LANGUAGE OverloadedStrings #-} module Network.PeyoTLS.Hello ( ClientHello(..), ServerHello(..), SessionId(..), CipherSuite(..), KeyExchange(..), BulkEncryption(..), CompressionMethod(..), SignAlg(..), HashAlg(..) ) where import Control.Applicative ((<$>), (<*>)) import Data.Word (Word8, Word16) import Numeric (showHex) import qualified Data.ByteString as BS import qualified Codec.Bytable.BigEndian as B import Network.PeyoTLS.Extension (Extension, SignAlg(..), HashAlg(..)) import Network.PeyoTLS.CipherSuite ( CipherSuite(..), KeyExchange(..), BulkEncryption(..)) data ClientHello = ClientHello (Word8, Word8) BS.ByteString SessionId [CipherSuite] [CompressionMethod] (Maybe [Extension]) | ClientHelloRaw BS.ByteString deriving Show instance B.Bytable ClientHello where decode = B.evalBytableM $ do (pv, r, sid) <- (,,) <$> ((,) <$> B.head <*> B.head) <*> B.take 32 <*> (B.take =<< B.take 1) cs <- flip B.list (B.take 2) =<< B.take 2 cm <- flip B.list (B.take 1) =<< B.take 1 nl <- B.null me <- if nl then return Nothing else Just <$> (flip B.list B.parse =<< B.take 2) return $ ClientHello pv r sid cs cm me encode = encodeCh encodeCh :: ClientHello -> BS.ByteString encodeCh (ClientHello (vmjr, vmnr) r sid css cms mel) = BS.concat [ B.encode vmjr, B.encode vmnr, B.encode r, B.addLen (undefined :: Word8) $ B.encode sid, B.addLen (undefined :: Word16) . BS.concat $ map B.encode css, B.addLen (undefined :: Word8) . BS.concat $ map B.encode cms, maybe "" (B.addLen (undefined :: Word16) . BS.concat . map B.encode) mel ] encodeCh (ClientHelloRaw bs) = bs data ServerHello = ServerHello (Word8, Word8) BS.ByteString SessionId CipherSuite CompressionMethod (Maybe [Extension]) | ServerHelloRaw BS.ByteString deriving Show instance B.Bytable ServerHello where decode = B.evalBytableM $ do (pv, r, sid) <- (,,) <$> ((,) <$> B.head <*> B.head) <*> B.take 32 <*> (B.take =<< B.take 1) cs <- B.take 2 cm <- B.take 1 e <- B.null me <- if e then return Nothing else do mel <- B.take 2 Just <$> B.list mel B.parse return $ ServerHello pv r sid cs cm me encode = encodeSh encodeSh :: ServerHello -> BS.ByteString encodeSh (ServerHello (vmjr, vmnr) r sid cs cm mes) = BS.concat [ B.encode vmjr, B.encode vmnr, B.encode r, B.addLen (undefined :: Word8) $ B.encode sid, B.encode cs, B.encode cm, maybe "" (B.addLen (undefined :: Word16) . BS.concat . map B.encode) mes ] encodeSh (ServerHelloRaw sh) = sh data CompressionMethod = CompressionMethodNull | CompressionMethodRaw Word8 deriving (Show, Eq) instance B.Bytable CompressionMethod where decode bs = case BS.unpack bs of [cm] -> Right $ case cm of 0 -> CompressionMethodNull _ -> CompressionMethodRaw cm _ -> Left "Hello.decodeCm" encode CompressionMethodNull = "\0" encode (CompressionMethodRaw cm) = BS.pack [cm] data SessionId = SessionId BS.ByteString instance Show SessionId where show (SessionId sid) = "(SessionID " ++ concatMap (`showHex` "") (BS.unpack sid) ++ ")" instance B.Bytable SessionId where decode = Right . SessionId encode (SessionId bs) = bs
YoshikuniJujo/forest
subprojects/tls-analysis/server/src/Network/PeyoTLS/Hello.hs
bsd-3-clause
3,120
46
16
540
1,333
714
619
79
1
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TypeFamilies, FlexibleInstances #-} -- | Interpreting a CFG derivation as a string in Japanese. -- That is, we generate a yield of a CFG derivation, -- this time in Japanese. -- -- <http://okmij.org/ftp/gengo/NASSLLI10/> -- module Lambda.CFGJ where import Lambda.CFG -- we shall re-use our earlier work -- | We represent each node in the derivation tree -- by a Japanese phrase or a Japanese "sentential form" -- (that is, a phrase with holes). Contrast with the EN -- interpreter in CFG.hs -- data JA a = JA { unJA :: TJ a } -- | A verb or a verb-like word (e.g., an i-adjective) require -- arguments of particular cases. We need a way for a verb -- to specify the desired case of its arguments. -- data Case = Nom | NomStrong | Acc case_particle :: Case -> String case_particle Nom = "は" case_particle NomStrong = "のことが" case_particle Acc = "を" -- | The type family TJ defines the types of -- sentential forms corresponding to syntactic categories. -- -- As we shall see in QCFGJ.hs, we are going to need -- high (raised) types of our NP. -- A verb will ask its argument to turn itself to the -- desired case. type SK = (String -> String) -> String type family TJ (a :: *) :: * type instance TJ S = String type instance TJ NP = Case -> SK type instance TJ VP = (Case -> SK) -> String type instance TJ TV = (Case -> SK) -> (Case -> SK) -> String -- | Auxiliary functions for the code below make_np :: String -> (Case -> SK) make_np str cas k = k (str ++ case_particle cas) make_tv :: String -> Case -> Case -> (Case -> SK) -> (Case -> SK) -> String make_tv str co cs o s = s cs (\sv -> o co (\ov -> sv ++ ov ++ str)) instance Symantics JA where john = JA (make_np "ジョンさん") mary = JA (make_np "メリさん") like = JA (make_tv "好きだ" NomStrong Nom) own = JA (make_tv "飼っている" Acc Nom) r2 (JA f) (JA x) = JA (f x) r1 (JA x) (JA f) = JA (f x) instance Show (JA S) where show = unJA -- | The translation is certainly different: "like" corresponds -- to an adjective in Japanese. sen1_ja = sen1 :: JA S
suhailshergill/liboleg
Lambda/CFGJ.hs
bsd-3-clause
2,187
0
12
496
507
285
222
31
1
{-# LANGUAGE TemplateHaskell, TypeOperators #-} module Network.Protocol.Http.Data where import Control.Category import Data.Char import Data.List import Data.List.Split import Data.Record.Label import Network.Protocol.Http.Status import Network.Protocol.Uri import Prelude hiding ((.), id, lookup) -- | List of HTTP request methods. data Method = OPTIONS | GET | HEAD | POST | PUT | DELETE | TRACE | CONNECT | OTHER String deriving (Show, Eq) -- | HTTP protocol version. data Version = Version {_major :: Int, _minor :: Int} deriving (Eq, Ord) type Key = String type Value = String -- | HTTP headers as mapping from keys to values. newtype Headers = Headers { unHeaders :: [(Key, Value)] } -- order seems to matter deriving Eq -- | Request specific part of HTTP messages. data Request = Request { __method :: Method, __uri :: String } deriving Eq -- | Response specific part of HTTP messages. data Response = Response { __status :: Status } deriving Eq -- | An HTTP message. The message body is *not* included. data Http a = Http { _headline :: a , _version :: Version , _headers :: Headers } deriving Eq -- | All recognized method constructors as a list. methods :: [Method] methods = [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT] -- | Create HTTP 1.0 version. http10 :: Version http10 = Version 1 0 -- | Create HTTP 1.1 version. http11 :: Version http11 = Version 1 1 -- | Create an empty set of headers. emptyHeaders :: Headers emptyHeaders = Headers [] -- | Create an empty HTTP request message. emptyRequest :: Http Request emptyRequest = Http (Request GET "") http11 emptyHeaders -- | Create an empty HTTP response message. emptyResponse :: Http Response emptyResponse = Http (Response OK) http11 emptyHeaders $(mkLabelsNoTypes [''Version, ''Request, ''Response, ''Http]) -- | Label to access the major part of the version. major :: Version :-> Int -- | Label to access the minor part of the version. minor :: Version :-> Int -- Internal helper labels. _uri :: Request :-> String _method :: Request :-> Method _status :: Response :-> Status -- | Label to access the header of an HTTP message. headers :: Http a :-> Headers -- | Label to access the version part of an HTTP message. version :: Http a :-> Version -- | Label to access the header line part of an HTTP message. headline :: Http a :-> a -- | Label to access the method part of an HTTP request message. method :: Http Request :-> Method method = _method . headline -- | Label to access the URI part of an HTTP request message. uri :: Http Request :-> String uri = _uri . headline -- | Label to access the URI part of an HTTP request message and access it as a -- true URI data type. asUri :: Http Request :-> Uri asUri = (toUri :<->: show) % uri -- | Label to access the status part of an HTTP response message. status :: Http Response :-> Status status = _status . headline -- | Normalize the capitalization of an HTTP header key. normalizeHeader :: Key -> Key normalizeHeader = intercalate "-" . map casing . splitOn "-" where casing "" = "" casing (x:xs) = toUpper x : map toLower xs -- | Generic lens to access an HTTP header field by key. header :: Key -> Http a :-> Maybe Value header key = lens (lookup (normalizeHeader key) . unHeaders . getL headers) (\x -> modL headers (Headers . alter (normalizeHeader key) x . unHeaders)) where alter :: Eq a => a -> Maybe b -> [(a, b)] -> [(a, b)] alter k v [] = maybe [] (\w -> (k, w):[]) v alter k v ((x, y):xs) | k == x = maybe xs (\w -> (k, w):xs) v | otherwise = (x, y) : alter k v xs
sebastiaanvisser/salvia-protocol
src/Network/Protocol/Http/Data.hs
bsd-3-clause
3,683
0
14
815
950
541
409
77
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE CPP #-} module Data.Store.Selection ( (.<) , (.<=) , (.>) , (.>=) , (./=) , (.==) , (.&&) , (.||) , not , all , all1D , any , any1D , IsSelection(..) , Selection ) where -------------------------------------------------------------------------------- import Prelude hiding (not, all, any) -------------------------------------------------------------------------------- import Data.Monoid ((<>)) import qualified Data.IntSet import qualified Data.List #if MIN_VERSION_containers(0,5,0) import qualified Data.IntMap.Strict as Data.IntMap import qualified Data.Map.Strict as Data.Map #else import qualified Data.IntMap import qualified Data.Map #endif -------------------------------------------------------------------------------- import qualified Data.Store.Internal.Type as I -------------------------------------------------------------------------------- moduleName :: String moduleName = "Data.Store.Selection" -- INTERFACE infix 4 .==, ./=, .<, .<=, .>=, .> infixr 3 .&& infixr 2 .|| -- | The expression (@not' sel@) is a selection that includes all values -- except those that match the selection @sel@. not :: IsSelection sel => sel tag krs irs ts -> Selection tag krs irs ts not = SelectionNot {-# INLINE not #-} -- | Selection that matches the intersection of all the selections in the -- list. -- -- NOTE: Expects nonempty list. all :: [Selection tag krs irs ts] -> Selection tag krs irs ts all [] = error $ moduleName <> ".all: empty list." all [s] = s all (s:rest) = Data.List.foldl' (.&&) s rest -- this way we do not have to intersect with "everything" {-# INLINE all #-} -- | The expression (@'Data.Store.Selection.all1D' d ss@) is equivalent to (@'Data.Store.Selection.all'' $ map ($ d) ss@). -- -- NOTE: Expects nonempty list. all1D :: (tag, n) -> [(tag, n) -> Selection tag krs irs ts] -> Selection tag krs irs ts all1D _ [] = error $ moduleName <> ".all1D: empty list." all1D d [h] = h d all1D d (h:rest) = Data.List.foldl' (\acc f -> acc .&& f d) (h d) rest -- this way we do not have to intersect with "everything" {-# INLINE all1D #-} -- | Selection that matches the union of all the selections in the -- list. -- -- NOTE: Expects nonempty list. any :: [Selection tag krs irs ts] -> Selection tag krs irs ts any [] = error $ moduleName <> ".any: empty list." any (x:xs) = Data.List.foldl' (.||) x xs {-# INLINE any #-} -- | The expression (@'Data.Store.Selection.any1D' d ss@) is equivalent to (@'Data.Store.Selection.any'' $ map ($ d) ss@). -- -- NOTE: Expects nonempty list. any1D :: (tag, n) -> [(tag, n) -> Selection tag krs irs ts] -> Selection tag krs irs ts any1D _ [] = error $ moduleName <> ".any1D: empty list." any1D d (x:xs) = Data.List.foldl' (\acc f -> acc .|| f d) (x d) xs {-# INLINE any1D #-} -- | The expression (@sDim .< c@) is a selection that includes value -- @x@ if and only if it is indexed in the @sDim@ dimension with a key @k@ -- such that @k < c@. -- -- Complexity of @'Data.Store.Selection.resolve'@: /O(log n + k)/ (.<) :: I.GetDimension n (I.Index irs ts) => (tag, n) -> I.DimensionType n irs ts -> Selection tag krs irs ts (.<) (_, n) = SelectionType . SelectionDimension n (Condition True False False) {-# INLINE (.<) #-} -- | The expression (@sDim .<= c@) is a selection that includes value -- @x@ if and only if it is indexed in the @sDim@ dimension with a key @k@ -- such that @k <= c@. -- -- Complexity of @'Data.Store.Selection.resolve'@: /O(log n + k)/ (.<=) :: I.GetDimension n (I.Index irs ts) => (tag, n) -> I.DimensionType n irs ts -> Selection tag krs irs ts (.<=) (_, n) = SelectionType . SelectionDimension n (Condition True True False) {-# INLINE (.<=) #-} -- | The expression (@sDim .> c@) is a selection that includes value -- @x@ if and only if it is indexed in the @sDim@ dimension with a key @k@ -- such that @k > c@. -- -- Complexity of @'Data.Store.Selection.resolve'@: /O(log n + k)/ (.>) :: I.GetDimension n (I.Index irs ts) => (tag, n) -> I.DimensionType n irs ts -> Selection tag krs irs ts (.>) (_, n) = SelectionType . SelectionDimension n (Condition False False True) {-# INLINE (.>) #-} -- | The expression (@sDim .>= c@) is a selection that includes value -- @x@ if and only if it is indexed in the @sDim@ dimension with a key @k@ -- such that @k >= c@. -- -- Complexity of @'Data.Store.Selection.resolve'@: /O(log n + k)/ (.>=) :: I.GetDimension n (I.Index irs ts) => (tag, n) -> I.DimensionType n irs ts -> Selection tag krs irs ts (.>=) (_, n) = SelectionType . SelectionDimension n (Condition False True True) {-# INLINE (.>=) #-} -- | The expression (@sDim ./= c@) is a selection that includes value -- @x@ if and only if it is indexed in the @sDim@ dimension with a key @k@ -- such that @k /= c@. -- -- Complexity of @'Data.Store.Selection.resolve'@: /O(n)/ (./=) :: I.GetDimension n (I.Index irs ts) => (tag, n) -> I.DimensionType n irs ts -> Selection tag krs irs ts (./=) (_, n) = SelectionType . SelectionDimension n (Condition True False True) {-# INLINE (./=) #-} -- | The expression (@sDim .== c@) is a selection that includes value -- @x@ if and only if it is indexed in the @sDim@ dimension with a key @k@ -- such that @k == c@. -- -- Complexity of @'Data.Store.Selection.resolve'@: /O(log n)/ (.==) :: I.GetDimension n (I.Index irs ts) => (tag, n) -> I.DimensionType n irs ts -> Selection tag krs irs ts (.==) (_, n) = SelectionType . SelectionDimension n (Condition False True False) {-# INLINE (.==) #-} -- | The expression (@s1 .&& s2@) is a selection that includes the -- intersection of the selections @s1@ and @s2@. -- -- Complexity of @'Data.Store.Selection.resolve'@: /O(c(s1) + c(s2) + s(s1) + s(s2)/ (.&&) :: (IsSelection s1, IsSelection s2) => s1 tag krs irs ts -> s2 tag krs irs ts -> Selection tag krs irs ts (.&&) = SelectionA {-# INLINE (.&&) #-} -- | The expression (@s1 .|| s2@) is a selection that includes the -- union of the selections @s1@ and @s2@. -- -- Complexity of @'Data.Store.Selection.resolve'@: /O(c(s1) + c(s2) + s(s1) + s(s2)/ (.||) :: (IsSelection s1, IsSelection s2) => s1 tag krs irs ts -> s2 tag krs irs ts -> Selection tag krs irs ts (.||) = SelectionO {-# INLINE (.||) #-} -- IMPLEMENTATION instance IsSelection Selection where resolve (SelectionType sel) s = resolve sel s resolve (SelectionA s1 s2) s = Data.IntSet.intersection (resolve s1 s) (resolve s2 s) resolve (SelectionO s1 s2) s = Data.IntSet.union (resolve s1 s) (resolve s2 s) resolve (SelectionNot sel) s@(I.Store vs _ _) = Data.IntSet.difference (Data.IntMap.keysSet vs) (resolve sel s) {-# INLINE resolve #-} instance IsSelection (SelectionDimension n) where resolve = resolveSD {-# INLINE resolve #-} resolveSD :: forall tag n krs irs ts v . SelectionDimension n tag krs irs ts -> I.Store tag krs irs ts v -> Data.IntSet.IntSet resolveSD (SelectionDimension _ (Condition False False False) _) _ = {-# SCC "resolveSD" #-} Data.IntSet.empty resolveSD (SelectionDimension _ (Condition True True True) _) (I.Store vs _ _) = {-# SCC "resolveSD" #-} Data.IntSet.fromList $ Data.IntMap.keys vs resolveSD (SelectionDimension n (Condition lt eq gt) v) (I.Store _ ix _) = {-# SCC "resolveSD" #-} go $! I.getDimension n ix where go (I.IndexDimensionO m) = m `seq` case Data.Map.splitLookup v m of (lk, ek, gk) -> (if lt then trO lk else Data.IntSet.empty) <> (if eq then trMaybeO ek else Data.IntSet.empty) <> (if gt then trO gk else Data.IntSet.empty) go (I.IndexDimensionM m) = m `seq` case Data.Map.splitLookup v m of (lk, ek, gk) -> (if lt then trM lk else Data.IntSet.empty) <> (if eq then trMaybeM ek else Data.IntSet.empty) <> (if gt then trM gk else Data.IntSet.empty) {-# INLINEABLE go #-} trO :: Data.Map.Map k Int -> Data.IntSet.IntSet trO xs = {-# SCC "resolveSD.trO" #-} Data.Map.foldl' ins Data.IntSet.empty xs where ins acc i = Data.IntSet.insert i acc {-# INLINE trO #-} trMaybeO :: Maybe Int -> Data.IntSet.IntSet trMaybeO (Just x) = Data.IntSet.singleton x trMaybeO _ = Data.IntSet.empty {-# INLINE trMaybeO #-} trM :: Data.Map.Map k Data.IntSet.IntSet -> Data.IntSet.IntSet trM = Data.Map.foldl' Data.IntSet.union Data.IntSet.empty {-# INLINE trM #-} trMaybeM :: Maybe Data.IntSet.IntSet -> Data.IntSet.IntSet trMaybeM (Just x) = x trMaybeM _ = Data.IntSet.empty {-# INLINE trMaybeM #-} {-# INLINE resolveSD #-} -- | TYPE data SelectionDimension n tag krs irs ts where SelectionDimension :: I.GetDimension n (I.Index irs ts) => n -> Condition -> I.DimensionType n irs ts -> SelectionDimension n tag krs irs ts data Selection tag krs irs ts where SelectionType :: IsSelection sel => sel tag krs irs ts -> Selection tag krs irs ts SelectionA :: (IsSelection s1, IsSelection s2) => s1 tag krs irs ts -> s2 tag krs irs ts -> Selection tag krs irs ts SelectionO :: (IsSelection s1, IsSelection s2) => s1 tag krs irs ts -> s2 tag krs irs ts -> Selection tag krs irs ts SelectionNot :: IsSelection sel => sel tag krs irs ts -> Selection tag krs irs ts data Condition = Condition !Bool !Bool !Bool class IsSelection sel where resolve :: sel tag krs irs ts -> I.Store tag krs irs ts v -> Data.IntSet.IntSet
Palmik/data-store
src/Data/Store/Selection.hs
bsd-3-clause
9,765
0
15
2,099
2,542
1,412
1,130
145
10
{-# LANGUAGE NamedFieldPuns, OverloadedStrings #-} module MusicPad.Env.Constant where import Prelude () import qualified Prelude as P import MPS.Env import Rika.Type c_pad_width = 9 :: Int c_pad_height = 15 :: Int c_square_radius :: RikaPrim c_square_radius = 0.95
nfjinjing/level5
src/MusicPad/Env/Constant.hs
bsd-3-clause
268
0
4
39
56
37
19
10
1
module Generics.GPAH.Date ( module Generics.GPAH.Date.Base ,module Generics.GPAH.Date.Analyze ,module Generics.GPAH.Date.PPrint ) where import Generics.GPAH.Date.Base import Generics.GPAH.Date.Analyze import Generics.GPAH.Date.PPrint
bezirg/gpah
src/Generics/GPAH/Date.hs
bsd-3-clause
279
0
5
62
54
39
15
7
0
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1997-1998 \section[BasicTypes]{Miscellanous types} This module defines a miscellaneously collection of very simple types that \begin{itemize} \item have no other obvious home \item don't depend on any other complicated types \item are used in more than one "part" of the compiler \end{itemize} -} {-# LANGUAGE DeriveDataTypeable #-} module BasicTypes( Version, bumpVersion, initialVersion, LeftOrRight(..), pickLR, ConTag, ConTagZ, fIRST_TAG, Arity, RepArity, Alignment, FunctionOrData(..), WarningTxt(..), StringLiteral(..), Fixity(..), FixityDirection(..), defaultFixity, maxPrecedence, minPrecedence, negateFixity, funTyFixity, compareFixity, RecFlag(..), isRec, isNonRec, boolToRecFlag, Origin(..), isGenerated, RuleName, pprRuleName, TopLevelFlag(..), isTopLevel, isNotTopLevel, DerivStrategy(..), OverlapFlag(..), OverlapMode(..), setOverlapModeMaybe, hasOverlappingFlag, hasOverlappableFlag, hasIncoherentFlag, Boxity(..), isBoxed, TyPrec(..), maybeParen, TupleSort(..), tupleSortBoxity, boxityTupleSort, tupleParens, sumParens, pprAlternative, -- ** The OneShotInfo type OneShotInfo(..), noOneShotInfo, hasNoOneShotInfo, isOneShotInfo, bestOneShot, worstOneShot, OccInfo(..), seqOccInfo, zapFragileOcc, isOneOcc, isDeadOcc, isStrongLoopBreaker, isWeakLoopBreaker, isNoOcc, strongLoopBreaker, weakLoopBreaker, InsideLam, insideLam, notInsideLam, OneBranch, oneBranch, notOneBranch, InterestingCxt, EP(..), DefMethSpec(..), SwapFlag(..), flipSwap, unSwap, isSwapped, CompilerPhase(..), PhaseNum, Activation(..), isActive, isActiveIn, competesWith, isNeverActive, isAlwaysActive, isEarlyActive, RuleMatchInfo(..), isConLike, isFunLike, InlineSpec(..), isEmptyInlineSpec, InlinePragma(..), defaultInlinePragma, alwaysInlinePragma, neverInlinePragma, dfunInlinePragma, isDefaultInlinePragma, isInlinePragma, isInlinablePragma, isAnyInlinePragma, inlinePragmaSpec, inlinePragmaSat, inlinePragmaActivation, inlinePragmaRuleMatchInfo, setInlinePragmaActivation, setInlinePragmaRuleMatchInfo, SuccessFlag(..), succeeded, failed, successIf, FractionalLit(..), negateFractionalLit, integralFractionalLit, SourceText, IntWithInf, infinity, treatZeroAsInf, mkIntWithInf, intGtLimit ) where import FastString import Outputable import SrcLoc ( Located,unLoc ) import StaticFlags( opt_PprStyle_Debug ) import Data.Data hiding (Fixity) import Data.Function (on) {- ************************************************************************ * * Binary choice * * ************************************************************************ -} data LeftOrRight = CLeft | CRight deriving( Eq, Data ) pickLR :: LeftOrRight -> (a,a) -> a pickLR CLeft (l,_) = l pickLR CRight (_,r) = r instance Outputable LeftOrRight where ppr CLeft = text "Left" ppr CRight = text "Right" {- ************************************************************************ * * \subsection[Arity]{Arity} * * ************************************************************************ -} -- | The number of value arguments that can be applied to a value before it does -- "real work". So: -- fib 100 has arity 0 -- \x -> fib x has arity 1 -- See also Note [Definition of arity] in CoreArity type Arity = Int -- | Representation Arity -- -- The number of represented arguments that can be applied to a value before it does -- "real work". So: -- fib 100 has representation arity 0 -- \x -> fib x has representation arity 1 -- \(# x, y #) -> fib (x + y) has representation arity 2 type RepArity = Int {- ************************************************************************ * * Constructor tags * * ************************************************************************ -} -- | Constructor Tag -- -- Type of the tags associated with each constructor possibility or superclass -- selector type ConTag = Int -- | A *zero-indexed* constructor tag type ConTagZ = Int fIRST_TAG :: ConTag -- ^ Tags are allocated from here for real constructors -- or for superclass selectors fIRST_TAG = 1 {- ************************************************************************ * * \subsection[Alignment]{Alignment} * * ************************************************************************ -} type Alignment = Int -- align to next N-byte boundary (N must be a power of 2). {- ************************************************************************ * * One-shot information * * ************************************************************************ -} -- | If the 'Id' is a lambda-bound variable then it may have lambda-bound -- variable info. Sometimes we know whether the lambda binding this variable -- is a \"one-shot\" lambda; that is, whether it is applied at most once. -- -- This information may be useful in optimisation, as computations may -- safely be floated inside such a lambda without risk of duplicating -- work. data OneShotInfo = NoOneShotInfo -- ^ No information | ProbOneShot -- ^ The lambda is probably applied at most once -- See Note [Computing one-shot info, and ProbOneShot] in Demand | OneShotLam -- ^ The lambda is applied at most once. deriving (Eq) -- | It is always safe to assume that an 'Id' has no lambda-bound variable information noOneShotInfo :: OneShotInfo noOneShotInfo = NoOneShotInfo isOneShotInfo, hasNoOneShotInfo :: OneShotInfo -> Bool isOneShotInfo OneShotLam = True isOneShotInfo _ = False hasNoOneShotInfo NoOneShotInfo = True hasNoOneShotInfo _ = False worstOneShot, bestOneShot :: OneShotInfo -> OneShotInfo -> OneShotInfo worstOneShot NoOneShotInfo _ = NoOneShotInfo worstOneShot ProbOneShot NoOneShotInfo = NoOneShotInfo worstOneShot ProbOneShot _ = ProbOneShot worstOneShot OneShotLam os = os bestOneShot NoOneShotInfo os = os bestOneShot ProbOneShot OneShotLam = OneShotLam bestOneShot ProbOneShot _ = ProbOneShot bestOneShot OneShotLam _ = OneShotLam pprOneShotInfo :: OneShotInfo -> SDoc pprOneShotInfo NoOneShotInfo = empty pprOneShotInfo ProbOneShot = text "ProbOneShot" pprOneShotInfo OneShotLam = text "OneShot" instance Outputable OneShotInfo where ppr = pprOneShotInfo {- ************************************************************************ * * Swap flag * * ************************************************************************ -} data SwapFlag = NotSwapped -- Args are: actual, expected | IsSwapped -- Args are: expected, actual instance Outputable SwapFlag where ppr IsSwapped = text "Is-swapped" ppr NotSwapped = text "Not-swapped" flipSwap :: SwapFlag -> SwapFlag flipSwap IsSwapped = NotSwapped flipSwap NotSwapped = IsSwapped isSwapped :: SwapFlag -> Bool isSwapped IsSwapped = True isSwapped NotSwapped = False unSwap :: SwapFlag -> (a->a->b) -> a -> a -> b unSwap NotSwapped f a b = f a b unSwap IsSwapped f a b = f b a {- ************************************************************************ * * \subsection[FunctionOrData]{FunctionOrData} * * ************************************************************************ -} data FunctionOrData = IsFunction | IsData deriving (Eq, Ord, Data) instance Outputable FunctionOrData where ppr IsFunction = text "(function)" ppr IsData = text "(data)" {- ************************************************************************ * * \subsection[Version]{Module and identifier version numbers} * * ************************************************************************ -} type Version = Int bumpVersion :: Version -> Version bumpVersion v = v+1 initialVersion :: Version initialVersion = 1 {- ************************************************************************ * * Deprecations * * ************************************************************************ -} -- | A String Literal in the source, including its original raw format for use by -- source to source manipulation tools. data StringLiteral = StringLiteral { sl_st :: SourceText, -- literal raw source. -- See not [Literal source text] sl_fs :: FastString -- literal string value } deriving Data instance Eq StringLiteral where (StringLiteral _ a) == (StringLiteral _ b) = a == b -- | Warning Text -- -- reason/explanation from a WARNING or DEPRECATED pragma data WarningTxt = WarningTxt (Located SourceText) [Located StringLiteral] | DeprecatedTxt (Located SourceText) [Located StringLiteral] deriving (Eq, Data) instance Outputable WarningTxt where ppr (WarningTxt _ ws) = doubleQuotes (vcat (map (ftext . sl_fs . unLoc) ws)) ppr (DeprecatedTxt _ ds) = text "Deprecated:" <+> doubleQuotes (vcat (map (ftext . sl_fs . unLoc) ds)) {- ************************************************************************ * * Rules * * ************************************************************************ -} type RuleName = FastString pprRuleName :: RuleName -> SDoc pprRuleName rn = doubleQuotes (ftext rn) {- ************************************************************************ * * \subsection[Fixity]{Fixity info} * * ************************************************************************ -} ------------------------ data Fixity = Fixity SourceText Int FixityDirection -- Note [Pragma source text] deriving Data instance Outputable Fixity where ppr (Fixity _ prec dir) = hcat [ppr dir, space, int prec] instance Eq Fixity where -- Used to determine if two fixities conflict (Fixity _ p1 dir1) == (Fixity _ p2 dir2) = p1==p2 && dir1 == dir2 ------------------------ data FixityDirection = InfixL | InfixR | InfixN deriving (Eq, Data) instance Outputable FixityDirection where ppr InfixL = text "infixl" ppr InfixR = text "infixr" ppr InfixN = text "infix" ------------------------ maxPrecedence, minPrecedence :: Int maxPrecedence = 9 minPrecedence = 0 defaultFixity :: Fixity defaultFixity = Fixity (show maxPrecedence) maxPrecedence InfixL negateFixity, funTyFixity :: Fixity -- Wired-in fixities negateFixity = Fixity "6" 6 InfixL -- Fixity of unary negate funTyFixity = Fixity "0" 0 InfixR -- Fixity of '->' {- Consider \begin{verbatim} a `op1` b `op2` c \end{verbatim} @(compareFixity op1 op2)@ tells which way to arrange appication, or whether there's an error. -} compareFixity :: Fixity -> Fixity -> (Bool, -- Error please Bool) -- Associate to the right: a op1 (b op2 c) compareFixity (Fixity _ prec1 dir1) (Fixity _ prec2 dir2) = case prec1 `compare` prec2 of GT -> left LT -> right EQ -> case (dir1, dir2) of (InfixR, InfixR) -> right (InfixL, InfixL) -> left _ -> error_please where right = (False, True) left = (False, False) error_please = (True, False) {- ************************************************************************ * * \subsection[Top-level/local]{Top-level/not-top level flag} * * ************************************************************************ -} data TopLevelFlag = TopLevel | NotTopLevel isTopLevel, isNotTopLevel :: TopLevelFlag -> Bool isNotTopLevel NotTopLevel = True isNotTopLevel TopLevel = False isTopLevel TopLevel = True isTopLevel NotTopLevel = False instance Outputable TopLevelFlag where ppr TopLevel = text "<TopLevel>" ppr NotTopLevel = text "<NotTopLevel>" {- ************************************************************************ * * Boxity flag * * ************************************************************************ -} data Boxity = Boxed | Unboxed deriving( Eq, Data ) isBoxed :: Boxity -> Bool isBoxed Boxed = True isBoxed Unboxed = False instance Outputable Boxity where ppr Boxed = text "Boxed" ppr Unboxed = text "Unboxed" {- ************************************************************************ * * Recursive/Non-Recursive flag * * ************************************************************************ -} -- | Recursivity Flag data RecFlag = Recursive | NonRecursive deriving( Eq, Data ) isRec :: RecFlag -> Bool isRec Recursive = True isRec NonRecursive = False isNonRec :: RecFlag -> Bool isNonRec Recursive = False isNonRec NonRecursive = True boolToRecFlag :: Bool -> RecFlag boolToRecFlag True = Recursive boolToRecFlag False = NonRecursive instance Outputable RecFlag where ppr Recursive = text "Recursive" ppr NonRecursive = text "NonRecursive" {- ************************************************************************ * * Code origin * * ************************************************************************ -} data Origin = FromSource | Generated deriving( Eq, Data ) isGenerated :: Origin -> Bool isGenerated Generated = True isGenerated FromSource = False instance Outputable Origin where ppr FromSource = text "FromSource" ppr Generated = text "Generated" {- ************************************************************************ * * Deriving strategies * * ************************************************************************ -} -- | Which technique the user explicitly requested when deriving an instance. data DerivStrategy -- See Note [Deriving strategies] in TcDeriv = DerivStock -- ^ GHC's \"standard\" strategy, which is to implement a -- custom instance for the data type. This only works for -- certain types that GHC knows about (e.g., 'Eq', 'Show', -- 'Functor' when @-XDeriveFunctor@ is enabled, etc.) | DerivAnyclass -- ^ @-XDeriveAnyClass@ | DerivNewtype -- ^ @-XGeneralizedNewtypeDeriving@ deriving (Eq, Data) instance Outputable DerivStrategy where ppr DerivStock = text "stock" ppr DerivAnyclass = text "anyclass" ppr DerivNewtype = text "newtype" {- ************************************************************************ * * Instance overlap flag * * ************************************************************************ -} -- | The semantics allowed for overlapping instances for a particular -- instance. See Note [Safe Haskell isSafeOverlap] (in `InstEnv.hs`) for a -- explanation of the `isSafeOverlap` field. -- -- - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpen' @'\{-\# OVERLAPPABLE'@ or -- @'\{-\# OVERLAPPING'@ or -- @'\{-\# OVERLAPS'@ or -- @'\{-\# INCOHERENT'@, -- 'ApiAnnotation.AnnClose' @`\#-\}`@, -- For details on above see note [Api annotations] in ApiAnnotation data OverlapFlag = OverlapFlag { overlapMode :: OverlapMode , isSafeOverlap :: Bool } deriving (Eq, Data) setOverlapModeMaybe :: OverlapFlag -> Maybe OverlapMode -> OverlapFlag setOverlapModeMaybe f Nothing = f setOverlapModeMaybe f (Just m) = f { overlapMode = m } hasIncoherentFlag :: OverlapMode -> Bool hasIncoherentFlag mode = case mode of Incoherent _ -> True _ -> False hasOverlappableFlag :: OverlapMode -> Bool hasOverlappableFlag mode = case mode of Overlappable _ -> True Overlaps _ -> True Incoherent _ -> True _ -> False hasOverlappingFlag :: OverlapMode -> Bool hasOverlappingFlag mode = case mode of Overlapping _ -> True Overlaps _ -> True Incoherent _ -> True _ -> False data OverlapMode -- See Note [Rules for instance lookup] in InstEnv = NoOverlap SourceText -- See Note [Pragma source text] -- ^ This instance must not overlap another `NoOverlap` instance. -- However, it may be overlapped by `Overlapping` instances, -- and it may overlap `Overlappable` instances. | Overlappable SourceText -- See Note [Pragma source text] -- ^ Silently ignore this instance if you find a -- more specific one that matches the constraint -- you are trying to resolve -- -- Example: constraint (Foo [Int]) -- instance Foo [Int] -- instance {-# OVERLAPPABLE #-} Foo [a] -- -- Since the second instance has the Overlappable flag, -- the first instance will be chosen (otherwise -- its ambiguous which to choose) | Overlapping SourceText -- See Note [Pragma source text] -- ^ Silently ignore any more general instances that may be -- used to solve the constraint. -- -- Example: constraint (Foo [Int]) -- instance {-# OVERLAPPING #-} Foo [Int] -- instance Foo [a] -- -- Since the first instance has the Overlapping flag, -- the second---more general---instance will be ignored (otherwise -- it is ambiguous which to choose) | Overlaps SourceText -- See Note [Pragma source text] -- ^ Equivalent to having both `Overlapping` and `Overlappable` flags. | Incoherent SourceText -- See Note [Pragma source text] -- ^ Behave like Overlappable and Overlapping, and in addition pick -- an an arbitrary one if there are multiple matching candidates, and -- don't worry about later instantiation -- -- Example: constraint (Foo [b]) -- instance {-# INCOHERENT -} Foo [Int] -- instance Foo [a] -- Without the Incoherent flag, we'd complain that -- instantiating 'b' would change which instance -- was chosen. See also note [Incoherent instances] in InstEnv deriving (Eq, Data) instance Outputable OverlapFlag where ppr flag = ppr (overlapMode flag) <+> pprSafeOverlap (isSafeOverlap flag) instance Outputable OverlapMode where ppr (NoOverlap _) = empty ppr (Overlappable _) = text "[overlappable]" ppr (Overlapping _) = text "[overlapping]" ppr (Overlaps _) = text "[overlap ok]" ppr (Incoherent _) = text "[incoherent]" pprSafeOverlap :: Bool -> SDoc pprSafeOverlap True = text "[safe]" pprSafeOverlap False = empty {- ************************************************************************ * * Type precedence * * ************************************************************************ -} data TyPrec -- See Note [Prededence in types] = TopPrec -- No parens | FunPrec -- Function args; no parens for tycon apps | TyOpPrec -- Infix operator | TyConPrec -- Tycon args; no parens for atomic deriving( Eq, Ord ) maybeParen :: TyPrec -> TyPrec -> SDoc -> SDoc maybeParen ctxt_prec inner_prec pretty | ctxt_prec < inner_prec = pretty | otherwise = parens pretty {- ************************************************************************ * * Tuples * * ************************************************************************ -} data TupleSort = BoxedTuple | UnboxedTuple | ConstraintTuple deriving( Eq, Data ) tupleSortBoxity :: TupleSort -> Boxity tupleSortBoxity BoxedTuple = Boxed tupleSortBoxity UnboxedTuple = Unboxed tupleSortBoxity ConstraintTuple = Boxed boxityTupleSort :: Boxity -> TupleSort boxityTupleSort Boxed = BoxedTuple boxityTupleSort Unboxed = UnboxedTuple tupleParens :: TupleSort -> SDoc -> SDoc tupleParens BoxedTuple p = parens p tupleParens UnboxedTuple p = text "(#" <+> p <+> ptext (sLit "#)") tupleParens ConstraintTuple p -- In debug-style write (% Eq a, Ord b %) | opt_PprStyle_Debug = text "(%" <+> p <+> ptext (sLit "%)") | otherwise = parens p {- ************************************************************************ * * Sums * * ************************************************************************ -} sumParens :: SDoc -> SDoc sumParens p = ptext (sLit "(#") <+> p <+> ptext (sLit "#)") -- | Pretty print an alternative in an unboxed sum e.g. "| a | |". pprAlternative :: (a -> SDoc) -- ^ The pretty printing function to use -> a -- ^ The things to be pretty printed -> ConTag -- ^ Alternative (one-based) -> Arity -- ^ Arity -> SDoc -- ^ 'SDoc' where the alternative havs been pretty -- printed and finally packed into a paragraph. pprAlternative pp x alt arity = fsep (replicate (alt - 1) vbar ++ [pp x] ++ replicate (arity - alt - 1) vbar) {- ************************************************************************ * * \subsection[Generic]{Generic flag} * * ************************************************************************ This is the "Embedding-Projection pair" datatype, it contains two pieces of code (normally either RenamedExpr's or Id's) If we have a such a pair (EP from to), the idea is that 'from' and 'to' represents functions of type from :: T -> Tring to :: Tring -> T And we should have to (from x) = x T and Tring are arbitrary, but typically T is the 'main' type while Tring is the 'representation' type. (This just helps us remember whether to use 'from' or 'to'. -} -- | Embedding Projection pair data EP a = EP { fromEP :: a, -- :: T -> Tring toEP :: a } -- :: Tring -> T {- Embedding-projection pairs are used in several places: First of all, each type constructor has an EP associated with it, the code in EP converts (datatype T) from T to Tring and back again. Secondly, when we are filling in Generic methods (in the typechecker, tcMethodBinds), we are constructing bimaps by induction on the structure of the type of the method signature. ************************************************************************ * * \subsection{Occurrence information} * * ************************************************************************ This data type is used exclusively by the simplifier, but it appears in a SubstResult, which is currently defined in VarEnv, which is pretty near the base of the module hierarchy. So it seemed simpler to put the defn of OccInfo here, safely at the bottom -} -- | identifier Occurrence Information data OccInfo = NoOccInfo -- ^ There are many occurrences, or unknown occurrences | IAmDead -- ^ Marks unused variables. Sometimes useful for -- lambda and case-bound variables. | OneOcc !InsideLam !OneBranch !InterestingCxt -- ^ Occurs exactly once, not inside a rule -- | This identifier breaks a loop of mutually recursive functions. The field -- marks whether it is only a loop breaker due to a reference in a rule | IAmALoopBreaker -- Note [LoopBreaker OccInfo] !RulesOnly deriving (Eq) type RulesOnly = Bool {- Note [LoopBreaker OccInfo] ~~~~~~~~~~~~~~~~~~~~~~~~~~ IAmALoopBreaker True <=> A "weak" or rules-only loop breaker Do not preInlineUnconditionally IAmALoopBreaker False <=> A "strong" loop breaker Do not inline at all See OccurAnal Note [Weak loop breakers] -} isNoOcc :: OccInfo -> Bool isNoOcc NoOccInfo = True isNoOcc _ = False seqOccInfo :: OccInfo -> () seqOccInfo occ = occ `seq` () ----------------- -- | Interesting Context type InterestingCxt = Bool -- True <=> Function: is applied -- Data value: scrutinised by a case with -- at least one non-DEFAULT branch ----------------- -- | Inside Lambda type InsideLam = Bool -- True <=> Occurs inside a non-linear lambda -- Substituting a redex for this occurrence is -- dangerous because it might duplicate work. insideLam, notInsideLam :: InsideLam insideLam = True notInsideLam = False ----------------- type OneBranch = Bool -- True <=> Occurs in only one case branch -- so no code-duplication issue to worry about oneBranch, notOneBranch :: OneBranch oneBranch = True notOneBranch = False strongLoopBreaker, weakLoopBreaker :: OccInfo strongLoopBreaker = IAmALoopBreaker False weakLoopBreaker = IAmALoopBreaker True isWeakLoopBreaker :: OccInfo -> Bool isWeakLoopBreaker (IAmALoopBreaker _) = True isWeakLoopBreaker _ = False isStrongLoopBreaker :: OccInfo -> Bool isStrongLoopBreaker (IAmALoopBreaker False) = True -- Loop-breaker that breaks a non-rule cycle isStrongLoopBreaker _ = False isDeadOcc :: OccInfo -> Bool isDeadOcc IAmDead = True isDeadOcc _ = False isOneOcc :: OccInfo -> Bool isOneOcc (OneOcc {}) = True isOneOcc _ = False zapFragileOcc :: OccInfo -> OccInfo zapFragileOcc (OneOcc {}) = NoOccInfo zapFragileOcc occ = occ instance Outputable OccInfo where -- only used for debugging; never parsed. KSW 1999-07 ppr NoOccInfo = empty ppr (IAmALoopBreaker ro) = text "LoopBreaker" <> if ro then char '!' else empty ppr IAmDead = text "Dead" ppr (OneOcc inside_lam one_branch int_cxt) = text "Once" <> pp_lam <> pp_br <> pp_args where pp_lam | inside_lam = char 'L' | otherwise = empty pp_br | one_branch = empty | otherwise = char '*' pp_args | int_cxt = char '!' | otherwise = empty {- ************************************************************************ * * Default method specfication * * ************************************************************************ The DefMethSpec enumeration just indicates what sort of default method is used for a class. It is generated from source code, and present in interface files; it is converted to Class.DefMethInfo before begin put in a Class object. -} -- | Default Method Specification data DefMethSpec ty = VanillaDM -- Default method given with polymorphic code | GenericDM ty -- Default method given with code of this type instance Outputable (DefMethSpec ty) where ppr VanillaDM = text "{- Has default method -}" ppr (GenericDM {}) = text "{- Has generic default method -}" {- ************************************************************************ * * \subsection{Success flag} * * ************************************************************************ -} data SuccessFlag = Succeeded | Failed instance Outputable SuccessFlag where ppr Succeeded = text "Succeeded" ppr Failed = text "Failed" successIf :: Bool -> SuccessFlag successIf True = Succeeded successIf False = Failed succeeded, failed :: SuccessFlag -> Bool succeeded Succeeded = True succeeded Failed = False failed Succeeded = False failed Failed = True {- ************************************************************************ * * \subsection{Source Text} * * ************************************************************************ Keeping Source Text for source to source conversions Note [Pragma source text] ~~~~~~~~~~~~~~~~~~~~~~~~~ The lexer does a case-insensitive match for pragmas, as well as accepting both UK and US spelling variants. So {-# SPECIALISE #-} {-# SPECIALIZE #-} {-# Specialize #-} will all generate ITspec_prag token for the start of the pragma. In order to be able to do source to source conversions, the original source text for the token needs to be preserved, hence the `SourceText` field. So the lexer will then generate ITspec_prag "{ -# SPECIALISE" ITspec_prag "{ -# SPECIALIZE" ITspec_prag "{ -# Specialize" for the cases above. [without the space between '{' and '-', otherwise this comment won't parse] Note [Literal source text] ~~~~~~~~~~~~~~~~~~~~~~~~~~ The lexer/parser converts literals from their original source text versions to an appropriate internal representation. This is a problem for tools doing source to source conversions, so the original source text is stored in literals where this can occur. Motivating examples for HsLit HsChar '\n' == '\x20` HsCharPrim '\x41`# == `A` HsString "\x20\x41" == " A" HsStringPrim "\x20"# == " "# HsInt 001 == 1 HsIntPrim 002# == 2# HsWordPrim 003## == 3## HsInt64Prim 004## == 4## HsWord64Prim 005## == 5## HsInteger 006 == 6 For OverLitVal HsIntegral 003 == 0x003 HsIsString "\x41nd" == "And" -} type SourceText = String -- Note [Literal source text],[Pragma source text] {- ************************************************************************ * * \subsection{Activation} * * ************************************************************************ When a rule or inlining is active -} -- | Phase Number type PhaseNum = Int -- Compilation phase -- Phases decrease towards zero -- Zero is the last phase data CompilerPhase = Phase PhaseNum | InitialPhase -- The first phase -- number = infinity! instance Outputable CompilerPhase where ppr (Phase n) = int n ppr InitialPhase = text "InitialPhase" -- See note [Pragma source text] data Activation = NeverActive | AlwaysActive | ActiveBefore SourceText PhaseNum -- Active only *strictly before* this phase | ActiveAfter SourceText PhaseNum -- Active in this phase and later deriving( Eq, Data ) -- Eq used in comparing rules in HsDecls -- | Rule Match Information data RuleMatchInfo = ConLike -- See Note [CONLIKE pragma] | FunLike deriving( Eq, Data, Show ) -- Show needed for Lexer.x data InlinePragma -- Note [InlinePragma] = InlinePragma { inl_src :: SourceText -- Note [Pragma source text] , inl_inline :: InlineSpec , inl_sat :: Maybe Arity -- Just n <=> Inline only when applied to n -- explicit (non-type, non-dictionary) args -- That is, inl_sat describes the number of *source-code* -- arguments the thing must be applied to. We add on the -- number of implicit, dictionary arguments when making -- the Unfolding, and don't look at inl_sat further , inl_act :: Activation -- Says during which phases inlining is allowed , inl_rule :: RuleMatchInfo -- Should the function be treated like a constructor? } deriving( Eq, Data ) -- | Inline Specification data InlineSpec -- What the user's INLINE pragma looked like = Inline | Inlinable | NoInline | EmptyInlineSpec -- Used in a place-holder InlinePragma in SpecPrag or IdInfo, -- where there isn't any real inline pragma at all deriving( Eq, Data, Show ) -- Show needed for Lexer.x {- Note [InlinePragma] ~~~~~~~~~~~~~~~~~~~ This data type mirrors what you can write in an INLINE or NOINLINE pragma in the source program. If you write nothing at all, you get defaultInlinePragma: inl_inline = EmptyInlineSpec inl_act = AlwaysActive inl_rule = FunLike It's not possible to get that combination by *writing* something, so if an Id has defaultInlinePragma it means the user didn't specify anything. If inl_inline = Inline or Inlineable, then the Id should have an InlineRule unfolding. If you want to know where InlinePragmas take effect: Look in DsBinds.makeCorePair Note [CONLIKE pragma] ~~~~~~~~~~~~~~~~~~~~~ The ConLike constructor of a RuleMatchInfo is aimed at the following. Consider first {-# RULE "r/cons" forall a as. r (a:as) = f (a+1) #-} g b bs = let x = b:bs in ..x...x...(r x)... Now, the rule applies to the (r x) term, because GHC "looks through" the definition of 'x' to see that it is (b:bs). Now consider {-# RULE "r/f" forall v. r (f v) = f (v+1) #-} g v = let x = f v in ..x...x...(r x)... Normally the (r x) would *not* match the rule, because GHC would be scared about duplicating the redex (f v), so it does not "look through" the bindings. However the CONLIKE modifier says to treat 'f' like a constructor in this situation, and "look through" the unfolding for x. So (r x) fires, yielding (f (v+1)). This is all controlled with a user-visible pragma: {-# NOINLINE CONLIKE [1] f #-} The main effects of CONLIKE are: - The occurrence analyser (OccAnal) and simplifier (Simplify) treat CONLIKE thing like constructors, by ANF-ing them - New function coreUtils.exprIsExpandable is like exprIsCheap, but additionally spots applications of CONLIKE functions - A CoreUnfolding has a field that caches exprIsExpandable - The rule matcher consults this field. See Note [Expanding variables] in Rules.hs. -} isConLike :: RuleMatchInfo -> Bool isConLike ConLike = True isConLike _ = False isFunLike :: RuleMatchInfo -> Bool isFunLike FunLike = True isFunLike _ = False isEmptyInlineSpec :: InlineSpec -> Bool isEmptyInlineSpec EmptyInlineSpec = True isEmptyInlineSpec _ = False defaultInlinePragma, alwaysInlinePragma, neverInlinePragma, dfunInlinePragma :: InlinePragma defaultInlinePragma = InlinePragma { inl_src = "{-# INLINE" , inl_act = AlwaysActive , inl_rule = FunLike , inl_inline = EmptyInlineSpec , inl_sat = Nothing } alwaysInlinePragma = defaultInlinePragma { inl_inline = Inline } neverInlinePragma = defaultInlinePragma { inl_act = NeverActive } inlinePragmaSpec :: InlinePragma -> InlineSpec inlinePragmaSpec = inl_inline -- A DFun has an always-active inline activation so that -- exprIsConApp_maybe can "see" its unfolding -- (However, its actual Unfolding is a DFunUnfolding, which is -- never inlined other than via exprIsConApp_maybe.) dfunInlinePragma = defaultInlinePragma { inl_act = AlwaysActive , inl_rule = ConLike } isDefaultInlinePragma :: InlinePragma -> Bool isDefaultInlinePragma (InlinePragma { inl_act = activation , inl_rule = match_info , inl_inline = inline }) = isEmptyInlineSpec inline && isAlwaysActive activation && isFunLike match_info isInlinePragma :: InlinePragma -> Bool isInlinePragma prag = case inl_inline prag of Inline -> True _ -> False isInlinablePragma :: InlinePragma -> Bool isInlinablePragma prag = case inl_inline prag of Inlinable -> True _ -> False isAnyInlinePragma :: InlinePragma -> Bool -- INLINE or INLINABLE isAnyInlinePragma prag = case inl_inline prag of Inline -> True Inlinable -> True _ -> False inlinePragmaSat :: InlinePragma -> Maybe Arity inlinePragmaSat = inl_sat inlinePragmaActivation :: InlinePragma -> Activation inlinePragmaActivation (InlinePragma { inl_act = activation }) = activation inlinePragmaRuleMatchInfo :: InlinePragma -> RuleMatchInfo inlinePragmaRuleMatchInfo (InlinePragma { inl_rule = info }) = info setInlinePragmaActivation :: InlinePragma -> Activation -> InlinePragma setInlinePragmaActivation prag activation = prag { inl_act = activation } setInlinePragmaRuleMatchInfo :: InlinePragma -> RuleMatchInfo -> InlinePragma setInlinePragmaRuleMatchInfo prag info = prag { inl_rule = info } instance Outputable Activation where ppr AlwaysActive = brackets (text "ALWAYS") ppr NeverActive = brackets (text "NEVER") ppr (ActiveBefore _ n) = brackets (char '~' <> int n) ppr (ActiveAfter _ n) = brackets (int n) instance Outputable RuleMatchInfo where ppr ConLike = text "CONLIKE" ppr FunLike = text "FUNLIKE" instance Outputable InlineSpec where ppr Inline = text "INLINE" ppr NoInline = text "NOINLINE" ppr Inlinable = text "INLINABLE" ppr EmptyInlineSpec = empty instance Outputable InlinePragma where ppr (InlinePragma { inl_inline = inline, inl_act = activation , inl_rule = info, inl_sat = mb_arity }) = ppr inline <> pp_act inline activation <+> pp_sat <+> pp_info where pp_act Inline AlwaysActive = empty pp_act NoInline NeverActive = empty pp_act _ act = ppr act pp_sat | Just ar <- mb_arity = parens (text "sat-args=" <> int ar) | otherwise = empty pp_info | isFunLike info = empty | otherwise = ppr info isActive :: CompilerPhase -> Activation -> Bool isActive InitialPhase AlwaysActive = True isActive InitialPhase (ActiveBefore {}) = True isActive InitialPhase _ = False isActive (Phase p) act = isActiveIn p act isActiveIn :: PhaseNum -> Activation -> Bool isActiveIn _ NeverActive = False isActiveIn _ AlwaysActive = True isActiveIn p (ActiveAfter _ n) = p <= n isActiveIn p (ActiveBefore _ n) = p > n competesWith :: Activation -> Activation -> Bool -- See Note [Activation competition] competesWith NeverActive _ = False competesWith _ NeverActive = False competesWith AlwaysActive _ = True competesWith (ActiveBefore {}) AlwaysActive = True competesWith (ActiveBefore {}) (ActiveBefore {}) = True competesWith (ActiveBefore _ a) (ActiveAfter _ b) = a < b competesWith (ActiveAfter {}) AlwaysActive = False competesWith (ActiveAfter {}) (ActiveBefore {}) = False competesWith (ActiveAfter _ a) (ActiveAfter _ b) = a >= b {- Note [Competing activations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sometimes a RULE and an inlining may compete, or two RULES. See Note [Rules and inlining/other rules] in Desugar. We say that act1 "competes with" act2 iff act1 is active in the phase when act2 *becomes* active NB: remember that phases count *down*: 2, 1, 0! It's too conservative to ensure that the two are never simultaneously active. For example, a rule might be always active, and an inlining might switch on in phase 2. We could switch off the rule, but it does no harm. -} isNeverActive, isAlwaysActive, isEarlyActive :: Activation -> Bool isNeverActive NeverActive = True isNeverActive _ = False isAlwaysActive AlwaysActive = True isAlwaysActive _ = False isEarlyActive AlwaysActive = True isEarlyActive (ActiveBefore {}) = True isEarlyActive _ = False -- | Fractional Literal -- -- Used (instead of Rational) to represent exactly the floating point literal that we -- encountered in the user's source program. This allows us to pretty-print exactly what -- the user wrote, which is important e.g. for floating point numbers that can't represented -- as Doubles (we used to via Double for pretty-printing). See also #2245. data FractionalLit = FL { fl_text :: String -- How the value was written in the source , fl_value :: Rational -- Numeric value of the literal } deriving (Data, Show) -- The Show instance is required for the derived Lexer.x:Token instance when DEBUG is on negateFractionalLit :: FractionalLit -> FractionalLit negateFractionalLit (FL { fl_text = '-':text, fl_value = value }) = FL { fl_text = text, fl_value = negate value } negateFractionalLit (FL { fl_text = text, fl_value = value }) = FL { fl_text = '-':text, fl_value = negate value } integralFractionalLit :: Integer -> FractionalLit integralFractionalLit i = FL { fl_text = show i, fl_value = fromInteger i } -- Comparison operations are needed when grouping literals -- for compiling pattern-matching (module MatchLit) instance Eq FractionalLit where (==) = (==) `on` fl_value instance Ord FractionalLit where compare = compare `on` fl_value instance Outputable FractionalLit where ppr = text . fl_text {- ************************************************************************ * * IntWithInf * * ************************************************************************ Represents an integer or positive infinity -} -- | An integer or infinity data IntWithInf = Int {-# UNPACK #-} !Int | Infinity deriving Eq -- | A representation of infinity infinity :: IntWithInf infinity = Infinity instance Ord IntWithInf where compare Infinity Infinity = EQ compare (Int _) Infinity = LT compare Infinity (Int _) = GT compare (Int a) (Int b) = a `compare` b instance Outputable IntWithInf where ppr Infinity = char '∞' ppr (Int n) = int n instance Num IntWithInf where (+) = plusWithInf (*) = mulWithInf abs Infinity = Infinity abs (Int n) = Int (abs n) signum Infinity = Int 1 signum (Int n) = Int (signum n) fromInteger = Int . fromInteger (-) = panic "subtracting IntWithInfs" intGtLimit :: Int -> IntWithInf -> Bool intGtLimit _ Infinity = False intGtLimit n (Int m) = n > m -- | Add two 'IntWithInf's plusWithInf :: IntWithInf -> IntWithInf -> IntWithInf plusWithInf Infinity _ = Infinity plusWithInf _ Infinity = Infinity plusWithInf (Int a) (Int b) = Int (a + b) -- | Multiply two 'IntWithInf's mulWithInf :: IntWithInf -> IntWithInf -> IntWithInf mulWithInf Infinity _ = Infinity mulWithInf _ Infinity = Infinity mulWithInf (Int a) (Int b) = Int (a * b) -- | Turn a positive number into an 'IntWithInf', where 0 represents infinity treatZeroAsInf :: Int -> IntWithInf treatZeroAsInf 0 = Infinity treatZeroAsInf n = Int n -- | Inject any integer into an 'IntWithInf' mkIntWithInf :: Int -> IntWithInf mkIntWithInf = Int
mettekou/ghc
compiler/basicTypes/BasicTypes.hs
bsd-3-clause
46,454
0
14
14,114
6,085
3,388
2,697
584
5
{-# OPTIONS_GHC -fno-warn-unused-imports #-} module Instances where import Kubernetes.OpenAPI.Model import Kubernetes.OpenAPI.Core import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as BL import qualified Data.HashMap.Strict as HM import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Time as TI import qualified Data.Vector as V import Control.Monad import Data.Char (isSpace) import Data.List (sort) import Test.QuickCheck import ApproxEq instance Arbitrary T.Text where arbitrary = T.pack <$> arbitrary instance Arbitrary TI.Day where arbitrary = TI.ModifiedJulianDay . (2000 +) <$> arbitrary shrink = (TI.ModifiedJulianDay <$>) . shrink . TI.toModifiedJulianDay instance Arbitrary TI.UTCTime where arbitrary = TI.UTCTime <$> arbitrary <*> (TI.secondsToDiffTime <$> choose (0, 86401)) instance Arbitrary BL.ByteString where arbitrary = BL.pack <$> arbitrary shrink xs = BL.pack <$> shrink (BL.unpack xs) instance Arbitrary ByteArray where arbitrary = ByteArray <$> arbitrary shrink (ByteArray xs) = ByteArray <$> shrink xs instance Arbitrary Binary where arbitrary = Binary <$> arbitrary shrink (Binary xs) = Binary <$> shrink xs instance Arbitrary DateTime where arbitrary = DateTime <$> arbitrary shrink (DateTime xs) = DateTime <$> shrink xs instance Arbitrary Date where arbitrary = Date <$> arbitrary shrink (Date xs) = Date <$> shrink xs -- | A naive Arbitrary instance for A.Value: instance Arbitrary A.Value where arbitrary = frequency [(3, simpleTypes), (1, arrayTypes), (1, objectTypes)] where simpleTypes :: Gen A.Value simpleTypes = frequency [ (1, return A.Null) , (2, liftM A.Bool (arbitrary :: Gen Bool)) , (2, liftM (A.Number . fromIntegral) (arbitrary :: Gen Int)) , (2, liftM (A.String . T.pack) (arbitrary :: Gen String)) ] mapF (k, v) = (T.pack k, v) simpleAndArrays = frequency [(1, sized sizedArray), (4, simpleTypes)] arrayTypes = sized sizedArray objectTypes = sized sizedObject sizedArray n = liftM (A.Array . V.fromList) $ replicateM n simpleTypes sizedObject n = liftM (A.object . map mapF) $ replicateM n $ (,) <$> (arbitrary :: Gen String) <*> simpleAndArrays -- | Checks if a given list has no duplicates in _O(n log n)_. hasNoDups :: (Ord a) => [a] -> Bool hasNoDups = go Set.empty where go _ [] = True go s (x:xs) | s' <- Set.insert x s , Set.size s' > Set.size s = go s' xs | otherwise = False instance ApproxEq TI.Day where (=~) = (==) -- * Models instance Arbitrary AdmissionregistrationV1beta1ServiceReference where arbitrary = AdmissionregistrationV1beta1ServiceReference <$> arbitrary -- admissionregistrationV1beta1ServiceReferenceName :: Text <*> arbitrary -- admissionregistrationV1beta1ServiceReferenceNamespace :: Text <*> arbitrary -- admissionregistrationV1beta1ServiceReferencePath :: Maybe Text instance Arbitrary ApiregistrationV1beta1ServiceReference where arbitrary = ApiregistrationV1beta1ServiceReference <$> arbitrary -- apiregistrationV1beta1ServiceReferenceName :: Maybe Text <*> arbitrary -- apiregistrationV1beta1ServiceReferenceNamespace :: Maybe Text instance Arbitrary AppsV1beta1Deployment where arbitrary = AppsV1beta1Deployment <$> arbitrary -- appsV1beta1DeploymentApiVersion :: Maybe Text <*> arbitrary -- appsV1beta1DeploymentKind :: Maybe Text <*> arbitrary -- appsV1beta1DeploymentMetadata :: Maybe V1ObjectMeta <*> arbitrary -- appsV1beta1DeploymentSpec :: Maybe AppsV1beta1DeploymentSpec <*> arbitrary -- appsV1beta1DeploymentStatus :: Maybe AppsV1beta1DeploymentStatus instance Arbitrary AppsV1beta1DeploymentCondition where arbitrary = AppsV1beta1DeploymentCondition <$> arbitrary -- appsV1beta1DeploymentConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- appsV1beta1DeploymentConditionLastUpdateTime :: Maybe DateTime <*> arbitrary -- appsV1beta1DeploymentConditionMessage :: Maybe Text <*> arbitrary -- appsV1beta1DeploymentConditionReason :: Maybe Text <*> arbitrary -- appsV1beta1DeploymentConditionStatus :: Text <*> arbitrary -- appsV1beta1DeploymentConditionType :: Text instance Arbitrary AppsV1beta1DeploymentList where arbitrary = AppsV1beta1DeploymentList <$> arbitrary -- appsV1beta1DeploymentListApiVersion :: Maybe Text <*> arbitrary -- appsV1beta1DeploymentListItems :: [AppsV1beta1Deployment] <*> arbitrary -- appsV1beta1DeploymentListKind :: Maybe Text <*> arbitrary -- appsV1beta1DeploymentListMetadata :: Maybe V1ListMeta instance Arbitrary AppsV1beta1DeploymentRollback where arbitrary = AppsV1beta1DeploymentRollback <$> arbitrary -- appsV1beta1DeploymentRollbackApiVersion :: Maybe Text <*> arbitrary -- appsV1beta1DeploymentRollbackKind :: Maybe Text <*> arbitrary -- appsV1beta1DeploymentRollbackName :: Text <*> arbitrary -- appsV1beta1DeploymentRollbackRollbackTo :: AppsV1beta1RollbackConfig <*> arbitrary -- appsV1beta1DeploymentRollbackUpdatedAnnotations :: Maybe (Map.Map String Text) instance Arbitrary AppsV1beta1DeploymentSpec where arbitrary = AppsV1beta1DeploymentSpec <$> arbitrary -- appsV1beta1DeploymentSpecMinReadySeconds :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentSpecPaused :: Maybe Bool <*> arbitrary -- appsV1beta1DeploymentSpecProgressDeadlineSeconds :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentSpecReplicas :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentSpecRollbackTo :: Maybe AppsV1beta1RollbackConfig <*> arbitrary -- appsV1beta1DeploymentSpecSelector :: Maybe V1LabelSelector <*> arbitrary -- appsV1beta1DeploymentSpecStrategy :: Maybe AppsV1beta1DeploymentStrategy <*> arbitrary -- appsV1beta1DeploymentSpecTemplate :: V1PodTemplateSpec instance Arbitrary AppsV1beta1DeploymentStatus where arbitrary = AppsV1beta1DeploymentStatus <$> arbitrary -- appsV1beta1DeploymentStatusAvailableReplicas :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentStatusCollisionCount :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentStatusConditions :: Maybe [AppsV1beta1DeploymentCondition] <*> arbitrary -- appsV1beta1DeploymentStatusObservedGeneration :: Maybe Integer <*> arbitrary -- appsV1beta1DeploymentStatusReadyReplicas :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentStatusReplicas :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentStatusUnavailableReplicas :: Maybe Int <*> arbitrary -- appsV1beta1DeploymentStatusUpdatedReplicas :: Maybe Int instance Arbitrary AppsV1beta1DeploymentStrategy where arbitrary = AppsV1beta1DeploymentStrategy <$> arbitrary -- appsV1beta1DeploymentStrategyRollingUpdate :: Maybe AppsV1beta1RollingUpdateDeployment <*> arbitrary -- appsV1beta1DeploymentStrategyType :: Maybe Text instance Arbitrary AppsV1beta1RollbackConfig where arbitrary = AppsV1beta1RollbackConfig <$> arbitrary -- appsV1beta1RollbackConfigRevision :: Maybe Integer instance Arbitrary AppsV1beta1RollingUpdateDeployment where arbitrary = AppsV1beta1RollingUpdateDeployment <$> arbitrary -- appsV1beta1RollingUpdateDeploymentMaxSurge :: Maybe A.Value <*> arbitrary -- appsV1beta1RollingUpdateDeploymentMaxUnavailable :: Maybe A.Value instance Arbitrary AppsV1beta1Scale where arbitrary = AppsV1beta1Scale <$> arbitrary -- appsV1beta1ScaleApiVersion :: Maybe Text <*> arbitrary -- appsV1beta1ScaleKind :: Maybe Text <*> arbitrary -- appsV1beta1ScaleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- appsV1beta1ScaleSpec :: Maybe AppsV1beta1ScaleSpec <*> arbitrary -- appsV1beta1ScaleStatus :: Maybe AppsV1beta1ScaleStatus instance Arbitrary AppsV1beta1ScaleSpec where arbitrary = AppsV1beta1ScaleSpec <$> arbitrary -- appsV1beta1ScaleSpecReplicas :: Maybe Int instance Arbitrary AppsV1beta1ScaleStatus where arbitrary = AppsV1beta1ScaleStatus <$> arbitrary -- appsV1beta1ScaleStatusReplicas :: Int <*> arbitrary -- appsV1beta1ScaleStatusSelector :: Maybe (Map.Map String Text) <*> arbitrary -- appsV1beta1ScaleStatusTargetSelector :: Maybe Text instance Arbitrary ExtensionsV1beta1Deployment where arbitrary = ExtensionsV1beta1Deployment <$> arbitrary -- extensionsV1beta1DeploymentApiVersion :: Maybe Text <*> arbitrary -- extensionsV1beta1DeploymentKind :: Maybe Text <*> arbitrary -- extensionsV1beta1DeploymentMetadata :: Maybe V1ObjectMeta <*> arbitrary -- extensionsV1beta1DeploymentSpec :: Maybe ExtensionsV1beta1DeploymentSpec <*> arbitrary -- extensionsV1beta1DeploymentStatus :: Maybe ExtensionsV1beta1DeploymentStatus instance Arbitrary ExtensionsV1beta1DeploymentCondition where arbitrary = ExtensionsV1beta1DeploymentCondition <$> arbitrary -- extensionsV1beta1DeploymentConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- extensionsV1beta1DeploymentConditionLastUpdateTime :: Maybe DateTime <*> arbitrary -- extensionsV1beta1DeploymentConditionMessage :: Maybe Text <*> arbitrary -- extensionsV1beta1DeploymentConditionReason :: Maybe Text <*> arbitrary -- extensionsV1beta1DeploymentConditionStatus :: Text <*> arbitrary -- extensionsV1beta1DeploymentConditionType :: Text instance Arbitrary ExtensionsV1beta1DeploymentList where arbitrary = ExtensionsV1beta1DeploymentList <$> arbitrary -- extensionsV1beta1DeploymentListApiVersion :: Maybe Text <*> arbitrary -- extensionsV1beta1DeploymentListItems :: [ExtensionsV1beta1Deployment] <*> arbitrary -- extensionsV1beta1DeploymentListKind :: Maybe Text <*> arbitrary -- extensionsV1beta1DeploymentListMetadata :: Maybe V1ListMeta instance Arbitrary ExtensionsV1beta1DeploymentRollback where arbitrary = ExtensionsV1beta1DeploymentRollback <$> arbitrary -- extensionsV1beta1DeploymentRollbackApiVersion :: Maybe Text <*> arbitrary -- extensionsV1beta1DeploymentRollbackKind :: Maybe Text <*> arbitrary -- extensionsV1beta1DeploymentRollbackName :: Text <*> arbitrary -- extensionsV1beta1DeploymentRollbackRollbackTo :: ExtensionsV1beta1RollbackConfig <*> arbitrary -- extensionsV1beta1DeploymentRollbackUpdatedAnnotations :: Maybe (Map.Map String Text) instance Arbitrary ExtensionsV1beta1DeploymentSpec where arbitrary = ExtensionsV1beta1DeploymentSpec <$> arbitrary -- extensionsV1beta1DeploymentSpecMinReadySeconds :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentSpecPaused :: Maybe Bool <*> arbitrary -- extensionsV1beta1DeploymentSpecProgressDeadlineSeconds :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentSpecReplicas :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentSpecRollbackTo :: Maybe ExtensionsV1beta1RollbackConfig <*> arbitrary -- extensionsV1beta1DeploymentSpecSelector :: Maybe V1LabelSelector <*> arbitrary -- extensionsV1beta1DeploymentSpecStrategy :: Maybe ExtensionsV1beta1DeploymentStrategy <*> arbitrary -- extensionsV1beta1DeploymentSpecTemplate :: V1PodTemplateSpec instance Arbitrary ExtensionsV1beta1DeploymentStatus where arbitrary = ExtensionsV1beta1DeploymentStatus <$> arbitrary -- extensionsV1beta1DeploymentStatusAvailableReplicas :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentStatusCollisionCount :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentStatusConditions :: Maybe [ExtensionsV1beta1DeploymentCondition] <*> arbitrary -- extensionsV1beta1DeploymentStatusObservedGeneration :: Maybe Integer <*> arbitrary -- extensionsV1beta1DeploymentStatusReadyReplicas :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentStatusReplicas :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentStatusUnavailableReplicas :: Maybe Int <*> arbitrary -- extensionsV1beta1DeploymentStatusUpdatedReplicas :: Maybe Int instance Arbitrary ExtensionsV1beta1DeploymentStrategy where arbitrary = ExtensionsV1beta1DeploymentStrategy <$> arbitrary -- extensionsV1beta1DeploymentStrategyRollingUpdate :: Maybe ExtensionsV1beta1RollingUpdateDeployment <*> arbitrary -- extensionsV1beta1DeploymentStrategyType :: Maybe Text instance Arbitrary ExtensionsV1beta1RollbackConfig where arbitrary = ExtensionsV1beta1RollbackConfig <$> arbitrary -- extensionsV1beta1RollbackConfigRevision :: Maybe Integer instance Arbitrary ExtensionsV1beta1RollingUpdateDeployment where arbitrary = ExtensionsV1beta1RollingUpdateDeployment <$> arbitrary -- extensionsV1beta1RollingUpdateDeploymentMaxSurge :: Maybe A.Value <*> arbitrary -- extensionsV1beta1RollingUpdateDeploymentMaxUnavailable :: Maybe A.Value instance Arbitrary ExtensionsV1beta1Scale where arbitrary = ExtensionsV1beta1Scale <$> arbitrary -- extensionsV1beta1ScaleApiVersion :: Maybe Text <*> arbitrary -- extensionsV1beta1ScaleKind :: Maybe Text <*> arbitrary -- extensionsV1beta1ScaleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- extensionsV1beta1ScaleSpec :: Maybe ExtensionsV1beta1ScaleSpec <*> arbitrary -- extensionsV1beta1ScaleStatus :: Maybe ExtensionsV1beta1ScaleStatus instance Arbitrary ExtensionsV1beta1ScaleSpec where arbitrary = ExtensionsV1beta1ScaleSpec <$> arbitrary -- extensionsV1beta1ScaleSpecReplicas :: Maybe Int instance Arbitrary ExtensionsV1beta1ScaleStatus where arbitrary = ExtensionsV1beta1ScaleStatus <$> arbitrary -- extensionsV1beta1ScaleStatusReplicas :: Int <*> arbitrary -- extensionsV1beta1ScaleStatusSelector :: Maybe (Map.Map String Text) <*> arbitrary -- extensionsV1beta1ScaleStatusTargetSelector :: Maybe Text instance Arbitrary RuntimeRawExtension where arbitrary = RuntimeRawExtension <$> arbitrary -- runtimeRawExtensionRaw :: ByteArray instance Arbitrary V1APIGroup where arbitrary = V1APIGroup <$> arbitrary -- v1APIGroupApiVersion :: Maybe Text <*> arbitrary -- v1APIGroupKind :: Maybe Text <*> arbitrary -- v1APIGroupName :: Text <*> arbitrary -- v1APIGroupPreferredVersion :: Maybe V1GroupVersionForDiscovery <*> arbitrary -- v1APIGroupServerAddressByClientCidRs :: [V1ServerAddressByClientCIDR] <*> arbitrary -- v1APIGroupVersions :: [V1GroupVersionForDiscovery] instance Arbitrary V1APIGroupList where arbitrary = V1APIGroupList <$> arbitrary -- v1APIGroupListApiVersion :: Maybe Text <*> arbitrary -- v1APIGroupListGroups :: [V1APIGroup] <*> arbitrary -- v1APIGroupListKind :: Maybe Text instance Arbitrary V1APIResource where arbitrary = V1APIResource <$> arbitrary -- v1APIResourceCategories :: Maybe [Text] <*> arbitrary -- v1APIResourceGroup :: Maybe Text <*> arbitrary -- v1APIResourceKind :: Text <*> arbitrary -- v1APIResourceName :: Text <*> arbitrary -- v1APIResourceNamespaced :: Bool <*> arbitrary -- v1APIResourceShortNames :: Maybe [Text] <*> arbitrary -- v1APIResourceSingularName :: Text <*> arbitrary -- v1APIResourceVerbs :: [Text] <*> arbitrary -- v1APIResourceVersion :: Maybe Text instance Arbitrary V1APIResourceList where arbitrary = V1APIResourceList <$> arbitrary -- v1APIResourceListApiVersion :: Maybe Text <*> arbitrary -- v1APIResourceListGroupVersion :: Text <*> arbitrary -- v1APIResourceListKind :: Maybe Text <*> arbitrary -- v1APIResourceListResources :: [V1APIResource] instance Arbitrary V1APIVersions where arbitrary = V1APIVersions <$> arbitrary -- v1APIVersionsApiVersion :: Maybe Text <*> arbitrary -- v1APIVersionsKind :: Maybe Text <*> arbitrary -- v1APIVersionsServerAddressByClientCidRs :: [V1ServerAddressByClientCIDR] <*> arbitrary -- v1APIVersionsVersions :: [Text] instance Arbitrary V1AWSElasticBlockStoreVolumeSource where arbitrary = V1AWSElasticBlockStoreVolumeSource <$> arbitrary -- v1AWSElasticBlockStoreVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1AWSElasticBlockStoreVolumeSourcePartition :: Maybe Int <*> arbitrary -- v1AWSElasticBlockStoreVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1AWSElasticBlockStoreVolumeSourceVolumeId :: Text instance Arbitrary V1Affinity where arbitrary = V1Affinity <$> arbitrary -- v1AffinityNodeAffinity :: Maybe V1NodeAffinity <*> arbitrary -- v1AffinityPodAffinity :: Maybe V1PodAffinity <*> arbitrary -- v1AffinityPodAntiAffinity :: Maybe V1PodAntiAffinity instance Arbitrary V1AggregationRule where arbitrary = V1AggregationRule <$> arbitrary -- v1AggregationRuleClusterRoleSelectors :: Maybe [V1LabelSelector] instance Arbitrary V1AttachedVolume where arbitrary = V1AttachedVolume <$> arbitrary -- v1AttachedVolumeDevicePath :: Text <*> arbitrary -- v1AttachedVolumeName :: Text instance Arbitrary V1AzureDiskVolumeSource where arbitrary = V1AzureDiskVolumeSource <$> arbitrary -- v1AzureDiskVolumeSourceCachingMode :: Maybe Text <*> arbitrary -- v1AzureDiskVolumeSourceDiskName :: Text <*> arbitrary -- v1AzureDiskVolumeSourceDiskUri :: Text <*> arbitrary -- v1AzureDiskVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1AzureDiskVolumeSourceKind :: Maybe Text <*> arbitrary -- v1AzureDiskVolumeSourceReadOnly :: Maybe Bool instance Arbitrary V1AzureFilePersistentVolumeSource where arbitrary = V1AzureFilePersistentVolumeSource <$> arbitrary -- v1AzureFilePersistentVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1AzureFilePersistentVolumeSourceSecretName :: Text <*> arbitrary -- v1AzureFilePersistentVolumeSourceSecretNamespace :: Maybe Text <*> arbitrary -- v1AzureFilePersistentVolumeSourceShareName :: Text instance Arbitrary V1AzureFileVolumeSource where arbitrary = V1AzureFileVolumeSource <$> arbitrary -- v1AzureFileVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1AzureFileVolumeSourceSecretName :: Text <*> arbitrary -- v1AzureFileVolumeSourceShareName :: Text instance Arbitrary V1Binding where arbitrary = V1Binding <$> arbitrary -- v1BindingApiVersion :: Maybe Text <*> arbitrary -- v1BindingKind :: Maybe Text <*> arbitrary -- v1BindingMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1BindingTarget :: V1ObjectReference instance Arbitrary V1CSIPersistentVolumeSource where arbitrary = V1CSIPersistentVolumeSource <$> arbitrary -- v1CSIPersistentVolumeSourceDriver :: Text <*> arbitrary -- v1CSIPersistentVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1CSIPersistentVolumeSourceVolumeHandle :: Text instance Arbitrary V1Capabilities where arbitrary = V1Capabilities <$> arbitrary -- v1CapabilitiesAdd :: Maybe [Text] <*> arbitrary -- v1CapabilitiesDrop :: Maybe [Text] instance Arbitrary V1CephFSPersistentVolumeSource where arbitrary = V1CephFSPersistentVolumeSource <$> arbitrary -- v1CephFSPersistentVolumeSourceMonitors :: [Text] <*> arbitrary -- v1CephFSPersistentVolumeSourcePath :: Maybe Text <*> arbitrary -- v1CephFSPersistentVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1CephFSPersistentVolumeSourceSecretFile :: Maybe Text <*> arbitrary -- v1CephFSPersistentVolumeSourceSecretRef :: Maybe V1SecretReference <*> arbitrary -- v1CephFSPersistentVolumeSourceUser :: Maybe Text instance Arbitrary V1CephFSVolumeSource where arbitrary = V1CephFSVolumeSource <$> arbitrary -- v1CephFSVolumeSourceMonitors :: [Text] <*> arbitrary -- v1CephFSVolumeSourcePath :: Maybe Text <*> arbitrary -- v1CephFSVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1CephFSVolumeSourceSecretFile :: Maybe Text <*> arbitrary -- v1CephFSVolumeSourceSecretRef :: Maybe V1LocalObjectReference <*> arbitrary -- v1CephFSVolumeSourceUser :: Maybe Text instance Arbitrary V1CinderVolumeSource where arbitrary = V1CinderVolumeSource <$> arbitrary -- v1CinderVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1CinderVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1CinderVolumeSourceVolumeId :: Text instance Arbitrary V1ClientIPConfig where arbitrary = V1ClientIPConfig <$> arbitrary -- v1ClientIPConfigTimeoutSeconds :: Maybe Int instance Arbitrary V1ClusterRole where arbitrary = V1ClusterRole <$> arbitrary -- v1ClusterRoleAggregationRule :: Maybe V1AggregationRule <*> arbitrary -- v1ClusterRoleApiVersion :: Maybe Text <*> arbitrary -- v1ClusterRoleKind :: Maybe Text <*> arbitrary -- v1ClusterRoleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ClusterRoleRules :: [V1PolicyRule] instance Arbitrary V1ClusterRoleBinding where arbitrary = V1ClusterRoleBinding <$> arbitrary -- v1ClusterRoleBindingApiVersion :: Maybe Text <*> arbitrary -- v1ClusterRoleBindingKind :: Maybe Text <*> arbitrary -- v1ClusterRoleBindingMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ClusterRoleBindingRoleRef :: V1RoleRef <*> arbitrary -- v1ClusterRoleBindingSubjects :: [V1Subject] instance Arbitrary V1ClusterRoleBindingList where arbitrary = V1ClusterRoleBindingList <$> arbitrary -- v1ClusterRoleBindingListApiVersion :: Maybe Text <*> arbitrary -- v1ClusterRoleBindingListItems :: [V1ClusterRoleBinding] <*> arbitrary -- v1ClusterRoleBindingListKind :: Maybe Text <*> arbitrary -- v1ClusterRoleBindingListMetadata :: Maybe V1ListMeta instance Arbitrary V1ClusterRoleList where arbitrary = V1ClusterRoleList <$> arbitrary -- v1ClusterRoleListApiVersion :: Maybe Text <*> arbitrary -- v1ClusterRoleListItems :: [V1ClusterRole] <*> arbitrary -- v1ClusterRoleListKind :: Maybe Text <*> arbitrary -- v1ClusterRoleListMetadata :: Maybe V1ListMeta instance Arbitrary V1ComponentCondition where arbitrary = V1ComponentCondition <$> arbitrary -- v1ComponentConditionError :: Maybe Text <*> arbitrary -- v1ComponentConditionMessage :: Maybe Text <*> arbitrary -- v1ComponentConditionStatus :: Text <*> arbitrary -- v1ComponentConditionType :: Text instance Arbitrary V1ComponentStatus where arbitrary = V1ComponentStatus <$> arbitrary -- v1ComponentStatusApiVersion :: Maybe Text <*> arbitrary -- v1ComponentStatusConditions :: Maybe [V1ComponentCondition] <*> arbitrary -- v1ComponentStatusKind :: Maybe Text <*> arbitrary -- v1ComponentStatusMetadata :: Maybe V1ObjectMeta instance Arbitrary V1ComponentStatusList where arbitrary = V1ComponentStatusList <$> arbitrary -- v1ComponentStatusListApiVersion :: Maybe Text <*> arbitrary -- v1ComponentStatusListItems :: [V1ComponentStatus] <*> arbitrary -- v1ComponentStatusListKind :: Maybe Text <*> arbitrary -- v1ComponentStatusListMetadata :: Maybe V1ListMeta instance Arbitrary V1ConfigMap where arbitrary = V1ConfigMap <$> arbitrary -- v1ConfigMapApiVersion :: Maybe Text <*> arbitrary -- v1ConfigMapData :: Maybe (Map.Map String Text) <*> arbitrary -- v1ConfigMapKind :: Maybe Text <*> arbitrary -- v1ConfigMapMetadata :: Maybe V1ObjectMeta instance Arbitrary V1ConfigMapEnvSource where arbitrary = V1ConfigMapEnvSource <$> arbitrary -- v1ConfigMapEnvSourceName :: Maybe Text <*> arbitrary -- v1ConfigMapEnvSourceOptional :: Maybe Bool instance Arbitrary V1ConfigMapKeySelector where arbitrary = V1ConfigMapKeySelector <$> arbitrary -- v1ConfigMapKeySelectorKey :: Text <*> arbitrary -- v1ConfigMapKeySelectorName :: Maybe Text <*> arbitrary -- v1ConfigMapKeySelectorOptional :: Maybe Bool instance Arbitrary V1ConfigMapList where arbitrary = V1ConfigMapList <$> arbitrary -- v1ConfigMapListApiVersion :: Maybe Text <*> arbitrary -- v1ConfigMapListItems :: [V1ConfigMap] <*> arbitrary -- v1ConfigMapListKind :: Maybe Text <*> arbitrary -- v1ConfigMapListMetadata :: Maybe V1ListMeta instance Arbitrary V1ConfigMapProjection where arbitrary = V1ConfigMapProjection <$> arbitrary -- v1ConfigMapProjectionItems :: Maybe [V1KeyToPath] <*> arbitrary -- v1ConfigMapProjectionName :: Maybe Text <*> arbitrary -- v1ConfigMapProjectionOptional :: Maybe Bool instance Arbitrary V1ConfigMapVolumeSource where arbitrary = V1ConfigMapVolumeSource <$> arbitrary -- v1ConfigMapVolumeSourceDefaultMode :: Maybe Int <*> arbitrary -- v1ConfigMapVolumeSourceItems :: Maybe [V1KeyToPath] <*> arbitrary -- v1ConfigMapVolumeSourceName :: Maybe Text <*> arbitrary -- v1ConfigMapVolumeSourceOptional :: Maybe Bool instance Arbitrary V1Container where arbitrary = V1Container <$> arbitrary -- v1ContainerArgs :: Maybe [Text] <*> arbitrary -- v1ContainerCommand :: Maybe [Text] <*> arbitrary -- v1ContainerEnv :: Maybe [V1EnvVar] <*> arbitrary -- v1ContainerEnvFrom :: Maybe [V1EnvFromSource] <*> arbitrary -- v1ContainerImage :: Maybe Text <*> arbitrary -- v1ContainerImagePullPolicy :: Maybe Text <*> arbitrary -- v1ContainerLifecycle :: Maybe V1Lifecycle <*> arbitrary -- v1ContainerLivenessProbe :: Maybe V1Probe <*> arbitrary -- v1ContainerName :: Text <*> arbitrary -- v1ContainerPorts :: Maybe [V1ContainerPort] <*> arbitrary -- v1ContainerReadinessProbe :: Maybe V1Probe <*> arbitrary -- v1ContainerResources :: Maybe V1ResourceRequirements <*> arbitrary -- v1ContainerSecurityContext :: Maybe V1SecurityContext <*> arbitrary -- v1ContainerStdin :: Maybe Bool <*> arbitrary -- v1ContainerStdinOnce :: Maybe Bool <*> arbitrary -- v1ContainerTerminationMessagePath :: Maybe Text <*> arbitrary -- v1ContainerTerminationMessagePolicy :: Maybe Text <*> arbitrary -- v1ContainerTty :: Maybe Bool <*> arbitrary -- v1ContainerVolumeDevices :: Maybe [V1VolumeDevice] <*> arbitrary -- v1ContainerVolumeMounts :: Maybe [V1VolumeMount] <*> arbitrary -- v1ContainerWorkingDir :: Maybe Text instance Arbitrary V1ContainerImage where arbitrary = V1ContainerImage <$> arbitrary -- v1ContainerImageNames :: [Text] <*> arbitrary -- v1ContainerImageSizeBytes :: Maybe Integer instance Arbitrary V1ContainerPort where arbitrary = V1ContainerPort <$> arbitrary -- v1ContainerPortContainerPort :: Int <*> arbitrary -- v1ContainerPortHostIp :: Maybe Text <*> arbitrary -- v1ContainerPortHostPort :: Maybe Int <*> arbitrary -- v1ContainerPortName :: Maybe Text <*> arbitrary -- v1ContainerPortProtocol :: Maybe Text instance Arbitrary V1ContainerState where arbitrary = V1ContainerState <$> arbitrary -- v1ContainerStateRunning :: Maybe V1ContainerStateRunning <*> arbitrary -- v1ContainerStateTerminated :: Maybe V1ContainerStateTerminated <*> arbitrary -- v1ContainerStateWaiting :: Maybe V1ContainerStateWaiting instance Arbitrary V1ContainerStateRunning where arbitrary = V1ContainerStateRunning <$> arbitrary -- v1ContainerStateRunningStartedAt :: Maybe DateTime instance Arbitrary V1ContainerStateTerminated where arbitrary = V1ContainerStateTerminated <$> arbitrary -- v1ContainerStateTerminatedContainerId :: Maybe Text <*> arbitrary -- v1ContainerStateTerminatedExitCode :: Int <*> arbitrary -- v1ContainerStateTerminatedFinishedAt :: Maybe DateTime <*> arbitrary -- v1ContainerStateTerminatedMessage :: Maybe Text <*> arbitrary -- v1ContainerStateTerminatedReason :: Maybe Text <*> arbitrary -- v1ContainerStateTerminatedSignal :: Maybe Int <*> arbitrary -- v1ContainerStateTerminatedStartedAt :: Maybe DateTime instance Arbitrary V1ContainerStateWaiting where arbitrary = V1ContainerStateWaiting <$> arbitrary -- v1ContainerStateWaitingMessage :: Maybe Text <*> arbitrary -- v1ContainerStateWaitingReason :: Maybe Text instance Arbitrary V1ContainerStatus where arbitrary = V1ContainerStatus <$> arbitrary -- v1ContainerStatusContainerId :: Maybe Text <*> arbitrary -- v1ContainerStatusImage :: Text <*> arbitrary -- v1ContainerStatusImageId :: Text <*> arbitrary -- v1ContainerStatusLastState :: Maybe V1ContainerState <*> arbitrary -- v1ContainerStatusName :: Text <*> arbitrary -- v1ContainerStatusReady :: Bool <*> arbitrary -- v1ContainerStatusRestartCount :: Int <*> arbitrary -- v1ContainerStatusState :: Maybe V1ContainerState instance Arbitrary V1ControllerRevision where arbitrary = V1ControllerRevision <$> arbitrary -- v1ControllerRevisionApiVersion :: Maybe Text <*> arbitrary -- v1ControllerRevisionData :: Maybe RuntimeRawExtension <*> arbitrary -- v1ControllerRevisionKind :: Maybe Text <*> arbitrary -- v1ControllerRevisionMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ControllerRevisionRevision :: Integer instance Arbitrary V1ControllerRevisionList where arbitrary = V1ControllerRevisionList <$> arbitrary -- v1ControllerRevisionListApiVersion :: Maybe Text <*> arbitrary -- v1ControllerRevisionListItems :: [V1ControllerRevision] <*> arbitrary -- v1ControllerRevisionListKind :: Maybe Text <*> arbitrary -- v1ControllerRevisionListMetadata :: Maybe V1ListMeta instance Arbitrary V1CrossVersionObjectReference where arbitrary = V1CrossVersionObjectReference <$> arbitrary -- v1CrossVersionObjectReferenceApiVersion :: Maybe Text <*> arbitrary -- v1CrossVersionObjectReferenceKind :: Text <*> arbitrary -- v1CrossVersionObjectReferenceName :: Text instance Arbitrary V1DaemonEndpoint where arbitrary = V1DaemonEndpoint <$> arbitrary -- v1DaemonEndpointPort :: Int instance Arbitrary V1DaemonSet where arbitrary = V1DaemonSet <$> arbitrary -- v1DaemonSetApiVersion :: Maybe Text <*> arbitrary -- v1DaemonSetKind :: Maybe Text <*> arbitrary -- v1DaemonSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1DaemonSetSpec :: Maybe V1DaemonSetSpec <*> arbitrary -- v1DaemonSetStatus :: Maybe V1DaemonSetStatus instance Arbitrary V1DaemonSetCondition where arbitrary = V1DaemonSetCondition <$> arbitrary -- v1DaemonSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1DaemonSetConditionMessage :: Maybe Text <*> arbitrary -- v1DaemonSetConditionReason :: Maybe Text <*> arbitrary -- v1DaemonSetConditionStatus :: Text <*> arbitrary -- v1DaemonSetConditionType :: Text instance Arbitrary V1DaemonSetList where arbitrary = V1DaemonSetList <$> arbitrary -- v1DaemonSetListApiVersion :: Maybe Text <*> arbitrary -- v1DaemonSetListItems :: [V1DaemonSet] <*> arbitrary -- v1DaemonSetListKind :: Maybe Text <*> arbitrary -- v1DaemonSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1DaemonSetSpec where arbitrary = V1DaemonSetSpec <$> arbitrary -- v1DaemonSetSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1DaemonSetSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- v1DaemonSetSpecSelector :: V1LabelSelector <*> arbitrary -- v1DaemonSetSpecTemplate :: V1PodTemplateSpec <*> arbitrary -- v1DaemonSetSpecUpdateStrategy :: Maybe V1DaemonSetUpdateStrategy instance Arbitrary V1DaemonSetStatus where arbitrary = V1DaemonSetStatus <$> arbitrary -- v1DaemonSetStatusCollisionCount :: Maybe Int <*> arbitrary -- v1DaemonSetStatusConditions :: Maybe [V1DaemonSetCondition] <*> arbitrary -- v1DaemonSetStatusCurrentNumberScheduled :: Int <*> arbitrary -- v1DaemonSetStatusDesiredNumberScheduled :: Int <*> arbitrary -- v1DaemonSetStatusNumberAvailable :: Maybe Int <*> arbitrary -- v1DaemonSetStatusNumberMisscheduled :: Int <*> arbitrary -- v1DaemonSetStatusNumberReady :: Int <*> arbitrary -- v1DaemonSetStatusNumberUnavailable :: Maybe Int <*> arbitrary -- v1DaemonSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1DaemonSetStatusUpdatedNumberScheduled :: Maybe Int instance Arbitrary V1DaemonSetUpdateStrategy where arbitrary = V1DaemonSetUpdateStrategy <$> arbitrary -- v1DaemonSetUpdateStrategyRollingUpdate :: Maybe V1RollingUpdateDaemonSet <*> arbitrary -- v1DaemonSetUpdateStrategyType :: Maybe Text instance Arbitrary V1DeleteOptions where arbitrary = V1DeleteOptions <$> arbitrary -- v1DeleteOptionsApiVersion :: Maybe Text <*> arbitrary -- v1DeleteOptionsGracePeriodSeconds :: Maybe Integer <*> arbitrary -- v1DeleteOptionsKind :: Maybe Text <*> arbitrary -- v1DeleteOptionsOrphanDependents :: Maybe Bool <*> arbitrary -- v1DeleteOptionsPreconditions :: Maybe V1Preconditions <*> arbitrary -- v1DeleteOptionsPropagationPolicy :: Maybe Text instance Arbitrary V1Deployment where arbitrary = V1Deployment <$> arbitrary -- v1DeploymentApiVersion :: Maybe Text <*> arbitrary -- v1DeploymentKind :: Maybe Text <*> arbitrary -- v1DeploymentMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1DeploymentSpec :: Maybe V1DeploymentSpec <*> arbitrary -- v1DeploymentStatus :: Maybe V1DeploymentStatus instance Arbitrary V1DeploymentCondition where arbitrary = V1DeploymentCondition <$> arbitrary -- v1DeploymentConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1DeploymentConditionLastUpdateTime :: Maybe DateTime <*> arbitrary -- v1DeploymentConditionMessage :: Maybe Text <*> arbitrary -- v1DeploymentConditionReason :: Maybe Text <*> arbitrary -- v1DeploymentConditionStatus :: Text <*> arbitrary -- v1DeploymentConditionType :: Text instance Arbitrary V1DeploymentList where arbitrary = V1DeploymentList <$> arbitrary -- v1DeploymentListApiVersion :: Maybe Text <*> arbitrary -- v1DeploymentListItems :: [V1Deployment] <*> arbitrary -- v1DeploymentListKind :: Maybe Text <*> arbitrary -- v1DeploymentListMetadata :: Maybe V1ListMeta instance Arbitrary V1DeploymentSpec where arbitrary = V1DeploymentSpec <$> arbitrary -- v1DeploymentSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1DeploymentSpecPaused :: Maybe Bool <*> arbitrary -- v1DeploymentSpecProgressDeadlineSeconds :: Maybe Int <*> arbitrary -- v1DeploymentSpecReplicas :: Maybe Int <*> arbitrary -- v1DeploymentSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- v1DeploymentSpecSelector :: V1LabelSelector <*> arbitrary -- v1DeploymentSpecStrategy :: Maybe V1DeploymentStrategy <*> arbitrary -- v1DeploymentSpecTemplate :: V1PodTemplateSpec instance Arbitrary V1DeploymentStatus where arbitrary = V1DeploymentStatus <$> arbitrary -- v1DeploymentStatusAvailableReplicas :: Maybe Int <*> arbitrary -- v1DeploymentStatusCollisionCount :: Maybe Int <*> arbitrary -- v1DeploymentStatusConditions :: Maybe [V1DeploymentCondition] <*> arbitrary -- v1DeploymentStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1DeploymentStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1DeploymentStatusReplicas :: Maybe Int <*> arbitrary -- v1DeploymentStatusUnavailableReplicas :: Maybe Int <*> arbitrary -- v1DeploymentStatusUpdatedReplicas :: Maybe Int instance Arbitrary V1DeploymentStrategy where arbitrary = V1DeploymentStrategy <$> arbitrary -- v1DeploymentStrategyRollingUpdate :: Maybe V1RollingUpdateDeployment <*> arbitrary -- v1DeploymentStrategyType :: Maybe Text instance Arbitrary V1DownwardAPIProjection where arbitrary = V1DownwardAPIProjection <$> arbitrary -- v1DownwardAPIProjectionItems :: Maybe [V1DownwardAPIVolumeFile] instance Arbitrary V1DownwardAPIVolumeFile where arbitrary = V1DownwardAPIVolumeFile <$> arbitrary -- v1DownwardAPIVolumeFileFieldRef :: Maybe V1ObjectFieldSelector <*> arbitrary -- v1DownwardAPIVolumeFileMode :: Maybe Int <*> arbitrary -- v1DownwardAPIVolumeFilePath :: Text <*> arbitrary -- v1DownwardAPIVolumeFileResourceFieldRef :: Maybe V1ResourceFieldSelector instance Arbitrary V1DownwardAPIVolumeSource where arbitrary = V1DownwardAPIVolumeSource <$> arbitrary -- v1DownwardAPIVolumeSourceDefaultMode :: Maybe Int <*> arbitrary -- v1DownwardAPIVolumeSourceItems :: Maybe [V1DownwardAPIVolumeFile] instance Arbitrary V1EmptyDirVolumeSource where arbitrary = V1EmptyDirVolumeSource <$> arbitrary -- v1EmptyDirVolumeSourceMedium :: Maybe Text <*> arbitrary -- v1EmptyDirVolumeSourceSizeLimit :: Maybe Text instance Arbitrary V1EndpointAddress where arbitrary = V1EndpointAddress <$> arbitrary -- v1EndpointAddressHostname :: Maybe Text <*> arbitrary -- v1EndpointAddressIp :: Text <*> arbitrary -- v1EndpointAddressNodeName :: Maybe Text <*> arbitrary -- v1EndpointAddressTargetRef :: Maybe V1ObjectReference instance Arbitrary V1EndpointPort where arbitrary = V1EndpointPort <$> arbitrary -- v1EndpointPortName :: Maybe Text <*> arbitrary -- v1EndpointPortPort :: Int <*> arbitrary -- v1EndpointPortProtocol :: Maybe Text instance Arbitrary V1EndpointSubset where arbitrary = V1EndpointSubset <$> arbitrary -- v1EndpointSubsetAddresses :: Maybe [V1EndpointAddress] <*> arbitrary -- v1EndpointSubsetNotReadyAddresses :: Maybe [V1EndpointAddress] <*> arbitrary -- v1EndpointSubsetPorts :: Maybe [V1EndpointPort] instance Arbitrary V1Endpoints where arbitrary = V1Endpoints <$> arbitrary -- v1EndpointsApiVersion :: Maybe Text <*> arbitrary -- v1EndpointsKind :: Maybe Text <*> arbitrary -- v1EndpointsMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1EndpointsSubsets :: [V1EndpointSubset] instance Arbitrary V1EndpointsList where arbitrary = V1EndpointsList <$> arbitrary -- v1EndpointsListApiVersion :: Maybe Text <*> arbitrary -- v1EndpointsListItems :: [V1Endpoints] <*> arbitrary -- v1EndpointsListKind :: Maybe Text <*> arbitrary -- v1EndpointsListMetadata :: Maybe V1ListMeta instance Arbitrary V1EnvFromSource where arbitrary = V1EnvFromSource <$> arbitrary -- v1EnvFromSourceConfigMapRef :: Maybe V1ConfigMapEnvSource <*> arbitrary -- v1EnvFromSourcePrefix :: Maybe Text <*> arbitrary -- v1EnvFromSourceSecretRef :: Maybe V1SecretEnvSource instance Arbitrary V1EnvVar where arbitrary = V1EnvVar <$> arbitrary -- v1EnvVarName :: Text <*> arbitrary -- v1EnvVarValue :: Maybe Text <*> arbitrary -- v1EnvVarValueFrom :: Maybe V1EnvVarSource instance Arbitrary V1EnvVarSource where arbitrary = V1EnvVarSource <$> arbitrary -- v1EnvVarSourceConfigMapKeyRef :: Maybe V1ConfigMapKeySelector <*> arbitrary -- v1EnvVarSourceFieldRef :: Maybe V1ObjectFieldSelector <*> arbitrary -- v1EnvVarSourceResourceFieldRef :: Maybe V1ResourceFieldSelector <*> arbitrary -- v1EnvVarSourceSecretKeyRef :: Maybe V1SecretKeySelector instance Arbitrary V1Event where arbitrary = V1Event <$> arbitrary -- v1EventAction :: Maybe Text <*> arbitrary -- v1EventApiVersion :: Maybe Text <*> arbitrary -- v1EventCount :: Maybe Int <*> arbitrary -- v1EventEventTime :: Maybe DateTime <*> arbitrary -- v1EventFirstTimestamp :: Maybe DateTime <*> arbitrary -- v1EventInvolvedObject :: V1ObjectReference <*> arbitrary -- v1EventKind :: Maybe Text <*> arbitrary -- v1EventLastTimestamp :: Maybe DateTime <*> arbitrary -- v1EventMessage :: Maybe Text <*> arbitrary -- v1EventMetadata :: V1ObjectMeta <*> arbitrary -- v1EventReason :: Maybe Text <*> arbitrary -- v1EventRelated :: Maybe V1ObjectReference <*> arbitrary -- v1EventReportingComponent :: Maybe Text <*> arbitrary -- v1EventReportingInstance :: Maybe Text <*> arbitrary -- v1EventSeries :: Maybe V1EventSeries <*> arbitrary -- v1EventSource :: Maybe V1EventSource <*> arbitrary -- v1EventType :: Maybe Text instance Arbitrary V1EventList where arbitrary = V1EventList <$> arbitrary -- v1EventListApiVersion :: Maybe Text <*> arbitrary -- v1EventListItems :: [V1Event] <*> arbitrary -- v1EventListKind :: Maybe Text <*> arbitrary -- v1EventListMetadata :: Maybe V1ListMeta instance Arbitrary V1EventSeries where arbitrary = V1EventSeries <$> arbitrary -- v1EventSeriesCount :: Maybe Int <*> arbitrary -- v1EventSeriesLastObservedTime :: Maybe DateTime <*> arbitrary -- v1EventSeriesState :: Maybe Text instance Arbitrary V1EventSource where arbitrary = V1EventSource <$> arbitrary -- v1EventSourceComponent :: Maybe Text <*> arbitrary -- v1EventSourceHost :: Maybe Text instance Arbitrary V1ExecAction where arbitrary = V1ExecAction <$> arbitrary -- v1ExecActionCommand :: Maybe [Text] instance Arbitrary V1FCVolumeSource where arbitrary = V1FCVolumeSource <$> arbitrary -- v1FCVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1FCVolumeSourceLun :: Maybe Int <*> arbitrary -- v1FCVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1FCVolumeSourceTargetWwNs :: Maybe [Text] <*> arbitrary -- v1FCVolumeSourceWwids :: Maybe [Text] instance Arbitrary V1FlexVolumeSource where arbitrary = V1FlexVolumeSource <$> arbitrary -- v1FlexVolumeSourceDriver :: Text <*> arbitrary -- v1FlexVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1FlexVolumeSourceOptions :: Maybe (Map.Map String Text) <*> arbitrary -- v1FlexVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1FlexVolumeSourceSecretRef :: Maybe V1LocalObjectReference instance Arbitrary V1FlockerVolumeSource where arbitrary = V1FlockerVolumeSource <$> arbitrary -- v1FlockerVolumeSourceDatasetName :: Maybe Text <*> arbitrary -- v1FlockerVolumeSourceDatasetUuid :: Maybe Text instance Arbitrary V1GCEPersistentDiskVolumeSource where arbitrary = V1GCEPersistentDiskVolumeSource <$> arbitrary -- v1GCEPersistentDiskVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1GCEPersistentDiskVolumeSourcePartition :: Maybe Int <*> arbitrary -- v1GCEPersistentDiskVolumeSourcePdName :: Text <*> arbitrary -- v1GCEPersistentDiskVolumeSourceReadOnly :: Maybe Bool instance Arbitrary V1GitRepoVolumeSource where arbitrary = V1GitRepoVolumeSource <$> arbitrary -- v1GitRepoVolumeSourceDirectory :: Maybe Text <*> arbitrary -- v1GitRepoVolumeSourceRepository :: Text <*> arbitrary -- v1GitRepoVolumeSourceRevision :: Maybe Text instance Arbitrary V1GlusterfsVolumeSource where arbitrary = V1GlusterfsVolumeSource <$> arbitrary -- v1GlusterfsVolumeSourceEndpoints :: Text <*> arbitrary -- v1GlusterfsVolumeSourcePath :: Text <*> arbitrary -- v1GlusterfsVolumeSourceReadOnly :: Maybe Bool instance Arbitrary V1GroupVersionForDiscovery where arbitrary = V1GroupVersionForDiscovery <$> arbitrary -- v1GroupVersionForDiscoveryGroupVersion :: Text <*> arbitrary -- v1GroupVersionForDiscoveryVersion :: Text instance Arbitrary V1HTTPGetAction where arbitrary = V1HTTPGetAction <$> arbitrary -- v1HTTPGetActionHost :: Maybe Text <*> arbitrary -- v1HTTPGetActionHttpHeaders :: Maybe [V1HTTPHeader] <*> arbitrary -- v1HTTPGetActionPath :: Maybe Text <*> arbitrary -- v1HTTPGetActionPort :: A.Value <*> arbitrary -- v1HTTPGetActionScheme :: Maybe Text instance Arbitrary V1HTTPHeader where arbitrary = V1HTTPHeader <$> arbitrary -- v1HTTPHeaderName :: Text <*> arbitrary -- v1HTTPHeaderValue :: Text instance Arbitrary V1Handler where arbitrary = V1Handler <$> arbitrary -- v1HandlerExec :: Maybe V1ExecAction <*> arbitrary -- v1HandlerHttpGet :: Maybe V1HTTPGetAction <*> arbitrary -- v1HandlerTcpSocket :: Maybe V1TCPSocketAction instance Arbitrary V1HorizontalPodAutoscaler where arbitrary = V1HorizontalPodAutoscaler <$> arbitrary -- v1HorizontalPodAutoscalerApiVersion :: Maybe Text <*> arbitrary -- v1HorizontalPodAutoscalerKind :: Maybe Text <*> arbitrary -- v1HorizontalPodAutoscalerMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1HorizontalPodAutoscalerSpec :: Maybe V1HorizontalPodAutoscalerSpec <*> arbitrary -- v1HorizontalPodAutoscalerStatus :: Maybe V1HorizontalPodAutoscalerStatus instance Arbitrary V1HorizontalPodAutoscalerList where arbitrary = V1HorizontalPodAutoscalerList <$> arbitrary -- v1HorizontalPodAutoscalerListApiVersion :: Maybe Text <*> arbitrary -- v1HorizontalPodAutoscalerListItems :: [V1HorizontalPodAutoscaler] <*> arbitrary -- v1HorizontalPodAutoscalerListKind :: Maybe Text <*> arbitrary -- v1HorizontalPodAutoscalerListMetadata :: Maybe V1ListMeta instance Arbitrary V1HorizontalPodAutoscalerSpec where arbitrary = V1HorizontalPodAutoscalerSpec <$> arbitrary -- v1HorizontalPodAutoscalerSpecMaxReplicas :: Int <*> arbitrary -- v1HorizontalPodAutoscalerSpecMinReplicas :: Maybe Int <*> arbitrary -- v1HorizontalPodAutoscalerSpecScaleTargetRef :: V1CrossVersionObjectReference <*> arbitrary -- v1HorizontalPodAutoscalerSpecTargetCpuUtilizationPercentage :: Maybe Int instance Arbitrary V1HorizontalPodAutoscalerStatus where arbitrary = V1HorizontalPodAutoscalerStatus <$> arbitrary -- v1HorizontalPodAutoscalerStatusCurrentCpuUtilizationPercentage :: Maybe Int <*> arbitrary -- v1HorizontalPodAutoscalerStatusCurrentReplicas :: Int <*> arbitrary -- v1HorizontalPodAutoscalerStatusDesiredReplicas :: Int <*> arbitrary -- v1HorizontalPodAutoscalerStatusLastScaleTime :: Maybe DateTime <*> arbitrary -- v1HorizontalPodAutoscalerStatusObservedGeneration :: Maybe Integer instance Arbitrary V1HostAlias where arbitrary = V1HostAlias <$> arbitrary -- v1HostAliasHostnames :: Maybe [Text] <*> arbitrary -- v1HostAliasIp :: Maybe Text instance Arbitrary V1HostPathVolumeSource where arbitrary = V1HostPathVolumeSource <$> arbitrary -- v1HostPathVolumeSourcePath :: Text <*> arbitrary -- v1HostPathVolumeSourceType :: Maybe Text instance Arbitrary V1IPBlock where arbitrary = V1IPBlock <$> arbitrary -- v1IPBlockCidr :: Text <*> arbitrary -- v1IPBlockExcept :: Maybe [Text] instance Arbitrary V1ISCSIPersistentVolumeSource where arbitrary = V1ISCSIPersistentVolumeSource <$> arbitrary -- v1ISCSIPersistentVolumeSourceChapAuthDiscovery :: Maybe Bool <*> arbitrary -- v1ISCSIPersistentVolumeSourceChapAuthSession :: Maybe Bool <*> arbitrary -- v1ISCSIPersistentVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1ISCSIPersistentVolumeSourceInitiatorName :: Maybe Text <*> arbitrary -- v1ISCSIPersistentVolumeSourceIqn :: Text <*> arbitrary -- v1ISCSIPersistentVolumeSourceIscsiInterface :: Maybe Text <*> arbitrary -- v1ISCSIPersistentVolumeSourceLun :: Int <*> arbitrary -- v1ISCSIPersistentVolumeSourcePortals :: Maybe [Text] <*> arbitrary -- v1ISCSIPersistentVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1ISCSIPersistentVolumeSourceSecretRef :: Maybe V1SecretReference <*> arbitrary -- v1ISCSIPersistentVolumeSourceTargetPortal :: Text instance Arbitrary V1ISCSIVolumeSource where arbitrary = V1ISCSIVolumeSource <$> arbitrary -- v1ISCSIVolumeSourceChapAuthDiscovery :: Maybe Bool <*> arbitrary -- v1ISCSIVolumeSourceChapAuthSession :: Maybe Bool <*> arbitrary -- v1ISCSIVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1ISCSIVolumeSourceInitiatorName :: Maybe Text <*> arbitrary -- v1ISCSIVolumeSourceIqn :: Text <*> arbitrary -- v1ISCSIVolumeSourceIscsiInterface :: Maybe Text <*> arbitrary -- v1ISCSIVolumeSourceLun :: Int <*> arbitrary -- v1ISCSIVolumeSourcePortals :: Maybe [Text] <*> arbitrary -- v1ISCSIVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1ISCSIVolumeSourceSecretRef :: Maybe V1LocalObjectReference <*> arbitrary -- v1ISCSIVolumeSourceTargetPortal :: Text instance Arbitrary V1Initializer where arbitrary = V1Initializer <$> arbitrary -- v1InitializerName :: Text instance Arbitrary V1Initializers where arbitrary = V1Initializers <$> arbitrary -- v1InitializersPending :: [V1Initializer] <*> arbitrary -- v1InitializersResult :: Maybe V1Status instance Arbitrary V1Job where arbitrary = V1Job <$> arbitrary -- v1JobApiVersion :: Maybe Text <*> arbitrary -- v1JobKind :: Maybe Text <*> arbitrary -- v1JobMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1JobSpec :: Maybe V1JobSpec <*> arbitrary -- v1JobStatus :: Maybe V1JobStatus instance Arbitrary V1JobCondition where arbitrary = V1JobCondition <$> arbitrary -- v1JobConditionLastProbeTime :: Maybe DateTime <*> arbitrary -- v1JobConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1JobConditionMessage :: Maybe Text <*> arbitrary -- v1JobConditionReason :: Maybe Text <*> arbitrary -- v1JobConditionStatus :: Text <*> arbitrary -- v1JobConditionType :: Text instance Arbitrary V1JobList where arbitrary = V1JobList <$> arbitrary -- v1JobListApiVersion :: Maybe Text <*> arbitrary -- v1JobListItems :: [V1Job] <*> arbitrary -- v1JobListKind :: Maybe Text <*> arbitrary -- v1JobListMetadata :: Maybe V1ListMeta instance Arbitrary V1JobSpec where arbitrary = V1JobSpec <$> arbitrary -- v1JobSpecActiveDeadlineSeconds :: Maybe Integer <*> arbitrary -- v1JobSpecBackoffLimit :: Maybe Int <*> arbitrary -- v1JobSpecCompletions :: Maybe Int <*> arbitrary -- v1JobSpecManualSelector :: Maybe Bool <*> arbitrary -- v1JobSpecParallelism :: Maybe Int <*> arbitrary -- v1JobSpecSelector :: Maybe V1LabelSelector <*> arbitrary -- v1JobSpecTemplate :: V1PodTemplateSpec instance Arbitrary V1JobStatus where arbitrary = V1JobStatus <$> arbitrary -- v1JobStatusActive :: Maybe Int <*> arbitrary -- v1JobStatusCompletionTime :: Maybe DateTime <*> arbitrary -- v1JobStatusConditions :: Maybe [V1JobCondition] <*> arbitrary -- v1JobStatusFailed :: Maybe Int <*> arbitrary -- v1JobStatusStartTime :: Maybe DateTime <*> arbitrary -- v1JobStatusSucceeded :: Maybe Int instance Arbitrary V1KeyToPath where arbitrary = V1KeyToPath <$> arbitrary -- v1KeyToPathKey :: Text <*> arbitrary -- v1KeyToPathMode :: Maybe Int <*> arbitrary -- v1KeyToPathPath :: Text instance Arbitrary V1LabelSelector where arbitrary = V1LabelSelector <$> arbitrary -- v1LabelSelectorMatchExpressions :: Maybe [V1LabelSelectorRequirement] <*> arbitrary -- v1LabelSelectorMatchLabels :: Maybe (Map.Map String Text) instance Arbitrary V1LabelSelectorRequirement where arbitrary = V1LabelSelectorRequirement <$> arbitrary -- v1LabelSelectorRequirementKey :: Text <*> arbitrary -- v1LabelSelectorRequirementOperator :: Text <*> arbitrary -- v1LabelSelectorRequirementValues :: Maybe [Text] instance Arbitrary V1Lifecycle where arbitrary = V1Lifecycle <$> arbitrary -- v1LifecyclePostStart :: Maybe V1Handler <*> arbitrary -- v1LifecyclePreStop :: Maybe V1Handler instance Arbitrary V1LimitRange where arbitrary = V1LimitRange <$> arbitrary -- v1LimitRangeApiVersion :: Maybe Text <*> arbitrary -- v1LimitRangeKind :: Maybe Text <*> arbitrary -- v1LimitRangeMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1LimitRangeSpec :: Maybe V1LimitRangeSpec instance Arbitrary V1LimitRangeItem where arbitrary = V1LimitRangeItem <$> arbitrary -- v1LimitRangeItemDefault :: Maybe (Map.Map String Text) <*> arbitrary -- v1LimitRangeItemDefaultRequest :: Maybe (Map.Map String Text) <*> arbitrary -- v1LimitRangeItemMax :: Maybe (Map.Map String Text) <*> arbitrary -- v1LimitRangeItemMaxLimitRequestRatio :: Maybe (Map.Map String Text) <*> arbitrary -- v1LimitRangeItemMin :: Maybe (Map.Map String Text) <*> arbitrary -- v1LimitRangeItemType :: Maybe Text instance Arbitrary V1LimitRangeList where arbitrary = V1LimitRangeList <$> arbitrary -- v1LimitRangeListApiVersion :: Maybe Text <*> arbitrary -- v1LimitRangeListItems :: [V1LimitRange] <*> arbitrary -- v1LimitRangeListKind :: Maybe Text <*> arbitrary -- v1LimitRangeListMetadata :: Maybe V1ListMeta instance Arbitrary V1LimitRangeSpec where arbitrary = V1LimitRangeSpec <$> arbitrary -- v1LimitRangeSpecLimits :: [V1LimitRangeItem] instance Arbitrary V1ListMeta where arbitrary = V1ListMeta <$> arbitrary -- v1ListMetaContinue :: Maybe Text <*> arbitrary -- v1ListMetaResourceVersion :: Maybe Text <*> arbitrary -- v1ListMetaSelfLink :: Maybe Text instance Arbitrary V1LoadBalancerIngress where arbitrary = V1LoadBalancerIngress <$> arbitrary -- v1LoadBalancerIngressHostname :: Maybe Text <*> arbitrary -- v1LoadBalancerIngressIp :: Maybe Text instance Arbitrary V1LoadBalancerStatus where arbitrary = V1LoadBalancerStatus <$> arbitrary -- v1LoadBalancerStatusIngress :: Maybe [V1LoadBalancerIngress] instance Arbitrary V1LocalObjectReference where arbitrary = V1LocalObjectReference <$> arbitrary -- v1LocalObjectReferenceName :: Maybe Text instance Arbitrary V1LocalSubjectAccessReview where arbitrary = V1LocalSubjectAccessReview <$> arbitrary -- v1LocalSubjectAccessReviewApiVersion :: Maybe Text <*> arbitrary -- v1LocalSubjectAccessReviewKind :: Maybe Text <*> arbitrary -- v1LocalSubjectAccessReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1LocalSubjectAccessReviewSpec :: V1SubjectAccessReviewSpec <*> arbitrary -- v1LocalSubjectAccessReviewStatus :: Maybe V1SubjectAccessReviewStatus instance Arbitrary V1LocalVolumeSource where arbitrary = V1LocalVolumeSource <$> arbitrary -- v1LocalVolumeSourcePath :: Text instance Arbitrary V1NFSVolumeSource where arbitrary = V1NFSVolumeSource <$> arbitrary -- v1NFSVolumeSourcePath :: Text <*> arbitrary -- v1NFSVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1NFSVolumeSourceServer :: Text instance Arbitrary V1Namespace where arbitrary = V1Namespace <$> arbitrary -- v1NamespaceApiVersion :: Maybe Text <*> arbitrary -- v1NamespaceKind :: Maybe Text <*> arbitrary -- v1NamespaceMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1NamespaceSpec :: Maybe V1NamespaceSpec <*> arbitrary -- v1NamespaceStatus :: Maybe V1NamespaceStatus instance Arbitrary V1NamespaceList where arbitrary = V1NamespaceList <$> arbitrary -- v1NamespaceListApiVersion :: Maybe Text <*> arbitrary -- v1NamespaceListItems :: [V1Namespace] <*> arbitrary -- v1NamespaceListKind :: Maybe Text <*> arbitrary -- v1NamespaceListMetadata :: Maybe V1ListMeta instance Arbitrary V1NamespaceSpec where arbitrary = V1NamespaceSpec <$> arbitrary -- v1NamespaceSpecFinalizers :: Maybe [Text] instance Arbitrary V1NamespaceStatus where arbitrary = V1NamespaceStatus <$> arbitrary -- v1NamespaceStatusPhase :: Maybe Text instance Arbitrary V1NetworkPolicy where arbitrary = V1NetworkPolicy <$> arbitrary -- v1NetworkPolicyApiVersion :: Maybe Text <*> arbitrary -- v1NetworkPolicyKind :: Maybe Text <*> arbitrary -- v1NetworkPolicyMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1NetworkPolicySpec :: Maybe V1NetworkPolicySpec instance Arbitrary V1NetworkPolicyEgressRule where arbitrary = V1NetworkPolicyEgressRule <$> arbitrary -- v1NetworkPolicyEgressRulePorts :: Maybe [V1NetworkPolicyPort] <*> arbitrary -- v1NetworkPolicyEgressRuleTo :: Maybe [V1NetworkPolicyPeer] instance Arbitrary V1NetworkPolicyIngressRule where arbitrary = V1NetworkPolicyIngressRule <$> arbitrary -- v1NetworkPolicyIngressRuleFrom :: Maybe [V1NetworkPolicyPeer] <*> arbitrary -- v1NetworkPolicyIngressRulePorts :: Maybe [V1NetworkPolicyPort] instance Arbitrary V1NetworkPolicyList where arbitrary = V1NetworkPolicyList <$> arbitrary -- v1NetworkPolicyListApiVersion :: Maybe Text <*> arbitrary -- v1NetworkPolicyListItems :: [V1NetworkPolicy] <*> arbitrary -- v1NetworkPolicyListKind :: Maybe Text <*> arbitrary -- v1NetworkPolicyListMetadata :: Maybe V1ListMeta instance Arbitrary V1NetworkPolicyPeer where arbitrary = V1NetworkPolicyPeer <$> arbitrary -- v1NetworkPolicyPeerIpBlock :: Maybe V1IPBlock <*> arbitrary -- v1NetworkPolicyPeerNamespaceSelector :: Maybe V1LabelSelector <*> arbitrary -- v1NetworkPolicyPeerPodSelector :: Maybe V1LabelSelector instance Arbitrary V1NetworkPolicyPort where arbitrary = V1NetworkPolicyPort <$> arbitrary -- v1NetworkPolicyPortPort :: Maybe A.Value <*> arbitrary -- v1NetworkPolicyPortProtocol :: Maybe Text instance Arbitrary V1NetworkPolicySpec where arbitrary = V1NetworkPolicySpec <$> arbitrary -- v1NetworkPolicySpecEgress :: Maybe [V1NetworkPolicyEgressRule] <*> arbitrary -- v1NetworkPolicySpecIngress :: Maybe [V1NetworkPolicyIngressRule] <*> arbitrary -- v1NetworkPolicySpecPodSelector :: V1LabelSelector <*> arbitrary -- v1NetworkPolicySpecPolicyTypes :: Maybe [Text] instance Arbitrary V1Node where arbitrary = V1Node <$> arbitrary -- v1NodeApiVersion :: Maybe Text <*> arbitrary -- v1NodeKind :: Maybe Text <*> arbitrary -- v1NodeMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1NodeSpec :: Maybe V1NodeSpec <*> arbitrary -- v1NodeStatus :: Maybe V1NodeStatus instance Arbitrary V1NodeAddress where arbitrary = V1NodeAddress <$> arbitrary -- v1NodeAddressAddress :: Text <*> arbitrary -- v1NodeAddressType :: Text instance Arbitrary V1NodeAffinity where arbitrary = V1NodeAffinity <$> arbitrary -- v1NodeAffinityPreferredDuringSchedulingIgnoredDuringExecution :: Maybe [V1PreferredSchedulingTerm] <*> arbitrary -- v1NodeAffinityRequiredDuringSchedulingIgnoredDuringExecution :: Maybe V1NodeSelector instance Arbitrary V1NodeCondition where arbitrary = V1NodeCondition <$> arbitrary -- v1NodeConditionLastHeartbeatTime :: Maybe DateTime <*> arbitrary -- v1NodeConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1NodeConditionMessage :: Maybe Text <*> arbitrary -- v1NodeConditionReason :: Maybe Text <*> arbitrary -- v1NodeConditionStatus :: Text <*> arbitrary -- v1NodeConditionType :: Text instance Arbitrary V1NodeConfigSource where arbitrary = V1NodeConfigSource <$> arbitrary -- v1NodeConfigSourceApiVersion :: Maybe Text <*> arbitrary -- v1NodeConfigSourceConfigMapRef :: Maybe V1ObjectReference <*> arbitrary -- v1NodeConfigSourceKind :: Maybe Text instance Arbitrary V1NodeDaemonEndpoints where arbitrary = V1NodeDaemonEndpoints <$> arbitrary -- v1NodeDaemonEndpointsKubeletEndpoint :: Maybe V1DaemonEndpoint instance Arbitrary V1NodeList where arbitrary = V1NodeList <$> arbitrary -- v1NodeListApiVersion :: Maybe Text <*> arbitrary -- v1NodeListItems :: [V1Node] <*> arbitrary -- v1NodeListKind :: Maybe Text <*> arbitrary -- v1NodeListMetadata :: Maybe V1ListMeta instance Arbitrary V1NodeSelector where arbitrary = V1NodeSelector <$> arbitrary -- v1NodeSelectorNodeSelectorTerms :: [V1NodeSelectorTerm] instance Arbitrary V1NodeSelectorRequirement where arbitrary = V1NodeSelectorRequirement <$> arbitrary -- v1NodeSelectorRequirementKey :: Text <*> arbitrary -- v1NodeSelectorRequirementOperator :: Text <*> arbitrary -- v1NodeSelectorRequirementValues :: Maybe [Text] instance Arbitrary V1NodeSelectorTerm where arbitrary = V1NodeSelectorTerm <$> arbitrary -- v1NodeSelectorTermMatchExpressions :: [V1NodeSelectorRequirement] instance Arbitrary V1NodeSpec where arbitrary = V1NodeSpec <$> arbitrary -- v1NodeSpecConfigSource :: Maybe V1NodeConfigSource <*> arbitrary -- v1NodeSpecExternalId :: Maybe Text <*> arbitrary -- v1NodeSpecPodCidr :: Maybe Text <*> arbitrary -- v1NodeSpecProviderId :: Maybe Text <*> arbitrary -- v1NodeSpecTaints :: Maybe [V1Taint] <*> arbitrary -- v1NodeSpecUnschedulable :: Maybe Bool instance Arbitrary V1NodeStatus where arbitrary = V1NodeStatus <$> arbitrary -- v1NodeStatusAddresses :: Maybe [V1NodeAddress] <*> arbitrary -- v1NodeStatusAllocatable :: Maybe (Map.Map String Text) <*> arbitrary -- v1NodeStatusCapacity :: Maybe (Map.Map String Text) <*> arbitrary -- v1NodeStatusConditions :: Maybe [V1NodeCondition] <*> arbitrary -- v1NodeStatusDaemonEndpoints :: Maybe V1NodeDaemonEndpoints <*> arbitrary -- v1NodeStatusImages :: Maybe [V1ContainerImage] <*> arbitrary -- v1NodeStatusNodeInfo :: Maybe V1NodeSystemInfo <*> arbitrary -- v1NodeStatusPhase :: Maybe Text <*> arbitrary -- v1NodeStatusVolumesAttached :: Maybe [V1AttachedVolume] <*> arbitrary -- v1NodeStatusVolumesInUse :: Maybe [Text] instance Arbitrary V1NodeSystemInfo where arbitrary = V1NodeSystemInfo <$> arbitrary -- v1NodeSystemInfoArchitecture :: Text <*> arbitrary -- v1NodeSystemInfoBootId :: Text <*> arbitrary -- v1NodeSystemInfoContainerRuntimeVersion :: Text <*> arbitrary -- v1NodeSystemInfoKernelVersion :: Text <*> arbitrary -- v1NodeSystemInfoKubeProxyVersion :: Text <*> arbitrary -- v1NodeSystemInfoKubeletVersion :: Text <*> arbitrary -- v1NodeSystemInfoMachineId :: Text <*> arbitrary -- v1NodeSystemInfoOperatingSystem :: Text <*> arbitrary -- v1NodeSystemInfoOsImage :: Text <*> arbitrary -- v1NodeSystemInfoSystemUuid :: Text instance Arbitrary V1NonResourceAttributes where arbitrary = V1NonResourceAttributes <$> arbitrary -- v1NonResourceAttributesPath :: Maybe Text <*> arbitrary -- v1NonResourceAttributesVerb :: Maybe Text instance Arbitrary V1NonResourceRule where arbitrary = V1NonResourceRule <$> arbitrary -- v1NonResourceRuleNonResourceUrLs :: Maybe [Text] <*> arbitrary -- v1NonResourceRuleVerbs :: [Text] instance Arbitrary V1ObjectFieldSelector where arbitrary = V1ObjectFieldSelector <$> arbitrary -- v1ObjectFieldSelectorApiVersion :: Maybe Text <*> arbitrary -- v1ObjectFieldSelectorFieldPath :: Text instance Arbitrary V1ObjectMeta where arbitrary = V1ObjectMeta <$> arbitrary -- v1ObjectMetaAnnotations :: Maybe (Map.Map String Text) <*> arbitrary -- v1ObjectMetaClusterName :: Maybe Text <*> arbitrary -- v1ObjectMetaCreationTimestamp :: Maybe DateTime <*> arbitrary -- v1ObjectMetaDeletionGracePeriodSeconds :: Maybe Integer <*> arbitrary -- v1ObjectMetaDeletionTimestamp :: Maybe DateTime <*> arbitrary -- v1ObjectMetaFinalizers :: Maybe [Text] <*> arbitrary -- v1ObjectMetaGenerateName :: Maybe Text <*> arbitrary -- v1ObjectMetaGeneration :: Maybe Integer <*> arbitrary -- v1ObjectMetaInitializers :: Maybe V1Initializers <*> arbitrary -- v1ObjectMetaLabels :: Maybe (Map.Map String Text) <*> arbitrary -- v1ObjectMetaName :: Maybe Text <*> arbitrary -- v1ObjectMetaNamespace :: Maybe Text <*> arbitrary -- v1ObjectMetaOwnerReferences :: Maybe [V1OwnerReference] <*> arbitrary -- v1ObjectMetaResourceVersion :: Maybe Text <*> arbitrary -- v1ObjectMetaSelfLink :: Maybe Text <*> arbitrary -- v1ObjectMetaUid :: Maybe Text instance Arbitrary V1ObjectReference where arbitrary = V1ObjectReference <$> arbitrary -- v1ObjectReferenceApiVersion :: Maybe Text <*> arbitrary -- v1ObjectReferenceFieldPath :: Maybe Text <*> arbitrary -- v1ObjectReferenceKind :: Maybe Text <*> arbitrary -- v1ObjectReferenceName :: Maybe Text <*> arbitrary -- v1ObjectReferenceNamespace :: Maybe Text <*> arbitrary -- v1ObjectReferenceResourceVersion :: Maybe Text <*> arbitrary -- v1ObjectReferenceUid :: Maybe Text instance Arbitrary V1OwnerReference where arbitrary = V1OwnerReference <$> arbitrary -- v1OwnerReferenceApiVersion :: Text <*> arbitrary -- v1OwnerReferenceBlockOwnerDeletion :: Maybe Bool <*> arbitrary -- v1OwnerReferenceController :: Maybe Bool <*> arbitrary -- v1OwnerReferenceKind :: Text <*> arbitrary -- v1OwnerReferenceName :: Text <*> arbitrary -- v1OwnerReferenceUid :: Text instance Arbitrary V1PersistentVolume where arbitrary = V1PersistentVolume <$> arbitrary -- v1PersistentVolumeApiVersion :: Maybe Text <*> arbitrary -- v1PersistentVolumeKind :: Maybe Text <*> arbitrary -- v1PersistentVolumeMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1PersistentVolumeSpec :: Maybe V1PersistentVolumeSpec <*> arbitrary -- v1PersistentVolumeStatus :: Maybe V1PersistentVolumeStatus instance Arbitrary V1PersistentVolumeClaim where arbitrary = V1PersistentVolumeClaim <$> arbitrary -- v1PersistentVolumeClaimApiVersion :: Maybe Text <*> arbitrary -- v1PersistentVolumeClaimKind :: Maybe Text <*> arbitrary -- v1PersistentVolumeClaimMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1PersistentVolumeClaimSpec :: Maybe V1PersistentVolumeClaimSpec <*> arbitrary -- v1PersistentVolumeClaimStatus :: Maybe V1PersistentVolumeClaimStatus instance Arbitrary V1PersistentVolumeClaimCondition where arbitrary = V1PersistentVolumeClaimCondition <$> arbitrary -- v1PersistentVolumeClaimConditionLastProbeTime :: Maybe DateTime <*> arbitrary -- v1PersistentVolumeClaimConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1PersistentVolumeClaimConditionMessage :: Maybe Text <*> arbitrary -- v1PersistentVolumeClaimConditionReason :: Maybe Text <*> arbitrary -- v1PersistentVolumeClaimConditionStatus :: Text <*> arbitrary -- v1PersistentVolumeClaimConditionType :: Text instance Arbitrary V1PersistentVolumeClaimList where arbitrary = V1PersistentVolumeClaimList <$> arbitrary -- v1PersistentVolumeClaimListApiVersion :: Maybe Text <*> arbitrary -- v1PersistentVolumeClaimListItems :: [V1PersistentVolumeClaim] <*> arbitrary -- v1PersistentVolumeClaimListKind :: Maybe Text <*> arbitrary -- v1PersistentVolumeClaimListMetadata :: Maybe V1ListMeta instance Arbitrary V1PersistentVolumeClaimSpec where arbitrary = V1PersistentVolumeClaimSpec <$> arbitrary -- v1PersistentVolumeClaimSpecAccessModes :: Maybe [Text] <*> arbitrary -- v1PersistentVolumeClaimSpecResources :: Maybe V1ResourceRequirements <*> arbitrary -- v1PersistentVolumeClaimSpecSelector :: Maybe V1LabelSelector <*> arbitrary -- v1PersistentVolumeClaimSpecStorageClassName :: Maybe Text <*> arbitrary -- v1PersistentVolumeClaimSpecVolumeMode :: Maybe Text <*> arbitrary -- v1PersistentVolumeClaimSpecVolumeName :: Maybe Text instance Arbitrary V1PersistentVolumeClaimStatus where arbitrary = V1PersistentVolumeClaimStatus <$> arbitrary -- v1PersistentVolumeClaimStatusAccessModes :: Maybe [Text] <*> arbitrary -- v1PersistentVolumeClaimStatusCapacity :: Maybe (Map.Map String Text) <*> arbitrary -- v1PersistentVolumeClaimStatusConditions :: Maybe [V1PersistentVolumeClaimCondition] <*> arbitrary -- v1PersistentVolumeClaimStatusPhase :: Maybe Text instance Arbitrary V1PersistentVolumeClaimVolumeSource where arbitrary = V1PersistentVolumeClaimVolumeSource <$> arbitrary -- v1PersistentVolumeClaimVolumeSourceClaimName :: Text <*> arbitrary -- v1PersistentVolumeClaimVolumeSourceReadOnly :: Maybe Bool instance Arbitrary V1PersistentVolumeList where arbitrary = V1PersistentVolumeList <$> arbitrary -- v1PersistentVolumeListApiVersion :: Maybe Text <*> arbitrary -- v1PersistentVolumeListItems :: [V1PersistentVolume] <*> arbitrary -- v1PersistentVolumeListKind :: Maybe Text <*> arbitrary -- v1PersistentVolumeListMetadata :: Maybe V1ListMeta instance Arbitrary V1PersistentVolumeSpec where arbitrary = V1PersistentVolumeSpec <$> arbitrary -- v1PersistentVolumeSpecAccessModes :: Maybe [Text] <*> arbitrary -- v1PersistentVolumeSpecAwsElasticBlockStore :: Maybe V1AWSElasticBlockStoreVolumeSource <*> arbitrary -- v1PersistentVolumeSpecAzureDisk :: Maybe V1AzureDiskVolumeSource <*> arbitrary -- v1PersistentVolumeSpecAzureFile :: Maybe V1AzureFilePersistentVolumeSource <*> arbitrary -- v1PersistentVolumeSpecCapacity :: Maybe (Map.Map String Text) <*> arbitrary -- v1PersistentVolumeSpecCephfs :: Maybe V1CephFSPersistentVolumeSource <*> arbitrary -- v1PersistentVolumeSpecCinder :: Maybe V1CinderVolumeSource <*> arbitrary -- v1PersistentVolumeSpecClaimRef :: Maybe V1ObjectReference <*> arbitrary -- v1PersistentVolumeSpecCsi :: Maybe V1CSIPersistentVolumeSource <*> arbitrary -- v1PersistentVolumeSpecFc :: Maybe V1FCVolumeSource <*> arbitrary -- v1PersistentVolumeSpecFlexVolume :: Maybe V1FlexVolumeSource <*> arbitrary -- v1PersistentVolumeSpecFlocker :: Maybe V1FlockerVolumeSource <*> arbitrary -- v1PersistentVolumeSpecGcePersistentDisk :: Maybe V1GCEPersistentDiskVolumeSource <*> arbitrary -- v1PersistentVolumeSpecGlusterfs :: Maybe V1GlusterfsVolumeSource <*> arbitrary -- v1PersistentVolumeSpecHostPath :: Maybe V1HostPathVolumeSource <*> arbitrary -- v1PersistentVolumeSpecIscsi :: Maybe V1ISCSIPersistentVolumeSource <*> arbitrary -- v1PersistentVolumeSpecLocal :: Maybe V1LocalVolumeSource <*> arbitrary -- v1PersistentVolumeSpecMountOptions :: Maybe [Text] <*> arbitrary -- v1PersistentVolumeSpecNfs :: Maybe V1NFSVolumeSource <*> arbitrary -- v1PersistentVolumeSpecPersistentVolumeReclaimPolicy :: Maybe Text <*> arbitrary -- v1PersistentVolumeSpecPhotonPersistentDisk :: Maybe V1PhotonPersistentDiskVolumeSource <*> arbitrary -- v1PersistentVolumeSpecPortworxVolume :: Maybe V1PortworxVolumeSource <*> arbitrary -- v1PersistentVolumeSpecQuobyte :: Maybe V1QuobyteVolumeSource <*> arbitrary -- v1PersistentVolumeSpecRbd :: Maybe V1RBDPersistentVolumeSource <*> arbitrary -- v1PersistentVolumeSpecScaleIo :: Maybe V1ScaleIOPersistentVolumeSource <*> arbitrary -- v1PersistentVolumeSpecStorageClassName :: Maybe Text <*> arbitrary -- v1PersistentVolumeSpecStorageos :: Maybe V1StorageOSPersistentVolumeSource <*> arbitrary -- v1PersistentVolumeSpecVolumeMode :: Maybe Text <*> arbitrary -- v1PersistentVolumeSpecVsphereVolume :: Maybe V1VsphereVirtualDiskVolumeSource instance Arbitrary V1PersistentVolumeStatus where arbitrary = V1PersistentVolumeStatus <$> arbitrary -- v1PersistentVolumeStatusMessage :: Maybe Text <*> arbitrary -- v1PersistentVolumeStatusPhase :: Maybe Text <*> arbitrary -- v1PersistentVolumeStatusReason :: Maybe Text instance Arbitrary V1PhotonPersistentDiskVolumeSource where arbitrary = V1PhotonPersistentDiskVolumeSource <$> arbitrary -- v1PhotonPersistentDiskVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1PhotonPersistentDiskVolumeSourcePdId :: Text instance Arbitrary V1Pod where arbitrary = V1Pod <$> arbitrary -- v1PodApiVersion :: Maybe Text <*> arbitrary -- v1PodKind :: Maybe Text <*> arbitrary -- v1PodMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1PodSpec :: Maybe V1PodSpec <*> arbitrary -- v1PodStatus :: Maybe V1PodStatus instance Arbitrary V1PodAffinity where arbitrary = V1PodAffinity <$> arbitrary -- v1PodAffinityPreferredDuringSchedulingIgnoredDuringExecution :: Maybe [V1WeightedPodAffinityTerm] <*> arbitrary -- v1PodAffinityRequiredDuringSchedulingIgnoredDuringExecution :: Maybe [V1PodAffinityTerm] instance Arbitrary V1PodAffinityTerm where arbitrary = V1PodAffinityTerm <$> arbitrary -- v1PodAffinityTermLabelSelector :: Maybe V1LabelSelector <*> arbitrary -- v1PodAffinityTermNamespaces :: Maybe [Text] <*> arbitrary -- v1PodAffinityTermTopologyKey :: Text instance Arbitrary V1PodAntiAffinity where arbitrary = V1PodAntiAffinity <$> arbitrary -- v1PodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecution :: Maybe [V1WeightedPodAffinityTerm] <*> arbitrary -- v1PodAntiAffinityRequiredDuringSchedulingIgnoredDuringExecution :: Maybe [V1PodAffinityTerm] instance Arbitrary V1PodCondition where arbitrary = V1PodCondition <$> arbitrary -- v1PodConditionLastProbeTime :: Maybe DateTime <*> arbitrary -- v1PodConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1PodConditionMessage :: Maybe Text <*> arbitrary -- v1PodConditionReason :: Maybe Text <*> arbitrary -- v1PodConditionStatus :: Text <*> arbitrary -- v1PodConditionType :: Text instance Arbitrary V1PodDNSConfig where arbitrary = V1PodDNSConfig <$> arbitrary -- v1PodDNSConfigNameservers :: Maybe [Text] <*> arbitrary -- v1PodDNSConfigOptions :: Maybe [V1PodDNSConfigOption] <*> arbitrary -- v1PodDNSConfigSearches :: Maybe [Text] instance Arbitrary V1PodDNSConfigOption where arbitrary = V1PodDNSConfigOption <$> arbitrary -- v1PodDNSConfigOptionName :: Maybe Text <*> arbitrary -- v1PodDNSConfigOptionValue :: Maybe Text instance Arbitrary V1PodList where arbitrary = V1PodList <$> arbitrary -- v1PodListApiVersion :: Maybe Text <*> arbitrary -- v1PodListItems :: [V1Pod] <*> arbitrary -- v1PodListKind :: Maybe Text <*> arbitrary -- v1PodListMetadata :: Maybe V1ListMeta instance Arbitrary V1PodSecurityContext where arbitrary = V1PodSecurityContext <$> arbitrary -- v1PodSecurityContextFsGroup :: Maybe Integer <*> arbitrary -- v1PodSecurityContextRunAsNonRoot :: Maybe Bool <*> arbitrary -- v1PodSecurityContextRunAsUser :: Maybe Integer <*> arbitrary -- v1PodSecurityContextSeLinuxOptions :: Maybe V1SELinuxOptions <*> arbitrary -- v1PodSecurityContextSupplementalGroups :: Maybe [Integer] instance Arbitrary V1PodSpec where arbitrary = V1PodSpec <$> arbitrary -- v1PodSpecActiveDeadlineSeconds :: Maybe Integer <*> arbitrary -- v1PodSpecAffinity :: Maybe V1Affinity <*> arbitrary -- v1PodSpecAutomountServiceAccountToken :: Maybe Bool <*> arbitrary -- v1PodSpecContainers :: [V1Container] <*> arbitrary -- v1PodSpecDnsConfig :: Maybe V1PodDNSConfig <*> arbitrary -- v1PodSpecDnsPolicy :: Maybe Text <*> arbitrary -- v1PodSpecHostAliases :: Maybe [V1HostAlias] <*> arbitrary -- v1PodSpecHostIpc :: Maybe Bool <*> arbitrary -- v1PodSpecHostNetwork :: Maybe Bool <*> arbitrary -- v1PodSpecHostPid :: Maybe Bool <*> arbitrary -- v1PodSpecHostname :: Maybe Text <*> arbitrary -- v1PodSpecImagePullSecrets :: Maybe [V1LocalObjectReference] <*> arbitrary -- v1PodSpecInitContainers :: Maybe [V1Container] <*> arbitrary -- v1PodSpecNodeName :: Maybe Text <*> arbitrary -- v1PodSpecNodeSelector :: Maybe (Map.Map String Text) <*> arbitrary -- v1PodSpecPriority :: Maybe Int <*> arbitrary -- v1PodSpecPriorityClassName :: Maybe Text <*> arbitrary -- v1PodSpecRestartPolicy :: Maybe Text <*> arbitrary -- v1PodSpecSchedulerName :: Maybe Text <*> arbitrary -- v1PodSpecSecurityContext :: Maybe V1PodSecurityContext <*> arbitrary -- v1PodSpecServiceAccount :: Maybe Text <*> arbitrary -- v1PodSpecServiceAccountName :: Maybe Text <*> arbitrary -- v1PodSpecSubdomain :: Maybe Text <*> arbitrary -- v1PodSpecTerminationGracePeriodSeconds :: Maybe Integer <*> arbitrary -- v1PodSpecTolerations :: Maybe [V1Toleration] <*> arbitrary -- v1PodSpecVolumes :: Maybe [V1Volume] instance Arbitrary V1PodStatus where arbitrary = V1PodStatus <$> arbitrary -- v1PodStatusConditions :: Maybe [V1PodCondition] <*> arbitrary -- v1PodStatusContainerStatuses :: Maybe [V1ContainerStatus] <*> arbitrary -- v1PodStatusHostIp :: Maybe Text <*> arbitrary -- v1PodStatusInitContainerStatuses :: Maybe [V1ContainerStatus] <*> arbitrary -- v1PodStatusMessage :: Maybe Text <*> arbitrary -- v1PodStatusPhase :: Maybe Text <*> arbitrary -- v1PodStatusPodIp :: Maybe Text <*> arbitrary -- v1PodStatusQosClass :: Maybe Text <*> arbitrary -- v1PodStatusReason :: Maybe Text <*> arbitrary -- v1PodStatusStartTime :: Maybe DateTime instance Arbitrary V1PodTemplate where arbitrary = V1PodTemplate <$> arbitrary -- v1PodTemplateApiVersion :: Maybe Text <*> arbitrary -- v1PodTemplateKind :: Maybe Text <*> arbitrary -- v1PodTemplateMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1PodTemplateTemplate :: Maybe V1PodTemplateSpec instance Arbitrary V1PodTemplateList where arbitrary = V1PodTemplateList <$> arbitrary -- v1PodTemplateListApiVersion :: Maybe Text <*> arbitrary -- v1PodTemplateListItems :: [V1PodTemplate] <*> arbitrary -- v1PodTemplateListKind :: Maybe Text <*> arbitrary -- v1PodTemplateListMetadata :: Maybe V1ListMeta instance Arbitrary V1PodTemplateSpec where arbitrary = V1PodTemplateSpec <$> arbitrary -- v1PodTemplateSpecMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1PodTemplateSpecSpec :: Maybe V1PodSpec instance Arbitrary V1PolicyRule where arbitrary = V1PolicyRule <$> arbitrary -- v1PolicyRuleApiGroups :: Maybe [Text] <*> arbitrary -- v1PolicyRuleNonResourceUrLs :: Maybe [Text] <*> arbitrary -- v1PolicyRuleResourceNames :: Maybe [Text] <*> arbitrary -- v1PolicyRuleResources :: Maybe [Text] <*> arbitrary -- v1PolicyRuleVerbs :: [Text] instance Arbitrary V1PortworxVolumeSource where arbitrary = V1PortworxVolumeSource <$> arbitrary -- v1PortworxVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1PortworxVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1PortworxVolumeSourceVolumeId :: Text instance Arbitrary V1Preconditions where arbitrary = V1Preconditions <$> arbitrary -- v1PreconditionsUid :: Maybe Text instance Arbitrary V1PreferredSchedulingTerm where arbitrary = V1PreferredSchedulingTerm <$> arbitrary -- v1PreferredSchedulingTermPreference :: V1NodeSelectorTerm <*> arbitrary -- v1PreferredSchedulingTermWeight :: Int instance Arbitrary V1Probe where arbitrary = V1Probe <$> arbitrary -- v1ProbeExec :: Maybe V1ExecAction <*> arbitrary -- v1ProbeFailureThreshold :: Maybe Int <*> arbitrary -- v1ProbeHttpGet :: Maybe V1HTTPGetAction <*> arbitrary -- v1ProbeInitialDelaySeconds :: Maybe Int <*> arbitrary -- v1ProbePeriodSeconds :: Maybe Int <*> arbitrary -- v1ProbeSuccessThreshold :: Maybe Int <*> arbitrary -- v1ProbeTcpSocket :: Maybe V1TCPSocketAction <*> arbitrary -- v1ProbeTimeoutSeconds :: Maybe Int instance Arbitrary V1ProjectedVolumeSource where arbitrary = V1ProjectedVolumeSource <$> arbitrary -- v1ProjectedVolumeSourceDefaultMode :: Maybe Int <*> arbitrary -- v1ProjectedVolumeSourceSources :: [V1VolumeProjection] instance Arbitrary V1QuobyteVolumeSource where arbitrary = V1QuobyteVolumeSource <$> arbitrary -- v1QuobyteVolumeSourceGroup :: Maybe Text <*> arbitrary -- v1QuobyteVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1QuobyteVolumeSourceRegistry :: Text <*> arbitrary -- v1QuobyteVolumeSourceUser :: Maybe Text <*> arbitrary -- v1QuobyteVolumeSourceVolume :: Text instance Arbitrary V1RBDPersistentVolumeSource where arbitrary = V1RBDPersistentVolumeSource <$> arbitrary -- v1RBDPersistentVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1RBDPersistentVolumeSourceImage :: Text <*> arbitrary -- v1RBDPersistentVolumeSourceKeyring :: Maybe Text <*> arbitrary -- v1RBDPersistentVolumeSourceMonitors :: [Text] <*> arbitrary -- v1RBDPersistentVolumeSourcePool :: Maybe Text <*> arbitrary -- v1RBDPersistentVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1RBDPersistentVolumeSourceSecretRef :: Maybe V1SecretReference <*> arbitrary -- v1RBDPersistentVolumeSourceUser :: Maybe Text instance Arbitrary V1RBDVolumeSource where arbitrary = V1RBDVolumeSource <$> arbitrary -- v1RBDVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1RBDVolumeSourceImage :: Text <*> arbitrary -- v1RBDVolumeSourceKeyring :: Maybe Text <*> arbitrary -- v1RBDVolumeSourceMonitors :: [Text] <*> arbitrary -- v1RBDVolumeSourcePool :: Maybe Text <*> arbitrary -- v1RBDVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1RBDVolumeSourceSecretRef :: Maybe V1LocalObjectReference <*> arbitrary -- v1RBDVolumeSourceUser :: Maybe Text instance Arbitrary V1ReplicaSet where arbitrary = V1ReplicaSet <$> arbitrary -- v1ReplicaSetApiVersion :: Maybe Text <*> arbitrary -- v1ReplicaSetKind :: Maybe Text <*> arbitrary -- v1ReplicaSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ReplicaSetSpec :: Maybe V1ReplicaSetSpec <*> arbitrary -- v1ReplicaSetStatus :: Maybe V1ReplicaSetStatus instance Arbitrary V1ReplicaSetCondition where arbitrary = V1ReplicaSetCondition <$> arbitrary -- v1ReplicaSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1ReplicaSetConditionMessage :: Maybe Text <*> arbitrary -- v1ReplicaSetConditionReason :: Maybe Text <*> arbitrary -- v1ReplicaSetConditionStatus :: Text <*> arbitrary -- v1ReplicaSetConditionType :: Text instance Arbitrary V1ReplicaSetList where arbitrary = V1ReplicaSetList <$> arbitrary -- v1ReplicaSetListApiVersion :: Maybe Text <*> arbitrary -- v1ReplicaSetListItems :: [V1ReplicaSet] <*> arbitrary -- v1ReplicaSetListKind :: Maybe Text <*> arbitrary -- v1ReplicaSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1ReplicaSetSpec where arbitrary = V1ReplicaSetSpec <$> arbitrary -- v1ReplicaSetSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1ReplicaSetSpecReplicas :: Maybe Int <*> arbitrary -- v1ReplicaSetSpecSelector :: V1LabelSelector <*> arbitrary -- v1ReplicaSetSpecTemplate :: Maybe V1PodTemplateSpec instance Arbitrary V1ReplicaSetStatus where arbitrary = V1ReplicaSetStatus <$> arbitrary -- v1ReplicaSetStatusAvailableReplicas :: Maybe Int <*> arbitrary -- v1ReplicaSetStatusConditions :: Maybe [V1ReplicaSetCondition] <*> arbitrary -- v1ReplicaSetStatusFullyLabeledReplicas :: Maybe Int <*> arbitrary -- v1ReplicaSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1ReplicaSetStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1ReplicaSetStatusReplicas :: Int instance Arbitrary V1ReplicationController where arbitrary = V1ReplicationController <$> arbitrary -- v1ReplicationControllerApiVersion :: Maybe Text <*> arbitrary -- v1ReplicationControllerKind :: Maybe Text <*> arbitrary -- v1ReplicationControllerMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ReplicationControllerSpec :: Maybe V1ReplicationControllerSpec <*> arbitrary -- v1ReplicationControllerStatus :: Maybe V1ReplicationControllerStatus instance Arbitrary V1ReplicationControllerCondition where arbitrary = V1ReplicationControllerCondition <$> arbitrary -- v1ReplicationControllerConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1ReplicationControllerConditionMessage :: Maybe Text <*> arbitrary -- v1ReplicationControllerConditionReason :: Maybe Text <*> arbitrary -- v1ReplicationControllerConditionStatus :: Text <*> arbitrary -- v1ReplicationControllerConditionType :: Text instance Arbitrary V1ReplicationControllerList where arbitrary = V1ReplicationControllerList <$> arbitrary -- v1ReplicationControllerListApiVersion :: Maybe Text <*> arbitrary -- v1ReplicationControllerListItems :: [V1ReplicationController] <*> arbitrary -- v1ReplicationControllerListKind :: Maybe Text <*> arbitrary -- v1ReplicationControllerListMetadata :: Maybe V1ListMeta instance Arbitrary V1ReplicationControllerSpec where arbitrary = V1ReplicationControllerSpec <$> arbitrary -- v1ReplicationControllerSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1ReplicationControllerSpecReplicas :: Maybe Int <*> arbitrary -- v1ReplicationControllerSpecSelector :: Maybe (Map.Map String Text) <*> arbitrary -- v1ReplicationControllerSpecTemplate :: Maybe V1PodTemplateSpec instance Arbitrary V1ReplicationControllerStatus where arbitrary = V1ReplicationControllerStatus <$> arbitrary -- v1ReplicationControllerStatusAvailableReplicas :: Maybe Int <*> arbitrary -- v1ReplicationControllerStatusConditions :: Maybe [V1ReplicationControllerCondition] <*> arbitrary -- v1ReplicationControllerStatusFullyLabeledReplicas :: Maybe Int <*> arbitrary -- v1ReplicationControllerStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1ReplicationControllerStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1ReplicationControllerStatusReplicas :: Int instance Arbitrary V1ResourceAttributes where arbitrary = V1ResourceAttributes <$> arbitrary -- v1ResourceAttributesGroup :: Maybe Text <*> arbitrary -- v1ResourceAttributesName :: Maybe Text <*> arbitrary -- v1ResourceAttributesNamespace :: Maybe Text <*> arbitrary -- v1ResourceAttributesResource :: Maybe Text <*> arbitrary -- v1ResourceAttributesSubresource :: Maybe Text <*> arbitrary -- v1ResourceAttributesVerb :: Maybe Text <*> arbitrary -- v1ResourceAttributesVersion :: Maybe Text instance Arbitrary V1ResourceFieldSelector where arbitrary = V1ResourceFieldSelector <$> arbitrary -- v1ResourceFieldSelectorContainerName :: Maybe Text <*> arbitrary -- v1ResourceFieldSelectorDivisor :: Maybe Text <*> arbitrary -- v1ResourceFieldSelectorResource :: Text instance Arbitrary V1ResourceQuota where arbitrary = V1ResourceQuota <$> arbitrary -- v1ResourceQuotaApiVersion :: Maybe Text <*> arbitrary -- v1ResourceQuotaKind :: Maybe Text <*> arbitrary -- v1ResourceQuotaMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ResourceQuotaSpec :: Maybe V1ResourceQuotaSpec <*> arbitrary -- v1ResourceQuotaStatus :: Maybe V1ResourceQuotaStatus instance Arbitrary V1ResourceQuotaList where arbitrary = V1ResourceQuotaList <$> arbitrary -- v1ResourceQuotaListApiVersion :: Maybe Text <*> arbitrary -- v1ResourceQuotaListItems :: [V1ResourceQuota] <*> arbitrary -- v1ResourceQuotaListKind :: Maybe Text <*> arbitrary -- v1ResourceQuotaListMetadata :: Maybe V1ListMeta instance Arbitrary V1ResourceQuotaSpec where arbitrary = V1ResourceQuotaSpec <$> arbitrary -- v1ResourceQuotaSpecHard :: Maybe (Map.Map String Text) <*> arbitrary -- v1ResourceQuotaSpecScopes :: Maybe [Text] instance Arbitrary V1ResourceQuotaStatus where arbitrary = V1ResourceQuotaStatus <$> arbitrary -- v1ResourceQuotaStatusHard :: Maybe (Map.Map String Text) <*> arbitrary -- v1ResourceQuotaStatusUsed :: Maybe (Map.Map String Text) instance Arbitrary V1ResourceRequirements where arbitrary = V1ResourceRequirements <$> arbitrary -- v1ResourceRequirementsLimits :: Maybe (Map.Map String Text) <*> arbitrary -- v1ResourceRequirementsRequests :: Maybe (Map.Map String Text) instance Arbitrary V1ResourceRule where arbitrary = V1ResourceRule <$> arbitrary -- v1ResourceRuleApiGroups :: Maybe [Text] <*> arbitrary -- v1ResourceRuleResourceNames :: Maybe [Text] <*> arbitrary -- v1ResourceRuleResources :: Maybe [Text] <*> arbitrary -- v1ResourceRuleVerbs :: [Text] instance Arbitrary V1Role where arbitrary = V1Role <$> arbitrary -- v1RoleApiVersion :: Maybe Text <*> arbitrary -- v1RoleKind :: Maybe Text <*> arbitrary -- v1RoleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1RoleRules :: [V1PolicyRule] instance Arbitrary V1RoleBinding where arbitrary = V1RoleBinding <$> arbitrary -- v1RoleBindingApiVersion :: Maybe Text <*> arbitrary -- v1RoleBindingKind :: Maybe Text <*> arbitrary -- v1RoleBindingMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1RoleBindingRoleRef :: V1RoleRef <*> arbitrary -- v1RoleBindingSubjects :: [V1Subject] instance Arbitrary V1RoleBindingList where arbitrary = V1RoleBindingList <$> arbitrary -- v1RoleBindingListApiVersion :: Maybe Text <*> arbitrary -- v1RoleBindingListItems :: [V1RoleBinding] <*> arbitrary -- v1RoleBindingListKind :: Maybe Text <*> arbitrary -- v1RoleBindingListMetadata :: Maybe V1ListMeta instance Arbitrary V1RoleList where arbitrary = V1RoleList <$> arbitrary -- v1RoleListApiVersion :: Maybe Text <*> arbitrary -- v1RoleListItems :: [V1Role] <*> arbitrary -- v1RoleListKind :: Maybe Text <*> arbitrary -- v1RoleListMetadata :: Maybe V1ListMeta instance Arbitrary V1RoleRef where arbitrary = V1RoleRef <$> arbitrary -- v1RoleRefApiGroup :: Text <*> arbitrary -- v1RoleRefKind :: Text <*> arbitrary -- v1RoleRefName :: Text instance Arbitrary V1RollingUpdateDaemonSet where arbitrary = V1RollingUpdateDaemonSet <$> arbitrary -- v1RollingUpdateDaemonSetMaxUnavailable :: Maybe A.Value instance Arbitrary V1RollingUpdateDeployment where arbitrary = V1RollingUpdateDeployment <$> arbitrary -- v1RollingUpdateDeploymentMaxSurge :: Maybe A.Value <*> arbitrary -- v1RollingUpdateDeploymentMaxUnavailable :: Maybe A.Value instance Arbitrary V1RollingUpdateStatefulSetStrategy where arbitrary = V1RollingUpdateStatefulSetStrategy <$> arbitrary -- v1RollingUpdateStatefulSetStrategyPartition :: Maybe Int instance Arbitrary V1SELinuxOptions where arbitrary = V1SELinuxOptions <$> arbitrary -- v1SELinuxOptionsLevel :: Maybe Text <*> arbitrary -- v1SELinuxOptionsRole :: Maybe Text <*> arbitrary -- v1SELinuxOptionsType :: Maybe Text <*> arbitrary -- v1SELinuxOptionsUser :: Maybe Text instance Arbitrary V1Scale where arbitrary = V1Scale <$> arbitrary -- v1ScaleApiVersion :: Maybe Text <*> arbitrary -- v1ScaleKind :: Maybe Text <*> arbitrary -- v1ScaleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ScaleSpec :: Maybe V1ScaleSpec <*> arbitrary -- v1ScaleStatus :: Maybe V1ScaleStatus instance Arbitrary V1ScaleIOPersistentVolumeSource where arbitrary = V1ScaleIOPersistentVolumeSource <$> arbitrary -- v1ScaleIOPersistentVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1ScaleIOPersistentVolumeSourceGateway :: Text <*> arbitrary -- v1ScaleIOPersistentVolumeSourceProtectionDomain :: Maybe Text <*> arbitrary -- v1ScaleIOPersistentVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1ScaleIOPersistentVolumeSourceSecretRef :: V1SecretReference <*> arbitrary -- v1ScaleIOPersistentVolumeSourceSslEnabled :: Maybe Bool <*> arbitrary -- v1ScaleIOPersistentVolumeSourceStorageMode :: Maybe Text <*> arbitrary -- v1ScaleIOPersistentVolumeSourceStoragePool :: Maybe Text <*> arbitrary -- v1ScaleIOPersistentVolumeSourceSystem :: Text <*> arbitrary -- v1ScaleIOPersistentVolumeSourceVolumeName :: Maybe Text instance Arbitrary V1ScaleIOVolumeSource where arbitrary = V1ScaleIOVolumeSource <$> arbitrary -- v1ScaleIOVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1ScaleIOVolumeSourceGateway :: Text <*> arbitrary -- v1ScaleIOVolumeSourceProtectionDomain :: Maybe Text <*> arbitrary -- v1ScaleIOVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1ScaleIOVolumeSourceSecretRef :: V1LocalObjectReference <*> arbitrary -- v1ScaleIOVolumeSourceSslEnabled :: Maybe Bool <*> arbitrary -- v1ScaleIOVolumeSourceStorageMode :: Maybe Text <*> arbitrary -- v1ScaleIOVolumeSourceStoragePool :: Maybe Text <*> arbitrary -- v1ScaleIOVolumeSourceSystem :: Text <*> arbitrary -- v1ScaleIOVolumeSourceVolumeName :: Maybe Text instance Arbitrary V1ScaleSpec where arbitrary = V1ScaleSpec <$> arbitrary -- v1ScaleSpecReplicas :: Maybe Int instance Arbitrary V1ScaleStatus where arbitrary = V1ScaleStatus <$> arbitrary -- v1ScaleStatusReplicas :: Int <*> arbitrary -- v1ScaleStatusSelector :: Maybe Text instance Arbitrary V1Secret where arbitrary = V1Secret <$> arbitrary -- v1SecretApiVersion :: Maybe Text <*> arbitrary -- v1SecretData :: Maybe (Map.Map String ByteArray) <*> arbitrary -- v1SecretKind :: Maybe Text <*> arbitrary -- v1SecretMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1SecretStringData :: Maybe (Map.Map String Text) <*> arbitrary -- v1SecretType :: Maybe Text instance Arbitrary V1SecretEnvSource where arbitrary = V1SecretEnvSource <$> arbitrary -- v1SecretEnvSourceName :: Maybe Text <*> arbitrary -- v1SecretEnvSourceOptional :: Maybe Bool instance Arbitrary V1SecretKeySelector where arbitrary = V1SecretKeySelector <$> arbitrary -- v1SecretKeySelectorKey :: Text <*> arbitrary -- v1SecretKeySelectorName :: Maybe Text <*> arbitrary -- v1SecretKeySelectorOptional :: Maybe Bool instance Arbitrary V1SecretList where arbitrary = V1SecretList <$> arbitrary -- v1SecretListApiVersion :: Maybe Text <*> arbitrary -- v1SecretListItems :: [V1Secret] <*> arbitrary -- v1SecretListKind :: Maybe Text <*> arbitrary -- v1SecretListMetadata :: Maybe V1ListMeta instance Arbitrary V1SecretProjection where arbitrary = V1SecretProjection <$> arbitrary -- v1SecretProjectionItems :: Maybe [V1KeyToPath] <*> arbitrary -- v1SecretProjectionName :: Maybe Text <*> arbitrary -- v1SecretProjectionOptional :: Maybe Bool instance Arbitrary V1SecretReference where arbitrary = V1SecretReference <$> arbitrary -- v1SecretReferenceName :: Maybe Text <*> arbitrary -- v1SecretReferenceNamespace :: Maybe Text instance Arbitrary V1SecretVolumeSource where arbitrary = V1SecretVolumeSource <$> arbitrary -- v1SecretVolumeSourceDefaultMode :: Maybe Int <*> arbitrary -- v1SecretVolumeSourceItems :: Maybe [V1KeyToPath] <*> arbitrary -- v1SecretVolumeSourceOptional :: Maybe Bool <*> arbitrary -- v1SecretVolumeSourceSecretName :: Maybe Text instance Arbitrary V1SecurityContext where arbitrary = V1SecurityContext <$> arbitrary -- v1SecurityContextAllowPrivilegeEscalation :: Maybe Bool <*> arbitrary -- v1SecurityContextCapabilities :: Maybe V1Capabilities <*> arbitrary -- v1SecurityContextPrivileged :: Maybe Bool <*> arbitrary -- v1SecurityContextReadOnlyRootFilesystem :: Maybe Bool <*> arbitrary -- v1SecurityContextRunAsNonRoot :: Maybe Bool <*> arbitrary -- v1SecurityContextRunAsUser :: Maybe Integer <*> arbitrary -- v1SecurityContextSeLinuxOptions :: Maybe V1SELinuxOptions instance Arbitrary V1SelfSubjectAccessReview where arbitrary = V1SelfSubjectAccessReview <$> arbitrary -- v1SelfSubjectAccessReviewApiVersion :: Maybe Text <*> arbitrary -- v1SelfSubjectAccessReviewKind :: Maybe Text <*> arbitrary -- v1SelfSubjectAccessReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1SelfSubjectAccessReviewSpec :: V1SelfSubjectAccessReviewSpec <*> arbitrary -- v1SelfSubjectAccessReviewStatus :: Maybe V1SubjectAccessReviewStatus instance Arbitrary V1SelfSubjectAccessReviewSpec where arbitrary = V1SelfSubjectAccessReviewSpec <$> arbitrary -- v1SelfSubjectAccessReviewSpecNonResourceAttributes :: Maybe V1NonResourceAttributes <*> arbitrary -- v1SelfSubjectAccessReviewSpecResourceAttributes :: Maybe V1ResourceAttributes instance Arbitrary V1SelfSubjectRulesReview where arbitrary = V1SelfSubjectRulesReview <$> arbitrary -- v1SelfSubjectRulesReviewApiVersion :: Maybe Text <*> arbitrary -- v1SelfSubjectRulesReviewKind :: Maybe Text <*> arbitrary -- v1SelfSubjectRulesReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1SelfSubjectRulesReviewSpec :: V1SelfSubjectRulesReviewSpec <*> arbitrary -- v1SelfSubjectRulesReviewStatus :: Maybe V1SubjectRulesReviewStatus instance Arbitrary V1SelfSubjectRulesReviewSpec where arbitrary = V1SelfSubjectRulesReviewSpec <$> arbitrary -- v1SelfSubjectRulesReviewSpecNamespace :: Maybe Text instance Arbitrary V1ServerAddressByClientCIDR where arbitrary = V1ServerAddressByClientCIDR <$> arbitrary -- v1ServerAddressByClientCIDRClientCidr :: Text <*> arbitrary -- v1ServerAddressByClientCIDRServerAddress :: Text instance Arbitrary V1Service where arbitrary = V1Service <$> arbitrary -- v1ServiceApiVersion :: Maybe Text <*> arbitrary -- v1ServiceKind :: Maybe Text <*> arbitrary -- v1ServiceMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ServiceSpec :: Maybe V1ServiceSpec <*> arbitrary -- v1ServiceStatus :: Maybe V1ServiceStatus instance Arbitrary V1ServiceAccount where arbitrary = V1ServiceAccount <$> arbitrary -- v1ServiceAccountApiVersion :: Maybe Text <*> arbitrary -- v1ServiceAccountAutomountServiceAccountToken :: Maybe Bool <*> arbitrary -- v1ServiceAccountImagePullSecrets :: Maybe [V1LocalObjectReference] <*> arbitrary -- v1ServiceAccountKind :: Maybe Text <*> arbitrary -- v1ServiceAccountMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1ServiceAccountSecrets :: Maybe [V1ObjectReference] instance Arbitrary V1ServiceAccountList where arbitrary = V1ServiceAccountList <$> arbitrary -- v1ServiceAccountListApiVersion :: Maybe Text <*> arbitrary -- v1ServiceAccountListItems :: [V1ServiceAccount] <*> arbitrary -- v1ServiceAccountListKind :: Maybe Text <*> arbitrary -- v1ServiceAccountListMetadata :: Maybe V1ListMeta instance Arbitrary V1ServiceList where arbitrary = V1ServiceList <$> arbitrary -- v1ServiceListApiVersion :: Maybe Text <*> arbitrary -- v1ServiceListItems :: [V1Service] <*> arbitrary -- v1ServiceListKind :: Maybe Text <*> arbitrary -- v1ServiceListMetadata :: Maybe V1ListMeta instance Arbitrary V1ServicePort where arbitrary = V1ServicePort <$> arbitrary -- v1ServicePortName :: Maybe Text <*> arbitrary -- v1ServicePortNodePort :: Maybe Int <*> arbitrary -- v1ServicePortPort :: Int <*> arbitrary -- v1ServicePortProtocol :: Maybe Text <*> arbitrary -- v1ServicePortTargetPort :: Maybe A.Value instance Arbitrary V1ServiceSpec where arbitrary = V1ServiceSpec <$> arbitrary -- v1ServiceSpecClusterIp :: Maybe Text <*> arbitrary -- v1ServiceSpecExternalIPs :: Maybe [Text] <*> arbitrary -- v1ServiceSpecExternalName :: Maybe Text <*> arbitrary -- v1ServiceSpecExternalTrafficPolicy :: Maybe Text <*> arbitrary -- v1ServiceSpecHealthCheckNodePort :: Maybe Int <*> arbitrary -- v1ServiceSpecLoadBalancerIp :: Maybe Text <*> arbitrary -- v1ServiceSpecLoadBalancerSourceRanges :: Maybe [Text] <*> arbitrary -- v1ServiceSpecPorts :: Maybe [V1ServicePort] <*> arbitrary -- v1ServiceSpecPublishNotReadyAddresses :: Maybe Bool <*> arbitrary -- v1ServiceSpecSelector :: Maybe (Map.Map String Text) <*> arbitrary -- v1ServiceSpecSessionAffinity :: Maybe Text <*> arbitrary -- v1ServiceSpecSessionAffinityConfig :: Maybe V1SessionAffinityConfig <*> arbitrary -- v1ServiceSpecType :: Maybe Text instance Arbitrary V1ServiceStatus where arbitrary = V1ServiceStatus <$> arbitrary -- v1ServiceStatusLoadBalancer :: Maybe V1LoadBalancerStatus instance Arbitrary V1SessionAffinityConfig where arbitrary = V1SessionAffinityConfig <$> arbitrary -- v1SessionAffinityConfigClientIp :: Maybe V1ClientIPConfig instance Arbitrary V1StatefulSet where arbitrary = V1StatefulSet <$> arbitrary -- v1StatefulSetApiVersion :: Maybe Text <*> arbitrary -- v1StatefulSetKind :: Maybe Text <*> arbitrary -- v1StatefulSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1StatefulSetSpec :: Maybe V1StatefulSetSpec <*> arbitrary -- v1StatefulSetStatus :: Maybe V1StatefulSetStatus instance Arbitrary V1StatefulSetCondition where arbitrary = V1StatefulSetCondition <$> arbitrary -- v1StatefulSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1StatefulSetConditionMessage :: Maybe Text <*> arbitrary -- v1StatefulSetConditionReason :: Maybe Text <*> arbitrary -- v1StatefulSetConditionStatus :: Text <*> arbitrary -- v1StatefulSetConditionType :: Text instance Arbitrary V1StatefulSetList where arbitrary = V1StatefulSetList <$> arbitrary -- v1StatefulSetListApiVersion :: Maybe Text <*> arbitrary -- v1StatefulSetListItems :: [V1StatefulSet] <*> arbitrary -- v1StatefulSetListKind :: Maybe Text <*> arbitrary -- v1StatefulSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1StatefulSetSpec where arbitrary = V1StatefulSetSpec <$> arbitrary -- v1StatefulSetSpecPodManagementPolicy :: Maybe Text <*> arbitrary -- v1StatefulSetSpecReplicas :: Maybe Int <*> arbitrary -- v1StatefulSetSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- v1StatefulSetSpecSelector :: V1LabelSelector <*> arbitrary -- v1StatefulSetSpecServiceName :: Text <*> arbitrary -- v1StatefulSetSpecTemplate :: V1PodTemplateSpec <*> arbitrary -- v1StatefulSetSpecUpdateStrategy :: Maybe V1StatefulSetUpdateStrategy <*> arbitrary -- v1StatefulSetSpecVolumeClaimTemplates :: Maybe [V1PersistentVolumeClaim] instance Arbitrary V1StatefulSetStatus where arbitrary = V1StatefulSetStatus <$> arbitrary -- v1StatefulSetStatusCollisionCount :: Maybe Int <*> arbitrary -- v1StatefulSetStatusConditions :: Maybe [V1StatefulSetCondition] <*> arbitrary -- v1StatefulSetStatusCurrentReplicas :: Maybe Int <*> arbitrary -- v1StatefulSetStatusCurrentRevision :: Maybe Text <*> arbitrary -- v1StatefulSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1StatefulSetStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1StatefulSetStatusReplicas :: Int <*> arbitrary -- v1StatefulSetStatusUpdateRevision :: Maybe Text <*> arbitrary -- v1StatefulSetStatusUpdatedReplicas :: Maybe Int instance Arbitrary V1StatefulSetUpdateStrategy where arbitrary = V1StatefulSetUpdateStrategy <$> arbitrary -- v1StatefulSetUpdateStrategyRollingUpdate :: Maybe V1RollingUpdateStatefulSetStrategy <*> arbitrary -- v1StatefulSetUpdateStrategyType :: Maybe Text instance Arbitrary V1Status where arbitrary = V1Status <$> arbitrary -- v1StatusApiVersion :: Maybe Text <*> arbitrary -- v1StatusCode :: Maybe Int <*> arbitrary -- v1StatusDetails :: Maybe V1StatusDetails <*> arbitrary -- v1StatusKind :: Maybe Text <*> arbitrary -- v1StatusMessage :: Maybe Text <*> arbitrary -- v1StatusMetadata :: Maybe V1ListMeta <*> arbitrary -- v1StatusReason :: Maybe Text <*> arbitrary -- v1StatusStatus :: Maybe Text instance Arbitrary V1StatusCause where arbitrary = V1StatusCause <$> arbitrary -- v1StatusCauseField :: Maybe Text <*> arbitrary -- v1StatusCauseMessage :: Maybe Text <*> arbitrary -- v1StatusCauseReason :: Maybe Text instance Arbitrary V1StatusDetails where arbitrary = V1StatusDetails <$> arbitrary -- v1StatusDetailsCauses :: Maybe [V1StatusCause] <*> arbitrary -- v1StatusDetailsGroup :: Maybe Text <*> arbitrary -- v1StatusDetailsKind :: Maybe Text <*> arbitrary -- v1StatusDetailsName :: Maybe Text <*> arbitrary -- v1StatusDetailsRetryAfterSeconds :: Maybe Int <*> arbitrary -- v1StatusDetailsUid :: Maybe Text instance Arbitrary V1StorageClass where arbitrary = V1StorageClass <$> arbitrary -- v1StorageClassAllowVolumeExpansion :: Maybe Bool <*> arbitrary -- v1StorageClassApiVersion :: Maybe Text <*> arbitrary -- v1StorageClassKind :: Maybe Text <*> arbitrary -- v1StorageClassMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1StorageClassMountOptions :: Maybe [Text] <*> arbitrary -- v1StorageClassParameters :: Maybe (Map.Map String Text) <*> arbitrary -- v1StorageClassProvisioner :: Text <*> arbitrary -- v1StorageClassReclaimPolicy :: Maybe Text <*> arbitrary -- v1StorageClassVolumeBindingMode :: Maybe Text instance Arbitrary V1StorageClassList where arbitrary = V1StorageClassList <$> arbitrary -- v1StorageClassListApiVersion :: Maybe Text <*> arbitrary -- v1StorageClassListItems :: [V1StorageClass] <*> arbitrary -- v1StorageClassListKind :: Maybe Text <*> arbitrary -- v1StorageClassListMetadata :: Maybe V1ListMeta instance Arbitrary V1StorageOSPersistentVolumeSource where arbitrary = V1StorageOSPersistentVolumeSource <$> arbitrary -- v1StorageOSPersistentVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1StorageOSPersistentVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1StorageOSPersistentVolumeSourceSecretRef :: Maybe V1ObjectReference <*> arbitrary -- v1StorageOSPersistentVolumeSourceVolumeName :: Maybe Text <*> arbitrary -- v1StorageOSPersistentVolumeSourceVolumeNamespace :: Maybe Text instance Arbitrary V1StorageOSVolumeSource where arbitrary = V1StorageOSVolumeSource <$> arbitrary -- v1StorageOSVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1StorageOSVolumeSourceReadOnly :: Maybe Bool <*> arbitrary -- v1StorageOSVolumeSourceSecretRef :: Maybe V1LocalObjectReference <*> arbitrary -- v1StorageOSVolumeSourceVolumeName :: Maybe Text <*> arbitrary -- v1StorageOSVolumeSourceVolumeNamespace :: Maybe Text instance Arbitrary V1Subject where arbitrary = V1Subject <$> arbitrary -- v1SubjectApiGroup :: Maybe Text <*> arbitrary -- v1SubjectKind :: Text <*> arbitrary -- v1SubjectName :: Text <*> arbitrary -- v1SubjectNamespace :: Maybe Text instance Arbitrary V1SubjectAccessReview where arbitrary = V1SubjectAccessReview <$> arbitrary -- v1SubjectAccessReviewApiVersion :: Maybe Text <*> arbitrary -- v1SubjectAccessReviewKind :: Maybe Text <*> arbitrary -- v1SubjectAccessReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1SubjectAccessReviewSpec :: V1SubjectAccessReviewSpec <*> arbitrary -- v1SubjectAccessReviewStatus :: Maybe V1SubjectAccessReviewStatus instance Arbitrary V1SubjectAccessReviewSpec where arbitrary = V1SubjectAccessReviewSpec <$> arbitrary -- v1SubjectAccessReviewSpecExtra :: Maybe (Map.Map String [Text]) <*> arbitrary -- v1SubjectAccessReviewSpecGroups :: Maybe [Text] <*> arbitrary -- v1SubjectAccessReviewSpecNonResourceAttributes :: Maybe V1NonResourceAttributes <*> arbitrary -- v1SubjectAccessReviewSpecResourceAttributes :: Maybe V1ResourceAttributes <*> arbitrary -- v1SubjectAccessReviewSpecUid :: Maybe Text <*> arbitrary -- v1SubjectAccessReviewSpecUser :: Maybe Text instance Arbitrary V1SubjectAccessReviewStatus where arbitrary = V1SubjectAccessReviewStatus <$> arbitrary -- v1SubjectAccessReviewStatusAllowed :: Bool <*> arbitrary -- v1SubjectAccessReviewStatusDenied :: Maybe Bool <*> arbitrary -- v1SubjectAccessReviewStatusEvaluationError :: Maybe Text <*> arbitrary -- v1SubjectAccessReviewStatusReason :: Maybe Text instance Arbitrary V1SubjectRulesReviewStatus where arbitrary = V1SubjectRulesReviewStatus <$> arbitrary -- v1SubjectRulesReviewStatusEvaluationError :: Maybe Text <*> arbitrary -- v1SubjectRulesReviewStatusIncomplete :: Bool <*> arbitrary -- v1SubjectRulesReviewStatusNonResourceRules :: [V1NonResourceRule] <*> arbitrary -- v1SubjectRulesReviewStatusResourceRules :: [V1ResourceRule] instance Arbitrary V1TCPSocketAction where arbitrary = V1TCPSocketAction <$> arbitrary -- v1TCPSocketActionHost :: Maybe Text <*> arbitrary -- v1TCPSocketActionPort :: A.Value instance Arbitrary V1Taint where arbitrary = V1Taint <$> arbitrary -- v1TaintEffect :: Text <*> arbitrary -- v1TaintKey :: Text <*> arbitrary -- v1TaintTimeAdded :: Maybe DateTime <*> arbitrary -- v1TaintValue :: Maybe Text instance Arbitrary V1TokenReview where arbitrary = V1TokenReview <$> arbitrary -- v1TokenReviewApiVersion :: Maybe Text <*> arbitrary -- v1TokenReviewKind :: Maybe Text <*> arbitrary -- v1TokenReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1TokenReviewSpec :: V1TokenReviewSpec <*> arbitrary -- v1TokenReviewStatus :: Maybe V1TokenReviewStatus instance Arbitrary V1TokenReviewSpec where arbitrary = V1TokenReviewSpec <$> arbitrary -- v1TokenReviewSpecToken :: Maybe Text instance Arbitrary V1TokenReviewStatus where arbitrary = V1TokenReviewStatus <$> arbitrary -- v1TokenReviewStatusAuthenticated :: Maybe Bool <*> arbitrary -- v1TokenReviewStatusError :: Maybe Text <*> arbitrary -- v1TokenReviewStatusUser :: Maybe V1UserInfo instance Arbitrary V1Toleration where arbitrary = V1Toleration <$> arbitrary -- v1TolerationEffect :: Maybe Text <*> arbitrary -- v1TolerationKey :: Maybe Text <*> arbitrary -- v1TolerationOperator :: Maybe Text <*> arbitrary -- v1TolerationTolerationSeconds :: Maybe Integer <*> arbitrary -- v1TolerationValue :: Maybe Text instance Arbitrary V1UserInfo where arbitrary = V1UserInfo <$> arbitrary -- v1UserInfoExtra :: Maybe (Map.Map String [Text]) <*> arbitrary -- v1UserInfoGroups :: Maybe [Text] <*> arbitrary -- v1UserInfoUid :: Maybe Text <*> arbitrary -- v1UserInfoUsername :: Maybe Text instance Arbitrary V1Volume where arbitrary = V1Volume <$> arbitrary -- v1VolumeAwsElasticBlockStore :: Maybe V1AWSElasticBlockStoreVolumeSource <*> arbitrary -- v1VolumeAzureDisk :: Maybe V1AzureDiskVolumeSource <*> arbitrary -- v1VolumeAzureFile :: Maybe V1AzureFileVolumeSource <*> arbitrary -- v1VolumeCephfs :: Maybe V1CephFSVolumeSource <*> arbitrary -- v1VolumeCinder :: Maybe V1CinderVolumeSource <*> arbitrary -- v1VolumeConfigMap :: Maybe V1ConfigMapVolumeSource <*> arbitrary -- v1VolumeDownwardApi :: Maybe V1DownwardAPIVolumeSource <*> arbitrary -- v1VolumeEmptyDir :: Maybe V1EmptyDirVolumeSource <*> arbitrary -- v1VolumeFc :: Maybe V1FCVolumeSource <*> arbitrary -- v1VolumeFlexVolume :: Maybe V1FlexVolumeSource <*> arbitrary -- v1VolumeFlocker :: Maybe V1FlockerVolumeSource <*> arbitrary -- v1VolumeGcePersistentDisk :: Maybe V1GCEPersistentDiskVolumeSource <*> arbitrary -- v1VolumeGitRepo :: Maybe V1GitRepoVolumeSource <*> arbitrary -- v1VolumeGlusterfs :: Maybe V1GlusterfsVolumeSource <*> arbitrary -- v1VolumeHostPath :: Maybe V1HostPathVolumeSource <*> arbitrary -- v1VolumeIscsi :: Maybe V1ISCSIVolumeSource <*> arbitrary -- v1VolumeName :: Text <*> arbitrary -- v1VolumeNfs :: Maybe V1NFSVolumeSource <*> arbitrary -- v1VolumePersistentVolumeClaim :: Maybe V1PersistentVolumeClaimVolumeSource <*> arbitrary -- v1VolumePhotonPersistentDisk :: Maybe V1PhotonPersistentDiskVolumeSource <*> arbitrary -- v1VolumePortworxVolume :: Maybe V1PortworxVolumeSource <*> arbitrary -- v1VolumeProjected :: Maybe V1ProjectedVolumeSource <*> arbitrary -- v1VolumeQuobyte :: Maybe V1QuobyteVolumeSource <*> arbitrary -- v1VolumeRbd :: Maybe V1RBDVolumeSource <*> arbitrary -- v1VolumeScaleIo :: Maybe V1ScaleIOVolumeSource <*> arbitrary -- v1VolumeSecret :: Maybe V1SecretVolumeSource <*> arbitrary -- v1VolumeStorageos :: Maybe V1StorageOSVolumeSource <*> arbitrary -- v1VolumeVsphereVolume :: Maybe V1VsphereVirtualDiskVolumeSource instance Arbitrary V1VolumeDevice where arbitrary = V1VolumeDevice <$> arbitrary -- v1VolumeDeviceDevicePath :: Text <*> arbitrary -- v1VolumeDeviceName :: Text instance Arbitrary V1VolumeMount where arbitrary = V1VolumeMount <$> arbitrary -- v1VolumeMountMountPath :: Text <*> arbitrary -- v1VolumeMountMountPropagation :: Maybe Text <*> arbitrary -- v1VolumeMountName :: Text <*> arbitrary -- v1VolumeMountReadOnly :: Maybe Bool <*> arbitrary -- v1VolumeMountSubPath :: Maybe Text instance Arbitrary V1VolumeProjection where arbitrary = V1VolumeProjection <$> arbitrary -- v1VolumeProjectionConfigMap :: Maybe V1ConfigMapProjection <*> arbitrary -- v1VolumeProjectionDownwardApi :: Maybe V1DownwardAPIProjection <*> arbitrary -- v1VolumeProjectionSecret :: Maybe V1SecretProjection instance Arbitrary V1VsphereVirtualDiskVolumeSource where arbitrary = V1VsphereVirtualDiskVolumeSource <$> arbitrary -- v1VsphereVirtualDiskVolumeSourceFsType :: Maybe Text <*> arbitrary -- v1VsphereVirtualDiskVolumeSourceStoragePolicyId :: Maybe Text <*> arbitrary -- v1VsphereVirtualDiskVolumeSourceStoragePolicyName :: Maybe Text <*> arbitrary -- v1VsphereVirtualDiskVolumeSourceVolumePath :: Text instance Arbitrary V1WatchEvent where arbitrary = V1WatchEvent <$> arbitrary -- v1WatchEventObject :: RuntimeRawExtension <*> arbitrary -- v1WatchEventType :: Text instance Arbitrary V1WeightedPodAffinityTerm where arbitrary = V1WeightedPodAffinityTerm <$> arbitrary -- v1WeightedPodAffinityTermPodAffinityTerm :: V1PodAffinityTerm <*> arbitrary -- v1WeightedPodAffinityTermWeight :: Int instance Arbitrary V1alpha1AggregationRule where arbitrary = V1alpha1AggregationRule <$> arbitrary -- v1alpha1AggregationRuleClusterRoleSelectors :: Maybe [V1LabelSelector] instance Arbitrary V1alpha1ClusterRole where arbitrary = V1alpha1ClusterRole <$> arbitrary -- v1alpha1ClusterRoleAggregationRule :: Maybe V1alpha1AggregationRule <*> arbitrary -- v1alpha1ClusterRoleApiVersion :: Maybe Text <*> arbitrary -- v1alpha1ClusterRoleKind :: Maybe Text <*> arbitrary -- v1alpha1ClusterRoleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1alpha1ClusterRoleRules :: [V1alpha1PolicyRule] instance Arbitrary V1alpha1ClusterRoleBinding where arbitrary = V1alpha1ClusterRoleBinding <$> arbitrary -- v1alpha1ClusterRoleBindingApiVersion :: Maybe Text <*> arbitrary -- v1alpha1ClusterRoleBindingKind :: Maybe Text <*> arbitrary -- v1alpha1ClusterRoleBindingMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1alpha1ClusterRoleBindingRoleRef :: V1alpha1RoleRef <*> arbitrary -- v1alpha1ClusterRoleBindingSubjects :: [V1alpha1Subject] instance Arbitrary V1alpha1ClusterRoleBindingList where arbitrary = V1alpha1ClusterRoleBindingList <$> arbitrary -- v1alpha1ClusterRoleBindingListApiVersion :: Maybe Text <*> arbitrary -- v1alpha1ClusterRoleBindingListItems :: [V1alpha1ClusterRoleBinding] <*> arbitrary -- v1alpha1ClusterRoleBindingListKind :: Maybe Text <*> arbitrary -- v1alpha1ClusterRoleBindingListMetadata :: Maybe V1ListMeta instance Arbitrary V1alpha1ClusterRoleList where arbitrary = V1alpha1ClusterRoleList <$> arbitrary -- v1alpha1ClusterRoleListApiVersion :: Maybe Text <*> arbitrary -- v1alpha1ClusterRoleListItems :: [V1alpha1ClusterRole] <*> arbitrary -- v1alpha1ClusterRoleListKind :: Maybe Text <*> arbitrary -- v1alpha1ClusterRoleListMetadata :: Maybe V1ListMeta instance Arbitrary V1alpha1Initializer where arbitrary = V1alpha1Initializer <$> arbitrary -- v1alpha1InitializerName :: Text <*> arbitrary -- v1alpha1InitializerRules :: Maybe [V1alpha1Rule] instance Arbitrary V1alpha1InitializerConfiguration where arbitrary = V1alpha1InitializerConfiguration <$> arbitrary -- v1alpha1InitializerConfigurationApiVersion :: Maybe Text <*> arbitrary -- v1alpha1InitializerConfigurationInitializers :: Maybe [V1alpha1Initializer] <*> arbitrary -- v1alpha1InitializerConfigurationKind :: Maybe Text <*> arbitrary -- v1alpha1InitializerConfigurationMetadata :: Maybe V1ObjectMeta instance Arbitrary V1alpha1InitializerConfigurationList where arbitrary = V1alpha1InitializerConfigurationList <$> arbitrary -- v1alpha1InitializerConfigurationListApiVersion :: Maybe Text <*> arbitrary -- v1alpha1InitializerConfigurationListItems :: [V1alpha1InitializerConfiguration] <*> arbitrary -- v1alpha1InitializerConfigurationListKind :: Maybe Text <*> arbitrary -- v1alpha1InitializerConfigurationListMetadata :: Maybe V1ListMeta instance Arbitrary V1alpha1PodPreset where arbitrary = V1alpha1PodPreset <$> arbitrary -- v1alpha1PodPresetApiVersion :: Maybe Text <*> arbitrary -- v1alpha1PodPresetKind :: Maybe Text <*> arbitrary -- v1alpha1PodPresetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1alpha1PodPresetSpec :: Maybe V1alpha1PodPresetSpec instance Arbitrary V1alpha1PodPresetList where arbitrary = V1alpha1PodPresetList <$> arbitrary -- v1alpha1PodPresetListApiVersion :: Maybe Text <*> arbitrary -- v1alpha1PodPresetListItems :: [V1alpha1PodPreset] <*> arbitrary -- v1alpha1PodPresetListKind :: Maybe Text <*> arbitrary -- v1alpha1PodPresetListMetadata :: Maybe V1ListMeta instance Arbitrary V1alpha1PodPresetSpec where arbitrary = V1alpha1PodPresetSpec <$> arbitrary -- v1alpha1PodPresetSpecEnv :: Maybe [V1EnvVar] <*> arbitrary -- v1alpha1PodPresetSpecEnvFrom :: Maybe [V1EnvFromSource] <*> arbitrary -- v1alpha1PodPresetSpecSelector :: Maybe V1LabelSelector <*> arbitrary -- v1alpha1PodPresetSpecVolumeMounts :: Maybe [V1VolumeMount] <*> arbitrary -- v1alpha1PodPresetSpecVolumes :: Maybe [V1Volume] instance Arbitrary V1alpha1PolicyRule where arbitrary = V1alpha1PolicyRule <$> arbitrary -- v1alpha1PolicyRuleApiGroups :: Maybe [Text] <*> arbitrary -- v1alpha1PolicyRuleNonResourceUrLs :: Maybe [Text] <*> arbitrary -- v1alpha1PolicyRuleResourceNames :: Maybe [Text] <*> arbitrary -- v1alpha1PolicyRuleResources :: Maybe [Text] <*> arbitrary -- v1alpha1PolicyRuleVerbs :: [Text] instance Arbitrary V1alpha1PriorityClass where arbitrary = V1alpha1PriorityClass <$> arbitrary -- v1alpha1PriorityClassApiVersion :: Maybe Text <*> arbitrary -- v1alpha1PriorityClassDescription :: Maybe Text <*> arbitrary -- v1alpha1PriorityClassGlobalDefault :: Maybe Bool <*> arbitrary -- v1alpha1PriorityClassKind :: Maybe Text <*> arbitrary -- v1alpha1PriorityClassMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1alpha1PriorityClassValue :: Int instance Arbitrary V1alpha1PriorityClassList where arbitrary = V1alpha1PriorityClassList <$> arbitrary -- v1alpha1PriorityClassListApiVersion :: Maybe Text <*> arbitrary -- v1alpha1PriorityClassListItems :: [V1alpha1PriorityClass] <*> arbitrary -- v1alpha1PriorityClassListKind :: Maybe Text <*> arbitrary -- v1alpha1PriorityClassListMetadata :: Maybe V1ListMeta instance Arbitrary V1alpha1Role where arbitrary = V1alpha1Role <$> arbitrary -- v1alpha1RoleApiVersion :: Maybe Text <*> arbitrary -- v1alpha1RoleKind :: Maybe Text <*> arbitrary -- v1alpha1RoleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1alpha1RoleRules :: [V1alpha1PolicyRule] instance Arbitrary V1alpha1RoleBinding where arbitrary = V1alpha1RoleBinding <$> arbitrary -- v1alpha1RoleBindingApiVersion :: Maybe Text <*> arbitrary -- v1alpha1RoleBindingKind :: Maybe Text <*> arbitrary -- v1alpha1RoleBindingMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1alpha1RoleBindingRoleRef :: V1alpha1RoleRef <*> arbitrary -- v1alpha1RoleBindingSubjects :: [V1alpha1Subject] instance Arbitrary V1alpha1RoleBindingList where arbitrary = V1alpha1RoleBindingList <$> arbitrary -- v1alpha1RoleBindingListApiVersion :: Maybe Text <*> arbitrary -- v1alpha1RoleBindingListItems :: [V1alpha1RoleBinding] <*> arbitrary -- v1alpha1RoleBindingListKind :: Maybe Text <*> arbitrary -- v1alpha1RoleBindingListMetadata :: Maybe V1ListMeta instance Arbitrary V1alpha1RoleList where arbitrary = V1alpha1RoleList <$> arbitrary -- v1alpha1RoleListApiVersion :: Maybe Text <*> arbitrary -- v1alpha1RoleListItems :: [V1alpha1Role] <*> arbitrary -- v1alpha1RoleListKind :: Maybe Text <*> arbitrary -- v1alpha1RoleListMetadata :: Maybe V1ListMeta instance Arbitrary V1alpha1RoleRef where arbitrary = V1alpha1RoleRef <$> arbitrary -- v1alpha1RoleRefApiGroup :: Text <*> arbitrary -- v1alpha1RoleRefKind :: Text <*> arbitrary -- v1alpha1RoleRefName :: Text instance Arbitrary V1alpha1Rule where arbitrary = V1alpha1Rule <$> arbitrary -- v1alpha1RuleApiGroups :: Maybe [Text] <*> arbitrary -- v1alpha1RuleApiVersions :: Maybe [Text] <*> arbitrary -- v1alpha1RuleResources :: Maybe [Text] instance Arbitrary V1alpha1Subject where arbitrary = V1alpha1Subject <$> arbitrary -- v1alpha1SubjectApiVersion :: Maybe Text <*> arbitrary -- v1alpha1SubjectKind :: Text <*> arbitrary -- v1alpha1SubjectName :: Text <*> arbitrary -- v1alpha1SubjectNamespace :: Maybe Text instance Arbitrary V1alpha1VolumeAttachment where arbitrary = V1alpha1VolumeAttachment <$> arbitrary -- v1alpha1VolumeAttachmentApiVersion :: Maybe Text <*> arbitrary -- v1alpha1VolumeAttachmentKind :: Maybe Text <*> arbitrary -- v1alpha1VolumeAttachmentMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1alpha1VolumeAttachmentSpec :: V1alpha1VolumeAttachmentSpec <*> arbitrary -- v1alpha1VolumeAttachmentStatus :: Maybe V1alpha1VolumeAttachmentStatus instance Arbitrary V1alpha1VolumeAttachmentList where arbitrary = V1alpha1VolumeAttachmentList <$> arbitrary -- v1alpha1VolumeAttachmentListApiVersion :: Maybe Text <*> arbitrary -- v1alpha1VolumeAttachmentListItems :: [V1alpha1VolumeAttachment] <*> arbitrary -- v1alpha1VolumeAttachmentListKind :: Maybe Text <*> arbitrary -- v1alpha1VolumeAttachmentListMetadata :: Maybe V1ListMeta instance Arbitrary V1alpha1VolumeAttachmentSource where arbitrary = V1alpha1VolumeAttachmentSource <$> arbitrary -- v1alpha1VolumeAttachmentSourcePersistentVolumeName :: Maybe Text instance Arbitrary V1alpha1VolumeAttachmentSpec where arbitrary = V1alpha1VolumeAttachmentSpec <$> arbitrary -- v1alpha1VolumeAttachmentSpecAttacher :: Text <*> arbitrary -- v1alpha1VolumeAttachmentSpecNodeName :: Text <*> arbitrary -- v1alpha1VolumeAttachmentSpecSource :: V1alpha1VolumeAttachmentSource instance Arbitrary V1alpha1VolumeAttachmentStatus where arbitrary = V1alpha1VolumeAttachmentStatus <$> arbitrary -- v1alpha1VolumeAttachmentStatusAttachError :: Maybe V1alpha1VolumeError <*> arbitrary -- v1alpha1VolumeAttachmentStatusAttached :: Bool <*> arbitrary -- v1alpha1VolumeAttachmentStatusAttachmentMetadata :: Maybe (Map.Map String Text) <*> arbitrary -- v1alpha1VolumeAttachmentStatusDetachError :: Maybe V1alpha1VolumeError instance Arbitrary V1alpha1VolumeError where arbitrary = V1alpha1VolumeError <$> arbitrary -- v1alpha1VolumeErrorMessage :: Maybe Text <*> arbitrary -- v1alpha1VolumeErrorTime :: Maybe DateTime instance Arbitrary V1beta1APIService where arbitrary = V1beta1APIService <$> arbitrary -- v1beta1APIServiceApiVersion :: Maybe Text <*> arbitrary -- v1beta1APIServiceKind :: Maybe Text <*> arbitrary -- v1beta1APIServiceMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1APIServiceSpec :: Maybe V1beta1APIServiceSpec <*> arbitrary -- v1beta1APIServiceStatus :: Maybe V1beta1APIServiceStatus instance Arbitrary V1beta1APIServiceCondition where arbitrary = V1beta1APIServiceCondition <$> arbitrary -- v1beta1APIServiceConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta1APIServiceConditionMessage :: Maybe Text <*> arbitrary -- v1beta1APIServiceConditionReason :: Maybe Text <*> arbitrary -- v1beta1APIServiceConditionStatus :: Text <*> arbitrary -- v1beta1APIServiceConditionType :: Text instance Arbitrary V1beta1APIServiceList where arbitrary = V1beta1APIServiceList <$> arbitrary -- v1beta1APIServiceListApiVersion :: Maybe Text <*> arbitrary -- v1beta1APIServiceListItems :: [V1beta1APIService] <*> arbitrary -- v1beta1APIServiceListKind :: Maybe Text <*> arbitrary -- v1beta1APIServiceListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1APIServiceSpec where arbitrary = V1beta1APIServiceSpec <$> arbitrary -- v1beta1APIServiceSpecCaBundle :: ByteArray <*> arbitrary -- v1beta1APIServiceSpecGroup :: Maybe Text <*> arbitrary -- v1beta1APIServiceSpecGroupPriorityMinimum :: Int <*> arbitrary -- v1beta1APIServiceSpecInsecureSkipTlsVerify :: Maybe Bool <*> arbitrary -- v1beta1APIServiceSpecService :: ApiregistrationV1beta1ServiceReference <*> arbitrary -- v1beta1APIServiceSpecVersion :: Maybe Text <*> arbitrary -- v1beta1APIServiceSpecVersionPriority :: Int instance Arbitrary V1beta1APIServiceStatus where arbitrary = V1beta1APIServiceStatus <$> arbitrary -- v1beta1APIServiceStatusConditions :: Maybe [V1beta1APIServiceCondition] instance Arbitrary V1beta1AggregationRule where arbitrary = V1beta1AggregationRule <$> arbitrary -- v1beta1AggregationRuleClusterRoleSelectors :: Maybe [V1LabelSelector] instance Arbitrary V1beta1AllowedFlexVolume where arbitrary = V1beta1AllowedFlexVolume <$> arbitrary -- v1beta1AllowedFlexVolumeDriver :: Text instance Arbitrary V1beta1AllowedHostPath where arbitrary = V1beta1AllowedHostPath <$> arbitrary -- v1beta1AllowedHostPathPathPrefix :: Maybe Text instance Arbitrary V1beta1CertificateSigningRequest where arbitrary = V1beta1CertificateSigningRequest <$> arbitrary -- v1beta1CertificateSigningRequestApiVersion :: Maybe Text <*> arbitrary -- v1beta1CertificateSigningRequestKind :: Maybe Text <*> arbitrary -- v1beta1CertificateSigningRequestMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1CertificateSigningRequestSpec :: Maybe V1beta1CertificateSigningRequestSpec <*> arbitrary -- v1beta1CertificateSigningRequestStatus :: Maybe V1beta1CertificateSigningRequestStatus instance Arbitrary V1beta1CertificateSigningRequestCondition where arbitrary = V1beta1CertificateSigningRequestCondition <$> arbitrary -- v1beta1CertificateSigningRequestConditionLastUpdateTime :: Maybe DateTime <*> arbitrary -- v1beta1CertificateSigningRequestConditionMessage :: Maybe Text <*> arbitrary -- v1beta1CertificateSigningRequestConditionReason :: Maybe Text <*> arbitrary -- v1beta1CertificateSigningRequestConditionType :: Text instance Arbitrary V1beta1CertificateSigningRequestList where arbitrary = V1beta1CertificateSigningRequestList <$> arbitrary -- v1beta1CertificateSigningRequestListApiVersion :: Maybe Text <*> arbitrary -- v1beta1CertificateSigningRequestListItems :: [V1beta1CertificateSigningRequest] <*> arbitrary -- v1beta1CertificateSigningRequestListKind :: Maybe Text <*> arbitrary -- v1beta1CertificateSigningRequestListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1CertificateSigningRequestSpec where arbitrary = V1beta1CertificateSigningRequestSpec <$> arbitrary -- v1beta1CertificateSigningRequestSpecExtra :: Maybe (Map.Map String [Text]) <*> arbitrary -- v1beta1CertificateSigningRequestSpecGroups :: Maybe [Text] <*> arbitrary -- v1beta1CertificateSigningRequestSpecRequest :: ByteArray <*> arbitrary -- v1beta1CertificateSigningRequestSpecUid :: Maybe Text <*> arbitrary -- v1beta1CertificateSigningRequestSpecUsages :: Maybe [Text] <*> arbitrary -- v1beta1CertificateSigningRequestSpecUsername :: Maybe Text instance Arbitrary V1beta1CertificateSigningRequestStatus where arbitrary = V1beta1CertificateSigningRequestStatus <$> arbitrary -- v1beta1CertificateSigningRequestStatusCertificate :: Maybe ByteArray <*> arbitrary -- v1beta1CertificateSigningRequestStatusConditions :: Maybe [V1beta1CertificateSigningRequestCondition] instance Arbitrary V1beta1ClusterRole where arbitrary = V1beta1ClusterRole <$> arbitrary -- v1beta1ClusterRoleAggregationRule :: Maybe V1beta1AggregationRule <*> arbitrary -- v1beta1ClusterRoleApiVersion :: Maybe Text <*> arbitrary -- v1beta1ClusterRoleKind :: Maybe Text <*> arbitrary -- v1beta1ClusterRoleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1ClusterRoleRules :: [V1beta1PolicyRule] instance Arbitrary V1beta1ClusterRoleBinding where arbitrary = V1beta1ClusterRoleBinding <$> arbitrary -- v1beta1ClusterRoleBindingApiVersion :: Maybe Text <*> arbitrary -- v1beta1ClusterRoleBindingKind :: Maybe Text <*> arbitrary -- v1beta1ClusterRoleBindingMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1ClusterRoleBindingRoleRef :: V1beta1RoleRef <*> arbitrary -- v1beta1ClusterRoleBindingSubjects :: [V1beta1Subject] instance Arbitrary V1beta1ClusterRoleBindingList where arbitrary = V1beta1ClusterRoleBindingList <$> arbitrary -- v1beta1ClusterRoleBindingListApiVersion :: Maybe Text <*> arbitrary -- v1beta1ClusterRoleBindingListItems :: [V1beta1ClusterRoleBinding] <*> arbitrary -- v1beta1ClusterRoleBindingListKind :: Maybe Text <*> arbitrary -- v1beta1ClusterRoleBindingListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1ClusterRoleList where arbitrary = V1beta1ClusterRoleList <$> arbitrary -- v1beta1ClusterRoleListApiVersion :: Maybe Text <*> arbitrary -- v1beta1ClusterRoleListItems :: [V1beta1ClusterRole] <*> arbitrary -- v1beta1ClusterRoleListKind :: Maybe Text <*> arbitrary -- v1beta1ClusterRoleListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1ControllerRevision where arbitrary = V1beta1ControllerRevision <$> arbitrary -- v1beta1ControllerRevisionApiVersion :: Maybe Text <*> arbitrary -- v1beta1ControllerRevisionData :: Maybe RuntimeRawExtension <*> arbitrary -- v1beta1ControllerRevisionKind :: Maybe Text <*> arbitrary -- v1beta1ControllerRevisionMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1ControllerRevisionRevision :: Integer instance Arbitrary V1beta1ControllerRevisionList where arbitrary = V1beta1ControllerRevisionList <$> arbitrary -- v1beta1ControllerRevisionListApiVersion :: Maybe Text <*> arbitrary -- v1beta1ControllerRevisionListItems :: [V1beta1ControllerRevision] <*> arbitrary -- v1beta1ControllerRevisionListKind :: Maybe Text <*> arbitrary -- v1beta1ControllerRevisionListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1CronJob where arbitrary = V1beta1CronJob <$> arbitrary -- v1beta1CronJobApiVersion :: Maybe Text <*> arbitrary -- v1beta1CronJobKind :: Maybe Text <*> arbitrary -- v1beta1CronJobMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1CronJobSpec :: Maybe V1beta1CronJobSpec <*> arbitrary -- v1beta1CronJobStatus :: Maybe V1beta1CronJobStatus instance Arbitrary V1beta1CronJobList where arbitrary = V1beta1CronJobList <$> arbitrary -- v1beta1CronJobListApiVersion :: Maybe Text <*> arbitrary -- v1beta1CronJobListItems :: [V1beta1CronJob] <*> arbitrary -- v1beta1CronJobListKind :: Maybe Text <*> arbitrary -- v1beta1CronJobListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1CronJobSpec where arbitrary = V1beta1CronJobSpec <$> arbitrary -- v1beta1CronJobSpecConcurrencyPolicy :: Maybe Text <*> arbitrary -- v1beta1CronJobSpecFailedJobsHistoryLimit :: Maybe Int <*> arbitrary -- v1beta1CronJobSpecJobTemplate :: V1beta1JobTemplateSpec <*> arbitrary -- v1beta1CronJobSpecSchedule :: Text <*> arbitrary -- v1beta1CronJobSpecStartingDeadlineSeconds :: Maybe Integer <*> arbitrary -- v1beta1CronJobSpecSuccessfulJobsHistoryLimit :: Maybe Int <*> arbitrary -- v1beta1CronJobSpecSuspend :: Maybe Bool instance Arbitrary V1beta1CronJobStatus where arbitrary = V1beta1CronJobStatus <$> arbitrary -- v1beta1CronJobStatusActive :: Maybe [V1ObjectReference] <*> arbitrary -- v1beta1CronJobStatusLastScheduleTime :: Maybe DateTime instance Arbitrary V1beta1CustomResourceDefinition where arbitrary = V1beta1CustomResourceDefinition <$> arbitrary -- v1beta1CustomResourceDefinitionApiVersion :: Maybe Text <*> arbitrary -- v1beta1CustomResourceDefinitionKind :: Maybe Text <*> arbitrary -- v1beta1CustomResourceDefinitionMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1CustomResourceDefinitionSpec :: Maybe V1beta1CustomResourceDefinitionSpec <*> arbitrary -- v1beta1CustomResourceDefinitionStatus :: Maybe V1beta1CustomResourceDefinitionStatus instance Arbitrary V1beta1CustomResourceDefinitionCondition where arbitrary = V1beta1CustomResourceDefinitionCondition <$> arbitrary -- v1beta1CustomResourceDefinitionConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta1CustomResourceDefinitionConditionMessage :: Maybe Text <*> arbitrary -- v1beta1CustomResourceDefinitionConditionReason :: Maybe Text <*> arbitrary -- v1beta1CustomResourceDefinitionConditionStatus :: Text <*> arbitrary -- v1beta1CustomResourceDefinitionConditionType :: Text instance Arbitrary V1beta1CustomResourceDefinitionList where arbitrary = V1beta1CustomResourceDefinitionList <$> arbitrary -- v1beta1CustomResourceDefinitionListApiVersion :: Maybe Text <*> arbitrary -- v1beta1CustomResourceDefinitionListItems :: [V1beta1CustomResourceDefinition] <*> arbitrary -- v1beta1CustomResourceDefinitionListKind :: Maybe Text <*> arbitrary -- v1beta1CustomResourceDefinitionListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1CustomResourceDefinitionNames where arbitrary = V1beta1CustomResourceDefinitionNames <$> arbitrary -- v1beta1CustomResourceDefinitionNamesKind :: Text <*> arbitrary -- v1beta1CustomResourceDefinitionNamesListKind :: Maybe Text <*> arbitrary -- v1beta1CustomResourceDefinitionNamesPlural :: Text <*> arbitrary -- v1beta1CustomResourceDefinitionNamesShortNames :: Maybe [Text] <*> arbitrary -- v1beta1CustomResourceDefinitionNamesSingular :: Maybe Text instance Arbitrary V1beta1CustomResourceDefinitionSpec where arbitrary = V1beta1CustomResourceDefinitionSpec <$> arbitrary -- v1beta1CustomResourceDefinitionSpecGroup :: Text <*> arbitrary -- v1beta1CustomResourceDefinitionSpecNames :: V1beta1CustomResourceDefinitionNames <*> arbitrary -- v1beta1CustomResourceDefinitionSpecScope :: Text <*> arbitrary -- v1beta1CustomResourceDefinitionSpecValidation :: Maybe V1beta1CustomResourceValidation <*> arbitrary -- v1beta1CustomResourceDefinitionSpecVersion :: Text instance Arbitrary V1beta1CustomResourceDefinitionStatus where arbitrary = V1beta1CustomResourceDefinitionStatus <$> arbitrary -- v1beta1CustomResourceDefinitionStatusAcceptedNames :: V1beta1CustomResourceDefinitionNames <*> arbitrary -- v1beta1CustomResourceDefinitionStatusConditions :: [V1beta1CustomResourceDefinitionCondition] instance Arbitrary V1beta1CustomResourceValidation where arbitrary = V1beta1CustomResourceValidation <$> arbitrary -- v1beta1CustomResourceValidationOpenApiv3Schema :: Maybe V1beta1JSONSchemaProps instance Arbitrary V1beta1DaemonSet where arbitrary = V1beta1DaemonSet <$> arbitrary -- v1beta1DaemonSetApiVersion :: Maybe Text <*> arbitrary -- v1beta1DaemonSetKind :: Maybe Text <*> arbitrary -- v1beta1DaemonSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1DaemonSetSpec :: Maybe V1beta1DaemonSetSpec <*> arbitrary -- v1beta1DaemonSetStatus :: Maybe V1beta1DaemonSetStatus instance Arbitrary V1beta1DaemonSetCondition where arbitrary = V1beta1DaemonSetCondition <$> arbitrary -- v1beta1DaemonSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta1DaemonSetConditionMessage :: Maybe Text <*> arbitrary -- v1beta1DaemonSetConditionReason :: Maybe Text <*> arbitrary -- v1beta1DaemonSetConditionStatus :: Text <*> arbitrary -- v1beta1DaemonSetConditionType :: Text instance Arbitrary V1beta1DaemonSetList where arbitrary = V1beta1DaemonSetList <$> arbitrary -- v1beta1DaemonSetListApiVersion :: Maybe Text <*> arbitrary -- v1beta1DaemonSetListItems :: [V1beta1DaemonSet] <*> arbitrary -- v1beta1DaemonSetListKind :: Maybe Text <*> arbitrary -- v1beta1DaemonSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1DaemonSetSpec where arbitrary = V1beta1DaemonSetSpec <$> arbitrary -- v1beta1DaemonSetSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1beta1DaemonSetSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- v1beta1DaemonSetSpecSelector :: Maybe V1LabelSelector <*> arbitrary -- v1beta1DaemonSetSpecTemplate :: V1PodTemplateSpec <*> arbitrary -- v1beta1DaemonSetSpecTemplateGeneration :: Maybe Integer <*> arbitrary -- v1beta1DaemonSetSpecUpdateStrategy :: Maybe V1beta1DaemonSetUpdateStrategy instance Arbitrary V1beta1DaemonSetStatus where arbitrary = V1beta1DaemonSetStatus <$> arbitrary -- v1beta1DaemonSetStatusCollisionCount :: Maybe Int <*> arbitrary -- v1beta1DaemonSetStatusConditions :: Maybe [V1beta1DaemonSetCondition] <*> arbitrary -- v1beta1DaemonSetStatusCurrentNumberScheduled :: Int <*> arbitrary -- v1beta1DaemonSetStatusDesiredNumberScheduled :: Int <*> arbitrary -- v1beta1DaemonSetStatusNumberAvailable :: Maybe Int <*> arbitrary -- v1beta1DaemonSetStatusNumberMisscheduled :: Int <*> arbitrary -- v1beta1DaemonSetStatusNumberReady :: Int <*> arbitrary -- v1beta1DaemonSetStatusNumberUnavailable :: Maybe Int <*> arbitrary -- v1beta1DaemonSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1beta1DaemonSetStatusUpdatedNumberScheduled :: Maybe Int instance Arbitrary V1beta1DaemonSetUpdateStrategy where arbitrary = V1beta1DaemonSetUpdateStrategy <$> arbitrary -- v1beta1DaemonSetUpdateStrategyRollingUpdate :: Maybe V1beta1RollingUpdateDaemonSet <*> arbitrary -- v1beta1DaemonSetUpdateStrategyType :: Maybe Text instance Arbitrary V1beta1Event where arbitrary = V1beta1Event <$> arbitrary -- v1beta1EventAction :: Maybe Text <*> arbitrary -- v1beta1EventApiVersion :: Maybe Text <*> arbitrary -- v1beta1EventDeprecatedCount :: Maybe Int <*> arbitrary -- v1beta1EventDeprecatedFirstTimestamp :: Maybe DateTime <*> arbitrary -- v1beta1EventDeprecatedLastTimestamp :: Maybe DateTime <*> arbitrary -- v1beta1EventDeprecatedSource :: Maybe V1EventSource <*> arbitrary -- v1beta1EventEventTime :: DateTime <*> arbitrary -- v1beta1EventKind :: Maybe Text <*> arbitrary -- v1beta1EventMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1EventNote :: Maybe Text <*> arbitrary -- v1beta1EventReason :: Maybe Text <*> arbitrary -- v1beta1EventRegarding :: Maybe V1ObjectReference <*> arbitrary -- v1beta1EventRelated :: Maybe V1ObjectReference <*> arbitrary -- v1beta1EventReportingController :: Maybe Text <*> arbitrary -- v1beta1EventReportingInstance :: Maybe Text <*> arbitrary -- v1beta1EventSeries :: Maybe V1beta1EventSeries <*> arbitrary -- v1beta1EventType :: Maybe Text instance Arbitrary V1beta1EventList where arbitrary = V1beta1EventList <$> arbitrary -- v1beta1EventListApiVersion :: Maybe Text <*> arbitrary -- v1beta1EventListItems :: [V1beta1Event] <*> arbitrary -- v1beta1EventListKind :: Maybe Text <*> arbitrary -- v1beta1EventListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1EventSeries where arbitrary = V1beta1EventSeries <$> arbitrary -- v1beta1EventSeriesCount :: Int <*> arbitrary -- v1beta1EventSeriesLastObservedTime :: DateTime <*> arbitrary -- v1beta1EventSeriesState :: Text instance Arbitrary V1beta1Eviction where arbitrary = V1beta1Eviction <$> arbitrary -- v1beta1EvictionApiVersion :: Maybe Text <*> arbitrary -- v1beta1EvictionDeleteOptions :: Maybe V1DeleteOptions <*> arbitrary -- v1beta1EvictionKind :: Maybe Text <*> arbitrary -- v1beta1EvictionMetadata :: Maybe V1ObjectMeta instance Arbitrary V1beta1ExternalDocumentation where arbitrary = V1beta1ExternalDocumentation <$> arbitrary -- v1beta1ExternalDocumentationDescription :: Maybe Text <*> arbitrary -- v1beta1ExternalDocumentationUrl :: Maybe Text instance Arbitrary V1beta1FSGroupStrategyOptions where arbitrary = V1beta1FSGroupStrategyOptions <$> arbitrary -- v1beta1FSGroupStrategyOptionsRanges :: Maybe [V1beta1IDRange] <*> arbitrary -- v1beta1FSGroupStrategyOptionsRule :: Maybe Text instance Arbitrary V1beta1HTTPIngressPath where arbitrary = V1beta1HTTPIngressPath <$> arbitrary -- v1beta1HTTPIngressPathBackend :: V1beta1IngressBackend <*> arbitrary -- v1beta1HTTPIngressPathPath :: Maybe Text instance Arbitrary V1beta1HTTPIngressRuleValue where arbitrary = V1beta1HTTPIngressRuleValue <$> arbitrary -- v1beta1HTTPIngressRuleValuePaths :: [V1beta1HTTPIngressPath] instance Arbitrary V1beta1HostPortRange where arbitrary = V1beta1HostPortRange <$> arbitrary -- v1beta1HostPortRangeMax :: Int <*> arbitrary -- v1beta1HostPortRangeMin :: Int instance Arbitrary V1beta1IDRange where arbitrary = V1beta1IDRange <$> arbitrary -- v1beta1IDRangeMax :: Integer <*> arbitrary -- v1beta1IDRangeMin :: Integer instance Arbitrary V1beta1IPBlock where arbitrary = V1beta1IPBlock <$> arbitrary -- v1beta1IPBlockCidr :: Text <*> arbitrary -- v1beta1IPBlockExcept :: Maybe [Text] instance Arbitrary V1beta1Ingress where arbitrary = V1beta1Ingress <$> arbitrary -- v1beta1IngressApiVersion :: Maybe Text <*> arbitrary -- v1beta1IngressKind :: Maybe Text <*> arbitrary -- v1beta1IngressMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1IngressSpec :: Maybe V1beta1IngressSpec <*> arbitrary -- v1beta1IngressStatus :: Maybe V1beta1IngressStatus instance Arbitrary V1beta1IngressBackend where arbitrary = V1beta1IngressBackend <$> arbitrary -- v1beta1IngressBackendServiceName :: Text <*> arbitrary -- v1beta1IngressBackendServicePort :: A.Value instance Arbitrary V1beta1IngressList where arbitrary = V1beta1IngressList <$> arbitrary -- v1beta1IngressListApiVersion :: Maybe Text <*> arbitrary -- v1beta1IngressListItems :: [V1beta1Ingress] <*> arbitrary -- v1beta1IngressListKind :: Maybe Text <*> arbitrary -- v1beta1IngressListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1IngressRule where arbitrary = V1beta1IngressRule <$> arbitrary -- v1beta1IngressRuleHost :: Maybe Text <*> arbitrary -- v1beta1IngressRuleHttp :: Maybe V1beta1HTTPIngressRuleValue instance Arbitrary V1beta1IngressSpec where arbitrary = V1beta1IngressSpec <$> arbitrary -- v1beta1IngressSpecBackend :: Maybe V1beta1IngressBackend <*> arbitrary -- v1beta1IngressSpecRules :: Maybe [V1beta1IngressRule] <*> arbitrary -- v1beta1IngressSpecTls :: Maybe [V1beta1IngressTLS] instance Arbitrary V1beta1IngressStatus where arbitrary = V1beta1IngressStatus <$> arbitrary -- v1beta1IngressStatusLoadBalancer :: Maybe V1LoadBalancerStatus instance Arbitrary V1beta1IngressTLS where arbitrary = V1beta1IngressTLS <$> arbitrary -- v1beta1IngressTLSHosts :: Maybe [Text] <*> arbitrary -- v1beta1IngressTLSSecretName :: Maybe Text instance Arbitrary V1beta1JSON where arbitrary = V1beta1JSON <$> arbitrary -- v1beta1JSONRaw :: ByteArray instance Arbitrary V1beta1JSONSchemaProps where arbitrary = V1beta1JSONSchemaProps <$> arbitrary -- v1beta1JSONSchemaPropsRef :: Maybe Text <*> arbitrary -- v1beta1JSONSchemaPropsSchema :: Maybe Text <*> arbitrary -- v1beta1JSONSchemaPropsAdditionalItems :: Maybe V1beta1JSONSchemaPropsOrBool <*> arbitrary -- v1beta1JSONSchemaPropsAdditionalProperties :: Maybe V1beta1JSONSchemaPropsOrBool <*> arbitrary -- v1beta1JSONSchemaPropsAllOf :: Maybe [V1beta1JSONSchemaProps] <*> arbitrary -- v1beta1JSONSchemaPropsAnyOf :: Maybe [V1beta1JSONSchemaProps] <*> arbitrary -- v1beta1JSONSchemaPropsDefault :: Maybe V1beta1JSON <*> arbitrary -- v1beta1JSONSchemaPropsDefinitions :: Maybe (Map.Map String V1beta1JSONSchemaProps) <*> arbitrary -- v1beta1JSONSchemaPropsDependencies :: Maybe (Map.Map String V1beta1JSONSchemaPropsOrStringArray) <*> arbitrary -- v1beta1JSONSchemaPropsDescription :: Maybe Text <*> arbitrary -- v1beta1JSONSchemaPropsEnum :: Maybe [V1beta1JSON] <*> arbitrary -- v1beta1JSONSchemaPropsExample :: Maybe V1beta1JSON <*> arbitrary -- v1beta1JSONSchemaPropsExclusiveMaximum :: Maybe Bool <*> arbitrary -- v1beta1JSONSchemaPropsExclusiveMinimum :: Maybe Bool <*> arbitrary -- v1beta1JSONSchemaPropsExternalDocs :: Maybe V1beta1ExternalDocumentation <*> arbitrary -- v1beta1JSONSchemaPropsFormat :: Maybe Text <*> arbitrary -- v1beta1JSONSchemaPropsId :: Maybe Text <*> arbitrary -- v1beta1JSONSchemaPropsItems :: Maybe V1beta1JSONSchemaPropsOrArray <*> arbitrary -- v1beta1JSONSchemaPropsMaxItems :: Maybe Integer <*> arbitrary -- v1beta1JSONSchemaPropsMaxLength :: Maybe Integer <*> arbitrary -- v1beta1JSONSchemaPropsMaxProperties :: Maybe Integer <*> arbitrary -- v1beta1JSONSchemaPropsMaximum :: Maybe Double <*> arbitrary -- v1beta1JSONSchemaPropsMinItems :: Maybe Integer <*> arbitrary -- v1beta1JSONSchemaPropsMinLength :: Maybe Integer <*> arbitrary -- v1beta1JSONSchemaPropsMinProperties :: Maybe Integer <*> arbitrary -- v1beta1JSONSchemaPropsMinimum :: Maybe Double <*> arbitrary -- v1beta1JSONSchemaPropsMultipleOf :: Maybe Double <*> arbitrary -- v1beta1JSONSchemaPropsNot :: Maybe V1beta1JSONSchemaProps <*> arbitrary -- v1beta1JSONSchemaPropsOneOf :: Maybe [V1beta1JSONSchemaProps] <*> arbitrary -- v1beta1JSONSchemaPropsPattern :: Maybe Text <*> arbitrary -- v1beta1JSONSchemaPropsPatternProperties :: Maybe (Map.Map String V1beta1JSONSchemaProps) <*> arbitrary -- v1beta1JSONSchemaPropsProperties :: Maybe (Map.Map String V1beta1JSONSchemaProps) <*> arbitrary -- v1beta1JSONSchemaPropsRequired :: Maybe [Text] <*> arbitrary -- v1beta1JSONSchemaPropsTitle :: Maybe Text <*> arbitrary -- v1beta1JSONSchemaPropsType :: Maybe Text <*> arbitrary -- v1beta1JSONSchemaPropsUniqueItems :: Maybe Bool instance Arbitrary V1beta1JSONSchemaPropsOrArray where arbitrary = V1beta1JSONSchemaPropsOrArray <$> arbitrary -- v1beta1JSONSchemaPropsOrArrayJsonSchemas :: [V1beta1JSONSchemaProps] <*> arbitrary -- v1beta1JSONSchemaPropsOrArraySchema :: V1beta1JSONSchemaProps instance Arbitrary V1beta1JSONSchemaPropsOrBool where arbitrary = V1beta1JSONSchemaPropsOrBool <$> arbitrary -- v1beta1JSONSchemaPropsOrBoolAllows :: Bool <*> arbitrary -- v1beta1JSONSchemaPropsOrBoolSchema :: V1beta1JSONSchemaProps instance Arbitrary V1beta1JSONSchemaPropsOrStringArray where arbitrary = V1beta1JSONSchemaPropsOrStringArray <$> arbitrary -- v1beta1JSONSchemaPropsOrStringArrayProperty :: [Text] <*> arbitrary -- v1beta1JSONSchemaPropsOrStringArraySchema :: V1beta1JSONSchemaProps instance Arbitrary V1beta1JobTemplateSpec where arbitrary = V1beta1JobTemplateSpec <$> arbitrary -- v1beta1JobTemplateSpecMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1JobTemplateSpecSpec :: Maybe V1JobSpec instance Arbitrary V1beta1LocalSubjectAccessReview where arbitrary = V1beta1LocalSubjectAccessReview <$> arbitrary -- v1beta1LocalSubjectAccessReviewApiVersion :: Maybe Text <*> arbitrary -- v1beta1LocalSubjectAccessReviewKind :: Maybe Text <*> arbitrary -- v1beta1LocalSubjectAccessReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1LocalSubjectAccessReviewSpec :: V1beta1SubjectAccessReviewSpec <*> arbitrary -- v1beta1LocalSubjectAccessReviewStatus :: Maybe V1beta1SubjectAccessReviewStatus instance Arbitrary V1beta1MutatingWebhookConfiguration where arbitrary = V1beta1MutatingWebhookConfiguration <$> arbitrary -- v1beta1MutatingWebhookConfigurationApiVersion :: Maybe Text <*> arbitrary -- v1beta1MutatingWebhookConfigurationKind :: Maybe Text <*> arbitrary -- v1beta1MutatingWebhookConfigurationMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1MutatingWebhookConfigurationWebhooks :: Maybe [V1beta1Webhook] instance Arbitrary V1beta1MutatingWebhookConfigurationList where arbitrary = V1beta1MutatingWebhookConfigurationList <$> arbitrary -- v1beta1MutatingWebhookConfigurationListApiVersion :: Maybe Text <*> arbitrary -- v1beta1MutatingWebhookConfigurationListItems :: [V1beta1MutatingWebhookConfiguration] <*> arbitrary -- v1beta1MutatingWebhookConfigurationListKind :: Maybe Text <*> arbitrary -- v1beta1MutatingWebhookConfigurationListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1NetworkPolicy where arbitrary = V1beta1NetworkPolicy <$> arbitrary -- v1beta1NetworkPolicyApiVersion :: Maybe Text <*> arbitrary -- v1beta1NetworkPolicyKind :: Maybe Text <*> arbitrary -- v1beta1NetworkPolicyMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1NetworkPolicySpec :: Maybe V1beta1NetworkPolicySpec instance Arbitrary V1beta1NetworkPolicyEgressRule where arbitrary = V1beta1NetworkPolicyEgressRule <$> arbitrary -- v1beta1NetworkPolicyEgressRulePorts :: Maybe [V1beta1NetworkPolicyPort] <*> arbitrary -- v1beta1NetworkPolicyEgressRuleTo :: Maybe [V1beta1NetworkPolicyPeer] instance Arbitrary V1beta1NetworkPolicyIngressRule where arbitrary = V1beta1NetworkPolicyIngressRule <$> arbitrary -- v1beta1NetworkPolicyIngressRuleFrom :: Maybe [V1beta1NetworkPolicyPeer] <*> arbitrary -- v1beta1NetworkPolicyIngressRulePorts :: Maybe [V1beta1NetworkPolicyPort] instance Arbitrary V1beta1NetworkPolicyList where arbitrary = V1beta1NetworkPolicyList <$> arbitrary -- v1beta1NetworkPolicyListApiVersion :: Maybe Text <*> arbitrary -- v1beta1NetworkPolicyListItems :: [V1beta1NetworkPolicy] <*> arbitrary -- v1beta1NetworkPolicyListKind :: Maybe Text <*> arbitrary -- v1beta1NetworkPolicyListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1NetworkPolicyPeer where arbitrary = V1beta1NetworkPolicyPeer <$> arbitrary -- v1beta1NetworkPolicyPeerIpBlock :: Maybe V1beta1IPBlock <*> arbitrary -- v1beta1NetworkPolicyPeerNamespaceSelector :: Maybe V1LabelSelector <*> arbitrary -- v1beta1NetworkPolicyPeerPodSelector :: Maybe V1LabelSelector instance Arbitrary V1beta1NetworkPolicyPort where arbitrary = V1beta1NetworkPolicyPort <$> arbitrary -- v1beta1NetworkPolicyPortPort :: Maybe A.Value <*> arbitrary -- v1beta1NetworkPolicyPortProtocol :: Maybe Text instance Arbitrary V1beta1NetworkPolicySpec where arbitrary = V1beta1NetworkPolicySpec <$> arbitrary -- v1beta1NetworkPolicySpecEgress :: Maybe [V1beta1NetworkPolicyEgressRule] <*> arbitrary -- v1beta1NetworkPolicySpecIngress :: Maybe [V1beta1NetworkPolicyIngressRule] <*> arbitrary -- v1beta1NetworkPolicySpecPodSelector :: V1LabelSelector <*> arbitrary -- v1beta1NetworkPolicySpecPolicyTypes :: Maybe [Text] instance Arbitrary V1beta1NonResourceAttributes where arbitrary = V1beta1NonResourceAttributes <$> arbitrary -- v1beta1NonResourceAttributesPath :: Maybe Text <*> arbitrary -- v1beta1NonResourceAttributesVerb :: Maybe Text instance Arbitrary V1beta1NonResourceRule where arbitrary = V1beta1NonResourceRule <$> arbitrary -- v1beta1NonResourceRuleNonResourceUrLs :: Maybe [Text] <*> arbitrary -- v1beta1NonResourceRuleVerbs :: [Text] instance Arbitrary V1beta1PodDisruptionBudget where arbitrary = V1beta1PodDisruptionBudget <$> arbitrary -- v1beta1PodDisruptionBudgetApiVersion :: Maybe Text <*> arbitrary -- v1beta1PodDisruptionBudgetKind :: Maybe Text <*> arbitrary -- v1beta1PodDisruptionBudgetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1PodDisruptionBudgetSpec :: Maybe V1beta1PodDisruptionBudgetSpec <*> arbitrary -- v1beta1PodDisruptionBudgetStatus :: Maybe V1beta1PodDisruptionBudgetStatus instance Arbitrary V1beta1PodDisruptionBudgetList where arbitrary = V1beta1PodDisruptionBudgetList <$> arbitrary -- v1beta1PodDisruptionBudgetListApiVersion :: Maybe Text <*> arbitrary -- v1beta1PodDisruptionBudgetListItems :: [V1beta1PodDisruptionBudget] <*> arbitrary -- v1beta1PodDisruptionBudgetListKind :: Maybe Text <*> arbitrary -- v1beta1PodDisruptionBudgetListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1PodDisruptionBudgetSpec where arbitrary = V1beta1PodDisruptionBudgetSpec <$> arbitrary -- v1beta1PodDisruptionBudgetSpecMaxUnavailable :: Maybe A.Value <*> arbitrary -- v1beta1PodDisruptionBudgetSpecMinAvailable :: Maybe A.Value <*> arbitrary -- v1beta1PodDisruptionBudgetSpecSelector :: Maybe V1LabelSelector instance Arbitrary V1beta1PodDisruptionBudgetStatus where arbitrary = V1beta1PodDisruptionBudgetStatus <$> arbitrary -- v1beta1PodDisruptionBudgetStatusCurrentHealthy :: Int <*> arbitrary -- v1beta1PodDisruptionBudgetStatusDesiredHealthy :: Int <*> arbitrary -- v1beta1PodDisruptionBudgetStatusDisruptedPods :: (Map.Map String DateTime) <*> arbitrary -- v1beta1PodDisruptionBudgetStatusDisruptionsAllowed :: Int <*> arbitrary -- v1beta1PodDisruptionBudgetStatusExpectedPods :: Int <*> arbitrary -- v1beta1PodDisruptionBudgetStatusObservedGeneration :: Maybe Integer instance Arbitrary V1beta1PodSecurityPolicy where arbitrary = V1beta1PodSecurityPolicy <$> arbitrary -- v1beta1PodSecurityPolicyApiVersion :: Maybe Text <*> arbitrary -- v1beta1PodSecurityPolicyKind :: Maybe Text <*> arbitrary -- v1beta1PodSecurityPolicyMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1PodSecurityPolicySpec :: Maybe V1beta1PodSecurityPolicySpec instance Arbitrary V1beta1PodSecurityPolicyList where arbitrary = V1beta1PodSecurityPolicyList <$> arbitrary -- v1beta1PodSecurityPolicyListApiVersion :: Maybe Text <*> arbitrary -- v1beta1PodSecurityPolicyListItems :: [V1beta1PodSecurityPolicy] <*> arbitrary -- v1beta1PodSecurityPolicyListKind :: Maybe Text <*> arbitrary -- v1beta1PodSecurityPolicyListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1PodSecurityPolicySpec where arbitrary = V1beta1PodSecurityPolicySpec <$> arbitrary -- v1beta1PodSecurityPolicySpecAllowPrivilegeEscalation :: Maybe Bool <*> arbitrary -- v1beta1PodSecurityPolicySpecAllowedCapabilities :: Maybe [Text] <*> arbitrary -- v1beta1PodSecurityPolicySpecAllowedFlexVolumes :: Maybe [V1beta1AllowedFlexVolume] <*> arbitrary -- v1beta1PodSecurityPolicySpecAllowedHostPaths :: Maybe [V1beta1AllowedHostPath] <*> arbitrary -- v1beta1PodSecurityPolicySpecDefaultAddCapabilities :: Maybe [Text] <*> arbitrary -- v1beta1PodSecurityPolicySpecDefaultAllowPrivilegeEscalation :: Maybe Bool <*> arbitrary -- v1beta1PodSecurityPolicySpecFsGroup :: V1beta1FSGroupStrategyOptions <*> arbitrary -- v1beta1PodSecurityPolicySpecHostIpc :: Maybe Bool <*> arbitrary -- v1beta1PodSecurityPolicySpecHostNetwork :: Maybe Bool <*> arbitrary -- v1beta1PodSecurityPolicySpecHostPid :: Maybe Bool <*> arbitrary -- v1beta1PodSecurityPolicySpecHostPorts :: Maybe [V1beta1HostPortRange] <*> arbitrary -- v1beta1PodSecurityPolicySpecPrivileged :: Maybe Bool <*> arbitrary -- v1beta1PodSecurityPolicySpecReadOnlyRootFilesystem :: Maybe Bool <*> arbitrary -- v1beta1PodSecurityPolicySpecRequiredDropCapabilities :: Maybe [Text] <*> arbitrary -- v1beta1PodSecurityPolicySpecRunAsUser :: V1beta1RunAsUserStrategyOptions <*> arbitrary -- v1beta1PodSecurityPolicySpecSeLinux :: V1beta1SELinuxStrategyOptions <*> arbitrary -- v1beta1PodSecurityPolicySpecSupplementalGroups :: V1beta1SupplementalGroupsStrategyOptions <*> arbitrary -- v1beta1PodSecurityPolicySpecVolumes :: Maybe [Text] instance Arbitrary V1beta1PolicyRule where arbitrary = V1beta1PolicyRule <$> arbitrary -- v1beta1PolicyRuleApiGroups :: Maybe [Text] <*> arbitrary -- v1beta1PolicyRuleNonResourceUrLs :: Maybe [Text] <*> arbitrary -- v1beta1PolicyRuleResourceNames :: Maybe [Text] <*> arbitrary -- v1beta1PolicyRuleResources :: Maybe [Text] <*> arbitrary -- v1beta1PolicyRuleVerbs :: [Text] instance Arbitrary V1beta1ReplicaSet where arbitrary = V1beta1ReplicaSet <$> arbitrary -- v1beta1ReplicaSetApiVersion :: Maybe Text <*> arbitrary -- v1beta1ReplicaSetKind :: Maybe Text <*> arbitrary -- v1beta1ReplicaSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1ReplicaSetSpec :: Maybe V1beta1ReplicaSetSpec <*> arbitrary -- v1beta1ReplicaSetStatus :: Maybe V1beta1ReplicaSetStatus instance Arbitrary V1beta1ReplicaSetCondition where arbitrary = V1beta1ReplicaSetCondition <$> arbitrary -- v1beta1ReplicaSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta1ReplicaSetConditionMessage :: Maybe Text <*> arbitrary -- v1beta1ReplicaSetConditionReason :: Maybe Text <*> arbitrary -- v1beta1ReplicaSetConditionStatus :: Text <*> arbitrary -- v1beta1ReplicaSetConditionType :: Text instance Arbitrary V1beta1ReplicaSetList where arbitrary = V1beta1ReplicaSetList <$> arbitrary -- v1beta1ReplicaSetListApiVersion :: Maybe Text <*> arbitrary -- v1beta1ReplicaSetListItems :: [V1beta1ReplicaSet] <*> arbitrary -- v1beta1ReplicaSetListKind :: Maybe Text <*> arbitrary -- v1beta1ReplicaSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1ReplicaSetSpec where arbitrary = V1beta1ReplicaSetSpec <$> arbitrary -- v1beta1ReplicaSetSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1beta1ReplicaSetSpecReplicas :: Maybe Int <*> arbitrary -- v1beta1ReplicaSetSpecSelector :: Maybe V1LabelSelector <*> arbitrary -- v1beta1ReplicaSetSpecTemplate :: Maybe V1PodTemplateSpec instance Arbitrary V1beta1ReplicaSetStatus where arbitrary = V1beta1ReplicaSetStatus <$> arbitrary -- v1beta1ReplicaSetStatusAvailableReplicas :: Maybe Int <*> arbitrary -- v1beta1ReplicaSetStatusConditions :: Maybe [V1beta1ReplicaSetCondition] <*> arbitrary -- v1beta1ReplicaSetStatusFullyLabeledReplicas :: Maybe Int <*> arbitrary -- v1beta1ReplicaSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1beta1ReplicaSetStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1beta1ReplicaSetStatusReplicas :: Int instance Arbitrary V1beta1ResourceAttributes where arbitrary = V1beta1ResourceAttributes <$> arbitrary -- v1beta1ResourceAttributesGroup :: Maybe Text <*> arbitrary -- v1beta1ResourceAttributesName :: Maybe Text <*> arbitrary -- v1beta1ResourceAttributesNamespace :: Maybe Text <*> arbitrary -- v1beta1ResourceAttributesResource :: Maybe Text <*> arbitrary -- v1beta1ResourceAttributesSubresource :: Maybe Text <*> arbitrary -- v1beta1ResourceAttributesVerb :: Maybe Text <*> arbitrary -- v1beta1ResourceAttributesVersion :: Maybe Text instance Arbitrary V1beta1ResourceRule where arbitrary = V1beta1ResourceRule <$> arbitrary -- v1beta1ResourceRuleApiGroups :: Maybe [Text] <*> arbitrary -- v1beta1ResourceRuleResourceNames :: Maybe [Text] <*> arbitrary -- v1beta1ResourceRuleResources :: Maybe [Text] <*> arbitrary -- v1beta1ResourceRuleVerbs :: [Text] instance Arbitrary V1beta1Role where arbitrary = V1beta1Role <$> arbitrary -- v1beta1RoleApiVersion :: Maybe Text <*> arbitrary -- v1beta1RoleKind :: Maybe Text <*> arbitrary -- v1beta1RoleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1RoleRules :: [V1beta1PolicyRule] instance Arbitrary V1beta1RoleBinding where arbitrary = V1beta1RoleBinding <$> arbitrary -- v1beta1RoleBindingApiVersion :: Maybe Text <*> arbitrary -- v1beta1RoleBindingKind :: Maybe Text <*> arbitrary -- v1beta1RoleBindingMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1RoleBindingRoleRef :: V1beta1RoleRef <*> arbitrary -- v1beta1RoleBindingSubjects :: [V1beta1Subject] instance Arbitrary V1beta1RoleBindingList where arbitrary = V1beta1RoleBindingList <$> arbitrary -- v1beta1RoleBindingListApiVersion :: Maybe Text <*> arbitrary -- v1beta1RoleBindingListItems :: [V1beta1RoleBinding] <*> arbitrary -- v1beta1RoleBindingListKind :: Maybe Text <*> arbitrary -- v1beta1RoleBindingListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1RoleList where arbitrary = V1beta1RoleList <$> arbitrary -- v1beta1RoleListApiVersion :: Maybe Text <*> arbitrary -- v1beta1RoleListItems :: [V1beta1Role] <*> arbitrary -- v1beta1RoleListKind :: Maybe Text <*> arbitrary -- v1beta1RoleListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1RoleRef where arbitrary = V1beta1RoleRef <$> arbitrary -- v1beta1RoleRefApiGroup :: Text <*> arbitrary -- v1beta1RoleRefKind :: Text <*> arbitrary -- v1beta1RoleRefName :: Text instance Arbitrary V1beta1RollingUpdateDaemonSet where arbitrary = V1beta1RollingUpdateDaemonSet <$> arbitrary -- v1beta1RollingUpdateDaemonSetMaxUnavailable :: Maybe A.Value instance Arbitrary V1beta1RollingUpdateStatefulSetStrategy where arbitrary = V1beta1RollingUpdateStatefulSetStrategy <$> arbitrary -- v1beta1RollingUpdateStatefulSetStrategyPartition :: Maybe Int instance Arbitrary V1beta1RuleWithOperations where arbitrary = V1beta1RuleWithOperations <$> arbitrary -- v1beta1RuleWithOperationsApiGroups :: Maybe [Text] <*> arbitrary -- v1beta1RuleWithOperationsApiVersions :: Maybe [Text] <*> arbitrary -- v1beta1RuleWithOperationsOperations :: Maybe [Text] <*> arbitrary -- v1beta1RuleWithOperationsResources :: Maybe [Text] instance Arbitrary V1beta1RunAsUserStrategyOptions where arbitrary = V1beta1RunAsUserStrategyOptions <$> arbitrary -- v1beta1RunAsUserStrategyOptionsRanges :: Maybe [V1beta1IDRange] <*> arbitrary -- v1beta1RunAsUserStrategyOptionsRule :: Text instance Arbitrary V1beta1SELinuxStrategyOptions where arbitrary = V1beta1SELinuxStrategyOptions <$> arbitrary -- v1beta1SELinuxStrategyOptionsRule :: Text <*> arbitrary -- v1beta1SELinuxStrategyOptionsSeLinuxOptions :: Maybe V1SELinuxOptions instance Arbitrary V1beta1SelfSubjectAccessReview where arbitrary = V1beta1SelfSubjectAccessReview <$> arbitrary -- v1beta1SelfSubjectAccessReviewApiVersion :: Maybe Text <*> arbitrary -- v1beta1SelfSubjectAccessReviewKind :: Maybe Text <*> arbitrary -- v1beta1SelfSubjectAccessReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1SelfSubjectAccessReviewSpec :: V1beta1SelfSubjectAccessReviewSpec <*> arbitrary -- v1beta1SelfSubjectAccessReviewStatus :: Maybe V1beta1SubjectAccessReviewStatus instance Arbitrary V1beta1SelfSubjectAccessReviewSpec where arbitrary = V1beta1SelfSubjectAccessReviewSpec <$> arbitrary -- v1beta1SelfSubjectAccessReviewSpecNonResourceAttributes :: Maybe V1beta1NonResourceAttributes <*> arbitrary -- v1beta1SelfSubjectAccessReviewSpecResourceAttributes :: Maybe V1beta1ResourceAttributes instance Arbitrary V1beta1SelfSubjectRulesReview where arbitrary = V1beta1SelfSubjectRulesReview <$> arbitrary -- v1beta1SelfSubjectRulesReviewApiVersion :: Maybe Text <*> arbitrary -- v1beta1SelfSubjectRulesReviewKind :: Maybe Text <*> arbitrary -- v1beta1SelfSubjectRulesReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1SelfSubjectRulesReviewSpec :: V1beta1SelfSubjectRulesReviewSpec <*> arbitrary -- v1beta1SelfSubjectRulesReviewStatus :: Maybe V1beta1SubjectRulesReviewStatus instance Arbitrary V1beta1SelfSubjectRulesReviewSpec where arbitrary = V1beta1SelfSubjectRulesReviewSpec <$> arbitrary -- v1beta1SelfSubjectRulesReviewSpecNamespace :: Maybe Text instance Arbitrary V1beta1StatefulSet where arbitrary = V1beta1StatefulSet <$> arbitrary -- v1beta1StatefulSetApiVersion :: Maybe Text <*> arbitrary -- v1beta1StatefulSetKind :: Maybe Text <*> arbitrary -- v1beta1StatefulSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1StatefulSetSpec :: Maybe V1beta1StatefulSetSpec <*> arbitrary -- v1beta1StatefulSetStatus :: Maybe V1beta1StatefulSetStatus instance Arbitrary V1beta1StatefulSetCondition where arbitrary = V1beta1StatefulSetCondition <$> arbitrary -- v1beta1StatefulSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta1StatefulSetConditionMessage :: Maybe Text <*> arbitrary -- v1beta1StatefulSetConditionReason :: Maybe Text <*> arbitrary -- v1beta1StatefulSetConditionStatus :: Text <*> arbitrary -- v1beta1StatefulSetConditionType :: Text instance Arbitrary V1beta1StatefulSetList where arbitrary = V1beta1StatefulSetList <$> arbitrary -- v1beta1StatefulSetListApiVersion :: Maybe Text <*> arbitrary -- v1beta1StatefulSetListItems :: [V1beta1StatefulSet] <*> arbitrary -- v1beta1StatefulSetListKind :: Maybe Text <*> arbitrary -- v1beta1StatefulSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1StatefulSetSpec where arbitrary = V1beta1StatefulSetSpec <$> arbitrary -- v1beta1StatefulSetSpecPodManagementPolicy :: Maybe Text <*> arbitrary -- v1beta1StatefulSetSpecReplicas :: Maybe Int <*> arbitrary -- v1beta1StatefulSetSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- v1beta1StatefulSetSpecSelector :: Maybe V1LabelSelector <*> arbitrary -- v1beta1StatefulSetSpecServiceName :: Text <*> arbitrary -- v1beta1StatefulSetSpecTemplate :: V1PodTemplateSpec <*> arbitrary -- v1beta1StatefulSetSpecUpdateStrategy :: Maybe V1beta1StatefulSetUpdateStrategy <*> arbitrary -- v1beta1StatefulSetSpecVolumeClaimTemplates :: Maybe [V1PersistentVolumeClaim] instance Arbitrary V1beta1StatefulSetStatus where arbitrary = V1beta1StatefulSetStatus <$> arbitrary -- v1beta1StatefulSetStatusCollisionCount :: Maybe Int <*> arbitrary -- v1beta1StatefulSetStatusConditions :: Maybe [V1beta1StatefulSetCondition] <*> arbitrary -- v1beta1StatefulSetStatusCurrentReplicas :: Maybe Int <*> arbitrary -- v1beta1StatefulSetStatusCurrentRevision :: Maybe Text <*> arbitrary -- v1beta1StatefulSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1beta1StatefulSetStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1beta1StatefulSetStatusReplicas :: Int <*> arbitrary -- v1beta1StatefulSetStatusUpdateRevision :: Maybe Text <*> arbitrary -- v1beta1StatefulSetStatusUpdatedReplicas :: Maybe Int instance Arbitrary V1beta1StatefulSetUpdateStrategy where arbitrary = V1beta1StatefulSetUpdateStrategy <$> arbitrary -- v1beta1StatefulSetUpdateStrategyRollingUpdate :: Maybe V1beta1RollingUpdateStatefulSetStrategy <*> arbitrary -- v1beta1StatefulSetUpdateStrategyType :: Maybe Text instance Arbitrary V1beta1StorageClass where arbitrary = V1beta1StorageClass <$> arbitrary -- v1beta1StorageClassAllowVolumeExpansion :: Maybe Bool <*> arbitrary -- v1beta1StorageClassApiVersion :: Maybe Text <*> arbitrary -- v1beta1StorageClassKind :: Maybe Text <*> arbitrary -- v1beta1StorageClassMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1StorageClassMountOptions :: Maybe [Text] <*> arbitrary -- v1beta1StorageClassParameters :: Maybe (Map.Map String Text) <*> arbitrary -- v1beta1StorageClassProvisioner :: Text <*> arbitrary -- v1beta1StorageClassReclaimPolicy :: Maybe Text <*> arbitrary -- v1beta1StorageClassVolumeBindingMode :: Maybe Text instance Arbitrary V1beta1StorageClassList where arbitrary = V1beta1StorageClassList <$> arbitrary -- v1beta1StorageClassListApiVersion :: Maybe Text <*> arbitrary -- v1beta1StorageClassListItems :: [V1beta1StorageClass] <*> arbitrary -- v1beta1StorageClassListKind :: Maybe Text <*> arbitrary -- v1beta1StorageClassListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1Subject where arbitrary = V1beta1Subject <$> arbitrary -- v1beta1SubjectApiGroup :: Maybe Text <*> arbitrary -- v1beta1SubjectKind :: Text <*> arbitrary -- v1beta1SubjectName :: Text <*> arbitrary -- v1beta1SubjectNamespace :: Maybe Text instance Arbitrary V1beta1SubjectAccessReview where arbitrary = V1beta1SubjectAccessReview <$> arbitrary -- v1beta1SubjectAccessReviewApiVersion :: Maybe Text <*> arbitrary -- v1beta1SubjectAccessReviewKind :: Maybe Text <*> arbitrary -- v1beta1SubjectAccessReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1SubjectAccessReviewSpec :: V1beta1SubjectAccessReviewSpec <*> arbitrary -- v1beta1SubjectAccessReviewStatus :: Maybe V1beta1SubjectAccessReviewStatus instance Arbitrary V1beta1SubjectAccessReviewSpec where arbitrary = V1beta1SubjectAccessReviewSpec <$> arbitrary -- v1beta1SubjectAccessReviewSpecExtra :: Maybe (Map.Map String [Text]) <*> arbitrary -- v1beta1SubjectAccessReviewSpecGroup :: Maybe [Text] <*> arbitrary -- v1beta1SubjectAccessReviewSpecNonResourceAttributes :: Maybe V1beta1NonResourceAttributes <*> arbitrary -- v1beta1SubjectAccessReviewSpecResourceAttributes :: Maybe V1beta1ResourceAttributes <*> arbitrary -- v1beta1SubjectAccessReviewSpecUid :: Maybe Text <*> arbitrary -- v1beta1SubjectAccessReviewSpecUser :: Maybe Text instance Arbitrary V1beta1SubjectAccessReviewStatus where arbitrary = V1beta1SubjectAccessReviewStatus <$> arbitrary -- v1beta1SubjectAccessReviewStatusAllowed :: Bool <*> arbitrary -- v1beta1SubjectAccessReviewStatusDenied :: Maybe Bool <*> arbitrary -- v1beta1SubjectAccessReviewStatusEvaluationError :: Maybe Text <*> arbitrary -- v1beta1SubjectAccessReviewStatusReason :: Maybe Text instance Arbitrary V1beta1SubjectRulesReviewStatus where arbitrary = V1beta1SubjectRulesReviewStatus <$> arbitrary -- v1beta1SubjectRulesReviewStatusEvaluationError :: Maybe Text <*> arbitrary -- v1beta1SubjectRulesReviewStatusIncomplete :: Bool <*> arbitrary -- v1beta1SubjectRulesReviewStatusNonResourceRules :: [V1beta1NonResourceRule] <*> arbitrary -- v1beta1SubjectRulesReviewStatusResourceRules :: [V1beta1ResourceRule] instance Arbitrary V1beta1SupplementalGroupsStrategyOptions where arbitrary = V1beta1SupplementalGroupsStrategyOptions <$> arbitrary -- v1beta1SupplementalGroupsStrategyOptionsRanges :: Maybe [V1beta1IDRange] <*> arbitrary -- v1beta1SupplementalGroupsStrategyOptionsRule :: Maybe Text instance Arbitrary V1beta1TokenReview where arbitrary = V1beta1TokenReview <$> arbitrary -- v1beta1TokenReviewApiVersion :: Maybe Text <*> arbitrary -- v1beta1TokenReviewKind :: Maybe Text <*> arbitrary -- v1beta1TokenReviewMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1TokenReviewSpec :: V1beta1TokenReviewSpec <*> arbitrary -- v1beta1TokenReviewStatus :: Maybe V1beta1TokenReviewStatus instance Arbitrary V1beta1TokenReviewSpec where arbitrary = V1beta1TokenReviewSpec <$> arbitrary -- v1beta1TokenReviewSpecToken :: Maybe Text instance Arbitrary V1beta1TokenReviewStatus where arbitrary = V1beta1TokenReviewStatus <$> arbitrary -- v1beta1TokenReviewStatusAuthenticated :: Maybe Bool <*> arbitrary -- v1beta1TokenReviewStatusError :: Maybe Text <*> arbitrary -- v1beta1TokenReviewStatusUser :: Maybe V1beta1UserInfo instance Arbitrary V1beta1UserInfo where arbitrary = V1beta1UserInfo <$> arbitrary -- v1beta1UserInfoExtra :: Maybe (Map.Map String [Text]) <*> arbitrary -- v1beta1UserInfoGroups :: Maybe [Text] <*> arbitrary -- v1beta1UserInfoUid :: Maybe Text <*> arbitrary -- v1beta1UserInfoUsername :: Maybe Text instance Arbitrary V1beta1ValidatingWebhookConfiguration where arbitrary = V1beta1ValidatingWebhookConfiguration <$> arbitrary -- v1beta1ValidatingWebhookConfigurationApiVersion :: Maybe Text <*> arbitrary -- v1beta1ValidatingWebhookConfigurationKind :: Maybe Text <*> arbitrary -- v1beta1ValidatingWebhookConfigurationMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta1ValidatingWebhookConfigurationWebhooks :: Maybe [V1beta1Webhook] instance Arbitrary V1beta1ValidatingWebhookConfigurationList where arbitrary = V1beta1ValidatingWebhookConfigurationList <$> arbitrary -- v1beta1ValidatingWebhookConfigurationListApiVersion :: Maybe Text <*> arbitrary -- v1beta1ValidatingWebhookConfigurationListItems :: [V1beta1ValidatingWebhookConfiguration] <*> arbitrary -- v1beta1ValidatingWebhookConfigurationListKind :: Maybe Text <*> arbitrary -- v1beta1ValidatingWebhookConfigurationListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta1Webhook where arbitrary = V1beta1Webhook <$> arbitrary -- v1beta1WebhookClientConfig :: V1beta1WebhookClientConfig <*> arbitrary -- v1beta1WebhookFailurePolicy :: Maybe Text <*> arbitrary -- v1beta1WebhookName :: Text <*> arbitrary -- v1beta1WebhookNamespaceSelector :: Maybe V1LabelSelector <*> arbitrary -- v1beta1WebhookRules :: Maybe [V1beta1RuleWithOperations] instance Arbitrary V1beta1WebhookClientConfig where arbitrary = V1beta1WebhookClientConfig <$> arbitrary -- v1beta1WebhookClientConfigCaBundle :: ByteArray <*> arbitrary -- v1beta1WebhookClientConfigService :: Maybe AdmissionregistrationV1beta1ServiceReference <*> arbitrary -- v1beta1WebhookClientConfigUrl :: Maybe Text instance Arbitrary V1beta2ControllerRevision where arbitrary = V1beta2ControllerRevision <$> arbitrary -- v1beta2ControllerRevisionApiVersion :: Maybe Text <*> arbitrary -- v1beta2ControllerRevisionData :: Maybe RuntimeRawExtension <*> arbitrary -- v1beta2ControllerRevisionKind :: Maybe Text <*> arbitrary -- v1beta2ControllerRevisionMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta2ControllerRevisionRevision :: Integer instance Arbitrary V1beta2ControllerRevisionList where arbitrary = V1beta2ControllerRevisionList <$> arbitrary -- v1beta2ControllerRevisionListApiVersion :: Maybe Text <*> arbitrary -- v1beta2ControllerRevisionListItems :: [V1beta2ControllerRevision] <*> arbitrary -- v1beta2ControllerRevisionListKind :: Maybe Text <*> arbitrary -- v1beta2ControllerRevisionListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta2DaemonSet where arbitrary = V1beta2DaemonSet <$> arbitrary -- v1beta2DaemonSetApiVersion :: Maybe Text <*> arbitrary -- v1beta2DaemonSetKind :: Maybe Text <*> arbitrary -- v1beta2DaemonSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta2DaemonSetSpec :: Maybe V1beta2DaemonSetSpec <*> arbitrary -- v1beta2DaemonSetStatus :: Maybe V1beta2DaemonSetStatus instance Arbitrary V1beta2DaemonSetCondition where arbitrary = V1beta2DaemonSetCondition <$> arbitrary -- v1beta2DaemonSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta2DaemonSetConditionMessage :: Maybe Text <*> arbitrary -- v1beta2DaemonSetConditionReason :: Maybe Text <*> arbitrary -- v1beta2DaemonSetConditionStatus :: Text <*> arbitrary -- v1beta2DaemonSetConditionType :: Text instance Arbitrary V1beta2DaemonSetList where arbitrary = V1beta2DaemonSetList <$> arbitrary -- v1beta2DaemonSetListApiVersion :: Maybe Text <*> arbitrary -- v1beta2DaemonSetListItems :: [V1beta2DaemonSet] <*> arbitrary -- v1beta2DaemonSetListKind :: Maybe Text <*> arbitrary -- v1beta2DaemonSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta2DaemonSetSpec where arbitrary = V1beta2DaemonSetSpec <$> arbitrary -- v1beta2DaemonSetSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1beta2DaemonSetSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- v1beta2DaemonSetSpecSelector :: V1LabelSelector <*> arbitrary -- v1beta2DaemonSetSpecTemplate :: V1PodTemplateSpec <*> arbitrary -- v1beta2DaemonSetSpecUpdateStrategy :: Maybe V1beta2DaemonSetUpdateStrategy instance Arbitrary V1beta2DaemonSetStatus where arbitrary = V1beta2DaemonSetStatus <$> arbitrary -- v1beta2DaemonSetStatusCollisionCount :: Maybe Int <*> arbitrary -- v1beta2DaemonSetStatusConditions :: Maybe [V1beta2DaemonSetCondition] <*> arbitrary -- v1beta2DaemonSetStatusCurrentNumberScheduled :: Int <*> arbitrary -- v1beta2DaemonSetStatusDesiredNumberScheduled :: Int <*> arbitrary -- v1beta2DaemonSetStatusNumberAvailable :: Maybe Int <*> arbitrary -- v1beta2DaemonSetStatusNumberMisscheduled :: Int <*> arbitrary -- v1beta2DaemonSetStatusNumberReady :: Int <*> arbitrary -- v1beta2DaemonSetStatusNumberUnavailable :: Maybe Int <*> arbitrary -- v1beta2DaemonSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1beta2DaemonSetStatusUpdatedNumberScheduled :: Maybe Int instance Arbitrary V1beta2DaemonSetUpdateStrategy where arbitrary = V1beta2DaemonSetUpdateStrategy <$> arbitrary -- v1beta2DaemonSetUpdateStrategyRollingUpdate :: Maybe V1beta2RollingUpdateDaemonSet <*> arbitrary -- v1beta2DaemonSetUpdateStrategyType :: Maybe Text instance Arbitrary V1beta2Deployment where arbitrary = V1beta2Deployment <$> arbitrary -- v1beta2DeploymentApiVersion :: Maybe Text <*> arbitrary -- v1beta2DeploymentKind :: Maybe Text <*> arbitrary -- v1beta2DeploymentMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta2DeploymentSpec :: Maybe V1beta2DeploymentSpec <*> arbitrary -- v1beta2DeploymentStatus :: Maybe V1beta2DeploymentStatus instance Arbitrary V1beta2DeploymentCondition where arbitrary = V1beta2DeploymentCondition <$> arbitrary -- v1beta2DeploymentConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta2DeploymentConditionLastUpdateTime :: Maybe DateTime <*> arbitrary -- v1beta2DeploymentConditionMessage :: Maybe Text <*> arbitrary -- v1beta2DeploymentConditionReason :: Maybe Text <*> arbitrary -- v1beta2DeploymentConditionStatus :: Text <*> arbitrary -- v1beta2DeploymentConditionType :: Text instance Arbitrary V1beta2DeploymentList where arbitrary = V1beta2DeploymentList <$> arbitrary -- v1beta2DeploymentListApiVersion :: Maybe Text <*> arbitrary -- v1beta2DeploymentListItems :: [V1beta2Deployment] <*> arbitrary -- v1beta2DeploymentListKind :: Maybe Text <*> arbitrary -- v1beta2DeploymentListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta2DeploymentSpec where arbitrary = V1beta2DeploymentSpec <$> arbitrary -- v1beta2DeploymentSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1beta2DeploymentSpecPaused :: Maybe Bool <*> arbitrary -- v1beta2DeploymentSpecProgressDeadlineSeconds :: Maybe Int <*> arbitrary -- v1beta2DeploymentSpecReplicas :: Maybe Int <*> arbitrary -- v1beta2DeploymentSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- v1beta2DeploymentSpecSelector :: V1LabelSelector <*> arbitrary -- v1beta2DeploymentSpecStrategy :: Maybe V1beta2DeploymentStrategy <*> arbitrary -- v1beta2DeploymentSpecTemplate :: V1PodTemplateSpec instance Arbitrary V1beta2DeploymentStatus where arbitrary = V1beta2DeploymentStatus <$> arbitrary -- v1beta2DeploymentStatusAvailableReplicas :: Maybe Int <*> arbitrary -- v1beta2DeploymentStatusCollisionCount :: Maybe Int <*> arbitrary -- v1beta2DeploymentStatusConditions :: Maybe [V1beta2DeploymentCondition] <*> arbitrary -- v1beta2DeploymentStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1beta2DeploymentStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1beta2DeploymentStatusReplicas :: Maybe Int <*> arbitrary -- v1beta2DeploymentStatusUnavailableReplicas :: Maybe Int <*> arbitrary -- v1beta2DeploymentStatusUpdatedReplicas :: Maybe Int instance Arbitrary V1beta2DeploymentStrategy where arbitrary = V1beta2DeploymentStrategy <$> arbitrary -- v1beta2DeploymentStrategyRollingUpdate :: Maybe V1beta2RollingUpdateDeployment <*> arbitrary -- v1beta2DeploymentStrategyType :: Maybe Text instance Arbitrary V1beta2ReplicaSet where arbitrary = V1beta2ReplicaSet <$> arbitrary -- v1beta2ReplicaSetApiVersion :: Maybe Text <*> arbitrary -- v1beta2ReplicaSetKind :: Maybe Text <*> arbitrary -- v1beta2ReplicaSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta2ReplicaSetSpec :: Maybe V1beta2ReplicaSetSpec <*> arbitrary -- v1beta2ReplicaSetStatus :: Maybe V1beta2ReplicaSetStatus instance Arbitrary V1beta2ReplicaSetCondition where arbitrary = V1beta2ReplicaSetCondition <$> arbitrary -- v1beta2ReplicaSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta2ReplicaSetConditionMessage :: Maybe Text <*> arbitrary -- v1beta2ReplicaSetConditionReason :: Maybe Text <*> arbitrary -- v1beta2ReplicaSetConditionStatus :: Text <*> arbitrary -- v1beta2ReplicaSetConditionType :: Text instance Arbitrary V1beta2ReplicaSetList where arbitrary = V1beta2ReplicaSetList <$> arbitrary -- v1beta2ReplicaSetListApiVersion :: Maybe Text <*> arbitrary -- v1beta2ReplicaSetListItems :: [V1beta2ReplicaSet] <*> arbitrary -- v1beta2ReplicaSetListKind :: Maybe Text <*> arbitrary -- v1beta2ReplicaSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta2ReplicaSetSpec where arbitrary = V1beta2ReplicaSetSpec <$> arbitrary -- v1beta2ReplicaSetSpecMinReadySeconds :: Maybe Int <*> arbitrary -- v1beta2ReplicaSetSpecReplicas :: Maybe Int <*> arbitrary -- v1beta2ReplicaSetSpecSelector :: V1LabelSelector <*> arbitrary -- v1beta2ReplicaSetSpecTemplate :: Maybe V1PodTemplateSpec instance Arbitrary V1beta2ReplicaSetStatus where arbitrary = V1beta2ReplicaSetStatus <$> arbitrary -- v1beta2ReplicaSetStatusAvailableReplicas :: Maybe Int <*> arbitrary -- v1beta2ReplicaSetStatusConditions :: Maybe [V1beta2ReplicaSetCondition] <*> arbitrary -- v1beta2ReplicaSetStatusFullyLabeledReplicas :: Maybe Int <*> arbitrary -- v1beta2ReplicaSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1beta2ReplicaSetStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1beta2ReplicaSetStatusReplicas :: Int instance Arbitrary V1beta2RollingUpdateDaemonSet where arbitrary = V1beta2RollingUpdateDaemonSet <$> arbitrary -- v1beta2RollingUpdateDaemonSetMaxUnavailable :: Maybe A.Value instance Arbitrary V1beta2RollingUpdateDeployment where arbitrary = V1beta2RollingUpdateDeployment <$> arbitrary -- v1beta2RollingUpdateDeploymentMaxSurge :: Maybe A.Value <*> arbitrary -- v1beta2RollingUpdateDeploymentMaxUnavailable :: Maybe A.Value instance Arbitrary V1beta2RollingUpdateStatefulSetStrategy where arbitrary = V1beta2RollingUpdateStatefulSetStrategy <$> arbitrary -- v1beta2RollingUpdateStatefulSetStrategyPartition :: Maybe Int instance Arbitrary V1beta2Scale where arbitrary = V1beta2Scale <$> arbitrary -- v1beta2ScaleApiVersion :: Maybe Text <*> arbitrary -- v1beta2ScaleKind :: Maybe Text <*> arbitrary -- v1beta2ScaleMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta2ScaleSpec :: Maybe V1beta2ScaleSpec <*> arbitrary -- v1beta2ScaleStatus :: Maybe V1beta2ScaleStatus instance Arbitrary V1beta2ScaleSpec where arbitrary = V1beta2ScaleSpec <$> arbitrary -- v1beta2ScaleSpecReplicas :: Maybe Int instance Arbitrary V1beta2ScaleStatus where arbitrary = V1beta2ScaleStatus <$> arbitrary -- v1beta2ScaleStatusReplicas :: Int <*> arbitrary -- v1beta2ScaleStatusSelector :: Maybe (Map.Map String Text) <*> arbitrary -- v1beta2ScaleStatusTargetSelector :: Maybe Text instance Arbitrary V1beta2StatefulSet where arbitrary = V1beta2StatefulSet <$> arbitrary -- v1beta2StatefulSetApiVersion :: Maybe Text <*> arbitrary -- v1beta2StatefulSetKind :: Maybe Text <*> arbitrary -- v1beta2StatefulSetMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v1beta2StatefulSetSpec :: Maybe V1beta2StatefulSetSpec <*> arbitrary -- v1beta2StatefulSetStatus :: Maybe V1beta2StatefulSetStatus instance Arbitrary V1beta2StatefulSetCondition where arbitrary = V1beta2StatefulSetCondition <$> arbitrary -- v1beta2StatefulSetConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v1beta2StatefulSetConditionMessage :: Maybe Text <*> arbitrary -- v1beta2StatefulSetConditionReason :: Maybe Text <*> arbitrary -- v1beta2StatefulSetConditionStatus :: Text <*> arbitrary -- v1beta2StatefulSetConditionType :: Text instance Arbitrary V1beta2StatefulSetList where arbitrary = V1beta2StatefulSetList <$> arbitrary -- v1beta2StatefulSetListApiVersion :: Maybe Text <*> arbitrary -- v1beta2StatefulSetListItems :: [V1beta2StatefulSet] <*> arbitrary -- v1beta2StatefulSetListKind :: Maybe Text <*> arbitrary -- v1beta2StatefulSetListMetadata :: Maybe V1ListMeta instance Arbitrary V1beta2StatefulSetSpec where arbitrary = V1beta2StatefulSetSpec <$> arbitrary -- v1beta2StatefulSetSpecPodManagementPolicy :: Maybe Text <*> arbitrary -- v1beta2StatefulSetSpecReplicas :: Maybe Int <*> arbitrary -- v1beta2StatefulSetSpecRevisionHistoryLimit :: Maybe Int <*> arbitrary -- v1beta2StatefulSetSpecSelector :: V1LabelSelector <*> arbitrary -- v1beta2StatefulSetSpecServiceName :: Text <*> arbitrary -- v1beta2StatefulSetSpecTemplate :: V1PodTemplateSpec <*> arbitrary -- v1beta2StatefulSetSpecUpdateStrategy :: Maybe V1beta2StatefulSetUpdateStrategy <*> arbitrary -- v1beta2StatefulSetSpecVolumeClaimTemplates :: Maybe [V1PersistentVolumeClaim] instance Arbitrary V1beta2StatefulSetStatus where arbitrary = V1beta2StatefulSetStatus <$> arbitrary -- v1beta2StatefulSetStatusCollisionCount :: Maybe Int <*> arbitrary -- v1beta2StatefulSetStatusConditions :: Maybe [V1beta2StatefulSetCondition] <*> arbitrary -- v1beta2StatefulSetStatusCurrentReplicas :: Maybe Int <*> arbitrary -- v1beta2StatefulSetStatusCurrentRevision :: Maybe Text <*> arbitrary -- v1beta2StatefulSetStatusObservedGeneration :: Maybe Integer <*> arbitrary -- v1beta2StatefulSetStatusReadyReplicas :: Maybe Int <*> arbitrary -- v1beta2StatefulSetStatusReplicas :: Int <*> arbitrary -- v1beta2StatefulSetStatusUpdateRevision :: Maybe Text <*> arbitrary -- v1beta2StatefulSetStatusUpdatedReplicas :: Maybe Int instance Arbitrary V1beta2StatefulSetUpdateStrategy where arbitrary = V1beta2StatefulSetUpdateStrategy <$> arbitrary -- v1beta2StatefulSetUpdateStrategyRollingUpdate :: Maybe V1beta2RollingUpdateStatefulSetStrategy <*> arbitrary -- v1beta2StatefulSetUpdateStrategyType :: Maybe Text instance Arbitrary V2alpha1CronJob where arbitrary = V2alpha1CronJob <$> arbitrary -- v2alpha1CronJobApiVersion :: Maybe Text <*> arbitrary -- v2alpha1CronJobKind :: Maybe Text <*> arbitrary -- v2alpha1CronJobMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v2alpha1CronJobSpec :: Maybe V2alpha1CronJobSpec <*> arbitrary -- v2alpha1CronJobStatus :: Maybe V2alpha1CronJobStatus instance Arbitrary V2alpha1CronJobList where arbitrary = V2alpha1CronJobList <$> arbitrary -- v2alpha1CronJobListApiVersion :: Maybe Text <*> arbitrary -- v2alpha1CronJobListItems :: [V2alpha1CronJob] <*> arbitrary -- v2alpha1CronJobListKind :: Maybe Text <*> arbitrary -- v2alpha1CronJobListMetadata :: Maybe V1ListMeta instance Arbitrary V2alpha1CronJobSpec where arbitrary = V2alpha1CronJobSpec <$> arbitrary -- v2alpha1CronJobSpecConcurrencyPolicy :: Maybe Text <*> arbitrary -- v2alpha1CronJobSpecFailedJobsHistoryLimit :: Maybe Int <*> arbitrary -- v2alpha1CronJobSpecJobTemplate :: V2alpha1JobTemplateSpec <*> arbitrary -- v2alpha1CronJobSpecSchedule :: Text <*> arbitrary -- v2alpha1CronJobSpecStartingDeadlineSeconds :: Maybe Integer <*> arbitrary -- v2alpha1CronJobSpecSuccessfulJobsHistoryLimit :: Maybe Int <*> arbitrary -- v2alpha1CronJobSpecSuspend :: Maybe Bool instance Arbitrary V2alpha1CronJobStatus where arbitrary = V2alpha1CronJobStatus <$> arbitrary -- v2alpha1CronJobStatusActive :: Maybe [V1ObjectReference] <*> arbitrary -- v2alpha1CronJobStatusLastScheduleTime :: Maybe DateTime instance Arbitrary V2alpha1JobTemplateSpec where arbitrary = V2alpha1JobTemplateSpec <$> arbitrary -- v2alpha1JobTemplateSpecMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v2alpha1JobTemplateSpecSpec :: Maybe V1JobSpec instance Arbitrary V2beta1CrossVersionObjectReference where arbitrary = V2beta1CrossVersionObjectReference <$> arbitrary -- v2beta1CrossVersionObjectReferenceApiVersion :: Maybe Text <*> arbitrary -- v2beta1CrossVersionObjectReferenceKind :: Text <*> arbitrary -- v2beta1CrossVersionObjectReferenceName :: Text instance Arbitrary V2beta1HorizontalPodAutoscaler where arbitrary = V2beta1HorizontalPodAutoscaler <$> arbitrary -- v2beta1HorizontalPodAutoscalerApiVersion :: Maybe Text <*> arbitrary -- v2beta1HorizontalPodAutoscalerKind :: Maybe Text <*> arbitrary -- v2beta1HorizontalPodAutoscalerMetadata :: Maybe V1ObjectMeta <*> arbitrary -- v2beta1HorizontalPodAutoscalerSpec :: Maybe V2beta1HorizontalPodAutoscalerSpec <*> arbitrary -- v2beta1HorizontalPodAutoscalerStatus :: Maybe V2beta1HorizontalPodAutoscalerStatus instance Arbitrary V2beta1HorizontalPodAutoscalerCondition where arbitrary = V2beta1HorizontalPodAutoscalerCondition <$> arbitrary -- v2beta1HorizontalPodAutoscalerConditionLastTransitionTime :: Maybe DateTime <*> arbitrary -- v2beta1HorizontalPodAutoscalerConditionMessage :: Maybe Text <*> arbitrary -- v2beta1HorizontalPodAutoscalerConditionReason :: Maybe Text <*> arbitrary -- v2beta1HorizontalPodAutoscalerConditionStatus :: Text <*> arbitrary -- v2beta1HorizontalPodAutoscalerConditionType :: Text instance Arbitrary V2beta1HorizontalPodAutoscalerList where arbitrary = V2beta1HorizontalPodAutoscalerList <$> arbitrary -- v2beta1HorizontalPodAutoscalerListApiVersion :: Maybe Text <*> arbitrary -- v2beta1HorizontalPodAutoscalerListItems :: [V2beta1HorizontalPodAutoscaler] <*> arbitrary -- v2beta1HorizontalPodAutoscalerListKind :: Maybe Text <*> arbitrary -- v2beta1HorizontalPodAutoscalerListMetadata :: Maybe V1ListMeta instance Arbitrary V2beta1HorizontalPodAutoscalerSpec where arbitrary = V2beta1HorizontalPodAutoscalerSpec <$> arbitrary -- v2beta1HorizontalPodAutoscalerSpecMaxReplicas :: Int <*> arbitrary -- v2beta1HorizontalPodAutoscalerSpecMetrics :: Maybe [V2beta1MetricSpec] <*> arbitrary -- v2beta1HorizontalPodAutoscalerSpecMinReplicas :: Maybe Int <*> arbitrary -- v2beta1HorizontalPodAutoscalerSpecScaleTargetRef :: V2beta1CrossVersionObjectReference instance Arbitrary V2beta1HorizontalPodAutoscalerStatus where arbitrary = V2beta1HorizontalPodAutoscalerStatus <$> arbitrary -- v2beta1HorizontalPodAutoscalerStatusConditions :: [V2beta1HorizontalPodAutoscalerCondition] <*> arbitrary -- v2beta1HorizontalPodAutoscalerStatusCurrentMetrics :: [V2beta1MetricStatus] <*> arbitrary -- v2beta1HorizontalPodAutoscalerStatusCurrentReplicas :: Int <*> arbitrary -- v2beta1HorizontalPodAutoscalerStatusDesiredReplicas :: Int <*> arbitrary -- v2beta1HorizontalPodAutoscalerStatusLastScaleTime :: Maybe DateTime <*> arbitrary -- v2beta1HorizontalPodAutoscalerStatusObservedGeneration :: Maybe Integer instance Arbitrary V2beta1MetricSpec where arbitrary = V2beta1MetricSpec <$> arbitrary -- v2beta1MetricSpecObject :: Maybe V2beta1ObjectMetricSource <*> arbitrary -- v2beta1MetricSpecPods :: Maybe V2beta1PodsMetricSource <*> arbitrary -- v2beta1MetricSpecResource :: Maybe V2beta1ResourceMetricSource <*> arbitrary -- v2beta1MetricSpecType :: Text instance Arbitrary V2beta1MetricStatus where arbitrary = V2beta1MetricStatus <$> arbitrary -- v2beta1MetricStatusObject :: Maybe V2beta1ObjectMetricStatus <*> arbitrary -- v2beta1MetricStatusPods :: Maybe V2beta1PodsMetricStatus <*> arbitrary -- v2beta1MetricStatusResource :: Maybe V2beta1ResourceMetricStatus <*> arbitrary -- v2beta1MetricStatusType :: Text instance Arbitrary V2beta1ObjectMetricSource where arbitrary = V2beta1ObjectMetricSource <$> arbitrary -- v2beta1ObjectMetricSourceMetricName :: Text <*> arbitrary -- v2beta1ObjectMetricSourceTarget :: V2beta1CrossVersionObjectReference <*> arbitrary -- v2beta1ObjectMetricSourceTargetValue :: Text instance Arbitrary V2beta1ObjectMetricStatus where arbitrary = V2beta1ObjectMetricStatus <$> arbitrary -- v2beta1ObjectMetricStatusCurrentValue :: Text <*> arbitrary -- v2beta1ObjectMetricStatusMetricName :: Text <*> arbitrary -- v2beta1ObjectMetricStatusTarget :: V2beta1CrossVersionObjectReference instance Arbitrary V2beta1PodsMetricSource where arbitrary = V2beta1PodsMetricSource <$> arbitrary -- v2beta1PodsMetricSourceMetricName :: Text <*> arbitrary -- v2beta1PodsMetricSourceTargetAverageValue :: Text instance Arbitrary V2beta1PodsMetricStatus where arbitrary = V2beta1PodsMetricStatus <$> arbitrary -- v2beta1PodsMetricStatusCurrentAverageValue :: Text <*> arbitrary -- v2beta1PodsMetricStatusMetricName :: Text instance Arbitrary V2beta1ResourceMetricSource where arbitrary = V2beta1ResourceMetricSource <$> arbitrary -- v2beta1ResourceMetricSourceName :: Text <*> arbitrary -- v2beta1ResourceMetricSourceTargetAverageUtilization :: Maybe Int <*> arbitrary -- v2beta1ResourceMetricSourceTargetAverageValue :: Maybe Text instance Arbitrary V2beta1ResourceMetricStatus where arbitrary = V2beta1ResourceMetricStatus <$> arbitrary -- v2beta1ResourceMetricStatusCurrentAverageUtilization :: Maybe Int <*> arbitrary -- v2beta1ResourceMetricStatusCurrentAverageValue :: Text <*> arbitrary -- v2beta1ResourceMetricStatusName :: Text instance Arbitrary VersionInfo where arbitrary = VersionInfo <$> arbitrary -- versionInfoBuildDate :: Text <*> arbitrary -- versionInfoCompiler :: Text <*> arbitrary -- versionInfoGitCommit :: Text <*> arbitrary -- versionInfoGitTreeState :: Text <*> arbitrary -- versionInfoGitVersion :: Text <*> arbitrary -- versionInfoGoVersion :: Text <*> arbitrary -- versionInfoMajor :: Text <*> arbitrary -- versionInfoMinor :: Text <*> arbitrary -- versionInfoPlatform :: Text
denibertovic/haskell
kubernetes/tests/Instances.hs
bsd-3-clause
200,011
0
41
36,662
17,879
10,290
7,589
3,664
2
{-# LANGUAGE OverloadedStrings #-} import Test.Hspec import Control.Monad.Except import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader import qualified Data.ByteString.Char8 as BS import Network.Wreq import Control.Lens.Operators import Data.Maybe import Data.Aeson import Auth import Types import Constant import CREST selectNoSuchCharacterException :: Either GideonException Int -> Bool selectNoSuchCharacterException (Left NoSuchCharacterException) = True selectNoSuchCharacterException _ = False obtainCharacterInfo' :: Gideon CharacterInfo obtainCharacterInfo' = do opts <- asks authOpt r <- liftIO $ getWith opts urlCharacterInfo return . fromJust . decode $ r ^. responseBody main :: IO () main = hspec $ do describe "test Auth functionality" $ do it "re-acquire access token automatically" $ do -- need to had a current user in database r' <- execute obtainCharacterInfo' let Right r = r' r `shouldSatisfy` (not . null . characterName) describe "test CREST.Market api" $ do it "getMarketType" $ do Right opts <- execute $ asks authOpt str <- getMarketType opts "11182" str `shouldSatisfy` (not . null) it "getMarketBuyOrders" $ do Right opts <- execute $ asks authOpt mos <- getMarketBuyOrders opts 10000002 "30834" mos `shouldSatisfy` \mo -> not (null mo) && moTypeID (head mo) == "30834" it "getMarketSellOrders" $ do Right opts <- execute $ asks authOpt mos <- getMarketSellOrders opts 10000002 "30832" mos `shouldSatisfy` \mo -> not (null mo) && moTypeID (head mo) == "30832"
Frefreak/Gideon
test/Spec.hs
bsd-3-clause
1,714
0
20
424
477
235
242
42
1
-- | Test on functions trimming data to given limit. module Test.Pos.Core.LimitsSpec ( spec ) where import Universum import qualified Data.HashMap.Strict as HM import Serokell.Data.Memory.Units (fromBytes) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (arbitrary, choose, counterexample, forAll, property, (===)) import qualified Pos.Binary.Class as Bi import Pos.Core.Limits (stripHashMap) spec :: Spec spec = describe "Limits" $ do describe "stripHashMap" $ do prop "limit more than size doesn't corrupt hashmap" $ genByte 0 $ \limit -> genHmap $ \hm -> stripHashMap (limit + Bi.biSize hm) hm === Just hm prop "stripped map has size <= limit" $ genByte 1 $ \limit -> genHmap $ \hm -> maybe (counterexample "shouldn't be Nothing" $ False) (\s -> property $ Bi.biSize s <= limit) (stripHashMap limit hm) where genHmap f = forAll arbitrary $ \(HM.fromList -> hm :: HashMap Word64 Bool) -> f hm genByte low f = forAll (choose (low, 1000)) $ \(fromBytes -> limit) -> f limit
input-output-hk/pos-haskell-prototype
core/test/Test/Pos/Core/LimitsSpec.hs
mit
1,229
0
21
365
355
195
160
-1
-1
module Main where import System import List import Char import IO nWords :: String -> [String] nWords [] = [] nWords (c:cs) | not (isSpace c) = case span (not . isSpace) cs of (xs,ys) -> ((case c of 'Á' -> 'á' 'É' -> 'é' 'Í' -> 'í' 'Ó' -> 'ó' 'U' -> 'ú'--obs! 'Ü' -> 'ü' 'Ý' -> 'ý' 'Ñ' -> 'ñ' c -> toLower c):xs):nWords ys | isSpace c = nWords cs where alphanumeric c = isAlpha c || elem c "ÁáÉéÍíÓóúÜüÝýÑñ" main = do xs <- getArgs case xs of [file] -> do prErr welcome s <- readFile file let ws = unlines $ map unwords $ sort $ nub $ map nWords $ lines s putStr ws _ -> do prErr welcome pr <- getProgName putStrLn $ "Usage: " ++ pr ++ " <lexicon file>\n" welcome = unlines [ "", "********************************************", "* Functional Morphology Lexicon Cleaner *", "********************************************", "* (c) Markus Forsberg *", "* under GNU General Public License. *", "********************************************", "" ] prErr s = hPutStr stderr (s ++ "\n")
johnjcamilleri/maltese-functional-morphology
tools/Clean.hs
lgpl-3.0
1,259
36
17
455
381
200
181
44
9
-- | Haskell's "instance of class" relation is mapped to "extends" in the Kythe -- schema. The choice is somewhat arbitrary, but enables nice interop with -- Kythe-based tooling. Mapping visually (and a bit superficially): -- -- Haskell class ~ interface -- Haskell instance ~ (singleton-instantiated) implementation -- module TypeClass where {-# ANN module "HLint: ignore Eta reduce" #-} -- - @Foo defines/binding ClassFoo class Foo a where -- TODO(robinpalotai): - FunFoo childof ClassFoo -- - @foo defines/binding FunFoo foo :: a -> String -- For UI convenience, we emit the binding site to the 'instance' keyword, since -- it is easier to click than say spaces in the instance head. -- - @instance defines/binding InstIntFoo -- - @Foo ref ClassFoo -- - InstIntFoo extends ClassFoo instance Foo Int where -- TODO(robinpalotai): - FunIntFoo childof InstIntFoo -- - @foo defines/binding FunIntFoo -- - FunIntFoo overrides FunFoo -- - FunIntFoo overrides/root FunFoo -- - @show childof FunIntFoo foo = show -- - @foo ref FunFoo f x = foo x g :: Int -> String -- TODO(robinpalotai): - @foo ref FunIntFoo, instead of the below, when we know -- the precise instance (here it is coerced by the type signature). -- - @foo ref FunFoo g = foo
robinp/haskell-indexer
kythe-verification/testdata/basic/TypeclassRef.hs
apache-2.0
1,287
0
7
258
85
57
28
9
1
module CmdLine ( Options(..) , getOptions ) where import Options.Applicative data Options = Options { optport :: Int } options :: Parser Options options = Options <$> option auto ( long "port" <> short 'p' <> metavar "PORT" <> value 8000 <> help "Use port PORT for the HTTP server" ) getOptions :: IO Options getOptions = execParser opts where opts = info (helper <*> options) ( fullDesc <> progDesc "Haskus system info" <> header "Haskus System Info" )
hsyl20/ViperVM
haskus-system-tools/src/system-info/CmdLine.hs
bsd-3-clause
536
0
12
161
144
75
69
20
1
{-#LANGUAGE CPP #-} {-#LANGUAGE OverloadedStrings#-} {-| Module : Eta.Utils.JAR Description : Small utility functions for creating Jars from class files. Copyright : (c) Christopher Wells 2016 (c) Rahul Muttineni 2016-2017 License : MIT This module provides utility functions for creating Jar archives from JVM class files. The general process used for creating a Jar archive is to first create an empty Jar in the desired location using `createEmptyJar`. After the Jar has been created, files can be added to it using the `addByteStringToJar` and `addMultiByteStringsToJar` functions. When adding multiple files to a Jar, be sure to use the `addMultiByteStringsToJar` function, as it writes all of the file changes in one action, while mapping over a list of files with `addByteStringToJar` would perform the file write actions all seperately. Here is a quick exampe of how to create a Jar and add a file into it. @ -- Create the empty jar let jarLocation = "build/Hello.jar" createEmptyJar jarLocation -- Add a single file to the jar import Data.ByteString.Internal (packChars) let fileLocation = "hellopackage/Main.class" let fileContents = packChars "Hello, World!" addByteStringToJar fileLocation fileContents jarLocation @ -} module Eta.Utils.JAR ( addMultiByteStringsToJar' , addByteStringToJar , createEmptyJar , getEntriesFromJar , getEntryContentFromJar , mergeClassesAndJars , CompressionMethod , deflate , normal , bzip2 , mkPath ) where #if MIN_VERSION_zip(1,0,0) #define PLAIN_FILEPATHS import System.Directory import Data.List (sortBy) #else import Path.IO (copyFile) import System.Directory hiding (copyFile) import Data.List (sortBy,isPrefixOf) #endif import Codec.Archive.Zip import Control.Monad import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Catch (MonadCatch(..), MonadThrow) import Data.ByteString.Internal (ByteString) import Path import Data.Map.Lazy (keys) import Data.Map.Strict (filterWithKey) import Data.Text (Text) import qualified Data.Text as T import Data.Time.Clock import Data.Time.Clock.POSIX type FileAndContents = (FilePath, ByteString) deflate, normal, bzip2 :: CompressionMethod deflate = Deflate normal = Store bzip2 = BZip2 -- | Creates an empty jar archive at the given relative filepath location. -- The name of the archive and its file ending should be included in the -- filepath. -- -- __Throws__: 'PathParseException' -- -- See 'createArchive' and 'parseRelFile' for more information. -- -- For example, passing in "src\/Main.jar" would create an empty jar archive -- named "Main.jar" in the "src" sub-directory of the current directory. -- -- @ -- createEmptyJar "src/Main.jar" -- @ -- -- __Before__ -- -- @ -- . -- └── src -- @ -- -- __After__ -- -- @ -- . -- └── src -- └── Main.jar -- @ createEmptyJar :: (MonadIO m, MonadCatch m) => FilePath -> m () createEmptyJar location = do #ifdef PLAIN_FILEPATHS let p = location #else p <- makeAbsoluteFilePath location #endif createArchive p (return ()) -- | Adds the given ByteString as a file at the given location within the given -- jar archive. -- -- __Throws__: 'PathParseException', 'EntrySelectorException', -- isAlreadyInUseError, isDoesNotExistError, isPermissionError, 'ParsingFailed' -- -- See 'withArchive', 'mkEntrySelector', and 'parseRelFile' for more information. -- -- For example, running the following would create a file named "Hello.class" -- containing the string "Hello, World!" within the "src" directory in the jar -- archive located at "build\/libs\/HelloWorld.jar". -- -- @ -- let fileLocation = "src\/Hello.class" -- let contents = packChars "Hello, World!" -- let jarLocation = "build\/libs\/HelloWorld.jar" -- addByteStringToJar fileLocation contents jarLocation -- @ -- -- __Before__ -- -- @ -- . -- └── build -- └── libs -- └── HelloWorld.jar -- @ -- -- __After__ -- -- @ -- . -- └── build -- └── libs -- └── HelloWorld.jar -- └── src -- └── Hello.class -- @ addByteStringToJar :: (MonadThrow m, MonadIO m) => FilePath -- ^ Location of the new file within the jar -> CompressionMethod -- ^ Compression Method -> ByteString -- ^ Contents of the new file to add -> FilePath -- ^ Location of the jar to add the new file into -> m () addByteStringToJar fileLocation compress contents jarLocation = zipAction where #ifdef PLAIN_FILEPATHS zipAction = withArchive jarPath zipChange zipChange = entrySel >>= addEntry compress contents entrySel = mkEntrySelector filePath jarPath = jarLocation filePath = fileLocation #else zipAction = jarPath >>= flip withArchive zipChange zipChange = entrySel >>= addEntry compress contents entrySel = filePath >>= mkEntrySelector jarPath = parseRelFile jarLocation filePath = parseRelFile fileLocation #endif -- | Adds the given files into the given jar. Each file is represented by a -- tuple containing the location where the file will be added inside the jar, -- and the contents of the file as a ByteString. -- -- __Throws__: 'PathParseException', 'EntrySelectorException', -- isAlreadyInUseError, isDoesNotExistError, isPermissionError, 'ParsingFailed' -- -- See 'withArchive', 'mkEntrySelector', and 'parseRelFile' for more information. -- -- For example, running the following would create two files within the jar -- archive located at "build\/libs\/HelloWorld.jar". The first file would be -- named "Hello.class" containing the string "Hello, World!" within the -- "helloworld" directory in the jar archive. The second file would be named -- \"MANIFEST.MF" containing the string "Manifest-Version: 1.0" within the -- \"META-INF" directory in the jar archive. -- -- @ -- let file1Location = "helloworld\/Hello.class" -- let file1Contents = "Hello, World!" -- let file1 = (file1Location, file1Contents) -- -- let file2Location = "META-INF\/MANIFEST.MF" -- let file2Contents = "Manifest-Version: 1.0" -- let file2 = (file2Location, file2Contents) -- -- let files = [file1, file2] -- let jarLocation = "build\/libs\/HelloWorld.jar" -- addMultiByteStringsToJar files jarLocation -- @ -- -- __Before__ -- -- @ -- . -- └── build -- └── libs -- └── HelloWorld.jar -- @ -- -- __After__ -- -- @ -- . -- └── build -- └── libs -- └── HelloWorld.jar -- ├── helloworld -- │ └── Hello.class -- └── META-INF -- └── MANIFEST.MF -- @ -- addMultiByteStringsToJar -- :: (MonadThrow m, MonadIO m) -- => [(FilePath, ByteString)] -- ^ Filepaths and contents of files to add into the jar -- -> FilePath -- ^ Location of the jar to add the new files into -- -> m () -- addMultiByteStringsToJar files jarLocation = do -- jarPath <- parseRelFile jarLocation -- withArchive jarPath $ -- forM_ files $ \(path, contents) -> do -- filePath <- parseRelFile path -- entrySel <- mkEntrySelector filePath -- addEntry Deflate contents entrySel addMultiByteStringsToJar' :: (MonadThrow m, MonadIO m, MonadCatch m) => Bool -- ^ Whether to set the modification time to a fixed value -> FilePath -- ^ Location of the jar to add the new files into -> CompressionMethod -- ^ Compression Method -> [(FilePath, ByteString)] -- ^ Filepaths and contents of files to add into the jar -> m () addMultiByteStringsToJar' setmodtime jarLocation compress files = do #ifdef PLAIN_FILEPATHS let p = jarLocation files' = files #else p <- makeAbsoluteFilePath jarLocation files' <- forM files $ \(fp, bs) -> do path <- mkPath fp return (path, bs) #endif createArchive p (action files') where action files = forM_ files $ \(path, contents) -> do entrySel <- mkEntrySelector path when setmodtime $ setDefaultTimestamp entrySel addEntry compress contents entrySel -- getFilesFromJar -- :: (MonadThrow m, MonadCatch m, MonadIO m) -- => FilePath -- -> m [(Path Rel File, ByteString)] -- getFilesFromJar jarLocation = -- withUnsafePath jarLocation (flip withArchive action) (flip withArchive action) -- where action = do -- entrySelectors <- keys <$> getEntries -- forM entrySelectors $ \es -> do -- contents <- getEntry es -- return (unEntrySelector es, contents) mkPath :: (MonadThrow m, MonadIO m) => FilePath -> m (Path Rel File) mkPath = parseRelFile #ifndef PLAIN_FILEPATHS makeAbsoluteFilePath :: (MonadIO m, MonadThrow m) => FilePath -> m (Path Abs File) makeAbsoluteFilePath fp = do absPath <- liftIO $ makeAbsolute fp let absPath' = removeDots [] absPath parseAbsFile absPath' where removeDots :: String -> String -> String removeDots s "" = s removeDots s "/" = s ++ "/" removeDots scanned path = let (h, t) = break (\c -> c == '\\' || c == '/') path in if null t then scanned ++ h else if ".." `isPrefixOf` tail t then removeDots scanned $ drop 4 t else removeDots (scanned ++ h ++ [head t]) $ tail t #endif getEntriesFromJar :: (MonadThrow m, MonadCatch m, MonadIO m) => FilePath -> m (FilePath, [EntrySelector]) getEntriesFromJar jarLocation = do #ifdef PLAIN_FILEPATHS let p = jarLocation #else p <- makeAbsoluteFilePath jarLocation #endif fmap (jarLocation,) $ withArchive p $ keys <$> getEntries getEntryContentFromJar :: (MonadThrow m, MonadCatch m, MonadIO m) => FilePath -> FilePath -> m (Maybe ByteString) getEntryContentFromJar jarLocation file = do #ifdef PLAIN_FILEPATHS let p = jarLocation s <- mkEntrySelector file #else p <- makeAbsoluteFilePath jarLocation s <- parseRelFile file >>= mkEntrySelector #endif exists <- withArchive p $ doesEntryExist s if exists then do content <- withArchive p $ getEntry s return $ Just content else return Nothing mergeClassesAndJars :: (MonadIO m, MonadCatch m, MonadThrow m) => Bool -- ^ Whether to set the modification time to a fixed value -> FilePath -> CompressionMethod -- ^ Compression Method -> [FileAndContents] -> [(FilePath, [EntrySelector])] -> m () mergeClassesAndJars setmodtime jarLocation compress fileAndContents jarSelectors = do let ((copy', _):selectors) = sortBy (\(_, e1) (_, e2) -> compare (length e2) (length e1)) jarSelectors exists <- liftIO $ doesFileExist jarLocation when (not exists) $ liftIO $ writeFile jarLocation "" #ifdef PLAIN_FILEPATHS let p = jarLocation copy = copy' copyFile x y = liftIO $ System.Directory.copyFile x y selectors' = selectors fileAndContents' = fileAndContents #else p <- makeAbsoluteFilePath jarLocation copy <- makeAbsoluteFilePath copy' selectors' <- forM selectors $ \(fp, bs) -> do path <- makeAbsoluteFilePath fp return (path, bs) fileAndContents' <- forM fileAndContents $ \(fp, bs) -> do path <- mkPath fp return (path, bs) #endif copyFile copy p withArchive p $ do existingEntries <- getEntries let invalidEntries = filterWithKey (\k _ -> invalidEntrySelector k) existingEntries mapM_ deleteEntry (keys invalidEntries) when setmodtime $ mapM_ setDefaultTimestamp (keys existingEntries) forM_ selectors' $ \(absFile, entries) -> do forM_ entries $ \entry -> do when (invalidEntrySelector entry /= True) $ do copyEntry absFile entry entry when setmodtime $ setDefaultTimestamp entry forM_ fileAndContents' $ \(relFile, contents) -> do entrySel <- mkEntrySelector relFile addEntry compress contents entrySel when setmodtime $ setDefaultTimestamp entrySel where invalidEntrySelector :: EntrySelector -> Bool invalidEntrySelector fname = any (endsWith (getEntryName fname)) filterFileExts filterFileExts = [".SF", ".DSA", ".RSA"] endsWith :: Text -> Text -> Bool endsWith txt ext = T.toUpper (T.takeEnd (T.length ext) txt) == (T.toUpper ext) setDefaultTimestamp :: EntrySelector -> ZipArchive () setDefaultTimestamp = setModTime dEFAULT_TIMESTAMP -- Corresponds to January 1, 2010 00:00 UTC. -- Should be a datetime that is greater than all the epoch times on all platforms. dEFAULT_TIMESTAMP :: UTCTime dEFAULT_TIMESTAMP = posixSecondsToUTCTime (fromInteger 1262304000)
rahulmutt/ghcvm
compiler/Eta/Utils/JAR.hs
bsd-3-clause
12,660
0
22
2,719
1,804
1,014
790
-1
-1
----------------------------------------------------------------------------- -- | -- Module : FreeGame.Data.Font -- Copyright : (C) 2013 Fumiaki Kinoshita -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Fumiaki Kinoshita <fumiexcel@gmail.com> -- Stability : provisional -- Portability : non-portable -- -- Rendering characters ---------------------------------------------------------------------------- module FreeGame.Data.Font ( Font , loadFontFromFile , loadFont , fontBoundingBox , metricsAscent , metricsDescent , charToBitmap , RenderedChar(..) ) where #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Control.Monad.IO.Class import Control.Monad import Data.IORef import Data.BoundingBox import qualified Data.Map as M import qualified Data.Vector.Storable as V import Linear import FreeGame.Class import FreeGame.Data.Bitmap import FreeGame.Internal.Finalizer import Graphics.Rendering.FreeType.Internal import qualified Graphics.Rendering.FreeType.Internal.GlyphSlot as GS import qualified Graphics.Rendering.FreeType.Internal.Vector as V import Graphics.Rendering.FreeType.Internal.Bitmap as B import Graphics.Rendering.FreeType.Internal.PrimitiveTypes as PT import Graphics.Rendering.FreeType.Internal.Face as F import Graphics.Rendering.FreeType.Internal.Library as L import Graphics.Rendering.FreeType.Internal.BBox as BB import Foreign.Marshal.Alloc import Foreign.C.Types import Foreign.C.String import Foreign.Storable import Foreign.ForeignPtr import Foreign.Ptr import System.IO.Unsafe import Codec.Picture import Codec.Picture.RGBA8 -- | Font object data Font = Font FT_Face (Double, Double) (Box V2 Double) (IORef (M.Map (Double, Char) RenderedChar)) -- | Create a 'Font' from the given file. loadFontFromFile :: MonadIO m => FilePath -> m Font loadFontFromFile path = liftIO $ alloca $ \p -> do runFreeType $ withCString path $ \str -> ft_New_Face freeType str 0 p f <- peek p b <- peek (bbox f) asc <- peek (ascender f) desc <- peek (descender f) u <- fromIntegral <$> peek (units_per_EM f) let box = fmap (/u) $ Box (V2 (fromIntegral (xMin b)) (fromIntegral (yMin b))) (V2 (fromIntegral (xMax b)) (fromIntegral (yMax b))) Font f (fromIntegral asc/u, fromIntegral desc/u) box <$> newIORef M.empty loadFont :: MonadIO m => FilePath -> m Font loadFont = loadFontFromFile -- | Get the font's metrics. metricsAscent :: Font -> Double metricsAscent (Font _ (a, _) _ _) = a -- | Get the font's metrics. metricsDescent :: Font -> Double metricsDescent (Font _ (_, d) _ _) = d -- | Get the font's boundingbox. fontBoundingBox :: Font -> Box V2 Double fontBoundingBox (Font _ _ b _) = b runFreeType :: IO CInt -> IO () runFreeType m = do r <- m unless (r == 0) $ fail $ "FreeType Error:" Prelude.++ show r freeType :: FT_Library freeType = unsafePerformIO $ alloca $ \p -> do runFreeType $ ft_Init_FreeType p peek p data RenderedChar = RenderedChar { charBitmap :: Bitmap , charOffset :: V2 Double , charAdvance :: Double } -- | The resolution used to render fonts. resolutionDPI :: Int resolutionDPI = 300 charToBitmap :: FromFinalizer m => Font -> Double -> Char -> m RenderedChar charToBitmap (Font face _ _ refCache) pixel ch = fromFinalizer $ do let siz = pixel * 72 / fromIntegral resolutionDPI cache <- liftIO $ readIORef refCache case M.lookup (siz, ch) cache of Just d -> return d Nothing -> do d <- liftIO $ render face siz ch liftIO $ writeIORef refCache $ M.insert (siz, ch) d cache finalizer $ modifyIORef refCache $ M.delete (siz, ch) return d render :: FT_Face -> Double -> Char -> IO RenderedChar render face siz ch = do let dpi = fromIntegral resolutionDPI runFreeType $ ft_Set_Char_Size face 0 (floor $ siz * 64) dpi dpi ix <- ft_Get_Char_Index face (fromIntegral $ fromEnum ch) runFreeType $ ft_Load_Glyph face ix ft_LOAD_DEFAULT slot <- peek $ glyph face runFreeType $ ft_Render_Glyph slot ft_RENDER_MODE_NORMAL bmp <- peek $ GS.bitmap slot left <- fmap fromIntegral $ peek $ GS.bitmap_left slot top <- fmap fromIntegral $ peek $ GS.bitmap_top slot let h = fromIntegral $ B.rows bmp w = fromIntegral $ B.width bmp fptr <- newForeignPtr_ $ castPtr $ buffer bmp adv <- peek $ GS.advance slot b <- liftBitmapIO $ fromColorAndOpacity (PixelRGB8 255 255 255) $ Image w h $ V.unsafeFromForeignPtr0 fptr $ h * w return $ RenderedChar b (V2 (left + fromIntegral w / 2) (-top + fromIntegral h / 2)) (fromIntegral (V.x adv) / 64)
jwvg0425/free-game
FreeGame/Data/Font.hs
bsd-3-clause
4,858
0
19
1,105
1,432
751
681
104
2
module Dotnet.System.Byte where import Dotnet import qualified Dotnet.System.Object data Byte_ a type Byte a = Dotnet.System.Object.Object (Byte_ a)
alekar/hugs
dotnet/lib/Dotnet/System/Byte.hs
bsd-3-clause
152
0
7
21
41
27
14
-1
-1
module Distribution.Solver.Types.Internal.Utils ( unsafeInternalFakeUnitId ) where import Distribution.Package (PackageId, UnitId, mkUnitId) import Distribution.Text (display) -- | In order to reuse the implementation of PackageIndex which relies -- on 'UnitId' for 'SolverInstallPlan', we need to be able to synthesize -- these IDs prior to installation. These should never be written out! -- Additionally, they need to be guaranteed unique within the install -- plan; this holds because an install plan only ever contains one -- instance of a particular package and version. (To fix this, -- the IDs not only have to identify a package ID, but also the -- transitive requirementso n it.) unsafeInternalFakeUnitId :: PackageId -> UnitId unsafeInternalFakeUnitId = mkUnitId . (".fake."++) . display
headprogrammingczar/cabal
cabal-install/Distribution/Solver/Types/Internal/Utils.hs
bsd-3-clause
813
0
7
129
74
49
25
6
1
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- {-# LANGUAGE Trustworthy #-} module System.Mem.StableName.Dynamic ( DynStableName(..) , hashDynStableName , makeDynStableName ) where import System.Mem.StableName (StableName, makeStableName, hashStableName) import Unsafe.Coerce (unsafeCoerce) -- XXX Not safe! newtype DynStableName = DynStableName (StableName ()) makeDynStableName :: a -> IO DynStableName makeDynStableName x = do stn <- makeStableName x return (DynStableName (unsafeCoerce stn)) hashDynStableName :: DynStableName -> Int hashDynStableName (DynStableName sn) = hashStableName sn instance Eq DynStableName where DynStableName sn1 == DynStableName sn2 = sn1 == sn2
niswegmann/copilot-language
src/System/Mem/StableName/Dynamic.hs
bsd-3-clause
889
0
11
114
174
95
79
17
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="id-ID"> <title>Script Console</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Konten</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Telusuri</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorit</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/scripts/src/main/javahelp/org/zaproxy/zap/extension/scripts/resources/help_id_ID/helpset_id_ID.hs
apache-2.0
958
77
66
156
407
206
201
-1
-1
module LazyWhere () where import Language.Haskell.Liquid.Prelude {-@ pos :: Nat -> Int @-} pos :: Int -> Int pos = undefined {-@ LAZYVAR z @-} foo = if x > 0 then z else x where z = pos x x = choose 0
mightymoose/liquidhaskell
tests/pos/LazyWhere.hs
bsd-3-clause
215
0
7
58
65
39
26
7
2
module FunIn4 where --Any unused parameter to a definition can be removed. --In this example: remove 'x' will fail, as (x,y) is treated as one parameter and 'y' is used. foo (x,y) = h + t where (h,t) = head $ zip [1..7] [3..y] main :: Int main = foo (10, 20)
mpickering/HaRe
old/testing/rmOneParameter/FunIn4_TokOut.hs
bsd-3-clause
268
0
9
61
76
44
32
4
1
-- trying to do 19b without any clever data structures -- this unfortunately required slightly more actualy thought about the code :P import Control.Monad import Data.List.Extra import Data.Maybe import qualified Data.Sequence as Seq import Data.Sequence ((<|), (|>), (><), ViewL(..)) ----- {- type Queue a = ([a], [a]) qfromList x = (x, []) qpush (h, t) x = (h, x:t) qpop (x:xs, t) = (x, (xs, t)) qpop ([], t) = qpop (reverse t, []) -} -------- {- type Queue a = [a] qfromList x = x qpush l x = l ++ [x] qpop (x:xs) = (x, xs) -} -------- type Queue a = Seq.Seq a qfromList = Seq.fromList qpush = (|>) qpop q = case Seq.viewl q of (x :< xs) -> (x, xs) -------- num = 3005290 advance q = let (x, q') = qpop q in qpush q' x kill = snd . qpop -- if odd, advance once after delete -- if even, none of that step (q, n) = let q' = kill q q'' = if odd n then advance q' else q' in (q'', n-1) solve n = let q = qfromList [1..n] q' = iterate advance q !! (n `div` 2) (qfin, _) = until ((==1) . snd) step (q', n) in fst $ qpop qfin main = print $ solve num
msullivan/advent-of-code
2016/A19b_stock.hs
mit
1,081
0
12
254
336
192
144
22
2
-------------------------------------------------------------------------------- -- Largest product in a series -- Problem 8 -- Find the greatest product of five consecutive digits in the 1000-digit number. -------------------------------------------------------------------------------- import Data.Char import Data.Bits n = "73167176531330624919225119674426574742355349194934" ++ "96983520312774506326239578318016984801869478851843" ++ "85861560789112949495459501737958331952853208805511" ++ "12540698747158523863050715693290963295227443043557" ++ "66896648950445244523161731856403098711121722383113" ++ "62229893423380308135336276614282806444486645238749" ++ "30358907296290491560440772390713810515859307960866" ++ "70172427121883998797908792274921901699720888093776" ++ "65727333001053367881220235421809751254540594752243" ++ "52584907711670556013604839586446706324415722155397" ++ "53697817977846174064955149290862569321978468622482" ++ "83972241375657056057490261407972968652414535100474" ++ "82166370484403199890008895243450658541227588666881" ++ "16427171479924442928230863465674813919123162824586" ++ "17866458359124566529476545682848912883142607690042" ++ "24219022671055626321111109370544217506941658960408" ++ "07198403850962455444362981230987879927244284909188" ++ "84580156166097919133875499200524063689912560717606" ++ "05886116467109405077541002256983155200055935729725" ++ "71636269561882670428252483600823257530420752963450" -- number of digits in product m = 5 -- convert known ascii decimal digit to integer digit_to_integer :: Char -> Integer digit_to_integer c = fromIntegral $ (ord c) .&. 0xf solve n pmax = let d5 = take 5 n i5 = map digit_to_integer d5 p = product i5 in case () of _ | (length d5) /= 5 -> pmax _ | (p > pmax) -> solve (tail n) p _ -> solve (tail n) pmax answer = solve n 0 main = print answer {- This is getting easier. -}
bertdouglas/euler-haskell
001-050/08a.hs
mit
1,980
0
23
277
273
139
134
37
3
module Main (main) where import Language.Haskell.HLint (hlint) import System.Exit (exitFailure, exitSuccess) arguments :: [String] arguments = [ "src" , "app" , "test" ] main :: IO () main = do hints <- hlint arguments if null hints then exitSuccess else exitFailure
cackharot/heub
test/HLint.hs
mit
300
0
8
74
94
54
40
13
2
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Network.BitFunctor.Theory.Extraction where import qualified Data.Map as Map import qualified Data.List as List import qualified Data.Text as Text import Data.Monoid ((<>)) import Data.Maybe (catMaybes) import Control.Monad import Control.Lens import Network.BitFunctor.Theory.Types import qualified Network.BitFunctor.Common as Common import qualified Network.BitFunctor.Theory.Utils as Utils eqCodeParts :: TheoryC a k c c' s t => t -> [Either c c'] -> [Either c c'] -> Bool eqCodeParts _ [] [] = True eqCodeParts th ((Left t1):pcp1) ((Left t2):pcp2) = if (toText t1 == toText t2) then (eqCodeParts th pcp1 pcp2) else False eqCodeParts th ((Right e1):pcp1) ((Right e2):pcp2) = -- shortname should be at least equal or that is self-reference let b1 = (toSuffix e1 == toSuffix e2) || (isSelfReference e1) && (isSelfReference e2) in -- if both "extractable" extract and compare if (isTheoriable e1) && (isTheoriable e2) then let ms1 = Map.lookup (toKey $ toKey e1) $ toStatementMap th in let ms2 = Map.lookup (toKey $ toKey e2) $ toStatementMap th in case (ms1, ms2) of (Nothing, _) -> if b1 then (eqCodeParts th pcp1 pcp2) else False (_, Nothing) -> if b1 then (eqCodeParts th pcp1 pcp2) else False (Just s1, Just s2) -> if (b1 || eqStatementCode th s1 s2) then (eqCodeParts th pcp1 pcp2) else False else -- if something unextractable, e.g. LocalConstructor, only shortname should be equal ??? if b1 then (eqCodeParts th pcp1 pcp2) else False eqCodeParts _ _ _ = False eqCode :: TheoryC a k c c' s t => t -> CodeA c c' -> CodeA c c' -> Bool eqCode _ (Left _) _ = False eqCode _ _ (Left _) = False eqCode th (Right p1) (Right p2) = eqCodeParts th p1 p2 eqStatementCode :: TheoryC a k c c' s t => t -> s -> s -> Bool eqStatementCode th s1 s2 = let c1 = toStatementCode s1 in let c2 = toStatementCode s2 in case (c1, c2) of -- never be called -- (Left _, Left _) -> False -- only for Constructors, should not be called for local constructors, when comparing Inductives -- so only one-typed constructors will be equal (Right [], Right []) -> (toSuffix $ toStatementName s1) == (toSuffix $ toStatementName s2) (_, _) -> eqCode th c1 c2 changeCodeReference :: (Nameable b n) => n -> n -> CodeA a b -> CodeA a b changeCodeReference _ _ c@(Left _) = c changeCodeReference s' s (Right ps) = Right $ List.map (\p -> case p of Left t -> Left t Right e -> Right $ changeNameWithKey s' s e) ps -- changeUsesReference :: CoqStatementName -> CoqStatementName -> CoqTerm -> CoqTerm -- changeUsesReference s' s u = if (snd u == s') then (fst u, s) else u changeStatementReference :: (StatementC a k c c' s) => a -> a -> s -> s changeStatementReference n' n st = changeStatementCode (changeCodeReference n' n $ toStatementCode st) st -- v { -- stuses = List.map (changeUsesReference s' s) $ stuses v, -- stcode = changeCodeReference s' s $ stcode v} collapseStatementGroups :: (StatementC a k c c' s) => [[s]] -> [s] -> [s] collapseStatementGroups [] acc = acc collapseStatementGroups ([]:gs) acc = collapseStatementGroups gs acc collapseStatementGroups ([s]:gs) acc = collapseStatementGroups gs (s:acc) collapseStatementGroups ((s:ss):gs) acc = let acc' = List.foldl (\a s' -> List.map (changeStatementReference (toStatementName s') (toStatementName s)) a) acc ss in let gs' = List.foldl (\g s' -> List.map (\gg -> (changeStatementReference (toStatementName s') (toStatementName s) $ List.head gg) : (List.tail gg)) g) gs ss in collapseStatementGroups gs' (s:acc') -- [[a1],[a1,a2,a3]] -- foldl :: (a -> b -> a) -> a -> [b] -> a foldEqualCode :: TheoryC a k c c' s t => t -> IO [s] foldEqualCode th = do let thl = toStatementList th -- let thm = toStatementMap th putStrLn $ "Grouping code, " ++ (show $ List.length thl) ++ " statements total..." stsg <- Utils.groupListBy (Text.unpack . toFQName '.' . toStatementName) (eqStatementCode th) thl putStrLn $ "Collapsing groups, " ++ (show $ List.length stsg) ++ " groups..." return $ collapseStatementGroups stsg [] --------------------------------------------------------------------------------------------------- getUsedStatements :: TheoryC a k c c' s t => t -> s -> [s] getUsedStatements th st = let stc = toStatementCode st in let thm = toStatementMap th in case stc of Left _ -> [] Right cl -> let usm = catMaybes $ List.map (\u -> case u of Left _ -> Nothing Right e -> if isTheoriable e then Map.lookup (toKey $ toKey e) thm else Nothing) cl in List.nub usm unfoldUses :: TheoryC a k c c' s t => [s] -> [s] -> t -> [s] unfoldUses [] acct _ = acct unfoldUses (st:sts) acct th = -- do -- putStrLn $ "Unfolding " ++ (Text.unpack $ toSuffix $ toStatementName st) ++ ", remaining " ++ (show $ List.length sts) let thm = toStatementMap th in let b = List.notElem st acct in -- let isExtractable u = (fst u /= SelfReference) && (fst u /= BoundVariable) && (fst u /= LocalConstructor) let stc = toStatementCode st in case stc of Left _ -> -- do -- putStrLn "Statement code is not parsed, skipping..." unfoldUses sts acct th Right cl -> let usm = catMaybes $ List.map (\u -> case u of Left _ -> Nothing Right e -> if isTheoriable e then Map.lookup (toKey $ toKey e) thm else Nothing) cl in if b then unfoldUses (usm ++ sts) (st:acct) th else -- do -- putStrLn "skipping..." unfoldUses sts acct th unfoldUsesList :: TheoryC a k c c' s t => [s] -> t -> [[s]] unfoldUsesList sts th = List.map (\s -> unfoldUses [s] [] th) sts getStatementsBySuffix :: TheoryC a k c c' s t => t -> Text.Text -> [s] getStatementsBySuffix th sfx = let thl = toStatementList th in List.filter (\s -> ((toSuffix $ toStatementName s) == sfx)) thl extractTerms :: TheoryC a k c c' s t => t -> [Text.Text] -> [[[s]]] extractTerms _ [] = [] extractTerms th (tt:tts) = let et = let fsts = getStatementsBySuffix th tt in let r = unfoldUsesList fsts th in List.map (Common.partsort toStatementName partCompare) r in et:(extractTerms th tts) shortenLibNames :: StatementC a k c c' s => [s] -> ([s], [(Text.Text, Text.Text)]) shortenLibNames sts = let preforig = List.nub $ mapped %~ (toPrefix '_' . toStatementName) $ sts in let prefsh = Utils.shortenText preforig in let chmap = zip preforig prefsh in (sts, chmap) extractTermsCode :: TheoryC a k c c' s t => t -> [Text.Text] -> [[Text.Text]] extractTermsCode th ts = let extss' = extractTerms th ts in -- putStrLn $ "Length of extracted terms: " ++ (show $ mapped.mapped %~ List.length $ extss') let chlibmap = mapped.mapped %~ shortenLibNames $ extss' in mapped.mapped %~ (\(exts, chmap) -> Text.concat $ List.map (\s -> (fromCodeWithPrefixMapA '_' (Map.fromList chmap) $ toStatementCode s) <> "\n(* end " <> (toFQName '.' $ toStatementName s) <> " *)\n\n") exts) $ chlibmap ----------------------------------------------------------------------------------------- checkTheoryConsistancy :: TheoryC a k c c' s t => t -> IO () checkTheoryConsistancy th = do putStrLn "Checking for presense..." let us = List.nub $ Prelude.concat $ List.map (getUsedStatements th) $ toStatementList th let thm = toStatementMap $ th forM_ us (\u -> if (Map.member (toKey $ toStatementName u) thm) then putStrLn $ "!Found: " ++ (show $ toFQName '.' $ toStatementName u) else putStrLn $ "?Found: " ++ (show $ toFQName '.' $ toStatementName u)) checkTheoryAcyclessness :: TheoryC a k c c' s t => t -> IO () checkTheoryAcyclessness th = do putStrLn "Checking for cycles..." let thl = toStatementList th let thm = toStatementMap th forM_ thl (\s -> do putStrLn $ "Checking " ++ (show $ toFQName '.' $ toStatementName s) let us = getUsedStatements th s forM_ us (\u -> let ms' = Map.lookup (toKey $ toStatementName u) thm in case ms' of Nothing -> putStrLn $ " Dependence " ++ (show $ toFQName '.' $ toStatementName u) ++ " not found" Just s' -> let us' = getUsedStatements th s' in if (List.elem u us') then putStrLn $ " Dependence " ++ (show $ toFQName '.' $ toStatementName u) ++ " form a cycle" else putStrLn $ " Dependence " ++ (show $ toFQName '.' $ toStatementName u) ++ " is OK"))
BitFunctor/bitfunctor-theory
src/Network/BitFunctor/Theory/Extraction.hs
mit
11,846
0
29
5,173
3,056
1,552
1,504
-1
-1
import Test.Hspec import PscInspect main :: IO () main = hspec $ do describe "hasPursExtension" $ do it "should return true for a FilePath ending in .purs" $ do PscInspect.hasPursExtension "Thermite.purs" `shouldBe` True
sgronblo/psc-inspect
test/Spec.hs
mit
246
0
16
58
62
30
32
7
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} module Main where import PreHomework.Type import PreHomework.Parser import qualified Data.HashMap.Strict as H import Data.Set (Set) import qualified Data.Set as Set import qualified Data.ByteString as B import Data.ByteString (ByteString) import Control.Monad.Trans.Resource import Data.Monoid ((<>)) import Data.Conduit import qualified Data.Conduit.Binary as CB import System.IO (stdin) type Table a = H.HashMap UserID a type ItemSet = Set ProductID main :: IO () main = do --sampleData 10000 runResourceT $ CB.sourceHandle stdin $$ parserConduit =$= filterUnknown =$= accumulateProduct H.empty =$= toByteString =$ CB.sinkFile "output" filterUnknown :: Conduit Product (ResourceT IO) Product filterUnknown = do p <- await case p of Just (Product "unknown" _) -> filterUnknown Just (Product _ "unknown") -> filterUnknown Just (Product u p) -> yield (Product u p) >> filterUnknown Nothing -> return () accumulateProduct :: Table ItemSet -> Conduit Product (ResourceT IO) (Table ItemSet) accumulateProduct table = do p <- await case p of Just (Product userID productID) -> accumulateProduct (H.insertWith (\new set -> () `seq` new `Set.union` set) userID (Set.singleton productID) table) Nothing -> yield table toByteString :: Conduit (Table ItemSet) (ResourceT IO) ByteString toByteString = do t <- await case t of Just table -> mapM_ (yield . toLine) (H.toList table) Nothing -> return () where toLine (k, v) = k <> " " <> Set.foldl' (\a b -> a <> " " <> b) B.empty v <> "\n" sampleData :: Int -> IO () sampleData n = do runResourceT $ CB.sourceHandle stdin $$ CB.lines =$= snatch (n * 11 - 1) =$ CB.sinkFile "data/data" snatch :: Int -> Conduit ByteString (ResourceT IO) ByteString snatch 0 = return () snatch n = do a <- await case a of Just s -> do yield (s <> "\n") snatch (n-1) Nothing -> return ()
DM2014/pre-homework
src/main.hs
mit
2,152
0
17
575
739
381
358
53
4
import Data.Char toDigits :: Integer -> [Integer] toDigits 0 = [] toDigits n | n < 0 = [] | otherwise = map fromIntegral $ map digitToInt $ show n toDigitsRev :: Integer -> [Integer] toDigitsRev 0 = [] toDigitsRev n | n < 0 = [] | otherwise = map fromIntegral $ map digitToInt $ reverse . show $ n
GrooveStomp/yorgey-haskell-course
week-01/exercise-01.hs
mit
308
0
10
71
147
70
77
11
1
import Graphics.X11.Xlib import Graphics.X11.Xlib.Extras import System.Environment import System.IO import Data.Char -- BUG: global XMessage warnings in /var/tmp/xmonad_* -- WARNING: QXcbWindow: Unhandled client message: "XMONAD_COMMAND" main :: IO () main = parse True "XMONAD_COMMAND" =<< getArgs parse :: Bool -> String -> [String] -> IO () parse input addr args = case args of ["--"] | input -> repl addr | otherwise -> return () ("--":xs) -> sendAll addr xs ("-a":a:xs) -> parse input a xs ("-h":_) -> showHelp ("--help":_) -> showHelp ("-?":_) -> showHelp (a@('-':_):_) -> hPutStrLn stderr ("Unknown option " ++ a) (x:xs) -> sendCommand addr x >> parse False addr xs [] | input -> repl addr | otherwise -> return () repl :: String -> IO () repl addr = do e <- isEOF case e of True -> return () False -> do l <- getLine sendCommand addr l repl addr sendAll :: String -> [String] -> IO () sendAll addr ss = foldr (\a b -> sendCommand addr a >> b) (return ()) ss sendCommand :: String -> String -> IO () sendCommand addr s = do d <- openDisplay "" rw <- rootWindow d $ defaultScreen d a <- internAtom d addr False m <- internAtom d s False allocaXEvent $ \e -> do setEventType e clientMessage setClientMessageEvent e rw a 32 m currentTime sendEvent d rw False structureNotifyMask e sync d False showHelp :: IO () showHelp = do pn <- getProgName putStrLn ("Send commands to a running instance of xmonad. xmonad.hs must be configured with XMonad.Hooks.ServerMode to work.\n-a atomname can be used at any point in the command line arguments to change which atom it is sending on.\nIf sent with no arguments or only -a atom arguments, it will read commands from stdin.\nEx:\n" ++ pn ++ " cmd1 cmd2\n" ++ pn ++ " -a XMONAD_COMMAND cmd1 cmd2 cmd3 -a XMONAD_PRINT hello world\n" ++ pn ++ " -a XMONAD_PRINT # will read data from stdin.\nThe atom defaults to XMONAD_COMMAND.")
amerlyq/airy
xmonad/ext/ctl.hs
mit
2,181
0
14
636
639
310
329
43
9
{-# LANGUAGE CPP, FlexibleContexts, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module System.Process.Text where #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif import Control.Monad import Data.ListLike.IO (hGetContents) import Data.Text (Text) import Prelude hiding (null) import System.Process import System.Process.Common import System.Exit (ExitCode) instance ProcessText Text Char -- | Like 'System.Process.readProcessWithExitCode', but using 'Text' instance ListLikeProcessIO Text Char where forceOutput = return readChunks h = (: []) <$> hGetContents h -- | Specialized version for backwards compatibility. readProcessWithExitCode :: FilePath -- ^ command to run -> [String] -- ^ any arguments -> Text -- ^ standard input -> IO (ExitCode, Text, Text) -- ^ exitcode, stdout, stderr readProcessWithExitCode = System.Process.Common.readProcessWithExitCode readCreateProcessWithExitCode :: CreateProcess -- ^ command and arguments to run -> Text -- ^ standard input -> IO (ExitCode, Text, Text) -- ^ exitcode, stdout, stderr readCreateProcessWithExitCode = System.Process.Common.readCreateProcessWithExitCode
seereason/process-extras
src/System/Process/Text.hs
mit
1,284
0
9
263
208
128
80
26
1
module Hasql.Postgres.Connector where import Hasql.Postgres.Prelude hiding (Error) import qualified Database.PostgreSQL.LibPQ as PQ import qualified Data.ByteString as B import qualified Data.ByteString.Lazy.Builder as BB import qualified Data.ByteString.Lazy.Builder.ASCII as BB import qualified Data.ByteString.Lazy as BL -- | -- Connection settings. data Settings = -- | -- A host, a port, a user, a password and a database. ParamSettings ByteString Word16 ByteString ByteString ByteString | -- | -- All settings encoded in a single byte string according to -- <http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-CONNSTRING the PostgreSQL format>. StringSettings ByteString data Error = BadStatus (Maybe ByteString) | UnsupportedVersion Int deriving (Show) -- | -- Establish and initialize a connection. open :: Settings -> IO (Either Error PQ.Connection) open s = runEitherT $ do c <- lift $ PQ.connectdb (settingsBS s) do s <- lift $ PQ.status c when (s /= PQ.ConnectionOk) $ do m <- lift $ PQ.errorMessage c left $ BadStatus m do v <- lift $ PQ.serverVersion c when (v < 80200) $ left $ UnsupportedVersion v lift $ PQ.exec c $ BL.toStrict $ BB.toLazyByteString $ mconcat $ map (<> BB.char7 ';') $ [ BB.string7 "SET client_encoding = 'UTF8'", BB.string7 "SET client_min_messages TO WARNING" ] return c settingsBS :: Settings -> ByteString settingsBS = \case ParamSettings host port user password database -> BL.toStrict $ BB.toLazyByteString $ mconcat $ intersperse (BB.char7 ' ') $ catMaybes $ [ mappend (BB.string7 "host=") . BB.byteString <$> partial (not . B.null) host , mappend (BB.string7 "port=") . BB.word16Dec <$> partial (/= 0) port , mappend (BB.string7 "user=") . BB.byteString <$> partial (not . B.null) user , mappend (BB.string7 "password=") . BB.byteString <$> partial (not . B.null) password , mappend (BB.string7 "dbname=") . BB.byteString <$> partial (not . B.null) database ] StringSettings x -> x
begriffs/hasql-postgres
library/Hasql/Postgres/Connector.hs
mit
2,209
0
16
551
619
324
295
-1
-1
{- DOC: Paste all the following commented lines in the file importing this module (don’t forget to update constant ‘filename’). import qualified SRC.Log as Log -- write code here -- logging boilerplate filename = "-.hs" fatal :: Show a => String -> a -> b fatal msg line = Log.reportFatal filename msg line fixme, bug, err :: Show a => a -> b fixme = fatal L.fixMe bug = fatal L.bug err = fatal L.err -} module SRC.Log ( reportFatal , fixMe , bug , err ) where reportFatal :: Show a => String -> String -> a -> b reportFatal filename msg line = let message = filename ++ ":" ++ (show line) ++ ": " ++ msg in error message fixMe = "FixMe" bug = "BUG" err = "error"
Fornost461/drafts-and-stuff
Haskell/projects/watcher/SRC/Log.hs
cc0-1.0
712
0
13
173
108
58
50
11
1
module Main where import System.Environment import Parser main :: IO () main = do args <- getArgs putStrLn (readExpr (args !! 0))
fbq/s48
Scheme.hs
gpl-2.0
135
0
11
27
53
28
25
7
1
{- | The "OWL2" directory contains the OWL2 instance of "Logic.Logic". The data for this instance is found in "OWL2.Logic_OWL2". /Abstact Syntax/ The syntax for OWL2 is represented using Haskell datatypes. It is defined both in OWL2.AS - which contains the entities and expressions (<http://www.w3.org/TR/owl2-syntax/>) and in OWL2.MS - which contains the frames (<http://www.w3.org/TR/owl2-manchester-syntax/>). As the official Manchester Syntax cannot express some of the valid OWL2 axioms, the Haskell datatypes for frames were extended to also accomodate these. /Parser/ The parsing of an OWL ontology happens in two main steps. First, the ontology is converted to XML, using the Java parser found in "OWL2.java". Then, the XML is parsed into the Haskell datatypes (see "OWL2.XML"). The top-level function which combines the two steps is found in "OWL2.ParseOWLAsLibDefn". The parser for the Het-CASL representation is found in "OWL2.Parse" and "OWL2.ManchesterParser" which take as argument an ontology in our extended Manchester Syntax and convert it into the Haskell datatypes. /Pretty printing/ This is done in "OWL2.Print" (for the "AS.hs" datatypes) and in "OWL2.ManchesterPrint" (fot the "MS.hs" datatypes). The output is written in our extended Manchester Syntax. A LaTeX output is not available, yet. /Static Analysis/ The file "OWL2.StaticAnalysis" repairs the ontology after parsing and then produces the final axioms and signature needed for hets analysis. /Provers/ There are two of these for OWL2, namely Pellet and FACT++, written in Java. The call for them happens in "OWL2.ProvePellet" and "OWL2.ProveFact". The input for the provers is XML syntax, which comes from "OWL2.XMLConversion". The conservativity check is implemented in "OWL2.Conservativity" and uses the Java- written locality checker. /Comorphisms/ There are three implemented comorphsims: from OWL2 to CASL and Common Logic and from DMU to OWL2. /Profiles and sublogics/ There are three OWL2 profiles: EL, QL and RL. In "OWL2.Profiles", an ontology is taken as argument and analysed, in order to see in which of the profiles it fits, while in "OWL2.Sublogics", the reasoning complexity of the ontology is computed. /Miscellaneous/ "OWL2.Function" provides a class for functions which go through all the Haskell datatypes and which are structurally equivalent (except maybe on what they do with the IRIs or entities). Currently, morphism mapping, prefix renaming and IRI expansion are implemented there. "OWL2.ColimSign" and "OWL2.Taxonomy" provide signature colimits and taxonomy extraction, respectively. -} module OWL2 where
nevrenato/Hets_Fork
OWL2.hs
gpl-2.0
2,635
0
2
403
5
4
1
1
0
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GLU.Tessellation -- Copyright : (c) Sven Panne 2002-2009 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : sven.panne@aedion.de -- Stability : stable -- Portability : portable -- -- This module corresponds to chapter 5 (Polygon Tessellation) of the GLU specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GLU.Tessellation ( -- * Polygon description AnnotatedVertex(..), ComplexContour(..), ComplexPolygon(..), -- * Combining vertices WeightedProperties(..), Combiner, -- * Tessellation parameters TessWinding(..), Tolerance, -- * Tessellator type Tessellator, -- * Contour extraction SimpleContour(..), PolygonContours(..), extractContours, -- * Triangulation TriangleVertex, Triangle(..), Triangulation(..), triangulate, -- * Tessellation into primitives Primitive(..), SimplePolygon(..), tessellate ) where import Control.Monad ( foldM, unless ) import Data.IORef ( newIORef, readIORef, writeIORef, modifyIORef ) import Data.Maybe ( fromJust ) import Data.Tensor import Foreign.Marshal.Alloc ( allocaBytes ) import Foreign.Marshal.Array ( peekArray, pokeArray ) import Foreign.Marshal.Pool ( Pool, withPool, pooledNew ) import Foreign.Ptr ( Ptr, nullPtr, plusPtr, castPtr, freeHaskellFunPtr ) import Foreign.Storable ( Storable(..) ) import Graphics.Rendering.GLU.Raw import Graphics.Rendering.OpenGL.Raw.Core31 import Graphics.Rendering.OpenGL.GL.EdgeFlag ( unmarshalEdgeFlag ) import Graphics.Rendering.OpenGL.GL.Exception ( bracket ) import Graphics.Rendering.OpenGL.GL.GLboolean ( marshalGLboolean ) import Graphics.Rendering.OpenGL.GL.PrimitiveMode ( unmarshalPrimitiveMode ) import Graphics.Rendering.OpenGL.GL.BeginEnd ( PrimitiveMode, EdgeFlag(BeginsInteriorEdge) ) import Graphics.Rendering.OpenGL.GL.VertexSpec import Graphics.Rendering.OpenGL.GL.QueryUtils import Graphics.Rendering.OpenGL.GLU.ErrorsInternal -------------------------------------------------------------------------------- data TessWinding = TessWindingOdd | TessWindingNonzero | TessWindingPositive | TessWindingNegative | TessWindingAbsGeqTwo deriving ( Eq, Ord, Show ) marshalTessWinding :: TessWinding -> GLenum marshalTessWinding x = case x of TessWindingOdd -> glu_TESS_WINDING_ODD TessWindingNonzero -> glu_TESS_WINDING_NONZERO TessWindingPositive -> glu_TESS_WINDING_POSITIVE TessWindingNegative -> glu_TESS_WINDING_NEGATIVE TessWindingAbsGeqTwo -> glu_TESS_WINDING_ABS_GEQ_TWO -------------------------------------------------------------------------------- -- | The basic building block in tessellation is a 3D vertex with an associated -- property, e.g. color, texture coordinates, etc. data AnnotatedVertex v = AnnotatedVertex (Vertex3 GLdouble) v deriving ( Eq, Ord ) offsetOfProperty :: Storable v => v -> Int offsetOfProperty v = alignOffset v (3 * sizeOf x) where AnnotatedVertex (Vertex3 x _ _) _ = undefined alignOffset :: Storable a => a -> Int -> Int alignOffset x offset = n - (n `mod` a) where a = alignment x n = a + offset - 1 instance Storable v => Storable (AnnotatedVertex v) where sizeOf ~(AnnotatedVertex (Vertex3 x _ _) v) = alignOffset x (sizeOf v + offsetOfProperty v) alignment ~(AnnotatedVertex (Vertex3 x _ _) _) = alignment x peek ptr = do x <- peekElemOff (castPtr ptr) 0 y <- peekElemOff (castPtr ptr) 1 z <- peekElemOff (castPtr ptr) 2 let dummyElement :: Ptr (AnnotatedVertex v) -> v dummyElement = undefined v <- peekByteOff (castPtr ptr) (offsetOfProperty (dummyElement ptr)) return $ AnnotatedVertex (Vertex3 x y z) v poke ptr (AnnotatedVertex (Vertex3 x y z) v) = do pokeElemOff (castPtr ptr) 0 x pokeElemOff (castPtr ptr) 1 y pokeElemOff (castPtr ptr) 2 z pokeByteOff (castPtr ptr) (offsetOfProperty v) v -------------------------------------------------------------------------------- -- | A complex contour, which can be self-intersecting and\/or concave. newtype ComplexContour v = ComplexContour [AnnotatedVertex v] deriving ( Eq, Ord ) sizeOfComplexContour :: Storable v => ComplexContour v -> Int sizeOfComplexContour (ComplexContour vs) = length vs * sizeOf (head vs) pokeComplexContour :: Storable v => Ptr (ComplexContour v) -> ComplexContour v -> IO () pokeComplexContour ptr (ComplexContour vs) = pokeArray (castPtr ptr) vs -------------------------------------------------------------------------------- -- | A complex (possibly concave) polygon, represented by one or more complex -- and possibly intersecting contours. newtype ComplexPolygon v = ComplexPolygon [ComplexContour v] deriving ( Eq, Ord ) sizeOfComplexPolygon :: Storable v => ComplexPolygon v -> Int sizeOfComplexPolygon (ComplexPolygon complexContours) = sum (map sizeOfComplexContour complexContours) pokeComplexPolygon :: Storable v => Ptr (ComplexPolygon v) -> ComplexPolygon v -> IO () pokeComplexPolygon ptr (ComplexPolygon complexContours) = foldM pokeAndAdvance (castPtr ptr) complexContours >> return () where pokeAndAdvance p complexContour = do pokeComplexContour p complexContour return $ p `plusPtr` sizeOfComplexContour complexContour withComplexPolygon :: Storable v => ComplexPolygon v -> (Ptr (ComplexPolygon v) -> IO a) -> IO a withComplexPolygon complexPolygon f = allocaBytes (sizeOfComplexPolygon complexPolygon) $ \ptr -> do pokeComplexPolygon ptr complexPolygon f ptr -------------------------------------------------------------------------------- -- | Four vertex properties (cf. 'AnnotatedVertex') with associated weigths -- summing up to 1.0. data WeightedProperties v = WeightedProperties (GLfloat, v) (GLfloat, v) (GLfloat, v) (GLfloat, v) deriving ( Eq, Ord ) -- | A function combining given vertex properties into a property for a newly -- generated vertex type Combiner v = Vertex3 GLdouble -> WeightedProperties v -> v -------------------------------------------------------------------------------- -- | The relative tolerance under which two vertices can be combined (see -- 'Combiner'). Multiplication with the largest coordinate magnitude of all -- polygon vertices yields the maximum distance between two mergeable vertices. -- -- Note that merging is optional and the tolerance is only a hint. type Tolerance = GLdouble -------------------------------------------------------------------------------- -- | A general tessellator type. -- -- Before tessellation of a complex polygon, all its vertices are projected into -- a plane perpendicular to the given normal. If the given normal is -- @Normal3 0 0 0@, a fitting plane of all vertices is used. type Tessellator p v = TessWinding -> Tolerance -> Normal3 GLdouble -> Combiner v -> ComplexPolygon v -> IO (p v) -------------------------------------------------------------------------------- -- | A simple, non-self-intersecting contour newtype SimpleContour v = SimpleContour [AnnotatedVertex v] deriving ( Eq, Ord ) -- | The contours of a complex polygon, represented by one or more -- non-intersecting simple contours newtype PolygonContours v = PolygonContours [SimpleContour v] deriving ( Eq, Ord ) extractContours :: Storable v => Tessellator PolygonContours v extractContours windingRule tolerance theNormal combiner complexPoly = do vertices <- newIORef [] let addVertex v = modifyIORef vertices (v:) contours <- newIORef [] let finishContour = do vs <- readIORef vertices writeIORef vertices [] modifyIORef contours (SimpleContour (reverse vs) :) getContours = fmap (PolygonContours . reverse) (readIORef contours) withTessellatorObj (PolygonContours [])$ \tessObj -> do setTessellatorProperties tessObj windingRule tolerance theNormal True withVertexCallback tessObj addVertex $ withEndCallback tessObj finishContour $ checkForError tessObj $ withCombineCallback tessObj combiner $ do defineComplexPolygon tessObj complexPoly getContours -------------------------------------------------------------------------------- -- | A triangle vertex with additional information about the edge it begins type TriangleVertex v = AnnotatedVertex (v,EdgeFlag) -- | A triangle, represented by three triangle vertices data Triangle v = Triangle (TriangleVertex v) (TriangleVertex v) (TriangleVertex v) deriving ( Eq, Ord ) -- | A triangulation of a complex polygon newtype Triangulation v = Triangulation [Triangle v] deriving ( Eq, Ord ) triangulate :: Storable v => Tessellator Triangulation v triangulate windingRule tolerance theNormal combiner complexPoly = do edgeFlagState <- newIORef BeginsInteriorEdge let registerEdgeFlag = writeIORef edgeFlagState vertices <- newIORef [] let addVertex (AnnotatedVertex xyz v) = do ef <- readIORef edgeFlagState modifyIORef vertices (AnnotatedVertex xyz (v,ef) :) getTriangulation = do vs <- readIORef vertices return $ Triangulation (collectTriangles (reverse vs)) withTessellatorObj (Triangulation []) $ \tessObj -> do setTessellatorProperties tessObj windingRule tolerance theNormal False withEdgeFlagCallback tessObj registerEdgeFlag $ withVertexCallback tessObj addVertex $ checkForError tessObj $ withCombineCallback tessObj combiner $ do defineComplexPolygon tessObj complexPoly getTriangulation collectTriangles :: [TriangleVertex v] -> [Triangle v] collectTriangles [] = [] collectTriangles (a:b:c:rest) = Triangle a b c : collectTriangles rest collectTriangles _ = error "triangles left" -------------------------------------------------------------------------------- data Primitive v = Primitive PrimitiveMode [AnnotatedVertex v] deriving ( Eq, Ord ) newtype SimplePolygon v = SimplePolygon [Primitive v] deriving ( Eq, Ord ) tessellate :: Storable v => Tessellator SimplePolygon v tessellate windingRule tolerance theNormal combiner complexPoly = do beginModeState <- newIORef undefined let setPrimitiveMode = writeIORef beginModeState vertices <- newIORef [] let addVertex v = modifyIORef vertices (v:) primitives <- newIORef [] let finishPrimitive = do beginMode <- readIORef beginModeState vs <- readIORef vertices writeIORef vertices [] modifyIORef primitives (Primitive beginMode (reverse vs) :) getSimplePolygon = fmap (SimplePolygon . reverse) (readIORef primitives) withTessellatorObj (SimplePolygon []) $ \tessObj -> do setTessellatorProperties tessObj windingRule tolerance theNormal False withBeginCallback tessObj setPrimitiveMode $ withVertexCallback tessObj addVertex $ withEndCallback tessObj finishPrimitive $ checkForError tessObj $ withCombineCallback tessObj combiner $ do defineComplexPolygon tessObj complexPoly getSimplePolygon -------------------------------------------------------------------------------- -- chapter 5.1: The Tessellation Object -- an opaque pointer to a tessellator object type TessellatorObj = Ptr GLUtesselator isNullTesselatorObj :: TessellatorObj -> Bool isNullTesselatorObj = (nullPtr ==) withTessellatorObj :: a -> (TessellatorObj -> IO a) -> IO a withTessellatorObj failureValue action = bracket gluNewTess safeDeleteTess (\tessObj -> if isNullTesselatorObj tessObj then do recordOutOfMemory return failureValue else action tessObj) safeDeleteTess :: TessellatorObj -> IO () safeDeleteTess tessObj = unless (isNullTesselatorObj tessObj) $ gluDeleteTess tessObj -------------------------------------------------------------------------------- -- chapter 5.2: Polygon Definition (polygons) defineComplexPolygon :: Storable v => TessellatorObj -> ComplexPolygon v -> IO () defineComplexPolygon tessObj cp@(ComplexPolygon complexContours) = withComplexPolygon cp $ \ptr -> tessBeginEndPolygon tessObj nullPtr $ let loop _ [] = return () loop p (c:cs) = do defineComplexContour tessObj (castPtr p) c loop (p `plusPtr` sizeOfComplexContour c) cs in loop ptr complexContours tessBeginEndPolygon :: TessellatorObj -> Ptr p -> IO a -> IO a tessBeginEndPolygon tessObj ptr f = do gluTessBeginPolygon tessObj ptr res <- f gluTessEndPolygon tessObj return res -------------------------------------------------------------------------------- -- chapter 5.2: Polygon Definition (contours) defineComplexContour :: Storable v => TessellatorObj -> Ptr (ComplexContour v) -> ComplexContour v -> IO () defineComplexContour tessObj ptr (ComplexContour annotatedVertices) = tessBeginEndContour tessObj $ let loop _ [] = return () loop p (v:vs) = do defineVertex tessObj (castPtr p) loop (p `plusPtr` sizeOf v) vs in loop ptr annotatedVertices tessBeginEndContour :: TessellatorObj -> IO a -> IO a tessBeginEndContour tessObj f = do gluTessBeginContour tessObj res <- f gluTessEndContour tessObj return res -------------------------------------------------------------------------------- -- chapter 5.2: Polygon Definition (vertices) defineVertex :: TessellatorObj -> Ptr (AnnotatedVertex v) -> IO () defineVertex tessObj ptr = gluTessVertex tessObj (castPtr ptr) ptr -------------------------------------------------------------------------------- -- chapter 5.3: Callbacks (begin) type BeginCallback = PrimitiveMode -> IO () withBeginCallback :: TessellatorObj -> BeginCallback -> IO a -> IO a withBeginCallback tessObj beginCallback action = bracket (makeTessBeginCallback (beginCallback . unmarshalPrimitiveMode)) freeHaskellFunPtr $ \callbackPtr -> do gluTessCallback tessObj glu_TESS_BEGIN callbackPtr action -------------------------------------------------------------------------------- -- chapter 5.3: Callbacks (edgeFlag) type EdgeFlagCallback = EdgeFlag -> IO () withEdgeFlagCallback :: TessellatorObj -> EdgeFlagCallback -> IO a -> IO a withEdgeFlagCallback tessObj edgeFlagCallback action = bracket (makeTessEdgeFlagCallback (edgeFlagCallback . unmarshalEdgeFlag)) freeHaskellFunPtr $ \callbackPtr -> do gluTessCallback tessObj glu_TESS_EDGE_FLAG callbackPtr action -------------------------------------------------------------------------------- -- chapter 5.3: Callbacks (vertex) type VertexCallback v = AnnotatedVertex v -> IO () withVertexCallback :: Storable v => TessellatorObj -> VertexCallback v -> IO a -> IO a withVertexCallback tessObj vertexCallback action = bracket (makeTessVertexCallback (\p -> peek p >>= vertexCallback)) freeHaskellFunPtr $ \callbackPtr -> do gluTessCallback tessObj glu_TESS_VERTEX callbackPtr action -------------------------------------------------------------------------------- -- chapter 5.3: Callbacks (end) type EndCallback = IO () withEndCallback :: TessellatorObj -> EndCallback -> IO a -> IO a withEndCallback tessObj endCallback action = bracket (makeTessEndCallback endCallback) freeHaskellFunPtr $ \callbackPtr -> do gluTessCallback tessObj glu_TESS_END callbackPtr action -------------------------------------------------------------------------------- -- chapter 5.3: Callbacks (error) type ErrorCallback = GLenum -> IO () withErrorCallback :: TessellatorObj -> ErrorCallback -> IO a -> IO a withErrorCallback tessObj errorCallback action = bracket (makeTessErrorCallback errorCallback) freeHaskellFunPtr $ \callbackPtr -> do gluTessCallback tessObj glu_TESS_ERROR callbackPtr action checkForError :: TessellatorObj -> IO a -> IO a checkForError tessObj = withErrorCallback tessObj recordErrorCode -------------------------------------------------------------------------------- -- chapter 5.3: Callbacks (combine) type CombineCallback v = Ptr GLdouble -> Ptr (Ptr (AnnotatedVertex v)) -> Ptr GLfloat -> Ptr (Ptr (AnnotatedVertex v)) -> IO () withCombineCallback :: Storable v => TessellatorObj -> Combiner v -> IO a -> IO a withCombineCallback tessObj combiner action = withPool $ \vertexPool -> bracket (makeTessCombineCallback (combineProperties vertexPool combiner)) freeHaskellFunPtr $ \callbackPtr -> do gluTessCallback tessObj glu_TESS_COMBINE callbackPtr action -- NOTE: SGI's tesselator has a bug, sometimes passing NULL for the last two -- vertices instead of valid vertex data, so we have to work around this. We -- just pass the first vertex in these cases, which is OK, because the -- corresponding weight is 0. combineProperties :: Storable v => Pool -> Combiner v -> CombineCallback v combineProperties pool combiner newVertexPtr propertyPtrs weights result = do newVertex <- peek (castPtr newVertexPtr :: Ptr (Vertex3 GLdouble)) [v0, v1, v2, v3] <- mapM (getProperty propertyPtrs) [0..3] [w0, w1, w2, w3] <- peekArray 4 weights let defaultProperty = fromJust v0 f = maybe defaultProperty id wp = WeightedProperties (w0, f v0) (w1, f v1) (w2, f v2) (w3, f v3) av = AnnotatedVertex newVertex (combiner newVertex wp) poke result =<< pooledNew pool av getProperty :: Storable v => Ptr (Ptr (AnnotatedVertex v)) -> Int -> IO (Maybe v) getProperty propertyPtrs n = peekElemOff propertyPtrs n >>= maybeNullPtr (return Nothing) peekProperty peekProperty :: Storable v => Ptr (AnnotatedVertex v) -> IO (Maybe v) peekProperty ptr = do AnnotatedVertex _ v <- peek ptr return (Just v) -------------------------------------------------------------------------------- -- chapter 5.4: Control over Tessellation setTessellatorProperties :: TessellatorObj -> TessWinding -> Tolerance -> Normal3 GLdouble -> Bool -> IO () setTessellatorProperties tessObj windingRule tolerance theNormal boundaryOnly = do setWindingRule tessObj windingRule setTolerance tessObj tolerance setNormal tessObj theNormal setBoundaryOnly tessObj boundaryOnly setWindingRule :: TessellatorObj -> TessWinding -> IO () setWindingRule tessObj = gluTessProperty tessObj glu_TESS_WINDING_RULE . fromIntegral . marshalTessWinding setBoundaryOnly :: TessellatorObj -> Bool -> IO () setBoundaryOnly tessObj = gluTessProperty tessObj glu_TESS_BOUNDARY_ONLY . marshalGLboolean setTolerance :: TessellatorObj -> Tolerance -> IO () setTolerance tessObj = gluTessProperty tessObj glu_TESS_TOLERANCE setNormal :: TessellatorObj -> Normal3 GLdouble -> IO () setNormal tessObj (Normal3 x y z) = gluTessNormal tessObj x y z
ducis/haAni
hs/common/Graphics/Rendering/OpenGL/GLU/Tessellation.hs
gpl-2.0
19,312
0
17
3,704
4,427
2,244
2,183
322
5
-- | Statistik module Operate.Statistik where import Gateway.CGI import Operate.Login import Control.Types import qualified Control.Aufgabe.Typ as A import qualified Control.Aufgabe.DB import qualified Control.Vorlesung.DB import qualified Control.Vorlesung.Typ as V import qualified Control.Gruppe.DB import qualified Control.Gruppe.Typ as G import Control.Stud_Aufg.Typ import Control.Stud_Aufg.DB import Control.Student.DB import Control.Student.CGI import qualified Control.Student as S import Control.Stud_Aufg as SA import Autolib.ToDoc import Autolib.FiniteMap import Autolib.Set import Autolib.Util.Sort import Control.Monad import qualified Data.List -- main :: IO () -- main = Operate.CGI.execute "Statistik.cgi" $ iface data Choice = None | All | Mandat deriving ( Eq, Ord, Show ) main svt @ ( stud, vor, status, attends ) = do h3 "autotool: Statistiken" guard $ status >= Tutor open btable action <- click_choice "zeige" [ ("Resultate (mandatory)", resultate vor Mandat ) , ("Resultate (alle)" , resultate vor All ) , ("Studenten anzeigen", resultate vor None ) , ("einen Studenten bearbeiten", student_bearbeiten vor) ] action -------------------------------------------------------------------------- student_bearbeiten vor = do studs <- io $ Control.Vorlesung.DB.steilnehmer $ V.vnr vor edit_studenten studs edit_studenten studs = do ( stud , _ ) <- selector_submit_click "bearbeite" Nothing $ do stud <- sortBy S.mnr studs let s = unwords [ toString $ S.mnr stud , toString $ S.vorname stud , toString $ S.name stud ] return (s, stud) close -- btable Control.Student.CGI.edit stud -------------------------------------------------------------------------- resultate vor choice = do let vnr = V.vnr vor close -- btable sgs <- io $ Control.Vorlesung.DB.snr_gnr_teilnehmer vnr aufs0 <- io $ Control.Aufgabe.DB.get ( Just vnr ) let aufs = do auf <- aufs0 guard $ case choice of None -> False Mandat -> A.status auf == Mandatory All -> True return auf -- anr to name let fma = listToFM $ do auf <- aufs return ( A.anr auf, A.name auf ) items <- sequence $ do auf <- aufs return $ io $ Control.Stud_Aufg.DB.get_anr $ A.anr auf let stud_aufg :: FiniteMap ( SNr, ANr ) ( Oks, Nos ) stud_aufg = listToFM $ do its <- items ; it <- its return ( (SA.snr it, SA.anr it) , ( SA.ok it, SA.no it )) let keys = mkSet $ keysFM stud_aufg snrs = smap fst keys anrs = smap snd keys h3 "Gruppen" open btable open row mapM_ plain [ "Nummer", "Bezeichnung", "Referent" ] close -- row sequence_ $ do gnr <- Data.List.nub $ map snd sgs return $ do [ g ] <- io $ Control.Gruppe.DB.get_gnr gnr open row plain $ show gnr plain $ toString $ G.name g plain $ toString $ G.referent g close -- row close -- table h3 "Einsendungen (Ok/No)" let anames = do anr <- setToList anrs return $ case lookupFM fma anr of Just name -> ( if choice == Mandat then take 3 else id ) $ toString name Nothing -> show anr let headings = [ "Matr.-Nr.", "Vorname", "Name", "Gruppe", "total" ] ++ anames open_btable_with_sorter headings sequence_ $ do (snr, gnr) <- sgs return $ do [ stud ] <- io $ Control.Student.DB.get_snr snr let mnr = S.mnr stud vorname = S.vorname stud name = S.name stud open row plain $ toString mnr plain $ toString vorname plain $ toString name plain $ show gnr let shownums = do anr <- setToList $ anrs let result = lookupFM stud_aufg (S.snr stud, anr) return ( case result of Just ( Oks o, Nos n ) -> if choice == Mandat then show o else show (o, n) Nothing -> "-" , case result of Just ( Oks o, _ ) | o > 0 -> 1 _ -> 0 ) plain $ show $ sum $ map snd shownums forM ( map fst shownums ) $ plain close -- row close -- btable
marcellussiegburg/autotool
db/src/Operate/Statistik.hs
gpl-2.0
4,454
74
19
1,445
1,292
694
598
-1
-1
module MuCalc.MuFormula where import Data.Map data MuFormula = Atom String | --Atomic proposition Variable String | --Unbound variable Negation MuFormula | Or MuFormula MuFormula | And MuFormula MuFormula | PossiblyNext String MuFormula | --(E X): If there's an action with that label leading to a state where the formula holds. Mu String MuFormula --Least fixpoint deriving (Show) implies :: MuFormula -> MuFormula -> MuFormula implies p q = Or (Negation p) q iff :: MuFormula -> MuFormula -> MuFormula iff p q = And (implies p q) (implies q p)
johnbcoughlin/mucalc
src/MuCalc/MuFormula.hs
gpl-2.0
634
0
7
178
147
81
66
12
1
module Language.SMTLib2.Pipe.Internals where import Language.SMTLib2.Internals.Backend as B import Language.SMTLib2.Internals.Type --hiding (Constr,Field,Datatype) import qualified Language.SMTLib2.Internals.Type as Type import Language.SMTLib2.Internals.Type.Nat as Type import Language.SMTLib2.Internals.Type.List (List(..)) import qualified Language.SMTLib2.Internals.Type.List as List import Language.SMTLib2.Internals.Expression hiding (Fun,Field,Var,QVar,LVar) import qualified Language.SMTLib2.Internals.Expression as Expr import qualified Language.SMTLib2.Internals.Proof as P import Language.SMTLib2.Strategy as Strat import qualified Data.Text as T import qualified Data.Text.Read as T import Data.Map (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Set as Set import Data.IntMap (IntMap) import qualified Data.IntMap as IMap import Data.Proxy import Data.Typeable import Data.GADT.Compare import Data.GADT.Show #if !MIN_VERSION_base(4,8,0) import Data.Monoid #endif import Data.Foldable (foldlM) import Control.Monad.Except import Data.Traversable import qualified GHC.TypeLits as TL import System.Process import System.IO import qualified Data.ByteString as BS hiding (reverse) import qualified Data.ByteString.Char8 as BS8 import Blaze.ByteString.Builder import Data.Attoparsec.ByteString import qualified Data.AttoLisp as L import qualified Data.Attoparsec.Number as L import Data.Ratio import Control.Monad.Identity import Control.Monad.State data PipeDatatype = forall a. IsDatatype a => PipeDatatype (Proxy a) data SMTPipe = SMTPipe { channelIn :: Handle , channelOut :: Handle , processHandle :: Maybe ProcessHandle , names :: Map String Int , vars :: Map T.Text RevVar , datatypes :: TypeRegistry T.Text T.Text T.Text , interpolationMode :: InterpolationMode } deriving Typeable data RevVar = forall (t::Type). Var !(Repr t) | forall (t::Type). QVar !(Repr t) | forall (arg::[Type]) (t::Type). Fun !(List Repr arg) !(Repr t) | forall (t::Type). FunArg !(Repr t) | forall (t::Type). LVar !(Repr t) data InterpolationMode = Z3Interpolation [T.Text] [T.Text] | MathSATInterpolation type PipeVar = UntypedVar T.Text type PipeFun = UntypedFun T.Text newtype PipeClauseId = PipeClauseId T.Text deriving (Show,Eq,Ord,Typeable) type PipeProofNode = P.Proof L.Lisp (Expr SMTPipe) Int data PipeProof = PipeProof { proofNodes :: Map Int PipeProofNode , proofNode :: Int } instance Eq PipeProof where (==) (PipeProof _ x) (PipeProof _ y) = x == y instance Ord PipeProof where compare (PipeProof _ x) (PipeProof _ y) = compare x y instance Show PipeProof where showsPrec p pr = showParen (p>10) $ showsPrec 0 (proofNode pr) instance GEq (Expr SMTPipe) where geq (PipeExpr e1) (PipeExpr e2) = geq e1 e2 instance GCompare (Expr SMTPipe) where gcompare (PipeExpr e1) (PipeExpr e2) = gcompare e1 e2 instance GShow (Expr SMTPipe) where gshowsPrec = showsPrec instance GetType (Expr SMTPipe) where getType (PipeExpr e) = getType e instance Backend SMTPipe where type SMTMonad SMTPipe = IO newtype Expr SMTPipe t = PipeExpr (Expression PipeVar PipeVar PipeFun PipeVar PipeVar (Expr SMTPipe) t) deriving (Show,Typeable) type Var SMTPipe = PipeVar type QVar SMTPipe = PipeVar type Fun SMTPipe = PipeFun type FunArg SMTPipe = PipeVar type LVar SMTPipe = PipeVar type ClauseId SMTPipe = PipeClauseId type Model SMTPipe = AssignmentModel SMTPipe type Proof SMTPipe = PipeProof setOption opt b = do putRequest b $ renderSetOption opt return ((),b) getInfo info b = do putRequest b (renderGetInfo info) resp <- parseResponse b case info of SMTSolverName -> case resp of L.List [L.Symbol ":name",L.String name] -> return (T.unpack name,b) _ -> error $ "Invalid response to 'get-info' query: "++show resp SMTSolverVersion -> case resp of L.List [L.Symbol ":version",L.String name] -> return (T.unpack name,b) _ -> error $ "Invalid response to 'get-info' query: "++show resp declareVar tp name b = do let (sym,req,nnames) = renderDeclareVar (names b) tp name nb = b { names = nnames , vars = Map.insert sym (Var tp) (vars b) } putRequest nb req return (UntypedVar sym tp,nb) createQVar tp name b = do let name' = case name of Just n -> n Nothing -> "qv" (name'',nb) = genName b name' return (UntypedVar name'' tp,nb { vars = Map.insert name'' (QVar tp) (vars nb) }) createFunArg tp name b = do let name' = case name of Just n -> n Nothing -> "fv" (name'',nb) = genName b name' return (UntypedVar name'' tp,nb { vars = Map.insert name'' (FunArg tp) (vars nb) }) defineVar name (PipeExpr expr) b = do let tp = getType expr (sym,req,nnames) = renderDefineVar (names b) tp name (exprToLisp (datatypes b) expr) nb = b { names = nnames , vars = Map.insert sym (Var tp) (vars b) } putRequest nb req return (UntypedVar sym tp,nb) declareFun arg res name b = do let (sym,req,nnames) = renderDeclareFun (names b) arg res name nb = b { names = nnames , vars = Map.insert sym (Fun arg res) (vars b) } putRequest nb req return (UntypedFun sym arg res,nb) defineFun name arg body b = do let argTp = runIdentity $ List.mapM (return . getType) arg bodyTp = getType body (name',req,nnames) = renderDefineFun (\(UntypedVar n _) -> L.Symbol n) (\(PipeExpr e) -> exprToLisp (datatypes b) e) (names b) name arg body nb = b { names = nnames } putRequest nb req return (UntypedFun name' argTp bodyTp,nb) assert (PipeExpr expr) b = do putRequest b (L.List [L.Symbol "assert" ,exprToLisp (datatypes b) expr]) return ((),b) assertId (PipeExpr expr) b = do let (name,b1) = genName b "cl" putRequest b1 (L.List [L.Symbol "assert" ,L.List [L.Symbol "!" ,exprToLisp (datatypes b) expr ,L.Symbol ":named" ,L.Symbol name]]) return (PipeClauseId name,b1) assertPartition (PipeExpr expr) part b = case interpolationMode b of Z3Interpolation grpA grpB -> do let (name,b1) = genName b "grp" putRequest b1 (L.List [L.Symbol "assert" ,L.List [L.Symbol "!" ,exprToLisp (datatypes b) expr ,L.Symbol ":named" ,L.Symbol name]]) return ((),b1 { interpolationMode = case part of PartitionA -> Z3Interpolation (name:grpA) grpB PartitionB -> Z3Interpolation grpA (name:grpB) }) MathSATInterpolation -> do putRequest b (L.List [L.Symbol "assert" ,L.List [L.Symbol "!" ,exprToLisp (datatypes b) expr ,L.Symbol ":interpolation-group" ,L.Symbol (case part of PartitionA -> "partA" PartitionB -> "partB")]]) return ((),b) getUnsatCore b = do putRequest b (L.List [L.Symbol "get-unsat-core"]) resp <- parseResponse b case resp of L.List names -> do cids <- mapM (\name -> case name of L.Symbol name' -> return $ PipeClauseId name' _ -> error $ "smtlib2: Invalid clause when getting unsatisfiable core: "++show name ) names return (cids,b) _ -> error $ "smtlib2: Invalid response to query for unsatisfiable core: "++show resp checkSat tactic limits b = do putRequest b $ renderCheckSat tactic limits res <- BS.hGetLine (channelOut b) return (case res of "sat" -> Sat "sat\r" -> Sat "unsat" -> Unsat "unsat\r" -> Unsat "unknown" -> Unknown "unknown\r" -> Unknown _ -> error $ "smtlib2: unknown check-sat response: "++show res,b) getValue expr b = do putRequest b (renderGetValue b expr) l <- parseResponse b return (parseGetValue b (getType expr) l,b) getProof b = do putRequest b renderGetProof l <- parseResponse b return (parseGetProof b l,b) analyzeProof b pr = case Map.lookup (proofNode pr) (proofNodes pr) of Just nd -> case nd of P.Rule r args res -> P.Rule (show r) (fmap (\arg -> PipeProof (proofNodes pr) arg) args) res push b = do putRequest b (L.List [L.Symbol "push",L.Number $ L.I 1]) return ((),b) pop b = do putRequest b (L.List [L.Symbol "pop",L.Number $ L.I 1]) return ((),b) getModel b = do putRequest b (L.List [L.Symbol "get-model"]) mdl <- parseResponse b case runExcept $ parseGetModel b mdl of Right mdl' -> return (mdl',b) Left err -> error $ "smtlib2: Unknown get-model response: "++err simplify (PipeExpr expr) b = do putRequest b (L.List [L.Symbol "simplify" ,exprToLisp (datatypes b) expr]) resp <- parseResponse b case runExcept $ lispToExprTyped b (getType expr) resp of Right res -> return (res,b) Left err -> error $ "smtlib2: Unknown simplify response: "++show resp++" ["++err++"]" toBackend expr b = return (PipeExpr expr,b) fromBackend b (PipeExpr expr) = expr interpolate b = do case interpolationMode b of Z3Interpolation grpA grpB -> do putRequest b (L.List [L.Symbol "get-interpolant",getAnd grpA,getAnd grpB]) MathSATInterpolation -> do putRequest b (L.List [L.Symbol "get-interpolant",L.List [L.Symbol "partA"]]) resp <- parseResponse b case runExcept $ lispToExprTyped b BoolRepr resp of Right res -> return (res,b) Left err -> error $ "smtlib2: Unknown get-interpolant response: "++show resp++" ["++err++"]" where getAnd [] = L.Symbol "true" getAnd [x] = L.Symbol x getAnd xs = L.List $ (L.Symbol "and"):fmap L.Symbol xs declareDatatypes coll b = do let (req,nnames,nreg) = renderDeclareDatatype (names b) (datatypes b) coll nb = b { names = nnames , datatypes = nreg } putRequest nb req return ((),nb) exit b = do putRequest b (L.List [L.Symbol "exit"]) hClose (channelIn b) hClose (channelOut b) case processHandle b of Nothing -> return () Just ph -> do terminateProcess ph _ <- waitForProcess ph return () return ((),b) comment msg b = do hPutStrLn (channelIn b) ("; "++msg) return ((),b) builtIn name arg ret b = return (UntypedFun (T.pack name) arg ret,b) applyTactic t b = do putRequest b (renderApplyTactic t) resp <- parseResponse b case runExcept $ parseGoals b resp of Right res -> return (res,b) Left err -> error $ "smtlib2: Unknown 'apply' response: "++show resp++" ["++err++"]" renderDeclareFun :: Map String Int -> List Repr arg -> Repr ret -> Maybe String -> (T.Text,L.Lisp,Map String Int) renderDeclareFun names args ret name = (name'',L.List [L.Symbol "declare-fun" ,L.Symbol name'' ,typeList args ,typeSymbol Set.empty ret],nnames) where name' = case name of Just n -> n Nothing -> "fun" (name'',nnames) = genName' names name' renderDefineFun :: (GetType e,GetType fv) => (forall t. fv t -> L.Lisp) -> (forall t. e t -> L.Lisp) -> Map String Int -> Maybe String -> List fv arg -> e ret -> (T.Text,L.Lisp,Map String Int) renderDefineFun renderFV renderE names name args body = (name'',L.List [L.Symbol "define-fun" ,L.Symbol name'' ,L.List $ mkList renderFV args ,typeSymbol Set.empty (getType body) ,renderE body],nnames) where name' = case name of Just n -> n Nothing -> "fun" (name'',nnames) = genName' names name' mkList :: GetType fv => (forall t. fv t -> L.Lisp) -> List fv ts -> [L.Lisp] mkList _ Nil = [] mkList renderFV (v ::: xs) = (L.List [renderFV v,typeSymbol Set.empty (getType v)]): mkList renderFV xs renderCheckSat :: Maybe Tactic -> CheckSatLimits -> L.Lisp renderCheckSat tactic limits = L.List (if extendedCheckSat then [L.Symbol "check-sat-using" ,case tactic of Just t -> tacticToLisp t Nothing -> L.Symbol "smt"]++ (case limitTime limits of Just t -> [L.Symbol ":timeout" ,L.Number (L.I t)] Nothing -> [])++ (case limitMemory limits of Just m -> [L.Symbol ":max-memory" ,L.Number (L.I m)] Nothing -> []) else [L.Symbol "check-sat"]) where extendedCheckSat = case tactic of Just _ -> True _ -> case limitTime limits of Just _ -> True _ -> case limitMemory limits of Just _ -> True _ -> False renderDeclareDatatype' :: Integer -> [(T.Text,[(T.Text,[(T.Text,L.Lisp)])])] -> L.Lisp renderDeclareDatatype' npar coll = L.List [L.Symbol "declare-datatypes" ,case npar of 0 -> L.Symbol "()" _ -> L.List [L.Symbol $ T.pack $ "a"++show i | i <- [0..npar-1]] ,L.List [ L.List ((L.Symbol name): [L.List ((L.Symbol con): [ L.List [L.Symbol field ,tp] | (field,tp) <- fields ]) | (con,fields) <- cons ]) | (name,cons) <- coll]] renderDeclareDatatype :: Map String Int -> TypeRegistry T.Text T.Text T.Text -> [AnyDatatype] -> (L.Lisp,Map String Int,TypeRegistry T.Text T.Text T.Text) renderDeclareDatatype names reg dts = (renderDeclareDatatype' (case dts of AnyDatatype dt : _ -> naturalToInteger (parameters dt) [] -> 0) str,nnames,nreg) where ((nnames,nreg),str) = mapAccumL mkDt (names,reg) dts mkDt (names,reg) dt'@(AnyDatatype dt) = let (name,names1) = genName' names (datatypeName dt) reg1 = reg { allDatatypes = Map.insert name dt' (allDatatypes reg) , revDatatypes = Map.insert dt' name (revDatatypes reg) } (cons,(names2,reg2)) = runState (List.toList (mkCon dt) (constructors dt)) (names1,reg1) in ((names2,reg2),(name,cons)) mkCon dt con = do (names,reg) <- get let (name,names1) = genName' names (constrName con) reg1 = reg { allConstructors = Map.insert name (AnyConstr dt con) (allConstructors reg) , revConstructors = Map.insert (AnyConstr dt con) name (revConstructors reg) } put (names1,reg1) fs <- List.toList (mkField dt) (fields con) return (name,fs) mkField dt field = do (names,reg) <- get let (name,names1) = genName' names (fieldName field) reg1 = reg { allFields = Map.insert name (AnyField dt field) (allFields reg) , revFields = Map.insert (AnyField dt field) name (revFields reg) } put (names1,reg1) return (name,typeSymbol allTypes (fieldType field)) allParameters :: (forall n. Natural n -> a) -> a allParameters f = case dts of AnyDatatype dt : dts' | all (\(AnyDatatype dt') -> case geq (parameters dt') (parameters dt) of Just Refl -> True Nothing -> False) dts' -> f (parameters dt) _ -> error "Not all datatypes in a cycle share the same parameters." isRecType :: IsDatatype dt => Datatype dt -> Bool isRecType dt = Set.member (datatypeName dt) allTypes allTypes :: Set String allTypes = Set.fromList [ datatypeName dt | AnyDatatype dt <- dts ] renderSetOption :: SMTOption -> L.Lisp renderSetOption (SMTLogic name) = L.List [L.Symbol "set-logic",L.Symbol $ T.pack name] renderSetOption opt = L.List $ [L.Symbol "set-option"]++ (case opt of PrintSuccess v -> [L.Symbol ":print-success" ,L.Symbol $ if v then "true" else "false"] ProduceModels v -> [L.Symbol ":produce-models" ,L.Symbol $ if v then "true" else "false"] B.ProduceProofs v -> [L.Symbol ":produce-proofs" ,L.Symbol $ if v then "true" else "false"] B.ProduceUnsatCores v -> [L.Symbol ":produce-unsat-cores" ,L.Symbol $ if v then "true" else "false"] ProduceInterpolants v -> [L.Symbol ":produce-interpolants" ,L.Symbol $ if v then "true" else "false"]) renderGetInfo :: SMTInfo i -> L.Lisp renderGetInfo SMTSolverName = L.List [L.Symbol "get-info" ,L.Symbol ":name"] renderGetInfo SMTSolverVersion = L.List [L.Symbol "get-info" ,L.Symbol ":version"] renderDeclareVar :: Map String Int -> Repr tp -> Maybe String -> (T.Text,L.Lisp,Map String Int) renderDeclareVar names tp name = (name'',L.List [L.Symbol "declare-fun" ,L.Symbol name'' ,L.Symbol "()" ,typeSymbol Set.empty tp ],nnames) where name' = case name of Just n -> n Nothing -> "var" (name'',nnames) = genName' names name' renderDefineVar :: Map String Int -> Repr t -> Maybe String -> L.Lisp -> (T.Text,L.Lisp,Map String Int) renderDefineVar names tp name lexpr = (name'', L.List [L.Symbol "define-fun" ,L.Symbol name'' ,L.Symbol "()" ,typeSymbol Set.empty tp ,lexpr], nnames) where name' = case name of Just n -> n Nothing -> "var" (name'',nnames) = genName' names name' renderGetValue :: SMTPipe -> Expr SMTPipe t -> L.Lisp renderGetValue b (PipeExpr e) = L.List [L.Symbol "get-value" ,L.List [exprToLisp (datatypes b) e]] parseGetValue :: SMTPipe -> Repr t -> L.Lisp -> Value t parseGetValue b repr (L.List [L.List [_,val]]) = case runExcept $ lispToValue b (Just $ Sort repr) val of Right (AnyValue v) -> case geq repr (valueType v) of Just Refl -> v Nothing -> error $ "smtlib2: Wrong type of returned value." Left err -> error $ "smtlib2: Failed to parse get-value entry: "++show val++" ["++err++"]" parseGetValue _ _ expr = error $ "smtlib2: Failed to parse get-value result: "++show expr renderGetProof :: L.Lisp renderGetProof = L.List [L.Symbol "get-proof"] parseGetProof :: SMTPipe -> L.Lisp -> PipeProof parseGetProof b resp = case runExcept $ parseProof b Map.empty Map.empty Map.empty proof of Right res -> res Left err -> error $ "smtlib2: Failed to parse proof: "++show resp++" ["++err++"]" where proof = case resp of L.List items -> case findProof items of Nothing -> resp Just p -> p _ -> resp findProof [] = Nothing findProof ((L.List [L.Symbol "proof",p]):_) = Just p findProof (x:xs) = findProof xs parseProof :: SMTPipe -> Map T.Text (Expr SMTPipe BoolType) -> Map T.Text Int -> Map Int PipeProofNode -> L.Lisp -> LispParse PipeProof parseProof pipe exprs proofs nodes l = case l of L.List [L.Symbol "let",L.List defs,body] -> do (nexprs,nproofs,nnodes) <- foldlM (\(exprs,proofs,nodes) def -> case def of L.List [L.Symbol name,def'] -> do res <- parseDef exprs proofs nodes def' case res of Left expr -> return (Map.insert name expr exprs,proofs,nodes) Right (proof,nnodes) -> return (exprs,Map.insert name proof proofs,nnodes) ) (exprs,proofs,nodes) defs parseProof pipe nexprs nproofs nnodes body _ -> do (res,nnodes) <- parseDefProof exprs proofs nodes l return (PipeProof nnodes res) where exprParser = pipeParser pipe exprParser' exprs = exprParser { parseRecursive = \_ -> parseDefExpr' exprs } parseDefExpr' :: Map T.Text (Expr SMTPipe BoolType) -> Maybe Sort -> L.Lisp -> (forall tp. Expr SMTPipe tp -> LispParse a) -> LispParse a parseDefExpr' exprs srt l@(L.Symbol name) res = case Map.lookup name exprs of Just def -> res def Nothing -> lispToExprWith (exprParser' exprs) srt l $ \e -> res (PipeExpr e) parseDefExpr' exprs srt l res = lispToExprWith (exprParser' exprs) srt l (res.PipeExpr) parseDefExpr :: Map T.Text (Expr SMTPipe BoolType) -> L.Lisp -> LispParse (Expr SMTPipe BoolType) parseDefExpr exprs l = parseDefExpr' exprs (Just $ Sort BoolRepr) l $ \e -> case getType e of BoolRepr -> return e _ -> throwError "let expression in proof is not bool" parseDefProof exprs proofs nodes (L.List (rule:args)) = do (args',res,nnodes) <- parseArgs nodes args let sz = Map.size nnodes return (sz,Map.insert sz (P.Rule rule args' res) nnodes) where parseArgs nodes [x] = case x of L.List [L.Symbol "~",lhs,rhs] -> do lhs' <- parseDefExpr exprs lhs rhs' <- parseDefExpr exprs rhs return ([],P.EquivSat lhs' rhs',nodes) _ -> do e <- parseDefExpr exprs x return ([],P.ProofExpr e,nodes) parseArgs nodes (x:xs) = do (nd,nodes1) <- parseDefProof exprs proofs nodes x (nds,res,nodes2) <- parseArgs nodes1 xs return (nd:nds,res,nodes2) parseDefProof exprs proofs nodes (L.Symbol sym) = case Map.lookup sym proofs of Just pr -> return (pr,nodes) parseDef exprs proofs nodes l = (fmap Left $ parseDefExpr exprs l) `catchError` (\_ -> fmap Right $ parseDefProof exprs proofs nodes l) parseGetModel :: SMTPipe -> L.Lisp -> LispParse (Model SMTPipe) parseGetModel b (L.List ((L.Symbol "model"):mdl)) = do nb <- foldlM adapt b mdl assign <- mapM (parseAssignment nb) mdl return $ AssignmentModel assign where adapt b (L.List [L.Symbol "define-fun",L.Symbol fname,L.List args,rtp,body]) = case args of [] -> do srt@(Sort tp) <- lispToSort (pipeParser b) rtp return $ b { vars = Map.insert fname (Var tp) (vars b) } _ -> do srt@(Sort tp) <- lispToSort (pipeParser b) rtp withFunList b args $ \b' tps args' -> return $ b { vars = Map.insert fname (Fun tps tp) (vars b) } parseAssignment b (L.List [L.Symbol "define-fun",L.Symbol fname,L.List args,rtp,body]) = case args of [] -> do srt@(Sort tp) <- lispToSort (pipeParser b) rtp expr <- lispToExprTyped b tp body return $ VarAssignment (UntypedVar fname tp) expr _ -> do srt@(Sort tp) <- lispToSort (pipeParser b) rtp withFunList b args $ \b' tps args' -> do body' <- lispToExprTyped b' tp body return $ FunAssignment (UntypedFun fname tps tp) args' body' parseAssignment _ lsp = throwError $ "Invalid model entry: "++show lsp withFunList :: SMTPipe -> [L.Lisp] -> (forall arg. SMTPipe -> List Repr arg -> List PipeVar arg -> LispParse a) -> LispParse a withFunList b [] f = f b Nil Nil withFunList b ((L.List [L.Symbol v,tp]):ls) f = do Sort tp <- lispToSort (pipeParser b) tp withFunList (b { vars = Map.insert v (FunArg tp) (vars b) }) ls $ \b' tps args -> f b' (tp ::: tps) ((UntypedVar v tp) ::: args) withFunList _ lsp _ = throwError $ "Invalid fun args: "++show lsp parseGetModel _ lsp = throwError $ "Invalid model: "++show lsp renderApplyTactic :: Tactic -> L.Lisp renderApplyTactic t = L.List [L.Symbol "apply" ,tacticToLisp t] parseGoals :: SMTPipe -> L.Lisp -> LispParse [[Expr SMTPipe BoolType]] parseGoals pipe (L.List (L.Symbol "goals":goals)) = mapM (\goal -> case goal of L.List (L.Symbol "goal":exprs) -> mapM (lispToExprTyped pipe bool) (stripAttrs exprs) _ -> throwError $ "Cannot parse goal: "++show goal ) goals where stripAttrs :: [L.Lisp] -> [L.Lisp] stripAttrs [] = [] stripAttrs (L.Symbol (T.uncons -> Just (':',_)):_:rest) = stripAttrs rest stripAttrs (x:xs) = x:stripAttrs xs parseGoals _ g = throwError $ "Cannot parse 'apply' response: "++show g data Sort = forall (t :: Type). Sort (Repr t) data Sorts = forall (t :: [Type]). Sorts (List Repr t) data ParsedFunction fun = ParsedFunction { argumentTypeRequired :: Integer -> Bool , getParsedFunction :: [Maybe Sort] -> LispParse (AnyFunction fun) } data AnyExpr e = forall (t :: Type). AnyExpr (e t) instance GShow e => Show (AnyExpr e) where showsPrec p (AnyExpr x) = gshowsPrec p x data LispParser (v :: Type -> *) (qv :: Type -> *) (fun :: ([Type],Type) -> *) (fv :: Type -> *) (lv :: Type -> *) (e :: Type -> *) = LispParser { parseFunction :: forall a. Maybe Sort -> T.Text -> (forall args res. fun '(args,res) -> LispParse a) -> (forall args res. (IsDatatype res) => Type.Datatype res -> Type.Constr res args -> LispParse a) -- constructor -> (forall args res. (IsDatatype res) => Type.Datatype res -> Type.Constr res args -> LispParse a) -- constructor test -> (forall t args res. (IsDatatype t) => Type.Datatype t -> Type.Field t res -> LispParse a) -> LispParse a , parseDatatype :: forall a. T.Text -> (forall dt. IsDatatype dt => Type.Datatype dt -> LispParse a) -> LispParse a , parseVar :: forall a. Maybe Sort -> T.Text -> (forall t. v t -> LispParse a) -> (forall t. qv t -> LispParse a) -> (forall t. fv t -> LispParse a) -> (forall t. lv t -> LispParse a) -> LispParse a , parseRecursive :: forall a. LispParser v qv fun fv lv e -> Maybe Sort -> L.Lisp -> (forall t. e t -> LispParse a) -> LispParse a , registerQVar :: forall (t :: Type). T.Text -> Repr t -> (qv t,LispParser v qv fun fv lv e) , registerLetVar :: forall (t :: Type). T.Text -> Repr t -> (lv t,LispParser v qv fun fv lv e) } type LispParse = Except String -- | Spawn a new SMT solver process and create a pipe to communicate with it. createPipe :: String -- ^ Path to the binary of the SMT solver -> [String] -- ^ Command line arguments to be passed to the SMT solver -> IO SMTPipe createPipe solver args = do let cmd = (proc solver args) { std_in = CreatePipe , std_out = CreatePipe , std_err = Inherit , close_fds = False } (Just hin,Just hout,_,handle) <- createProcess cmd let p0 = SMTPipe { channelIn = hin , channelOut = hout , processHandle = Just handle , names = Map.empty , vars = Map.empty , datatypes = emptyTypeRegistry , interpolationMode = MathSATInterpolation } putRequest p0 (L.List [L.Symbol "get-info" ,L.Symbol ":name"]) resp <- parseResponse p0 case resp of L.List [L.Symbol ":name",L.String name] -> case name of "Z3" -> return $ p0 { interpolationMode = Z3Interpolation [] [] } _ -> return p0 _ -> return p0 -- | Create a SMT pipe by giving the input and output handle. createPipeFromHandle :: Handle -- ^ Input handle -> Handle -- ^ Output handle -> IO SMTPipe createPipeFromHandle hin hout = do return SMTPipe { channelIn = hin , channelOut = hout , processHandle = Nothing , names = Map.empty , vars = Map.empty , datatypes = emptyTypeRegistry , interpolationMode = MathSATInterpolation } lispToExprUntyped :: SMTPipe -> L.Lisp -> (forall (t::Type). Expr SMTPipe t -> LispParse a) -> LispParse a lispToExprUntyped st l res = lispToExprWith (pipeParser st) Nothing l $ \e -> res (PipeExpr e) lispToExprTyped :: SMTPipe -> Repr t -> L.Lisp -> LispParse (Expr SMTPipe t) lispToExprTyped st tp l = lispToExprWith (pipeParser st) (Just (Sort tp)) l $ \e -> case geq tp (getType e) of Just Refl -> return (PipeExpr e) Nothing -> throwError $ show l++" has type "++show (getType e)++", but "++show tp++" was expected." pipeParser :: SMTPipe -> LispParser PipeVar PipeVar PipeFun PipeVar PipeVar (Expr SMTPipe) pipeParser st = parse where parse = LispParser { parseFunction = \srt name fun con test field -> case T.stripPrefix "is-" name of Just con -> case Map.lookup name (allConstructors $ datatypes st) of Just (AnyConstr dt con) -> test dt con _ -> throwError $ "Unknown constructor: "++show name Nothing -> case Map.lookup name (allConstructors $ datatypes st) of Just (AnyConstr dt c) -> con dt c Nothing -> case Map.lookup name (allFields $ datatypes st) of Just (AnyField dt f) -> field dt f Nothing -> case Map.lookup name (vars st) of Just (Fun arg tp) -> fun (UntypedFun name arg tp) _ -> throwError $ "Unknown symbol "++show name , parseDatatype = \name res -> case Map.lookup name (allDatatypes $ datatypes st) of Just (AnyDatatype p) -> res p _ -> throwError $ "Unknown datatype "++show name , parseVar = \srt name v qv fv lv -> case Map.lookup name (vars st) of Just (Var tp) -> v (UntypedVar name tp) Just (QVar tp) -> qv (UntypedVar name tp) Just (FunArg tp) -> fv (UntypedVar name tp) Just (LVar tp) -> lv (UntypedVar name tp) _ -> throwError $ "Unknown variable "++show name , parseRecursive = \parse srt l res -> lispToExprWith parse srt l $ \e -> res (PipeExpr e) , registerQVar = \name tp -> (UntypedVar name tp, pipeParser (st { vars = Map.insert name (QVar tp) (vars st) })) , registerLetVar = \name tp -> (UntypedVar name tp, pipeParser (st { vars = Map.insert name (LVar tp) (vars st) })) } lispToExprWith :: (GShow fun,GShow e,GetFunType fun,GetType e) => LispParser v qv fun fv lv e -> Maybe Sort -> L.Lisp -> (forall (t :: Type). Expression v qv fun fv lv e t -> LispParse a) -> LispParse a lispToExprWith p hint (runExcept . lispToConstant -> Right (AnyValue val)) res = res (Const val) lispToExprWith p hint (L.Symbol sym) res = parseVar p hint sym (res . Expr.Var) (res . Expr.QVar) (res . Expr.FVar) (res . Expr.LVar) `catchError` (\_ -> do parsed <- lispToFunction p hint (L.Symbol sym) AnyFunction f <- getParsedFunction parsed [] case getFunType f of (Nil,_) -> res $ App f Nil _ -> throwError $ "Arguments expected for function "++show sym) lispToExprWith p hint (L.List [L.Symbol "_",L.Symbol "as-array",fsym]) res = do parsed <- lispToFunction p el_hint fsym AnyFunction fun <- getParsedFunction parsed idx_hint res (AsArray fun) where (idx_hint,el_hint) = case hint of Nothing -> ([],Nothing) Just (Sort tp) -> case tp of ArrayRepr args el -> (runIdentity $ List.toList (\t -> return (Just $ Sort t)) args, Just $ Sort el) lispToExprWith p hint (L.List [L.Symbol "forall",L.List args,body]) res = mkQuant p args $ \np args' -> parseRecursive np np (Just (Sort BoolRepr)) body $ \body' -> case getType body' of BoolRepr -> res (Quantification Forall args' body') lispToExprWith p hint (L.List [L.Symbol "exists",L.List args,body]) res = mkQuant p args $ \np args' -> parseRecursive np np (Just (Sort BoolRepr)) body $ \body' -> case getType body' of BoolRepr -> res (Quantification Exists args' body') lispToExprWith p hint (L.List [L.Symbol "let",L.List args,body]) res = mkLet p args $ \np args' -> parseRecursive np np hint body $ \body' -> res (Let args' body') lispToExprWith p hint (L.List [L.Symbol "as",expr,tp]) res = do srt <- lispToSort p tp lispToExprWith p (Just srt) expr res lispToExprWith p hint (L.List (fun:args)) res = do parsed <- lispToFunction p hint fun args' <- matchList (argumentTypeRequired parsed) 0 args let hints = fmap (\arg -> case arg of Left _ -> Nothing Right (AnyExpr e) -> Just $ Sort (getType e) ) args' AnyFunction fun' <- getParsedFunction parsed hints let (argTps,ret) = getFunType fun' args'' <- catchError (makeList p argTps args') $ \err -> throwError $ "While parsing arguments of function: "++ show fun'++": "++err res $ App fun' args'' where matchList _ _ [] = return [] matchList f i (e:es) = if f i then parseRecursive p p Nothing e (\e' -> do rest <- matchList f (i+1) es return $ (Right (AnyExpr e')):rest) else do rest <- matchList f (i+1) es return $ (Left e):rest makeList :: (GShow e,GetType e) => LispParser v qv fun fv lv e -> List Repr arg -> [Either L.Lisp (AnyExpr e)] -> LispParse (List e arg) makeList _ Nil [] = return Nil makeList _ Nil _ = throwError $ "Too many arguments to function." makeList p (tp ::: args) (e:es) = case e of Right (AnyExpr e') -> do r <- case geq tp (getType e') of Just Refl -> return e' Nothing -> throwError $ "Argument "++gshowsPrec 11 e' ""++" has wrong type." rs <- makeList p args es return (r ::: rs) Left l -> parseRecursive p p (Just $ Sort tp) l $ \e' -> do r <- case geq tp (getType e') of Just Refl -> return e' Nothing -> throwError $ "Argument "++gshowsPrec 11 e' ""++" has wrong type." rs <- makeList p args es return (r ::: rs) makeList _ (_ ::: _) [] = throwError $ "Not enough arguments to function." lispToExprWith _ _ lsp _ = throwError $ "Invalid SMT expression: "++show lsp mkQuant :: LispParser v qv fun fv lv e -> [L.Lisp] -> (forall arg. LispParser v qv fun fv lv e -> List qv arg -> LispParse a) -> LispParse a mkQuant p [] f = f p Nil mkQuant p ((L.List [L.Symbol name,sort]):args) f = do Sort srt <- lispToSort p sort let (qvar,np) = registerQVar p name srt mkQuant np args $ \p args -> f p (qvar ::: args) mkQuant _ lsp _ = throwError $ "Invalid forall/exists parameter: "++show lsp mkLet :: GetType e => LispParser v qv fun fv lv e -> [L.Lisp] -> (LispParser v qv fun fv lv e -> [LetBinding lv e] -> LispParse a) -> LispParse a mkLet p [] f = f p [] mkLet p ((L.List [L.Symbol name,expr]):args) f = parseRecursive p p Nothing expr $ \expr' -> do let (lvar,np) = registerLetVar p name (getType expr') mkLet np args $ \p args -> f p ((LetBinding lvar expr'):args) mkLet _ lsp _ = throwError $ "Invalid let parameter: "++show lsp withEq :: Repr t -> [b] -> (forall n. Natural n -> List Repr (AllEq t n) -> a) -> a withEq tp [] f = f Zero Nil withEq tp (_:xs) f = withEq tp xs $ \n args -> f (Succ n) (tp ::: args) lispToFunction :: LispParser v qv fun fv lv e -> Maybe Sort -> L.Lisp -> LispParse (ParsedFunction fun) lispToFunction _ _ (L.Symbol "=") = return $ ParsedFunction (==0) (\args -> case args of Just (Sort tp):_ -> withEq tp args $ \n args -> return $ AnyFunction (Eq tp n) _ -> throwError $ "Cannot derive type of = parameters.") lispToFunction _ _ (L.Symbol "distinct") = return $ ParsedFunction (==0) (\args -> case args of Just (Sort tp):_ -> withEq tp args $ \n args' -> return $ AnyFunction (Distinct tp n) _ -> throwError $ "Cannot derive type of \"distinct\" parameters.") lispToFunction rf sort (L.List [L.Symbol "_",L.Symbol "map",sym]) = do f <- lispToFunction rf sort' sym let reqList 0 = case idx' of Nothing -> True Just _ -> argumentTypeRequired f 0 reqList n = argumentTypeRequired f n fun args = do Sorts pidx <- case idx' of Just srts -> return srts Nothing -> case args of Just srt:_ -> case asArraySort srt of Just (idx,_) -> return idx Nothing -> throwError $ "Could not derive type of the array index in map function." _ -> throwError $ "Could not derive type of the array index in map function." argSorts <- mapM (\prx -> case prx of Nothing -> return Nothing Just srt -> do (_,elsrt) <- case asArraySort srt of Just srt' -> return srt' Nothing -> throwError $ "Argument to map function isn't an array." return (Just elsrt) ) args fun' <- getParsedFunction f argSorts return $ mkMap pidx fun' return (ParsedFunction reqList fun) where (sort',idx') = case sort of Just (Sort tp) -> case tp of ArrayRepr idx el -> (Just (Sort el), Just (Sorts idx)) _ -> (Nothing,Nothing) _ -> (Nothing,Nothing) lispToFunction _ _ (L.Symbol ">=") = lispToOrdFunction Ge lispToFunction _ _ (L.Symbol ">") = lispToOrdFunction Gt lispToFunction _ _ (L.Symbol "<=") = lispToOrdFunction Le lispToFunction _ _ (L.Symbol "<") = lispToOrdFunction Lt lispToFunction _ sort (L.Symbol "+") = lispToArithFunction sort Plus lispToFunction _ sort (L.Symbol "*") = lispToArithFunction sort Mult lispToFunction _ sort (L.Symbol "-") = lispToArithFunction sort Minus lispToFunction _ _ (L.Symbol "div") = return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (ArithIntBin Div)) lispToFunction _ _ (L.Symbol "mod") = return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (ArithIntBin Mod)) lispToFunction _ _ (L.Symbol "rem") = return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (ArithIntBin Rem)) lispToFunction _ _ (L.Symbol "^") = return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (ArithIntBin Exp)) lispToFunction _ _ (L.Symbol "/") = return $ ParsedFunction (const False) (\_ -> return $ AnyFunction Divide) lispToFunction _ sort (L.Symbol "abs") = case sort of Just (Sort tp) -> case tp of IntRepr -> return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (Abs NumInt)) RealRepr -> return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (Abs NumReal)) exp -> throwError $ "abs function can't have type "++show exp Nothing -> return $ ParsedFunction (==0) $ \args -> case args of [Just (Sort tp)] -> case tp of IntRepr -> return $ AnyFunction (Abs NumInt) RealRepr -> return $ AnyFunction (Abs NumReal) srt -> throwError $ "abs can't take argument of type "++show srt _ -> throwError $ "abs function takes exactly one argument." lispToFunction _ _ (L.Symbol "not") = return $ ParsedFunction (const False) (\_ -> return $ AnyFunction Not) lispToFunction _ _ (L.Symbol "and") = return $ lispToLogicFunction And lispToFunction _ _ (L.Symbol "or") = return $ lispToLogicFunction Or lispToFunction _ _ (L.Symbol "xor") = return $ lispToLogicFunction XOr lispToFunction _ _ (L.Symbol "=>") = return $ lispToLogicFunction Implies lispToFunction _ _ (L.List [L.Symbol "_", L.Symbol "at-least", L.Number (L.I n)]) = return $ lispToLogicFunction (AtLeast n) lispToFunction _ _ (L.List [L.Symbol "_", L.Symbol "at-most", L.Number (L.I n)]) = return $ lispToLogicFunction (AtMost n) lispToFunction _ _ (L.Symbol "to_real") = return $ ParsedFunction (const False) (\_ -> return $ AnyFunction ToReal) lispToFunction _ _ (L.Symbol "to_int") = return$ ParsedFunction (const False) (\_ -> return $ AnyFunction ToInt) lispToFunction _ sort (L.Symbol "ite") = case sort of Just (Sort tp) -> return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (ITE tp)) Nothing -> return $ ParsedFunction (==1) $ \args -> case args of [_,Just (Sort tp),_] -> return $ AnyFunction (ITE tp) _ -> throwError $ "Invalid arguments to ite function." lispToFunction _ _ (L.Symbol "bvule") = return $ lispToBVCompFunction BVULE lispToFunction _ _ (L.Symbol "bvult") = return $ lispToBVCompFunction BVULT lispToFunction _ _ (L.Symbol "bvuge") = return $ lispToBVCompFunction BVUGE lispToFunction _ _ (L.Symbol "bvugt") = return $ lispToBVCompFunction BVUGT lispToFunction _ _ (L.Symbol "bvsle") = return $ lispToBVCompFunction BVSLE lispToFunction _ _ (L.Symbol "bvslt") = return $ lispToBVCompFunction BVSLT lispToFunction _ _ (L.Symbol "bvsge") = return $ lispToBVCompFunction BVSGE lispToFunction _ _ (L.Symbol "bvsgt") = return $ lispToBVCompFunction BVSGT lispToFunction _ sort (L.Symbol "bvadd") = lispToBVBinFunction sort BVAdd lispToFunction _ sort (L.Symbol "bvsub") = lispToBVBinFunction sort BVSub lispToFunction _ sort (L.Symbol "bvmul") = lispToBVBinFunction sort BVMul lispToFunction _ sort (L.Symbol "bvurem") = lispToBVBinFunction sort BVURem lispToFunction _ sort (L.Symbol "bvsrem") = lispToBVBinFunction sort BVSRem lispToFunction _ sort (L.Symbol "bvudiv") = lispToBVBinFunction sort BVUDiv lispToFunction _ sort (L.Symbol "bvsdiv") = lispToBVBinFunction sort BVSDiv lispToFunction _ sort (L.Symbol "bvshl") = lispToBVBinFunction sort BVSHL lispToFunction _ sort (L.Symbol "bvlshr") = lispToBVBinFunction sort BVLSHR lispToFunction _ sort (L.Symbol "bvashr") = lispToBVBinFunction sort BVASHR lispToFunction _ sort (L.Symbol "bvxor") = lispToBVBinFunction sort BVXor lispToFunction _ sort (L.Symbol "bvand") = lispToBVBinFunction sort BVAnd lispToFunction _ sort (L.Symbol "bvor") = lispToBVBinFunction sort BVOr lispToFunction _ sort (L.Symbol "bvnot") = lispToBVUnFunction sort BVNot lispToFunction _ sort (L.Symbol "bvneg") = lispToBVUnFunction sort BVNeg lispToFunction _ _ (L.Symbol "select") = return $ ParsedFunction (==0) (\args -> case args of Just (Sort arr):_ -> case arr of ArrayRepr idx el -> return $ AnyFunction (Select idx el) srt -> throwError $ "Invalid argument type to select function: "++show srt _ -> throwError $ "Invalid arguments to select function.") lispToFunction _ sort (L.Symbol "store") = case sort of Just (Sort srt) -> case srt of ArrayRepr idx el -> return (ParsedFunction (const False) (\_ -> return $ AnyFunction (Store idx el))) srt' -> throwError $ "Invalid argument types to store function: "++show srt' Nothing -> return $ ParsedFunction (==0) (\args -> case args of Just (Sort arr):_ -> case arr of ArrayRepr idx el -> return $ AnyFunction (Store idx el) srt -> throwError $ "Invalid first argument type to store function: "++show srt _ -> throwError $ "Invalid arguments to store function.") lispToFunction r sort (L.List [L.Symbol "as",L.Symbol "const",sig]) = do Sort rsig <- case sort of Just srt -> return srt Nothing -> lispToSort r sig case rsig of ArrayRepr idx el -> return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (ConstArray idx el)) _ -> throwError $ "Invalid signature for (as const ...) function." lispToFunction _ sort (L.Symbol "concat") = return $ ParsedFunction (const True) (\args -> case args of [Just (Sort tp1),Just (Sort tp2)] -> case (tp1,tp2) of (BitVecRepr sz1,BitVecRepr sz2) -> return $ AnyFunction (Concat sz1 sz2) _ -> throwError $ "Invalid argument types to concat function." _ -> throwError $ "Wrong number of arguments to concat function.") lispToFunction _ sort (L.List [L.Symbol "_",L.Symbol "extract",L.Number (L.I end),L.Number (L.I start)]) = return $ ParsedFunction (==0) (\args -> case args of [Just (Sort srt)] -> case srt of BitVecRepr size | start <= end && end <= bwSize size -> case TL.someNatVal start of Just (TL.SomeNat start') -> case TL.someNatVal (end-start+1) of Just (TL.SomeNat len') -> return $ AnyFunction (Extract size (bw start') (bw len')) | otherwise -> throwError $ "Invalid extract parameters." srt -> throwError $ "Invalid type of extract argument: "++show srt _ -> throwError $ "Wrong number of arguments to extract function.") lispToFunction _ sort (L.List [L.Symbol "_",L.Symbol "divisible",L.Number (L.I div)]) = return $ ParsedFunction (const False) (\_ -> return $ AnyFunction (Divisible div)) lispToFunction _ sort (L.List (L.Symbol "_": L.Symbol (T.stripPrefix "pb" -> Just op): coeff)) = do coeffNum <- mapM (\c -> case c of L.Number (L.I c') -> return c' _ -> throwError $ "Invalid pseudo-boolean coefficient: "++show c ) coeff rop <- case op of "eq" -> return PBEq "le" -> return PBLe "ge" -> return PBGe _ -> throwError $ "Invalid pseudo-boolean operator: "++show op case coeffNum of [] -> throwError $ "Invalid number of pseudo-boolean coefficients" res:coeff' -> List.reifyCList coeff' $ \rcoeff -> return $ ParsedFunction (const False) (\_ -> return $ AnyFunction $ PseudoBoolean rop rcoeff res) lispToFunction rf sort (L.List [sym,lispToList -> Just sig,tp]) = do nsort <- lispToSort rf tp fun <- lispToFunction rf (Just nsort) sym rsig <- lispToSorts rf sig $ \sig' -> return $ runIdentity $ List.toList (\tp -> return $ Just (Sort tp)) sig' return $ ParsedFunction (const False) (\_ -> getParsedFunction fun rsig) lispToFunction rf sort (L.Symbol name) = parseFunction rf sort name (p . Expr.Fun) getCon getTest getField where p f = return $ ParsedFunction (const False) (const (return $ AnyFunction f)) getCon :: IsDatatype dt => Datatype dt -> Constr dt csig -> LispParse (ParsedFunction fun) getCon (dt :: Datatype dt) con = return $ ParsedFunction (case sort of Just _ -> const False Nothing -> \i -> List.indexDyn (fields con) i $ \f -> not $ Set.null $ containedParameter (fieldType f) Set.empty) (\argSorts -> case sort of Just (Sort (DataRepr (dt'::Datatype dt') par)) -> case eqT :: Maybe (dt :~: dt') of Nothing -> throwError "Type mismatch" Just Refl -> return $ AnyFunction $ Expr.Constructor dt par con Nothing -> case inferArgs argSorts (fields con) IMap.empty of Nothing -> throwError "Cannot infer parameter type" Just mp -> case fullArgs 0 (IMap.toList mp) (parameters dt) $ \par -> AnyFunction $ Expr.Constructor dt par con of Nothing -> throwError "Cannot infer parameter type" Just res -> return res) getTest :: IsDatatype dt => Datatype dt -> Constr dt csig -> LispParse (ParsedFunction fun) getTest (dt :: Datatype dt) con = return $ ParsedFunction (\i -> i==0 && (case parameters dt of Zero -> False _ -> True)) (\argSorts -> case parameters dt of Zero -> return $ AnyFunction $ Expr.Test dt Nil con _ -> case argSorts of [Just (Sort (DataRepr (dt'::Datatype dt') par))] -> case eqT :: Maybe (dt :~: dt') of Nothing -> throwError "Type mismatch" Just Refl -> return $ AnyFunction $ Expr.Test dt par con) getField :: IsDatatype dt => Datatype dt -> Field dt tp -> LispParse (ParsedFunction fun) getField (dt::Datatype dt) f = return $ ParsedFunction (\i -> i==0 && (case parameters dt of Zero -> False _ -> True)) (\argSorts -> case parameters dt of Zero -> return $ AnyFunction $ Expr.Field dt Nil f _ -> case argSorts of [Just (Sort (DataRepr (dt'::Datatype dt') par))] -> case eqT :: Maybe (dt :~: dt') of Nothing -> throwError "Type mismatch" Just Refl -> return $ AnyFunction $ Expr.Field dt par f _ -> throwError "Cannot infer field type") inferArgs :: IsDatatype dt => [Maybe Sort] -> List (Field dt) tps -> IntMap Sort -> Maybe (IntMap Sort) inferArgs [] Nil mp = Just mp inferArgs (Nothing : args) (_ ::: fs) mp = inferArgs args fs mp inferArgs (Just (Sort arg) : args) (f ::: fs) mp = do mp1 <- typeInference arg (fieldType f) (\p tp cmp -> let p' = fromInteger $ naturalToInteger p in case IMap.lookup p' cmp of Nothing -> Just $ IMap.insert p' (Sort tp) cmp Just (Sort tp') -> do Refl <- geq tp tp' return cmp) mp inferArgs args fs mp1 lispToFunction _ _ lsp = throwError $ "Unknown function: "++show lsp fullArgs :: Int -> [(Int,Sort)] -> Natural len -> (forall tps. (List.Length tps ~ len) => List Repr tps -> a) -> Maybe a fullArgs cpos [] Zero f = Just $ f Nil fullArgs cpos ((pos,Sort srt):srts) (Succ n) f = if cpos==pos then fullArgs (cpos+1) srts n $ \lst -> f (srt ::: lst) else Nothing fullArgs _ _ _ _ = Nothing lispToOrdFunction :: OrdOp -> LispParse (ParsedFunction fun) lispToOrdFunction op = return (ParsedFunction (==0) (\argSrt -> case argSrt of (Just (Sort srt)):_ -> case srt of IntRepr -> return $ AnyFunction (Ord NumInt op) RealRepr -> return $ AnyFunction (Ord NumReal op) srt' -> throwError $ "Invalid argument to "++show op++" function: "++show srt' _ -> throwError $ "Wrong number of arguments to "++show op++" function.")) lispToArithFunction :: Maybe Sort -> ArithOp -> LispParse (ParsedFunction fun) lispToArithFunction sort op = case sort of Just (Sort tp) -> case tp of IntRepr -> return (ParsedFunction (const False) (\args -> withEq IntRepr args $ \n _ -> return $ AnyFunction (Arith NumInt op n))) RealRepr -> return (ParsedFunction (const False) (\args -> withEq RealRepr args $ \n _ -> return $ AnyFunction (Arith NumReal op n))) srt -> throwError $ "Invalid type of "++show op++" function: "++show srt Nothing -> return (ParsedFunction (==0) (\argSrt -> case argSrt of (Just (Sort srt)):_ -> case srt of IntRepr -> withEq IntRepr argSrt $ \n args -> return $ AnyFunction (Arith NumInt op n) RealRepr -> withEq RealRepr argSrt $ \n args -> return $ AnyFunction (Arith NumReal op n) srt' -> throwError $ "Wrong argument type to "++show op++" function: "++show srt' _ -> throwError $ "Wrong number of arguments to "++show op++" function.")) lispToLogicFunction :: LogicOp -> ParsedFunction fun lispToLogicFunction op = ParsedFunction (const False) (\args -> withEq BoolRepr args $ \n args -> return $ AnyFunction (Logic op n)) lispToBVCompFunction :: BVCompOp -> ParsedFunction fun lispToBVCompFunction op = ParsedFunction (==0) (\args -> case args of [Just (Sort srt),_] -> case srt of BitVecRepr bw -> return $ AnyFunction (BVComp op bw) srt -> throwError $ "Invalid argument type to "++show op++" function: "++show srt _ -> throwError $ "Wrong number of arguments to "++show op++" function.") lispToBVBinFunction :: Maybe Sort -> BVBinOp -> LispParse (ParsedFunction fun) lispToBVBinFunction (Just (Sort srt)) op = case srt of BitVecRepr bw -> return $ ParsedFunction (const False) $ \_ -> return $ AnyFunction (BVBin op bw) srt' -> throwError $ "Invalid argument type to "++show op++" function: "++show srt' lispToBVBinFunction Nothing op = return $ ParsedFunction (==0) $ \args -> case args of [Just (Sort srt),_] -> case srt of BitVecRepr bw -> return $ AnyFunction (BVBin op bw) srt' -> throwError $ "Invalid argument type to "++show op++" function: "++show srt' _ -> throwError $ "Wrong number of arguments to "++show op++" function." lispToBVUnFunction :: Maybe Sort -> BVUnOp -> LispParse (ParsedFunction fun) lispToBVUnFunction (Just (Sort srt)) op = case srt of BitVecRepr bw -> return $ ParsedFunction (const False) $ \_ -> return $ AnyFunction (BVUn op bw) srt' -> throwError $ "Invalid argument type to "++show op++" function: "++show srt' lispToBVUnFunction Nothing op = return $ ParsedFunction (==0) $ \args -> case args of [Just (Sort srt)] -> case srt of BitVecRepr bw -> return $ AnyFunction (BVUn op bw) srt' -> throwError $ "Invalid argument type to "++show op++" function: "++show srt' _ -> throwError $ "Wrong number of arguments to "++show op++" function." mkMap :: List Repr idx -> AnyFunction fun -> AnyFunction fun mkMap idx (AnyFunction f) = AnyFunction (Map idx f) asArraySort :: Sort -> Maybe (Sorts,Sort) asArraySort (Sort tp) = case tp of ArrayRepr idx el -> return (Sorts idx,Sort el) _ -> Nothing lispToList :: L.Lisp -> Maybe [L.Lisp] lispToList (L.Symbol "()") = Just [] lispToList (L.List lst) = Just lst lispToList _ = Nothing lispToSort :: LispParser v qv fun fv lv e -> L.Lisp -> LispParse Sort lispToSort _ (L.Symbol "Bool") = return (Sort BoolRepr) lispToSort _ (L.Symbol "Int") = return (Sort IntRepr) lispToSort _ (L.Symbol "Real") = return (Sort RealRepr) lispToSort r (L.List ((L.Symbol "Array"):tps)) = do Sort rtp' <- lispToSort r rtp lispToSorts r idx (\idx' -> return $ Sort (ArrayRepr idx' rtp')) where (idx,rtp) = splitLast tps splitLast [x] = ([],x) splitLast (x:xs) = let (xs',y') = splitLast xs in (x:xs',y') lispToSort _ (L.List [L.Symbol "_",L.Symbol "BitVec",L.Number (L.I n)]) = case TL.someNatVal n of Just (TL.SomeNat w) -> return (Sort (BitVecRepr (bw w))) lispToSort r (L.Symbol name) = parseDatatype r name $ \dt -> case geq (parameters dt) Zero of Just Refl -> return $ Sort (DataRepr dt Nil) Nothing -> throwError $ "Wrong sort for type "++show name lispToSort r (L.List (L.Symbol name:args)) = parseDatatype r name $ \dt -> lispToSorts r args $ \args' -> case geq (List.length args') (parameters dt) of Just Refl -> return $ Sort (DataRepr dt args') Nothing -> throwError $ "Wrong number of arguments for type "++show name lispToSort _ lsp = throwError $ "Invalid SMT type: "++show lsp lispToSorts :: LispParser v qv fun fv lv e -> [L.Lisp] -> (forall (arg :: [Type]). List Repr arg -> LispParse a) -> LispParse a lispToSorts _ [] f = f Nil lispToSorts r (x:xs) f = do Sort tp <- lispToSort r x lispToSorts r xs $ \tps -> f (tp ::: tps) lispToValue :: SMTPipe -> Maybe Sort -> L.Lisp -> LispParse AnyValue lispToValue b hint l = case runExcept $ lispToConstant l of Right r -> return r Left e -> lispToConstrConstant b hint l lispToConstant :: L.Lisp -> LispParse AnyValue lispToConstant (L.Symbol "true") = return (AnyValue (BoolValue True)) lispToConstant (L.Symbol "false") = return (AnyValue (BoolValue False)) lispToConstant (lispToNumber -> Just n) = return (AnyValue (IntValue n)) lispToConstant (lispToReal -> Just n) = return (AnyValue (RealValue n)) lispToConstant (lispToBitVec -> Just (val,sz)) = case TL.someNatVal sz of Just (TL.SomeNat w) -> return (AnyValue (BitVecValue val (bw w))) lispToConstant l = throwError $ "Invalid constant "++show l lispToConstrConstant :: SMTPipe -> Maybe Sort -> L.Lisp -> LispParse AnyValue lispToConstrConstant b hint sym = do (constr,args) <- case sym of L.Symbol s -> return (s,[]) L.List ((L.Symbol s):args) -> return (s,args) _ -> throwError $ "Invalid constant: "++show sym case Map.lookup constr (allConstructors $ datatypes b) of Just (AnyConstr (dt::Datatype dt) con) -> makeList (case hint of Just (Sort (DataRepr dt' par)) -> IMap.fromList $ runIdentity $ List.toListIndex (\i srt -> return (fromInteger $ naturalToInteger i, Sort srt)) par Nothing -> IMap.empty) (fields con) args $ \par rargs -> case fullArgs 0 (IMap.toList par) (parameters dt) $ \rpar -> case instantiate (runIdentity $ List.mapM (return.fieldType) (fields con)) rpar of (tsig,Refl) -> do Refl <- geq tsig (runIdentity $ List.mapM (return.getType) rargs) return $ AnyValue $ DataValue $ construct rpar con rargs of Just (Just res) -> return res _ -> throwError "Type error in constructor" Nothing -> throwError $ "Invalid constructor "++show constr where makeList :: IsDatatype dt => IntMap Sort -> List (Type.Field dt) arg -> [L.Lisp] -> (forall narg. List.Length arg ~ List.Length narg => IntMap Sort -> List Value narg -> LispParse a) -> LispParse a makeList par Nil [] res = res par Nil makeList _ Nil _ _ = throwError $ "Too many arguments to constructor." makeList par (f ::: fs) (l:ls) res = partialInstantiation (fieldType f) (\n g -> do Sort parTp <- IMap.lookup (fromInteger $ naturalToInteger n) par return $ g parTp) $ \ftp -> do AnyValue v <- lispToValue b (Just $ Sort ftp) l case typeInference ftp (valueType v) (\pos ptp cpar -> let pos' = fromInteger $ naturalToInteger pos in case IMap.lookup pos' cpar of Just (Sort ptp') -> case geq ptp ptp' of Just Refl -> return cpar Nothing -> Nothing Nothing -> return $ IMap.insert pos' (Sort ptp) cpar) par of Nothing -> throwError "Type error in constructor arguments." Just npar -> makeList npar fs ls $ \rpar rest -> res rpar (v ::: rest) makeList _ (_ ::: _) [] _ = throwError $ "Not enough arguments to constructor." lispToNumber :: L.Lisp -> Maybe Integer lispToNumber (L.Number (L.I n)) = Just n lispToNumber (L.List [L.Symbol "-",n]) = do n' <- lispToNumber n return (negate n') lispToNumber _ = Nothing lispToReal :: L.Lisp -> Maybe Rational lispToReal (L.Number (L.D n)) = Just $ toRational n lispToReal (L.Number (L.I n)) = Just $ fromInteger n lispToReal (L.List [L.Symbol "/",v1,v2]) = do r1 <- lispToReal v1 r2 <- lispToReal v2 return $ r1 / r2 lispToReal (L.List [L.Symbol "-",v]) = do r <- lispToReal v return $ -r lispToReal _ = Nothing lispToBitVec :: L.Lisp -> Maybe (Integer,Integer) lispToBitVec (L.List [L.Symbol "_",L.Symbol (T.stripPrefix "bv" -> Just val),L.Number (L.I sz)]) = case T.decimal val of Right (rval,"") -> Just (rval,sz) _ -> Nothing lispToBitVec (L.Symbol (T.stripPrefix "#x" -> Just bv)) = case T.hexadecimal bv of Right (rbv,"") -> Just (rbv,(fromIntegral $ T.length bv)*4) _ -> Nothing lispToBitVec (L.Symbol (T.stripPrefix "#b" -> Just bv)) | T.all (\c -> c=='0' || c=='1') bv = Just (T.foldl (\v c -> case c of '0' -> v*2 '1' -> v*2+1) 0 bv, fromIntegral $ T.length bv) | otherwise = Nothing lispToBitVec _ = Nothing exprToLisp :: TypeRegistry T.Text T.Text T.Text -> Expression PipeVar PipeVar PipeFun PipeVar PipeVar (Expr SMTPipe) t -> L.Lisp exprToLisp reg = runIdentity . exprToLispWith (\(UntypedVar v _) -> return $ L.Symbol v) (\(UntypedVar v _) -> return $ L.Symbol v) (\(UntypedFun v _ _) -> return $ L.Symbol v) (\dt con -> case Map.lookup (AnyConstr dt con) (revConstructors reg) of Just sym -> return $ L.Symbol sym) (\dt con -> case Map.lookup (AnyConstr dt con) (revConstructors reg) of Just sym -> return $ L.Symbol $ T.append "is-" sym) (\dt field -> case Map.lookup (AnyField dt field) (revFields reg) of Just sym -> return $ L.Symbol sym) (\(UntypedVar v _) -> return $ L.Symbol v) (\(UntypedVar v _) -> return $ L.Symbol v) (\(PipeExpr v) -> return $ exprToLisp reg v) exprToLispWith :: (Monad m,GetType v,GetType qv,GetType fv,GetType lv,GetFunType fun,GetType e) => (forall (t' :: Type). v t' -> m L.Lisp) -- ^ variables -> (forall (t' :: Type). qv t' -> m L.Lisp) -- ^ quantified variables -> (forall (arg :: [Type]) (res :: Type). fun '(arg,res) -> m L.Lisp) -- ^ functions -> (forall (arg :: [Type]) (dt :: [Type] -> (Type -> *) -> *). IsDatatype dt => Datatype dt -> Type.Constr dt arg -> m L.Lisp) -- ^ constructor -> (forall (arg :: [Type]) (dt :: [Type] -> (Type -> *) -> *). IsDatatype dt => Datatype dt -> Type.Constr dt arg -> m L.Lisp) -- ^ constructor tests -> (forall (dt :: [Type] -> (Type -> *) -> *) (res :: Type). IsDatatype dt => Datatype dt -> Type.Field dt res -> m L.Lisp) -- ^ field accesses -> (forall t. fv t -> m L.Lisp) -- ^ function variables -> (forall t. lv t -> m L.Lisp) -- ^ let variables -> (forall (t' :: Type). e t' -> m L.Lisp) -- ^ sub expressions -> Expression v qv fun fv lv e t -> m L.Lisp exprToLispWith f _ _ _ _ _ _ _ _ (Expr.Var v) = f v exprToLispWith _ f _ _ _ _ _ _ _ (Expr.QVar v) = f v exprToLispWith _ _ _ _ _ _ f _ _ (Expr.FVar v) = f v exprToLispWith _ _ _ _ _ _ _ f _ (Expr.LVar v) = f v -- This is a special case because the argument order is different exprToLispWith _ _ f g h i _ _ j (Expr.App (Store _ _) (arr ::: val ::: idx)) = do arr' <- j arr idx' <- List.toList j idx val' <- j val return $ L.List ((L.Symbol "store"):arr':idx'++[val']) exprToLispWith _ _ f g h i _ _ j e@(Expr.App fun args) = do let needAs = case fun of Constructor dt par con -> not $ determines dt con _ -> False args' <- List.toList j args sym <- functionSymbol f g h i fun let c = case args' of [] -> sym _ -> L.List $ sym:args' rc = if needAs then L.List [L.Symbol "as",c,typeSymbol Set.empty (getType e)] else c return rc exprToLispWith _ _ _ f _ _ _ _ _ (Expr.Const val) = valueToLisp f val exprToLispWith _ _ f g h i _ _ _ (Expr.AsArray fun) = do sym <- functionSymbolWithSig f g h i fun return $ L.List [L.Symbol "_" ,L.Symbol "as-array" ,sym] exprToLispWith _ f _ _ _ _ _ _ g (Expr.Quantification q args body) = do bind <- List.toList (\arg -> do sym <- f arg return $ L.List [sym,typeSymbol Set.empty $ getType arg] ) args body' <- g body return $ L.List [L.Symbol (case q of Expr.Forall -> "forall" Expr.Exists -> "exists") ,L.List bind ,body'] exprToLispWith _ _ _ _ _ _ _ f g (Expr.Let args body) = do binds <- mapM (\(LetBinding v e) -> do sym <- f v expr <- g e return $ L.List [sym,expr] ) args body' <- g body return $ L.List [L.Symbol "let" ,L.List binds ,body'] valueToLisp :: Monad m => (forall arg tp. (IsDatatype tp) => Datatype tp -> Type.Constr tp arg -> m L.Lisp) -> Value t -> m L.Lisp valueToLisp _ (BoolValue True) = return $ L.Symbol "true" valueToLisp _ (BoolValue False) = return $ L.Symbol "false" valueToLisp _ (IntValue n) = return $ numToLisp n valueToLisp _ (RealValue n) = return $ L.List [L.Symbol "/" ,numToLisp $ numerator n ,numToLisp $ denominator n] valueToLisp _ (BitVecValue n bw) = return $ L.List [L.Symbol "_" ,L.Symbol (T.pack $ "bv"++show rn) ,L.Number $ L.I bw'] where bw' = bwSize bw rn = n `mod` 2^bw' valueToLisp f v@(DataValue val) = do let (dt,par) = datatypeGet val case deconstruct val of ConApp { constructor = con , arguments = args } -> do let needAs = not $ determines dt con con' <- f dt con args' <- List.toList (valueToLisp f) args let c = case args' of [] -> con' xs -> L.List (con' : xs) rc = if needAs then L.List [L.Symbol "as",c,typeSymbol Set.empty (getType v)] else c return rc isOverloaded :: Function fun sig -> Bool isOverloaded (Expr.Eq _ _) = True isOverloaded (Expr.Distinct _ _) = True isOverloaded (Expr.Map _ _) = True isOverloaded (Expr.Ord _ _) = True isOverloaded (Expr.Arith _ _ _) = True isOverloaded (Expr.Abs _) = True isOverloaded (Expr.ITE _) = True isOverloaded (Expr.BVComp _ _) = True isOverloaded (Expr.BVBin _ _) = True isOverloaded (Expr.BVUn _ _) = True isOverloaded (Expr.Select _ _) = True isOverloaded (Expr.Store _ _) = True isOverloaded (Expr.ConstArray _ _) = True isOverloaded (Expr.Concat _ _) = True isOverloaded (Expr.Extract _ _ _) = True isOverloaded _ = False functionSymbol :: (Monad m,GetFunType fun) => (forall (arg' :: [Type]) (res' :: Type). fun '(arg',res') -> m L.Lisp) -- ^ How to render user functions -> (forall (arg' :: [Type]) (dt :: [Type] -> (Type -> *) -> *). IsDatatype dt => Datatype dt -> Type.Constr dt arg' -> m L.Lisp) -- ^ How to render constructor applications -> (forall (arg' :: [Type]) (dt :: [Type] -> (Type -> *) -> *). IsDatatype dt => Datatype dt -> Type.Constr dt arg' -> m L.Lisp) -- ^ How to render constructor tests -> (forall (dt :: [Type] -> (Type -> *) -> *) (res' :: Type). IsDatatype dt => Datatype dt -> Type.Field dt res' -> m L.Lisp) -- ^ How to render field acceses -> Function fun '(arg,res) -> m L.Lisp functionSymbol f _ _ _ (Expr.Fun g) = f g functionSymbol _ _ _ _ (Expr.Eq _ _) = return $ L.Symbol "=" functionSymbol _ _ _ _ (Expr.Distinct _ _) = return $ L.Symbol "distinct" functionSymbol f g h i (Expr.Map _ j) = do sym <- functionSymbolWithSig f g h i j return $ L.List [L.Symbol "_" ,L.Symbol "map" ,sym] functionSymbol _ _ _ _ (Ord _ op) = return $ ordSymbol op functionSymbol _ _ _ _ (Arith _ op _) = return $ arithSymbol op functionSymbol _ _ _ _ (ArithIntBin Div) = return $ L.Symbol "div" functionSymbol _ _ _ _ (ArithIntBin Mod) = return $ L.Symbol "mod" functionSymbol _ _ _ _ (ArithIntBin Rem) = return $ L.Symbol "rem" functionSymbol _ _ _ _ (ArithIntBin Exp) = return $ L.Symbol "^" functionSymbol _ _ _ _ Divide = return $ L.Symbol "/" functionSymbol _ _ _ _ (Abs _) = return $ L.Symbol "abs" functionSymbol _ _ _ _ Not = return $ L.Symbol "not" functionSymbol _ _ _ _ (Logic And _) = return $ L.Symbol "and" functionSymbol _ _ _ _ (Logic Or _) = return $ L.Symbol "or" functionSymbol _ _ _ _ (Logic XOr _) = return $ L.Symbol "xor" functionSymbol _ _ _ _ (Logic Implies _) = return $ L.Symbol "=>" functionSymbol _ _ _ _ (Logic (AtLeast n) _) = return $ L.List [L.Symbol "_",L.Symbol "at-least",L.Number $ L.I n] functionSymbol _ _ _ _ (Logic (AtMost n) _) = return $ L.List [L.Symbol "_",L.Symbol "at-most",L.Number $ L.I n] functionSymbol _ _ _ _ ToReal = return $ L.Symbol "to_real" functionSymbol _ _ _ _ ToInt = return $ L.Symbol "to_int" functionSymbol _ _ _ _ (ITE _) = return $ L.Symbol "ite" functionSymbol _ _ _ _ (BVComp op _) = return $ L.Symbol $ case op of BVULE -> "bvule" BVULT -> "bvult" BVUGE -> "bvuge" BVUGT -> "bvugt" BVSLE -> "bvsle" BVSLT -> "bvslt" BVSGE -> "bvsge" BVSGT -> "bvsgt" functionSymbol _ _ _ _ (BVBin op _) = return $ L.Symbol $ case op of BVAdd -> "bvadd" BVSub -> "bvsub" BVMul -> "bvmul" BVURem -> "bvurem" BVSRem -> "bvsrem" BVUDiv -> "bvudiv" BVSDiv -> "bvsdiv" BVSHL -> "bvshl" BVLSHR -> "bvlshr" BVASHR -> "bvashr" BVXor -> "bvxor" BVAnd -> "bvand" BVOr -> "bvor" functionSymbol _ _ _ _ (BVUn op _) = return $ L.Symbol $ case op of BVNot -> "bvnot" BVNeg -> "bvneg" functionSymbol _ _ _ _ (Select _ _) = return $ L.Symbol "select" functionSymbol _ _ _ _ (Store _ _) = return $ L.Symbol "store" functionSymbol _ _ _ _ (ConstArray idx el) = return $ L.List [L.Symbol "as" ,L.Symbol "const" ,typeSymbol Set.empty (ArrayRepr idx el)] functionSymbol _ _ _ _ (Concat _ _) = return $ L.Symbol "concat" functionSymbol _ _ _ _ (Extract bw start len) = return $ L.List [L.Symbol "_" ,L.Symbol "extract" ,L.Number $ L.I $ start'+len'-1 ,L.Number $ L.I start'] where start' = bwSize start len' = bwSize len functionSymbol _ g _ _ (Constructor dt par con) = g dt con functionSymbol _ _ h _ (Test dt par con) = h dt con functionSymbol _ _ _ i (Expr.Field dt par f) = i dt f functionSymbol _ _ _ _ (Divisible n) = return $ L.List [L.Symbol "_" ,L.Symbol "divisible" ,L.Number $ L.I n] functionSymbol _ _ _ _ (PseudoBoolean op coeff res) = return $ L.List (L.Symbol "_": L.Symbol (case op of PBEq -> "pbeq" PBLe -> "pble" PBGe -> "pbge"): (L.Number $ L.I res): (fmap (L.Number . L.I) $ List.toListC coeff)) functionSymbolWithSig :: (Monad m,GetFunType fun) => (forall (arg' :: [Type]) (res' :: Type). fun '(arg',res') -> m L.Lisp) -- ^ How to render user functions -> (forall (arg' :: [Type]) (dt :: [Type] -> (Type -> *) -> *). IsDatatype dt => Datatype dt -> Type.Constr dt arg' -> m L.Lisp) -- ^ How to render constructor applications -> (forall (arg' :: [Type]) (dt :: [Type] -> (Type -> *) -> *). IsDatatype dt => Datatype dt -> Type.Constr dt arg' -> m L.Lisp) -- ^ How to render constructor tests -> (forall (dt :: [Type] -> (Type -> *) -> *) (res' :: Type). IsDatatype dt => Datatype dt -> Type.Field dt res' -> m L.Lisp) -- ^ How to render field acceses -> Function fun '(arg,res) -> m L.Lisp functionSymbolWithSig f g h i j = do sym <- functionSymbol f g h i j if isOverloaded j then return $ L.List [sym ,typeList arg ,typeSymbol Set.empty res] else return sym where (arg,res) = getFunType j typeSymbol :: Set String -> Repr t -> L.Lisp typeSymbol _ BoolRepr = L.Symbol "Bool" typeSymbol _ IntRepr = L.Symbol "Int" typeSymbol _ RealRepr = L.Symbol "Real" typeSymbol _ (BitVecRepr n) = L.List [L.Symbol "_" ,L.Symbol "BitVec" ,L.Number (L.I $ bwSize n)] typeSymbol recDt (ArrayRepr idx el) = L.List ((L.Symbol "Array"): runIdentity (List.toList (return.typeSymbol recDt) idx) ++ [typeSymbol recDt el]) typeSymbol recDt (DataRepr dt par) | Set.member (datatypeName dt) recDt = L.Symbol (T.pack $ datatypeName dt) | otherwise = L.List $ [L.Symbol (T.pack $ datatypeName dt)]++ (runIdentity $ List.toList (return.typeSymbol recDt) par) typeSymbol _ (ParameterRepr n) = L.Symbol (T.pack $ "a"++show (naturalToInteger n)) typeList :: List Repr t -> L.Lisp typeList Nil = L.Symbol "()" typeList args = L.List (runIdentity $ List.toList (return.typeSymbol Set.empty) args) ordSymbol :: OrdOp -> L.Lisp ordSymbol Ge = L.Symbol ">=" ordSymbol Gt = L.Symbol ">" ordSymbol Le = L.Symbol "<=" ordSymbol Lt = L.Symbol "<" arithSymbol :: ArithOp -> L.Lisp arithSymbol Plus = L.Symbol "+" arithSymbol Mult = L.Symbol "*" arithSymbol Minus = L.Symbol "-" numToLisp :: Integer -> L.Lisp numToLisp n = if n>=0 then L.Number $ L.I n else L.List [L.Symbol "-" ,L.Number $ L.I $ abs n] clearInput :: SMTPipe -> IO () clearInput pipe = do r <- hReady (channelOut pipe) if r then (do _ <- BS.hGetSome (channelOut pipe) 1024 clearInput pipe) else return () putRequest :: SMTPipe -> L.Lisp -> IO () putRequest pipe expr = do clearInput pipe toByteStringIO (BS.hPutStr $ channelIn pipe) (mappend (L.fromLispExpr expr) flush) BS8.hPutStrLn (channelIn pipe) "" hFlush (channelIn pipe) parseResponse :: SMTPipe -> IO L.Lisp parseResponse pipe = do str <- BS.hGetLine (channelOut pipe) let continue (Done _ r) = return r continue res@(Partial _) = do line <- BS.hGetLine (channelOut pipe) continue (feed (feed res line) (BS8.singleton '\n')) continue (Fail str' ctx msg) = error $ "Error parsing "++show str'++" response in "++show ctx++": "++msg continue $ parse L.lisp (BS8.snoc str '\n') genName :: SMTPipe -> String -> (T.Text,SMTPipe) genName pipe name = (sym,pipe { names = nnames }) where (sym,nnames) = genName' (names pipe) name genName' :: Map String Int -> String -> (T.Text,Map String Int) genName' names name = case Map.lookup name names of Nothing -> (T.pack name',Map.insert name 0 names) Just n -> (T.pack $ name' ++ "_" ++ show (n+1), Map.insert name (n+1) names) where name' = escapeName name escapeName :: String -> String escapeName [] = [] escapeName ('_':xs) = '_':'_':escapeName xs escapeName (x:xs) = x:escapeName xs tacticToLisp :: Tactic -> L.Lisp tacticToLisp Skip = L.Symbol "skip" tacticToLisp (AndThen ts) = L.List ((L.Symbol "and-then"):fmap tacticToLisp ts) tacticToLisp (OrElse ts) = L.List ((L.Symbol "or-else"):fmap tacticToLisp ts) tacticToLisp (ParOr ts) = L.List ((L.Symbol "par-or"):fmap tacticToLisp ts) tacticToLisp (ParThen t1 t2) = L.List [L.Symbol "par-then" ,tacticToLisp t1 ,tacticToLisp t2] tacticToLisp (TryFor t n) = L.List [L.Symbol "try-for" ,tacticToLisp t ,L.Number $ L.I n] tacticToLisp (If c t1 t2) = L.List [L.Symbol "if" ,probeToLisp c ,tacticToLisp t1 ,tacticToLisp t2] tacticToLisp (FailIf c) = L.List [L.Symbol "fail-if" ,probeToLisp c] tacticToLisp (UsingParams (CustomTactic name) []) = L.Symbol (T.pack name) tacticToLisp (UsingParams (CustomTactic name) pars) = L.List ([L.Symbol "using-params" ,L.Symbol $ T.pack name]++ concat [ [L.Symbol (T.pack $ ':':pname) ,case par of ParBool True -> L.Symbol "true" ParBool False -> L.Symbol "false" ParInt i -> L.Number $ L.I i ParDouble i -> L.Number $ L.D i] | (pname,par) <- pars ]) probeToLisp :: Probe a -> L.Lisp probeToLisp (ProbeBoolConst b) = L.Symbol $ if b then "true" else "false" probeToLisp (ProbeIntConst i) = L.Number $ L.I i probeToLisp (ProbeAnd ps) = L.List ((L.Symbol "and"): fmap probeToLisp ps) probeToLisp (ProbeOr ps) = L.List ((L.Symbol "or"): fmap probeToLisp ps) probeToLisp (ProbeNot p) = L.List [L.Symbol "not" ,probeToLisp p] probeToLisp (ProbeEq p1 p2) = L.List [L.Symbol "=" ,probeToLisp p1 ,probeToLisp p2] probeToLisp (ProbeGt p1 p2) = L.List [L.Symbol ">" ,probeToLisp p1 ,probeToLisp p2] probeToLisp (ProbeGe p1 p2) = L.List [L.Symbol ">=" ,probeToLisp p1 ,probeToLisp p2] probeToLisp (ProbeLt p1 p2) = L.List [L.Symbol "<" ,probeToLisp p1 ,probeToLisp p2] probeToLisp (ProbeGe p1 p2) = L.List [L.Symbol "<=" ,probeToLisp p1 ,probeToLisp p2] probeToLisp IsPB = L.Symbol "is-pb" probeToLisp ArithMaxDeg = L.Symbol "arith-max-deg" probeToLisp ArithAvgDeg = L.Symbol "arith-avg-deg" probeToLisp ArithMaxBW = L.Symbol "arith-max-bw" probeToLisp ArithAvgBW = L.Symbol "arith-avg-bw" probeToLisp IsQFLIA = L.Symbol "is-qflia" probeToLisp IsQFLRA = L.Symbol "is-qflra" probeToLisp IsQFLIRA = L.Symbol "is-qflira" probeToLisp IsILP = L.Symbol "is-ilp" probeToLisp IsQFNIA = L.Symbol "is-qfnia" probeToLisp IsQFNRA = L.Symbol "is-qfnra" probeToLisp IsNIA = L.Symbol "is-nia" probeToLisp IsNRA = L.Symbol "is-nra" probeToLisp IsUnbounded = L.Symbol "is-unbounded" probeToLisp Memory = L.Symbol "memory" probeToLisp Depth = L.Symbol "depth" probeToLisp Size = L.Symbol "size" probeToLisp NumExprs = L.Symbol "num-exprs" probeToLisp NumConsts = L.Symbol "num-consts" probeToLisp NumBoolConsts = L.Symbol "num-bool-consts" probeToLisp NumArithConsts = L.Symbol "num-arith-consts" probeToLisp NumBVConsts = L.Symbol "num-bv-consts" probeToLisp Strat.ProduceProofs = L.Symbol "produce-proofs" probeToLisp ProduceModel = L.Symbol "produce-model" probeToLisp Strat.ProduceUnsatCores = L.Symbol "produce-unsat-cores" probeToLisp HasPatterns = L.Symbol "has-patterns" probeToLisp IsPropositional = L.Symbol "is-propositional" probeToLisp IsQFBV = L.Symbol "is-qfbv" probeToLisp IsQFBVEQ = L.Symbol "is-qfbv-eq"
hguenther/smtlib2
backends/pipe/Language/SMTLib2/Pipe/Internals.hs
gpl-3.0
84,002
517
27
28,122
29,858
15,084
14,774
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Hoodle.ModelAction.Eraser -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Hoodle.ModelAction.Eraser where import Control.Monad.State -- from hoodle-platform import Data.Hoodle.BBox import Graphics.Hoodle.Render.Type.HitTest import Graphics.Hoodle.Render.Util.HitTest -- | eraseHitted :: (GetBBoxable a) => AlterList (NotHitted a) (AlterList (NotHitted a) (Hitted a)) -> State (Maybe BBox) [a] eraseHitted Empty = error "something wrong in eraseHitted" eraseHitted (n :-Empty) = return (unNotHitted n) eraseHitted (n:-h:-rest) = do mid <- elimHitted h return . (unNotHitted n ++) . (mid ++) =<< eraseHitted rest
wavewave/hoodle-core
src/Hoodle/ModelAction/Eraser.hs
gpl-3.0
965
0
11
161
204
116
88
13
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Orwell.CommitMetaData ( CommitMetaData(..), FileChange(..), CommitAuthor, ) where import Data.Text import Prelude as P (FilePath) import Prelude hiding (FilePath) import Data.Aeson type CommitAuthor = Text data FileChange = FileChange { changeFile :: P.FilePath, changeAdded :: Int, changeDeleted :: Int } deriving (Eq, Ord, Show) data CommitMetaData = CommitMetaData { commitHash :: Text, commitSubject :: Text, commitAuthor :: CommitAuthor, commitTimestamp :: Int, commitCodeFiles :: [FileChange], commitTestFiles :: [FileChange], commitChanges :: [FileChange], commitTestsAdded :: Int } deriving (Eq, Ord, Show) instance ToJSON CommitMetaData where toJSON (CommitMetaData {..}) = object [ "commitAuthor" .= commitAuthor, "commitHash" .= commitHash, "commitTimestamp" .= (commitTimestamp * 1000), "commitTestsAdded" .= commitTestsAdded ]
Ragnaroek/orwell
src/Orwell/CommitMetaData.hs
gpl-3.0
1,005
0
10
201
251
154
97
32
0
{-| Module : Ranking.Glicko.Types License : GPL-3 Maintainer : rasmus@precenth.eu Stability : experimental For examples, see `Ranking.Glicko.Core` and `Ranking.Glicko.Inference`. -} {-# LANGUAGE KindSignatures #-} module Ranking.Glicko.Types ( -- * Data types Player(..) , Match(..) , PlayerId , Score , ScoreFunction(..) , GlickoSettings(..) ) where import Control.DeepSeq import Data.Default import GHC.TypeLits (Nat) type PlayerId = Int -- | Data type representing a player's Glicko rating. The type -- 'version' is used to differentiate between Glicko ('Player' 1) and -- Glicko-2 ('Player' 2). data Player (version :: Nat) = Player { playerId :: PlayerId -- ^ Player id, can be anything , playerRating :: Double -- ^ Rating , playerDev :: Double -- ^ Deviation , playerVol :: Double -- ^ Volatility , playerInactivity :: Int -- ^ Inactivity (not part of Glicko-2), -- keeps track of the number of rating -- updates a player has been inactive. , playerAge :: Int -- ^ Age (not part of Glicko-2), -- keeps track of the number of rating -- updates since the player was added. } deriving (Show, Eq) instance NFData (Player v) where rnf (Player x1 x2 x3 x4 x5 x6) = rnf (x1, x2, x3, x4, x5, x6) type Score = Int data Match = Match { matchPlayerA :: PlayerId , matchPlayerB :: PlayerId , matchScoreA :: Score , matchScoreB :: Score} deriving (Show, Eq) -- | 'ScoreFunction's are used in 'compute' to evaluate two players performances against -- eachother. It should obey the following laws, -- -- -- prop> 0 <= compareScores x y -- prop> 1 >= compareScores x y -- prop> compareScores x y == 1 - compareScores y x -- -- -- The default implementation is -- -- @ -- \\s1 s2 -> case s1 \`compare\` s2 of -- LT -> 0 -- EQ -> 0.5 -- GT -> 1 -- @ newtype ScoreFunction = ScoreFunction { compareScores :: Score -> Score -> Double } instance Default ScoreFunction where def = ScoreFunction $ \s1 s2 -> case s1 `compare` s2 of LT -> 0 EQ -> 0.5 GT -> 1 instance Show ScoreFunction where show _ = "{score function}" -- | Provides the 'Ranking.Glicko.Core.compute' function with parameters. -- See <http://glicko.net/glicko/glicko2.pdf> for an explanation. -- -- (NOTE: 'scoreFunction' is not a part of Glicko-2) -- -- The default settings are as defined in the above paper. data GlickoSettings = GlickoSettings { initialRating :: Double , initialDeviation :: Double , initialVolatility :: Double , tau :: Double , scoreFunction :: ScoreFunction} deriving Show instance Default GlickoSettings where def = GlickoSettings { initialRating = 1500 , initialDeviation = 350 , initialVolatility = 0.06 , tau = 0.5 , scoreFunction = def}
Prillan/haskell-glicko
src/Ranking/Glicko/Types.hs
gpl-3.0
3,194
0
10
1,018
456
292
164
-1
-1
import Test.HUnit import Yaml test_decodeYamlLine :: Test test_decodeYamlLine = TestCase $ assertEqual "Decode yaml into (key,value)" ("wikiname","testwiki") $ decodeYamlLine "wikiname: testwiki" test_decodeYamlLines :: Test test_decodeYamlLines = TestCase $ assertEqual "Decode list of yaml lines into list of\ \(key,value) tuples." [ ("wikiname","testwiki") , ("srcdir", "/home/test/testwiki") ] (decodeYamlLines [ "wikiname: testwiki" , "srcdir: /home/test/testwiki" ]) test_decodeYamlMarkdownHeader :: Test test_decodeYamlMarkdownHeader = TestCase $ assertEqual "Decode only the yaml lines from a markdown header\ \that starts and stops with '---'" [ ("wikiname","testwiki") , ("srcdir", "/home/test/testwiki") ] (decodeYamlMarkdownHeader [ "---" , "wikiname: testwiki" , "srcdir: /home/test/testwiki" , "---" ]) test_lookupYaml :: Test test_lookupYaml = TestCase $ assertEqual "Failed to look up value for an existing key." (Just "bar") $ lookupYaml "foo" [("key","value"),("foo","bar")] main :: IO Counts main = runTestTT $ TestList [ test_decodeYamlLines , test_decodeYamlLine , test_decodeYamlMarkdownHeader , test_lookupYaml ]
scottwakeling/hikiwiki
test/Main.hs
gpl-3.0
1,533
0
8
532
239
133
106
31
1
module Ignifera.Format.Pgn where data Comment = Comment String deriving (Eq, Read, Show) data Tag = Tag String String deriving (Eq, Read, Show) data CheckIndicator = Check | CheckMate deriving (Eq, Read, Show)
fthomas/ignifera
src/Ignifera/Format/Pgn.hs
gpl-3.0
219
0
6
41
82
46
36
7
0
module Paths_date ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,0], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "c:/Documents and Settings/Robin Seeley/workspace/bin\\bin" libdir = "c:/Documents and Settings/Robin Seeley/workspace/bin\\date-0.0\\ghc-7.4.2" datadir = "c:/Documents and Settings/Robin Seeley/workspace/bin\\date-0.0" libexecdir = "c:/Documents and Settings/Robin Seeley/workspace/bin\\date-0.0" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "date_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "date_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "date_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "date_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "\\" ++ name)
b1g3ar5/Date
dist/build/autogen/Paths_date.hs
gpl-3.0
1,227
0
10
176
323
184
139
25
1
-- | Script output type. We launch the executable asked after -- injecting the environment variables related to the report. module OrgStat.Outputs.Script ( processScriptOutput ) where import Universum import Control.Lens (views) import qualified Data.Map.Strict as M import System.Environment (lookupEnv, setEnv, unsetEnv) import System.Process (callCommand) import OrgStat.Ast import OrgStat.Config (confReports, crName) import OrgStat.Helpers (resolveReport) import OrgStat.Outputs.Types (ScriptParams(..)) import OrgStat.Util (timeF) import OrgStat.WorkMonad (WorkM, wcConfig) -- | Processes script output. processScriptOutput :: ScriptParams -> WorkM () processScriptOutput ScriptParams{..} = do -- Considering all the reports if none are specified. reportsToConsider <- case spReports of [] -> views wcConfig (map crName . confReports) xs -> pure xs allReports <- mapM (\r -> (r,) <$> resolveReport r) reportsToConsider -- Set env variables prevVars <- forM allReports $ \(toString -> reportName,org) -> do let duration = timeF $ orgTotalDuration $ filterHasClock org let mean = timeF $ orgMeanDuration $ filterHasClock org let median = timeF $ orgMedianDuration $ filterHasClock org let pomodoro = orgPomodoroNum $ filterHasClock org let toMinutes x = round x `div` 60 -- logWarning $ "1: " <> show org -- logWarning $ "2: " <> show (filterHasClock org) -- logWarning $ "3: " <> show (orgDurations $ filterHasClock org) let durationsPyth :: [Int] = map toMinutes $ orgDurations $ filterHasClock org (prevVar :: Maybe String) <- liftIO $ lookupEnv reportName liftIO $ setEnv reportName (toString duration) liftIO $ setEnv (reportName <> "Mean") (toString mean) liftIO $ setEnv (reportName <> "Median") (toString median) liftIO $ setEnv (reportName <> "Pomodoro") (show pomodoro) liftIO $ setEnv (reportName <> "DurationsList") (show durationsPyth) pure $ (reportName,) <$> prevVar let prevVarsMap :: Map String String prevVarsMap = M.fromList $ catMaybes prevVars -- Execute script let cmdArgument = either id (\t -> "-c \"" <> toString t <> "\"") spScript liftIO $ callCommand $ spInterpreter <> " " <> cmdArgument --"/bin/env sh " <> cmdArgument -- Restore the old variables, clean new. forM_ (map fst allReports) $ \(toString -> reportName) -> do liftIO $ case M.lookup reportName prevVarsMap of Nothing -> unsetEnv reportName Just prevValue -> setEnv reportName prevValue where
volhovM/orgstat
src/OrgStat/Outputs/Script.hs
gpl-3.0
2,663
0
17
618
707
362
345
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.TPU.Projects.Locations.AcceleratorTypes.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists accelerator types supported by this API. -- -- /See:/ <https://cloud.google.com/tpu/ Cloud TPU API Reference> for @tpu.projects.locations.acceleratorTypes.list@. module Network.Google.Resource.TPU.Projects.Locations.AcceleratorTypes.List ( -- * REST Resource ProjectsLocationsAcceleratorTypesListResource -- * Creating a Request , projectsLocationsAcceleratorTypesList , ProjectsLocationsAcceleratorTypesList -- * Request Lenses , platlParent , platlXgafv , platlUploadProtocol , platlOrderBy , platlAccessToken , platlUploadType , platlFilter , platlPageToken , platlPageSize , platlCallback ) where import Network.Google.Prelude import Network.Google.TPU.Types -- | A resource alias for @tpu.projects.locations.acceleratorTypes.list@ method which the -- 'ProjectsLocationsAcceleratorTypesList' request conforms to. type ProjectsLocationsAcceleratorTypesListResource = "v1" :> Capture "parent" Text :> "acceleratorTypes" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "orderBy" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListAcceleratorTypesResponse -- | Lists accelerator types supported by this API. -- -- /See:/ 'projectsLocationsAcceleratorTypesList' smart constructor. data ProjectsLocationsAcceleratorTypesList = ProjectsLocationsAcceleratorTypesList' { _platlParent :: !Text , _platlXgafv :: !(Maybe Xgafv) , _platlUploadProtocol :: !(Maybe Text) , _platlOrderBy :: !(Maybe Text) , _platlAccessToken :: !(Maybe Text) , _platlUploadType :: !(Maybe Text) , _platlFilter :: !(Maybe Text) , _platlPageToken :: !(Maybe Text) , _platlPageSize :: !(Maybe (Textual Int32)) , _platlCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsAcceleratorTypesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'platlParent' -- -- * 'platlXgafv' -- -- * 'platlUploadProtocol' -- -- * 'platlOrderBy' -- -- * 'platlAccessToken' -- -- * 'platlUploadType' -- -- * 'platlFilter' -- -- * 'platlPageToken' -- -- * 'platlPageSize' -- -- * 'platlCallback' projectsLocationsAcceleratorTypesList :: Text -- ^ 'platlParent' -> ProjectsLocationsAcceleratorTypesList projectsLocationsAcceleratorTypesList pPlatlParent_ = ProjectsLocationsAcceleratorTypesList' { _platlParent = pPlatlParent_ , _platlXgafv = Nothing , _platlUploadProtocol = Nothing , _platlOrderBy = Nothing , _platlAccessToken = Nothing , _platlUploadType = Nothing , _platlFilter = Nothing , _platlPageToken = Nothing , _platlPageSize = Nothing , _platlCallback = Nothing } -- | Required. The parent resource name. platlParent :: Lens' ProjectsLocationsAcceleratorTypesList Text platlParent = lens _platlParent (\ s a -> s{_platlParent = a}) -- | V1 error format. platlXgafv :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Xgafv) platlXgafv = lens _platlXgafv (\ s a -> s{_platlXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). platlUploadProtocol :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Text) platlUploadProtocol = lens _platlUploadProtocol (\ s a -> s{_platlUploadProtocol = a}) -- | Sort results. platlOrderBy :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Text) platlOrderBy = lens _platlOrderBy (\ s a -> s{_platlOrderBy = a}) -- | OAuth access token. platlAccessToken :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Text) platlAccessToken = lens _platlAccessToken (\ s a -> s{_platlAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). platlUploadType :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Text) platlUploadType = lens _platlUploadType (\ s a -> s{_platlUploadType = a}) -- | List filter. platlFilter :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Text) platlFilter = lens _platlFilter (\ s a -> s{_platlFilter = a}) -- | The next_page_token value returned from a previous List request, if any. platlPageToken :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Text) platlPageToken = lens _platlPageToken (\ s a -> s{_platlPageToken = a}) -- | The maximum number of items to return. platlPageSize :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Int32) platlPageSize = lens _platlPageSize (\ s a -> s{_platlPageSize = a}) . mapping _Coerce -- | JSONP platlCallback :: Lens' ProjectsLocationsAcceleratorTypesList (Maybe Text) platlCallback = lens _platlCallback (\ s a -> s{_platlCallback = a}) instance GoogleRequest ProjectsLocationsAcceleratorTypesList where type Rs ProjectsLocationsAcceleratorTypesList = ListAcceleratorTypesResponse type Scopes ProjectsLocationsAcceleratorTypesList = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsAcceleratorTypesList'{..} = go _platlParent _platlXgafv _platlUploadProtocol _platlOrderBy _platlAccessToken _platlUploadType _platlFilter _platlPageToken _platlPageSize _platlCallback (Just AltJSON) tPUService where go = buildClient (Proxy :: Proxy ProjectsLocationsAcceleratorTypesListResource) mempty
brendanhay/gogol
gogol-tpu/gen/Network/Google/Resource/TPU/Projects/Locations/AcceleratorTypes/List.hs
mpl-2.0
6,856
0
20
1,578
1,039
598
441
152
1
{- v-clock < pattern.vcd -- Clocks in signals on rising jtg_tck -- TODO clock outputs on falling tck -} {-# LANGUAGE OverloadedStrings #-} module Main where import qualified Data.ByteString.Char8 as B import qualified Data.HashMap.Strict as HashMap import Lib getAlias (Wire _ alias _) = alias keepLast :: Hashable b => Eq b => (a -> b) -> [a] -> [a] keepLast f as = HashMap.elems . HashMap.fromList $ zip (map f as) as stateChangeAlias = B.tail stateChangeState :: ByteString -> Char stateChangeState sc | B.null sc = 'x' | otherwise = B.head sc hasAlias alias sc = alias == stateChangeAlias sc isState st sc = st == stateChangeState sc groupUntil = split . keepDelimsR . whenElt interleve :: [a] -> [a] -> [a] interleve (a:as) (b:bs) = a:b:interleve as bs interleve _ [] = [] interleve [] _ = [] enlist :: [a] -> [[a]] enlist ( a:as ) = [a]:enlist as clock :: B.ByteString -> B.ByteString -> B.ByteString clock tck_alias = let -- group state changes in each timestamp discarding the timestamp groupByTime = splitWhen isTimestamp uniquify = keepLast stateChangeAlias tckRise = any (\sc -> hasAlias tck_alias sc && isState '1' sc) groupByTckRise = groupUntil tckRise interleveTimestamps = interleve (enlist ascendingTimestamps ) ascendingTimestamps = zipWith B.cons (repeat '#') (map (B.pack . show) [0..]) in B.unlines . concat . interleveTimestamps . map uniquify . -- [[BS]] map concat . -- [[BS]] grouped by time groupByTckRise . -- [[[BS]]] groupByTime . -- [[BS]] B.lines -- [BS] data Opts = Opts { clockName :: ByteString , newTimeScale :: (Int, ByteString) , optInput :: FilePath } decodeTimeScale :: String -> (Int, ByteString) decodeTimeScale s = fromMaybe ( error $ "Invalid timescale, " ++ s ++ ". Valid example: 200ns" ) ( B.readInt . B.pack $ s ) parseOpts :: OptionsParser Opts parseOpts = Opts <$> (fmap B.pack . strOption) ( long "clock" <> short 'c' <> value "jtg_tck" <> metavar "CLOCK_NAME" <> help "All signals will be sampled on the rising edge of this clock") <*> (fmap decodeTimeScale . strOption) ( long "time-scale" <> short 't' <> value "200ns" <> metavar "NUM SCALE" <> help "A number and suffix giving the new timescale like 200ns or 10ps. This only affects the 'timescale' statement in the output vcd. Its mostly so you can compare original and clocked VCDs side-by-side in twinwave") <*> argument str ( metavar "VCDFILE.vcd" <> value "" <> help "A Vector-Change Dump file") opts :: ParserInfo Opts opts = info (parseOpts <**> helper) ( fullDesc <> progDesc "Clock in a VCD so that one #TIMESTAMP = one cycle of the clock. #0 is the first cycle, #1 is the second cycle ... you get it. All signals are sampled on the rising edge of the clock" <> header "vcd-clock - clock-sample a VCD") replaceTimeScale :: (Int, ByteString) -> Header -> Header replaceTimeScale (nm,sc) (TimeScale _ _) = (TimeScale nm sc) replaceTimeScale _ x = x main :: IO () main = do Opts clockWire timeScale vcdFile <- execParser opts f <- getInput vcdFile let (hdrs, theRest) = splitHeaders f hdrsOut = mapHeaders (replaceTimeScale timeScale) hdrs let isTckWire (Wire _ _ nm) = nm == clockWire isTckWire _ = False -- TODO: ERROR if not exactly one match tck_alias = getAlias ( head (filter isTckWire (flattenHeaders hdrs )) ) hPutBuilder stdout (foldMap render hdrsOut) -- XXX Ugly hack, should add a top-level header to contain the others B.putStrLn "$enddefinitions $end" -- TODO: probably won't stream because has to read the whole input before beginning output B.putStr (clock tck_alias theRest)
gitfoxi/vcd-haskell
app/vcd-clock.hs
agpl-3.0
3,801
0
16
886
1,053
538
515
-1
-1
{- Habit of Fate, a game to incentivize habit formation. Copyright (C) 2017 Gregory Crosswhite This program is free software: you can redistribute it and/or modify it under version 3 of the terms of the GNU Affero General Public License. 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 <https://www.gnu.org/licenses/>. -} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE UnicodeSyntax #-} module HabitOfFate.Server.Requests.Web.EditAndDeleteGroup (handler) where import HabitOfFate.Prelude import qualified Data.Text.Lazy as Lazy import Data.UUID (UUID) import qualified Data.UUID as UUID import Network.HTTP.Types.Status (ok200, temporaryRedirect307) import Text.Blaze.Html5 ((!), toHtml) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Web.Scotty (ScottyM) import qualified Web.Scotty as Scotty import HabitOfFate.Data.Account import HabitOfFate.Data.Group import HabitOfFate.Data.ItemsSequence import HabitOfFate.Server.Common import HabitOfFate.Server.Transaction data DeletionMode = NoDeletion | DeletionAvailable | ConfirmDeletion groupPage ∷ Monad m ⇒ UUID → Lazy.Text → DeletionMode → Group → m TransactionResult groupPage group_id error_message deletion_mode group = renderTopOnlyPageResult "Group of Fate - Editing a Group" (\_ → ["edit_group"]) [] Nothing ok200 >>> pure $ \_ → H.form ! A.method "post" $ do H.div ! A.class_ "fields" $ do -- Name H.div ! A.class_ "label" $ H.toHtml ("Name:" ∷ Text) H.div $ H.input ! A.type_ "text" ! A.name "name" ! A.value (H.toValue group) ! A.required "true" ! A.id "name_input" H.hr H.div ! A.id "error_message" $ H.toHtml error_message H.div ! A.class_ "submit" $ do H.a ! A.class_ "sub" ! A.href "/habits" $ toHtml ("Cancel" ∷ Text) H.input ! A.class_ "sub" ! A.formaction (H.toValue [i|/groups/#{UUID.toText group_id}|]) ! A.type_ "submit" case deletion_mode of NoDeletion → mempty DeletionAvailable → do H.hr H.form ! A.method "get" $ do H.input ! A.type_ "hidden" ! A.name "confirm" ! A.value "0" H.input ! A.type_ "submit" ! A.formaction (H.toValue [i|/groups/#{UUID.toText group_id}/delete|]) ! A.value "Delete" ConfirmDeletion → do H.hr H.form ! A.method "post" $ do H.input ! A.type_ "hidden" ! A.name "confirm" ! A.value "1" H.input ! A.type_ "submit" ! A.formaction (H.toValue [i|/groups/#{UUID.toText group_id}/delete|]) ! A.value "Confirm Delete?" handleEditGroupGet ∷ Environment → ScottyM () handleEditGroupGet environment = do Scotty.get "/groups/:group_id" <<< webTransaction environment $ do group_id ← getParam "group_id" log [i|Web GET request for group with id #{group_id}.|] maybe_group ← use (groups_ . at group_id) uncurry (groupPage group_id "") $ case maybe_group of Nothing → (NoDeletion, "") Just group → (DeletionAvailable, group) extractGroup ∷ Transaction (Group, Lazy.Text) extractGroup = do group_id ← getParam "group_id" default_group ← use (groups_ . at group_id) <&> fromMaybe "" (name_value, name_error) ← getParamMaybe "name" <&> maybe (default_group, "No value for the name was present.") (\value → if null value then ("", "Name for the group may not be empty.") else (pack value, "") ) pure ( name_value , find (onull >>> not) >>> fromMaybe "" $ [ name_error ] ) handleEditGroupPost ∷ Environment → ScottyM () handleEditGroupPost environment = do Scotty.post "/groups/:group_id" <<< webTransaction environment $ do group_id ← getParam "group_id" log [i|Web POST request for group with id #{group_id}.|] (extracted_group, error_message) ← extractGroup if onull error_message then do log [i|Updating group #{group_id} to #{extracted_group}|] groups_ . at group_id .= Just extracted_group pure $ redirectsToResult temporaryRedirect307 "/habits" else do log [i|Failed to update group #{group_id}:|] log [i| Error message: #{error_message}|] deletion_mode ← use (groups_ . items_map_) <&> (member group_id >>> bool NoDeletion DeletionAvailable) groupPage group_id error_message deletion_mode extracted_group handleDeleteGroupGet ∷ Environment → ScottyM () handleDeleteGroupGet environment = do Scotty.get "/groups/:group_id/delete" <<< webTransaction environment $ do group_id ← getParam "group_id" log [i|Web GET request to delete group with id #{group_id}.|] maybe_group ← use (groups_ . at group_id) case maybe_group of Nothing → pure $ redirectsToResult temporaryRedirect307 "/habits" Just group → groupPage group_id "" DeletionAvailable group handleDeleteGroupPost ∷ Environment → ScottyM () handleDeleteGroupPost environment = do Scotty.post "/groups/:group_id/delete" <<< webTransaction environment $ do group_id ← getParam "group_id" log [i|Web POST request to delete group with id #{group_id}.|] confirm ∷ Int ← getParamMaybe "confirm" <&> fromMaybe 0 if confirm == 1 then do log [i|Deleting group #{group_id}|] groups_ . at group_id .= Nothing pure $ redirectsToResult temporaryRedirect307 "/habits" else do log [i|Confirming delete for group #{group_id}|] (extracted_group, error_message) ← extractGroup groupPage group_id error_message ConfirmDeletion extracted_group handler ∷ Environment → ScottyM () handler environment = do handleEditGroupGet environment handleEditGroupPost environment handleDeleteGroupGet environment handleDeleteGroupPost environment
gcross/habit-of-fate
sources/library/HabitOfFate/Server/Requests/Web/EditAndDeleteGroup.hs
agpl-3.0
6,675
0
23
1,646
1,545
778
767
-1
-1
-- -- Copyright 2017-2018 Azad Bolour -- Licensed under GNU Affero General Public License v3.0 - -- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md -- module BoardGame.Server.Service.PieceProviderSpec where import Test.Hspec import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Except (ExceptT, runExceptT) import Data.List import BoardGame.Common.Domain.Piece (Piece, Piece(Piece)) import qualified BoardGame.Common.Domain.Piece as Piece import Bolour.Util.FrequencyDistribution (FrequencyDistribution(..)) import qualified Bolour.Util.FrequencyDistribution as FrequencyDistribution import qualified BoardGame.Server.Domain.PieceProvider as PieceProvider import BoardGame.Server.Domain.PieceProvider (PieceProvider(..)) import BoardGame.Server.Domain.GameError (GameError) letterFrequencies = [ ('A', 10), ('B', 20), ('C', 30), ('D', 40) ] letterDistribution :: FrequencyDistribution Char letterDistribution = FrequencyDistribution.mkFrequencyDistribution letterFrequencies provider0 :: PieceProvider provider0 = RandomPieceProvider 0 (FrequencyDistribution.randomValue letterDistribution) makePiece :: PieceProvider -> ExceptT GameError IO (Piece, PieceProvider) makePiece provider = PieceProvider.take provider nextState :: IO (Piece, PieceProvider) -> IO (Piece, PieceProvider) nextState ioPair = do (piece, provider) <- ioPair Right pair <- runExceptT $ makePiece provider return pair spec :: Spec spec = describe "for visual inspection of random piece generation" $ it "generate random pieces and count the letters generated" $ do Right (piece, provider) <- runExceptT (PieceProvider.take provider0) pairs <- sequence $ take 100 $ iterate nextState (return (piece, provider)) let pieces = fst <$> pairs letters = Piece.value <$> pieces print letters let groups = group $ sort letters counted = (\g -> (head g, length g)) <$> groups print counted
azadbolour/boardgame
haskell-server/test/BoardGame/Server/Service/PieceProviderSpec.hs
agpl-3.0
1,981
0
15
308
499
284
215
40
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_HADDOCK hide #-} -- | Data types for interpretation of DNA DSL using cloud haskell module DNA.Interpreter.Types where import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State.Strict import Control.Exception import Control.Distributed.Process import Control.Distributed.Process.Serializable import Data.Monoid import Data.Binary (Binary) import Data.Typeable (Typeable) import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import GHC.Generics (Generic) import Lens.Family.TH import DNA.Types import DNA.Lens import DNA.DSL import DNA.CH import DNA.Logging ---------------------------------------------------------------- -- Extra functions for matching on messages -- -- FIXME: should be greatly simplified by Functor instance for -- Match. We could get rid of MatchS altogether ---------------------------------------------------------------- -- | Handlers for events which could be used with State monad with state s data MatchS = forall a. Serializable a => MatchS (a -> Controller ()) -- | Wait for message from Match' and handle auxiliary messages handleRecieve :: [MatchS] -> [Match' a] -> DnaMonad a handleRecieve auxMs mA = loop where matches e s = map toMatch ((fmap . fmap) Right mA) ++ [ match $ \a -> Left <$> (flip runReaderT e . flip runStateT s . unDnaMonad . runController) (f a) | MatchS f <- auxMs] loop = do e <- ask s <- get r <- liftP $ receiveWait $ matches e s case r of Right a -> return a Left ((),s') -> put s' >> loop -- | Wait for message blockForMessage :: [MatchS] -> DnaMonad () blockForMessage auxMs = do e <- ask s <- get s' <- liftP $ receiveWait $ matches e s put s' where matches e s = [ match $ \a -> (flip runReaderT e . flip execStateT s . unDnaMonad . runController) (f a) | MatchS f <- auxMs ] ---------------------------------------------------------------- -- Monads ---------------------------------------------------------------- -- | Type synonym for monad which is used for interpretation of DNA -- programs. -- -- It have custom definition of fail which is used to raise panic -- level error. newtype DnaMonad a = DnaMonad { unDnaMonad :: StateT StateDNA (ReaderT Env Process) a } deriving (Functor,Applicative,MonadIO,MonadProcess,MonadState StateDNA,MonadReader Env) instance Monad DnaMonad where return = DnaMonad . return DnaMonad m >>= f = DnaMonad $ m >>= fmap unDnaMonad f fail = doPanic instance MonadLog DnaMonad where logSource = liftP logSource logLoggerOpt = _stLogOpt <$> get -- | Monad for event handlers. It adds explicit error handling type Controller = ExceptT DnaError DnaMonad -- | Error encountered during DNA computation data DnaError = FatalErr String -- ^ Fatal error | PanicErr String -- ^ Internal error | Except SomeException -- ^ Uncaught exception -- | Unrecoverable error. Could only occur due to bug in DNA -- implementation. data PanicException = PanicException String deriving (Show,Typeable) instance Exception PanicException -- | Unrecoverable error. Actor must immediately stop execution data FatalException = FatalException String deriving (Show,Typeable) instance Exception FatalException -- | Raise fatal error. fatal :: MonadError DnaError m => String -> m a fatal = throwError . FatalErr -- | Violation of internal invariant which should not ever happen -- unless implementation is buggy. panic :: MonadError DnaError m => String -> m a panic = throwError . PanicErr -- | Actually raise panic doPanic :: MonadLog m => String -> m a doPanic msg = do panicMsg msg liftIO $ throw $ PanicException msg -- | Write fatal error to log doFatal :: MonadLog m => String -> m a doFatal msg = do fatalMsg msg liftIO $ throw $ FatalException msg -- | Run controller monad. On failure will terminate process forefully runController :: Controller a -> DnaMonad a runController m = do r <- runExceptT m case r of Left err -> case err of PanicErr e -> doPanic e FatalErr e -> doFatal e Except e -> liftIO $ throw e Right a -> return a -- | Run DNA monad using ActorParam as source of input parameters and -- interpreter runDnaParam :: ActorParam -> DNA a -> Process a runDnaParam p action = do interpreter <- unClosure $ actorInterpreter p flip runReaderT env $ flip evalStateT s0 $ unDnaMonad $ dnaInterpreter interpreter action where env = Env { envRank = case actorRank p of Rank i -> i , envGroupSize = case actorGroupSize p of GroupSize i -> i , envInterpreter = actorInterpreter p , envWorkDir = actorWorkDir p } s0 = StateDNA { _stCounter = 0 , _stDebugFlags = actorDebugFlags p , _stLogOpt = actorLogOpt p , _stNodePool = Set.fromList $ vcadNodePool $ actorNodes p , _stActors = Map.empty , _stActorState = Map.empty , _stActorSrc = Map.empty , _stActorDst = Map.empty , _stVars = Map.empty , _stPid2Aid = Map.empty } -- | Evaluator for DNA monad. We have to pass closure with function -- for interpreting DNA monad manually since we have to break -- dependency loop. We also want to wrap function into newtype DnaInterpreter = DnaInterpreter { dnaInterpreter :: forall a. DNA a -> DnaMonad a } deriving Typeable ---------------------------------------------------------------- -- Data types ---------------------------------------------------------------- -- | Parameter send to actor on startup data ActorParam = ActorParam { actorParent :: Maybe ProcessId -- ^ Parent of an actor. Nothing for top level actor , actorInterpreter :: Closure DnaInterpreter -- ^ Interpreter for DNA DSL , actorRank :: Rank -- ^ Rank of an actor , actorGroupSize :: GroupSize -- ^ Size of group of actors , actorNodes :: VirtualCAD -- ^ Nodes allocated to an actor , actorDebugFlags :: [DebugFlag] -- ^ Extra flags for debugging , actorSendBack :: SendPort (RecvAddr Recv) -- ^ Send receive address and list of port ID's back to the parent process , actorLogOpt :: LoggerOpt -- ^ Logging preferences , actorWorkDir :: FilePath -- ^ Actor working directory } deriving (Show,Typeable,Generic) instance Binary ActorParam -- | Parameters of an actor which are constant during its execution data Env = Env { envRank :: !Int , envGroupSize :: !Int , envInterpreter :: !(Closure DnaInterpreter) , envWorkDir :: !FilePath } -- | State of interpreter -- -- Dataflow graph is append-only in the sense that we don't remove -- actors which completed execution from graph but mark them as -- completed instead. -- -- Note that resources are allocated to individual CH processes not -- to logical CH actors -- -- Invariants: -- -- * For every actor ID exist entry stChildren and stActorRecvAddr -- -- data StateDNA = StateDNA { _stCounter :: !Int -- ^ Counter for generation of unique IDs , _stDebugFlags :: [DebugFlag] -- ^ Extra debug flags , _stLogOpt :: LoggerOpt -- ^ Options for logger -- Resources , _stNodePool :: !(Set NodeInfo) -- ^ Nodes which are currently not in use -- Append only dataflow graph , _stActors :: !(Map AID ActorHier) -- ^ List of all spawned processes , _stActorState :: !(Map AID ActorState) -- ^ State of all groups of processes , _stActorSrc :: !(Map AID ActorSrc) -- ^ Data source of an actor. , _stActorDst :: !(Map AID ActorDst) -- ^ Data destination of an actor. , _stVars :: !(Map VID (RecvAddr Recv)) -- ^ All local variables , _stPid2Aid :: !(Map ProcessId AID) -- ^ Mapping from PIDs to AIDs } -- | Description of actor. It's persistent and doesn't change after -- creation. data ActorHier = SimpleActor -- ^ Simple 1-process actor | GroupMember AID -- ^ Actor which is member of a group | ActorGroup [AID] -- ^ Group of actors | ActorTree [AID] -- ^ Tree actors deriving (Show,Eq,Typeable,Generic) -- | State of actor. data ActorState = Completed -- ^ Actor completed execution successfully | Failed -- ^ Actor failed | Running ProcInfo -- ^ Actor is running | GrpRunning Int -- ^ Group of actor is still running deriving (Show,Typeable,Generic) -- | Data source of an actor data ActorSrc = SrcParent (RecvAddr Recv -> Process ()) -- ^ Actor receive data from parent | SrcActor AID -- ^ Actor receive data from another actor | SrcSubordinate -- ^ Actor is member of group of actors -- | Destination of an actor data ActorDst = DstParent VID -- ^ Actor sends data back to parent | DstActor AID -- ^ Actor sends data to another actor deriving (Show,Eq,Typeable,Generic) -- | Data about actor which corresponds to single CH process. data ProcInfo = ProcInfo { _pinfoPID :: ProcessId -- ^ PID of actor , _pinfoRecvAddr :: RecvAddr Recv -- ^ Address for receiving data , _pinfoNodes :: VirtualCAD -- ^ Allocated nodes , _pinfoClosure :: Maybe SpawnCmd -- ^ Optional command for restart of process } deriving (Show,Typeable,Generic) -- | Command for spawning actor data SpawnCmd = SpawnSingle (Closure (Process ())) Rank GroupSize ActorHier RecvAddrType [SpawnFlag] deriving (Show,Eq) $(makeLenses ''StateDNA) $(makeLenses ''ProcInfo) ---------------------------------------------------------------- -- Helpers ---------------------------------------------------------------- -- | Get ID of top-level actor in group, maybe this is same ID topLevelActor :: (MonadState StateDNA m, MonadError DnaError m) => AID -> m AID topLevelActor aid = do mst <- use $ stActors . at aid case mst of Just (GroupMember a) -> return a Just _ -> return aid Nothing -> panic "Unknown AID" -- | Obtain receive address for an actor getRecvAddress :: (MonadState StateDNA m, MonadError DnaError m) => AID -> m (RecvAddr Recv) getRecvAddress aid = do Just act <- use $ stActors . at aid Just st <- use $ stActorState . at aid case (act,st) of -- 1-process actor (_ , Completed) -> return RcvCompleted (_ , Failed ) -> return RcvFailed (SimpleActor , Running p) -> return $ p^.pinfoRecvAddr (GroupMember{}, Running p) -> return $ p^.pinfoRecvAddr -- Tree collector (ActorTree as, GrpRunning{}) -> do RcvTree `liftM` forM as getRecvAddress -- Group of worker processes (ActorGroup as, GrpRunning{}) -> do RcvGrp `liftM` forM as getRecvAddress -- Impossible _ -> panic $ "getRecvAddress: " ++ show (act,st) -- | Execute action for each sub actor in compound actor traverseActor :: (MonadState StateDNA m, Monoid r) => (AID -> m r) -> AID -> m r traverseActor action aid = do r0 <- action aid mst <- use $ stActors . at aid case mst of Just (ActorGroup as) -> do r <- forM as $ traverseActor action return $ r0 <> mconcat r Just (ActorTree as) -> do r <- forM as $ traverseActor action return $ r0 <> mconcat r _ -> return r0 -- | Send same message to all live processes in actor sendToActor :: (MonadProcess m, MonadState StateDNA m, Serializable a) => AID -> a -> m () sendToActor aid x = flip traverseActor aid $ \a -> do use (stActorState . at a) >>= \case Just (Running p) -> liftP $ send (p^.pinfoPID) x _ -> return () -- | Terminate actor forcefully. This only kill actors' processes and -- doesn't affect registry terminateActor :: (MonadProcess m, MonadState StateDNA m) => AID -> m () terminateActor aid = sendToActor aid (Terminate "TERMINATE") -- | Free actor's resources freeActor :: (MonadProcess m, MonadState StateDNA m) => AID -> m () freeActor aid = do me <- liftP getSelfNode st <- use $ stActorState . at aid case st of Just (Running p) -> case p^.pinfoNodes of VirtualCAD n ns -> stNodePool %= (\xs -> Set.delete (NodeInfo me) $ Set.singleton n <> Set.fromList ns <> xs) _ -> return () -- | Generate unique ID uniqID :: MonadState StateDNA m => m Int uniqID = do i <- use stCounter stCounter .= (i + 1) return i
SKA-ScienceDataProcessor/RC
MS5/dna/core/DNA/Interpreter/Types.hs
apache-2.0
13,559
0
21
3,771
2,917
1,553
1,364
271
7
module Handler.Root where import Import import Data.Time.Clock (getCurrentTime) import Model.Accessor data ThreadForm = ThreadForm { title :: Text } deriving Show threadForm :: Html -> MForm Jabaraster Jabaraster (FormResult ThreadForm, Widget) threadForm = renderDivs $ ThreadForm <$> areq textField "新規スレッド" Nothing getRootR :: Handler RepHtml getRootR = do ((_, widget), enctype) <- runFormPost threadForm threads <- runDB $ selectList [] [Desc ThreadUpdated] defaultLayout $ do setTitle "bbs homepage" $(widgetFile "homepage") $(widgetFile "submit") postRootR :: Handler RepHtml postRootR = runFormPost threadForm >>= processForm processForm :: ((FormResult ThreadForm, Widget), Enctype) -> Handler RepHtml processForm ((FormSuccess thread, _), _) = do now <- liftIO getCurrentTime _ <- runDB $ insert Thread { threadTitle = (title thread) , threadCreated = now , threadUpdated = now } redirect RedirectTemporary RootR processForm ((_, widget), enctype) = do threads <- runDB $ selectList [] [Desc ThreadUpdated] defaultLayout $ do setTitle "bbs homepage" $(widgetFile "homepage") $(widgetFile "submit")
jabaraster/yefib
Handler/Root.hs
bsd-2-clause
1,267
0
13
296
385
196
189
34
1
module Application.DiagramDrawer.Command where import Application.DiagramDrawer.ProgType import Application.DiagramDrawer.Job commandLineProcess :: Diagdrawer -> IO () commandLineProcess Test = do putStrLn "test called" startJob
wavewave/diagdrawer
lib/Application/DiagramDrawer/Command.hs
bsd-2-clause
236
0
7
28
50
27
23
7
1
{- | Module : IO Copyright : Copyright (C) 2013-2014 Krzysztof Langner License : BSD3 Helper module with functions operating on IO -} module IO ( listFiles , listDirs )where import System.Directory (canonicalizePath, getDirectoryContents, doesDirectoryExist) import Data.List import Control.Monad -- | list files listFiles :: FilePath -> IO [FilePath] listFiles p = do contents <- list p filterM (fmap not . doesDirectoryExist) contents -- | list subdirectories listDirs :: FilePath -> IO [FilePath] listDirs p = do contents <- list p filterM doesDirectoryExist contents -- | list directory content list :: FilePath -> IO [FilePath] list p = do ds <- getDirectoryContents p let filtered = filter f ds path <- canonicalizePath $ p return $ map ((path++"/")++) filtered where f x = and [x /= ".", x /= "..", (not . isPrefixOf ".") x]
klangner/Condor
src-app/IO.hs
bsd-2-clause
952
0
12
255
258
132
126
21
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Web.Twitter.Conduit.Base ( ResponseBodyType (..), NoContent, getResponse, call, call', callWithResponse, callWithResponse', checkResponse, sourceWithMaxId, sourceWithMaxId', sourceWithCursor, sourceWithCursor', sourceWithSearchResult, sourceWithSearchResult', endpoint, makeRequest, sinkJSON, sinkFromJSON, ) where import Web.Twitter.Conduit.Cursor import Web.Twitter.Conduit.Request import Web.Twitter.Conduit.Request.Internal import Web.Twitter.Conduit.Response import Web.Twitter.Conduit.Types import Web.Twitter.Types.Lens import Control.Lens import Control.Monad (void) import Control.Monad.Catch (MonadThrow (..)) import Control.Monad.IO.Class import Control.Monad.Trans.Resource (MonadResource, ResourceT, runResourceT) import Data.Aeson import Data.Aeson.Lens import Data.ByteString (ByteString) import Data.Coerce import qualified Data.Conduit as C import qualified Data.Conduit.Attoparsec as CA import qualified Data.Conduit.List as CL import qualified Data.Map as M import qualified Data.Text.Encoding as T import GHC.TypeLits (KnownSymbol) import Network.HTTP.Client.MultipartFormData import qualified Network.HTTP.Conduit as HTTP import qualified Network.HTTP.Types as HT import Web.Authenticate.OAuth (signOAuth) makeRequest :: APIRequest apiName responseType -> IO HTTP.Request makeRequest (APIRequest m u pa) = makeRequest' m u (makeSimpleQuery pa) makeRequest (APIRequestMultipart m u param prt) = formDataBody body =<< makeRequest' m u [] where body = prt ++ partParam partParam = Prelude.map (uncurry partBS . over _1 T.decodeUtf8) (makeSimpleQuery param) makeRequest (APIRequestJSON m u param body) = do req <- makeRequest' m u (makeSimpleQuery param) return $ req { HTTP.requestBody = HTTP.RequestBodyLBS $ encode body , HTTP.requestHeaders = ("Content-Type", "application/json") : HTTP.requestHeaders req } makeRequest' :: -- | HTTP request method (GET or POST) HT.Method -> -- | API Resource URL String -> -- | Query HT.SimpleQuery -> IO HTTP.Request makeRequest' m url query = do req <- HTTP.parseRequest url let addParams = if m == "POST" then HTTP.urlEncodedBody query else \r -> r {HTTP.queryString = HT.renderSimpleQuery False query} return $ addParams $ req {HTTP.method = m} class ResponseBodyType a where parseResponseBody :: Response (C.ConduitM () ByteString (ResourceT IO) ()) -> ResourceT IO (Response a) type NoContent = () instance ResponseBodyType NoContent where parseResponseBody res = case responseStatus res of st | st == HT.status204 -> return $ void res _ -> do body <- C.runConduit $ responseBody res C..| sinkJSON throwM $ TwitterStatusError (responseStatus res) (responseHeaders res) body instance {-# OVERLAPPABLE #-} FromJSON a => ResponseBodyType a where parseResponseBody = getValueOrThrow getResponse :: MonadResource m => TWInfo -> HTTP.Manager -> HTTP.Request -> m (Response (C.ConduitM () ByteString m ())) getResponse TWInfo {..} mgr req = do signedReq <- signOAuth (twOAuth twToken) (twCredential twToken) $ req {HTTP.proxy = twProxy} res <- HTTP.http signedReq mgr return Response { responseStatus = HTTP.responseStatus res , responseHeaders = HTTP.responseHeaders res , responseBody = HTTP.responseBody res } endpoint :: String endpoint = "https://api.twitter.com/1.1/" getValue :: Response (C.ConduitM () ByteString (ResourceT IO) ()) -> ResourceT IO (Response Value) getValue res = do value <- C.runConduit $ responseBody res C..| sinkJSON return $ res {responseBody = value} checkResponse :: Response Value -> Either TwitterError Value checkResponse Response {..} = case responseBody ^? key "errors" of Just errs@(Array _) -> case fromJSON errs of Success errList -> Left $ TwitterErrorResponse responseStatus responseHeaders errList Error msg -> Left $ FromJSONError msg Just err -> Left $ TwitterUnknownErrorResponse responseStatus responseHeaders err Nothing -> if sci < 200 || sci > 400 then Left $ TwitterStatusError responseStatus responseHeaders responseBody else Right responseBody where sci = HT.statusCode responseStatus getValueOrThrow :: FromJSON a => Response (C.ConduitM () ByteString (ResourceT IO) ()) -> ResourceT IO (Response a) getValueOrThrow res = do res' <- getValue res case checkResponse res' of Left err -> throwM err Right _ -> return () case fromJSON (responseBody res') of Success r -> return $ res' {responseBody = r} Error err -> throwM $ FromJSONError err -- | Perform an 'APIRequest' and then provide the response which is mapped to a suitable type of -- <http://hackage.haskell.org/package/twitter-types twitter-types>. -- -- Example: -- -- @ -- user <- 'call' twInfo mgr $ 'accountVerifyCredentials' -- print user -- @ -- -- If you need raw JSON value which is parsed by <http://hackage.haskell.org/package/aeson aeson>, -- use 'call'' to obtain it. call :: ResponseBodyType responseType => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest apiName responseType -> IO responseType call = call' -- | Perform an 'APIRequest' and then provide the response. -- The response of this function is not restrict to @responseType@, -- so you can choose an arbitrarily type of FromJSON instances. call' :: ResponseBodyType value => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest apiName responseType -> IO value call' info mgr req = responseBody `fmap` callWithResponse' info mgr req -- | Perform an 'APIRequest' and then provide the 'Response'. -- -- Example: -- -- @ -- res \<- 'callWithResponse' twInfo mgr $ 'accountVerifyCredentials' -- 'print' $ 'responseStatus' res -- 'print' $ 'responseHeaders' res -- 'print' $ 'responseBody' res -- @ callWithResponse :: ResponseBodyType responseType => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest apiName responseType -> IO (Response responseType) callWithResponse = callWithResponse' -- | Perform an 'APIRequest' and then provide the 'Response'. -- The response of this function is not restrict to @responseType@, -- so you can choose an arbitrarily type of FromJSON instances. -- -- Example: -- -- @ -- res \<- 'callWithResponse'' twInfo mgr $ 'accountVerifyCredentials' -- 'print' $ 'responseStatus' res -- 'print' $ 'responseHeaders' res -- 'print' $ 'responseBody' (res :: Value) -- @ callWithResponse' :: ResponseBodyType value => TWInfo -> HTTP.Manager -> APIRequest apiName responseType -> IO (Response value) callWithResponse' info mgr req = runResourceT $ do res <- getResponse info mgr =<< liftIO (makeRequest req) parseResponseBody res -- | A wrapper function to perform multiple API request with changing @max_id@ parameter. -- -- This function cooperate with instances of 'HasMaxIdParam'. sourceWithMaxId :: ( MonadIO m , FromJSON responseType , AsStatus responseType , HasParam "max_id" Integer supports ) => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest supports [responseType] -> C.ConduitT () responseType m () sourceWithMaxId info mgr = loop where loop req = do res <- liftIO $ call info mgr req case getMinId res of Just mid -> do CL.sourceList res loop $ req & #max_id ?~ mid - 1 Nothing -> CL.sourceList res getMinId = minimumOf (traverse . status_id) -- | A wrapper function to perform multiple API request with changing @max_id@ parameter. -- The response of this function is not restrict to @responseType@, -- so you can choose an arbitrarily type of FromJSON instances. -- -- This function cooperate with instances of 'HasMaxIdParam'. sourceWithMaxId' :: ( MonadIO m , HasParam "max_id" Integer supports ) => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest supports [responseType] -> C.ConduitT () Value m () sourceWithMaxId' info mgr = loop where loop req = do (res :: [Value]) <- liftIO $ call' info mgr req case minimumOf (traverse . key "id" . _Integer) res of Just mid -> do CL.sourceList res loop $ req & #max_id ?~ mid - 1 Nothing -> CL.sourceList res -- | A wrapper function to perform multiple API request with changing @cursor@ parameter. -- -- This function cooperate with instances of 'HasCursorParam'. sourceWithCursor :: ( MonadIO m , FromJSON responseType , KnownSymbol ck , HasParam "cursor" Integer supports ) => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest supports (WithCursor Integer ck responseType) -> C.ConduitT () responseType m () sourceWithCursor info mgr req = loop (Just (-1)) where loop Nothing = CL.sourceNull loop (Just 0) = CL.sourceNull loop (Just cur) = do res <- liftIO $ call info mgr $ req & #cursor ?~ cur CL.sourceList $ contents res loop $ nextCursor res -- | A wrapper function to perform multiple API request with changing @cursor@ parameter. -- The response of this function is not restrict to @responseType@, -- so you can choose an arbitrarily type of FromJSON instances. -- -- This function cooperate with instances of 'HasCursorParam'. sourceWithCursor' :: ( MonadIO m , KnownSymbol ck , HasParam "cursor" Integer supports ) => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest supports (WithCursor Integer ck responseType) -> C.ConduitT () Value m () sourceWithCursor' info mgr req = loop (Just (-1)) where relax :: APIRequest apiName (WithCursor Integer ck responseType) -> APIRequest apiName (WithCursor Integer ck Value) relax = coerce loop Nothing = CL.sourceNull loop (Just 0) = CL.sourceNull loop (Just cur) = do res <- liftIO $ call info mgr $ relax $ req & #cursor ?~ cur CL.sourceList $ contents res loop $ nextCursor res -- | A wrapper function to perform multiple API request with @SearchResult@. sourceWithSearchResult :: ( MonadIO m , FromJSON responseType ) => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest supports (SearchResult [responseType]) -> m (SearchResult (C.ConduitT () responseType m ())) sourceWithSearchResult info mgr req = do res <- liftIO $ call info mgr req let body = CL.sourceList (res ^. searchResultStatuses) <> loop (res ^. searchResultSearchMetadata . searchMetadataNextResults) return $ res & searchResultStatuses .~ body where origQueryMap = req ^. params . to M.fromList loop Nothing = CL.sourceNull loop (Just nextResultsStr) = do let nextResults = nextResultsStr & HT.parseSimpleQuery . T.encodeUtf8 & traversed . _2 %~ (PVString . T.decodeUtf8) nextParams = M.toList $ M.union (M.fromList nextResults) origQueryMap res <- liftIO $ call info mgr $ req & params .~ nextParams CL.sourceList (res ^. searchResultStatuses) loop $ res ^. searchResultSearchMetadata . searchMetadataNextResults -- | A wrapper function to perform multiple API request with @SearchResult@. sourceWithSearchResult' :: ( MonadIO m ) => -- | Twitter Setting TWInfo -> HTTP.Manager -> APIRequest supports (SearchResult [responseType]) -> m (SearchResult (C.ConduitT () Value m ())) sourceWithSearchResult' info mgr req = do res <- liftIO $ call info mgr $ relax req let body = CL.sourceList (res ^. searchResultStatuses) <> loop (res ^. searchResultSearchMetadata . searchMetadataNextResults) return $ res & searchResultStatuses .~ body where origQueryMap = req ^. params . to M.fromList relax :: APIRequest apiName (SearchResult [responseType]) -> APIRequest apiName (SearchResult [Value]) relax = coerce loop Nothing = CL.sourceNull loop (Just nextResultsStr) = do let nextResults = nextResultsStr & HT.parseSimpleQuery . T.encodeUtf8 & traversed . _2 %~ (PVString . T.decodeUtf8) nextParams = M.toList $ M.union (M.fromList nextResults) origQueryMap res <- liftIO $ call info mgr $ relax $ req & params .~ nextParams CL.sourceList (res ^. searchResultStatuses) loop $ res ^. searchResultSearchMetadata . searchMetadataNextResults sinkJSON :: ( MonadThrow m ) => C.ConduitT ByteString o m Value sinkJSON = CA.sinkParser json sinkFromJSON :: ( FromJSON a , MonadThrow m ) => C.ConduitT ByteString o m a sinkFromJSON = do v <- sinkJSON case fromJSON v of Error err -> throwM $ FromJSONError err Success r -> return r
himura/twitter-conduit
src/Web/Twitter/Conduit/Base.hs
bsd-2-clause
13,541
0
17
3,244
3,341
1,720
1,621
-1
-1
module Transf.Id where import Lang.Php import TransfUtil import qualified Data.Intercal as IC transfs :: [Transf] transfs = [ "id" -:- ftype -?- "For testing lex-pass. Rewrite all files as is." -=- argless (lexPass $ changeNothing False True), "no-op" -:- ftype -?- "For testing lex-pass. Scan all files but do nothing." -=- argless (lexPass $ changeNothing False False), "dump-ast" -:- ftype -?- "For testing lex-pass. Dump the AST." -=- argless (lexPass $ changeNothing True False), "dump-ast-id" -:- ftype -?- "For testing lex-pass. Dump the AST and rewrite as is." -=- argless (lexPass $ changeNothing True True)] -- optionally pretend we changed something to make this file count and force -- rewrite. changeNothing :: Bool -> Bool -> Ast -> Transformed Ast changeNothing dumpAst pretendMod ast = Transformed (if dumpAst then [show ast] else []) $ if pretendMod then Just ast else Nothing
facebookarchive/lex-pass
src/Transf/Id.hs
bsd-3-clause
937
0
10
184
226
121
105
24
3
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Snap.Snaplet.ActionLog ( -- * Core types and functions ActionLog , initActionLog , HasActionLog(..) , ActionType(..) , actionToInt , intToAction , DeltaField(..) , CanDelta(..) , storeDeltas , getDeltas -- * Retrieving actions , getLoggedAction , getEntityActions , getAllActions , getTenantActions , getTenantEntities , getTenantUids -- * Storing actions -- $storingActions , logAction , loggedInsert , loggedReplace , loggedUpdate , loggedDelete , loggedDeleteKey -- * Types , actionLogEntityDefs , migrateActionLog , LoggedAction(..) , LoggedActionId , LoggedActionDetails(..) , LoggedActionDetailsId ) where ------------------------------------------------------------------------------ import Control.Lens import Control.Monad import qualified Data.Map.Syntax as MS import Data.Monoid as Monoid import Data.Text.Encoding import Heist import qualified Heist.Interpreted as I import Snap import Snap.Restful import Snap.Snaplet.Heist.Compiled ------------------------------------------------------------------------------ import Paths_snaplet_actionlog import Snap.Snaplet.ActionLog.API import Snap.Snaplet.ActionLog.Resource import Snap.Snaplet.ActionLog.Types ------------------------------------------------------------------------------- ------------------------------------------------------------------------------ -- | Initializer for the action log snaplet. It sets up templates, routes, -- and compiled and interpreted splices. -- -- Includes two built-in top level splices: actionLogListing and -- actionLogFilterForm initActionLog :: (HasActionLog (Handler b b), HasHeist b) => Snaplet (Heist b) -> SnapletInit b ActionLog initActionLog heist = makeSnaplet "actionlog" description datadir $ do url <- getSnapletRootURL let resource = actionLogR { rRoot = decodeUtf8 url } addResourceRelative resource [(RIndex, indexH), (RShow, showH)] [] [] heist addConfig heist $ Monoid.mempty & scCompiledSplices .~ actionLogSplices resource & scInterpretedSplices .~ actionLogISplices resource -- Load time splices are for splices that can be used in the apply and -- bind tags. & scLoadTimeSplices .~ ("actionlogTemplate" MS.## I.textSplice (decodeUtf8 url)) addTemplates heist "" return ActionLog where description = "Snaplet providing generalized logging" datadir = Just $ liftM (++"/resources") getDataDir -- $storingActions -- These functions provide a nice API for logging actions based on database -- operations. Typically you should be able to simply substitute the -- 'loggedInsert', 'loggedUpdate', etc functions in the place of your existing -- calls to 'insert', 'update', etc from the persistent library.
Soostone/snaplet-actionlog
src/Snap/Snaplet/ActionLog.hs
bsd-3-clause
3,352
0
15
764
458
280
178
68
1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Doc.Extending -- Copyright : (C) 2007 Andrea Rossato -- License : BSD3 -- -- Maintainer : andrea.rossato@unibz.it -- Stability : unstable -- Portability : portable -- -- This module documents the xmonad-contrib library and -- how to use it to extend the capabilities of xmonad. -- -- Reading this document should not require a deep knowledge of -- Haskell; the examples are intended to be useful and understandable -- for those users who do not know Haskell and don't want to have to -- learn it just to configure xmonad. You should be able to get by -- just fine by ignoring anything you don't understand and using the -- provided examples as templates. However, relevant Haskell features -- are discussed when appropriate, so this document will hopefully be -- useful for more advanced Haskell users as well. -- -- Those wishing to be totally hardcore and develop their own xmonad -- extensions (it's easier than it sounds, we promise!) should read -- the documentation in "XMonad.Doc.Developing". -- -- More configuration examples may be found on the Haskell wiki: -- -- <http://haskell.org/haskellwiki/Xmonad/Config_archive> -- ----------------------------------------------------------------------------- module XMonad.Doc.Extending ( -- * The xmonad-contrib library -- $library -- ** Actions -- $actions -- ** Configurations -- $configs -- ** Hooks -- $hooks -- ** Layouts -- $layouts -- ** Prompts -- $prompts -- ** Utilities -- $utils -- * Extending xmonad -- $extending -- ** Editing key bindings -- $keys -- *** Adding key bindings -- $keyAdding -- *** Removing key bindings -- $keyDel -- *** Adding and removing key bindings -- $keyAddDel -- ** Editing mouse bindings -- $mouse -- ** Editing the layout hook -- $layoutHook -- ** Editing the manage hook -- $manageHook -- ** The log hook and external status bars -- $logHook ) where -------------------------------------------------------------------------------- -- -- The XmonadContrib Library -- -------------------------------------------------------------------------------- {- $library The xmonad-contrib (xmc) library is a set of extension modules contributed by xmonad hackers and users, which provide additional xmonad features. Examples include various layout modes (tabbed, spiral, three-column...), prompts, program launchers, the ability to manipulate windows and workspaces in various ways, alternate navigation modes, and much more. There are also \"meta-modules\" which make it easier to write new modules and extensions. This is a concise yet complete overview of the xmonad-contrib modules. For more information about any particular module, just click on its name to view its Haddock documentation; each module should come with extensive documentation. If you find a module that could be better documented, or has incorrect documentation, please report it as a bug (<http://code.google.com/p/xmonad/issues/list>)! -} {- $actions In the @XMonad.Actions@ namespace you can find modules exporting various functions that are usually intended to be bound to key combinations or mouse actions, in order to provide functionality beyond the standard keybindings provided by xmonad. See "XMonad.Doc.Extending#Editing_key_bindings" for instructions on how to edit your key bindings. * "XMonad.Actions.Commands": Allows you to run internal xmonad commands (X () actions) using a dmenu menu in addition to key bindings. Requires dmenu and the Dmenu XMonad.Actions module. * "XMonad.Actions.ConstrainedResize": Lets you constrain the aspect ratio of a floating window (by, say, holding shift while you resize). Useful for making a nice circular XClock window. * "XMonad.Actions.CopyWindow": Provides bindings to duplicate a window on multiple workspaces, providing dwm-like tagging functionality. * "XMonad.Actions.CycleRecentWS": Provides bindings to cycle through most recently used workspaces with repeated presses of a single key (as long as modifier key is held down). This is similar to how many window managers handle window switching. * "XMonad.Actions.CycleSelectedLayouts": This module allows to cycle through the given subset of layouts. * "XMonad.Actions.CycleWS": Provides bindings to cycle forward or backward through the list of workspaces, to move windows between workspaces, and to cycle between screens. Replaces the former XMonad.Actions.RotView. * "XMonad.Actions.CycleWindows": Provides bindings to cycle windows up or down on the current workspace stack while maintaining focus in place. * "XMonad.Actions.DeManage": This module provides a method to cease management of a window without unmapping it. "XMonad.Hooks.ManageDocks" is a more automated solution if your panel supports it. * "XMonad.Actions.DwmPromote": Dwm-like swap function for xmonad. Swaps focused window with the master window. If focus is in the master, swap it with the next window in the stack. Focus stays in the master. * "XMonad.Actions.DynamicWorkspaces": Provides bindings to add and delete workspaces. Note that you may only delete a workspace that is already empty. * "XMonad.Actions.FindEmptyWorkspace": Find an empty workspace. * "XMonad.Actions.FlexibleManipulate": Move and resize floating windows without warping the mouse. * "XMonad.Actions.FlexibleResize": Resize floating windows from any corner. * "XMonad.Actions.FloatKeys": Move and resize floating windows. * "XMonad.Layout.FloatSnap": Move and resize floating windows using other windows and the edge of the screen as guidelines. * "XMonad.Actions.FocusNth": Focus the nth window of the current workspace. * "XMonad.Actions.GridSelect": GridSelect displays items(e.g. the opened windows) in a 2D grid and lets the user select from it with the cursor/hjkl keys or the mouse. * "XMonad.Actions.MessageFeedback": Alternative to 'XMonad.Operations.sendMessage' that provides knowledge of whether the message was handled, and utility functions based on this facility. * "XMonad.Actions.MouseGestures": Support for simple mouse gestures. * "XMonad.Actions.MouseResize": A layout modifier to resize windows with the mouse by grabbing the window's lower right corner. * "XMonad.Actions.NoBorders": This module provides helper functions for dealing with window borders. * "XMonad.Actions.OnScreen": Control workspaces on different screens (in xinerama mode). * "XMonad.Actions.PerWorkspaceKeys": Define key-bindings on per-workspace basis. * "XMonad.Actions.PhysicalScreens": Manipulate screens ordered by physical location instead of ID * "XMonad.Actions.Plane": This module has functions to navigate through workspaces in a bidimensional manner. * "XMonad.Actions.Promote": Alternate promote function for xmonad. * "XMonad.Actions.RandomBackground": An action to start terminals with a random background color * "XMonad.Actions.RotSlaves": Rotate all windows except the master window and keep the focus in place. * "XMonad.Actions.Search": A module for easily running Internet searches on web sites through xmonad. Modeled after the handy Surfraw CLI search tools at <https://secure.wikimedia.org/wikipedia/en/wiki/Surfraw>. * "XMonad.Actions.SimpleDate": An example external contrib module for XMonad. Provides a simple binding to dzen2 to print the date as a popup menu. * "XMonad.Actions.SinkAll": (Deprecated) Provides a simple binding that pushes all floating windows on the current workspace back into tiling. Instead, use the more general "XMonad.Actions.WithAll" * "XMonad.Actions.SpawnOn": Provides a way to modify a window spawned by a command(e.g shift it to the workspace it was launched on) by using the _NET_WM_PID property that most windows set on creation. * "XMonad.Actions.Submap": A module that allows the user to create a sub-mapping of key bindings. * "XMonad.Actions.SwapWorkspaces": Lets you swap workspace tags, so you can keep related ones next to each other, without having to move individual windows. * "XMonad.Actions.TagWindows": Functions for tagging windows and selecting them by tags. * "XMonad.Actions.TopicSpace": Turns your workspaces into a more topic oriented system. * "XMonad.Actions.UpdateFocus": Updates the focus on mouse move in unfocused windows. * "XMonadContrib.UpdatePointer": Causes the pointer to follow whichever window focus changes to. * "XMonad.Actions.Warp": Warp the pointer to a given window or screen. * "XMonad.Actions.WindowBringer": dmenu operations to bring windows to you, and bring you to windows. That is to say, it pops up a dmenu with window names, in case you forgot where you left your XChat. * "XMonad.Actions.WindowGo": Defines a few convenient operations for raising (traveling to) windows based on XMonad's Query monad, such as 'runOrRaise'. * "XMonad.Actions.WindowMenu": Uses "XMonad.Actions.GridSelect" to display a number of actions related to window management in the center of the focused window. * "XMonad.Actions.WindowNavigation": Experimental rewrite of "XMonad.Layout.WindowNavigation". * "XMonad.Actions.WithAll": Provides functions for performing a given action on all windows of the current workspace. * "XMonad.Actions.WorkspaceCursors": Like "XMonad.Actions.Plane" for an arbitrary number of dimensions. -} {- $configs In the @XMonad.Config@ namespace you can find modules exporting the configurations used by some of the xmonad and xmonad-contrib developers. You can look at them for examples while creating your own configuration; you can also simply import them and use them as your own configuration, possibly with some modifications. * "XMonad.Config.Arossato" This module specifies my xmonad defaults. * "XMonad.Config.Azerty" Fixes some keybindings for users of French keyboard layouts. * "XMonad.Config.Desktop" This module provides core desktop environment settings used in the Gnome, Kde, and Xfce config configs. It is also useful for people using other environments such as lxde, or using tray or panel applications without full desktop environments. * "XMonad.Config.Gnome" * "XMonad.Config.Kde" * "XMonad.Config.Sjanssen" * "XMonad.Config.Xfce" -} {- $hooks In the @XMonad.Hooks@ namespace you can find modules exporting hooks. Hooks are actions that xmonad performs when certain events occur. The two most important hooks are: * 'XMonad.Core.manageHook': this hook is called when a new window xmonad must take care of is created. This is a very powerful hook, since it lets us examine the new window's properties and act accordingly. For instance, we can configure xmonad to put windows belonging to a given application in the float layer, not to manage dock applications, or open them in a given workspace. See "XMonad.Doc.Extending#Editing_the_manage_hook" for more information on customizing 'XMonad.Core.manageHook'. * 'XMonad.Core.logHook': this hook is called when the stack of windows managed by xmonad has been changed, by calling the 'XMonad.Operations.windows' function. For instance "XMonad.Hooks.DynamicLog" will produce a string (whose format can be configured) to be printed to the standard output. This can be used to display some information about the xmonad state in a status bar. See "XMonad.Doc.Extending#The_log_hook_and_external_status_bars" for more information. * 'XMonad.Core.handleEventHook': this hook is called on all events handled by xmonad, thus it is extremely powerful. See "Graphics.X11.Xlib.Extras" and xmonad source and development documentation for more details. Here is a list of the modules found in @XMonad.Hooks@: * "XMonad.Hooks.DynamicHooks": One-shot and permanent ManageHooks that can be updated at runtime. * "XMonad.Hooks.DynamicLog": for use with 'XMonad.Core.logHook'; send information about xmonad's state to standard output, suitable for putting in a status bar of some sort. See "XMonad.Doc.Extending#The_log_hook_and_external_status_bars". * "XMonad.Hooks.EwmhDesktops": Makes xmonad use the EWMH hints to tell panel applications about its workspaces and the windows therein. It also allows the user to interact with xmonad by clicking on panels and window lists. * "XMonad.Hooks.FadeInactive": Makes XMonad set the _NET_WM_WINDOW_OPACITY atom for inactive windows, which causes those windows to become slightly translucent if something like xcompmgr is running * "XMonad.Hooks.FloatNext": Hook and keybindings for automatically sending the next spawned window(s) to the floating layer. * "XMonad.Hooks.InsertPosition": Configure where new windows should be added and which window should be focused. * "XMonad.Hooks.ManageDocks": This module provides tools to automatically manage 'dock' type programs, such as gnome-panel, kicker, dzen, and xmobar. * "XMonad.Hooks.ManageHelpers": provide helper functions to be used in @manageHook@. * "XMonad.Hooks.Minimize": Handles window manager hints to minimize and restore windows. Use this with XMonad.Layout.Minimize. * "XMonad.Hooks.Place": Automatic placement of floating windows. * "XMonad.Hooks.RestoreMinimized": (Deprecated: Use XMonad.Hooks.Minimize) Lets you restore minimized windows (see "XMonad.Layout.Minimize") by selecting them on a taskbar (listens for _NET_ACTIVE_WINDOW and WM_CHANGE_STATE). * "XMonad.Hooks.Script": Provides a simple interface for running a ~\/.xmonad\/hooks script with the name of a hook. * "XMonad.Hooks.ServerMode": Allows sending commands to a running xmonad process. * "XMonad.Hooks.SetCursor": Set a default mouse cursor on startup. * "XMonad.Hooks.SetWMName": Sets the WM name to a given string, so that it could be detected using _NET_SUPPORTING_WM_CHECK protocol. May be useful for making Java GUI programs work. * "XMonad.Hooks.UrgencyHook": UrgencyHook lets you configure an action to occur when a window demands your attention. (In traditional WMs, this takes the form of \"flashing\" on your \"taskbar.\" Blech.) * "XMonad.Hooks.WorkspaceByPos": Useful in a dual-head setup: Looks at the requested geometry of new windows and moves them to the workspace of the non-focused screen if necessary. * "XMonad.Hooks.XPropManage": A ManageHook matching on XProperties. -} {- $layouts In the @XMonad.Layout@ namespace you can find modules exporting contributed tiling algorithms, such as a tabbed layout, a circle, a spiral, three columns, and so on. You will also find modules which provide facilities for combining different layouts, such as "XMonad.Layout.Combo", "XMonad.Layout.ComboP", "XMonad.Layout.LayoutBuilder", "XMonad.Layout.SubLayouts", or "XMonad.Layout.LayoutCombinators". Layouts can be also modified with layout modifiers. A general interface for writing layout modifiers is implemented in "XMonad.Layout.LayoutModifier". For more information on using those modules for customizing your 'XMonad.Core.layoutHook' see "XMonad.Doc.Extending#Editing_the_layout_hook". * "XMonad.Layout.Accordion": LayoutClass that puts non-focused windows in ribbons at the top and bottom of the screen. * "XMonad.Layout.AutoMaster": Provides layout modifier AutoMaster. It separates screen in two parts - master and slave. Size of slave area automatically changes depending on number of slave windows. * "XMonad.Layout.BorderResize": This layout modifier will allow to resize windows by dragging their borders with the mouse. However, it only works in layouts or modified layouts that react to the SetGeometry message. "XMonad.Layout.WindowArranger" can be used to create such a setup. BorderResize is probably most useful in floating layouts. * "XMonad.Layout.BoringWindows": BoringWindows is an extension to allow windows to be marked boring * "XMonad.Layout.CenteredMaster": Two layout modifiers. centerMaster places master window at center, on top of all other windows, which are managed by base layout. topRightMaster is similar, but places master window in top right corner instead of center. * "XMonad.Layout.Circle": Circle is an elliptical, overlapping layout. * "XMonad.Layout.Column": Provides Column layout that places all windows in one column. Windows heights are calculated from equation: H1/H2 = H2/H3 = ... = q, where q is given. With Shrink/Expand messages you can change the q value. * "XMonad.Layout.Combo": A layout that combines multiple layouts. * "XMonad.Layout.ComboP": A layout that combines multiple layouts and allows to specify where to put new windows. * "XMonad.Layout.Cross": A Cross Layout with the main window in the center. * "XMonad.Layout.Decoration": A layout modifier and a class for easily creating decorated layouts. * "XMonad.Layout.DecorationMadness": A collection of decorated layouts: some of them may be nice, some usable, others just funny. * "XMonad.Layout.Dishes": Dishes is a layout that stacks extra windows underneath the master windows. * "XMonad.Layout.DragPane": Layouts that splits the screen either horizontally or vertically and shows two windows. The first window is always the master window, and the other is either the currently focused window or the second window in layout order. See also "XMonad.Layout.MouseResizableTall" * "XMonad.Layout.DwmStyle": A layout modifier for decorating windows in a dwm like style. * "XMonad.Layout.FixedColumn": A layout much like Tall, but using a multiple of a window's minimum resize amount instead of a percentage of screen to decide where to split. This is useful when you usually leave a text editor or terminal in the master pane and like it to be 80 columns wide. * "XMonad.Layout.Gaps": Create manually-sized gaps along edges of the screen which will not be used for tiling, along with support for toggling gaps on and off. You probably want "XMonad.Hooks.ManageDocks". * "XMonad.Layout.Grid": A simple layout that attempts to put all windows in a square grid. * "XMonad.Layout.GridVariants": Two layouts: one is a variant of the Grid layout that allows the desired aspect ratio of windows to be specified. The other is like Tall but places a grid with fixed number of rows and columns in the master area and uses an aspect-ratio-specified layout for the slaves. * "XMonad.Layout.HintedGrid": A not so simple layout that attempts to put all windows in a square grid while obeying their size hints. * "XMonad.Layout.HintedTile": A gapless tiled layout that attempts to obey window size hints, rather than simply ignoring them. * "XMonad.Layout.IM": Layout modfier suitable for workspace with multi-windowed instant messenger (like Psi or Tkabber). * "XMonad.Layout.IndependentScreens": Utility functions for simulating independent sets of workspaces on each screen (like dwm's workspace model), using internal tags to distinguish workspaces associated with each screen. * "XMonad.Layout.LayoutBuilder": A layout combinator that sends a specified number of windows to one rectangle and the rest to another. * "XMonad.Layout.LayoutCombinators": The "XMonad.Layout.LayoutCombinators" module provides combinators for easily combining multiple layouts into one composite layout, as well as a way to jump directly to any particular layout (say, with a keybinding) without having to cycle through other layouts to get to it. * "XMonad.Layout.LayoutHints": Make layouts respect size hints. * "XMonad.Layout.LayoutModifier": A module for writing easy layout modifiers, which do not define a layout in and of themselves, but modify the behavior of or add new functionality to other layouts. If you ever find yourself writing a layout which takes another layout as a parameter, chances are you should be writing a LayoutModifier instead! In case it is not clear, this module is not intended to help you configure xmonad, it is to help you write other extension modules. So get hacking! * "XMonad.Layout.LayoutScreens": Divide a single screen into multiple screens. * "XMonad.Layout.LimitWindows": A layout modifier that limits the number of windows that can be shown. * "XMonad.Layout.MagicFocus": Automagically put the focused window in the master area. * "XMonad.Layout.Magnifier": Screenshot : <http://caladan.rave.org/magnifier.png> This is a layout modifier that will make a layout increase the size of the window that has focus. * "XMonad.Layout.Master": Layout modfier that adds a master window to another layout. * "XMonad.Layout.Maximize": Temporarily yanks the focused window out of the layout to mostly fill the screen. * "XMonad.Layout.MessageControl": Provides message escaping and filtering facilities which help control complex nested layouts. * "XMonad.Layout.Minimize": Makes it possible to minimize windows, temporarily removing them from the layout until they are restored. * "XMonad.Layout.Monitor": Layout modfier for displaying some window (monitor) above other windows * "XMonad.Layout.Mosaic": Based on MosaicAlt, but aspect ratio messages always change the aspect ratios, and rearranging the window stack changes the window sizes. * "XMonad.Layout.MosaicAlt": A layout which gives each window a specified amount of screen space relative to the others. Compared to the 'Mosaic' layout, this one divides the space in a more balanced way. * "XMonad.Layout.MouseResizableTile": A layout in the spirit of "XMonad.Layout.ResizableTile", but with the option to use the mouse to adjust the layout. * "XMonad.Layout.MultiToggle": Dynamically apply and unapply transformers to your window layout. This can be used to rotate your window layout by 90 degrees, or to make the currently focused window occupy the whole screen (\"zoom in\") then undo the transformation (\"zoom out\"). * "XMonad.Layout.Named": A module for assigning a name to a given layout. * "XMonad.Layout.NoBorders": Make a given layout display without borders. This is useful for full-screen or tabbed layouts, where you don't really want to waste a couple of pixels of real estate just to inform yourself that the visible window has focus. * "XMonad.Layout.NoFrillsDecoration": Most basic version of decoration for windows without any additional modifications. In contrast to "XMonad.Layout.SimpleDecoration" this will result in title bars that span the entire window instead of being only the length of the window title. * "XMonad.Layout.OneBig": Places one (master) window at top left corner of screen, and other (slave) windows at the top. * "XMonad.Layout.PerWorkspace": Configure layouts on a per-workspace basis: use layouts and apply layout modifiers selectively, depending on the workspace. * "XMonad.Layout.Reflect": Reflect a layout horizontally or vertically. * "XMonad.Layout.ResizableTile": More useful tiled layout that allows you to change a width\/height of window. See also "XMonad.Layout.MouseResizableTile". * "XMonad.Layout.ResizeScreen": A layout transformer to have a layout respect a given screen geometry. Mostly used with "Decoration" (the Horizontal and the Vertical version will react to SetTheme and change their dimension accordingly. * "XMonad.Layout.Roledex": This is a completely pointless layout which acts like Microsoft's Flip 3D * "XMonad.Layout.ShowWName": This is a layout modifier that will show the workspace name * "XMonad.Layout.SimpleDecoration": A layout modifier for adding simple decorations to the windows of a given layout. The decorations are in the form of ion-like tabs for window titles. * "XMonad.Layout.SimpleFloat": A basic floating layout. * "XMonad.Layout.Simplest": A very simple layout. The simplest, afaik. Used as a base for decorated layouts. * "XMonad.Layout.SimplestFloat": A basic floating layout like SimpleFloat but without the decoration. * "XMonad.Layout.Spacing": Add a configurable amount of space around windows. * "XMonad.Layout.Spiral": A spiral tiling layout. * "XMonad.Layout.Square": A layout that splits the screen into a square area and the rest of the screen. This is probably only ever useful in combination with "XMonad.Layout.Combo". It sticks one window in a square region, and makes the rest of the windows live with what's left (in a full-screen sense). * "XMonad.Layout.StackTile": A stacking layout, like dishes but with the ability to resize master pane. Mostly useful on small screens. * "XMonad.Layout.SubLayouts": A layout combinator that allows layouts to be nested. * "XMonad.Layout.TabBarDecoration": A layout modifier to add a bar of tabs to your layouts. * "XMonad.Layout.Tabbed": A tabbed layout for the Xmonad Window Manager * "XMonad.Layout.ThreeColumns": A layout similar to tall but with three columns. With 2560x1600 pixels this layout can be used for a huge main window and up to six reasonable sized slave windows. * "XMonad.Layout.ToggleLayouts": A module to toggle between two layouts. * "XMonad.Layout.TwoPane": A layout that splits the screen horizontally and shows two windows. The left window is always the master window, and the right is either the currently focused window or the second window in layout order. * "XMonad.Layout.WindowArranger": This is a pure layout modifier that will let you move and resize windows with the keyboard in any layout. * "XMonad.Layout.WindowNavigation": WindowNavigation is an extension to allow easy navigation of a workspace. See also "XMonad.Actions.WindowNavigation". * "XMonad.Layout.WorkspaceDir": WorkspaceDir is an extension to set the current directory in a workspace. Actually, it sets the current directory in a layout, since there's no way I know of to attach a behavior to a workspace. This means that any terminals (or other programs) pulled up in that workspace (with that layout) will execute in that working directory. Sort of handy, I think. Note this extension requires the 'directory' package to be installed. -} {- $prompts In the @XMonad.Prompt@ name space you can find modules providing graphical prompts for getting user input and using it to perform various actions. The "XMonad.Prompt" provides a library for easily writing new prompt modules. These are the available prompts: * "XMonad.Prompt.AppLauncher": A module for launch applicationes that receive parameters in the command line. The launcher call a prompt to get the parameters. * "XMonad.Prompt.AppendFile": A prompt for appending a single line of text to a file. Useful for keeping a file of notes, things to remember for later, and so on--- using a keybinding, you can write things down just about as quickly as you think of them, so it doesn't have to interrupt whatever else you're doing. Who knows, it might be useful for other purposes as well! * "XMonad.Prompt.DirExec": A directory file executables prompt for XMonad. This might be useful if you don't want to have scripts in your PATH environment variable (same executable names, different behavior) - otherwise you might want to use "XMonad.Prompt.Shell" instead - but you want to have easy access to these executables through the xmonad's prompt. * "XMonad.Prompt.Directory": A directory prompt for XMonad * "XMonad.Prompt.Email": A prompt for sending quick, one-line emails, via the standard GNU \'mail\' utility (which must be in your $PATH). This module is intended mostly as an example of using "XMonad.Prompt.Input" to build an action requiring user input. * "XMonad.Prompt.Input": A generic framework for prompting the user for input and passing it along to some other action. * "XMonad.Prompt.Layout": A layout-selection prompt for XMonad * "XMonad.Prompt.Man": A manual page prompt for XMonad window manager. TODO * narrow completions by section number, if the one is specified (like @\/etc\/bash_completion@ does) * "XMonad.Prompt.RunOrRaise": A prompt for XMonad which will run a program, open a file, or raise an already running program, depending on context. * "XMonad.Prompt.Shell": A shell prompt for XMonad * "XMonad.Prompt.Ssh": A ssh prompt for XMonad * "XMonad.Prompt.Theme": A prompt for changing the theme of the current workspace * "XMonad.Prompt.Window": xprompt operations to bring windows to you, and bring you to windows. * "XMonad.Prompt.Workspace": A workspace prompt for XMonad * "XMonad.Prompt.XMonad": A prompt for running XMonad commands Usually a prompt is called by some key binding. See "XMonad.Doc.Extending#Editing_key_bindings", which includes examples of adding some prompts. -} {- $utils In the @XMonad.Util@ namespace you can find modules exporting various utility functions that are used by the other modules of the xmonad-contrib library. There are also utilities for helping in configuring xmonad or using external utilities. A non complete list with a brief description: * "XMonad.Util.Cursor": configure the default cursor/pointer glyph. * "XMonad.Util.CustomKeys": configure key bindings (see "XMonad.Doc.Extending#Editing_key_bindings"). * "XMonad.Util.Dmenu": A convenient binding to dmenu. Requires the process-1.0 package * "XMonad.Util.Dzen": Handy wrapper for dzen. Requires dzen >= 0.2.4. * "XMonad.Util.EZConfig": configure key bindings easily, including a parser for writing key bindings in "M-C-x" style. * "XMonad.Util.Font": A module for abstracting a font facility over Core fonts and Xft * "XMonad.Util.Invisible": A data type to store the layout state * "XMonad.Util.Loggers": A collection of simple logger functions and formatting utilities which can be used in the 'XMonad.Hooks.DynamicLog.ppExtras' field of a pretty-printing status logger format. See "XMonad.Hooks.DynamicLog" for more information. * "XMonad.Util.NamedActions": A wrapper for keybinding configuration that can list the available keybindings. * "XMonad.Util.NamedScratchpad": Like "XMonad.Util.Scratchpad" toggle windows to and from the current workspace. Supports several arbitrary applications at the same time. * "XMonad.Util.NamedWindows": This module allows you to associate the X titles of windows with them. * "XMonad.Util.Paste": A module for sending key presses to windows. This modules provides generalized and specialized functions for this task. * "XMonad.Util.Replace": Implements a @--replace@ flag outside of core. * "XMonad.Util.Run": This modules provides several commands to run an external process. It is composed of functions formerly defined in "XMonad.Util.Dmenu" (by Spencer Janssen), "XMonad.Util.Dzen" (by glasser\@mit.edu) and XMonad.Util.RunInXTerm (by Andrea Rossato). * "XMonad.Util.Scratchpad": Very handy hotkey-launched toggleable floating terminal window. * "XMonad.Util.StringProp": Internal utility functions for storing Strings with the root window. Used for global state like IORefs with string keys, but more latency, persistent between xmonad restarts. * "XMonad.Util.Themes": A (hopefully) growing collection of themes for decorated layouts. * "XMonad.Util.Timer": A module for setting up timers * "XMonad.Util.Types": Miscellaneous commonly used types. * "XMonad.Util.WindowProperties": EDSL for specifying window properties; various utilities related to window properties. * "XMonad.Util.XSelection": A module for accessing and manipulating X Window's mouse selection (the buffer used in copy and pasting). 'getSelection' and 'putSelection' are adaptations of Hxsel.hs and Hxput.hs from the XMonad-utils * "XMonad.Util.XUtils": A module for painting on the screen -} -------------------------------------------------------------------------------- -- -- Extending Xmonad -- -------------------------------------------------------------------------------- {- $extending #Extending_xmonad# Since the @xmonad.hs@ file is just another Haskell module, you may import and use any Haskell code or libraries you wish, such as extensions from the xmonad-contrib library, or other code you write yourself. -} {- $keys #Editing_key_bindings# Editing key bindings means changing the 'XMonad.Core.XConfig.keys' field of the 'XMonad.Core.XConfig' record used by xmonad. For example, you could write: > import XMonad > > main = xmonad $ defaultConfig { keys = myKeys } and provide an appropriate definition of @myKeys@, such as: > myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList > [ ((modm, xK_F12), xmonadPrompt defaultXPConfig) > , ((modm, xK_F3 ), shellPrompt defaultXPConfig) > ] This particular definition also requires importing "XMonad.Prompt", "XMonad.Prompt.Shell", "XMonad.Prompt.XMonad", and "Data.Map": > import qualified Data.Map as M > import XMonad.Prompt > import XMonad.Prompt.Shell > import XMonad.Prompt.XMonad For a list of the names of particular keys (such as xK_F12, and so on), see <http://hackage.haskell.org/packages/archive/X11/latest/doc/html/Graphics-X11-Types.html> Usually, rather than completely redefining the key bindings, as we did above, we want to simply add some new bindings and\/or remove existing ones. -} {- $keyAdding #Adding_key_bindings# Adding key bindings can be done in different ways. See the end of this section for the easiest ways. The type signature of 'XMonad.Core.XConfig.keys' is: > keys :: XConfig Layout -> M.Map (ButtonMask,KeySym) (X ()) In order to add new key bindings, you need to first create an appropriate 'Data.Map.Map' from a list of key bindings using 'Data.Map.fromList'. This 'Data.Map.Map' of new key bindings then needs to be joined to a 'Data.Map.Map' of existing bindings using 'Data.Map.union'. Since we are going to need some of the functions of the "Data.Map" module, before starting we must first import this modules: > import qualified Data.Map as M For instance, if you have defined some additional key bindings like these: > myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList > [ ((modm, xK_F12), xmonadPrompt defaultXPConfig) > , ((modm, xK_F3 ), shellPrompt defaultXPConfig) > ] then you can create a new key bindings map by joining the default one with yours: > newKeys x = myKeys x `M.union` keys defaultConfig x Finally, you can use @newKeys@ in the 'XMonad.Core.XConfig.keys' field of the configuration: > main = xmonad $ defaultConfig { keys = newKeys } Alternatively, the '<+>' operator can be used which in this usage does exactly the same as the explicit usage of 'M.union' and propagation of the config argument, thanks to appropriate instances in "Data.Monoid". > main = xmonad $ defaultConfig { keys = myKeys <+> keys defaultConfig } All together, your @~\/.xmonad\/xmonad.hs@ would now look like this: > module Main (main) where > > import XMonad > > import qualified Data.Map as M > import Graphics.X11.Xlib > import XMonad.Prompt > import XMonad.Prompt.Shell > import XMonad.Prompt.XMonad > > main :: IO () > main = xmonad $ defaultConfig { keys = myKeys <+> keys defaultConfig } > > myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList > [ ((modm, xK_F12), xmonadPrompt defaultXPConfig) > , ((modm, xK_F3 ), shellPrompt defaultXPConfig) > ] There are much simpler ways to accomplish this, however, if you are willing to use an extension module to help you configure your keys. For instance, "XMonad.Util.EZConfig" and "XMonad.Util.CustomKeys" both provide useful functions for editing your key bindings; "XMonad.Util.EZConfig" even lets you use emacs-style keybinding descriptions like \"M-C-<F12>\". -} {- $keyDel #Removing_key_bindings# Removing key bindings requires modifying the 'Data.Map.Map' which stores the key bindings. This can be done with 'Data.Map.difference' or with 'Data.Map.delete'. For example, suppose you want to get rid of @mod-q@ and @mod-shift-q@ (you just want to leave xmonad running forever). To do this you need to define @newKeys@ as a 'Data.Map.difference' between the default map and the map of the key bindings you want to remove. Like so: > newKeys x = keys defaultConfig x `M.difference` keysToRemove x > > keysToRemove :: XConfig Layout -> M.Map (KeyMask, KeySym) (X ()) > keysToRemove x = M.fromList > [ ((modm , xK_q ), return ()) > , ((modm .|. shiftMask, xK_q ), return ()) > ] As you can see, it doesn't matter what actions we associate with the keys listed in @keysToRemove@, so we just use @return ()@ (the \"null\" action). It is also possible to simply define a list of keys we want to unbind and then use 'Data.Map.delete' to remove them. In that case we would write something like: > newKeys x = foldr M.delete (keys defaultConfig x) (keysToRemove x) > > keysToRemove :: XConfig Layout -> [(KeyMask, KeySym)] > keysToRemove x = > [ (modm , xK_q ) > , (modm .|. shiftMask, xK_q ) > ] Another even simpler possibility is the use of some of the utilities provided by the xmonad-contrib library. Look, for instance, at 'XMonad.Util.EZConfig.removeKeys'. -} {- $keyAddDel #Adding_and_removing_key_bindings# Adding and removing key bindings requires simply combining the steps for removing and adding. Here is an example from "XMonad.Config.Arossato": > defKeys = keys defaultConfig > delKeys x = foldr M.delete (defKeys x) (toRemove x) > newKeys x = foldr (uncurry M.insert) (delKeys x) (toAdd x) > -- remove some of the default key bindings > toRemove XConfig{modMask = modm} = > [ (modm , xK_j ) > , (modm , xK_k ) > , (modm , xK_p ) > , (modm .|. shiftMask, xK_p ) > , (modm .|. shiftMask, xK_q ) > , (modm , xK_q ) > ] ++ > -- I want modm .|. shiftMask 1-9 to be free! > [(shiftMask .|. modm, k) | k <- [xK_1 .. xK_9]] > -- These are my personal key bindings > toAdd XConfig{modMask = modm} = > [ ((modm , xK_F12 ), xmonadPrompt defaultXPConfig ) > , ((modm , xK_F3 ), shellPrompt defaultXPConfig ) > ] ++ > -- Use modm .|. shiftMask .|. controlMask 1-9 instead > [( (m .|. modm, k), windows $ f i) > | (i, k) <- zip (workspaces x) [xK_1 .. xK_9] > , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask .|. controlMask)] > ] You can achieve the same result using the "XMonad.Util.CustomKeys" module; take a look at the 'XMonad.Util.CustomKeys.customKeys' function in particular. NOTE: modm is defined as the modMask you defined (or left as the default) in your config. -} {- $mouse #Editing_mouse_bindings# Most of the previous discussion of key bindings applies to mouse bindings as well. For example, you could configure button4 to close the window you click on like so: > import qualified Data.Map as M > > myMouse x = [ (0, button4), (\w -> focus w >> kill) ] > > newMouse x = M.union (mouseBindings defaultConfig x) (M.fromList (myMouse x)) > > main = xmonad $ defaultConfig { ..., mouseBindings = newMouse, ... } Overriding or deleting mouse bindings works similarly. You can also configure mouse bindings much more easily using the 'XMonad.Util.EZConfig.additionalMouseBindings' and 'XMonad.Util.EZConfig.removeMouseBindings' functions from the "XMonad.Util.EZConfig" module. -} {- $layoutHook #Editing_the_layout_hook# When you start an application that opens a new window, when you change the focused window, or move it to another workspace, or change that workspace's layout, xmonad will use the 'XMonad.Core.layoutHook' for reordering the visible windows on the visible workspace(s). Since different layouts may be attached to different workspaces, and you can change them, xmonad needs to know which one to use. In this sense the layoutHook may be thought as the list of layouts that xmonad will use for laying out windows on the screen(s). The problem is that the layout subsystem is implemented with an advanced feature of the Haskell programming language: type classes. This allows us to very easily write new layouts, combine or modify existing layouts, create layouts with internal state, etc. See "XMonad.Doc.Extending#The_LayoutClass" for more information. This means that we cannot simply have a list of layouts as we used to have before the 0.5 release: a list requires every member to belong to the same type! Instead the combination of layouts to be used by xmonad is created with a specific layout combinator: 'XMonad.Layout.|||'. Suppose we want a list with the 'XMonad.Layout.Full', 'XMonad.Layout.Tabbed.tabbed' and 'XMonad.Layout.Accordion.Accordion' layouts. First we import, in our @~\/.xmonad\/xmonad.hs@, all the needed modules: > import XMonad > > import XMonad.Layout.Tabbed > import XMonad.Layout.Accordion Then we create the combination of layouts we need: > mylayoutHook = Full ||| tabbed shrinkText defaultTheme ||| Accordion Now, all we need to do is change the 'XMonad.Core.layoutHook' field of the 'XMonad.Core.XConfig' record, like so: > main = xmonad $ defaultConfig { layoutHook = mylayoutHook } Thanks to the new combinator, we can apply a layout modifier to a whole combination of layouts, instead of applying it to each one. For example, suppose we want to use the 'XMonad.Layout.NoBorders.noBorders' layout modifier, from the "XMonad.Layout.NoBorders" module (which must be imported): > mylayoutHook = noBorders (Full ||| tabbed shrinkText defaultTheme ||| Accordion) If we want only the tabbed layout without borders, then we may write: > mylayoutHook = Full ||| noBorders (tabbed shrinkText defaultTheme) ||| Accordion Our @~\/.xmonad\/xmonad.hs@ will now look like this: > import XMonad > > import XMonad.Layout.Tabbed > import XMonad.Layout.Accordion > import XMonad.Layout.NoBorders > > mylayoutHook = Full ||| noBorders (tabbed shrinkText defaultTheme) ||| Accordion > > main = xmonad $ defaultConfig { layoutHook = mylayoutHook } That's it! -} {- $manageHook #Editing_the_manage_hook# The 'XMonad.Core.manageHook' is a very powerful tool for customizing the behavior of xmonad with regard to new windows. Whenever a new window is created, xmonad calls the 'XMonad.Core.manageHook', which can thus be used to perform certain actions on the new window, such as placing it in a specific workspace, ignoring it, or placing it in the float layer. The default 'XMonad.Core.manageHook' causes xmonad to float MPlayer and Gimp, and to ignore gnome-panel, desktop_window, kicker, and kdesktop. The "XMonad.ManageHook" module provides some simple combinators that can be used to alter the 'XMonad.Core.manageHook' by replacing or adding to the default actions. Let's start by analyzing the default 'XMonad.Config.manageHook', defined in "XMonad.Config": > manageHook :: ManageHook > manageHook = composeAll > [ className =? "MPlayer" --> doFloat > , className =? "Gimp" --> doFloat > , resource =? "desktop_window" --> doIgnore > , resource =? "kdesktop" --> doIgnore ] 'XMonad.ManageHook.composeAll' can be used to compose a list of different 'XMonad.Config.ManageHook's. In this example we have a list of 'XMonad.Config.ManageHook's formed by the following commands: the Mplayer's and the Gimp's windows, whose 'XMonad.ManageHook.className' are, respectively \"Mplayer\" and \"Gimp\", are to be placed in the float layer with the 'XMonad.ManageHook.doFloat' function; the windows whose resource names are respectively \"desktop_window\" and \kdesktop\" are to be ignored with the 'XMonad.ManageHook.doIgnore' function. This is another example of 'XMonad.Config.manageHook', taken from "XMonad.Config.Arossato": > myManageHook = composeAll [ resource =? "realplay.bin" --> doFloat > , resource =? "win" --> doF (W.shift "doc") -- xpdf > , resource =? "firefox-bin" --> doF (W.shift "web") > ] > newManageHook = myManageHook <+> manageHook defaultConfig Again we use 'XMonad.ManageHook.composeAll' to compose a list of different 'XMonad.Config.ManageHook's. The first one will put RealPlayer on the float layer, the second one will put the xpdf windows in the workspace named \"doc\", with 'XMonad.ManageHook.doF' and 'XMonad.StackSet.shift' functions, and the third one will put all firefox windows on the workspace called "web". Then we use the 'XMonad.ManageHook.<+>' combinator to compose @myManageHook@ with the default 'XMonad.Config.manageHook' to form @newManageHook@. Each 'XMonad.Config.ManageHook' has the form: > property =? match --> action Where @property@ can be: * 'XMonad.ManageHook.title': the window's title * 'XMonad.ManageHook.resource': the resource name * 'XMonad.ManageHook.className': the resource class name. * 'XMonad.ManageHook.stringProperty' @somestring@: the contents of the property @somestring@. (You can retrieve the needed information using the X utility named @xprop@; for example, to find the resource class name, you can type > xprop | grep WM_CLASS at a prompt, then click on the window whose resource class you want to know.) @match@ is the string that will match the property value (for instance the one you retrieved with @xprop@). An @action@ can be: * 'XMonad.ManageHook.doFloat': to place the window in the float layer; * 'XMonad.ManageHook.doIgnore': to ignore the window; * 'XMonad.ManageHook.doF': to execute a function with the window as argument. For example, suppose we want to add a 'XMonad.Config.manageHook' to float RealPlayer, which usually has a 'XMonad.ManageHook.resource' name of \"realplay.bin\". First we need to import "XMonad.ManageHook": > import XMonad.ManageHook Then we create our own 'XMonad.Config.manageHook': > myManageHook = resource =? "realplay.bin" --> doFloat We can now use the 'XMonad.ManageHook.<+>' combinator to add our 'XMonad.Config.manageHook' to the default one: > newManageHook = myManageHook <+> manageHook defaultConfig (Of course, if we wanted to completely replace the default 'XMonad.Config.manageHook', this step would not be necessary.) Now, all we need to do is change the 'XMonad.Core.manageHook' field of the 'XMonad.Core.XConfig' record, like so: > main = xmonad defaultConfig { ..., manageHook = newManageHook, ... } And we are done. Obviously, we may wish to add more then one 'XMonad.Config.manageHook'. In this case we can use a list of hooks, compose them all with 'XMonad.ManageHook.composeAll', and add the composed to the default one. For instance, if we want RealPlayer to float and thunderbird always opened in the workspace named "mail", we can do so like this: > myManageHook = composeAll [ resource =? "realplay.bin" --> doFloat > , resource =? "thunderbird-bin" --> doF (W.shift "mail") > ] Remember to import the module that defines the 'XMonad.StackSet.shift' function, "XMonad.StackSet", like this: > import qualified XMonad.StackSet as W And then we can add @myManageHook@ to the default one to create @newManageHook@ as we did in the previous example. One more thing to note about this system is that if a window matches multiple rules in a 'XMonad.Config.manageHook', /all/ of the corresponding actions will be run (in the order in which they are defined). This is a change from versions before 0.5, when only the first rule that matched was run. Finally, for additional rules and actions you can use in your manageHook, check out the contrib module "XMonad.Hooks.ManageHelpers". -} {- $logHook #The_log_hook_and_external_status_bars# When the stack of the windows managed by xmonad changes for any reason, xmonad will call 'XMonad.Core.logHook', which can be used to output some information about the internal state of xmonad, such as the layout that is presently in use, the workspace we are in, the focused window's title, and so on. Extracting information about the internal xmonad state can be somewhat difficult if you are not familiar with the source code. Therefore, it's usually easiest to use a module that has been designed specifically for logging some of the most interesting information about the internal state of xmonad: "XMonad.Hooks.DynamicLog". This module can be used with an external status bar to print the produced logs in a convenient way; the most commonly used status bars are dzen and xmobar. By default the 'XMonad.Core.logHook' doesn't produce anything. To enable it you need first to import "XMonad.Hooks.DynamicLog": > import XMonad.Hooks.DynamicLog Then you just need to update the 'XMonad.Core.logHook' field of the 'XMonad.Core.XConfig' record with one of the provided functions. For example: > main = xmonad defaultConfig { logHook = dynamicLog } More interesting configurations are also possible; see the "XMonad.Hooks.DynamicLog" module for more possibilities. You may now enjoy your extended xmonad experience. Have fun! -}
csstaub/xmonad-contrib
XMonad/Doc/Extending.hs
bsd-3-clause
50,343
0
3
9,658
99
96
3
2
0
-- Testing ---------------------------------------------------------------- module Tests where ---------------------------------------------------------------- import Test.Tasty import Test.Tasty.QuickCheck -- for property testing import Test.Tasty.HUnit -- for case testing import Finite.Tests ---------------------------------------------------------------- -- MAIN ---------------------------------------------------------------- main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [propertyTests, unitTests] propertyTests :: TestTree propertyTests = testGroup "Property Tests" [ finitePropertyTests] unitTests :: TestTree unitTests = testGroup "Unit Tests" [ finiteCaseTests]
Conflagrationator/HMath
tests/tests.hs
bsd-3-clause
728
0
6
81
109
66
43
15
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} {-| [@ISO639-1@] ru [@ISO639-2@] rus [@ISO639-3@] rus [@Native name@] Русский язык [@English name@] Russian -} module Text.Numeral.Language.RUS.TestData (cardinals) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import "base" Prelude ( Integral ) import "base-unicode-symbols" Prelude.Unicode ( (⋅) ) import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection ) import "numerals" Text.Numeral.Misc ( dec ) import "this" Text.Numeral.Test ( TestData ) -------------------------------------------------------------------------------- -- Test data -------------------------------------------------------------------------------- {- Sources: http://en.wikibooks.org/wiki/Russian/Numbers http://russian.speak7.com/russian_numbers.htm http://learningrussian.net/games_verbs_grammar3.php http://www.waytorussia.net/WhatIsRussia/Russian/Part1a.html -} cardinals ∷ (Integral i) ⇒ TestData i cardinals = [ ( "default" , defaultInflection , [ (0, "ноль") , (1, "один") , (2, "два") , (3, "три") , (4, "четыре") , (5, "пять") , (6, "шесть") , (7, "семь") , (8, "восемь") , (9, "девять") , (10, "десять") , (11, "одиннадцать") , (12, "двенадцать") , (13, "тринадцать") , (14, "четырнадцать") , (15, "пятнадцать") , (16, "шестнадцать") , (17, "семнадцать") , (18, "восемнадцать") , (19, "девятнадцать") , (20, "двадцать") , (21, "двадцать один") , (22, "двадцать два") , (23, "двадцать три") , (24, "двадцать четыре") , (25, "двадцать пять") , (26, "двадцать шесть") , (27, "двадцать семь") , (28, "двадцать восемь") , (29, "двадцать девять") , (30, "тридцать") , (31, "тридцать один") , (32, "тридцать два") , (33, "тридцать три") , (34, "тридцать четыре") , (35, "тридцать пять") , (36, "тридцать шесть") , (37, "тридцать семь") , (38, "тридцать восемь") , (39, "тридцать девять") , (40, "сорок") , (41, "сорок один") , (42, "сорок два") , (43, "сорок три") , (44, "сорок четыре") , (45, "сорок пять") , (46, "сорок шесть") , (47, "сорок семь") , (48, "сорок восемь") , (49, "сорок девять") , (50, "пятьдесят") , (51, "пятьдесят один") , (52, "пятьдесят два") , (53, "пятьдесят три") , (54, "пятьдесят четыре") , (55, "пятьдесят пять") , (56, "пятьдесят шесть") , (57, "пятьдесят семь") , (58, "пятьдесят восемь") , (59, "пятьдесят девять") , (60, "шестьдесят") , (61, "шестьдесят один") , (62, "шестьдесят два") , (63, "шестьдесят три") , (64, "шестьдесят четыре") , (65, "шестьдесят пять") , (66, "шестьдесят шесть") , (67, "шестьдесят семь") , (68, "шестьдесят восемь") , (69, "шестьдесят девять") , (70, "семьдесят") , (71, "семьдесят один") , (72, "семьдесят два") , (73, "семьдесят три") , (74, "семьдесят четыре") , (75, "семьдесят пять") , (76, "семьдесят шесть") , (77, "семьдесят семь") , (78, "семьдесят восемь") , (79, "семьдесят девять") , (80, "восемьдесят") , (81, "восемьдесят один") , (82, "восемьдесят два") , (83, "восемьдесят три") , (84, "восемьдесят четыре") , (85, "восемьдесят пять") , (86, "восемьдесят шесть") , (87, "восемьдесят семь") , (88, "восемьдесят восемь") , (89, "восемьдесят девять") , (90, "девяносто") , (91, "девяносто один") , (92, "девяносто два") , (93, "девяносто три") , (94, "девяносто четыре") , (95, "девяносто пять") , (96, "девяносто шесть") , (97, "девяносто семь") , (98, "девяносто восемь") , (99, "девяносто девять") , (100, "сто") , (101, "сто один") , (108, "сто восемь") , (110, "сто десять") , (115, "сто пятнадцать") , (121, "сто двадцать один") , (133, "сто тридцать три") , (147, "сто сорок семь") , (200, "двести") , (300, "триста") , (400, "четыреста") , (500, "пятьсот") , (600, "шестьсот") , (700, "семьсот") , (800, "восемьсот") , (900, "девятьсот") , (1000, "тысяча") , (2000, "две тысячи") , (3000, "три тысячи") , (5000, "пять тысяч") , (6000, "шесть тысяч") , (9000, "девять тысяч") , (16000, "шестнадцать тысяч") , (21000, "двадцать одна тысяча") , (22000, "двадцать две тысячи") , (23000, "двадцать три тысячи") , (28000, "двадцать восемь тысяч") , (41000, "сорок одна тысяча") , (42000, "сорок две тысячи") , (49000, "сорок девять тысяч") , (100000, "сто тысяч") , (200000, "двести тысяч") , (300000, "триста тысяч") , (300001, "триста тысяч один") , (300020, "триста тысяч двадцать") , (300825, "триста тысячь восемьсот двадцать пять") , (dec 6, "один миллион") , (2 ⋅ dec 6, "два миллиона") , (5 ⋅ dec 6, "пять миллионов") , (dec 9, "один миллиард") , (2 ⋅ dec 9, "два миллиарда") ] ) ]
telser/numerals
src-test/Text/Numeral/Language/RUS/TestData.hs
bsd-3-clause
7,265
0
10
1,585
1,416
940
476
156
1
import System.Environment (getArgs) import Data.Char (digitToInt, intToDigit) count :: (Eq a) => a -> [a] -> Int count x ys = length (filter (== x) ys) selfd :: Int -> String -> Bool selfd i s | i > 9 || i == length s = True | digitToInt (s!!i) == count (intToDigit i) s = selfd (succ i) s | otherwise = False selfDesc :: String -> String selfDesc s | selfd 0 s = "1" | otherwise = "0" main :: IO () main = do [inpFile] <- getArgs input <- readFile inpFile putStr . unlines . map selfDesc $ lines input
nikai3d/ce-challenges
easy/self_describing_numbers.hs
bsd-3-clause
609
0
11
210
265
130
135
16
1
{-| Module : Idris.Elab.Implementation Description : Code to elaborate instances. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE PatternGuards #-} module Idris.Elab.Implementation(elabImplementation) where import Idris.AbsSyntax import Idris.ASTUtils import Idris.Core.CaseTree import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.TT import Idris.Core.Typecheck import Idris.Coverage import Idris.DataOpts import Idris.DeepSeq import Idris.Delaborate import Idris.Docstrings import Idris.DSL import Idris.Elab.Data import Idris.Elab.Term import Idris.Elab.Type import Idris.Elab.Utils import Idris.Error import Idris.Imports import Idris.Inliner import Idris.Output (iWarn, iputStrLn, pshow, sendHighlighting) import Idris.PartialEval import Idris.Primitives import Idris.Providers import IRTS.Lang import Util.Pretty (pretty, text) import Prelude hiding (id, (.)) import Control.Applicative hiding (Const) import Control.Category import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.Char (isLetter, toLower) import Data.List import Data.List.Split (splitOn) import qualified Data.Map as Map import Data.Maybe import qualified Data.Set as S import qualified Data.Text as T import Debug.Trace elabImplementation :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) -> [(Name, Docstring (Either Err PTerm))] -> ElabWhat -- ^ phase -> FC -> [(Name, PTerm)] -- ^ constraints -> [Name] -- ^ parent dictionary names (optionally) -> Accessibility -> FnOpts -> Name -- ^ the interface -> FC -- ^ precise location of interface name -> [PTerm] -- ^ interface parameters (i.e. implementation) -> [(Name, PTerm)] -- ^ Extra arguments in scope (e.g. implementation in where block) -> PTerm -- ^ full implementation type -> Maybe Name -- ^ explicit name -> [PDecl] -> Idris () elabImplementation info syn doc argDocs what fc cs parents acc opts n nfc ps pextra t expn ds = do ist <- getIState (n, ci) <- case lookupCtxtName n (idris_interfaces ist) of [c] -> return c [] -> ifail $ show fc ++ ":" ++ show n ++ " is not an interface" cs -> tclift $ tfail $ At fc (CantResolveAlts (map fst cs)) let constraint = PApp fc (PRef fc [] n) (map pexp ps) let iname = mkiname n (namespace info) ps expn putIState (ist { hide_list = addDef iname acc (hide_list ist) }) ist <- getIState let totopts = Dictionary : Inlinable : opts let emptyinterface = null (interface_methods ci) when (what /= EDefns) $ do nty <- elabType' True info syn doc argDocs fc totopts iname NoFC (piBindp expl_param pextra t) -- if the implementation type matches any of the implementations we have already, -- and it's not a named implementation, then it's overlapping, so report an error case expn of Nothing | OverlappingDictionary `notElem` opts -> do mapM_ (maybe (return ()) overlapping . findOverlapping ist (interface_determiners ci) (delab ist nty)) (map fst $ interface_implementations ci) addImplementation intImpl True n iname _ -> addImplementation intImpl False n iname when (what /= ETypes && (not (null ds && not emptyinterface))) $ do -- Add the parent implementation names to the privileged set oldOpen <- addOpenImpl parents let ips = zip (interface_params ci) ps let ns = case n of NS n ns' -> ns' _ -> [] -- get the implicit parameters that need passing through to the -- where block wparams <- mapM (\p -> case p of PApp _ _ args -> getWParams (map getTm args) a@(PRef fc _ f) -> getWParams [a] _ -> return []) ps ist <- getIState let pnames = nub $ map pname (concat (nub wparams)) ++ concatMap (namesIn [] ist) ps let superInterfaceImplementations = map (substImplementation ips pnames) (interface_default_super_interfaces ci) undefinedSuperInterfaceImplementations <- filterM (fmap not . isOverlapping ist) superInterfaceImplementations mapM_ (rec_elabDecl info EAll info) undefinedSuperInterfaceImplementations ist <- getIState -- Bring variables in implementation head into scope when building the -- dictionary let headVars = nub $ concatMap getHeadVars ps let (headVarTypes, ty) = case lookupTyExact iname (tt_ctxt ist) of Just ty -> (map (\n -> (n, getTypeIn ist n ty)) headVars, ty) _ -> (zip headVars (repeat Placeholder), Erased) let impps = getImpParams ist (interface_impparams ci) (snd (unApply (substRetTy ty))) let iimpps = zip (interface_impparams ci) impps logElab 5 $ "ImpPS: " ++ show impps ++ " --- " ++ show iimpps logElab 5 $ "Head var types " ++ show headVarTypes ++ " from " ++ show ty let all_meths = map (nsroot . fst) (interface_methods ci) let mtys = map (\ (n, (inj, op, t)) -> let t_in = substMatchesShadow (iimpps ++ ips) pnames t mnamemap = map (\n -> (n, PApp fc (PRef fc [] (decorate ns iname n)) (map (toImp fc) headVars))) all_meths t' = substMatchesShadow mnamemap pnames t_in in (decorate ns iname n, op, coninsert cs pextra t', t')) (interface_methods ci) logElab 5 (show (mtys, (iimpps ++ ips))) logElab 5 ("Before defaults: " ++ show ds ++ "\n" ++ show (map fst (interface_methods ci))) let ds_defs = insertDefaults ist iname (interface_defaults ci) ns ds logElab 3 ("After defaults: " ++ show ds_defs ++ "\n") let ds' = map (addUnfold iname (map fst (interface_methods ci))) $ reorderDefs (map fst (interface_methods ci)) ds_defs logElab 1 ("Reordered: " ++ show ds' ++ "\n") mapM_ (warnMissing ds' ns iname) (map fst (interface_methods ci)) mapM_ (checkInInterface (map fst (interface_methods ci))) (concatMap defined ds') let wbTys = map mkTyDecl mtys let wbVals_orig = map (decorateid (decorate ns iname)) ds' ist <- getIState let wbVals = map (expandParamsD False ist id pextra (map methName mtys)) wbVals_orig let wb = wbTys ++ wbVals logElab 3 $ "Method types " ++ showSep "\n" (map (show . showDeclImp verbosePPOption . mkTyDecl) mtys) logElab 3 $ "Implementation is " ++ show ps ++ " implicits " ++ show (concat (nub wparams)) let lhsImps = map (\n -> pimp n (PRef fc [] n) True) headVars let lhs = PApp fc (PRef fc [] iname) (lhsImps ++ map (toExp .fst) pextra) let rhs = PApp fc (PRef fc [] (implementationCtorName ci)) (map (pexp . (mkMethApp lhsImps)) mtys) logElab 5 $ "Implementation LHS " ++ show totopts ++ "\n" ++ showTmImpls lhs ++ " " ++ show headVars logElab 5 $ "Implementation RHS " ++ show rhs push_estack iname True logElab 3 ("Method types: " ++ show wbTys) logElab 3 ("Method bodies (before params): " ++ show wbVals_orig) logElab 3 ("Method bodies: " ++ show wbVals) let idecls = [PClauses fc totopts iname [PClause fc iname lhs [] rhs []]] mapM_ (rec_elabDecl info EAll info) (map (impBind headVarTypes) wbTys) mapM_ (rec_elabDecl info EAll info) idecls ctxt <- getContext let ifn_ty = case lookupTyExact iname ctxt of Just t -> t Nothing -> error "Can't happen (interface constructor)" let ifn_is = case lookupCtxtExact iname (idris_implicits ist) of Just t -> t Nothing -> [] let prop_params = getParamsInType ist [] ifn_is ifn_ty logElab 3 $ "Propagating parameters to methods: " ++ show (iname, prop_params) let wbVals' = map (addParams prop_params) wbVals logElab 5 ("Elaborating method bodies: " ++ show wbVals') mapM_ (rec_elabDecl info EAll info) wbVals' mapM_ (checkInjectiveDef fc (interface_methods ci)) (zip ds' wbVals') pop_estack setOpenImpl oldOpen -- totalityCheckBlock checkInjectiveArgs fc n (interface_determiners ci) (lookupTyExact iname (tt_ctxt ist)) addIBC (IBCImplementation intImpl (isNothing expn) n iname) where getImpParams ist = zipWith (\n tm -> delab ist tm) intImpl = case ps of [PConstant NoFC (AType (ATInt ITNative))] -> True _ -> False addUnfold iname ms (PTy doc docs syn fc opts n fc' tm) = PTy doc docs syn fc (UnfoldIface iname ms : opts) n fc' tm addUnfold iname ms (PClauses fc opts n cs) = PClauses fc (UnfoldIface iname ms : opts) n cs addUnfold iname ms dec = dec mkiname n' ns ps' expn' = case expn' of Nothing -> case ns of [] -> SN (sImplementationN n' (map show ps')) m -> sNS (SN (sImplementationN n' (map show ps'))) m Just nm -> nm substImplementation ips pnames (PImplementation doc argDocs syn _ cs parents acc opts n nfc ps pextra t expn ds) = PImplementation doc argDocs syn fc cs parents acc opts n nfc (map (substMatchesShadow ips pnames) ps) pextra (substMatchesShadow ips pnames t) expn ds isOverlapping i (PImplementation doc argDocs syn _ _ _ _ _ n nfc ps pextra t expn _) = case lookupCtxtName n (idris_interfaces i) of [(n, ci)] -> let iname = (mkiname n (namespace info) ps expn) in case lookupTy iname (tt_ctxt i) of [] -> elabFindOverlapping i ci iname syn t (_:_) -> return True _ -> return False -- couldn't find interface, just let elabImplementation fail later -- TODO: largely based upon elabType' - should try to abstract -- Issue #1614 in the issue tracker: -- https://github.com/idris-lang/Idris-dev/issues/1614 elabFindOverlapping i ci iname syn t = do ty' <- addUsingConstraints syn fc t -- TODO think: something more in info? ty' <- implicit info syn iname ty' let ty = addImpl [] i ty' ctxt <- getContext (ElabResult tyT _ _ ctxt' newDecls highlights newGName, _) <- tclift $ elaborate (constraintNS info) ctxt (idris_datatypes i) (idris_name i) iname (TType (UVal 0)) initEState (errAt "type of " iname Nothing (erun fc (build i info ERHS [] iname ty))) setContext ctxt' processTacticDecls info newDecls sendHighlighting highlights updateIState $ \i -> i { idris_name = newGName } ctxt <- getContext (cty, _) <- recheckC (constraintNS info) fc id [] tyT let nty = normalise ctxt [] cty return $ any (isJust . findOverlapping i (interface_determiners ci) (delab i nty)) (map fst $ interface_implementations ci) findOverlapping i dets t n | SN (ParentN _ _) <- n = Nothing | Just opts <- lookupCtxtExact n (idris_flags i), OverlappingDictionary `elem` opts = Nothing | otherwise = case lookupTy n (tt_ctxt i) of [t'] -> let tret = getRetType t tret' = getRetType (delab i t') in case matchArgs i dets tret' tret of Right _ -> Just tret' Left _ -> case matchArgs i dets tret tret' of Right _ -> Just tret' Left _ -> Nothing _ -> Nothing overlapping t' = tclift $ tfail (At fc (Msg $ "Overlapping implementation: " ++ show t' ++ " already defined")) getRetType (PPi _ _ _ _ sc) = getRetType sc getRetType t = t matchArgs i dets x y = let x' = keepDets dets x y' = keepDets dets y in matchClause i x' y' keepDets dets (PApp fc f args) = PApp fc f $ let a' = zip [0..] args in map snd (filter (\(i, _) -> i `elem` dets) a') keepDets dets t = t methName (n, _, _, _) = n toExp n = pexp (PRef fc [] n) mkMethApp ps (n, _, _, ty) = lamBind 0 ty (papp fc (PRef fc [] n) (ps ++ map (toExp . fst) pextra ++ methArgs 0 ty)) where needed is p = pname p `elem` map pname is lamBind i (PPi (Constraint _ _ _) _ _ _ sc) sc' = PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc') lamBind i (PPi _ n _ ty sc) sc' = PLam fc (sMN i "meth") NoFC Placeholder (lamBind (i+1) sc sc') lamBind i _ sc = sc methArgs i (PPi (Imp _ _ _ _ _ _) n _ ty sc) = PImp 0 True [] n (PRef fc [] (sMN i "meth")) : methArgs (i+1) sc methArgs i (PPi (Exp _ _ _ _) n _ ty sc) = PExp 0 [] (sMN 0 "marg") (PRef fc [] (sMN i "meth")) : methArgs (i+1) sc methArgs i (PPi (Constraint _ _ _) n _ ty sc) = PConstraint 0 [] (sMN 0 "marg") (PResolveTC fc) : methArgs (i+1) sc methArgs i _ = [] papp fc f [] = f papp fc f as = PApp fc f as getWParams [] = return [] getWParams (p : ps) | PRef _ _ n <- p = do ps' <- getWParams ps ctxt <- getContext case lookupP n ctxt of [] -> return (pimp n (PRef fc [] n) True : ps') _ -> return ps' getWParams (_ : ps) = getWParams ps decorate ns iname (NS (UN nm) s) = NS (SN (WhereN 0 iname (SN (MethodN (UN nm))))) ns decorate ns iname nm = NS (SN (WhereN 0 iname (SN (MethodN nm)))) ns mkTyDecl (n, op, t, _) = PTy emptyDocstring [] syn fc op n NoFC (mkUniqueNames [] [] t) conbind :: [(Name, PTerm)] -> PTerm -> PTerm conbind ((c,ty) : ns) x = PPi constraint c NoFC ty (conbind ns x) conbind [] x = x extrabind :: [(Name, PTerm)] -> PTerm -> PTerm extrabind ((c,ty) : ns) x = PPi expl c NoFC ty (extrabind ns x) extrabind [] x = x coninsert :: [(Name, PTerm)] -> [(Name, PTerm)] -> PTerm -> PTerm coninsert cs ex (PPi p@(Imp _ _ _ _ _ _) n fc t sc) = PPi p n fc t (coninsert cs ex sc) coninsert cs ex sc = conbind cs (extrabind ex sc) -- Reorder declarations to be in the same order as defined in the -- interface declaration (important so that we insert default definitions -- in the right place, and so that dependencies between methods are -- respected) reorderDefs :: [Name] -> [PDecl] -> [PDecl] reorderDefs ns [] = [] reorderDefs [] ds = ds reorderDefs (n : ns) ds = case pick n [] ds of Just (def, ds') -> def : reorderDefs ns ds' Nothing -> reorderDefs ns ds pick n acc [] = Nothing pick n acc (def@(PClauses _ _ cn cs) : ds) | nsroot n == nsroot cn = Just (def, acc ++ ds) pick n acc (d : ds) = pick n (acc ++ [d]) ds insertDefaults :: IState -> Name -> [(Name, (Name, PDecl))] -> [T.Text] -> [PDecl] -> [PDecl] insertDefaults i iname [] ns ds = ds insertDefaults i iname ((n,(dn, clauses)) : defs) ns ds = insertDefaults i iname defs ns (insertDef i n dn clauses ns iname ds) insertDef i meth def clauses ns iname decls | not $ any (clauseFor meth iname ns) decls = let newd = expandParamsD False i (\n -> meth) [] [def] clauses in -- trace (show newd) $ decls ++ [newd] | otherwise = decls warnMissing decls ns iname meth | not $ any (clauseFor meth iname ns) decls = iWarn fc . text $ "method " ++ show meth ++ " not defined" | otherwise = return () checkInInterface ns meth | any (eqRoot meth) ns = return () | otherwise = tclift $ tfail (At fc (Msg $ show meth ++ " not a method of interface " ++ show n)) eqRoot x y = nsroot x == nsroot y clauseFor m iname ns (PClauses _ _ m' _) = decorate ns iname m == decorate ns iname m' clauseFor m iname ns _ = False getHeadVars :: PTerm -> [Name] getHeadVars (PRef _ _ n) | implicitable n = [n] getHeadVars (PApp _ _ args) = concatMap getHeadVars (map getTm args) getHeadVars (PPair _ _ _ l r) = getHeadVars l ++ getHeadVars r getHeadVars (PDPair _ _ _ l t r) = getHeadVars l ++ getHeadVars t ++ getHeadVars t getHeadVars _ = [] -- | Implicitly bind variables from the implementation head in method types impBind :: [(Name, PTerm)] -> PDecl -> PDecl impBind vs (PTy d ds syn fc opts n fc' t) = PTy d ds syn fc opts n fc' (doImpBind (filter (\(n, ty) -> n `notElem` boundIn t) vs) t) where doImpBind [] ty = ty doImpBind ((n, argty) : ns) ty = PPi impl n NoFC argty (doImpBind ns ty) boundIn (PPi _ n _ _ sc) = n : boundIn sc boundIn _ = [] getTypeIn :: IState -> Name -> Type -> PTerm getTypeIn ist n (Bind x b sc) | n == x = delab ist (binderTy b) | otherwise = getTypeIn ist n (substV (P Ref x Erased) sc) getTypeIn ist n tm = Placeholder toImp fc n = pimp n (PRef fc [] n) True -- | Propagate interface parameters to method bodies, if they're not -- already there, and they are needed (i.e. appear in method's type) addParams :: [Name] -> PDecl -> PDecl addParams ps (PClauses fc opts n cs) = PClauses fc opts n (map addCParams cs) where addCParams (PClause fc n lhs ws rhs wb) = PClause fc n (addTmParams (dropPs (allNamesIn lhs) ps) lhs) ws rhs wb addCParams (PWith fc n lhs ws sc pn ds) = PWith fc n (addTmParams (dropPs (allNamesIn lhs) ps) lhs) ws sc pn (map (addParams ps) ds) addCParams c = c addTmParams ps (PRef fc hls n) = PApp fc (PRef fc hls n) (map (toImp fc) ps) addTmParams ps (PApp fc ap@(PRef fc' hls n) args) = PApp fc ap (mergePs (map (toImp fc) ps) args) addTmParams ps tm = tm mergePs [] args = args mergePs (p : ps) args | isImplicit p, pname p `notElem` map pname args = p : mergePs ps args where isImplicit (PExp{}) = False isImplicit _ = True mergePs (p : ps) args = mergePs ps args -- Don't propagate a parameter if the name is rebound explicitly dropPs :: [Name] -> [Name] -> [Name] dropPs ns = filter (\x -> x `notElem` ns) addParams ps d = d -- | Check a given method definition is injective, if the interface info -- says it needs to be. Takes originally written decl and the one -- with name decoration, so we know which name to look up. checkInjectiveDef :: FC -> [(Name, (Bool, FnOpts, PTerm))] -> (PDecl, PDecl) -> Idris () checkInjectiveDef fc ns (PClauses _ _ n cs, PClauses _ _ elabn _) | Just (True, _, _) <- clookup n ns = do ist <- getIState case lookupDefExact elabn (tt_ctxt ist) of Just (CaseOp _ _ _ _ _ cdefs) -> checkInjectiveCase ist (snd (cases_compiletime cdefs)) where checkInjectiveCase ist (STerm tm) = checkInjectiveApp ist (fst (unApply tm)) checkInjectiveCase _ _ = notifail checkInjectiveApp ist (P (TCon _ _) n _) = return () checkInjectiveApp ist (P (DCon _ _ _) n _) = return () checkInjectiveApp ist (P Ref n _) | Just True <- lookupInjectiveExact n (tt_ctxt ist) = return () checkInjectiveApp ist (P Ref n _) = notifail checkInjectiveApp _ _ = notifail notifail = ierror $ At fc (Msg (show n ++ " must be defined by a type or data constructor")) clookup n [] = Nothing clookup n ((n', d) : ds) | nsroot n == nsroot n' = Just d | otherwise = Nothing checkInjectiveDef fc ns _ = return () checkInjectiveArgs :: FC -> Name -> [Int] -> Maybe Type -> Idris () checkInjectiveArgs fc n ds Nothing = return () checkInjectiveArgs fc n ds (Just ty) = do ist <- getIState let (_, args) = unApply (instantiateRetTy ty) ci 0 ist args where ci i ist (a : as) | i `elem` ds = if isInj ist a then ci (i + 1) ist as else tclift $ tfail (At fc (InvalidTCArg n a)) ci i ist (a : as) = ci (i + 1) ist as ci i ist [] = return () isInj i (P Bound n _) = True isInj i (P _ n _) = isConName n (tt_ctxt i) isInj i (App _ f a) = isInj i f && isInj i a isInj i (V _) = True isInj i (Bind n b sc) = isInj i sc isInj _ _ = True instantiateRetTy (Bind n (Pi _ _ _ _) sc) = substV (P Bound n Erased) (instantiateRetTy sc) instantiateRetTy t = t
bravit/Idris-dev
src/Idris/Elab/Implementation.hs
bsd-3-clause
21,882
1
28
7,397
7,829
3,891
3,938
405
42
----------------------------------------------------------------------------- -- | -- Module : System.Win32.Com.Server.StdDispatch -- Copyright : (c) Sigbjorn Finne <sof@dcs.gla.ac.uk> 1998-99 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : sof@forkIO.com -- Stability : provisional -- Portability : portable -- -- Implementation of IDispatch in Haskell; pretty useful -- when creating\/registering dynamic, on-the-fly event -- sinks. -- ----------------------------------------------------------------------------- module System.Win32.Com.Server.StdDispatch ( createStdDispatchVTBL , createStdDispatchVTBL2 , createStdDispatch , DispMethod(..) , inArg , inIUnknownArg , inoutArg , outArg , retVal , apply_0 , apply_1 , apply_2 , apply_3 , apply_4 , apply_5 , apply_6 , apply_7 , mkDispMethod , dispmethod_0_0 , dispmethod_1_0 , dispmethod_2_0 , dispmethod_3_0 , dispmethod_0_1 , dispmethod_0_2 ) where import System.Win32.Com.Automation.TypeLib hiding (DISPID,invoke, getIDsOfNames) import System.Win32.Com.Server import System.Win32.Com import System.Win32.Com.Automation import System.Win32.Com.HDirect.HDirect import Foreign.Ptr import Foreign.Storable import System.Win32.Com.Exception import System.Win32.Com.HDirect.WideString import Data.Bits import System.IO.Unsafe import Data.IORef ( newIORef, readIORef, writeIORef ) import Data.Int import Data.List ( find ) createStdDispatch :: objState -> IO () -> [DispMethod objState] -> IID (IUnknown iid) -> IO (IUnknown iid) createStdDispatch objState final meths iid = do vtbl <- createStdDispatchVTBL2 meths createComInstance "" objState final [ mkIface iid vtbl , mkIface iidIDispatch vtbl ] iid {- This presents a simple, no-fuss implementation of a custom IDispatch interface. It takes care of the minutiae of implementing IDispatch, but leaves the programmer with the task of specifying the instance specific bits of: mapping from method names to DISPIDs + the invocation function which performs the action associated with a particular DISPID, including the marshaling and unmarshaling of VARIANT args. Abstractions with varying degress of sophistication can be layered on top of this basic IDispatch impl - see <tt/createStdDispatchVTBL2/ for one way of doing this. -} createStdDispatchVTBL :: (String -> Maybe DISPID) -> (DISPID -> MethodKind -> [VARIANT] -> objState -> IO (Maybe VARIANT)) -> IO (ComVTable (IDispatch iid) objState) createStdDispatchVTBL meths fun = do a_getTypeInfoCount <- export_getTypeInfoCount getTypeInfoCount_none a_getTypeInfo <- export_getTypeInfo getTypeInfo_none a_getIDsOfNames <- export_getIDsOfNames (getIDsOfNames meths) a_invoke <- export_invoke (invoke fun) createComVTable [ a_getTypeInfoCount , a_getTypeInfo , a_getIDsOfNames , a_invoke ] {- evDisp = {- simpleDisp mapDISPIDs invokeDISPIDs -} simpleDisp2 [ dispmethod_0_0 "DownloadComplete" 1 onDownloadComplete , dispmethod_0_0 "DownloadBegin" 2 onDownloadBegin ] where mapDISPIDs x = case x of "DownloadComplete" -> Just 1 "DownloadBegin" -> Just 2 "ProgressChange" -> Just 3 _ -> Nothing invokeDISPIDs st d mk args = case d of 1 -> st # onDownloadComplete 2 -> st # onDownloadBegin 3 -> st # onProgressChange _ -> return Nothing -- silently ignore. -} data DispMethod objState = DispMethod { disp_method_name :: String, -- method name disp_method_id :: DISPID, -- its ... disp_method_kind :: MethodKind, -- bit of a misnomer. disp_method_act :: ([VARIANT] -> objState -> IO (Maybe VARIANT)) } mkDispMethod :: String -> DISPID -> ([VARIANT] -> objState -> IO (Maybe VARIANT)) -> DispMethod objState mkDispMethod nm d f = DispMethod nm d Method f dispmethod_0_0 :: String -> DISPID -> (objState -> IO ()) -> DispMethod objState dispmethod_0_0 name id f = DispMethod name id Method (apply_0 f) dispmethod_1_0 name id f = DispMethod name id Method (inArg $ \ x -> apply_0 (f x)) dispmethod_2_0 name id f = DispMethod name id Method (inArg $ \ x -> inArg $ \ y -> apply_0 (f x y)) dispmethod_3_0 name id f = DispMethod name id Method (inArg $ \ x -> inArg $ \ y -> inArg $ \ z -> apply_0 (f x y z)) dispmethod_0_1 name id f = DispMethod name id Method (outArg $ \ ret_x -> apply_1 f ret_x) dispmethod_0_2 name id f = DispMethod name id Method (outArg $ \ ret_x -> outArg $ \ ret_y -> apply_2 f ret_x ret_y) -- and so on.. createStdDispatchVTBL2 :: [DispMethod objState] -> IO (ComVTable (IDispatch iid) objState) createStdDispatchVTBL2 assoc = createStdDispatchVTBL lookup_dispid invoke_meths where lookup_dispid m_nm = case (find ((==m_nm).disp_method_name) assoc) of Nothing -> Nothing Just d -> Just (disp_method_id d) invoke_meths did mkind args obj_st = case (find ((==did).disp_method_id) assoc) of Nothing -> return Nothing Just d -> (disp_method_act d) args obj_st {- When using <tt/createStdDispatchVTBL2/, here's a couple of helper functions to let you wrap up HRESULT f([in]int i,[in,out]int* j,[out]int* pres, [out,retval]int* retval); as wrap_f = inArg $ \ i -> inArg $ \ j j_out -> resArg $ \ pres -> retVal $ \ retval -> apply_3 (f i j) j_out pres retval -} inArg :: ( Variant a ) => (a -> [VARIANT] -> objState -> IO b) -> [VARIANT] -> objState -> IO b inArg cont (a:args) objState = do x <- resVariant a cont x args objState inIUnknownArg :: (IUnknown a -> [VARIANT] -> objState -> IO b) -> [VARIANT] -> objState -> IO b inIUnknownArg cont (a:args) objState = do x <- resIUnknown a cont x args objState inoutArg :: ( Variant a, Variant b ) => ( a -> (b -> IO ()) -> [VARIANT] -> objState -> IO c) -> [VARIANT] -> objState -> IO c inoutArg cont (a:args) objState = do x <- resVariant a cont x (\ x -> inVariant x a) args objState outArg :: ( Variant a ) => ((a -> IO ()) -> [VARIANT] -> objState -> IO b) -> [VARIANT] -> objState -> IO b outArg cont (a:args) objState = cont (\ x -> inVariant x a) args objState retVal :: ( Variant a ) => ((a -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT)) -> [VARIANT] -> objState -> IO (Maybe VARIANT) retVal cont args objState = do -- what a hack. res_ref <- newIORef Nothing cont (\ x -> writeIORef res_ref (Just x)) args objState retv <- readIORef res_ref case retv of Nothing -> return Nothing Just x -> do pVarResult <- allocBytes (fromIntegral sizeofVARIANT) inVariant x pVarResult return (Just pVarResult) apply_0 :: (objState -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT) apply_0 f _ objState = f objState >> return Nothing apply_1 :: (Variant a) => (objState -> IO a) -> (a -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT) apply_1 f res_1 _ objState = do x <- f objState res_1 x return Nothing apply_2 :: (Variant a0, Variant a1) => (objState -> IO (a0,a1)) -> (a0 -> IO ()) -> (a1 -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT) apply_2 f res_1 res_2 _ objState = do (x,y) <- f objState res_1 x res_2 y return Nothing apply_3 :: (Variant a0, Variant a1, Variant a2) => (objState -> IO (a0,a1,a2)) -> (a0 -> IO ()) -> (a1 -> IO ()) -> (a2 -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT) apply_3 f res_1 res_2 res_3 _ objState = do (a0,a1,a2) <- f objState res_1 a0 res_2 a1 res_3 a2 return Nothing apply_4 :: (Variant a0, Variant a1, Variant a2, Variant a3) => (objState -> IO (a0,a1,a2,a3)) -> (a0 -> IO ()) -> (a1 -> IO ()) -> (a2 -> IO ()) -> (a3 -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT) apply_4 f res_1 res_2 res_3 res_4 _ objState = do (a0,a1,a2,a3) <- f objState res_1 a0 res_2 a1 res_3 a2 res_4 a3 return Nothing apply_5 :: (Variant a0, Variant a1, Variant a2, Variant a3, Variant a4) => (objState -> IO (a0,a1,a2,a3,a4)) -> (a0 -> IO ()) -> (a1 -> IO ()) -> (a2 -> IO ()) -> (a3 -> IO ()) -> (a4 -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT) apply_5 f res_1 res_2 res_3 res_4 res_5 _ objState = do (a0,a1,a2,a3,a4) <- f objState res_1 a0 res_2 a1 res_3 a2 res_4 a3 res_5 a4 return Nothing apply_6 :: (Variant a0, Variant a1, Variant a2, Variant a3, Variant a4, Variant a5) => (objState -> IO (a0,a1,a2,a3,a4,a5)) -> (a0 -> IO ()) -> (a1 -> IO ()) -> (a2 -> IO ()) -> (a3 -> IO ()) -> (a4 -> IO ()) -> (a5 -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT) apply_6 f res_1 res_2 res_3 res_4 res_5 res_6 _ objState = do (a0,a1,a2,a3,a4,a5) <- f objState res_1 a0 res_2 a1 res_3 a2 res_4 a3 res_5 a4 res_6 a5 return Nothing apply_7 :: (Variant a0, Variant a1, Variant a2, Variant a3, Variant a4, Variant a5, Variant a6) => (objState -> IO (a0,a1,a2,a3,a4,a5,a6)) -> (a0 -> IO ()) -> (a1 -> IO ()) -> (a2 -> IO ()) -> (a3 -> IO ()) -> (a4 -> IO ()) -> (a5 -> IO ()) -> (a6 -> IO ()) -> [VARIANT] -> objState -> IO (Maybe VARIANT) apply_7 f res_1 res_2 res_3 res_4 res_5 res_6 res_7 _ objState = do (a0,a1,a2,a3,a4,a5,a6) <- f objState res_1 a0 res_2 a1 res_3 a2 res_4 a3 res_5 a4 res_6 a5 res_7 a6 return Nothing type ThisPtr a = Ptr a invoke :: (DISPID -> MethodKind -> [VARIANT] -> objState -> IO (Maybe VARIANT)) -> Ptr (IDispatch ()) -> DISPID -> Ptr (IID ()) -> LCID -> Word32 -> Ptr (Ptr ()) --DISPPARAMS -> Ptr VARIANT -> Ptr (Ptr ()) --EXCEPINFO -> Ptr Word32 -> IO HRESULT invoke dispMeth this dispIdMember riid lcid wFlags pDispParams pVarResult pExcepInfo puArgErr = do iid <- unmarshallIID False riid if (iid /= iidNULL) then return dISP_E_UNKNOWNINTERFACE else do let mkind = toMethodKind wFlags args = unsafePerformIO (unmarshallArgs (castPtr pDispParams)) st <- getObjState this catchComException (do res <- dispMeth dispIdMember mkind args st case res of Nothing -> do if pVarResult == nullPtr then return () else poke pVarResult nullPtr Just x -> do -- putMessage ("Invoke: " ++ show dispIdMember ++ " interested") writeVARIANT pVarResult x return s_OK) (\ err -> case coGetErrorHR err of Nothing -> do if pExcepInfo == nullPtr then return dISP_E_EXCEPTION else do poke (castPtr pExcepInfo) nullPtr return dISP_E_EXCEPTION Just hr -> -- ToDo: a lot better. if pExcepInfo == nullPtr then return hr else do poke (castPtr pExcepInfo) nullPtr return hr) unmarshallArgs :: Ptr DISPPARAMS -> IO [VARIANT] unmarshallArgs ptr | ptr == nullPtr = return [] | otherwise = do dp <- readDISPPARAMS (castPtr ptr) case dp of (TagDISPPARAMS rs _) -> return rs data MethodKind = Method | PropertyGet | PropertyPut toMethodKind :: Word32 -> MethodKind toMethodKind x | x .&. dISPATCH_METHOD /= 0 = Method | x .&. dISPATCH_PROPERTYGET /= 0 = PropertyGet | x .&. dISPATCH_PROPERTYPUT /= 0 = PropertyPut | x .&. dISPATCH_PROPERTYPUTREF /= 0 = PropertyPut | otherwise = Method dISPATCH_METHOD :: Word32 dISPATCH_METHOD = 0x1 dISPATCH_PROPERTYGET :: Word32 dISPATCH_PROPERTYGET = 0x2 dISPATCH_PROPERTYPUT :: Word32 dISPATCH_PROPERTYPUT = 0x4 dISPATCH_PROPERTYPUTREF :: Word32 dISPATCH_PROPERTYPUTREF = 0x8 getIDsOfNames :: (String -> Maybe DISPID) -> ThisPtr (IDispatch ()) -> Ptr (IID ()) -> Ptr WideString -> Word32 -> LCID -> Ptr DISPID -> IO HRESULT getIDsOfNames lookup_dispid this riid rgszNames cNames lcid rgDispID | cNames /= 1 = return e_FAIL | otherwise = do pwide <- peek (castPtr rgszNames) (pstr,hr) <- wideToString pwide checkHR hr str <- unmarshallString (castPtr pstr) case lookup_dispid str of Nothing -> return e_FAIL Just v -> do writeInt32 rgDispID v return s_OK {- We don't expose type information of any sort, so here's the negative versions of the two IDispatch methods. -} getTypeInfoCount_none :: Ptr () -> Ptr Word32 -> IO HRESULT getTypeInfoCount_none iptr pctInfo = do writeWord32 pctInfo 0 return s_OK getTypeInfo_none :: Ptr (IDispatch ()) -> Word32 -> LCID -> Ptr () -> IO HRESULT getTypeInfo_none this iTInfo lcid ppTInfo | iTInfo /= 0 = return tYPE_E_ELEMENTNOTFOUND | ppTInfo == nullPtr = return e_POINTER | otherwise = do poke (castPtr ppTInfo) nullPtr return s_OK
jjinkou2/ComForGHC7.4
System/Win32/Com/Server/StdDispatch.hs
bsd-3-clause
13,321
223
27
3,604
4,367
2,234
2,133
362
7
module Text.Strapped.Utils where import Blaze.ByteString.Builder import Blaze.ByteString.Builder.Char.Utf8 import Control.Monad import Data.List hiding (find) import Text.Strapped.Types import Text.Strapped.Parser import Data.Typeable import System.FilePath.Find import System.FilePath.Posix (addTrailingPathSeparator) import Text.ParserCombinators.Parsec templateStoreFromList :: StrappedConfig -> [(String, String)] -> Either ParseError TemplateStore templateStoreFromList config tmpls = do templateTups <- forM tmpls (\(tn, t) -> fmap ((,) tn) $ parseTemplate config t tn) return (\n -> return $ lookup n templateTups) -- | Given a file path and extension, load all templates in a directory, recursively. templateStoreFromDirectory :: StrappedConfig -> FilePath -> String -> IO (Either ParseError TemplateStore) templateStoreFromDirectory config dir ext = do files <- find always (extension ==? ext) dirPath tmpls <- forM files (\fn -> let fname = maybe [] id $ stripPrefix dirPath fn in print fname >> readFile fn >>= (return . (,) fname)) return $! templateStoreFromList config tmpls where dirPath = addTrailingPathSeparator dir putStore :: TemplateStore -> StrappedConfig -> StrappedConfig putStore ts rc = rc { templateStore = ts } showToBuilder :: Show a => a -> Builder showToBuilder = fromShow lit :: ToLiteral a => a -> Input m lit = LitVal . toLiteral dyn :: (Renderable a, Typeable a) => a -> Input m dyn = LitVal . LitDyn
hansonkd/StrappedTemplates
src/Text/Strapped/Utils.hs
bsd-3-clause
1,588
0
17
352
460
244
216
30
1
module ThreadsLang.Parser ( expression , program , parseProgram ) where import Control.Monad (void) import Data.Maybe (fromMaybe) import Text.Megaparsec hiding (ParseError) import Text.Megaparsec.Expr import qualified Text.Megaparsec.Lexer as L import Text.Megaparsec.String import ThreadsLang.Data parseProgram :: String -> Try Program parseProgram input = case runParser program "Program Parser" input of Left err -> Left $ ParseError err Right p -> Right p spaceConsumer :: Parser () spaceConsumer = L.space (void spaceChar) lineCmnt blockCmnt where lineCmnt = L.skipLineComment "//" blockCmnt = L.skipBlockComment "/*" "*/" symbol = L.symbol spaceConsumer parens = between (symbol "(") (symbol ")") minus = symbol "-" equal = symbol "=" comma = symbol "," longArrow = symbol "==>" semiColon = symbol ";" lexeme :: Parser a -> Parser a lexeme = L.lexeme spaceConsumer keyWord :: String -> Parser () keyWord w = string w *> notFollowedBy alphaNumChar *> spaceConsumer reservedWords :: [String] reservedWords = [ "let", "in", "if", "then", "else", "zero?", "minus" , "equal?", "greater?", "less?", "proc", "letrec", "begin", "set" , "spawn", "mutex", "wait", "signal", "yield" ] genOpParser :: Show a => [(String, a)] -> Parser a genOpParser opsMap = do opStr <- foldl1 (<|>) (fmap (try . symbol . fst) opsMap) return $ fromMaybe (error ("Unknown operator '" `mappend` opStr `mappend` "'")) (lookup opStr opsMap) binOpsMap :: [(String, BinOp)] binOpsMap = [ ("+", Add), ("-", Sub), ("*", Mul), ("/", Div), ("equal?", Eq) , ("greater?", Gt), ("less?", Le) ] binOp :: Parser BinOp binOp = genOpParser binOpsMap unaryOpsMap :: [(String, UnaryOp)] unaryOpsMap = [ ("minus", Minus), ("zero?", IsZero), ("wait", Wait), ("signal", Signal) ] unaryOp :: Parser UnaryOp unaryOp = genOpParser unaryOpsMap nullOpsMap :: [(String, NullOp)] nullOpsMap = [ ("mutex", Mut), ("yield", Yield) ] nullOp :: Parser NullOp nullOp = genOpParser nullOpsMap -- | Identifier ::= String (without reserved words) identifier :: Parser String identifier = lexeme (p >>= check) where p = (:) <$> letterChar <*> many alphaNumChar check x = if x `elem` reservedWords then fail $ concat ["keyword ", show x, " cannot be an identifier"] else return x integer :: Parser Integer integer = lexeme L.integer signedInteger :: Parser Integer signedInteger = L.signed spaceConsumer integer pairOf :: Parser a -> Parser b -> Parser (a, b) pairOf pa pb = parens $ do a <- pa comma b <- pb return (a, b) -- expressionPair ::= (Expression, Expression) expressionPair :: Parser (Expression, Expression) expressionPair = pairOf expression expression -- | ConstExpr ::= Number constExpr :: Parser Expression constExpr = ConstExpr . ExprNum <$> signedInteger -- | BinOpExpr ::= BinOp (Expression, Expression) binOpExpr :: Parser Expression binOpExpr = do op <- binOp exprPair <- expressionPair return $ uncurry (BinOpExpr op) exprPair -- | UnaryOpExpr ::= UnaryOp (Expression) unaryOpExpr :: Parser Expression unaryOpExpr = do op <- unaryOp expr <- parens expression return $ UnaryOpExpr op expr -- | NullOpExpr ::= NullOp () nullOpExpr :: Parser Expression nullOpExpr = do op <- nullOp parens space return $ NullOpExpr op -- | IfExpr ::= if Expression then Expression ifExpr :: Parser Expression ifExpr = do keyWord "if" ifE <- expression keyWord "then" thenE <- expression keyWord "else" elseE <- expression return $ IfExpr ifE thenE elseE -- | VarExpr ::= Identifier varExpr :: Parser Expression varExpr = VarExpr <$> identifier -- | LetExpr ::= let {Identifier = Expression}* in Expression letExpr :: Parser Expression letExpr = letFamilyExpr "let" LetExpr letFamilyExpr :: String -> ([(String, Expression)] -> Expression -> Expression) -> Parser Expression letFamilyExpr letType builder = do keyWord letType bindings <- many binding keyWord "in" body <- expression return $ builder bindings body where binding = try assignment -- | LetrecExpr ::= letrec {Identifier (Identifier) = Expression} in Expression letRecExpr :: Parser Expression letRecExpr = do keyWord "letrec" procBindings <- many procBinding keyWord "in" recBody <- expression return $ LetRecExpr procBindings recBody where procBinding = try $ do procName <- identifier params <- parens $ many identifier equal procBody <- expression return (procName, params, procBody) -- | ManyExprs ::= <empty> -- ::= Many1Exprs manyExprs :: Parser [Expression] manyExprs = sepBy expression comma -- | Many1Exprs ::= Expression -- ::= Expression , Many1Exprs many1Exprs :: Parser [Expression] many1Exprs = sepBy1 expression comma -- | ProcExpr ::= proc ({Identifier}*) Expression procExpr :: Parser Expression procExpr = do keyWord "proc" params <- parens $ many identifier body <- expression return $ ProcExpr params body -- | CallExpr ::= (Expression {Expression}*) callExpr :: Parser Expression callExpr = parens $ do rator <- expression rands <- many expression return $ CallExpr rator rands -- | BeginExpr ::= begin BeginBody end -- -- BeginBody ::= Expression BeginBodyTail -- -- BeginBodyTail ::= <empty> -- ::= ; Expression BeginBodyTail beginExpr :: Parser Expression beginExpr = do keyWord "begin" exprs <- sepBy1 (try expression) semiColon keyWord "end" return $ BeginExpr exprs assignment :: Parser (String, Expression) assignment = do name <- identifier equal expr <- expression return (name, expr) -- | AssignExpr ::= set Identifier = Expression assignExpr :: Parser Expression assignExpr = do keyWord "set" assign <- assignment return $ uncurry AssignExpr assign -- | SpawnExpr ::= spawn (Expression) spawnExpr :: Parser Expression spawnExpr = do keyWord "spawn" SpawnExpr <$> parens expression -- | Expression ::= ConstExpr -- ::= BinOpExpr -- ::= UnaryOpExpr -- ::= NullOpExpr -- ::= IfExpr -- ::= VarExpr -- ::= LetExpr -- ::= LetRecExpr -- ::= ProcExpr -- ::= CallExpr -- ::= BeginExpr -- ::= AssignExpr -- ::= SpawnExpr expression :: Parser Expression expression = foldl1 (<|>) (fmap try expressionList) where expressionList = [ constExpr , binOpExpr , unaryOpExpr , nullOpExpr , ifExpr , varExpr , letExpr , letRecExpr , procExpr , callExpr , beginExpr , assignExpr , spawnExpr ] program :: Parser Program program = do spaceConsumer expr <- expression eof return $ Prog expr
li-zhirui/EoplLangs
src/ThreadsLang/Parser.hs
bsd-3-clause
6,910
0
13
1,650
1,850
972
878
186
2
---------------------------------------------------------------- -- the Henk Parser -- Copyright 2000, Jan-Willem Roorda and Daan Leijen ---------------------------------------------------------------- module HenkParser where import Text.ParserCombinators.Parsec import qualified Text.ParserCombinators.Parsec.Token as P import Text.ParserCombinators.Parsec.Language import HenkAS ---------------------------------------------------------------- -- the Henk Parser -- -- anonymous variables are any identifiers starting with "_" -- -- unknown types (those that need to be inferred) can explicitly -- be given using "?" -- -- instead of grammar: "var : aexpr" as in the henk paper, -- we use "var : expr" instead. This means that variable -- sequences as in \, |~|, \/ and /\ expressions need to -- be comma seperated. Pattern variables are also comma -- seperated. The case arrow (->) now needs to be (=>) in -- order to distinguish the end of the pattern from function -- arrows. ---------------------------------------------------------------- program = do{ whiteSpace ; ts <- semiSep tdecl ; vs <- semiSep vdecl ; eof ; return $ Program ts vs } ---------------------------------------------------------------- -- Type declarations ---------------------------------------------------------------- tdecl = do{ reserved "data" ; t <- bindVar ; symbol "=" ; ts <- braces (semiSep1 tvar) ; return $ Data t ts } ---------------------------------------------------------------- -- Value declarations ---------------------------------------------------------------- vdecl :: Parser ValueDecl vdecl = do{ reserved "let" ; b <- bind ; return $ Let b } <|> do{ reserved "letrec" ; bs <- braces (semiSep1 bind) ; return $ LetRec bs } bind = do{ t <- tvar ; symbol "=" ; e <- expr ; return $ Bind t e } ---------------------------------------------------------------- -- Expressions ---------------------------------------------------------------- expr :: Parser Expr expr = choice [ letExpr , forallExpr -- forall before lambda! \/ vs. \ , lambdaExpr , piExpr , caseExpr , functionExpr , bigLamdaExpr ] <?> "expression" letExpr = do{ vd <- vdecl ; reserved "in" ; e <- expr ; return (In vd e) } lambdaExpr = do{ symbol "\\" ; ts <- commaSep1 bindVar ; symbol "." ; e <- expr ; return $ (foldr Lam e ts) } piExpr = do{ symbol "|~|" ; ts <- commaSep1 bindVar ; symbol "." ; e <- expr ; return (foldr Pi e ts) } ---------------------------------------------------------------- -- Case expressions ---------------------------------------------------------------- caseExpr = do{ reserved "case" ; e <- expr ; reserved "of" ; as <- braces (semiSep1 alt) ; es <- option [] (do{ reserved "at" ; braces (semiSep expr) }) ; return (Case e as es) } alt = do{ pat <- pattern ; symbol "=>" ; e <- expr ; return (pat e) } pattern = do{ p <- atomPattern ; vs <- commaSep boundVar ; return (\e -> Alt p (foldr Lam e vs)) } atomPattern = do{ v <- boundVar ; return (PatVar v) } <|> do{ l <- literal ; return (PatLit l) } <?> "pattern" ---------------------------------------------------------------- -- Syntactic sugar: ->, \/, /\ ---------------------------------------------------------------- functionExpr = chainr1 appExpr arrow where arrow = do{ symbol "->" ; return ((\x y -> Pi (TVar anonymous x) y)) } <?> "" bigLamdaExpr = do{ symbol "/\\" ; ts <- commaSep1 bindVar ; symbol "." ; e <- expr ; return (foldr Lam e ts) } forallExpr = do{ try (symbol "\\/") -- use "try" to try "\" (lambda) too. ; ts <- commaSep1 bindVar ; symbol "." ; e <- expr ; return (foldr Pi e ts) } ---------------------------------------------------------------- -- Simple expressions ---------------------------------------------------------------- appExpr = do{ es <- many1 atomExpr ; return (foldl1 App es) } atomExpr = parens expr <|> do{ v <- boundVar; return (Var v) } <|> do{ l <- literal; return (Lit l)} <|> do{ symbol "*"; return Star } <|> do{ symbol "[]"; return Box } <|> do{ symbol "?"; return Unknown } <?> "simple expression" ---------------------------------------------------------------- -- Variables & Literals ---------------------------------------------------------------- variable = identifier anonymousVar = lexeme $ do{ c <- char '_' ; cs <- many (identLetter henkDef) ; return (c:cs) } bindVar = do{ i <- variable <|> anonymousVar ; do{ e <- varType ; return (TVar i e) } <|> return (TVar i Star) } <?> "variable" boundVar = do{ i <- variable ; do{ e <- varType ; return (TVar i e) } <|> return (TVar i Unknown) } <?> "variable" tvar = do{ v <- variable ; t <- varType ; return (TVar v t) } <?> "typed variable" varType = do{ symbol ":" ; expr } <?> "variable type" literal = do{ i <- natural ; return (LitInt i) } <?> "literal" ---------------------------------------------------------------- -- Tokens ---------------------------------------------------------------- henk = P.makeTokenParser henkDef lexeme = P.lexeme henk parens = P.parens henk braces = P.braces henk semiSep = P.semiSep henk semiSep1 = P.semiSep1 henk commaSep = P.commaSep henk commaSep1 = P.commaSep1 henk whiteSpace = P.whiteSpace henk symbol = P.symbol henk identifier = P.identifier henk reserved = P.reserved henk natural = P.natural henk henkDef = haskellStyle { identStart = letter , identLetter = alphaNum <|> oneOf "_'" , opStart = opLetter henkDef , opLetter = oneOf ":=\\->/|~.*[]" , reservedOpNames = ["::","=","\\","->","=>","/\\","\\/" ,"|~|",".",":","*","[]"] , reservedNames = [ "case", "data", "letrec", "type" , "import", "in", "let", "of", "at" ] }
FranklinChen/hugs98-plus-Sep2006
packages/parsec/examples/Henk/HenkParser.hs
bsd-3-clause
7,016
1
16
2,322
1,617
853
764
166
1
module Distribution.Client.Dependency.Modular.Assignment where import Control.Applicative import Control.Monad import Data.Array as A import Data.List as L import Data.Map as M import Data.Maybe import Data.Graph import Prelude hiding (pi) import Distribution.PackageDescription (FlagAssignment) -- from Cabal import Distribution.Client.Dependency.Modular.Configured import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Index import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.Version -- | A (partial) package assignment. Qualified package names -- are associated with instances. type PAssignment = Map QPN I -- | A (partial) package preassignment. Qualified package names -- are associated with constrained instances. Constrained instances -- record constraints about the instances that can still be chosen, -- and in the extreme case fix a concrete instance. type PPreAssignment = Map QPN (CI QPN) type FAssignment = Map QFN Bool -- | A (partial) assignment of variables. data Assignment = A PAssignment FAssignment deriving (Show, Eq) -- | A preassignment comprises knowledge about variables, but not -- necessarily fixed values. data PreAssignment = PA PPreAssignment FAssignment -- | Extend a package preassignment. -- -- Either returns a witness of the conflict that would arise during the merge, -- or the successfully extended assignment. extend :: Var QPN -> PPreAssignment -> [Dep QPN] -> Either (ConflictSet QPN, [Dep QPN]) PPreAssignment extend var pa qa = foldM (\ a (Dep qpn ci) -> let ci' = M.findWithDefault (Constrained []) qpn a in case (\ x -> M.insert qpn x a) <$> merge ci' ci of Left (c, (d, d')) -> Left (c, L.map (Dep qpn) (simplify (P qpn) d d')) Right x -> Right x) pa qa where -- We're trying to remove trivial elements of the conflict. If we're just -- making a choice pkg == instance, and pkg => pkg == instance is a part -- of the conflict, then this info is clear from the context and does not -- have to be repeated. simplify v (Fixed _ (Goal var' _)) c | v == var && var' == var = [c] simplify v c (Fixed _ (Goal var' _)) | v == var && var' == var = [c] simplify _ c d = [c, d] -- | Delivers an ordered list of fully configured packages. -- -- TODO: This function is (sort of) ok. However, there's an open bug -- w.r.t. unqualification. There might be several different instances -- of one package version chosen by the solver, which will lead to -- clashes. toCPs :: Assignment -> RevDepMap -> [CP QPN] toCPs (A pa fa) rdm = let -- get hold of the graph g :: Graph vm :: Vertex -> ((), QPN, [QPN]) cvm :: QPN -> Maybe Vertex -- Note that the RevDepMap contains duplicate dependencies. Therefore the nub. (g, vm, cvm) = graphFromEdges (L.map (\ (x, xs) -> ((), x, nub xs)) (M.toList rdm)) tg :: Graph tg = transposeG g -- Topsort the dependency graph, yielding a list of pkgs in the right order. -- The graph will still contain all the installed packages, and it might -- contain duplicates, because several variables might actually resolve to -- the same package in the presence of qualified package names. ps :: [PI QPN] ps = L.map ((\ (_, x, _) -> PI x (pa M.! x)) . vm) $ topSort g -- Determine the flags per package, by walking over and regrouping the -- complete flag assignment by package. fapp :: Map QPN FlagAssignment fapp = M.fromListWith (++) $ L.map (\ ((FN (PI qpn _) fn), b) -> (qpn, [(fn, b)])) $ M.toList $ fa -- Dependencies per package. depp :: QPN -> [PI QPN] depp qpn = let v :: Vertex v = fromJust (cvm qpn) dvs :: [Vertex] dvs = tg A.! v in L.map (\ dv -> case vm dv of (_, x, _) -> PI x (pa M.! x)) dvs in L.map (\ pi@(PI qpn _) -> CP pi (M.findWithDefault [] qpn fapp) (depp qpn)) ps -- | Finalize an assignment and a reverse dependency map. -- -- This is preliminary, and geared towards output right now. finalize :: Index -> Assignment -> RevDepMap -> IO () finalize idx (A pa fa) rdm = let -- get hold of the graph g :: Graph vm :: Vertex -> ((), QPN, [QPN]) (g, vm) = graphFromEdges' (L.map (\ (x, xs) -> ((), x, xs)) (M.toList rdm)) -- topsort the dependency graph, yielding a list of pkgs in the right order f :: [PI QPN] f = L.filter (not . instPI) (L.map ((\ (_, x, _) -> PI x (pa M.! x)) . vm) (topSort g)) fapp :: Map QPN [(QFN, Bool)] -- flags per package fapp = M.fromListWith (++) $ L.map (\ (qfn@(FN (PI qpn _) _), b) -> (qpn, [(qfn, b)])) $ M.toList $ fa -- print one instance ppi pi@(PI qpn _) = showPI pi ++ status pi ++ " " ++ pflags (M.findWithDefault [] qpn fapp) -- print install status status :: PI QPN -> String status (PI (Q _ pn) _) = case insts of [] -> " (new)" vs -> " (" ++ intercalate ", " (L.map showVer vs) ++ ")" where insts = L.map (\ (I v _) -> v) $ L.filter isInstalled $ M.keys (M.findWithDefault M.empty pn idx) isInstalled (I _ (Inst _ )) = True isInstalled _ = False -- print flag assignment pflags = unwords . L.map (uncurry showFBool) in -- show packages with associated flag assignments putStr (unlines (L.map ppi f))
IreneKnapp/Faction
faction/Distribution/Client/Dependency/Modular/Assignment.hs
bsd-3-clause
5,788
0
20
1,615
1,621
892
729
83
4
{-# LANGUAGE TemplateHaskell #-} -- | The @home@ element of a OSM file. module Data.Geo.OSM.Home ( Home , home ) where import Text.XML.HXT.Arrow.Pickle import Data.Geo.OSM.Lens.LatL import Data.Geo.OSM.Lens.LonL import Data.Geo.OSM.Lens.ZoomL import Control.Lens.TH -- | The @home@ element of a OSM file. data Home = Home { _homeLat :: String, _homeLon :: String, _homeZoom :: String } deriving Eq makeLenses ''Home -- | Constructs a @home@ with lat, lon and zoom. home :: String -- ^ The @lat@ attribute. -> String -- ^ The @lon@ attribute. -> String -- ^ The @zoom@ attribute. -> Home home = Home instance XmlPickler Home where xpickle = xpElem "home" (xpWrap (\(lat', lon', zoom') -> home lat' lon' zoom', \(Home lat' lon' zoom') -> (lat', lon', zoom')) (xpTriple (xpAttr "lat" xpText) (xpAttr "lon" xpText) (xpAttr "zoom" xpText))) instance Show Home where show = showPickled [] instance LatL Home where latL = homeLat instance LonL Home where lonL = homeLon instance ZoomL Home where zoomL = homeZoom
tonymorris/geo-osm
src/Data/Geo/OSM/Home.hs
bsd-3-clause
1,054
0
12
208
289
170
119
35
1
{-# LANGUAGE OverloadedStrings #-} -- | This package provides a variety of utilities for parsing and producing -- SVMlight input files. module Math.SVM.SVMLight.Utils ( -- * Types Qid(..) , FeatureIdx(..) , Point(..) -- * Parsing SVMlight files , point , featureIdx -- * Generating SVMlight files , renderPoints , renderPoint ) where import Data.Monoid import Data.Foldable (foldMap) import Data.List (intersperse) import Data.Char (ord) import Control.Applicative import qualified Data.Map.Strict as M import Data.Attoparsec.ByteString.Char8 as AP import qualified Data.ByteString.Builder as BSB import qualified Data.ByteString.Char8 as BS newtype Qid = Qid Int deriving (Show, Ord, Eq) -- | A feature identifier newtype FeatureIdx = FIdx Int deriving (Show, Ord, Eq) featureIdx :: Parser FeatureIdx featureIdx = fmap FIdx decimal {-# INLINE featureIdx #-} qid :: Parser Qid qid = Qid <$> ("qid:" *> decimal) {-# INLINE qid #-} -- | A sample point (e.g. a line of an SVMlight input file). data Point = Point { pLabel :: !Int , pQid :: !(Maybe Qid) , pFeatures :: !(M.Map FeatureIdx Double) , pComment :: !(Maybe BS.ByteString) } deriving (Show, Ord, Eq) -- | Parse a sample point point :: Parser Point point = do label <- decimal skipSpace qid <- optional qid skipSpace features <- M.unions <$> feature `sepBy` char ' ' skipSpace comment <- optional $ do char '#' skipSpace takeTill (isEndOfLine . fromIntegral . ord) skipSpace return $ Point label qid features comment where feature = M.singleton <$> featureIdx <* char ':' <*> double {-# INLINE point #-} -- | A @Builder@ containing the given @Point@s renderPoints :: [Point] -> BSB.Builder renderPoints pts = mconcat $ intersperse "\n" $ map renderPoint pts {-# INLINEABLE renderPoints #-} -- | A @Builder@ containing the given @Point@ renderPoint :: Point -> BSB.Builder renderPoint pt = mconcat $ intersperse " " $ [BSB.intDec (pLabel pt)] ++ qid ++ vs ++ c where vs = map (\(FIdx i,v)->BSB.intDec i<>":"<>BSB.doubleDec v) $ M.assocs (pFeatures pt) c = maybe [] (\c->[" #"<>BSB.byteString c]) (pComment pt) qid = maybe [] (\(Qid q)->["qid:"<>BSB.intDec q]) (pQid pt) {-# INLINEABLE renderPoint #-}
bgamari/svm-light-utils
Math/SVM/SVMLight/Utils.hs
bsd-3-clause
2,425
0
14
609
680
373
307
66
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} module EFA.IO.CSVParser ( csvFile, csvFileWithHeader, cellContent, Header, Name(..), TrimmedName(..), Transpose(..), Cells, CellsParser, structuredCell, csvFileWithStructure, ) where -- Geklaut und adaptiert aus Real World Haskell, Kapitel 16 import Text.ParserCombinators.Parsec import qualified EFA.IO.Parser as EFAParser import EFA.IO.Parser (Sequence, eol) import qualified Data.List as List import Control.Applicative (liftA2, liftA3, (<*)) import Data.String.HT (trim) import Data.Tuple.HT (mapPair, mapTriple) -- | Takes a separator character. csvFile :: (Sequence table, Sequence line) => Char -> Parser (table (line String)) csvFile sepChar = EFAParser.endBy (line sepChar) eol line :: Sequence line => Char -> Parser (line String) line sepChar = do -- remove separators from the beginning of a line skipMany (char sepChar) EFAParser.sepBy (cell sepChar) (char sepChar) type Interpret a = String -> Either String a cellContent :: (Read a) => Interpret a cellContent str = case reads str of [(a,"")] -> Right a _ -> Left $ "could not parse cell content: " ++ show str interpret :: Interpret a -> Parser String -> Parser a interpret intp p = do str <- p case intp str of Left msg -> fail msg Right a -> return a csvFileWithHeader :: (Sequence line) => line (Interpret header) -> Interpret a -> Char -> Parser (line header, [line a]) csvFileWithHeader intpHeader intpData sepChar = do hdrLine <- headerLine intpHeader sepChar <* eol body <- endBy (fixedLine intpData hdrLine sepChar) eol return (hdrLine, body) headerLine :: Sequence line => line (Interpret header) -> Char -> Parser (line header) headerLine intps sepChar = do -- remove separators from the beginning of a line skipMany (char sepChar) EFAParser.sepByVar (fmap (flip interpret $ cell sepChar) intps) (char sepChar) fixedLine :: (Sequence line) => Interpret a -> line void -> Char -> Parser (line a) fixedLine intp n sepChar = do -- remove separators from the beginning of a line skipMany (char sepChar) EFAParser.sepByMatch n (interpret intp $ cell sepChar) (char sepChar) class (CellsParser cells, CellsParser (Header cells), Transpose cells) => Cells cells where type Header cells :: * class CellsParser cells where structuredCell :: Char -> Parser cells class Transpose cells where type Transposed cells :: * transpose :: [cells] -> Transposed cells instance Cells Integer where type Header Integer = Name instance CellsParser Integer where structuredCell = interpret cellContent . cell instance Transpose Integer where type Transposed Integer = [Integer] transpose = id instance Cells Double where type Header Double = Name instance CellsParser Double where structuredCell = interpret cellContent . cell instance Transpose Double where type Transposed Double = [Double] transpose = id newtype Name = Name String deriving (Show, Eq) instance Cells Name where type Header Name = Name instance CellsParser Name where structuredCell = fmap Name . cell instance Transpose Name where type Transposed Name = [Name] transpose = id newtype TrimmedName = TrimmedName String deriving (Show, Eq) instance Cells TrimmedName where type Header TrimmedName = Name instance CellsParser TrimmedName where structuredCell = fmap (TrimmedName . trim) . cell instance Transpose TrimmedName where type Transposed TrimmedName = [TrimmedName] transpose = id instance Cells a => Cells [a] where type Header [a] = [Name] instance CellsParser a => CellsParser [a] where structuredCell sepChar = sepBy (structuredCell sepChar) (char sepChar) instance Transpose [a] where type Transposed [a] = [[a]] transpose = List.transpose instance (Cells a, Cells b) => Cells (a,b) where type Header (a,b) = (Header a, Header b) instance (CellsParser a, CellsParser b) => CellsParser (a,b) where structuredCell sepChar = liftA2 (,) (structuredCell sepChar) (char sepChar >> structuredCell sepChar) instance (Transpose a, Transpose b) => Transpose (a,b) where type Transposed (a,b) = (Transposed a, Transposed b) transpose = mapPair (transpose, transpose) . unzip instance (Cells a, Cells b, Cells c) => Cells (a,b,c) where type Header (a,b,c) = (Header a, Header b, Header c) instance (CellsParser a, CellsParser b, CellsParser c) => CellsParser (a,b,c) where structuredCell sepChar = liftA3 (,,) (structuredCell sepChar) (char sepChar >> structuredCell sepChar) (char sepChar >> structuredCell sepChar) instance (Transpose a, Transpose b, Transpose c) => Transpose (a,b,c) where type Transposed (a,b,c) = (Transposed a, Transposed b, Transposed c) transpose = mapTriple (transpose, transpose, transpose) . unzip3 csvFileWithStructure :: (Cells cells) => Char -> Parser (Header cells, [cells]) csvFileWithStructure sepChar = liftA2 (,) (structuredCell sepChar <* eol) (endBy (structuredCell sepChar) eol) cell :: Char -> Parser String cell sepChar = quotedCell <|> many (noneOf (sepChar:"\n\r")) quotedCell :: Parser String quotedCell = between (char '"') (char '"' <?> "quote at end of cell") $ many quotedChar quotedChar :: Parser Char quotedChar = noneOf "\"" <|> try (string "\"\"" >> return '"')
energyflowanalysis/efa-2.1
src/EFA/IO/CSVParser.hs
bsd-3-clause
5,380
0
12
1,035
1,884
993
891
143
2
module Hrpg.Framework.Items.ItemDefinition ( ItemId (..) , ItemType (..) , ItemDefinition (..) ) where import Data.Text import Hrpg.Framework.Combat.Dmg import Hrpg.Framework.Stats newtype ItemId = ItemId Int deriving (Show, Eq) data ItemType = Weapon | Armour | Junk deriving (Show, Eq) data ItemDefinition = ItemDefinition { itemId :: ItemId , itemName :: Text , itemType :: ItemType , weaponDmg :: Maybe Dmg , itemStats :: Maybe Stats } deriving Show
cwmunn/hrpg
src/Hrpg/Framework/Items/ItemDefinition.hs
bsd-3-clause
526
0
9
139
140
88
52
20
0
module Optimizer.Optimizer(optimizeProgram) where import Identifiers import AST.AST import AST.Util import qualified AST.Meta as Meta import Types import Control.Applicative (liftA2) optimizeProgram :: Program -> Program optimizeProgram p@(Program{classes, traits, functions}) = p{classes = map optimizeClass classes ,traits = map optimizeTrait traits ,functions = map optimizeFunction functions} where optimizeFunction f@(Function{funbody}) = f{funbody = optimizeExpr funbody} optimizeTrait t@(Trait{tmethods}) = t{tmethods = map optimizeMethod tmethods} optimizeClass c@(Class{cname, cmethods}) | isMainClass c = c{cmethods = map (optimizeMethod . addMainInitCall) cmethods} | otherwise = c{cmethods = map optimizeMethod cmethods} where addMainInitCall m@Method{mbody} | isMainMethod cname (methodName m) = let em = emeta mbody this = setType cname VarAccess{emeta = em, qname = qLocal thisName} initCall = setType unitType MethodCall{emeta = em ,target = this ,name = constructorName ,typeArguments = [] ,args = [] } in m{mbody = Seq{emeta = emeta mbody, eseq = [initCall, mbody]}} | otherwise = m optimizeMethod m = m{mbody = optimizeExpr (mbody m)} optimizeExpr ast = foldl (\ast opt -> opt ast) ast optimizerPasses -- | The functions in this list will be performed in order during optimization optimizerPasses :: [Expr -> Expr] optimizerPasses = [constantFolding, sugarPrintedStrings, tupleMaybeIdComparison, dropBorrowBlocks, forwardGeneral] -- Note that this is not intended as a serious optimization, but -- as an example to how an optimization could be made. As soon as -- there is a serious optimization in place, please remove this -- function. constantFolding :: Expr -> Expr constantFolding = extend foldConst where foldConst (Binop {emeta = meta, binop = PLUS, loper = IntLiteral{intLit = m}, roper = IntLiteral{intLit = n}}) = IntLiteral{emeta = meta, intLit = m + n} foldConst e = e -- Desugars a == b when a : Just[t] and b : Just[t] into -- match (a, b) with -- case (Just(_fst), Just(_snd)) when _fst == _snd => true -- case _ => false -- end tupleMaybeIdComparison = extend tupleMaybeIdComparison' where tupleMaybeIdComparison' Binop {emeta, binop, loper=MaybeValue{mdt=NothingData}, roper=MaybeValue{mdt=NothingData}} = setType boolType BTrue{emeta} tupleMaybeIdComparison' Binop {emeta, binop, loper, roper} | (isMaybeType $ getType loper) && (isMaybeType $ getType roper) && (binop == Identifiers.EQ || binop == Identifiers.NEQ) = tupleMaybeIdComparison $ maybeNeg Match{emeta, arg=setType tt Tuple{emeta, args}, clauses=[trueClause1, trueClause2, falseClause]} where tt = tupleType [lmty, rmty] args = [loper, roper] falseClause = MatchClause{mcpattern=setType tt VarAccess{emeta, qname=qName "_"} ,mchandler=setType boolType BFalse{emeta} ,mcguard=setType boolType BTrue{emeta}} trueClause1 = MatchClause{mcpattern=setType tt Tuple{emeta ,args=[setType lmty MaybeValue{emeta, mdt=JustData lid} ,setType rmty MaybeValue{emeta, mdt=JustData rid}]} ,mchandler ,mcguard=setType boolType Binop{emeta, binop, loper=lid, roper=rid}} trueClause2 = MatchClause{mcpattern=setType tt Tuple{emeta ,args=[setType lmty MaybeValue{emeta, mdt=NothingData} ,setType rmty MaybeValue{emeta, mdt=NothingData}]} ,mchandler ,mcguard=setType boolType BTrue{emeta}} lid = setType lty VarAccess{emeta, qname=qName "_fst"} rid = setType rty VarAccess{emeta, qname=qName "_snd"} leftResult = getResultType $ getType loper rightResult = getResultType $ getType roper -- When one operand is Nothing, replace its inferred bottom type by the type of the other operand lty = if leftResult == bottomType then rightResult else leftResult rty = if rightResult == bottomType then leftResult else rightResult lmty = maybeType lty rmty = maybeType rty -- Negate result when != comparison maybeNeg n = setType boolType $ if binop == Identifiers.EQ then n else Unary{emeta, uop=NOT, operand=n} mchandler = setType boolType BTrue{emeta} tupleMaybeIdComparison' b@Binop {emeta, binop, loper, roper} | (isTupleType $ getType loper) && (isTupleType $ getType roper) && (binop == Identifiers.EQ || binop == Identifiers.NEQ) = tupleMaybeIdComparison $ foldl and (setType boolType BTrue{emeta}) pairwiseCompare where and loper roper = setType boolType Binop{emeta, binop=Identifiers.AND, loper, roper} pairwiseCompare = map mkComparison [0..(tupleLength $ getType loper)-1] mkComparison idx = setType boolType Binop {emeta ,binop ,loper=setType (lty!!idx) TupleAccess{emeta ,target=loper ,compartment=idx} ,roper=setType (rty!!idx) TupleAccess{emeta ,target=roper ,compartment=idx}} lty = getArgTypes $ getType loper rty = getArgTypes $ getType roper tupleMaybeIdComparison' e = e sugarPrintedStrings = extend sugarPrintedString where sugarPrintedString e@(Print{args}) = e{args = map simplifyStringLit args} sugarPrintedString e = e simplifyStringLit arg | NewWithInit{ty} <- arg , isStringObjectType ty , Just sugared@StringLiteral{} <- getSugared arg = setType stringType sugared | otherwise = arg dropBorrowBlocks = extend dropBorrowBlock where dropBorrowBlock e@Borrow{emeta, target, name, body} = Let{emeta ,mutability = Val ,decls = [([VarNoType name], target)] ,body} dropBorrowBlock e = e forwardGeneral = extend forwardGeneral' where forwardGeneral' e@(Forward{forwardExpr=MessageSend{}}) = e forwardGeneral' e@(Forward{forwardExpr=FutureChain{}}) = e forwardGeneral' e@(Forward{emeta, forwardExpr}) = Forward{emeta=emeta', forwardExpr=newExpr} where emeta' = Meta.setType (Meta.getType emeta) (Meta.meta $ Meta.getPos emeta) newExpr = FutureChain{emeta=fcmeta, future=forwardExpr, chain=idfun} fcmeta = Meta.setType (getType $ forwardExpr) (Meta.meta (Meta.getPos emeta')) idfun = Closure {emeta=mclosure ,eparams=[pdecl] ,mty=Just closureType ,body=VarAccess {emeta=Meta.setType paramType mclosure ,qname=qName "_id_fun_tmp"}} closureType = arrowType [paramType] paramType mclosure = Meta.metaClosure "" (Meta.setType closureType emeta) paramType = getResultType . getType $ forwardExpr pdecl = Param {pmeta=Meta.setType paramType (Meta.meta (Meta.getPos emeta)) ,pmut =Val ,pname=Name "_id_fun_tmp" ,ptype=paramType ,pdefault= Nothing} forwardGeneral' e = e
parapluu/encore
src/opt/Optimizer/Optimizer.hs
bsd-3-clause
8,367
0
18
2,977
2,136
1,185
951
-1
-1
module AbstractInterpretation.CreatedBy.Util where import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map import Data.Vector (Vector) import qualified Data.Vector as Vec import Data.Maybe import Data.Functor.Foldable as Foldable import Control.Monad.State import Grin.Grin import AbstractInterpretation.LiveVariable.Result import AbstractInterpretation.CreatedBy.CodeGen (undefinedProducerName) import AbstractInterpretation.CreatedBy.Result import Transformations.Util {- NOTE: The functions in this module handle #undefined producers as well. This means that the producer groupings will include a variable named "#undefined" if any undefined values appear in the code -} -- An untyped representation of the ProducerGraph (easier to handle). type ProducerGraph' = Map Name (Map Tag (Set Name)) -- Constructs the connection graph between all producers. -- First, it constructs the basic connection graph, -- then it calculcates the basic graph's transitive closure. groupAllProducers :: ProducerMap -> ProducerGraph groupAllProducers = toProducerGraph . transitiveClosure . undirectedReflexiveClosure . mkBasicProdGraph -- Constructs the connection graph between the active producers. -- First, it constructs the basic connection graph. -- Then it calculcates the basic graph's transitive closure for the active producers. -- Then it inserts the inactive producers with only reflexive connections. -- This way, the function calculates the transitive closure for potentially less nodes, -- but still retains information about all producers. groupActiveProducers :: LVAResult -> ProducerMap -> ProducerGraph groupActiveProducers lvaResult prodMap = toProducerGraph groupedProducers where groupedProducers :: ProducerGraph' groupedProducers = Map.union groupedActives reflexiveInactives reflexiveInactives :: ProducerGraph' reflexiveInactives = onlyReflexiveConnections . flip Map.withoutKeys activeProds $ basicGraph groupedActives :: ProducerGraph' groupedActives = transitiveClosure . undirectedReflexiveClosure . flip Map.restrictKeys activeProds $ basicGraph basicGraph :: ProducerGraph' basicGraph = mkBasicProdGraph prodMap activeProds :: Set Name activeProds = collectActiveProducers lvaResult prodMap toProducerGraph :: ProducerGraph' -> ProducerGraph toProducerGraph = ProducerGraph . ProducerMap . Map.map ProducerSet fromProducerGraph :: ProducerGraph -> ProducerGraph' fromProducerGraph = Map.map _producerSet . _producerMap . _producerGraph collectActiveProducers :: LVAResult -> ProducerMap -> Set Name collectActiveProducers lvaResult = selectActiveProducers lvaResult . collectProducers collectProducers :: ProducerMap -> Set Name collectProducers = mconcat . concatMap Map.elems . Map.elems . Map.map _producerSet . _producerMap -- Selects the active producers from a producer set. -- A producers is active if at least one of its tags has a live field. -- Producers are grouped by tags for each consumer, which means -- only producers with active tags will be grouped. As a consequence, -- we do not have to (explicitly) consider tag liveness info here. selectActiveProducers :: LVAResult -> Set Name -> Set Name selectActiveProducers lvaResult prods = Map.keysSet . Map.filter isNodeLive' . producerLiveness $ lvaResult where producerLiveness :: LVAResult -> Map Name Liveness producerLiveness = flip Map.restrictKeys prods . _registerLv isNodeLive' :: Liveness -> Bool isNodeLive' (NodeSet m) = any hasLiveField m isNodeLive' _ = error "Producers cannot have non-node liveness information" -- Constructs the basic connection graph between all producers. -- If a consumer has multiple producers with the same tag, -- then one producer will be selected, and the others will be connected to it. mkBasicProdGraph :: ProducerMap -> ProducerGraph' mkBasicProdGraph producers = flip execState mempty $ do let -- All the active producers found in the program grouped by tags. taggedGroups :: [(Tag, Set Name)] taggedGroups = concatMap (Map.toList . _producerSet) . Map.elems . _producerMap $ producers forM taggedGroups $ \(t,ps) -> do let (p:_) = Set.toList ps entry = Map.singleton t ps update = Map.unionWith Set.union modify $ Map.insertWith update p entry -- Deletes all connections then connects each producer with itself onlyReflexiveConnections :: ProducerGraph' -> ProducerGraph' onlyReflexiveConnections = Map.mapWithKey (\k m -> Map.map (const $ Set.singleton k) m) -- Creates an undirected graph from a directed one by connecting vertices -- in both directions. Also connects each vertex with itself. undirectedReflexiveClosure :: ProducerGraph' -> ProducerGraph' undirectedReflexiveClosure m = flip execState m $ do let pList = Map.toList . Map.map Map.toList . Map.map (Map.map Set.toList) $ m -- for each (p, (t, [p1 .. pn])), -- it add the entries: (p1, (t, [p])) .. (pn, (t, [p])) -- also insert p into (p, (t, [p1 .. pn])), forM pList $ \(p, taggedGroups) -> forM taggedGroups $ \(t, ps) -> forM ps $ \p' -> do let entry = Map.singleton t (Set.singleton p) itself = Map.singleton t (Set.singleton p) update = Map.unionWith Set.union modify $ Map.insertWith update p' entry -- undirecting modify $ Map.insertWith update p itself -- reflexivity -- Transitive clocure for undirected graphs. transitiveClosure :: ProducerGraph' -> ProducerGraph' transitiveClosure m | next <- tcStep m , next /= m = transitiveClosure next | otherwise = m where lookup' :: (Ord k, Monoid v) => k -> Map k v -> v lookup' k = fromMaybe mempty . Map.lookup k -- if p1 --t-> p2 and p2 --t-> p3 then p1 --t-> p3 tcStep :: ProducerGraph' -> ProducerGraph' tcStep m = flip execState m $ do let pList = Map.toList . Map.map Map.toList . Map.map (Map.map Set.toList) $ m forM pList $ \(p, taggedGroups) -> forM taggedGroups $ \(t, ps) -> forM ps $ \p' -> do let entry = (lookup' t . lookup' p' $ m) :: Set Name update = Map.adjust (Set.union entry) t modify $ Map.adjust update p withoutUndefined :: ProducerGraph' -> ProducerGraph' withoutUndefined = Map.delete undefinedProducerName
andorp/grin
grin/src/AbstractInterpretation/CreatedBy/Util.hs
bsd-3-clause
6,778
0
24
1,585
1,304
681
623
111
2
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Minecraft.Format.NBT.Data -- Copyright : (c) Tamar Christina 2012 -- License : BSD3 -- -- Maintainer : tamar@zhox.com -- Stability : experimental -- Portability : portable -- -- Datatype description of the Named Binary Type (NBT) format. -- Read more at of the format at -- http://web.archive.org/web/20110723210920/http://www.minecraft.net/docs/NBT.txt -- Remember that .NBT files are NOT gzipped but .schematic files are. -- ----------------------------------------------------------------------------- module Minecraft.Format.NBT.Data ( -- * Datatype descriptions Name(..) , NBT_Data(..) , NBT -- * Name creation functions , mkName ) where import Data.Int import Data.Word import Minecraft.Utils.CaseInSensitive type NBT = NBT_Data -- | An abstract representation of a Named and Unnamed structure data Name = Named { nmStr :: String } -- ^ A named string, e.g. an Explicitly named structure | Unnamed -- ^ An unnamed structured, only used in NBT_TAG_List deriving (Eq, Show) instance CaseInSensitiveEq Name Name where Unnamed === Unnamed = True (Named s1) === (Named s2) = s1 === s2 _ === _ = False instance CaseInSensitiveEq String Name where s1 === (Named s2) = s1 === s2 _ === _ = False instance CaseInSensitiveEq Name String where (===) = flip (===) instance CaseInSensitiveEq String NBT where a === b = a === nbtName b data NBT_Data = NBT_TAG_End { nbtName :: Name } -- ^ This tag is used to mark the end of a list. -- .Cannot be named! If type 0 appears where a Named Tag is expected, the name is assumed to be "". -- .(In other words, this Tag is always just a single 0 byte when named, and nothing in all other cases) | NBT_TAG_Byte { nbtName :: Name, nbtByte :: Int8 } -- ^ A single signed byte (8 bits) | NBT_TAG_Short { nbtName :: Name, nbtShort :: Int16 } -- ^ A signed short (16 bits, big endian) | NBT_TAG_Int { nbtName :: Name, nbtInt :: Int32 } -- ^ A signed short (32 bits, big endian) | NBT_TAG_Long { nbtName :: Name, nbtLong :: Int64 } -- ^ A signed long (64 bits, big endian) | NBT_TAG_Float { nbtName :: Name, nbtFloat :: Float } -- ^ A floating point value (32 bits, big endian, IEEE 754-2008, binary32) | NBT_TAG_Double { nbtName :: Name, nbtDouble :: Double } -- ^ A floating point value (64 bits, big endian, IEEE 754-2008, binary64) | NBT_TAG_Byte_Array { nbtName :: Name, nbtBArr :: [Int8] } -- ^ An array of bytes of unspecified format. The length of this array is <length> bytes | NBT_TAG_String { nbtName :: Name, nbtString :: String } -- ^ An array of bytes defining a string in UTF-8 format. The length of this array is <length> bytes | NBT_TAG_List { nbtName :: Name, nbtLCount :: Int8 , nbtPayload :: [NBT_Data] } -- ^ A sequential list of Tags (not Named Tags), of type <typeId>. The length of this array is <length> Tags -- . Notes: All tags share the same type | NBT_TAG_Compound { nbtName :: Name , nbtPayload :: [NBT_Data] } -- ^ A sequential list of Named Tags. This array keeps going until a TAG_End is found. -- . TAG_End end -- .Notes: If there's a nested TAG_Compound within this tag, that one will also have a TAG_End, so simply reading until the next TAG_End will not work. -- . The names of the named tags have to be unique within each TAG_Compound -- . The order of the tags is not guaranteed. deriving (Eq, Show) -- | Encode a string as a Name type, Specifically, -- an empty string should become an unnamed string mkName :: String -> Name mkName [] = Unnamed mkName s = Named s
Mistuke/CraftGen
Minecraft/Format/NBT/Data.hs
bsd-3-clause
4,470
0
9
1,454
517
320
197
46
1
import Execs main :: IO () main = potyogosHeu
AndrasKovacs/elte-cbsd
TestExecs/Components/PotyogosHeu.hs
bsd-3-clause
47
0
6
10
19
10
9
3
1
{-# LANGUAGE OverloadedStrings, PackageImports #-} module Lexer (sepTag) where -- import "monads-tf" Control.Monad.Trans import Data.Pipe -- import Data.Pipe.List -- import Data.Word8 import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC endWith :: Monad m => (Char -> Bool) -> Char -> BS.ByteString -> Pipe BS.ByteString BS.ByteString m () endWith p c rest = do let (t, d) = BSC.span (not . p) rest if BS.null d then do mbs <- await case mbs of Just bs -> endWith p c $ t `BS.append` bs _ -> return () else yield (BSC.cons c t) >> endWith p (BSC.head d) (BS.tail d) -- endByDot :: Monad m => Pipe BS.ByteString BS.ByteString m () -- -- -- -- -- -- -- -- endByDot = endWith (== '.') '.' "" sepTag :: Monad m => Pipe BS.ByteString BS.ByteString m () sepTag = endWith (`elem` "<>") '>' "" {- endByDot :: Monad m => BS.ByteString -> Pipe BS.ByteString BS.ByteString m () endByDot rest = do let (t, d) = BS.span (/= 46) rest if BS.null d then do mbs <- await case mbs of Just bs -> endByDot $ t `BS.append` bs _ -> return () else yield t >> endByDot (BS.tail d) -} {- bsToUpper :: BS.ByteString -> BS.ByteString bsToUpper = BS.pack . map toUpper . BS.unpack upper :: Monad m => Pipe BS.ByteString BS.ByteString m () upper = await >>= maybe (return ()) (\bs -> yield (bsToUpper bs) >> upper) -}
YoshikuniJujo/forest
subprojects/xml-pipe/Lexer.hs
bsd-3-clause
1,355
4
14
273
285
152
133
17
3
{-# LANGUAGE OverlappingInstances #-} {-# OPTIONS_GHC -cpp #-} -- -- Circuit compiler for the Faerieplay hardware-assisted secure -- computation project at Dartmouth College. -- -- Copyright (C) 2003-2007, Alexander Iliev <sasho@cs.dartmouth.edu> and -- Sean W. Smith <sws@cs.dartmouth.edu> -- -- All rights reserved. -- -- This code is released under a BSD license. -- Please see LICENSE.txt for the full license and disclaimers. -- module Main where import List (intersect, sort) import Maybe (isJust, fromJust, fromMaybe, listToMaybe, maybeToList) import System (getArgs, exitWith, ExitCode(..), getProgName, exitFailure) import IO ( Handle, stdin, stdout, stderr, hGetContents, hPrint, hFlush, hPutStrLn, hPutStr, openFile, hClose, IOMode(..), ioeGetErrorString) import qualified System.Console.GetOpt as Opt import Data.IORef (IORef,newIORef,readIORef,writeIORef) import System.IO.Unsafe (unsafePerformIO) import qualified Data.Graph.Inductive.Graph as Gr import qualified Data.Graph.Inductive.Tree as TreeGr import qualified Debug.Trace as Trace import qualified Text.PrettyPrint as PP import qualified System.IO.Error as IOErr -- get the parser stuff; for SFDL syntax, or for C #if defined SYNTAX_SFDL import qualified Faerieplay.Bnfc.Sfdl.Abs as SrcAbs -- the abstract syntax types from BNFC import qualified Faerieplay.Bnfc.Sfdl.Par as SrcPar -- the Happy parser import qualified Faerieplay.Bnfc.Sfdl.ErrM as SrcErrM import qualified Faerieplay.SFDL_Fixup as SrcFixup (fixupProg) import qualified Faerieplay.GenHelper_SFDL as SrcGenHelper (genHelper) #elif defined SYNTAX_C -- for C: import qualified Faerieplay.Bnfc.Fcpp.Abs as SrcAbs -- the abstract syntax types from BNFC import qualified Faerieplay.Bnfc.Fcpp.Par as SrcPar -- the Happy parser import qualified Faerieplay.Bnfc.Fcpp.ErrM as SrcErrM import qualified Faerieplay.SFDL_C_Fixup as SrcFixup (fixupProg) import qualified Faerieplay.GenHelper_C as SrcGenHelper (genHelper) #else #error No syntax defined #endif import qualified Data.Map as Map import qualified Faerieplay.Version as Vers import qualified Faerieplay.Intermediate as Im import qualified Faerieplay.HoistStms as Ho import qualified Faerieplay.Unroll as Ur import qualified Faerieplay.CircGen as CG import qualified Faerieplay.Runtime as Run import qualified IlievUtils.GraphLib as GrLib import IlievUtils.UDraw import Faerieplay.Common (trace,cMINPRIO,LogPrio(..),RunFlag(..)) import Faerieplay.ErrorWithContext (ErrorWithContext(..)) import Faerieplay.TypeChecker import IlievUtils.Misc cC_HELPER_TEMPLATE = "GenHelper_C.templ.cc" logmsg prio msg = do if prio >= cMINPRIO then hPutStrLn stderr $ "Main log " ++ show prio ++ ": " ++ msg else return () main = do argv <- getArgs name <- getProgName let o@(given_opts,args,errs) = Opt.getOpt Opt.Permute optionControl argv -- hPrint stderr o -- check for an error during option parsing. if (not $ null errs) then do hPutStrLn stderr "Command line errors:" mapM_ (hPutStrLn stderr) errs hPutStrLn stderr $ usage name exitWith ExitSuccess else return () -- if no options - default is to compile let unsorted_opts = if (null given_opts) then [Compile] else given_opts -- bring the action to the front by sorting let (action:opts) = sort $ unsorted_opts -- check for trivial actions, which do not need I/O file names case action of Version -> do putStrLn $ name ++ " " ++ Vers.getVersion exitWith ExitSuccess Help -> do hPutStrLn stderr $ usage name exitWith ExitSuccess _ -> return () -- need an input file infile <- maybe (do hPutStrLn stderr $ name ++ ": no input files.\nUse -h for help" exitFailure) (return) (listToMaybe args) -- get the input handle, a file or stdin hIn <- openFH ReadMode infile -- get an output file name if an input was provided -- Maybe monad let outfile = modFileExt infile $ case action of Compile -> "runtime" Run -> "run" MakeGraph -> "udg" -- UDrawGraph PruneGraph _ _ -> "pruned-cct" _ -> fail "" -- no output file in this case -- output handle: -- in order try: an '-o' option, input file with changed suffix. let fOut = fromJust $ listToMaybe $ [f | Output f <- unsorted_opts] ++ [outfile] hOut <- openFH WriteMode fOut case action of Compile -> driveCompile infile hIn hOut opts `trace` ("Compiling into " ++ fOut) Run -> driveRunFile (getRTFlags opts) hIn hOut MakeGraph -> driveGraph hIn hOut PruneGraph s d -> doPruneGraph s d hIn hOut mapM_ hClose [hIn, hOut] exitWith ExitSuccess -- save away the flags and input file name -- writeIORef g_Flags (unsorted_opts, mb_infile) driveCompile fIn hIn hOut opts = do let fIn' = case fIn of "-" -> "a.sfdl" -- just so any intermediate files have a -- basename _ -> fIn hGetContents hIn >>= doCompile 1 (getRTFlags opts) SrcPar.pProg fIn' hOut driveRunFile = doRunCct driveGraph = doWriteGraph ------------ -- command line argument processing stuff ------------ g_Flags :: IORef ([Flag], -- flags Maybe String) -- (optional) input file name g_Flags = unsafePerformIO $ newIORef ([], Nothing) data Flag = -- actions: Compile | MakeGraph | PruneGraph { start :: Gr.Node, d :: Int } -- produce a cct file with just a part of the circuit, 'd' -- nodes going backwards from 'start' | Run | Version | Help -- options: | RunFlag RunFlag -- a run-time flag, defined in Common.hs | Output String deriving (Eq,Ord,Show) -- possible extra files to generate during the compilation phase. cCOMPILE_EXTRAS = [DumpGates, DumpGraph] optionControl :: [Opt.OptDescr Flag] optionControl = [ -- actions Opt.Option ['c'] ["compile"] (Opt.NoArg Compile) "Compile SFDL (default action); .runtime" , Opt.Option ['G'] ["mkgraph"] (Opt.NoArg MakeGraph) "generate a UDrawGraph file; .cct -> .udg" , Opt.Option ['r'] ["run"] (Opt.NoArg Run) "Run circuit; .gates -> .run" , Opt.Option [ ] ["prune"] (Opt.ReqArg getPruneArgs "<start node>,<path len>") "Prune the circuit around a given node;\n.cct -> .cct" , Opt.Option ['V','?'] ["version"] (Opt.NoArg Version) "Show version number" , Opt.Option ['h'] ["help"] (Opt.NoArg Help) "Print help (this text)" , Opt.Option ['o'] ["output"] (Opt.ReqArg Output "<file>") "Output to <file>" , Opt.Option [ ] [] (Opt.NoArg Help) "Flags:" -- ############ flags -- here, internal form is using the standard (derived) Haskell Read/Show instances. , Opt.Option [ ] ["dump-gates", "dgt"] (Opt.NoArg (RunFlag DumpGates)) "dump the list of gates in internal form; -> .gates" , Opt.Option [ ] ["dump-graph", "dgr"] (Opt.NoArg (RunFlag DumpGraph)) "dump the graph in internal form; -> .cct" , Opt.Option ['p'] ["gen-print" ] (Opt.NoArg (RunFlag DoPrint)) "Generate Print gates from print() statements.\nIf not set, print statements are ignored." , Opt.Option ['v'] ["verbose"] (Opt.NoArg (RunFlag Verbose)) "Chatty output on stderr" , Opt.Option [ ] ["bindump"] (Opt.NoArg (RunFlag RunTraceBinary)) "Produce a run trace in binary, for comparing with the real runtime" ] getPruneArgs :: String -> Flag getPruneArgs str = let (start,str1) = head $ reads str (',':str2) = str1 (dist,[]) = head $ reads str2 in PruneGraph start dist getRTFlags :: [Flag] -> [RunFlag] getRTFlags flags = [rtf | (RunFlag rtf) <- flags] usage name = Opt.usageInfo ("Usage: " ++ name ++ " <options> in.sfdl\n\ Compiles SFDL files, simulates a circuit, and manipulates circuit files.\n\ Options, with associated default output filename extensions:") optionControl openFH mode name = Trace.trace ("Opening file " ++ name ++ " in " ++ show mode) $ case name of "-" -> return $ case mode of WriteMode -> stdout ReadMode -> stdin _ -> openFile name mode `catch` (\e -> do hPutStrLn stderr $ "failed to open " ++ name ++ ": " ++ ioeGetErrorString e exitWith $ ExitFailure 2) -- extract various options from the global options list getOutFile = do (flags,_) <- readIORef g_Flags return $ listToMaybe [f | Output f <- flags] getInFile = do (_,mb_infile) <- readIORef g_Flags return $ fromJustMsg "No actual input file specified" mb_infile type Verbosity = Int putStrV :: Verbosity -> String -> IO () putStrV v s = if v > 1 then putStrLn s else return () cCOMPILE_INTERMEDIATE_INFO = [ (DumpGraph, "cct"), (DumpGates, "gates") ] doCompile v rtFlags parser filenameIn hOut strIn = let tokens = SrcPar.myLexer strIn ast = parser tokens in case ast of SrcErrM.Bad s -> do putStrLn "\nParse Failed...\n" putStrV v "Tokens:" putStrV v $ show tokens putStrLn s SrcErrM.Ok prog@(SrcAbs.Prog _ _) -> do logmsg INFO "Parse Successful!" let fix_prog = SrcFixup.fixupProg prog case typeCheck fix_prog of (Left err) -> do hPutStrLn stderr $ "Type Error! " ++ showErrs err exitFailure (Right prog@(Im.Prog pname Im.ProgTables {Im.types=typ_table, Im.funcs=fs})) -> do -- hPrint stderr prog logmsg PROGRESS "Typechecking done" #ifdef SYNTAX_C -- FIXME: the helper file generation shouldbe controlled by some options probably. templ <- catch (openFile cC_HELPER_TEMPLATE ReadMode >>= hGetContents) (\e -> IOErr.ioError $ if IOErr.isDoesNotExistError e then IOErr.annotateIOError e ("Could not find the helper template " ++ cC_HELPER_TEMPLATE ++ ", ensure it is present in the current dir.") Nothing (Just cC_HELPER_TEMPLATE) else e) let helper = SrcGenHelper.genHelper templ prog helperFileName = modFileExt filenameIn "helper.cc" if not (null helper) then writeFile helperFileName helper else return () #endif let prog_flat = Ho.flattenProg prog logmsg PROGRESS "Flattened program" logmsg DEBUG $ "The flattened program:\n" ++ strShow prog_flat case Ur.unrollProg prog_flat of (Left err) -> do hPutStrLn stderr $ "Unrolling Error! " ++ showErrs err exitFailure (Right stms) -> do logmsg PROGRESS "Unrolled main; \ Starting to generate the circuit" logmsg DEBUG $ "The unrolled statements:\n" ++ PP.render (PP.vcat $ map Im.docStm stms) let -- compile the circuit args = CG.extractInputs prog (cct,gates) = CG.genCircuit rtFlags typ_table stms args -- write the .runtime file mapM_ (hPutStr hOut . CG.cctShow) gates logmsg PROGRESS "Wrote the circuit runtime file" -- and the extra outputs requested let extras = rtFlags `intersect` cCOMPILE_EXTRAS mapM_ (doExtras filenameIn (cct,gates)) extras showErrs (EWC (e, cs)) = show e ++ concatMap (("\n\tIn context of:\n" ++)) (reverse cs) doExtras filenameIn ccts flag = do let outfile = modFileExt filenameIn (fromJustMsg "extra compile action" (lookup flag cCOMPILE_INTERMEDIATE_INFO)) logmsg PROGRESS $ "Doing " ++ show flag ++ " into " ++ outfile writeFile outfile (doExtra flag ccts) logmsg PROGRESS $ "Done with " ++ show flag ++ "." doExtra DumpGates (cct,gates) = show gates doExtra DumpGraph (cct,gates) = GrLib.showGraph cct readCct :: (Read a, Read b) => Handle -> IO (TreeGr.Gr a b) readCct hIn = hGetContents hIn >>= readIO doWriteGraph cct_fh hOut = do logmsg PROGRESS $ "Generating the circuit graph (UDrawGraph)" cct <- hGetContents cct_fh >>= readIO -- NOTE: get an "Overlapping instances for Read" error if -- the type of cct is not specified, could be solved by ghc -- option -fallow-incoherent-instances which sounds bad. let _ = (cct :: CG.Circuit) hPutStrLn hOut $ CG.showCctGraph cct doPruneGraph :: Gr.Node -> Int -> Handle -> Handle -> IO() doPruneGraph start dist hIn hOut = do logmsg PROGRESS "Pruning the circuit graph" cct <- hGetContents hIn >>= readIO let _ = cct :: CG.Circuit let cct_pruned = GrLib.pruneGraph GrLib.back start dist cct (hPutStrLn hOut $ GrLib.showGraph cct_pruned) `trace` ("doPruneGraph: cct_pruned is\n" ++ show cct_pruned) doRunCct rtFlags gates_fh hOut = do logmsg PROGRESS "Now running the circuit" gates <- hGetContents gates_fh >>= readIO ins <- Run.getUserInputs gates vals <- Run.formatRun rtFlags gates ins mapM_ (hPutStrLn hOut) vals -- | change a filename's extension (part after the last dot) modFileExt file newext = let components = split '.' file in (joinLists "." (init components)) ++ "." ++ newext -- mapM_ print cct {- (stms,errs') -> -- errs' = strictList errs do print (PP.vcat (map Im.docStm stms)) print errs' {- if not $ null errs' then putStrLn "Failed!" -- >> print errs' else return () -} -} -- printMap m = mapM_ print $ Map.fold (:) [] m getMain (Im.Prog _ (Im.ProgTables {Im.funcs=fs})) = fromJustMsg "Failed to find main function" $ Map.lookup "main" fs testFlatten (Im.Prog pname (Im.ProgTables {Im.funcs=fs})) fname = do let (Just f) = Map.lookup fname fs f_flat = Ho.flattenFunc f print f_flat -- Prog _ decls -> case head decls of -- FunDecl _ _ _ _ stms -> print $ unrollStms stms -- showTree v $ Fun TInt (Ident "unrolled") unrolled {- Local Variables: time-stamp-start:"g_timestamp[ ]*=[ ][\"]" time-stamp-line-limit:60 End: -}
ailiev/faerieplay-compiler
Faerieplay/sfdlc.hs
bsd-3-clause
18,427
139
17
7,820
3,203
1,759
1,444
-1
-1
module Sound.Perform ( -- * Instrument Tuning , Instrument , sineInstrument , defaultTuning , perform -- * Composing , Com , NoteNumber , Duration , Freq , note , sqn , par ) where import Sound.Class import Sound.Fm import Sound.InfList import Sound.Table import Sound.Time import Unstable type NoteNumber a = a type Duration a = a type Freq a = a type Tuning a b = NoteNumber a -> Freq b {- | This is twelve-tone equal temperament where note number 96 is middle C tuned to 256 Hz. -} defaultTuning :: (Floating a) => Tuning a a defaultTuning n = 2 ** (n / 12) type Instrument a = Precision Int Double -> Freq (L a) -> Build (L a) (L a) sineInstrument :: Instrument Double sineInstrument p f = return (sfm (_prPeriod p) t f) where t = tsin 12 perform :: (Floating a) => Tuning a a -> Instrument a -> Com -> Build (L a) () perform tun ins = loop where loop com = case com of MkNote n d -> brate >>= \ r -> ins (fromRate $ _unRate r) (point $ tun $ fromIntegral n) >>= blwrite_ (bbeat d) Seq h t -> loop h >> loop t _ -> return () -- | Musical composition. data Com = MkNote (NoteNumber Int) (Duration Rational) | Seq Com Com | Par Com Com deriving (Read, Show) note :: NoteNumber Int -> Duration Rational -> Com note = MkNote sqn :: Com -> Com -> Com sqn = Seq par :: Com -> Com -> Com par = Par
edom/sound
src/Sound/Perform.hs
bsd-3-clause
1,468
0
16
437
519
278
241
50
3
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-} -- | This module re-exports the @Github.Data.Definitions@ module, adding -- instances of @FromJSON@ to it. If you wish to use the data without the -- instances, use the @Github.Data.Definitions@ module instead. module Github.Data (module Github.Data.Definitions) where import Data.Time import Control.Applicative import Control.Monad import qualified Data.Text as T import Data.Aeson.Types import Data.Monoid import System.Locale (defaultTimeLocale) import qualified Data.Vector as V import qualified Data.HashMap.Lazy as Map import Data.Hashable (Hashable) import Github.Data.Definitions instance FromJSON GithubDate where parseJSON (String t) = case parseTime defaultTimeLocale "%FT%T%Z" (T.unpack t) of Just d -> pure $ GithubDate d _ -> fail "could not parse Github datetime" parseJSON _ = fail "Given something besides a String" instance FromJSON Commit where parseJSON (Object o) = Commit <$> o .: "sha" <*> o .: "parents" <*> o .: "url" <*> o .: "commit" <*> o .:? "committer" <*> o .:? "author" <*> o .:< "files" <*> o .:? "stats" parseJSON _ = fail "Could not build a Commit" instance FromJSON Tree where parseJSON (Object o) = Tree <$> o .: "sha" <*> o .: "url" <*> o .:< "tree" parseJSON _ = fail "Could not build a Tree" instance FromJSON GitTree where parseJSON (Object o) = GitTree <$> o .: "type" <*> o .: "sha" <*> o .: "url" <*> o .:? "size" <*> o .: "path" <*> o .: "mode" parseJSON _ = fail "Could not build a GitTree" instance FromJSON GitCommit where parseJSON (Object o) = GitCommit <$> o .: "message" <*> o .: "url" <*> o .: "committer" <*> o .: "author" <*> o .: "tree" <*> o .:? "sha" <*> o .:< "parents" parseJSON _ = fail "Could not build a GitCommit" instance FromJSON GithubOwner where parseJSON (Object o) | o `at` "gravatar_id" == Nothing = GithubOrganization <$> o .: "avatar_url" <*> o .: "login" <*> o .: "url" <*> o .: "id" | otherwise = GithubUser <$> o .: "avatar_url" <*> o .: "login" <*> o .: "url" <*> o .: "id" <*> o .: "gravatar_id" parseJSON v = fail $ "Could not build a GithubOwner out of " ++ (show v) instance FromJSON GitUser where parseJSON (Object o) = GitUser <$> o .: "name" <*> o .: "email" <*> o .: "date" parseJSON _ = fail "Could not build a GitUser" instance FromJSON File where parseJSON (Object o) = File <$> o .: "blob_url" <*> o .: "status" <*> o .: "raw_url" <*> o .: "additions" <*> o .: "sha" <*> o .: "changes" <*> o .: "patch" <*> o .: "filename" <*> o .: "deletions" parseJSON _ = fail "Could not build a File" instance FromJSON Stats where parseJSON (Object o) = Stats <$> o .: "additions" <*> o .: "total" <*> o .: "deletions" parseJSON _ = fail "Could not build a Stats" instance FromJSON Comment where parseJSON (Object o) = Comment <$> o .:? "position" <*> o .:? "line" <*> o .: "body" <*> o .: "commit_id" <*> o .: "updated_at" <*> o .:? "html_url" <*> o .: "url" <*> o .: "created_at" <*> o .: "path" <*> o .: "user" <*> o .: "id" parseJSON _ = fail "Could not build a Comment" instance ToJSON NewComment where toJSON (NewComment b) = object [ "body" .= b ] instance ToJSON EditComment where toJSON (EditComment b) = object [ "body" .= b ] instance FromJSON Diff where parseJSON (Object o) = Diff <$> o .: "status" <*> o .: "behind_by" <*> o .: "patch_url" <*> o .: "url" <*> o .: "base_commit" <*> o .:< "commits" <*> o .: "total_commits" <*> o .: "html_url" <*> o .:< "files" <*> o .: "ahead_by" <*> o .: "diff_url" <*> o .: "permalink_url" parseJSON _ = fail "Could not build a Diff" instance FromJSON Gist where parseJSON (Object o) = Gist <$> o .: "user" <*> o .: "git_push_url" <*> o .: "url" <*> o .:? "description" <*> o .: "created_at" <*> o .: "public" <*> o .: "comments" <*> o .: "updated_at" <*> o .: "html_url" <*> o .: "id" <*> o `values` "files" <*> o .: "git_push_url" parseJSON _ = fail "Could not build a Gist" instance FromJSON GistFile where parseJSON (Object o) = GistFile <$> o .: "type" <*> o .: "raw_url" <*> o .: "size" <*> o .:? "language" <*> o .: "filename" <*> o .:? "content" parseJSON _ = fail "Could not build a GistFile" instance FromJSON GistComment where parseJSON (Object o) = GistComment <$> o .: "user" <*> o .: "url" <*> o .: "created_at" <*> o .: "body" <*> o .: "updated_at" <*> o .: "id" parseJSON _ = fail "Could not build a GistComment" instance FromJSON Blob where parseJSON (Object o) = Blob <$> o .: "url" <*> o .: "encoding" <*> o .: "content" <*> o .: "sha" <*> o .: "size" parseJSON _ = fail "Could not build a Blob" instance FromJSON GitReference where parseJSON (Object o) = GitReference <$> o .: "object" <*> o .: "url" <*> o .: "ref" parseJSON _ = fail "Could not build a GitReference" instance FromJSON GitObject where parseJSON (Object o) = GitObject <$> o .: "type" <*> o .: "sha" <*> o .: "url" parseJSON _ = fail "Could not build a GitObject" instance FromJSON Issue where parseJSON (Object o) = Issue <$> o .:? "closed_at" <*> o .: "updated_at" <*> o .: "html_url" <*> o .:? "closed_by" <*> o .: "labels" <*> o .: "number" <*> o .:? "assignee" <*> o .: "user" <*> o .: "title" <*> o .: "pull_request" <*> o .: "url" <*> o .: "created_at" <*> o .: "body" <*> o .: "state" <*> o .: "id" <*> o .: "comments" <*> o .:? "milestone" parseJSON _ = fail "Could not build an Issue" instance ToJSON NewIssue where toJSON (NewIssue t b a m ls) = object [ "title" .= t , "body" .= b , "assignee" .= a , "milestone" .= m , "labels" .= ls ] instance ToJSON EditIssue where toJSON (EditIssue t b a s m ls) = object $ filter notNull $ [ "title" .= t , "body" .= b , "assignee" .= a , "state" .= s , "milestone" .= m , "labels" .= ls ] where notNull (_, Null) = False notNull (_, _) = True instance FromJSON Milestone where parseJSON (Object o) = Milestone <$> o .: "creator" <*> o .: "due_on" <*> o .: "open_issues" <*> o .: "number" <*> o .: "closed_issues" <*> o .: "description" <*> o .: "title" <*> o .: "url" <*> o .: "created_at" <*> o .: "state" parseJSON _ = fail "Could not build a Milestone" instance FromJSON IssueLabel where parseJSON (Object o) = IssueLabel <$> o .: "color" <*> o .: "url" <*> o .: "name" parseJSON _ = fail "Could not build a Milestone" instance FromJSON PullRequestReference where parseJSON (Object o) = PullRequestReference <$> o .:? "html_url" <*> o .:? "patch_url" <*> o .:? "diff_url" parseJSON _ = fail "Could not build a PullRequest" instance FromJSON IssueComment where parseJSON (Object o) = IssueComment <$> o .: "updated_at" <*> o .: "user" <*> o .: "url" <*> o .: "created_at" <*> o .: "body" <*> o .: "id" parseJSON _ = fail "Could not build an IssueComment" instance FromJSON Event where parseJSON (Object o) = Event <$> o .: "actor" <*> o .: "event" <*> o .:? "commit_id" <*> o .: "url" <*> o .: "created_at" <*> o .: "id" <*> o .:? "issue" parseJSON _ = fail "Could not build an Event" instance FromJSON EventType where parseJSON (String "closed") = pure Closed parseJSON (String "reopened") = pure Reopened parseJSON (String "subscribed") = pure Subscribed parseJSON (String "merged") = pure Merged parseJSON (String "referenced") = pure Referenced parseJSON (String "mentioned") = pure Mentioned parseJSON (String "assigned") = pure Assigned parseJSON (String "unsubscribed") = pure Unsubscribed parseJSON _ = fail "Could not build an EventType" instance FromJSON SimpleOrganization where parseJSON (Object o) = SimpleOrganization <$> o .: "url" <*> o .: "avatar_url" <*> o .: "id" <*> o .: "login" parseJSON _ = fail "Could not build a SimpleOrganization" instance FromJSON Organization where parseJSON (Object o) = Organization <$> o .: "type" <*> o .:? "blog" <*> o .:? "location" <*> o .: "login" <*> o .: "followers" <*> o .:? "company" <*> o .: "avatar_url" <*> o .: "public_gists" <*> o .: "html_url" <*> o .:? "email" <*> o .: "following" <*> o .: "public_repos" <*> o .: "url" <*> o .: "created_at" <*> o .:? "name" <*> o .: "id" parseJSON _ = fail "Could not build an Organization" instance FromJSON PullRequest where parseJSON (Object o) = PullRequest <$> o .:? "closed_at" <*> o .: "created_at" <*> o .: "user" <*> o .: "patch_url" <*> o .: "state" <*> o .: "number" <*> o .: "html_url" <*> o .: "updated_at" <*> o .: "body" <*> o .: "issue_url" <*> o .: "diff_url" <*> o .: "url" <*> o .: "_links" <*> o .:? "merged_at" <*> o .: "title" <*> o .: "id" parseJSON _ = fail "Could not build a PullRequest" instance FromJSON DetailedPullRequest where parseJSON (Object o) = DetailedPullRequest <$> o .:? "closed_at" <*> o .: "created_at" <*> o .: "user" <*> o .: "patch_url" <*> o .: "state" <*> o .: "number" <*> o .: "html_url" <*> o .: "updated_at" <*> o .: "body" <*> o .: "issue_url" <*> o .: "diff_url" <*> o .: "url" <*> o .: "_links" <*> o .:? "merged_at" <*> o .: "title" <*> o .: "id" <*> o .:? "merged_by" <*> o .: "changed_files" <*> o .: "head" <*> o .: "comments" <*> o .: "deletions" <*> o .: "additions" <*> o .: "review_comments" <*> o .: "base" <*> o .: "commits" <*> o .: "merged" <*> o .: "mergeable" parseJSON _ = fail "Could not build a DetailedPullRequest" instance FromJSON PullRequestLinks where parseJSON (Object o) = PullRequestLinks <$> o <.:> ["review_comments", "href"] <*> o <.:> ["comments", "href"] <*> o <.:> ["html", "href"] <*> o <.:> ["self", "href"] parseJSON _ = fail "Could not build a PullRequestLinks" instance FromJSON PullRequestCommit where parseJSON (Object _) = return PullRequestCommit parseJSON _ = fail "Could not build a PullRequestCommit" instance FromJSON SearchReposResult where parseJSON (Object o) = SearchReposResult <$> o .: "total_count" <*> o .:< "items" parseJSON _ = fail "Could not build a SearchReposResult" instance FromJSON Repo where parseJSON (Object o) = Repo <$> o .: "ssh_url" <*> o .: "description" <*> o .: "created_at" <*> o .: "html_url" <*> o .: "svn_url" <*> o .: "forks" <*> o .:? "homepage" <*> o .: "fork" <*> o .: "git_url" <*> o .: "private" <*> o .: "clone_url" <*> o .: "size" <*> o .: "updated_at" <*> o .: "watchers" <*> o .: "owner" <*> o .: "name" <*> o .: "language" <*> o .:? "master_branch" <*> o .: "pushed_at" <*> o .: "id" <*> o .: "url" <*> o .: "open_issues" <*> o .:? "has_wiki" <*> o .:? "has_issues" <*> o .:? "has_downloads" <*> o .:? "parent" <*> o .:? "source" parseJSON _ = fail "Could not build a Repo" instance FromJSON RepoRef where parseJSON (Object o) = RepoRef <$> o .: "owner" <*> o .: "name" parseJSON _ = fail "Could not build a RepoRef" instance FromJSON Contributor where parseJSON (Object o) | o `at` "type" == (Just "Anonymous") = AnonymousContributor <$> o .: "contributions" <*> o .: "name" | otherwise = KnownContributor <$> o .: "contributions" <*> o .: "avatar_url" <*> o .: "login" <*> o .: "url" <*> o .: "id" <*> o .: "gravatar_id" parseJSON _ = fail "Could not build a Contributor" instance FromJSON Languages where parseJSON (Object o) = Languages <$> mapM (\name -> Language (T.unpack name) <$> o .: name) (Map.keys o) parseJSON _ = fail "Could not build Languages" instance FromJSON Tag where parseJSON (Object o) = Tag <$> o .: "name" <*> o .: "zipball_url" <*> o .: "tarball_url" <*> o .: "commit" parseJSON _ = fail "Could not build a Tag" instance FromJSON Branch where parseJSON (Object o) = Branch <$> o .: "name" <*> o .: "commit" parseJSON _ = fail "Could not build a Branch" instance FromJSON BranchCommit where parseJSON (Object o) = BranchCommit <$> o .: "sha" <*> o .: "url" parseJSON _ = fail "Could not build a BranchCommit" instance FromJSON DetailedOwner where parseJSON (Object o) | o `at` "gravatar_id" == Nothing = DetailedOrganization <$> o .: "created_at" <*> o .: "type" <*> o .: "public_gists" <*> o .: "avatar_url" <*> o .: "followers" <*> o .: "following" <*> o .:? "blog" <*> o .:? "bio" <*> o .: "public_repos" <*> o .:? "name" <*> o .:? "location" <*> o .:? "company" <*> o .: "url" <*> o .: "id" <*> o .: "html_url" <*> o .: "login" | otherwise = DetailedUser <$> o .: "created_at" <*> o .: "type" <*> o .: "public_gists" <*> o .: "avatar_url" <*> o .: "followers" <*> o .: "following" <*> o .: "hireable" <*> o .: "gravatar_id" <*> o .:? "blog" <*> o .:? "bio" <*> o .: "public_repos" <*> o .:? "name" <*> o .:? "location" <*> o .:? "company" <*> o .: "email" <*> o .: "url" <*> o .: "id" <*> o .: "html_url" <*> o .: "login" parseJSON _ = fail "Could not build a DetailedOwner" -- | A slightly more generic version of Aeson's @(.:?)@, using `mzero' instead -- of `Nothing'. (.:<) :: (FromJSON a) => Object -> T.Text -> Parser [a] obj .:< key = case Map.lookup key obj of Nothing -> pure mzero Just v -> parseJSON v -- | Produce all values for the given key. values :: (Eq k, Hashable k, FromJSON v) => Map.HashMap k Value -> k -> Parser v obj `values` key = let (Object children) = findWithDefault (Object Map.empty) key obj in parseJSON $ Array $ V.fromList $ Map.elems children -- | Produce the value for the last key by traversing. (<.:>) :: (FromJSON v) => Object -> [T.Text] -> Parser v obj <.:> [key] = obj .: key obj <.:> (key:keys) = let (Object nextObj) = findWithDefault (Object Map.empty) key obj in nextObj <.:> keys -- | Produce the value for the given key, maybe. at :: Object -> T.Text -> Maybe Value obj `at` key = Map.lookup key obj -- Taken from Data.Map: findWithDefault :: (Eq k, Hashable k) => v -> k -> Map.HashMap k v -> v findWithDefault def k m = case Map.lookup k m of Nothing -> def Just x -> x
rom1504/github
Github/Data.hs
bsd-3-clause
17,561
7
59
6,665
4,779
2,395
2,384
491
2
module Main where import Data.Workshop.ListMap as M --import Data.Workshop.HashMap as M type MyMap = M.ListMap Int --type MyMap = M.HashMap Int type MapData = Int showMap :: MyMap -> IO () showMap m = do let ks = M.keys m kvs = map (\k -> k ++ ": " ++ (show (M.get m k))) ks emptyStr = "empty: " ++ (show (M.isEmpty m)) sizeStr = "size: " ++ (show (M.size m)) containsSpideyStr = "spider-man: " ++ (show (M.contains m "Spider-Man")) putStrLn $ unlines $ [emptyStr, sizeStr, containsSpideyStr, "data:\n"] ++ kvs putStrLn "---- DUMP ----" putStrLn $ M.dump m putStrLn "---- DUMP ----\n\n" main :: IO () main = do let m = M.empty :: MyMap m' = M.put m "Iron Man" 1900 m'' = M.put m' "Spider-Man" 1250 m''' = M.put m'' "Elephant Man" 1150 m'''' = M.put m''' "Spider-Man" 1850 m''''' = M.delete m'''' "Spider-Man" m'''''' = M.clear m''''' putStrLn "Mapper" putStrLn $ "m" showMap m putStrLn $ "m'" showMap m' putStrLn $ "m''" showMap m'' putStrLn $ "m'''" showMap m''' putStrLn $ "m''''" showMap m'''' putStrLn $ "m'''''" showMap m''''' putStrLn $ "m''''''" showMap m''''''
wiggly/workshop
app/Mapper.hs
bsd-3-clause
1,176
0
18
294
435
212
223
39
1
--{-# OPTIONS_GHC -F -pgmF hspec-discover #-} module Spec where import Test.Hspec import qualified MainSpec import qualified ProposerSpec import qualified AcceptorSpec import qualified UtilsSpec main :: IO () main = hspec spec spec :: Spec spec = do describe "MainSpec" MainSpec.spec describe "ProposerSpec" ProposerSpec.spec describe "AcceptorSpec" AcceptorSpec.spec describe "UtilsSpec" UtilsSpec.spec
michelrivas/paxos
test/Spec.hs
bsd-3-clause
435
0
8
80
94
50
44
14
1
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE MultiParamTypeClasses #-} #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE PolyKinds #-} -- gplate1 #endif #ifdef TRUSTWORTHY {-# LANGUAGE Trustworthy #-} -- template-haskell #endif #if __GLASGOW_HASKELL__ < 710 {-# LANGUAGE OverlappingInstances #-} #define OVERLAPPING_PRAGMA #else #define OVERLAPPING_PRAGMA {-# OVERLAPPING #-} #endif #include "lens-common.h" ------------------------------------------------------------------------------- -- | -- Module : Control.Lens.Plated -- Copyright : (C) 2012-16 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : Rank2Types -- -- The name \"plate\" stems originally from \"boilerplate\", which was the term -- used by the \"Scrap Your Boilerplate\" papers, and later inherited by Neil -- Mitchell's \"Uniplate\". -- -- <http://community.haskell.org/~ndm/uniplate/> -- -- The combinators in here are designed to be compatible with and subsume the -- @uniplate@ API with the notion of a 'Traversal' replacing -- a 'Data.Data.Lens.uniplate' or 'Data.Data.Lens.biplate'. -- -- By implementing these combinators in terms of 'plate' instead of -- 'Data.Data.Lens.uniplate' additional type safety is gained, as the user is -- no longer responsible for maintaining invariants such as the number of -- children they received. -- -- Note: The @Biplate@ is /deliberately/ excluded from the API here, with the -- intention that you replace them with either explicit traversals, or by using the -- @On@ variants of the combinators below with 'Data.Data.Lens.biplate' from -- @Data.Data.Lens@. As a design, it forced the user into too many situations where -- they had to choose between correctness and ease of use, and it was brittle in the -- face of competing imports. -- -- The sensible use of these combinators makes some simple assumptions. Notably, any -- of the @On@ combinators are expecting a 'Traversal', 'Setter' or 'Fold' -- to play the role of the 'Data.Data.Lens.biplate' combinator, and so when the -- types of the contents and the container match, they should be the 'id' 'Traversal', -- 'Setter' or 'Fold'. -- -- It is often beneficial to use the combinators in this module with the combinators -- from @Data.Data.Lens@ or @GHC.Generics.Lens@ to make it easier to automatically -- derive definitions for 'plate', or to derive custom traversals. ------------------------------------------------------------------------------- module Control.Lens.Plated ( -- * Uniplate Plated(..) -- * Uniplate Combinators , children , rewrite, rewriteOf, rewriteOn, rewriteOnOf , rewriteM, rewriteMOf, rewriteMOn, rewriteMOnOf , universe, universeOf, universeOn, universeOnOf , cosmos, cosmosOf, cosmosOn, cosmosOnOf , transform, transformOf, transformOn, transformOnOf , transformM, transformMOf, transformMOn, transformMOnOf , contexts, contextsOf, contextsOn, contextsOnOf , holes, holesOn, holesOnOf , para, paraOf , (...), deep -- * Compos -- $compos , composOpFold -- * Parts , parts -- * Generics , gplate , gplate1 , GPlated , GPlated1 ) where import Prelude () import Control.Comonad.Cofree import qualified Control.Comonad.Trans.Cofree as CoTrans import Control.Lens.Fold import Control.Lens.Getter import Control.Lens.Indexed import Control.Lens.Internal.Context import Control.Lens.Internal.Prelude import Control.Lens.Type import Control.Lens.Setter import Control.Lens.Traversal import Control.Monad.Free as Monad import Control.Monad.Free.Church as Church import Control.Monad.Trans.Free as Trans #if !(MIN_VERSION_free(4,6,0)) import Control.MonadPlus.Free as MonadPlus #endif import qualified Language.Haskell.TH as TH import Data.Data import Data.Data.Lens import Data.Tree import GHC.Generics #ifdef HLINT {-# ANN module "HLint: ignore Reduce duplication" #-} #endif -- | A 'Plated' type is one where we know how to extract its immediate self-similar children. -- -- /Example 1/: -- -- @ -- import Control.Applicative -- import Control.Lens -- import Control.Lens.Plated -- import Data.Data -- import Data.Data.Lens ('Data.Data.Lens.uniplate') -- @ -- -- @ -- data Expr -- = Val 'Int' -- | Neg Expr -- | Add Expr Expr -- deriving ('Eq','Ord','Show','Read','Data','Typeable') -- @ -- -- @ -- instance 'Plated' Expr where -- 'plate' f (Neg e) = Neg '<$>' f e -- 'plate' f (Add a b) = Add '<$>' f a '<*>' f b -- 'plate' _ a = 'pure' a -- @ -- -- /or/ -- -- @ -- instance 'Plated' Expr where -- 'plate' = 'Data.Data.Lens.uniplate' -- @ -- -- /Example 2/: -- -- @ -- import Control.Applicative -- import Control.Lens -- import Control.Lens.Plated -- import Data.Data -- import Data.Data.Lens ('Data.Data.Lens.uniplate') -- @ -- -- @ -- data Tree a -- = Bin (Tree a) (Tree a) -- | Tip a -- deriving ('Eq','Ord','Show','Read','Data','Typeable') -- @ -- -- @ -- instance 'Plated' (Tree a) where -- 'plate' f (Bin l r) = Bin '<$>' f l '<*>' f r -- 'plate' _ t = 'pure' t -- @ -- -- /or/ -- -- @ -- instance 'Data' a => 'Plated' (Tree a) where -- 'plate' = 'uniplate' -- @ -- -- Note the big distinction between these two implementations. -- -- The former will only treat children directly in this tree as descendents, -- the latter will treat trees contained in the values under the tips also -- as descendants! -- -- When in doubt, pick a 'Traversal' and just use the various @...Of@ combinators -- rather than pollute 'Plated' with orphan instances! -- -- If you want to find something unplated and non-recursive with 'Data.Data.Lens.biplate' -- use the @...OnOf@ variant with 'ignored', though those usecases are much better served -- in most cases by using the existing 'Lens' combinators! e.g. -- -- @ -- 'toListOf' 'biplate' ≡ 'universeOnOf' 'biplate' 'ignored' -- @ -- -- This same ability to explicitly pass the 'Traversal' in question is why there is no -- analogue to uniplate's @Biplate@. -- -- Moreover, since we can allow custom traversals, we implement reasonable defaults for -- polymorphic data types, that only 'Control.Traversable.traverse' into themselves, and /not/ their -- polymorphic arguments. class Plated a where -- | 'Traversal' of the immediate children of this structure. -- -- If you're using GHC 7.2 or newer and your type has a 'Data' instance, -- 'plate' will default to 'uniplate' and you can choose to not override -- it with your own definition. plate :: Traversal' a a default plate :: Data a => Traversal' a a plate = uniplate instance Plated [a] where plate f (x:xs) = (x:) <$> f xs plate _ [] = pure [] instance Traversable f => Plated (Monad.Free f a) where plate f (Monad.Free as) = Monad.Free <$> traverse f as plate _ x = pure x instance (Traversable f, Traversable m) => Plated (Trans.FreeT f m a) where plate f (Trans.FreeT xs) = Trans.FreeT <$> traverse (traverse f) xs #if !(MIN_VERSION_free(4,6,0)) instance Traversable f => Plated (MonadPlus.Free f a) where plate f (MonadPlus.Free as) = MonadPlus.Free <$> traverse f as plate f (MonadPlus.Plus as) = MonadPlus.Plus <$> traverse f as plate _ x = pure x #endif instance Traversable f => Plated (Church.F f a) where plate f = fmap Church.toF . plate (fmap Church.fromF . f . Church.toF) . Church.fromF -- -- This one can't work -- -- instance (Traversable f, Traversable m) => Plated (ChurchT.FT f m a) where -- plate f = fmap ChurchT.toFT . plate (fmap ChurchT.fromFT . f . ChurchT.toFT) . ChurchT.fromFT instance (Traversable f, Traversable w) => Plated (CoTrans.CofreeT f w a) where plate f (CoTrans.CofreeT xs) = CoTrans.CofreeT <$> traverse (traverse f) xs instance Traversable f => Plated (Cofree f a) where plate f (a :< as) = (:<) a <$> traverse f as instance Plated (Tree a) where plate f (Node a as) = Node a <$> traverse f as {- Default uniplate instances -} instance Plated TH.Exp instance Plated TH.Dec instance Plated TH.Con instance Plated TH.Type #if !(MIN_VERSION_template_haskell(2,8,0)) instance Plated TH.Kind -- in 2.8 Kind is an alias for Type #endif instance Plated TH.Stmt instance Plated TH.Pat infixr 9 ... -- | Compose through a plate (...) :: (Applicative f, Plated c) => LensLike f s t c c -> Over p f c c a b -> Over p f s t a b l ... m = l . plate . m {-# INLINE (...) #-} -- | Try to apply a traversal to all transitive descendants of a 'Plated' container, but -- do not recurse through matching descendants. -- -- @ -- 'deep' :: 'Plated' s => 'Fold' s a -> 'Fold' s a -- 'deep' :: 'Plated' s => 'IndexedFold' s a -> 'IndexedFold' s a -- 'deep' :: 'Plated' s => 'Traversal' s s a b -> 'Traversal' s s a b -- 'deep' :: 'Plated' s => 'IndexedTraversal' s s a b -> 'IndexedTraversal' s s a b -- @ deep :: (Conjoined p, Applicative f, Plated s) => Traversing p f s s a b -> Over p f s s a b deep = deepOf plate ------------------------------------------------------------------------------- -- Children ------------------------------------------------------------------------------- -- | Extract the immediate descendants of a 'Plated' container. -- -- @ -- 'children' ≡ 'toListOf' 'plate' -- @ children :: Plated a => a -> [a] children = toListOf plate {-# INLINE children #-} ------------------------------------------------------------------------------- -- Rewriting ------------------------------------------------------------------------------- -- | Rewrite by applying a rule everywhere you can. Ensures that the rule cannot -- be applied anywhere in the result: -- -- @ -- propRewrite r x = 'all' ('Data.Just.isNothing' '.' r) ('universe' ('rewrite' r x)) -- @ -- -- Usually 'transform' is more appropriate, but 'rewrite' can give better -- compositionality. Given two single transformations @f@ and @g@, you can -- construct @\\a -> f a '<|>' g a@ which performs both rewrites until a fixed point. rewrite :: Plated a => (a -> Maybe a) -> a -> a rewrite = rewriteOf plate {-# INLINE rewrite #-} -- | Rewrite by applying a rule everywhere you can. Ensures that the rule cannot -- be applied anywhere in the result: -- -- @ -- propRewriteOf l r x = 'all' ('Data.Just.isNothing' '.' r) ('universeOf' l ('rewriteOf' l r x)) -- @ -- -- Usually 'transformOf' is more appropriate, but 'rewriteOf' can give better -- compositionality. Given two single transformations @f@ and @g@, you can -- construct @\\a -> f a '<|>' g a@ which performs both rewrites until a fixed point. -- -- @ -- 'rewriteOf' :: 'Control.Lens.Iso.Iso'' a a -> (a -> 'Maybe' a) -> a -> a -- 'rewriteOf' :: 'Lens'' a a -> (a -> 'Maybe' a) -> a -> a -- 'rewriteOf' :: 'Traversal'' a a -> (a -> 'Maybe' a) -> a -> a -- 'rewriteOf' :: 'Setter'' a a -> (a -> 'Maybe' a) -> a -> a -- @ rewriteOf :: ASetter a b a b -> (b -> Maybe a) -> a -> b rewriteOf l f = go where go = transformOf l (\x -> maybe x go (f x)) {-# INLINE rewriteOf #-} -- | Rewrite recursively over part of a larger structure. -- -- @ -- 'rewriteOn' :: 'Plated' a => 'Control.Lens.Iso.Iso'' s a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOn' :: 'Plated' a => 'Lens'' s a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOn' :: 'Plated' a => 'Traversal'' s a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOn' :: 'Plated' a => 'ASetter'' s a -> (a -> 'Maybe' a) -> s -> s -- @ rewriteOn :: Plated a => ASetter s t a a -> (a -> Maybe a) -> s -> t rewriteOn b = over b . rewrite {-# INLINE rewriteOn #-} -- | Rewrite recursively over part of a larger structure using a specified 'Setter'. -- -- @ -- 'rewriteOnOf' :: 'Control.Lens.Iso.Iso'' s a -> 'Control.Lens.Iso.Iso'' a a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOnOf' :: 'Lens'' s a -> 'Lens'' a a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOnOf' :: 'Traversal'' s a -> 'Traversal'' a a -> (a -> 'Maybe' a) -> s -> s -- 'rewriteOnOf' :: 'Setter'' s a -> 'Setter'' a a -> (a -> 'Maybe' a) -> s -> s -- @ rewriteOnOf :: ASetter s t a b -> ASetter a b a b -> (b -> Maybe a) -> s -> t rewriteOnOf b l = over b . rewriteOf l {-# INLINE rewriteOnOf #-} -- | Rewrite by applying a monadic rule everywhere you can. Ensures that the rule cannot -- be applied anywhere in the result. rewriteM :: (Monad m, Plated a) => (a -> m (Maybe a)) -> a -> m a rewriteM = rewriteMOf plate {-# INLINE rewriteM #-} -- | Rewrite by applying a monadic rule everywhere you recursing with a user-specified 'Traversal'. -- Ensures that the rule cannot be applied anywhere in the result. rewriteMOf :: Monad m => LensLike (WrappedMonad m) a b a b -> (b -> m (Maybe a)) -> a -> m b rewriteMOf l f = go where go = transformMOf l (\x -> f x >>= maybe (return x) go) {-# INLINE rewriteMOf #-} -- | Rewrite by applying a monadic rule everywhere inside of a structure located by a user-specified 'Traversal'. -- Ensures that the rule cannot be applied anywhere in the result. rewriteMOn :: (Monad m, Plated a) => LensLike (WrappedMonad m) s t a a -> (a -> m (Maybe a)) -> s -> m t rewriteMOn b = mapMOf b . rewriteM {-# INLINE rewriteMOn #-} -- | Rewrite by applying a monadic rule everywhere inside of a structure located by a user-specified 'Traversal', -- using a user-specified 'Traversal' for recursion. Ensures that the rule cannot be applied anywhere in the result. rewriteMOnOf :: Monad m => LensLike (WrappedMonad m) s t a b -> LensLike (WrappedMonad m) a b a b -> (b -> m (Maybe a)) -> s -> m t rewriteMOnOf b l = mapMOf b . rewriteMOf l {-# INLINE rewriteMOnOf #-} ------------------------------------------------------------------------------- -- Universe ------------------------------------------------------------------------------- -- | Retrieve all of the transitive descendants of a 'Plated' container, including itself. universe :: Plated a => a -> [a] universe = universeOf plate {-# INLINE universe #-} -- | Given a 'Fold' that knows how to locate immediate children, retrieve all of the transitive descendants of a node, including itself. -- -- @ -- 'universeOf' :: 'Fold' a a -> a -> [a] -- @ universeOf :: Getting [a] a a -> a -> [a] universeOf l = go where go a = a : foldMapOf l go a {-# INLINE universeOf #-} -- | Given a 'Fold' that knows how to find 'Plated' parts of a container retrieve them and all of their descendants, recursively. universeOn :: Plated a => Getting [a] s a -> s -> [a] universeOn b = universeOnOf b plate {-# INLINE universeOn #-} -- | Given a 'Fold' that knows how to locate immediate children, retrieve all of the transitive descendants of a node, including itself that lie -- in a region indicated by another 'Fold'. -- -- @ -- 'toListOf' l ≡ 'universeOnOf' l 'ignored' -- @ universeOnOf :: Getting [a] s a -> Getting [a] a a -> s -> [a] universeOnOf b = foldMapOf b . universeOf {-# INLINE universeOnOf #-} -- | Fold over all transitive descendants of a 'Plated' container, including itself. cosmos :: Plated a => Fold a a cosmos = cosmosOf plate {-# INLINE cosmos #-} -- | Given a 'Fold' that knows how to locate immediate children, fold all of the transitive descendants of a node, including itself. -- -- @ -- 'cosmosOf' :: 'Fold' a a -> 'Fold' a a -- @ cosmosOf :: (Applicative f, Contravariant f) => LensLike' f a a -> LensLike' f a a cosmosOf d f s = f s *> d (cosmosOf d f) s {-# INLINE cosmosOf #-} -- | Given a 'Fold' that knows how to find 'Plated' parts of a container fold them and all of their descendants, recursively. -- -- @ -- 'cosmosOn' :: 'Plated' a => 'Fold' s a -> 'Fold' s a -- @ cosmosOn :: (Applicative f, Contravariant f, Plated a) => LensLike' f s a -> LensLike' f s a cosmosOn d = cosmosOnOf d plate {-# INLINE cosmosOn #-} -- | Given a 'Fold' that knows how to locate immediate children, fold all of the transitive descendants of a node, including itself that lie -- in a region indicated by another 'Fold'. -- -- @ -- 'cosmosOnOf' :: 'Fold' s a -> 'Fold' a a -> 'Fold' s a -- @ cosmosOnOf :: (Applicative f, Contravariant f) => LensLike' f s a -> LensLike' f a a -> LensLike' f s a cosmosOnOf d p = d . cosmosOf p {-# INLINE cosmosOnOf #-} ------------------------------------------------------------------------------- -- Transformation ------------------------------------------------------------------------------- -- | Transform every element in the tree, in a bottom-up manner. -- -- For example, replacing negative literals with literals: -- -- @ -- negLits = 'transform' $ \\x -> case x of -- Neg (Lit i) -> Lit ('negate' i) -- _ -> x -- @ transform :: Plated a => (a -> a) -> a -> a transform = transformOf plate {-# INLINE transform #-} -- | Transform every element in the tree in a bottom-up manner over a region indicated by a 'Setter'. -- -- @ -- 'transformOn' :: 'Plated' a => 'Traversal'' s a -> (a -> a) -> s -> s -- 'transformOn' :: 'Plated' a => 'Setter'' s a -> (a -> a) -> s -> s -- @ transformOn :: Plated a => ASetter s t a a -> (a -> a) -> s -> t transformOn b = over b . transform {-# INLINE transformOn #-} -- | Transform every element by recursively applying a given 'Setter' in a bottom-up manner. -- -- @ -- 'transformOf' :: 'Traversal'' a a -> (a -> a) -> a -> a -- 'transformOf' :: 'Setter'' a a -> (a -> a) -> a -> a -- @ transformOf :: ASetter a b a b -> (b -> b) -> a -> b transformOf l f = go where go = f . over l go {-# INLINE transformOf #-} -- | Transform every element in a region indicated by a 'Setter' by recursively applying another 'Setter' -- in a bottom-up manner. -- -- @ -- 'transformOnOf' :: 'Setter'' s a -> 'Traversal'' a a -> (a -> a) -> s -> s -- 'transformOnOf' :: 'Setter'' s a -> 'Setter'' a a -> (a -> a) -> s -> s -- @ transformOnOf :: ASetter s t a b -> ASetter a b a b -> (b -> b) -> s -> t transformOnOf b l = over b . transformOf l {-# INLINE transformOnOf #-} -- | Transform every element in the tree, in a bottom-up manner, monadically. transformM :: (Monad m, Plated a) => (a -> m a) -> a -> m a transformM = transformMOf plate {-# INLINE transformM #-} -- | Transform every element in the tree in a region indicated by a supplied 'Traversal', in a bottom-up manner, monadically. -- -- @ -- 'transformMOn' :: ('Monad' m, 'Plated' a) => 'Traversal'' s a -> (a -> m a) -> s -> m s -- @ transformMOn :: (Monad m, Plated a) => LensLike (WrappedMonad m) s t a a -> (a -> m a) -> s -> m t transformMOn b = mapMOf b . transformM {-# INLINE transformMOn #-} -- | Transform every element in a tree using a user supplied 'Traversal' in a bottom-up manner with a monadic effect. -- -- @ -- 'transformMOf' :: 'Monad' m => 'Traversal'' a a -> (a -> m a) -> a -> m a -- @ transformMOf :: Monad m => LensLike (WrappedMonad m) a b a b -> (b -> m b) -> a -> m b transformMOf l f = go where go t = mapMOf l go t >>= f {-# INLINE transformMOf #-} -- | Transform every element in a tree that lies in a region indicated by a supplied 'Traversal', walking with a user supplied 'Traversal' in -- a bottom-up manner with a monadic effect. -- -- @ -- 'transformMOnOf' :: 'Monad' m => 'Traversal'' s a -> 'Traversal'' a a -> (a -> m a) -> s -> m s -- @ transformMOnOf :: Monad m => LensLike (WrappedMonad m) s t a b -> LensLike (WrappedMonad m) a b a b -> (b -> m b) -> s -> m t transformMOnOf b l = mapMOf b . transformMOf l {-# INLINE transformMOnOf #-} ------------------------------------------------------------------------------- -- Holes and Contexts ------------------------------------------------------------------------------- -- | Return a list of all of the editable contexts for every location in the structure, recursively. -- -- @ -- propUniverse x = 'universe' x '==' 'map' 'Control.Comonad.Store.Class.pos' ('contexts' x) -- propId x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'contexts' x] -- @ -- -- @ -- 'contexts' ≡ 'contextsOf' 'plate' -- @ contexts :: Plated a => a -> [Context a a a] contexts = contextsOf plate {-# INLINE contexts #-} -- | Return a list of all of the editable contexts for every location in the structure, recursively, using a user-specified 'Traversal' to walk each layer. -- -- @ -- propUniverse l x = 'universeOf' l x '==' 'map' 'Control.Comonad.Store.Class.pos' ('contextsOf' l x) -- propId l x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'contextsOf' l x] -- @ -- -- @ -- 'contextsOf' :: 'Traversal'' a a -> a -> ['Context' a a a] -- @ contextsOf :: ATraversal' a a -> a -> [Context a a a] contextsOf l x = sell x : f (map context (holesOf l x)) where f xs = do Context ctx child <- xs Context cont y <- contextsOf l child return $ Context (ctx . cont) y {-# INLINE contextsOf #-} -- | Return a list of all of the editable contexts for every location in the structure in an areas indicated by a user supplied 'Traversal', recursively using 'plate'. -- -- @ -- 'contextsOn' b ≡ 'contextsOnOf' b 'plate' -- @ -- -- @ -- 'contextsOn' :: 'Plated' a => 'Traversal'' s a -> s -> ['Context' a a s] -- @ contextsOn :: Plated a => ATraversal s t a a -> s -> [Context a a t] contextsOn b = contextsOnOf b plate {-# INLINE contextsOn #-} -- | Return a list of all of the editable contexts for every location in the structure in an areas indicated by a user supplied 'Traversal', recursively using -- another user-supplied 'Traversal' to walk each layer. -- -- @ -- 'contextsOnOf' :: 'Traversal'' s a -> 'Traversal'' a a -> s -> ['Context' a a s] -- @ contextsOnOf :: ATraversal s t a a -> ATraversal' a a -> s -> [Context a a t] contextsOnOf b l = f . map context . holesOf b where f xs = do Context ctx child <- xs Context cont y <- contextsOf l child return $ Context (ctx . cont) y {-# INLINE contextsOnOf #-} -- | The one-level version of 'context'. This extracts a list of the immediate children as editable contexts. -- -- Given a context you can use 'Control.Comonad.Store.Class.pos' to see the values, 'Control.Comonad.Store.Class.peek' at what the structure would be like with an edited result, or simply 'Control.Lens.Internal.Context.extract' the original structure. -- -- @ -- propChildren x = 'children' l x '==' 'map' 'Control.Comonad.Store.Class.pos' ('holes' l x) -- propId x = 'all' ('==' x) ['Control.Lens.Internal.Context.extract' w | w <- 'holes' l x] -- @ -- -- @ -- 'holes' = 'holesOf' 'plate' -- @ holes :: Plated a => a -> [Pretext (->) a a a] holes = holesOf plate {-# INLINE holes #-} -- | An alias for 'holesOf', provided for consistency with the other combinators. -- -- @ -- 'holesOn' ≡ 'holesOf' -- @ -- -- @ -- 'holesOn' :: 'Iso'' s a -> s -> ['Pretext' (->) a a s] -- 'holesOn' :: 'Lens'' s a -> s -> ['Pretext' (->) a a s] -- 'holesOn' :: 'Traversal'' s a -> s -> ['Pretext' (->) a a s] -- 'holesOn' :: 'IndexedLens'' i s a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- 'holesOn' :: 'IndexedTraversal'' i s a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- @ holesOn :: Conjoined p => Over p (Bazaar p a a) s t a a -> s -> [Pretext p a a t] holesOn = holesOf {-# INLINE holesOn #-} -- | Extract one level of 'holes' from a container in a region specified by one 'Traversal', using another. -- -- @ -- 'holesOnOf' b l ≡ 'holesOf' (b '.' l) -- @ -- -- @ -- 'holesOnOf' :: 'Iso'' s a -> 'Iso'' a a -> s -> ['Pretext' (->) a a s] -- 'holesOnOf' :: 'Lens'' s a -> 'Lens'' a a -> s -> ['Pretext' (->) a a s] -- 'holesOnOf' :: 'Traversal'' s a -> 'Traversal'' a a -> s -> ['Pretext' (->) a a s] -- 'holesOnOf' :: 'Lens'' s a -> 'IndexedLens'' i a a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- 'holesOnOf' :: 'Traversal'' s a -> 'IndexedTraversal'' i a a -> s -> ['Pretext' ('Control.Lens.Internal.Indexed.Indexed' i) a a s] -- @ holesOnOf :: Conjoined p => LensLike (Bazaar p r r) s t a b -> Over p (Bazaar p r r) a b r r -> s -> [Pretext p r r t] holesOnOf b l = holesOf (b . l) {-# INLINE holesOnOf #-} ------------------------------------------------------------------------------- -- Paramorphisms ------------------------------------------------------------------------------- -- | Perform a fold-like computation on each value, technically a paramorphism. -- -- @ -- 'paraOf' :: 'Fold' a a -> (a -> [r] -> r) -> a -> r -- @ paraOf :: Getting (Endo [a]) a a -> (a -> [r] -> r) -> a -> r paraOf l f = go where go a = f a (go <$> toListOf l a) {-# INLINE paraOf #-} -- | Perform a fold-like computation on each value, technically a paramorphism. -- -- @ -- 'para' ≡ 'paraOf' 'plate' -- @ para :: Plated a => (a -> [r] -> r) -> a -> r para = paraOf plate {-# INLINE para #-} ------------------------------------------------------------------------------- -- Compos ------------------------------------------------------------------------------- -- $compos -- -- Provided for compatibility with Björn Bringert's @compos@ library. -- -- Note: Other operations from compos that were inherited by @uniplate@ are /not/ included -- to avoid having even more redundant names for the same operators. For comparison: -- -- @ -- 'composOpMonoid' ≡ 'foldMapOf' 'plate' -- 'composOpMPlus' f ≡ 'msumOf' ('plate' '.' 'to' f) -- 'composOp' ≡ 'descend' ≡ 'over' 'plate' -- 'composOpM' ≡ 'descendM' ≡ 'mapMOf' 'plate' -- 'composOpM_' ≡ 'descendM_' ≡ 'mapMOf_' 'plate' -- @ -- | Fold the immediate children of a 'Plated' container. -- -- @ -- 'composOpFold' z c f = 'foldrOf' 'plate' (c '.' f) z -- @ composOpFold :: Plated a => b -> (b -> b -> b) -> (a -> b) -> a -> b composOpFold z c f = foldrOf plate (c . f) z {-# INLINE composOpFold #-} ------------------------------------------------------------------------------- -- Parts ------------------------------------------------------------------------------- -- | The original @uniplate@ combinator, implemented in terms of 'Plated' as a 'Lens'. -- -- @ -- 'parts' ≡ 'partsOf' 'plate' -- @ -- -- The resulting 'Lens' is safer to use as it ignores 'over-application' and deals gracefully with under-application, -- but it is only a proper 'Lens' if you don't change the list 'length'! parts :: Plated a => Lens' a [a] parts = partsOf plate {-# INLINE parts #-} ------------------------------------------------------------------------------- -- Generics ------------------------------------------------------------------------------- -- | Implement 'plate' operation for a type using its 'Generic' instance. gplate :: (Generic a, GPlated a (Rep a)) => Traversal' a a gplate f x = GHC.Generics.to <$> gplate' f (GHC.Generics.from x) {-# INLINE gplate #-} class GPlated a g where gplate' :: Traversal' (g p) a instance GPlated a f => GPlated a (M1 i c f) where gplate' f (M1 x) = M1 <$> gplate' f x {-# INLINE gplate' #-} instance (GPlated a f, GPlated a g) => GPlated a (f :+: g) where gplate' f (L1 x) = L1 <$> gplate' f x gplate' f (R1 x) = R1 <$> gplate' f x {-# INLINE gplate' #-} instance (GPlated a f, GPlated a g) => GPlated a (f :*: g) where gplate' f (x :*: y) = (:*:) <$> gplate' f x <*> gplate' f y {-# INLINE gplate' #-} instance OVERLAPPING_PRAGMA GPlated a (K1 i a) where gplate' f (K1 x) = K1 <$> f x {-# INLINE gplate' #-} instance GPlated a (K1 i b) where gplate' _ = pure {-# INLINE gplate' #-} instance GPlated a U1 where gplate' _ = pure {-# INLINE gplate' #-} instance GPlated a V1 where gplate' _ v = v `seq` error "GPlated/V1" {-# INLINE gplate' #-} #if MIN_VERSION_base(4,9,0) instance GPlated a (URec b) where gplate' _ = pure {-# INLINE gplate' #-} #endif -- | Implement 'plate' operation for a type using its 'Generic1' instance. gplate1 :: (Generic1 f, GPlated1 f (Rep1 f)) => Traversal' (f a) (f a) gplate1 f x = GHC.Generics.to1 <$> gplate1' f (GHC.Generics.from1 x) {-# INLINE gplate1 #-} class GPlated1 f g where gplate1' :: Traversal' (g a) (f a) -- | recursive match instance GPlated1 f g => GPlated1 f (M1 i c g) where gplate1' f (M1 x) = M1 <$> gplate1' f x {-# INLINE gplate1' #-} -- | recursive match instance (GPlated1 f g, GPlated1 f h) => GPlated1 f (g :+: h) where gplate1' f (L1 x) = L1 <$> gplate1' f x gplate1' f (R1 x) = R1 <$> gplate1' f x {-# INLINE gplate1' #-} -- | recursive match instance (GPlated1 f g, GPlated1 f h) => GPlated1 f (g :*: h) where gplate1' f (x :*: y) = (:*:) <$> gplate1' f x <*> gplate1' f y {-# INLINE gplate1' #-} -- | ignored instance GPlated1 f (K1 i a) where gplate1' _ = pure {-# INLINE gplate1' #-} -- | ignored instance GPlated1 f Par1 where gplate1' _ = pure {-# INLINE gplate1' #-} -- | ignored instance GPlated1 f U1 where gplate1' _ = pure {-# INLINE gplate1' #-} -- | ignored instance GPlated1 f V1 where gplate1' _ = pure {-# INLINE gplate1' #-} -- | match instance OVERLAPPING_PRAGMA GPlated1 f (Rec1 f) where gplate1' f (Rec1 x) = Rec1 <$> f x {-# INLINE gplate1' #-} -- | ignored instance GPlated1 f (Rec1 g) where gplate1' _ = pure {-# INLINE gplate1' #-} -- | recursive match under outer 'Traversable' instance instance (Traversable t, GPlated1 f g) => GPlated1 f (t :.: g) where gplate1' f (Comp1 x) = Comp1 <$> traverse (gplate1' f) x {-# INLINE gplate1' #-} #if MIN_VERSION_base(4,9,0) -- | ignored instance GPlated1 f (URec a) where gplate1' _ = pure {-# INLINE gplate1' #-} #endif
ddssff/lens
src/Control/Lens/Plated.hs
bsd-3-clause
29,478
0
13
5,737
4,891
2,738
2,153
273
1
{-# LANGUAGE TypeFamilies #-} -- | -- Module : Simulation.Aivika.Lattice.Event -- Copyright : Copyright (c) 2016-2017, David Sorokin <david.sorokin@gmail.com> -- License : BSD3 -- Maintainer : David Sorokin <david.sorokin@gmail.com> -- Stability : experimental -- Tested with: GHC 7.10.3 -- -- The module defines an event queue, where 'LIO' is an instance of 'EventQueueing'. -- module Simulation.Aivika.Lattice.Event () where import Simulation.Aivika.Trans import Simulation.Aivika.Lattice.Internal.Event import Simulation.Aivika.Lattice.Internal.LIO
dsorokin/aivika-lattice
Simulation/Aivika/Lattice/Event.hs
bsd-3-clause
564
0
4
76
44
35
9
5
0
{- - Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved. - - This file is part of Hacq. - Hacq is distributed under the 3-clause BSD license. - See the LICENSE file for more details. -} {-# LANGUAGE FlexibleContexts #-} import Control.Monad (replicateM) import qualified Data.ByteString.Lazy as ByteString import qualified System.IO as IO import Control.Monad.Quantum.Class import Control.Monad.Quantum.Counter import Control.Monad.Quantum.CircuitBuilder import Data.Quantum.Circuit (Wire, Gate, IsCircuit, Circuit) import Data.Quantum.Circuit.QC (runQCBuilder) import Data.Quantum.Cost.TotalGates (showTotalGates) import Data.Quantum.Cost.Width (showWidth) main :: IO () main = do putStrLn "Multiply controlled NOT" let builder :: MonadQuantum w m => m () builder = do ctrls <- replicateM 10 newWire targ <- newWire controls (map bit ctrls) $ compressCtrls 1 $ do applyX targ applyH targ applyX targ -- Compute the cost of the circuit, and name the result "cost". let (width, totalGates) = generateCost builder () -- Output the cost. putStr "\n=== cost ===\n\n" putStr $ showWidth width putStr $ showTotalGates totalGates -- Generate the circuit, and name the result "circuit". let circuit :: IsCircuit Gate Wire c => c circuit = buildCircuit builder -- Output the circuit with full information (including which part is counted as parallelized). putStr "\n=== circuit ===\n\n" print (circuit :: Circuit Gate Wire) -- Output the circuit in the QC format. putStr "\n=== circuit (QC format) ===\n\n" ByteString.putStr $ runQCBuilder IO.nativeNewline circuit
ti1024/hacq
examples/controls.hs
bsd-3-clause
1,727
0
16
379
345
179
166
32
1
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Monad.Trans (liftIO) import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.Encoding as E import Snap.Core import Snap.Http.Server import Snugio.Core -- Create a new type of resource, for now, this is a blog post data Post = Post { title :: String , content :: String } deriving (Show) -- Make it a resource instance Resource Post where serviceAvailable _ = True knownMethods _ = ["GET", "POST", "DELETE"] resourceHandler _ = writeText "Welcome to Snugio" -- Start post = Post "Welcome to the webmachine" "Llorum Ipsum..." serve :: Config Snap a -> IO () serve config = httpServe config $ route [ ("/", resourceHandler post) ] main :: IO () main = serve defaultConfig
hdgarrood/snugio
examples/SimpleAPI.hs
bsd-3-clause
865
0
9
231
205
117
88
22
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE TupleSections #-} module HSync.Server.Handler.Realm where import Control.Lens hiding (children) import HSync.Server.Import import HSync.Server.Handler.ManualUpload(webCreateDir, webStoreFile) import HSync.Server.Handler.AcidUtils(queryRealmName) import qualified Data.Bimap as BM import qualified Data.Map as M import qualified Data.List.NonEmpty as NE import qualified Data.Text as T -------------------------------------------------------------------------------- -- TODO: improve this thing getViewRealmR :: RealmId -> Path -> Handler Html getViewRealmR ri p = do mr <- queryAcid $ Access ri p case mr of Nothing -> do setMessage "No such Realm or Path" notFound Just node -> getViewRealmR' ri p node getViewRealmR' :: RealmId -> Path -> RealmTree -> Handler Html getViewRealmR' ri p node = do rn <- queryRealmName ri allRenders <- mapM (\(i,v) -> (i,v,) <$> getViewNodeVersion ri p node v) $ NE.zip (NE.fromList [1..]) allVersions jumbotronLayout $(widgetFile "viewNodeData") $(widgetFile "nodeVersions") where allVersions@(latestVersion NE.:| _) = node^.nodeData.versions numVersions = NE.length allVersions fk = latestVersion^.fileKind isOne i = i == 1 parentPath = let ps = map (^.unFileName) $ (parentOf p)^.pathParts in "/" <> T.intercalate "/" ps -- | get a specific version with the given last mod. time getViewRealmVersionR :: RealmId -> DateTime -> Path -> Handler Html getViewRealmVersionR ri dt p = undefined withPrevAndNext :: NE.NonEmpty a -> NE.NonEmpty (Maybe a, a, Maybe a) withPrevAndNext xs = NE.fromList $ zip3 prevs xs' nexts where xs' = NE.toList xs prevs = Nothing : map Just xs' nexts = map Just (NE.tail xs) ++ [Nothing] getViewNodeVersion :: RealmId -> Path -> RealmTree -> FileVersion ClientId -> Handler Widget getViewNodeVersion ri p@(Path ps) node v = do lastModifiedWidget <- getLastModifiedWidget v case v^.fileKind of NonExistent -> return $(widgetFile "nonExistent") Directory -> do showAddWidgets <- (&& isLatest) <$> hasRights [Write] Nothing ri p createDirWidget <- webCreateDir ri p storeFileWidget <- webStoreFile ri p return $(widgetFile "viewDirectory") File sig -> return $(widgetFile "viewFile") where chs = fmap (^.unOrdByName) . toList $ node^.children pathOf c = Path $ ps <> [c^.name] fileKindOf c = c^.nodeData.headVersionLens.fileKind isNonExistent = not . exists . fileKindOf isLatest = node^.nodeData.headVersionLens == v getLastModifiedWidget :: FileVersion ClientId -> Handler Widget getLastModifiedWidget v = do user <- queryAcid . LookupUserById $ v^.lastModified.modUser let clientId = v^.lastModified.modClient modifiedTime = v^.lastModified.modificationTime userName' = user^._Just.userName.unUserName clientName = if clientId == webClientId then webClientName else webClientName -- TODO!!!! -- user^?_Just.clients.to (BM.lookup clientId) -- webClientName -- fromMaybe webClientName $ user^._Just.clients.at clientId return $(widgetFile "lastModified") fileIcon :: Html fileIcon = [shamlet|<span class="glyphicon glyphicon-file" aria-hidden="true">|] directoryIcon :: Html directoryIcon = [shamlet|<span class="glyphicon glyphicon-folder-open" aria-hidden="true">|] iconOf :: RealmTree -> Html iconOf node = case (^.fileKind) <$> lastExistingVersion (node^.nodeData) of Just (File _) -> fileIcon Just Directory -> directoryIcon _ -> fileIcon -- this case should not occur actually getListRealmsR :: Handler Html getListRealmsR = do (Realms m _) <- queryAcid QueryRealms let allRealms = M.assocs m defaultLayout $(widgetFile "listRealms")
noinia/hsync-server
src/HSync/Server/Handler/Realm.hs
bsd-3-clause
4,329
0
15
1,247
1,084
559
525
-1
-1
{-# LANGUAGE OverloadedStrings #-} module SimpleStore.CellSpec (main, spec) where import Test.Hspec import TestImport import Test.QuickCheck (arbitrary, Property) import Test.QuickCheck.Monadic (assert, monadicIO, pick, run) main :: IO () main = hspec spec spec :: Spec spec = do describe "serialization Test" $ do it "after initializing a value, closing and opening the value should match" $ do propInitThenRead propInitThenRead :: Property propInitThenRead = monadicIO $ do i <- pick arbitrary r <- run $ runRestartTest i assert $ (r) == i
plow-technologies/simple-cell
test/SimpleStore/CellSpec.hs
bsd-3-clause
566
0
12
104
159
85
74
18
1
{-# LANGUAGE TemplateHaskell #-} -- | Incremental yet pure version of the wallet -- -- This is intended to be one step between the spec and the implementation. -- We provide it here so that we can quickcheck this, and then base the -- real implementation on this incremental version. module Wallet.Incremental ( -- * State State(..) , stateUtxo , statePending , stateUtxoBalance , initState -- * Construction , mkWallet , walletEmpty -- * Implementation , applyBlock' ) where import Universum hiding (State) import Control.Lens.TH import qualified Data.Map as Map import Formatting (bprint, build, (%)) import qualified Formatting.Buildable import UTxO.Util (disjoint) import UTxO.DSL import Wallet.Abstract import qualified Wallet.Basic as Basic {------------------------------------------------------------------------------- State -------------------------------------------------------------------------------} -- Invariant: -- -- > stateUtxoBalance == balance stateUtxo data State h a = State { _stateBasic :: Basic.State h a , _stateUtxoBalance :: Value } makeLenses ''State stateUtxo :: Lens' (State h a) (Utxo h a) stateUtxo = stateBasic . Basic.stateUtxo statePending :: Lens' (State h a) (Pending h a) statePending = stateBasic . Basic.statePending initState :: State h a initState = State { _stateBasic = Basic.initState , _stateUtxoBalance = 0 } {------------------------------------------------------------------------------- Construction -------------------------------------------------------------------------------} mkWallet :: (Hash h a, Buildable st) => Ours a -> Lens' st (State h a) -> WalletConstr h a st mkWallet ours l self st = (Basic.mkWallet ours (l . stateBasic) self st) { applyBlock = \b -> let utxoPlus = utxoRestrictToOurs ours (txOuts b) in self (st & l %~ applyBlock' (txIns b, utxoPlus)) , availableBalance = (st ^. l . stateUtxoBalance) - utxoBalance (utxoRestrictToInputs (txIns (pending this)) (utxo this)) , totalBalance = availableBalance this + utxoBalance (change this) } where this = self st walletEmpty :: (Hash h a, Buildable a) => Ours a -> Wallet h a walletEmpty ours = fix (mkWallet ours identity) initState {------------------------------------------------------------------------------- Implementation -------------------------------------------------------------------------------} applyBlock' :: Hash h a => (Set (Input h a), Utxo h a) -> State h a -> State h a applyBlock' (ins, outs) State{..} = State{ _stateBasic = Basic.State { _statePending = pending' , _stateUtxo = utxo' } , _stateUtxoBalance = balance' } where pending' = Map.filter (\t -> disjoint (trIns t) ins) _statePending utxoNew = outs unionNew = _stateUtxo `utxoUnion` utxoNew utxoRem = utxoRestrictToInputs ins unionNew utxo' = utxoRemoveInputs ins unionNew balance' = _stateUtxoBalance + utxoBalance utxoNew - utxoBalance utxoRem Basic.State{..} = _stateBasic {------------------------------------------------------------------------------- Pretty-printing -------------------------------------------------------------------------------} instance (Hash h a, Buildable a) => Buildable (State h a) where build State{..} = bprint ( "State" % "{ basic: " % build % ", utxoBalance: " % build % "}" ) _stateBasic _stateUtxoBalance
input-output-hk/pos-haskell-prototype
wallet/test/unit/Wallet/Incremental.hs
mit
3,614
0
15
792
839
459
380
-1
-1