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 : XMonad.Prompt.Workspace -- Copyright : (C) 2007 Andrea Rossato, David Roundy -- License : BSD3 -- -- Maintainer : -- Stability : unstable -- Portability : unportable -- -- A workspace prompt for XMonad -- ----------------------------------------------------------------------------- module XMonad.Prompt.Workspace ( -- * Usage -- $usage workspacePrompt, -- * For developers Wor(Wor), ) where import XMonad hiding ( workspaces ) import XMonad.Prompt import XMonad.StackSet ( workspaces, tag ) import XMonad.Util.WorkspaceCompare ( getSortByIndex ) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Prompt -- > import XMonad.Prompt.Workspace -- -- > , ((modm .|. shiftMask, xK_m ), workspacePrompt def (windows . W.shift)) -- -- For detailed instruction on editing the key binding see -- "XMonad.Doc.Extending#Editing_key_bindings". data Wor = Wor String instance XPrompt Wor where showXPrompt (Wor x) = x workspacePrompt :: XPConfig -> (String -> X ()) -> X () workspacePrompt c job = do ws <- gets (workspaces . windowset) sort <- getSortByIndex let ts = map tag $ sort ws mkXPrompt (Wor "") c (mkComplFunFromList' ts) job
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Prompt/Workspace.hs
bsd-2-clause
1,571
0
11
472
222
130
92
17
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, MagicHash #-} {-# OPTIONS_HADDOCK hide #-} module PrimInt( ptake, mtake, ztake, itake ) where import Data.Maybe import GHC.Base {-@ assert ztake :: n: {v: Int# | 0 <= v} -> {v: Int | v = n } @-} ztake :: Int# -> Int ztake 0# = 0 ztake n# = 1 + ztake (n# -# 1#) {-@ assert itake :: n: {v: Int | 0 <= v} -> {v: Int | v = n } @-} itake :: Int -> Int itake 0 = 0 itake n = 1 + itake (n - 1) {-@ assert ptake :: n: {v: GHC.Prim.Int# | 0 <= v} -> {v:[a] | ((len v) >= n)} -> {v:[a] | (len(v) = n)} @-} ptake :: Int# -> [a] -> [a] ptake 0# _ = [] ptake n# (x:xs) = x : ptake (n# -# 1#) xs {-@ assert mtake :: n: {v: Int | 0 <= v} -> {v:[a]|((len v) >= n)} -> {v:[a] | (len(v) = n)} @-} mtake :: Int -> [a] -> [a] mtake 0 _ = [] mtake n (x:xs) = x : mtake (n - 1) xs
mightymoose/liquidhaskell
tests/pos/primInt0.hs
bsd-3-clause
858
0
8
247
241
133
108
19
1
{- expireGititCache - (C) 2009 John MacFarlane, licensed under the GPL This program is designed to be used in post-update hooks and other scripts. Usage: expireGititCache base-url [file..] Example: expireGititCache http://localhost:5001 page1.page foo/bar.hs "Front Page.page" will produce POST requests to http://localhost:5001/_expire/page1, http://localhost:5001/_expire/foo/bar.hs, and http://localhost:5001/_expire/Front Page. Return statuses: 0 -> the cached page was successfully expired (or was not cached in the first place) 1 -> fewer than two arguments were supplied 3 -> did not receive a 200 OK response from the request 5 -> could not parse the uri -} module Main where import Network.HTTP import System.Environment import Network.URI import System.FilePath import Control.Monad import System.IO import System.Exit main :: IO () main = do args <- getArgs (uriString : files) <- if length args < 2 then usageMessage >> return [""] else return args uri <- case parseURI uriString of Just u -> return u Nothing -> do hPutStrLn stderr ("Could not parse URI " ++ uriString) exitWith (ExitFailure 5) forM_ files (expireFile uri) usageMessage :: IO () usageMessage = do hPutStrLn stderr $ "Usage: expireGititCache base-url [file..]\n" ++ "Example: expireGititCache http://localhost:5001 page1.page foo/bar.hs" exitWith (ExitFailure 1) expireFile :: URI -> FilePath -> IO () expireFile uri file = do let path' = if takeExtension file == ".page" then dropExtension file else file let uri' = uri{uriPath = "/_expire/" ++ urlEncode path'} resResp <- simpleHTTP Request{rqURI = uri', rqMethod = POST, rqHeaders = [], rqBody = ""} case resResp of Left connErr -> error $ show connErr Right (Response (2,0,0) _ _ _) -> return () _ -> do hPutStrLn stderr ("Request for " ++ show uri' ++ " did not return success status") exitWith (ExitFailure 3)
bergmannf/gitit
expireGititCache.hs
gpl-2.0
2,083
0
16
516
433
215
218
38
4
{-# LANGUAGE TypeOperators, TypeFamilies #-} {-# OPTIONS -Wno-star-is-type #-} module X (type (X.*)) where type family (*) a b where { (*) a b = Either b a }
sdiehl/ghc
testsuite/tests/warnings/should_compile/StarBinder.hs
bsd-3-clause
160
4
5
31
36
29
7
-1
-1
{-# OPTIONS_GHC -O2 #-} -- Trac #1988: this one killed GHC 6.8.2 -- at least with -O2 module ShouldCompile where newtype CFTree = CFTree (String, [CFTree]) prCFTree :: CFTree -> String prCFTree (CFTree (_,trees)) = concatMap ps trees where ps t@(CFTree (_,[])) = prCFTree t
urbanslug/ghc
testsuite/tests/stranal/should_compile/T1988.hs
bsd-3-clause
284
0
12
55
88
51
37
6
1
{-# LANGUAGE KindSignatures #-} -- Trac #3095 module T3095 where class Bla (forall x . x :: *) where
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/parser/should_fail/T3095.hs
bsd-3-clause
102
1
8
20
28
16
12
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module ShouldCompile where f (x :: Int) = x + 1
GaloisInc/halvm-ghc
testsuite/tests/parser/should_compile/read022.hs
bsd-3-clause
86
0
7
16
24
14
10
3
1
{-# LANGUAGE TemplateHaskell #-} module UnitTest.CallbackParse.PreCheckoutCallback where import Data.Aeson (Value) import Data.Yaml.TH (decodeFile) import Test.Tasty as Tasty import Web.Facebook.Messenger import UnitTest.Internal ---------- -- READ -- ---------- preCheckoutCallbackVal :: Value preCheckoutCallbackVal = $$(decodeFile "test/json/callback/pre_checkout_callback.json") preCheckoutTest :: TestTree preCheckoutTest = parseTest "Pre Checkout Callback" preCheckoutCallbackVal $ standardMessaging (Just 1473208792799) Nothing contnt where contnt = CMPreCheckout $ PreCheckout "xyz" reqUserInfo $ Amount "USD" "2.70" reqUserInfo = RequestedUserInfo address (Just "Tao Jiang") Nothing Nothing address = Just $ TemplateAddress { taStreet1 = "600 Edgewater Blvd" , taStreet2 = Just "" , taCity = "Foster City" , taPostalCode = "94404" , taState = "CA" , taCountry = "US" }
Vlix/facebookmessenger
test/UnitTest/CallbackParse/PreCheckoutCallback.hs
mit
1,195
0
10
421
194
112
82
-1
-1
module RailFenceCipher (encode, decode) where import Data.List (sortBy) import Data.Function (on) encode :: Int -> [a] -> [a] encode n xs = concat [[a | (a, b) <- zip xs c, b == i] | i <- [1..n]] where c = cycle $ [1..n] ++ [n-1,n-2..2] decode :: Int -> [a] -> [a] decode n xs = map snd $ sortBy (compare `on` fst) zippedL where zippedL = zip (encode n [0..length xs - 1]) xs
exercism/xhaskell
exercises/practice/rail-fence-cipher/.meta/examples/success-standard/src/RailFenceCipher.hs
mit
383
0
12
83
228
125
103
9
1
module Main where fib :: Integer -> Integer fib = fst . fibNthPair fibNextPair :: (Integer, Integer) -> (Integer, Integer) fibNextPair (x,y) = (y,x+y) fibNthPair :: Integer -> (Integer, Integer) fibNthPair 0 = (0,1) fibNthPair n = fibNextPair(fibNthPair(n-1))
henryaddison/7-lang-7-weeks
week7-haskell/1/fib_pair.hs
mit
276
0
9
54
120
69
51
8
1
import Control.Arrow ((***), (&&&)) import Data.List (sort, break) import Data.Tuple (swap) intervals :: [String] -> [(Int, Int)] intervals = sort . map parse where parse = (read *** read . tail) . break (=='-') merge :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] merge xs [] = reverse xs merge [] (y:ys) = merge [y] ys merge (x@(xl, xh):xs) (y@(yl, yh):ys) | xh <= yl = merge (y:x:xs) ys | xh < yh = merge ((xl, yh):xs) ys | otherwise = merge (x:xs) ys solve :: [String] -> (Int, Int) solve = (lowest &&& total) . merge [] . intervals where lowest = (+1) . snd . head total = sum . map f . (zip <*> tail) f = subtract 1 . uncurry (-) . swap . (snd *** fst) main :: IO () main = do input <- lines <$> readFile "../input.txt" print . solve $ input
mattvperry/AoC_2016
day20/haskell/day20.hs
mit
807
0
10
208
462
253
209
-1
-1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} ------------------------------------------------------------------------------- -- | -- Module : Yesod.Auth.HashDB -- Copyright : (c) Patrick Brisbin 2010 -- License : as-is -- -- Maintainer : [email protected] -- Stability : Stable -- Portability : Portable -- -- A yesod-auth AuthPlugin designed to look users up in Persist where -- their user id's and a salted SHA1 hash of their password is stored. -- -- Example usage: -- -- > -- import the function -- > import Auth.HashDB -- > -- > -- make sure you have an auth route -- > mkYesodData "MyApp" [$parseRoutes| -- > / RootR GET -- > /auth AuthR Auth getAuth -- > |] -- > -- > -- > -- make your app an instance of YesodAuth using this plugin -- > instance YesodAuth MyApp where -- > type AuthId MyApp = UserId -- > -- > loginDest _ = RootR -- > logoutDest _ = RootR -- > getAuthId = getAuthIdHashDB AuthR (Just . UniqueUser) -- > authPlugins = [authHashDB (Just . UniqueUser)] -- > -- > -- > -- include the migration function in site startup -- > withServer :: (Application -> IO a) -> IO a -- > withServer f = withConnectionPool $ \p -> do -- > runSqlPool (runMigration migrateUsers) p -- > let h = DevSite p -- -- Note that function which converts username to unique identifier must be same. -- -- Your app must be an instance of YesodPersist. and the username, -- salt and hashed-passwords should be added to the database. -- -- > echo -n 'MySaltMyPassword' | sha1sum -- -- can be used to get the hash from the commandline. -- ------------------------------------------------------------------------------- module Yesod.Auth.HashDB ( HashDBUser(..) , Unique (..) , setPassword -- * Authentification , validateUser , authHashDB , getAuthIdHashDB -- * Predefined data type , User , UserGeneric (..) , UserId , migrateUsers ) where import Yesod.Persist import Yesod.Handler import Yesod.Form import Yesod.Auth import Yesod.Widget (toWidget) import Text.Hamlet (hamlet) import Control.Applicative ((<$>), (<*>)) import Control.Monad (replicateM,liftM) import Control.Monad.IO.Class (MonadIO, liftIO) import qualified Data.ByteString.Lazy.Char8 as BS (pack) import Data.Digest.Pure.SHA (sha1, showDigest) import Data.Text (Text, pack, unpack, append) import Data.Maybe (fromMaybe) import System.Random (randomRIO) -- | Interface for data type which holds user info. It's just a -- collection of getters and setters class HashDBUser user where -- | Retrieve password hash from user data userPasswordHash :: user -> Maybe Text -- | Retrieve salt for password userPasswordSalt :: user -> Maybe Text -- | Deprecated for the better named setSaltAndPasswordHash setUserHashAndSalt :: Text -- ^ Salt -> Text -- ^ Password hash -> user -> user setUserHashAndSalt = setSaltAndPasswordHash -- | a callback for setPassword setSaltAndPasswordHash :: Text -- ^ Salt -> Text -- ^ Password hash -> user -> user setSaltAndPasswordHash = setUserHashAndSalt -- | Generate random salt. Length of 8 is chosen arbitrarily randomSalt :: MonadIO m => m Text randomSalt = pack `liftM` liftIO (replicateM 8 (randomRIO ('0','z'))) -- | Calculate salted hash using SHA1. saltedHash :: Text -- ^ Salt -> Text -- ^ Password -> Text saltedHash salt = pack . showDigest . sha1 . BS.pack . unpack . append salt -- | Set password for user. This function should be used for setting -- passwords. It generates random salt and calculates proper hashes. setPassword :: (MonadIO m, HashDBUser user) => Text -> user -> m user setPassword pwd u = do salt <- randomSalt return $ setSaltAndPasswordHash salt (saltedHash salt pwd) u ---------------------------------------------------------------- -- Authentification ---------------------------------------------------------------- -- | Given a user ID and password in plaintext, validate them against -- the database values. validateUser :: ( YesodPersist yesod , b ~ YesodPersistBackend yesod , b ~ PersistEntityBackend user , PersistStore b (GHandler sub yesod) , PersistUnique b (GHandler sub yesod) , PersistEntity user , HashDBUser user ) => Unique user b -- ^ User unique identifier -> Text -- ^ Password in plaint-text -> GHandler sub yesod Bool validateUser userID passwd = do -- Checks that hash and password match let validate u = do hash <- userPasswordHash u salt <- userPasswordSalt u return $ hash == saltedHash salt passwd -- Get user data user <- runDB $ getBy userID return $ fromMaybe False $ validate . entityVal =<< user login :: AuthRoute login = PluginR "hashdb" ["login"] -- | Handle the login form. First parameter is function which maps -- username (whatever it might be) to unique user ID. postLoginR :: ( YesodAuth y, YesodPersist y , b ~ YesodPersistBackend y , b ~ PersistEntityBackend user , HashDBUser user, PersistEntity user , PersistStore b (GHandler Auth y) , PersistUnique b (GHandler Auth y)) => (Text -> Maybe (Unique user b)) -> GHandler Auth y () postLoginR uniq = do (mu,mp) <- runInputPost $ (,) <$> iopt textField "username" <*> iopt textField "password" isValid <- fromMaybe (return False) (validateUser <$> (uniq =<< mu) <*> mp) if isValid then setCreds True $ Creds "hashdb" (fromMaybe "" mu) [] else do setMessage "Invalid username/password" toMaster <- getRouteToMaster redirect $ toMaster LoginR -- | A drop in for the getAuthId method of your YesodAuth instance which -- can be used if authHashDB is the only plugin in use. getAuthIdHashDB :: ( YesodAuth master, YesodPersist master , HashDBUser user, PersistEntity user , Key b user ~ AuthId master , b ~ YesodPersistBackend master , b ~ PersistEntityBackend user , PersistUnique b (GHandler sub master) , PersistStore b (GHandler sub master)) => (AuthRoute -> Route master) -- ^ your site's Auth Route -> (Text -> Maybe (Unique user b)) -- ^ gets user ID -> Creds master -- ^ the creds argument -> GHandler sub master (Maybe (AuthId master)) getAuthIdHashDB authR uniq creds = do muid <- maybeAuthId case muid of -- user already authenticated Just uid -> return $ Just uid Nothing -> do x <- case uniq (credsIdent creds) of Nothing -> return Nothing Just u -> runDB (getBy u) case x of -- user exists Just (Entity uid _) -> return $ Just uid Nothing -> do setMessage "User not found" redirect $ authR LoginR -- | Prompt for username and password, validate that against a database -- which holds the username and a hash of the password authHashDB :: ( YesodAuth m, YesodPersist m , HashDBUser user , PersistEntity user , b ~ YesodPersistBackend m , b ~ PersistEntityBackend user , PersistStore b (GHandler Auth m) , PersistUnique b (GHandler Auth m)) => (Text -> Maybe (Unique user b)) -> AuthPlugin m authHashDB uniq = AuthPlugin "hashdb" dispatch $ \tm -> toWidget [hamlet| $newline never <div id="header"> <h1>Login <div id="login"> <form method="post" action="@{tm login}"> <table> <tr> <th>Username: <td> <input id="x" name="username" autofocus="" required> <tr> <th>Password: <td> <input type="password" name="password" required> <tr> <td>&nbsp; <td> <input type="submit" value="Login"> <script> if (!("autofocus" in document.createElement("input"))) { document.getElementById("x").focus(); } |] where dispatch "POST" ["login"] = postLoginR uniq >>= sendResponse dispatch _ _ = notFound ---------------------------------------------------------------- -- Predefined datatype ---------------------------------------------------------------- -- | Generate data base instances for a valid user share [mkPersist sqlSettings, mkMigrate "migrateUsers"] [persistUpperCase| User username Text Eq password Text salt Text UniqueUser username |] instance HashDBUser (UserGeneric backend) where userPasswordHash = Just . userPassword userPasswordSalt = Just . userSalt setSaltAndPasswordHash s h u = u { userSalt = s , userPassword = h }
piyush-kurur/yesod
yesod-auth/Yesod/Auth/HashDB.hs
mit
9,790
0
18
3,092
1,582
860
722
132
4
module Prettify where import SimpleJSON data Doc = Empty | Char Char | Text String | Line | Concat Doc Doc | Union Doc Doc deriving (Show, Eq) empty :: Doc empty = Empty string :: String -> Doc string str = undefined text :: String -> Doc text "" = Empty text s = Text s double :: Double -> Doc double num = text (show num) char :: Char -> Doc char c = Char c line :: Doc line = Line (<>) :: Doc -> Doc -> Doc Empty <> y = y x <> Empty = x x <> y = x `Concat` y hcat :: [Doc] -> Doc hcat = fold (<>) fold :: (Doc -> Doc -> Doc) -> [Doc] -> Doc fold f = foldr f empty fsep :: [Doc] -> Doc fsep = fold (</>) (</>) :: Doc -> Doc -> Doc x </> y = x <> softline <> y softline :: Doc softline = group line group :: Doc -> Doc group x = flatten x `Union` x flatten :: Doc -> Doc flatten (x `Concat` y) = flatten x `Concat` flatten y flatten Line = Char ' ' flatten (x `Union` _) = flatten x flatten other = other compact :: Doc -> String compact x = transform [x] where transform [] = "" transform (d:ds) = case d of Empty -> transform ds Char c -> c : transform ds Text s -> s ++ transform ds Line -> '\n' : transform ds a `Concat` b -> transform (a:b:ds) _ `Union` b -> transform (b:ds) pretty :: Int -> Doc -> String pretty width x = best 0 [x] where best col (d:ds) = case d of Empty -> best col ds Char c -> c : best (col + 1) ds Text s -> s ++ best (col + length s) ds Line -> '\n' : best 0 ds a `Concat` b -> best col (a:b:ds) a `Union` b -> nicest col (best col (a:ds)) (best col (b:ds)) best _ _ = "" nicest col a b | (width - least) `fits` a = a | otherwise = b where least = min width col fits :: Int -> String -> Bool w `fits` _ | w < 0 = False w `fits` "" = True w `fits` ('\n':_) = True w `fits` (c:cs) = (w - 1) `fits` cs punctuate :: Doc -> [Doc] -> [Doc] punctuate p [] = [] punctuate p [d] = [d] punctuate p (d:ds) = (d <> p) : punctuate p ds
Bolt64/my_code
haskell/myprecious/Prettify.hs
mit
2,336
0
14
913
1,063
558
505
78
7
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UndecidableSuperClasses #-} module AI.Funn.CL.DSL.Tensor (TensorCL, MTensorCL, CTensor(..), dimsOf, splitIndex, indexFlat) where import Control.Monad import Control.Monad.Free import Data.Foldable import Data.List import Data.Monoid import Data.Proxy import Data.Traversable import GHC.TypeLits import qualified AI.Funn.CL.DSL.AST as AST import AI.Funn.CL.DSL.Array import AI.Funn.CL.DSL.Code import AI.Funn.Space data CTensor (m :: Mode) (ds :: [Nat]) = CTensor (DimDict ds) (Array m Double) deriving Show type TensorCL = CTensor R type MTensorCL = CTensor W data DimDict (ds :: [Nat]) where DimZero :: DimDict '[] DimSucc :: Expr Int -> DimDict ds -> DimDict (d ': ds) instance Show (DimDict ds) where showsPrec n DimZero = showString "DimZero" showsPrec n (DimSucc d ds) = showParen (n > 10) $ showString "DimSucc " . showsPrec 11 d . showString " " . showsPrec 11 ds declareDict :: AST.Name -> Int -> KnownListOf ds -> (DimDict ds, [AST.Decl]) declareDict name n KnownListNil = (DimZero, []) declareDict name n (KnownListCons xs) = (DimSucc d ds, darg ++ dsargs) where (ds, dsargs) = declareDict name (n+1) xs (d, darg) = declareArgument (name ++ "_" ++ show n) instance KnownList ds => Argument (DimDict ds) where declareArgument name = declareDict name 0 (knownList (Proxy @ ds)) instance (Argument (Array m Double), KnownList ds) => Argument (CTensor m ds) where declareArgument name = (CTensor dim arr, dim_args ++ arr_args) where (dim, dim_args) = declareArgument name (arr, arr_args) = declareArgument name instance Index (CTensor m ds) [Expr Int] Double where at = index dimsOf :: CTensor m ds -> [Expr Int] dimsOf (CTensor ds _) = go ds where go :: DimDict xs -> [Expr Int] go DimZero = [] go (DimSucc d ds) = d : go ds index :: CTensor m ds -> [Expr Int] -> Expr Double index (CTensor (DimSucc _ ds) arr) (i:is) = go ds arr is i where go :: DimDict xs -> Array m Double -> [Expr Int] -> Expr Int -> Expr Double go DimZero arr [] ix = at arr ix go (DimSucc d ds) arr (i:is) ix = go ds arr is (ix * d + i) indexFlat :: CTensor m ds -> Expr Int -> Expr Double indexFlat (CTensor _ arr) i = at arr i splitIndex :: [Expr Int] -> Expr Int -> CL [Expr Int] splitIndex ds i = reverse <$> go (reverse $ tail ds) i where go (d:ds) i = do a <- eval (i `mod'` d) i' <- eval (i `div'` d) (a:) <$> go ds i' go [] i = return [i]
nshepperd/funn
AI/Funn/CL/DSL/Tensor.hs
mit
3,016
0
12
721
1,121
594
527
69
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} module Data.FreeAgent.Types.Users where import qualified Data.ByteString as BS import Control.Applicative ((<$>), (<*>), empty) import Control.Lens import Data.Aeson import Data.Aeson.TH import Data.Data type Users = [ User ] data User = User { _created_at :: BS.ByteString -- 2011-07-28T11:25:11Z , _url :: BS.ByteString -- https://api.freeagent.com/v2/users/1 , _permission_level :: Double , _role :: BS.ByteString -- Director , _last_name :: BS.ByteString -- Team , _opening_mileage :: Double , _email :: BS.ByteString -- [email protected] , _updated_at :: BS.ByteString -- 2011-08-24T08:10:23Z , _first_name :: BS.ByteString -- Development } deriving (Show, Data, Typeable) instance FromJSON User where parseJSON (Object v) = User <$> v .: "created_at" <*> v .: "url" <*> v .: "permission_level" <*> v .: "role" <*> v .: "last_name" <*> v .: "opening_mileage" <*> v .: "email" <*> v .: "updated_at" <*> v .: "first_name" parseJSON _ = empty $(deriveToJSON tail ''User) $(makeLenses ''User)
perurbis/hfreeagent
src/Data/FreeAgent/Types/Users.hs
mit
1,454
0
23
510
296
173
123
36
0
module Feature.UpsertSpec where import Network.Wai (Application) import Network.HTTP.Types import Test.Hspec import Test.Hspec.Wai import Test.Hspec.Wai.JSON import Protolude hiding (get, put) import SpecHelper spec :: SpecWith ((), Application) spec = describe "UPSERT" $ do context "with POST" $ do context "when Prefer: resolution=merge-duplicates is specified" $ do it "INSERTs and UPDATEs rows on pk conflict" $ request methodPost "/tiobe_pls" [("Prefer", "return=representation"), ("Prefer", "resolution=merge-duplicates")] [json| [ { "name": "Javascript", "rank": 6 }, { "name": "Java", "rank": 2 }, { "name": "C", "rank": 1 } ]|] `shouldRespondWith` [json| [ { "name": "Javascript", "rank": 6 }, { "name": "Java", "rank": 2 }, { "name": "C", "rank": 1 } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=merge-duplicates", matchContentTypeJson] } it "INSERTs and UPDATEs row on composite pk conflict" $ request methodPost "/employees" [("Prefer", "return=representation"), ("Prefer", "resolution=merge-duplicates")] [json| [ { "first_name": "Frances M.", "last_name": "Roe", "salary": "30000" }, { "first_name": "Peter S.", "last_name": "Yang", "salary": 42000 } ]|] `shouldRespondWith` [json| [ { "first_name": "Frances M.", "last_name": "Roe", "salary": "$30,000.00", "company": "One-Up Realty", "occupation": "Author" }, { "first_name": "Peter S.", "last_name": "Yang", "salary": "$42,000.00", "company": null, "occupation": null } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=merge-duplicates", matchContentTypeJson] } it "succeeds when the payload has no elements" $ request methodPost "/articles" [("Prefer", "return=representation"), ("Prefer", "resolution=merge-duplicates")] [json|[]|] `shouldRespondWith` [json|[]|] { matchStatus = 201 , matchHeaders = [matchContentTypeJson] } it "INSERTs and UPDATEs rows on single unique key conflict" $ request methodPost "/single_unique?on_conflict=unique_key" [("Prefer", "return=representation"), ("Prefer", "resolution=merge-duplicates")] [json| [ { "unique_key": 1, "value": "B" }, { "unique_key": 2, "value": "C" } ]|] `shouldRespondWith` [json| [ { "unique_key": 1, "value": "B" }, { "unique_key": 2, "value": "C" } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=merge-duplicates", matchContentTypeJson] } it "INSERTs and UPDATEs rows on compound unique keys conflict" $ request methodPost "/compound_unique?on_conflict=key1,key2" [("Prefer", "return=representation"), ("Prefer", "resolution=merge-duplicates")] [json| [ { "key1": 1, "key2": 1, "value": "B" }, { "key1": 1, "key2": 2, "value": "C" } ]|] `shouldRespondWith` [json| [ { "key1": 1, "key2": 1, "value": "B" }, { "key1": 1, "key2": 2, "value": "C" } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=merge-duplicates", matchContentTypeJson] } context "when Prefer: resolution=ignore-duplicates is specified" $ do it "INSERTs and ignores rows on pk conflict" $ request methodPost "/tiobe_pls" [("Prefer", "return=representation"), ("Prefer", "resolution=ignore-duplicates")] [json|[ { "name": "PHP", "rank": 9 }, { "name": "Python", "rank": 10 } ]|] `shouldRespondWith` [json|[ { "name": "PHP", "rank": 9 } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=ignore-duplicates", matchContentTypeJson] } it "INSERTs and ignores rows on composite pk conflict" $ request methodPost "/employees" [("Prefer", "return=representation"), ("Prefer", "resolution=ignore-duplicates")] [json|[ { "first_name": "Daniel B.", "last_name": "Lyon", "salary": "72000", "company": null, "occupation": null }, { "first_name": "Sara M.", "last_name": "Torpey", "salary": 60000, "company": "Burstein-Applebee", "occupation": "Soil scientist" } ]|] `shouldRespondWith` [json|[ { "first_name": "Sara M.", "last_name": "Torpey", "salary": "$60,000.00", "company": "Burstein-Applebee", "occupation": "Soil scientist" } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=ignore-duplicates", matchContentTypeJson] } it "INSERTs and ignores rows on single unique key conflict" $ request methodPost "/single_unique?on_conflict=unique_key" [("Prefer", "return=representation"), ("Prefer", "resolution=ignore-duplicates")] [json| [ { "unique_key": 1, "value": "B" }, { "unique_key": 2, "value": "C" }, { "unique_key": 3, "value": "D" } ]|] `shouldRespondWith` [json| [ { "unique_key": 2, "value": "C" }, { "unique_key": 3, "value": "D" } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=ignore-duplicates"] } it "INSERTs and UPDATEs rows on compound unique keys conflict" $ request methodPost "/compound_unique?on_conflict=key1,key2" [("Prefer", "return=representation"), ("Prefer", "resolution=ignore-duplicates")] [json| [ { "key1": 1, "key2": 1, "value": "B" }, { "key1": 1, "key2": 2, "value": "C" }, { "key1": 1, "key2": 3, "value": "D" } ]|] `shouldRespondWith` [json| [ { "key1": 1, "key2": 2, "value": "C" }, { "key1": 1, "key2": 3, "value": "D" } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=ignore-duplicates"] } it "succeeds if the table has only PK cols and no other cols" $ do request methodPost "/only_pk" [("Prefer", "return=representation"), ("Prefer", "resolution=ignore-duplicates")] [json|[ { "id": 1 }, { "id": 2 }, { "id": 3} ]|] `shouldRespondWith` [json|[ { "id": 3} ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=ignore-duplicates", matchContentTypeJson] } request methodPost "/only_pk" [("Prefer", "return=representation"), ("Prefer", "resolution=merge-duplicates")] [json|[ { "id": 1 }, { "id": 2 }, { "id": 4} ]|] `shouldRespondWith` [json|[ { "id": 1 }, { "id": 2 }, { "id": 4} ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=merge-duplicates", matchContentTypeJson] } it "succeeds and ignores the Prefer: resolution header(no Preference-Applied present) if the table has no PK" $ request methodPost "/no_pk" [("Prefer", "return=representation"), ("Prefer", "resolution=merge-duplicates")] [json|[ { "a": "1", "b": "0" } ]|] `shouldRespondWith` [json|[ { "a": "1", "b": "0" } ]|] { matchStatus = 201 , matchHeaders = [matchContentTypeJson] } it "succeeds if not a single resource is created" $ do request methodPost "/tiobe_pls" [("Prefer", "return=representation"), ("Prefer", "resolution=ignore-duplicates")] [json|[ { "name": "Java", "rank": 1 } ]|] `shouldRespondWith` [json|[]|] { matchStatus = 201 , matchHeaders = [matchContentTypeJson] } request methodPost "/tiobe_pls" [("Prefer", "return=representation"), ("Prefer", "resolution=ignore-duplicates")] [json|[ { "name": "Java", "rank": 1 }, { "name": "C", "rank": 2 } ]|] `shouldRespondWith` [json|[]|] { matchStatus = 201 , matchHeaders = [matchContentTypeJson] } context "with PUT" $ do context "Restrictions" $ do it "fails if Range is specified" $ request methodPut "/tiobe_pls?name=eq.Javascript" [("Range", "0-5")] [json| [ { "name": "Javascript", "rank": 1 } ]|] `shouldRespondWith` [json|{"message":"Range header and limit/offset querystring parameters are not allowed for PUT"}|] { matchStatus = 400 , matchHeaders = [matchContentTypeJson] } it "fails if limit is specified" $ put "/tiobe_pls?name=eq.Javascript&limit=1" [json| [ { "name": "Javascript", "rank": 1 } ]|] `shouldRespondWith` [json|{"message":"Range header and limit/offset querystring parameters are not allowed for PUT"}|] { matchStatus = 400 , matchHeaders = [matchContentTypeJson] } it "fails if offset is specified" $ put "/tiobe_pls?name=eq.Javascript&offset=1" [json| [ { "name": "Javascript", "rank": 1 } ]|] `shouldRespondWith` [json|{"message":"Range header and limit/offset querystring parameters are not allowed for PUT"}|] { matchStatus = 400 , matchHeaders = [matchContentTypeJson] } it "rejects every other filter than pk cols eq's" $ do put "/tiobe_pls?rank=eq.19" [json| [ { "name": "Go", "rank": 19 } ]|] `shouldRespondWith` [json|{"message":"Filters must include all and only primary key columns with 'eq' operators"}|] { matchStatus = 405 , matchHeaders = [matchContentTypeJson] } put "/tiobe_pls?id=not.eq.Java" [json| [ { "name": "Go", "rank": 19 } ]|] `shouldRespondWith` [json|{"message":"Filters must include all and only primary key columns with 'eq' operators"}|] { matchStatus = 405 , matchHeaders = [matchContentTypeJson] } put "/tiobe_pls?id=in.(Go)" [json| [ { "name": "Go", "rank": 19 } ]|] `shouldRespondWith` [json|{"message":"Filters must include all and only primary key columns with 'eq' operators"}|] { matchStatus = 405 , matchHeaders = [matchContentTypeJson] } put "/tiobe_pls?and=(id.eq.Go)" [json| [ { "name": "Go", "rank": 19 } ]|] `shouldRespondWith` [json|{"message":"Filters must include all and only primary key columns with 'eq' operators"}|] { matchStatus = 405 , matchHeaders = [matchContentTypeJson] } it "fails if not all composite key cols are specified as eq filters" $ do put "/employees?first_name=eq.Susan" [json| [ { "first_name": "Susan", "last_name": "Heidt", "salary": "48000", "company": "GEX", "occupation": "Railroad engineer" } ]|] `shouldRespondWith` [json|{"message":"Filters must include all and only primary key columns with 'eq' operators"}|] { matchStatus = 405 , matchHeaders = [matchContentTypeJson] } put "/employees?last_name=eq.Heidt" [json| [ { "first_name": "Susan", "last_name": "Heidt", "salary": "48000", "company": "GEX", "occupation": "Railroad engineer" } ]|] `shouldRespondWith` [json|{"message":"Filters must include all and only primary key columns with 'eq' operators"}|] { matchStatus = 405 , matchHeaders = [matchContentTypeJson] } it "fails if the uri primary key doesn't match the payload primary key" $ do put "/tiobe_pls?name=eq.MATLAB" [json| [ { "name": "Perl", "rank": 17 } ]|] `shouldRespondWith` [json|{"message":"Payload values do not match URL in primary key column(s)"}|] { matchStatus = 400 , matchHeaders = [matchContentTypeJson] } put "/employees?first_name=eq.Wendy&last_name=eq.Anderson" [json| [ { "first_name": "Susan", "last_name": "Heidt", "salary": "48000", "company": "GEX", "occupation": "Railroad engineer" } ]|] `shouldRespondWith` [json|{"message":"Payload values do not match URL in primary key column(s)"}|] { matchStatus = 400 , matchHeaders = [matchContentTypeJson] } it "fails if the table has no PK" $ put "/no_pk?a=eq.one&b=eq.two" [json| [ { "a": "one", "b": "two" } ]|] `shouldRespondWith` [json|{"message":"Filters must include all and only primary key columns with 'eq' operators"}|] { matchStatus = 405 , matchHeaders = [matchContentTypeJson] } context "Inserting row" $ do it "succeeds on table with single pk col" $ do -- assert that the next request will indeed be an insert get "/tiobe_pls?name=eq.Go" `shouldRespondWith` [json|[]|] request methodPut "/tiobe_pls?name=eq.Go" [("Prefer", "return=representation")] [json| [ { "name": "Go", "rank": 19 } ]|] `shouldRespondWith` [json| [ { "name": "Go", "rank": 19 } ]|] it "succeeds on table with composite pk" $ do -- assert that the next request will indeed be an insert get "/employees?first_name=eq.Susan&last_name=eq.Heidt" `shouldRespondWith` [json|[]|] request methodPut "/employees?first_name=eq.Susan&last_name=eq.Heidt" [("Prefer", "return=representation")] [json| [ { "first_name": "Susan", "last_name": "Heidt", "salary": "48000", "company": "GEX", "occupation": "Railroad engineer" } ]|] `shouldRespondWith` [json| [ { "first_name": "Susan", "last_name": "Heidt", "salary": "$48,000.00", "company": "GEX", "occupation": "Railroad engineer" } ]|] it "succeeds if the table has only PK cols and no other cols" $ do -- assert that the next request will indeed be an insert get "/only_pk?id=eq.10" `shouldRespondWith` [json|[]|] request methodPut "/only_pk?id=eq.10" [("Prefer", "return=representation")] [json|[ { "id": 10 } ]|] `shouldRespondWith` [json|[ { "id": 10 } ]|] context "Updating row" $ do it "succeeds on table with single pk col" $ do -- assert that the next request will indeed be an update get "/tiobe_pls?name=eq.Java" `shouldRespondWith` [json|[ { "name": "Java", "rank": 1 } ]|] request methodPut "/tiobe_pls?name=eq.Java" [("Prefer", "return=representation")] [json| [ { "name": "Java", "rank": 13 } ]|] `shouldRespondWith` [json| [ { "name": "Java", "rank": 13 } ]|] -- TODO: move this to SingularSpec? it "succeeds if the payload has more than one row, but it only puts the first element" $ do -- assert that the next request will indeed be an update get "/tiobe_pls?name=eq.Java" `shouldRespondWith` [json|[ { "name": "Java", "rank": 1 } ]|] request methodPut "/tiobe_pls?name=eq.Java" [("Prefer", "return=representation"), ("Accept", "application/vnd.pgrst.object+json")] [json| [ { "name": "Java", "rank": 19 }, { "name": "Swift", "rank": 12 } ] |] `shouldRespondWith` [json|{ "name": "Java", "rank": 19 }|] { matchHeaders = [matchContentTypeSingular] } it "succeeds on table with composite pk" $ do -- assert that the next request will indeed be an update get "/employees?first_name=eq.Frances M.&last_name=eq.Roe" `shouldRespondWith` [json| [ { "first_name": "Frances M.", "last_name": "Roe", "salary": "$24,000.00", "company": "One-Up Realty", "occupation": "Author" } ]|] request methodPut "/employees?first_name=eq.Frances M.&last_name=eq.Roe" [("Prefer", "return=representation")] [json| [ { "first_name": "Frances M.", "last_name": "Roe", "salary": "60000", "company": "Gamma Gas", "occupation": "Railroad engineer" } ]|] `shouldRespondWith` [json| [ { "first_name": "Frances M.", "last_name": "Roe", "salary": "$60,000.00", "company": "Gamma Gas", "occupation": "Railroad engineer" } ]|] it "succeeds if the table has only PK cols and no other cols" $ do -- assert that the next request will indeed be an update get "/only_pk?id=eq.1" `shouldRespondWith` [json|[ { "id": 1 } ]|] request methodPut "/only_pk?id=eq.1" [("Prefer", "return=representation")] [json|[ { "id": 1 } ]|] `shouldRespondWith` [json|[ { "id": 1 } ]|] -- TODO: move this to SingularSpec? it "works with return=representation and vnd.pgrst.object+json" $ request methodPut "/tiobe_pls?name=eq.Ruby" [("Prefer", "return=representation"), ("Accept", "application/vnd.pgrst.object+json")] [json| [ { "name": "Ruby", "rank": 11 } ]|] `shouldRespondWith` [json|{ "name": "Ruby", "rank": 11 }|] { matchHeaders = [matchContentTypeSingular] } context "with a camel case pk column" $ do it "works with POST and merge-duplicates" $ do request methodPost "/UnitTest" [("Prefer", "return=representation"), ("Prefer", "resolution=merge-duplicates")] [json|[ { "idUnitTest": 1, "nameUnitTest": "name of unittest 1" }, { "idUnitTest": 2, "nameUnitTest": "name of unittest 2" } ]|] `shouldRespondWith` [json|[ { "idUnitTest": 1, "nameUnitTest": "name of unittest 1" }, { "idUnitTest": 2, "nameUnitTest": "name of unittest 2" } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=merge-duplicates"] } it "works with POST and ignore-duplicates headers" $ do request methodPost "/UnitTest" [("Prefer", "return=representation"), ("Prefer", "resolution=ignore-duplicates")] [json|[ { "idUnitTest": 1, "nameUnitTest": "name of unittest 1" }, { "idUnitTest": 2, "nameUnitTest": "name of unittest 2" } ]|] `shouldRespondWith` [json|[ { "idUnitTest": 2, "nameUnitTest": "name of unittest 2" } ]|] { matchStatus = 201 , matchHeaders = ["Preference-Applied" <:> "resolution=ignore-duplicates"] } it "works with PUT" $ do put "/UnitTest?idUnitTest=eq.1" [json| [ { "idUnitTest": 1, "nameUnitTest": "unit test 1" } ]|] `shouldRespondWith` 204 get "/UnitTest?idUnitTest=eq.1" `shouldRespondWith` [json| [ { "idUnitTest": 1, "nameUnitTest": "unit test 1" } ]|]
steve-chavez/postgrest
test/Feature/UpsertSpec.hs
mit
19,376
0
20
5,668
2,422
1,498
924
-1
-1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.SVGFETurbulenceElement (pattern SVG_TURBULENCE_TYPE_UNKNOWN, pattern SVG_TURBULENCE_TYPE_FRACTALNOISE, pattern SVG_TURBULENCE_TYPE_TURBULENCE, pattern SVG_STITCHTYPE_UNKNOWN, pattern SVG_STITCHTYPE_STITCH, pattern SVG_STITCHTYPE_NOSTITCH, getBaseFrequencyX, getBaseFrequencyY, getNumOctaves, getSeed, getStitchTiles, getType, SVGFETurbulenceElement(..), gTypeSVGFETurbulenceElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums pattern SVG_TURBULENCE_TYPE_UNKNOWN = 0 pattern SVG_TURBULENCE_TYPE_FRACTALNOISE = 1 pattern SVG_TURBULENCE_TYPE_TURBULENCE = 2 pattern SVG_STITCHTYPE_UNKNOWN = 0 pattern SVG_STITCHTYPE_STITCH = 1 pattern SVG_STITCHTYPE_NOSTITCH = 2 -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFETurbulenceElement.baseFrequencyX Mozilla SVGFETurbulenceElement.baseFrequencyX documentation> getBaseFrequencyX :: (MonadDOM m) => SVGFETurbulenceElement -> m SVGAnimatedNumber getBaseFrequencyX self = liftDOM ((self ^. js "baseFrequencyX") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFETurbulenceElement.baseFrequencyY Mozilla SVGFETurbulenceElement.baseFrequencyY documentation> getBaseFrequencyY :: (MonadDOM m) => SVGFETurbulenceElement -> m SVGAnimatedNumber getBaseFrequencyY self = liftDOM ((self ^. js "baseFrequencyY") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFETurbulenceElement.numOctaves Mozilla SVGFETurbulenceElement.numOctaves documentation> getNumOctaves :: (MonadDOM m) => SVGFETurbulenceElement -> m SVGAnimatedInteger getNumOctaves self = liftDOM ((self ^. js "numOctaves") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFETurbulenceElement.seed Mozilla SVGFETurbulenceElement.seed documentation> getSeed :: (MonadDOM m) => SVGFETurbulenceElement -> m SVGAnimatedNumber getSeed self = liftDOM ((self ^. js "seed") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFETurbulenceElement.stitchTiles Mozilla SVGFETurbulenceElement.stitchTiles documentation> getStitchTiles :: (MonadDOM m) => SVGFETurbulenceElement -> m SVGAnimatedEnumeration getStitchTiles self = liftDOM ((self ^. js "stitchTiles") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFETurbulenceElement.type Mozilla SVGFETurbulenceElement.type documentation> getType :: (MonadDOM m) => SVGFETurbulenceElement -> m SVGAnimatedEnumeration getType self = liftDOM ((self ^. js "type") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/SVGFETurbulenceElement.hs
mit
3,548
0
10
456
688
406
282
52
1
{-# LANGUAGE RecordWildCards, PatternSynonyms, BangPatterns #-} module Genetic where import Data.Vector (Vector(..), fromList) import Data.List (foldl', genericLength, splitAt, sortBy) import Data.Ord (comparing) import System.Random import Control.Monad.Random (MonadRandom(), getRandomR, getRandomRs) import Data.Word (Word8(..)) import Player (Player(..), sortByDscRatio, newPlayer) import Board.Types (Board(..), Move(..), Value(..), Result(..)) import Crossover -- | Chromosome length -- \_______________/ -- | genIndividual :: MonadRandom m => Int -> m Player genIndividual len = do stream <- getRandomRs (0, 8) let chrom = take len stream return $ newPlayer chrom -- | Population size Chromosome length -- \_____________/ \_______________/ -- | / -- | / genIndividuals :: MonadRandom m => Int -> Int -> m [Player] genIndividuals = go [] where go :: MonadRandom m => [Player] -> Int -> Int -> m [Player] go !acc 0 _ = return acc go !acc size len = do res <- genIndividual len go (res : acc) (size - 1) len -- | mutates every player with δ chance, mutation β percent of the Chromosome -- no fitness adjusting -- -- δ = chance to mutate -- β = percent of the Chromosome to mutate -- -- δ β -- | | mutate :: MonadRandom m => Double -> Double -> [Player] -> m [Player] mutate = go [] where go :: MonadRandom m => [Player] -> Double -> Double -> [Player] -> m [Player] go !acc _ _ [] = return $ reverse acc go !acc delta beta (p:ps) = do v <- getRandomR (0.0, 1.0) p' <- mutateP p beta case delta >= v of True -> go (p':acc) delta beta ps False -> go (p :acc) delta beta ps -- -- β -- | mutateP :: MonadRandom m => Player -> Double -> m Player mutateP (Player l turns wins ties losses played games) = go ([], turns, wins, ties, losses, played, games) l where go :: MonadRandom m => ([Word8], Int, Int, Int, Int, Bool, Int) -> [Word8] -> Double -> m Player go (!acc, turns, wins, ties, losses, played, games) [] _ = return $ Player (reverse acc) turns wins ties losses played games go (!acc, turns, wins, ties, losses, played, games) (x:xs) beta = do v <- getRandomR (0.0, 1.0) c <- getRandomR (0, 8) case beta >= v of True -> go ((c:acc), turns, wins, ties, losses, played, games) xs beta False -> go ((x:acc), turns, wins, ties, losses, played, games) xs beta -- | fills up the player list with new individuals up to the population size -- -- Population size Chromosome length -- \___________/ \_______________/ -- \ | repopulate :: MonadRandom m => [Player] -> Int -> Int -> m [Player] repopulate players size chromlen = do let popsize = size - length players pop <- genIndividuals popsize chromlen let !npop = players ++ pop return $ npop -- | θ = percent to be removed by natural selection -- -- θ -- | naturalselection :: Double -> [Player] -> [Player] naturalselection tetha players = take best (sortByDscRatio players) where best = length players - round (tetha * genericLength players)
cirquit/genetic-tic-tac-toe
src/Genetic.hs
mit
3,844
0
17
1,448
1,110
602
508
52
5
module My.Serialize ( encodeDir , decodeDir , encodeEntry , encodeEntry0 , decodeEntry ) where import My.Data import My.Exception import My.Crypt import Control.Monad.Catch import Control.Monad import Control.Monad.Trans import Control.Applicative import Data.Char import Data.Word import Data.Conduit import Data.Binary hiding (encodeFile, decodeFile) import Data.Binary.Get import Data.Binary.Put import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import System.Fuse import Foreign.C.Types encodeEntry0 :: Entry -> Put encodeEntry0 = encodeEntry encodeEntry :: Entry -> Put encodeEntry Entry{..} = do putWord16le entryVer putByteString entryKey putByteString entryIV putByteString (T.encodeUtf8 entryName) putWord8 0 putByteString (T.encodeUtf8 entryId) putWord8 0 putWord64le (fromIntegral entrySize) putWord32le (fromIntegral entryMode) putWord64le (let CTime ctime = entryCTime in fromIntegral ctime) putWord64le (let CTime mtime = entryMTime in fromIntegral mtime) decodeEntry :: EntryVer -> Get Entry decodeEntry parentVer = case parentVer of 0 -> do ver <- getWord16le CipherOne emptyCipher <- chooseCipher ver let keySize = maxCipherKeySize emptyCipher ivSize = blockSize emptyCipher key <- getByteString keySize iv <- getByteString ivSize nameBytes <- getLazyByteStringNul let name = T.decodeUtf8With T.lenientDecode (BL.toStrict nameBytes) fileIdBytes <- getLazyByteStringNul let fileId = T.decodeUtf8With T.lenientDecode (BL.toStrict fileIdBytes) size <- return . fromIntegral =<< getWord64le mode <- return . fromIntegral =<< getWord32le ctime <- return . fromIntegral =<< getWord64le mtime <- return . fromIntegral =<< getWord64le return $ Entry ver key iv name fileId size mode ctime mtime encodeDir :: (MonadThrow m, MonadIO m) => Entry -> Conduit Entry m B.ByteString encodeDir entry = go where go = await >>= \case Nothing -> return () Just entry -> mapM_ yield (BL.toChunks . runPut $ encodeEntry entry) >> go decodeDir :: (MonadThrow m, MonadIO m) => Entry -> Conduit B.ByteString m Entry decodeDir entry = go decoder0 where decoder0 = runGetIncremental (decodeEntry (entryVer entry)) go decoder = do await >>= \case Just seg -> case pushChunk decoder seg of Fail _ _ _ -> throwM UnrecognizeFormatException Done remain _ entry -> do yield entry leftover remain go decoder0 next -> go next _ -> return ()
CindyLinz/GCryptDrive
src/My/Serialize.hs
mit
2,678
0
18
539
838
415
423
-1
-1
{-# LANGUAGE CPP, NondecreasingIndentation, TupleSections, LambdaCase #-} -- GHC frontend ( ghc/Main.hs ) adapted for GHCJS #undef GHCI #undef HAVE_INTERNAL_INTERPRETER {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-} ----------------------------------------------------------------------------- -- -- GHC Driver program -- -- (c) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module Compiler.Program where import qualified Compiler.GhcjsProgram as Ghcjs import qualified Compiler.GhcjsPlatform as Ghcjs import qualified Compiler.GhcjsHooks as Ghcjs import qualified Compiler.Info as Ghcjs import qualified Compiler.Settings as Ghcjs import qualified Compiler.Utils as Ghcjs import Data.IORef import Prelude -- The official GHC API import qualified GHC import GHC ( -- DynFlags(..), HscTarget(..), -- GhcMode(..), GhcLink(..), Ghc, GhcMonad(..), LoadHowMuch(..) ) import CmdLineParser -- Implementations of the various modes (--show-iface, mkdependHS. etc.) import LoadIface ( showIface ) import HscMain ( newHscEnv ) import DriverPipeline ( oneShot, compileFile ) import DriverMkDepend ( doMkDependHS ) #if defined(HAVE_INTERNAL_INTERPRETER) import GHCi.UI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings ) #endif -- Frontend plugins -- #if defined(HAVE_INTERNAL_INTERPRETER) import DynamicLoading ( loadFrontendPlugin ) import Plugins -- #else -- import DynamicLoading ( pluginError ) -- #endif import Module ( ModuleName ) -- Various other random stuff that we need import GHC.HandleEncoding import GHC.Platform import GHC.Platform.Host import Config import Constants import HscTypes import Packages ( pprPackages, pprPackagesSimple ) import DriverPhases import BasicTypes ( failed ) import DynFlags hiding (WarnReason(..)) import ErrUtils import FastString import Outputable import SysTools.BaseDir import SrcLoc import Util import Panic import UniqSupply import MonadUtils ( liftIO ) import SysTools.Settings -- Imports for --abi-hash import LoadIface ( loadUserInterface ) import Module ( mkModuleName ) import Finder ( findImportedModule, cannotFindModule ) import TcRnMonad ( initIfaceCheck ) import Binary ( openBinMem, put_) import BinFingerprint ( fingerprintBinMem ) -- Standard Haskell libraries import System.IO import System.Exit import System.FilePath import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.Except (throwE, runExceptT) import Data.Char import Data.List ( isPrefixOf, partition, intercalate ) import Data.Maybe ----------------------------------------------------------------------------- -- ToDo: -- time commands when run with -v -- user ways -- Win32 support: proper signal handling -- reading the package configuration file is too slow -- -K<size> ----------------------------------------------------------------------------- -- GHC's command-line interface main :: IO () main = do initGCStatistics -- See Note [-Bsymbolic and hooks] hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering configureHandleEncoding Ghcjs.ghcjsErrorHandler defaultFatalMessager defaultFlushOut $ do -- 1. extract the -B flag from the args (argv0, _booting, booting_stage1) <- Ghcjs.getWrappedArgs let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0 mbMinusB | null minusB_args = Nothing | otherwise = Just (drop 2 (last minusB_args)) argv1' = map (mkGeneralLocated "on the commandline") argv1 when (any (== "--run") argv1) (Ghcjs.runJsProgram mbMinusB argv1) (argv2, ghcjsSettings) <- Ghcjs.getGhcjsSettings argv1' -- fall back to native GHC if we're booting (we can't build Setup.hs with GHCJS yet) when (booting_stage1 && Ghcjs.gsBuildRunner ghcjsSettings) Ghcjs.bootstrapFallback -- 2. Parse the "mode" flags (--make, --interactive etc.) (mode, argv3, flagWarnings) <- parseModeFlags argv2 -- If all we want to do is something like showing the version number -- then do it now, before we start a GHC session etc. This makes -- getting basic information much more resilient. -- In particular, if we wait until later before giving the version -- number then bootstrapping gets confused, as it tries to find out -- what version of GHC it's using before package.conf exists, so -- starting the session fails. case mode of Left preStartupMode -> do case preStartupMode of ShowSupportedExtensions -> showSupportedExtensions mbMinusB ShowVersion -> Ghcjs.printVersion ShowNumVersion -> Ghcjs.printNumericVersion ShowNumGhcVersion -> putStrLn cProjectVersion ShowOptions isInteractive -> showOptions isInteractive Right postStartupMode -> do -- start our GHC session GHC.runGhc mbMinusB $ do dflags <- GHC.getSessionDynFlags case postStartupMode of Left preLoadMode -> liftIO $ do case preLoadMode of ShowInfo -> showInfo ghcjsSettings dflags ShowGhcUsage -> showGhcUsage dflags ShowGhciUsage -> showGhciUsage dflags PrintWithDynFlags f -> putStrLn (f ghcjsSettings dflags) Right postLoadMode -> main' postLoadMode dflags argv3 flagWarnings ghcjsSettings False main' :: PostLoadMode -> DynFlags -> [Located String] -> [Warn] -> Ghcjs.GhcjsSettings -> Bool -> Ghc () main' postLoadMode dflags0 args flagWarnings ghcjsSettings native = do -- set the default GhcMode, HscTarget and GhcLink. The HscTarget -- can be further adjusted on a module by module basis, using only -- the -fvia-C and -fasm flags. If the default HscTarget is not -- HscC or HscAsm, -fvia-C and -fasm have no effect. let dflt_target = hscTarget dflags0 (mode, lang, link) = case postLoadMode of DoInteractive -> (CompManager, HscInterpreted, LinkInMemory) DoEval _ -> (CompManager, HscInterpreted, LinkInMemory) DoMake -> (CompManager, dflt_target, LinkBinary) DoMkDependHS -> (MkDepend, dflt_target, LinkBinary) DoAbiHash -> (OneShot, dflt_target, LinkBinary) _ -> (OneShot, dflt_target, LinkBinary) let dflags1 = case lang of HscInterpreted -> let platform = targetPlatform dflags0 dflags0a = updateWays $ dflags0 { ways = interpWays } dflags0b = foldl gopt_set dflags0a $ concatMap (wayGeneralFlags platform) interpWays dflags0c = foldl gopt_unset dflags0b $ concatMap (wayUnsetGeneralFlags platform) interpWays in dflags0c _ -> dflags0 dflags1a = dflags1{ ghcMode = mode, hscTarget = lang, ghcLink = link, verbosity = case postLoadMode of DoEval _ -> 0 _other -> 1 } -- turn on -fimplicit-import-qualified for GHCi now, so that it -- can be overriden from the command-line -- XXX: this should really be in the interactive DynFlags, but -- we don't set that until later in interactiveUI -- We also set -fignore-optim-changes and -fignore-hpc-changes, -- which are program-level options. Again, this doesn't really -- feel like the right place to handle this, but we don't have -- a great story for the moment. dflags2 | DoInteractive <- postLoadMode = def_ghci_flags | DoEval _ <- postLoadMode = def_ghci_flags | otherwise = dflags1a where def_ghci_flags = dflags1 `gopt_set` Opt_ImplicitImportQualified `gopt_set` Opt_IgnoreOptimChanges `gopt_set` Opt_IgnoreHpcChanges -- The rest of the arguments are "dynamic" -- Leftover ones are presumably files (dflags3, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags2 args let dflags4 = case lang of HscInterpreted | not (gopt Opt_ExternalInterpreter dflags3) -> let platform = targetPlatform dflags3 dflags3a = updateWays $ dflags3 { ways = interpWays } dflags3b = foldl gopt_set dflags3a $ concatMap (wayGeneralFlags platform) interpWays dflags3c = foldl gopt_unset dflags3b $ concatMap (wayUnsetGeneralFlags platform) interpWays in dflags3c _ -> dflags3 GHC.prettyPrintGhcErrors dflags4 $ do let flagWarnings' = flagWarnings ++ dynamicFlagWarnings handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ handleFlagWarnings dflags4 flagWarnings' jsEnv <- liftIO Ghcjs.newGhcjsEnv -- make sure we clean up after ourselves Ghcjs.ghcjsCleanupHandler dflags4 jsEnv $ do liftIO $ showBanner postLoadMode dflags4 let -- To simplify the handling of filepaths, we normalise all filepaths right -- away - e.g., for win32 platforms, backslashes are converted -- into forward slashes. normal_fileish_paths = map (normalise . unLoc) fileish_args (srcs, js_objs, objs) = partition_args_js normal_fileish_paths [] [] -- add GHCJS configuration let baseDir = Ghcjs.getLibDir dflags4 dflags4b <- if native then return (Ghcjs.setNativePlatform jsEnv ghcjsSettings baseDir dflags4) else return $ Ghcjs.setGhcjsPlatform ghcjsSettings jsEnv js_objs baseDir $ updateWays $ addWay' (WayCustom "js") $ Ghcjs.setGhcjsSuffixes {- oneshot -} False dflags4 -- fixme value of oneshot? let dflags5 = dflags4b { ldInputs = map (FileOption "") objs ++ ldInputs dflags4b } -- we've finished manipulating the DynFlags, update the session _ <- GHC.setSessionDynFlags dflags5 dflags6 <- GHC.getSessionDynFlags hsc_env <- GHC.getSession liftIO (writeIORef (canGenerateDynamicToo dflags6) True) -- fixme is this still necessary for GHCJS? ---------------- Display configuration ----------- case verbosity dflags6 of v | v == 4 -> liftIO $ dumpPackagesSimple dflags6 | v >= 5 -> liftIO $ dumpPackages dflags6 | otherwise -> return () liftIO $ initUniqSupply (initialUnique dflags6) (uniqueIncrement dflags6) ---------------- Final sanity checking ----------- liftIO $ checkOptions ghcjsSettings postLoadMode dflags6 srcs objs (js_objs ++ Ghcjs.gsJsLibSrcs ghcjsSettings) ---------------- Do the business ----------- handleSourceError (\e -> do GHC.printException e liftIO $ exitWith (ExitFailure 1)) $ do case postLoadMode of ShowInterface f -> liftIO (doShowIface dflags6 f) DoMake -> doMake jsEnv ghcjsSettings native srcs DoMkDependHS -> doMkDependHS (map fst srcs) StopBefore p -> liftIO (Ghcjs.ghcjsOneShot jsEnv ghcjsSettings native hsc_env p srcs) DoInteractive -> ghciUI srcs Nothing DoEval exprs -> (ghciUI srcs $ Just $ reverse exprs) DoAbiHash -> abiHash (map fst srcs) ShowPackages -> liftIO $ showPackages dflags6 DoGenerateLib -> Ghcjs.generateLib ghcjsSettings DoPrintRts -> liftIO (Ghcjs.printRts dflags6) DoInstallExecutable -> liftIO (Ghcjs.installExecutable dflags6 ghcjsSettings normal_fileish_paths) DoPrintObj obj -> liftIO (Ghcjs.printObj obj) DoPrintDeps obj -> liftIO (Ghcjs.printDeps obj) DoBuildJsLibrary -> liftIO (Ghcjs.buildJsLibrary dflags6 (map fst srcs) js_objs objs) liftIO $ dumpFinalStats dflags6 return () ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc () #if !defined(HAVE_INTERNAL_INTERPRETER) ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use") #else ghciUI = interactiveUI defaultGhciSettings #endif -- ----------------------------------------------------------------------------- -- Splitting arguments into source files and object files. This is where we -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source -- file indicating the phase specified by the -x option in force, if any. partition_args_js :: [String] -> [(String, Maybe Phase)] -> [String] -> ([(String, Maybe Phase)], [String], [String]) partition_args_js args srcs objs = let (srcs', objs') = partition_args args srcs objs (js_objs, nonjs_objs) = partition Ghcjs.isJsFile objs' in (srcs', js_objs, nonjs_objs) partition_args :: [String] -> [(String, Maybe Phase)] -> [String] -> ([(String, Maybe Phase)], [String]) partition_args [] srcs objs = (reverse srcs, reverse objs) partition_args ("-x":suff:args) srcs objs | "none" <- suff = partition_args args srcs objs | StopLn <- phase = partition_args args srcs (slurp ++ objs) | otherwise = partition_args rest (these_srcs ++ srcs) objs where phase = startPhase suff (slurp,rest) = break (== "-x") args these_srcs = zip slurp (repeat (Just phase)) partition_args (arg:args) srcs objs | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs | otherwise = partition_args args srcs (arg:objs) {- We split out the object files (.o, .dll) and add them to ldInputs for use by the linker. The following things should be considered compilation manager inputs: - haskell source files (strings ending in .hs, .lhs or other haskellish extension), - module names (not forgetting hierarchical module names), - things beginning with '-' are flags that were not recognised by the flag parser, and we want them to generate errors later in checkOptions, so we class them as source files (#5921) - and finally we consider everything not containing a '.' to be a comp manager input, as shorthand for a .hs or .lhs filename. Everything else is considered to be a linker object, and passed straight through to the linker. -} looks_like_an_input :: String -> Bool looks_like_an_input m = isSourceFilename m || looksLikeModuleName m || "-" `isPrefixOf` m || '.' `notElem` m -- ----------------------------------------------------------------------------- -- Option sanity checks -- | Ensure sanity of options. -- -- Throws 'UsageError' or 'CmdLineError' if not. checkOptions :: Ghcjs.GhcjsSettings -> PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> [String] -> IO () -- Final sanity checking before kicking off a compilation (pipeline). checkOptions settings mode dflags srcs objs js_objs = do -- Complain about any unknown flags let unknown_opts = [ f | (f@('-':_), _) <- srcs ] when (notNull unknown_opts) (unknownFlagsErr unknown_opts) when (notNull (filter wayRTSOnly (ways dflags)) && isInterpretiveMode mode) $ hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi") when (isInterpretiveMode mode) $ do throwGhcException (UsageError "--interactive is not yet supported.") -- -prof and --interactive are not a good combination when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays) && isInterpretiveMode mode) $ do throwGhcException (UsageError "--interactive can't be used with -prof or -static.") -- -ohi sanity check if (isJust (outputHi dflags) && (isCompManagerMode mode || srcs `lengthExceeds` 1)) then throwGhcException (UsageError "-ohi can only be used when compiling a single source file") else do -- -o sanity checking if (srcs `lengthExceeds` 1 && isJust (outputFile dflags) && not (isLinkMode mode)) then throwGhcException (UsageError "can't apply -o to multiple source files") else do let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags) when (not_linking && not (null objs)) $ hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs) -- Check that there are some input files -- (except in the interactive case) if null srcs && isNothing (Ghcjs.gsLinkJsLib settings) && (null (objs++js_objs) || not_linking) && needsInputsMode mode then throwGhcException (UsageError "no input files") else do case mode of StopBefore HCc | hscTarget dflags /= HscC -> throwGhcException $ UsageError $ "the option -C is only available with an unregisterised GHC" StopBefore (As False) | ghcLink dflags == NoLink -> throwGhcException $ UsageError $ "the options -S and -fno-code are incompatible. Please omit -S" _ -> return () -- Verify that output files point somewhere sensible. verifyOutputFiles dflags -- Compiler output options -- called to verify that the output files & directories -- point somewhere valid. -- Called to verify that the output files point somewhere valid. -- -- The assumption is that the directory portion of these output -- options will have to exist by the time 'verifyOutputFiles' -- is invoked. -- -- We create the directories for -odir, -hidir, -outputdir etc. ourselves if -- they don't exist, so don't check for those here (#2278). verifyOutputFiles :: DynFlags -> IO () verifyOutputFiles dflags = do let ofile = outputFile dflags when (isJust ofile) $ do let fn = fromJust ofile flg <- doesDirNameExist fn when (not flg) (nonExistentDir "-o" fn) let ohi = outputHi dflags when (isJust ohi) $ do let hi = fromJust ohi flg <- doesDirNameExist hi when (not flg) (nonExistentDir "-ohi" hi) where nonExistentDir flg dir = throwGhcException (CmdLineError ("error: directory portion of " ++ show dir ++ " does not exist (used with " ++ show flg ++ " option.)")) ----------------------------------------------------------------------------- -- GHC modes of operation type Mode = Either PreStartupMode PostStartupMode type PostStartupMode = Either PreLoadMode PostLoadMode data PreStartupMode = ShowVersion -- ghc -V/--version | ShowNumVersion -- ghc --numeric-version | ShowSupportedExtensions -- ghc --supported-extensions | ShowOptions Bool {- isInteractive -} -- ghc --show-options -- GHCJS pre-startup modes | ShowNumGhcVersion -- ghcjs --numeric-ghc-version showNumGhcVersionMode :: Mode showNumGhcVersionMode = mkPreStartupMode ShowNumGhcVersion -- end GHCJS pre-startup modes showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode showVersionMode = mkPreStartupMode ShowVersion showNumVersionMode = mkPreStartupMode ShowNumVersion showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions showOptionsMode = mkPreStartupMode (ShowOptions False) mkPreStartupMode :: PreStartupMode -> Mode mkPreStartupMode = Left isShowVersionMode :: Mode -> Bool isShowVersionMode (Left ShowVersion) = True isShowVersionMode _ = False isShowNumVersionMode :: Mode -> Bool isShowNumVersionMode (Left ShowNumVersion) = True isShowNumVersionMode _ = False isShowNumGhcVersionMode :: Mode -> Bool isShowNumGhcVersionMode (Left ShowNumGhcVersion) = True isShowNumGhcVersionMode _ = False data PreLoadMode = ShowGhcUsage -- ghcjs -? | ShowGhciUsage -- ghci -? | ShowInfo -- ghcjs --info | PrintWithDynFlags (Ghcjs.GhcjsSettings -> DynFlags -> String) -- ghcjs --print-foo showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode showGhcUsageMode = mkPreLoadMode ShowGhcUsage showGhciUsageMode = mkPreLoadMode ShowGhciUsage showInfoMode = mkPreLoadMode ShowInfo printSetting :: String -> Mode printSetting k = mkPreLoadMode (PrintWithDynFlags f) where f _settings dflags = fromMaybe (panic ("Setting not found: " ++ show k)) $ lookup k (Ghcjs.compilerInfo dflags) mkPreLoadMode :: PreLoadMode -> Mode mkPreLoadMode = Right . Left isShowGhcUsageMode :: Mode -> Bool isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True isShowGhcUsageMode _ = False isShowGhciUsageMode :: Mode -> Bool isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True isShowGhciUsageMode _ = False data PostLoadMode = ShowInterface FilePath -- ghc --show-iface | DoMkDependHS -- ghc -M | StopBefore Phase -- ghc -E | -C | -S -- StopBefore StopLn is the default | DoMake -- ghc --make | DoInteractive -- ghc --interactive | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"] | DoAbiHash -- ghc --abi-hash | ShowPackages -- ghc --show-packages -- GHCJS modes | DoGenerateLib -- ghcjs --generate-lib | DoPrintRts -- ghcjs --print-rts | DoInstallExecutable -- ghcjs --install-executable ? -o ? | DoPrintObj FilePath -- ghcjs --print-obj file | DoPrintDeps FilePath -- ghcjs --print-deps file | DoBuildJsLibrary -- ghcjs --build-js-library doGenerateLib, doPrintRts, doBuildJsLibrary :: Mode doGenerateLib = mkPostLoadMode DoGenerateLib doPrintRts = mkPostLoadMode DoPrintRts doBuildJsLibrary = mkPostLoadMode DoBuildJsLibrary doInstallExecutable :: Mode doInstallExecutable = mkPostLoadMode DoInstallExecutable doPrintObj :: FilePath -> Mode doPrintObj file = mkPostLoadMode (DoPrintObj file) doPrintDeps :: FilePath -> Mode doPrintDeps file = mkPostLoadMode (DoPrintDeps file) ---- end GHCJS modes doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode :: Mode doMkDependHSMode = mkPostLoadMode DoMkDependHS doMakeMode = mkPostLoadMode DoMake doInteractiveMode = mkPostLoadMode DoInteractive doAbiHashMode = mkPostLoadMode DoAbiHash showPackagesMode :: Mode showPackagesMode = mkPostLoadMode ShowPackages showInterfaceMode :: FilePath -> Mode showInterfaceMode fp = mkPostLoadMode (ShowInterface fp) stopBeforeMode :: Phase -> Mode stopBeforeMode phase = mkPostLoadMode (StopBefore phase) doEvalMode :: String -> Mode doEvalMode str = mkPostLoadMode (DoEval [str]) mkPostLoadMode :: PostLoadMode -> Mode mkPostLoadMode = Right . Right isDoInteractiveMode :: Mode -> Bool isDoInteractiveMode (Right (Right DoInteractive)) = True isDoInteractiveMode _ = False isStopLnMode :: Mode -> Bool isStopLnMode (Right (Right (StopBefore StopLn))) = True isStopLnMode _ = False isDoMakeMode :: Mode -> Bool isDoMakeMode (Right (Right DoMake)) = True isDoMakeMode _ = False isDoEvalMode :: Mode -> Bool isDoEvalMode (Right (Right (DoEval _))) = True isDoEvalMode _ = False #if defined(HAVE_INTERNAL_INTERPRETER) isInteractiveMode :: PostLoadMode -> Bool isInteractiveMode DoInteractive = True isInteractiveMode _ = False #endif -- isInterpretiveMode: byte-code compiler involved isInterpretiveMode :: PostLoadMode -> Bool isInterpretiveMode DoInteractive = True isInterpretiveMode (DoEval _) = True isInterpretiveMode _ = False needsInputsMode :: PostLoadMode -> Bool needsInputsMode DoMkDependHS = True needsInputsMode (StopBefore _) = True needsInputsMode DoMake = True needsInputsMode _ = False -- True if we are going to attempt to link in this mode. -- (we might not actually link, depending on the GhcLink flag) isLinkMode :: PostLoadMode -> Bool isLinkMode (StopBefore StopLn) = True isLinkMode DoMake = True isLinkMode DoInteractive = True isLinkMode (DoEval _) = True isLinkMode _ = False isCompManagerMode :: PostLoadMode -> Bool isCompManagerMode DoMake = True isCompManagerMode DoInteractive = True isCompManagerMode (DoEval _) = True isCompManagerMode _ = False -- ----------------------------------------------------------------------------- -- Parsing the mode flag parseModeFlags :: [Located String] -> IO (Mode, [Located String], [Warn]) parseModeFlags args = do let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) = runCmdLine (processArgs mode_flags args) (Nothing, [], []) mode = case mModeFlag of Nothing -> doMakeMode Just (m, _) -> m -- See Note [Handling errors when parsing commandline flags] unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $ map (("on the commandline", )) $ map (unLoc . errMsg) errs1 ++ errs2 return (mode, flags' ++ leftover, warns) type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String]) -- mode flags sometimes give rise to new DynFlags (eg. -C, see below) -- so we collect the new ones and return them. mode_flags :: [Flag ModeM] mode_flags = [ ------- help / version ---------------------------------------------- defFlag "?" (PassFlag (setMode showGhcUsageMode)) , defFlag "-help" (PassFlag (setMode showGhcUsageMode)) , defFlag "V" (PassFlag (setMode showVersionMode)) , defFlag "-version" (PassFlag (setMode showVersionMode)) , defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode)) , defFlag "-info" (PassFlag (setMode showInfoMode)) , defFlag "-show-options" (PassFlag (setMode showOptionsMode)) , defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode)) , defFlag "-show-packages" (PassFlag (setMode showPackagesMode)) ] ++ [ defFlag k' (PassFlag (setMode (printSetting k))) | k <- ["Project version", "Booter version", "Stage", "Build platform", "Host platform", "Target platform", "Have interpreter", "Object splitting supported", "Have native code generator", "Support SMP", "Unregisterised", "Tables next to code", "RTS ways", "Leading underscore", "Debug on", "LibDir", "Global Package DB", "C compiler flags", "Gcc Linker flags", "Ld Linker flags", "Native Too"], let k' = "-print-" ++ map (replaceSpace . toLower) k replaceSpace ' ' = '-' replaceSpace c = c ] ++ ------- interfaces ---------------------------------------------------- [ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f) "--show-iface")) ------- primary modes ------------------------------------------------ , defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f addFlag "-no-link" f)) , defFlag "M" (PassFlag (setMode doMkDependHSMode)) , defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc))) , defFlag "C" (PassFlag (setMode (stopBeforeMode HCc))) , defFlag "S" (PassFlag (setMode (stopBeforeMode (As False)))) , defFlag "-make" (PassFlag (setMode doMakeMode)) , defFlag "-interactive" (PassFlag (setMode doInteractiveMode)) , defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode)) , defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e")) ------- GHCJS modes ------------------------------------------------ , defFlag "-generate-lib" (PassFlag (setMode doGenerateLib)) , defFlag "-install-executable" (PassFlag (setMode doInstallExecutable)) , defFlag "-print-obj" (HasArg (\f -> setMode (doPrintObj f) "--print-obj")) , defFlag "-print-deps" (HasArg (\f -> setMode (doPrintDeps f) "--print-deps")) , defFlag "-print-rts" (PassFlag (setMode doPrintRts)) , defFlag "-numeric-ghc-version" (PassFlag (setMode (showNumGhcVersionMode))) , defFlag "-numeric-ghcjs-version" (PassFlag (setMode (showNumVersionMode))) , defFlag "-build-js-library" (PassFlag (setMode doBuildJsLibrary)) ] setMode :: Mode -> String -> EwM ModeM () setMode newMode newFlag = liftEwM $ do (mModeFlag, errs, flags') <- getCmdLineState let (modeFlag', errs') = case mModeFlag of Nothing -> ((newMode, newFlag), errs) Just (oldMode, oldFlag) -> case (oldMode, newMode) of -- -c/--make are allowed together, and mean --make -no-link _ | isStopLnMode oldMode && isDoMakeMode newMode || isStopLnMode newMode && isDoMakeMode oldMode -> ((doMakeMode, "--make"), []) -- If we have both --help and --interactive then we -- want showGhciUsage _ | isShowGhcUsageMode oldMode && isDoInteractiveMode newMode -> ((showGhciUsageMode, oldFlag), []) | isShowGhcUsageMode newMode && isDoInteractiveMode oldMode -> ((showGhciUsageMode, newFlag), []) -- If we have both -e and --interactive then -e always wins _ | isDoEvalMode oldMode && isDoInteractiveMode newMode -> ((oldMode, oldFlag), []) | isDoEvalMode newMode && isDoInteractiveMode oldMode -> ((newMode, newFlag), []) -- Otherwise, --help/--version/--numeric-version always win | isDominantFlag oldMode -> ((oldMode, oldFlag), []) | isDominantFlag newMode -> ((newMode, newFlag), []) -- We need to accumulate eval flags like "-e foo -e bar" (Right (Right (DoEval esOld)), Right (Right (DoEval [eNew]))) -> ((Right (Right (DoEval (eNew : esOld))), oldFlag), errs) -- Saying e.g. --interactive --interactive is OK _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs) -- --interactive and --show-options are used together (Right (Right DoInteractive), Left (ShowOptions _)) -> ((Left (ShowOptions True), "--interactive --show-options"), errs) (Left (ShowOptions _), (Right (Right DoInteractive))) -> ((Left (ShowOptions True), "--show-options --interactive"), errs) -- Otherwise, complain _ -> let err = flagMismatchErr oldFlag newFlag in ((oldMode, oldFlag), err : errs) putCmdLineState (Just modeFlag', errs', flags') where isDominantFlag f = isShowGhcUsageMode f || isShowGhciUsageMode f || isShowVersionMode f || isShowNumVersionMode f || isShowNumGhcVersionMode f flagMismatchErr :: String -> String -> String flagMismatchErr oldFlag newFlag = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'" addFlag :: String -> String -> EwM ModeM () addFlag s flag = liftEwM $ do (m, e, flags') <- getCmdLineState putCmdLineState (m, e, mkGeneralLocated loc s : flags') where loc = "addFlag by " ++ flag ++ " on the commandline" -- ---------------------------------------------------------------------------- -- Run --make mode doMake :: Ghcjs.GhcjsEnv -> Ghcjs.GhcjsSettings -> Bool -> [(String,Maybe Phase)] -> Ghc () doMake jsEnv settings native srcs = do let (hs_srcs, non_hs_srcs) = partition haskellish srcs haskellish (f,Nothing) = looksLikeModuleName f || isHaskellUserSrcFilename f || '.' `notElem` f haskellish (_,Just phase) = phase `notElem` [As False, As True, Cc, Cobjc, Cobjcxx, CmmCpp, Cmm, StopLn] hsc_env <- GHC.getSession -- if we have no haskell sources from which to do a dependency -- analysis, then just do one-shot compilation and/or linking. -- This means that "ghc Foo.o Bar.o -o baz" links the program as -- we expect. if (null hs_srcs) then liftIO (Ghcjs.ghcjsOneShot jsEnv settings native hsc_env StopLn srcs) else do o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x) non_hs_srcs dflags <- GHC.getSessionDynFlags let dflags' = dflags { ldInputs = map (FileOption "") o_files ++ ldInputs dflags } _ <- GHC.setSessionDynFlags dflags' targets <- mapM (uncurry GHC.guessTarget) hs_srcs GHC.setTargets targets ok_flag <- GHC.load LoadAllTargets when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1)) return () -- --------------------------------------------------------------------------- -- --show-iface mode doShowIface :: DynFlags -> FilePath -> IO () doShowIface dflags file = do hsc_env <- newHscEnv dflags showIface hsc_env file -- --------------------------------------------------------------------------- -- Various banners and verbosity output. showBanner :: PostLoadMode -> DynFlags -> IO () showBanner _postLoadMode dflags = do let verb = verbosity dflags #if defined(HAVE_INTERNAL_INTERPRETER) -- Show the GHCi banner when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg #endif -- Display details of the configuration in verbose mode when (verb >= 2) $ do hPutStr stderr "Glasgow Haskell Compiler for JavaScript, Version " hPutStr stderr cProjectVersion hPutStr stderr ", stage " hPutStr stderr cStage hPutStr stderr " booted by GHC version " hPutStrLn stderr cBooterVersion -- We print out a Read-friendly string, but a prettier one than the -- Show instance gives us showInfo :: Ghcjs.GhcjsSettings -> DynFlags -> IO () showInfo _settings dflags = do let sq x = " [" ++ x ++ "\n ]" putStrLn $ sq $ intercalate "\n ," $ map show $ Ghcjs.compilerInfo dflags showSupportedExtensions :: Maybe String -> IO () showSupportedExtensions m_top_dir = do res <- runExceptT $ do top_dir <- lift (tryFindTopDir m_top_dir) >>= \case Nothing -> throwE $ SettingsError_MissingData "Could not find the top directory, missing -B flag" Just dir -> pure dir initSettings top_dir targetPlatformMini <- case res of Right s -> pure $ platformMini $ sTargetPlatform s Left (SettingsError_MissingData msg) -> do hPutStrLn stderr $ "WARNING: " ++ show msg hPutStrLn stderr $ "cannot know target platform so guessing target == host (native compiler)." pure cHostPlatformMini Left (SettingsError_BadData msg) -> do hPutStrLn stderr msg exitWith $ ExitFailure 1 mapM_ putStrLn $ supportedLanguagesAndExtensions targetPlatformMini showVersion :: IO () showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion) showOptions :: Bool -> IO () showOptions isInteractive = putStr (unlines availableOptions) where availableOptions = concat [ flagsForCompletion isInteractive, map ('-':) (getFlagNames mode_flags) ] getFlagNames opts = map flagName opts showGhcUsage :: DynFlags -> IO () showGhcUsage = showUsage False showGhciUsage :: DynFlags -> IO () showGhciUsage = showUsage True showUsage :: Bool -> DynFlags -> IO () showUsage ghci dflags = do let usage_path = if ghci then ghciUsagePath dflags else ghcUsagePath dflags usage <- readFile usage_path dump usage where dump "" = return () dump ('$':'$':s) = putStr progName >> dump s dump (c:s) = putChar c >> dump s dumpFinalStats :: DynFlags -> IO () dumpFinalStats dflags = when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags dumpFastStringStats :: DynFlags -> IO () dumpFastStringStats dflags = do segments <- getFastStringTable hasZ <- getFastStringZEncCounter let buckets = concat segments bucketsPerSegment = map length segments entriesPerBucket = map length buckets entries = sum entriesPerBucket msg = text "FastString stats:" $$ nest 4 (vcat [ text "segments: " <+> int (length segments) , text "buckets: " <+> int (sum bucketsPerSegment) , text "entries: " <+> int entries , text "largest segment: " <+> int (maximum bucketsPerSegment) , text "smallest segment: " <+> int (minimum bucketsPerSegment) , text "longest bucket: " <+> int (maximum entriesPerBucket) , text "has z-encoding: " <+> (hasZ `pcntOf` entries) ]) -- we usually get more "has z-encoding" than "z-encoded", because -- when we z-encode a string it might hash to the exact same string, -- which is not counted as "z-encoded". Only strings whose -- Z-encoding is different from the original string are counted in -- the "z-encoded" total. putMsg dflags msg where x `pcntOf` y = int ((x * 100) `quot` y) Outputable.<> char '%' showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO () showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags)) dumpPackages dflags = putMsg dflags (pprPackages dflags) dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags) -- ----------------------------------------------------------------------------- -- Frontend plugin support doFrontend :: ModuleName -> [(String, Maybe Phase)] -> Ghc () doFrontend modname srcs = do hsc_env <- getSession frontend_plugin <- liftIO $ loadFrontendPlugin hsc_env modname frontend frontend_plugin (reverse $ frontendPluginOpts (hsc_dflags hsc_env)) srcs -- ----------------------------------------------------------------------------- -- ABI hash support {- ghc --abi-hash Data.Foo System.Bar Generates a combined hash of the ABI for modules Data.Foo and System.Bar. The modules must already be compiled, and appropriate -i options may be necessary in order to find the .hi files. This is used by Cabal for generating the ComponentId for a package. The ComponentId must change when the visible ABI of the package chagnes, so during registration Cabal calls ghc --abi-hash to get a hash of the package's ABI. -} -- | Print ABI hash of input modules. -- -- The resulting hash is the MD5 of the GHC version used (#5328, -- see 'hiVersion') and of the existing ABI hash from each module (see -- 'mi_mod_hash'). abiHash :: [String] -- ^ List of module names -> Ghc () abiHash strs = do hsc_env <- getSession let dflags = hsc_dflags hsc_env liftIO $ do let find_it str = do let modname = mkModuleName str r <- findImportedModule hsc_env modname Nothing case r of Found _ m -> return m _error -> throwGhcException $ CmdLineError $ showSDoc dflags $ cannotFindModule dflags modname r mods <- mapM find_it strs let get_iface modl = loadUserInterface False (text "abiHash") modl ifaces <- initIfaceCheck (text "abiHash") hsc_env $ mapM get_iface mods bh <- openBinMem (3*1024) -- just less than a block put_ bh hiVersion -- package hashes change when the compiler version changes (for now) -- see #5328 mapM_ (put_ bh . mi_mod_hash . mi_final_exts) ifaces f <- fingerprintBinMem bh putStrLn (showPpr dflags f) -- ----------------------------------------------------------------------------- -- Util unknownFlagsErr :: [String] -> a unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs where oneError f = "unrecognised flag: " ++ f ++ "\n" ++ (case match f (nubSort allNonDeprecatedFlags) of [] -> "" suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs)) -- fixes #11789 -- If the flag contains '=', -- this uses both the whole and the left side of '=' for comparing. match f allFlags | elem '=' f = let (flagsWithEq, flagsWithoutEq) = partition (elem '=') allFlags fName = takeWhile (/= '=') f in (fuzzyMatch f flagsWithEq) ++ (fuzzyMatch fName flagsWithoutEq) | otherwise = fuzzyMatch f allFlags {- Note [-Bsymbolic and hooks] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Bsymbolic is a flag that prevents the binding of references to global symbols to symbols outside the shared library being compiled (see `man ld`). When dynamically linking, we don't use -Bsymbolic on the RTS package: that is because we want hooks to be overridden by the user, we don't want to constrain them to the RTS package. Unfortunately this seems to have broken somehow on OS X: as a result, defaultHooks (in hschooks.c) is not called, which does not initialize the GC stats. As a result, this breaks things like `:set +s` in GHCi (#8754). As a hacky workaround, we instead call 'defaultHooks' directly to initalize the flags in the RTS. A byproduct of this, I believe, is that hooks are likely broken on OS X when dynamically linking. But this probably doesn't affect most people since we're linking GHC dynamically, but most things themselves link statically. -} -- foreign import ccall safe "initGCStatistics" -- initGCStatistics :: IO () initGCStatistics :: IO () initGCStatistics = pure ()
ghcjs/ghcjs
src/Compiler/Program.hs
mit
43,329
0
29
11,888
8,824
4,547
4,277
671
23
{-# LANGUAGE OverloadedStrings #-} module Text.CSS.Shorthand.ListStyleSpec (main, spec) where import Test.Hspec import Text.CSS.Shorthand import Data.Maybe parse = fromJust . parseListStyle parseSingle f = fromJust . f . parse lsType = parseSingle getListStyleType lsPosition = parseSingle getListStylePosition lsImage = parseSingle getListStyleImage main = hspec spec spec = describe "list style" $ do describe "longhand" $ do it "parses longhand" $ do parse "disc outside none" == ListStyle (Just DiscLSType) (Just OutsideLSPos) (Just NoneImage) it "parses inherit" $ do parse "inherit" == InheritListStyle describe "type" $ do it "parses disc" $ do lsType "disc" == DiscLSType it "parses inherit" $ do lsType "inherit outside" == InheritLSType describe "position" $ do it "parses outside" $ do lsPosition "outside" == OutsideLSPos it "parses inherit" $ do lsPosition "disc inherit" == InheritLSPos describe "image" $ do it "parses image" $ do lsImage "url(foo.jpg)" == Url "foo.jpg" it "parses inherit" $ do lsImage "disc outside inherit" == InheritImage
zmoazeni/csscss-haskell
spec/Text/CSS/Shorthand/ListStyleSpec.hs
mit
1,167
0
17
261
330
150
180
32
1
-- | -- Module : $Header$ -- Description : The low level dataflow graph that the compiler produces in the end. -- Copyright : (c) Sebastian Ertel and Justus Adam 2017. All Rights Reserved. -- License : EPL-1.0 -- Maintainer : [email protected], [email protected] -- Stability : experimental -- This source code is licensed under the terms described in the associated LICENSE.TXT file module Ohua.DFGraph where import Ohua.Prelude import qualified Data.HashMap.Strict as HM import qualified Data.HashSet as HS import Ohua.DFLang.Lang data Operator = Operator { operatorId :: !FnId , operatorType :: !QualifiedBinding , operatorNType :: !NodeType } deriving (Eq, Generic, Show) data Target = Target { operator :: !FnId , index :: !Int } deriving (Eq, Generic, Show) data Arcs envExpr = Arcs { direct :: ![DirectArc envExpr] , state :: ![StateArc envExpr] , dead :: ![DeadArc] } deriving (Eq, Generic, Show) data Arc target source = Arc { target :: !target , source :: !source } deriving (Eq, Show, Generic) type DirectArc envExpr = Arc Target (Source envExpr) type StateArc envExpr = Arc FnId (Source envExpr) -- | A dead arc is a binding created in DFLang that is unused. Hence its -- 'target' field is the constant '()' and the 'source' is some operator at some -- index. Mostly this is used when dataflow operators that implement the -- argument dispatch themselves have one of their outputs be unused. type DeadArc = Arc () Target data Source envExpr = LocalSource !Target | EnvSource !envExpr deriving (Eq, Generic, Show) -- | Graph emitted by the compiler. Abstracted over the type of -- environment expression it contains. data AbstractOutGraph envExpr = OutGraph { operators :: [Operator] , arcs :: Arcs envExpr , returnArc :: Target } deriving (Eq, Generic, Show) type OutGraph = AbstractOutGraph Lit -- instance Functor Source where -- fmap f (EnvSource e) = EnvSource $ f e -- fmap _ (LocalSource t) = LocalSource t -- -- instance Functor DirectArc where -- fmap f (DirectArc t s) = DirectArc t $ fmap f s -- -- instance Functor AbstractOutGraph where -- fmap f (OutGraph ops grArcs r) = OutGraph ops (fmap (fmap f) grArcs) r instance NFData Operator instance NFData Target instance (NFData a, NFData b) => NFData (Arc a b) instance (NFData a) => NFData (Arcs a) instance NFData a => NFData (Source a) instance NFData a => NFData (AbstractOutGraph a) toGraph :: DFExpr -> OutGraph toGraph (DFExpr lets r) = OutGraph ops grArcs (getSource r) where ops = map toOp $ toList lets states = mapMaybe (\LetExpr {..} -> fmap (Arc callSiteId . varToSource) stateArgument) $ toList lets toOp LetExpr {..} = Operator callSiteId (nodeRef functionRef) (nodeType functionRef) sources = HM.fromList $ toList lets >>= \l -> [ (var, Target (callSiteId l) idx) | (var, idx) <- zip (output l) [0 ..] ] grArcs = let directs = [ Arc (Target callSiteId idx) $ varToSource v | LetExpr {..} <- toList lets , (idx, v) <- zip [0 ..] callArguments ] in Arcs directs states deads getSource v = fromMaybe (error $ "Undefined Binding: DFVar " <> show v <> " defined vars: " <> show sources) $ HM.lookup v sources varToSource = \case DFVar v -> LocalSource $ getSource v DFEnvVar envExpr -> EnvSource envExpr deads = map (Arc () . getSource) $ HS.toList $ allBindings `HS.difference` usedBindings where allBindings = HS.fromList $ toList lets >>= output usedBindings = HS.fromList $ r : [v | l <- toList lets, DFVar v <- callArguments l] -- spliceEnv :: (Int -> a) -> OutGraph -> AbstractOutGraph a -- spliceEnv lookupExpr = fmap f where f i = lookupExpr $ unwrap i
ohua-dev/ohua-core
core/src/Ohua/DFGraph.hs
epl-1.0
4,023
0
15
1,074
959
515
444
-1
-1
{- | Module : $Header$ Copyright : DFKI GmbH 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable printing AS_ExtModal ExtModalSign data types -} module ExtModal.Print_AS where import Common.Keywords import Common.Doc import Common.DocUtils import Common.Id import qualified Common.Lib.MapSet as MapSet import qualified Data.Set as Set import ExtModal.AS_ExtModal import ExtModal.ExtModalSign import ExtModal.Keywords import CASL.AS_Basic_CASL (FORMULA (..)) import CASL.ToDoc instance Pretty ModDefn where pretty (ModDefn time term id_list ax_list _) = fsep [(if time then keyword timeS else empty) <+> (if term then keyword termS else empty) <+> keyword modalityS , semiAnnos pretty id_list , if null ax_list then empty else specBraces (semiAnnos pretty ax_list)] instance Pretty EM_BASIC_ITEM where pretty itm = case itm of ModItem md -> pretty md Nominal_decl id_list _ -> sep [keyword nominalS, semiAnnos pretty id_list] modPrec :: MODALITY -> Int modPrec m = case m of SimpleMod _ -> 0 -- strongest TermMod _ -> 0 -- strongest Guard _ -> 1 TransClos _ -> 2 ModOp Composition _ _ -> 3 ModOp Intersection _ _ -> 4 ModOp Union _ _ -> 5 -- weakest printMPrec :: Bool -> MODALITY -> MODALITY -> Doc printMPrec b oP cP = (if (if b then (>) else (>=)) (modPrec oP) $ modPrec cP then id else parens) $ pretty cP instance Pretty MODALITY where pretty mdl = case mdl of SimpleMod idt -> if tokStr idt == emptyS then empty else pretty idt TermMod t -> pretty t Guard sen -> prJunct sen <> keyword quMark TransClos md -> printMPrec False mdl md <> keyword tmTransClosS ModOp o md1 md2 -> fsep [printMPrec True mdl md1 , keyword (show o) <+> printMPrec False mdl md2] prettyRigor :: Bool -> Doc prettyRigor b = keyword $ if b then rigidS else flexibleS instance Pretty EM_SIG_ITEM where pretty (Rigid_op_items rig op_list _) = cat [prettyRigor rig <+> keyword (opS ++ pluralS op_list), space <> semiAnnos pretty op_list] pretty (Rigid_pred_items rig pred_list _) = cat [prettyRigor rig <+> keyword (predS ++ pluralS pred_list), space <> semiAnnos pretty pred_list] instance FormExtension EM_FORMULA where isQuantifierLike ef = case ef of UntilSince {} -> False _ -> True isEMJunct :: FORMULA EM_FORMULA -> Bool isEMJunct f = case f of ExtFORMULA (UntilSince {}) -> True _ -> isJunct f prJunct :: FORMULA EM_FORMULA -> Doc prJunct f = (if isEMJunct f then parens else id) $ pretty f instance Pretty EM_FORMULA where pretty ef = case ef of BoxOrDiamond choice modality leq_geq number s _ -> let sp = case modality of SimpleMod _ -> (<>) _ -> (<+>) mdl = pretty modality in sep [ (if choice then brackets mdl else less `sp` mdl `sp` greater) <+> if not leq_geq && number == 1 then empty else keyword (if leq_geq then lessEq else greaterEq) <> text (show number) , prJunct s] Hybrid choice nom s _ -> keyword (if choice then atS else hereS) <+> pretty nom <+> prJunct s UntilSince choice s1 s2 _ -> printInfix True sep (prJunct s1) (keyword $ if choice then untilS else sinceS) $ prJunct s2 PathQuantification choice s _ -> keyword (if choice then allPathsS else somePathsS) <+> prJunct s NextY choice s _ -> keyword (if choice then nextS else yesterdayS) <+> prJunct s StateQuantification dir_choice choice s _ -> keyword (if dir_choice then if choice then generallyS else eventuallyS else if choice then hithertoS else previouslyS) <+> prJunct s FixedPoint choice p_var s _ -> sep [ keyword (if choice then muS else nuS) <+> pretty p_var , bullet <+> prJunct s] ModForm md -> pretty md instance Pretty EModalSign where pretty sign = let mds = modalities sign tims = time_modalities sign terms = termMods sign nms = nominals sign in printSetMap (keyword rigidS <+> keyword opS) empty (MapSet.toMap $ rigidOps sign) $+$ printSetMap (keyword rigidS <+> keyword predS) empty (MapSet.toMap $ rigidPreds sign) $+$ vcat (map (\ i -> fsep $ [keyword timeS | Set.member i tims] ++ [keyword termS | Set.member i terms] ++ [keyword modalityS, idDoc i]) $ Set.toList mds) $+$ (if Set.null nms then empty else keyword nominalS <+> sepBySemis (map sidDoc (Set.toList nms)))
nevrenato/Hets_Fork
ExtModal/Print_AS.hs
gpl-2.0
4,871
0
22
1,432
1,552
785
767
116
7
{-# LANGUAGE TemplateHaskell #-} module PL.Signatur where import PL.Data import PL.Util import PL.ToDoc import Autolib.FiniteMap import Autolib.TES.Identifier import Autolib.Set import Autolib.Reporter import Autolib.Reader import Autolib.ToDoc data Signatur = Signatur { funktionen :: FiniteMap Identifier Int , relationen :: FiniteMap Identifier Int , freie_variablen :: Set Identifier } $(derives [makeReader, makeToDoc] [''Signatur]) class Signed s where signatur :: s -> Signatur check :: Signatur -> s -> Reporter () instance Signed Formel where signatur f = case f of Quantified q v f -> remove_variable v $ signatur f Predicate p ts -> add_relation (p, length ts ) $ vereinige $ map signatur ts Operation op fs -> vereinige $ map signatur fs Equals l r -> vereinige $ map signatur [ l, r ] check sig f = case f of Quantified q v f -> check ( add_variable v sig ) f Operation op fs -> mapM_ ( check sig ) fs Predicate p ts -> check_exp sig ( relationen sig ) p ts check_exp sig fm p xs = do n <- find_or_complain "symbol" fm p when ( n /= length xs ) $ reject $ vcat [ text "number of arguments" <+> toDoc ( length xs) , text "does not match definition" <+> toDoc n , text "for relation/function symbol" <+> toDoc p , text "arguments are" <+> toDoc xs ] mapM_ ( check sig ) xs leer :: Signatur leer = Signatur { funktionen = emptyFM , relationen = emptyFM , freie_variablen = emptySet } instance Signed Term where signatur ( Variable v ) = leer { freie_variablen = mkSet [v] } signatur ( Apply f xs ) = add_function ( f, length xs ) $ vereinige $ map signatur xs check sig ( Variable v ) = do when ( not $ v `elementOf` freie_variablen sig ) $ reject $ text "Variable" <+> toDoc v <+> text "nicht deklariert" check sig ( Apply f xs ) = check_exp sig ( funktionen sig ) f xs add_function (f, n) sig = sig { funktionen = addToFM ( funktionen sig ) f n } add_relation (r, n) sig = sig { relationen = addToFM ( relationen sig ) r n } vereinige = foldr vereinige_zwei leer vereinige_zwei s t = Signatur { funktionen = plusFM ( funktionen s ) ( funktionen t ) , relationen = plusFM ( relationen s ) ( relationen t ) , freie_variablen = union ( freie_variablen s ) ( freie_variablen t ) } remove_variable v sig = sig { freie_variablen = minusSet ( freie_variablen sig ) ( unitSet v ) } add_variable v sig = sig { freie_variablen = union ( freie_variablen sig ) ( unitSet v ) } -- local variables: -- mode: haskell -- end:
florianpilz/autotool
src/PL/Signatur.hs
gpl-2.0
2,720
65
15
753
801
437
364
67
1
{-# OPTIONS -w -O0 #-} {- | Module : ATC/OrderedMap.der.hs Description : generated Typeable, ShATermConvertible instances Copyright : (c) DFKI Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable(overlapping Typeable instances) Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible for the type(s): 'Common.OrderedMap.ElemWOrd' -} {- Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!! dependency files: Common/OrderedMap.hs -} module ATC.OrderedMap () where import ATerm.Lib import Common.OrderedMap import Data.Ord import Data.Typeable import Prelude hiding (lookup, map, filter, null) import qualified Data.List as List import qualified Data.Map as Map {-! for Common.OrderedMap.ElemWOrd derive : Typeable !-} {-! for Common.OrderedMap.ElemWOrd derive : ShATermConvertible !-}
nevrenato/Hets_Fork
ATC/OrderedMap.der.hs
gpl-2.0
954
0
5
145
68
47
21
9
0
-- P05 Reverse a list. -- Predefined function f0 :: [a] -> [a] f0 = reverse -- Recursion (inefficient) f1 :: [a] -> [a] f1 [] = [] f1 (x:xs) = f1 xs ++ [x] -- Tail recursion f2 :: [a] -> [a] f2 = f2' [] where f2' :: [a] -> [a] -> [a] f2' acc [] = acc f2' acc (x:xs) = f2' (x:acc) xs -- Folding f3 :: [a] -> [a] f3 = foldl (flip (:)) []
pavelfatin/ninety-nine
haskell/p05.hs
gpl-3.0
354
0
9
98
203
114
89
12
2
module Deploy where { import Deployment; import State; import Control.Concurrent.MVar; import WASH.CGI.RawCGI as RawCGI; addDeployment :: DeployedObject -> IO (); addDeployment dobj = do { st0 <- takeMVar currentState; let { ds = deploymentState st0; dobjs = objs ds; st1 = st0{deploymentState = ds{objs = dobj : dobjs}}}; putMVar currentState st1}; activate :: [String] -> IO (); activate names = modify names True; passivate :: [String] -> IO (); passivate names = modify names False; modify :: [String] -> Bool -> IO (); modify names newValue = do { st0 <- takeMVar currentState; let { ds = deploymentState st0; dobjs = map actOn (objs ds); st1 = st0{deploymentState = ds{objs = dobjs}}; actOn dobj = if objectName dobj `elem` names && not (objectSystem dobj) then dobj{objectActive = newValue} else dobj}; putMVar currentState st1}; undeploy :: [String] -> IO (); undeploy names = do { st0 <- takeMVar currentState; let { ds = deploymentState st0; dobjs = filter testOn (objs ds); st1 = st0{deploymentState = ds{objs = dobjs}}; testOn dobj = objectName dobj `elem` names}; putMVar currentState st1}; modifyOptions :: [String] -> (CGIOptions -> CGIOptions) -> IO (); modifyOptions names converter = do { st0 <- takeMVar currentState; let { ds = deploymentState st0; dobjs = map actOn (objs ds); st1 = st0{deploymentState = ds{objs = dobjs}}; actOn dobj = if objectName dobj `elem` names then dobj{objectOptions = converter (objectOptions dobj)} else dobj}; putMVar currentState st1}}
ckaestne/CIDE
CIDE_Language_Haskell/test/WSP/Webserver/Deploy.hs
gpl-3.0
1,916
0
15
664
621
346
275
44
2
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grid is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with grid. If not, see <http://www.gnu.org/licenses/>. -- {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE MultiParamTypeClasses #-} module Game.Grid.GridWorld ( GridWorld (..), GridEvent (..), module Game.Grid.GridWorld.Path, module Game.Grid.GridWorld.Camera, module Game.Grid.GridWorld.Segment, module Game.Grid.GridWorld.CameraCommand, ) where import MyPrelude import Game.MEnv import Game.World import Game.Grid.GridWorld.Turn import Game.Grid.GridWorld.Path import Game.Grid.GridWorld.Camera import Game.Grid.GridWorld.Node import Game.Grid.GridWorld.Segment import Game.Grid.GridWorld.CameraCommand data GridWorld = GridWorld { gridTick :: !TickT, gridEvents :: [GridEvent], gridCamera :: !Camera, gridCameraCommands :: ![CameraCommand], gridCameraCommandTick :: !TickT, -- physical objects: -- fixme: use either gridPaths, or gridPathA, -- if we use some array-container, we can probably let PathIx be a direct index, -- not causing so much overhead as searching for ix each time (an old functional -- programmer probably now the best datatype...) --gridPaths :: [Path] gridPathA :: !Path, -- control state gridControlPosRef :: Position } -------------------------------------------------------------------------------- -- -- | GridEvent data GridEvent --EventCameraCommandsComplete instance World GridWorld GridEvent where worldTick = gridTick worldTickModify grid f = grid { gridTick = f $ gridTick grid } worldAllEvents = gridEvents worldPushEvent grid e = grid { gridEvents = gridEvents grid ++ [e] } -------------------------------------------------------------------------------- --
karamellpelle/grid
designer/source/Game/Grid/GridWorld.hs
gpl-3.0
2,522
0
10
544
282
190
92
-1
-1
module Hkl.H5 ( Dataset , File , check_ndims , closeDataset , get_position , get_ub , lenH5Dataspace , openDataset , withH5File ) where import Bindings.HDF5.Core ( HSize(..) ) import Bindings.HDF5.File ( File , AccFlags(ReadOnly) , openFile , closeFile ) import Bindings.HDF5.Dataset ( Dataset , openDataset , closeDataset , getDatasetSpace , readDataset , readDatasetInto ) import Bindings.HDF5.Dataspace ( Dataspace , SelectionOperator(Set) , closeDataspace , createSimpleDataspace , getSimpleDataspaceExtentNDims , getSimpleDataspaceExtentNPoints , selectHyperslab ) import Control.Exception (bracket) import Data.ByteString.Char8 (pack) import Data.Vector.Storable (Vector, freeze) import Data.Vector.Storable.Mutable (replicate) import Foreign.C.Types (CInt(..)) import Numeric.LinearAlgebra (Matrix, reshape) import Prelude hiding (replicate) {-# ANN module "HLint: ignore Use camelCase" #-} check_ndims :: Dataset -> Int -> IO Bool check_ndims d expected = do space_id <- getDatasetSpace d (CInt ndims) <- getSimpleDataspaceExtentNDims space_id return $ expected == fromEnum ndims get_position :: Dataset -> Int -> IO (Vector Double) get_position dataset n = withDataspace dataset $ \dataspace -> do let start = HSize (fromIntegral n) let stride = Just (HSize 1) let count = HSize 1 let block = Just (HSize 1) selectHyperslab dataspace Set [(start, stride, count, block)] withDataspace' $ \memspace -> do data_out <- replicate 1 (0.0 :: Double) readDatasetInto dataset (Just memspace) (Just dataspace) Nothing data_out freeze data_out get_ub :: Dataset -> IO (Matrix Double) get_ub dataset = do v <- readDataset dataset Nothing Nothing return $ reshape 3 v -- | File withH5File :: FilePath -> (File -> IO r) -> IO r withH5File fp = bracket acquire release where acquire = openFile (pack fp) [ReadOnly] Nothing release = closeFile -- | Dataspace -- check how to merge both methods withDataspace' :: (Dataspace -> IO r) -> IO r withDataspace' = bracket acquire release where acquire = createSimpleDataspace [HSize 1] release = closeDataspace withDataspace :: Dataset -> (Dataspace -> IO r) -> IO r withDataspace d = bracket acquire release where acquire = getDatasetSpace d release = closeDataspace lenH5Dataspace :: Dataset -> IO (Maybe Int) lenH5Dataspace = withDataspace'' len where withDataspace'' f d = withDataspace d f len space_id = do (HSize n) <- getSimpleDataspaceExtentNPoints space_id return $ if n < 0 then Nothing else Just (fromIntegral n)
picca/hkl
contrib/haskell/src/Hkl/H5.hs
gpl-3.0
3,146
0
15
1,037
805
428
377
75
2
{-# 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.DLP.Organizations.Locations.DeidentifyTemplates.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a DeidentifyTemplate. See -- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates-deid to learn -- more. -- -- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.organizations.locations.deidentifyTemplates.delete@. module Network.Google.Resource.DLP.Organizations.Locations.DeidentifyTemplates.Delete ( -- * REST Resource OrganizationsLocationsDeidentifyTemplatesDeleteResource -- * Creating a Request , organizationsLocationsDeidentifyTemplatesDelete , OrganizationsLocationsDeidentifyTemplatesDelete -- * Request Lenses , oldtdXgafv , oldtdUploadProtocol , oldtdAccessToken , oldtdUploadType , oldtdName , oldtdCallback ) where import Network.Google.DLP.Types import Network.Google.Prelude -- | A resource alias for @dlp.organizations.locations.deidentifyTemplates.delete@ method which the -- 'OrganizationsLocationsDeidentifyTemplatesDelete' request conforms to. type OrganizationsLocationsDeidentifyTemplatesDeleteResource = "v2" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] GoogleProtobufEmpty -- | Deletes a DeidentifyTemplate. See -- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates-deid to learn -- more. -- -- /See:/ 'organizationsLocationsDeidentifyTemplatesDelete' smart constructor. data OrganizationsLocationsDeidentifyTemplatesDelete = OrganizationsLocationsDeidentifyTemplatesDelete' { _oldtdXgafv :: !(Maybe Xgafv) , _oldtdUploadProtocol :: !(Maybe Text) , _oldtdAccessToken :: !(Maybe Text) , _oldtdUploadType :: !(Maybe Text) , _oldtdName :: !Text , _oldtdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrganizationsLocationsDeidentifyTemplatesDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oldtdXgafv' -- -- * 'oldtdUploadProtocol' -- -- * 'oldtdAccessToken' -- -- * 'oldtdUploadType' -- -- * 'oldtdName' -- -- * 'oldtdCallback' organizationsLocationsDeidentifyTemplatesDelete :: Text -- ^ 'oldtdName' -> OrganizationsLocationsDeidentifyTemplatesDelete organizationsLocationsDeidentifyTemplatesDelete pOldtdName_ = OrganizationsLocationsDeidentifyTemplatesDelete' { _oldtdXgafv = Nothing , _oldtdUploadProtocol = Nothing , _oldtdAccessToken = Nothing , _oldtdUploadType = Nothing , _oldtdName = pOldtdName_ , _oldtdCallback = Nothing } -- | V1 error format. oldtdXgafv :: Lens' OrganizationsLocationsDeidentifyTemplatesDelete (Maybe Xgafv) oldtdXgafv = lens _oldtdXgafv (\ s a -> s{_oldtdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). oldtdUploadProtocol :: Lens' OrganizationsLocationsDeidentifyTemplatesDelete (Maybe Text) oldtdUploadProtocol = lens _oldtdUploadProtocol (\ s a -> s{_oldtdUploadProtocol = a}) -- | OAuth access token. oldtdAccessToken :: Lens' OrganizationsLocationsDeidentifyTemplatesDelete (Maybe Text) oldtdAccessToken = lens _oldtdAccessToken (\ s a -> s{_oldtdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). oldtdUploadType :: Lens' OrganizationsLocationsDeidentifyTemplatesDelete (Maybe Text) oldtdUploadType = lens _oldtdUploadType (\ s a -> s{_oldtdUploadType = a}) -- | Required. Resource name of the organization and deidentify template to -- be deleted, for example -- \`organizations\/433245324\/deidentifyTemplates\/432452342\` or -- projects\/project-id\/deidentifyTemplates\/432452342. oldtdName :: Lens' OrganizationsLocationsDeidentifyTemplatesDelete Text oldtdName = lens _oldtdName (\ s a -> s{_oldtdName = a}) -- | JSONP oldtdCallback :: Lens' OrganizationsLocationsDeidentifyTemplatesDelete (Maybe Text) oldtdCallback = lens _oldtdCallback (\ s a -> s{_oldtdCallback = a}) instance GoogleRequest OrganizationsLocationsDeidentifyTemplatesDelete where type Rs OrganizationsLocationsDeidentifyTemplatesDelete = GoogleProtobufEmpty type Scopes OrganizationsLocationsDeidentifyTemplatesDelete = '["https://www.googleapis.com/auth/cloud-platform"] requestClient OrganizationsLocationsDeidentifyTemplatesDelete'{..} = go _oldtdName _oldtdXgafv _oldtdUploadProtocol _oldtdAccessToken _oldtdUploadType _oldtdCallback (Just AltJSON) dLPService where go = buildClient (Proxy :: Proxy OrganizationsLocationsDeidentifyTemplatesDeleteResource) mempty
brendanhay/gogol
gogol-dlp/gen/Network/Google/Resource/DLP/Organizations/Locations/DeidentifyTemplates/Delete.hs
mpl-2.0
5,886
0
15
1,210
703
414
289
111
1
{- Habit of Fate, a game to incentivize habit formation. Copyright (C) 2019 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 AutoDeriveTypeable #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} module HabitOfFate. where import HabitOfFate.Prelude
gcross/habit-of-fate
misc/Template.hs
agpl-3.0
862
1
4
170
17
11
6
-1
-1
---------------------------------------------------------------- -- Jedes Modul beginnt mit diesen Teil -- weil wir ein lauffähiges Programm haben wollen -- schreiben wir nur das Hauptmodul (`Main`) module Main where -- danach kommt de Teil wo externe Module improtiert werden import Control.Monad (forM_) import System.IO (hSetBuffering, BufferMode(NoBuffering), stdout) ---------------------------------------------------------------- -- dieser Teil ist der Programmeinstiegspunkt -- `main` fragt einfach nur die Zahlen und die Zielzahl ab -- (die Zahlen können als Liste wie in Haskell eingegeben werden) -- berechnet dann die Lösungen und gibt diese aus -- die Details sollen heute nicht so interessant sein main :: IO () main = do hSetBuffering stdout NoBuffering putStrLn "Countdown" putStr "Liste mit verfügbaren Zahlen? " zahlen <- read <$> getLine putStr "Zielzahl? " ziel <- read <$> getLine let lösungen = solutions zahlen ziel forM_ lösungen print --------------------------------------------------------------- -- HIER beginnt der Spaß für uns ;) -- unser ziel ist es eine Expression aufzubauen -- deren Value Blätter nur Werte aus den gegebenen -- Zahlen annehmen und die dem Zielwert entspricht data Expression = Value Int | Apply Operand Expression Expression deriving (Eq) -- dafür stehen uns folgende Operationen zur Auswahl: data Operand = Add | Sub | Mul | Div deriving (Eq, Ord) -- apply soll zwei Zahlen mit den gegebenen Operanden -- verknüpfen und das Ergebnis der Operation berechnen apply :: Operand -> Int -> Int -> Int apply Add = (+) apply Sub = (-) apply Mul = (*) apply Div = div -- wie oben erwähnt soll eine gültige Expression -- nur Zahlen aus der gegebenen Liste enthalten -- mit values suchen wir alle verwendeten Werte -- (die Werte der Blätter des Expression-Baums) values :: Expression -> [Int] values (Value n) = [n] values (Apply _ x y) = values x ++ values y -- um später alle möglichen Expressions aufzulisten -- brauchen wir alle Teillisten der Verfügbaren -- Zahlen (wobei hier die Anordnung bestehen bleiben soll) subs :: [a] -> [[a]] subs [] = [[]] subs (x:xs) = map (x:) (subs xs) ++ subs xs -- um gleich perms zu implementieren können wir -- pick benutzen: es liefert alle Möglichkeiten -- ein Element aus einer Liste zu wählen (zusammen mit -- den Rest) -- Beispiel: pick [1,2,3] = [(1,[2,3]),(2,[1,3]),(3,[1,2])] pick :: [a] -> [ (a,[a]) ] pick [] = [] pick (x:xs) = (x,xs) : [ (y,x:ys) | (y,ys) <- pick xs ] -- schließlich brauchen wir noch eine Funktion die uns -- alle Permutationen (Umordnungen) einer Liste liefert -- Tipp: Pick ist sicher nützlich ;) perms :: [a] -> [[a]] perms [] = [[]] perms xs = [ y:ys | (y,ys') <- pick xs, ys <- perms ys' ] -- wir haben das oben noch nicht gemacht, aber wir müssen -- eine Expression ja noch "auswerten" -- allerdings benutzen wir hier einen Trick: eval soll nicht -- nur ein Ergebnis liefern - es soll auch prüfen ob überall -- valide Operationen verwendet wurden, und dafür können wir -- Listen und Comprehensions clever benutzen: -- die Leere Menge steht für kein Ergebnis möglich (z.B. weil -- irgendwo durch 0 geteilt wurde) und ein Ergebnis n wird -- durch eine Liste mit genau einem Element [n] angezeigt eval :: Expression -> [Int] eval (Value n) = [ n | n > 0 ] eval (Apply op x y) = [ apply op a b | a <- eval x, b <- eval y, isValidOp op a b ] -- subbags verbindet jetzt einfach perms und subs: damit bekommen -- wir alle Permutationen aller Teillisten: subbags :: [a] -> [[a]] subbags xs = [ zs | ys <- subs xs, zs <- perms ys ] -- diese Funktion liefert alle Möglichkeiten wie -- eine Liste in zwei Teile geteilt werden kann split :: [a] -> [ ([a],[a]) ] split [] = [ ([],[]) ] split (x:xs) = ([], x:xs) : [ (x:ls,rs) | (ls,rs) <- split xs ] -- allerdings interessieren wir uns nur für die Aufteilungen -- wo kein Teil leer ist notEmptySplit :: [a] -> [ ([a],[a]) ] notEmptySplit = filter notEmpty . split where notEmpty (xs,ys) = not (null xs || null ys) -- um Schneller zu werden, erzeugen wir nicht nur die -- Expressions sondern die Expressions + Ihren Wert -- dabei filtern wir gleich diejenigen heraus, die -- ungültig sind type Result = (Expression, Int) results :: [Int] -> [Result] results [] = [] results [n] = [ (Value n, n) | n > 0 ] results ns = [ res | (ls,rs) <- notEmptySplit ns , lx <- results ls , ry <- results rs , res <- combine lx ry ] where combine (l,x) (r,y) = [ (Apply op l r, apply op x y) | op <- ops, isValidOp op x y ] ops = [ Add, Sub, Mul, Div ] -- außerdem schränken wir die gültigen Operationen noch weiter ein -- um zu verhindern, dass wir 3+4 und 4+3 erzeugen, verlangen wird, dass -- der erste Operand kleiner als der zweite sein soll, außerdem -- machen Dinge wie *1 oder /1 keinen Unterschied isValidOp :: (Ord a, Integral a) => Operand -> a -> a -> Bool isValidOp Add x y = x <= y isValidOp Sub x y = x > y isValidOp Mul x y = x /= 1 && y /= 1 && x <= y isValidOp Div x y = y /= 1 && x `mod` y == 0 solutions :: [Int] -> Int -> [Expression] solutions ns n = [ e | ns' <- subbags ns, (e,m) <- results ns', m == n ] ------------------------------------------------------ -- dieser Teil dient nur dazu die Expressions etwas -- shöner Darzustellen, als es `deriving Show` könnte instance Show Expression where show ex = snd $ formatEx 0 ex formatEx :: Int -> Expression -> (Int, String) formatEx _ (Value n) = (9, show n) formatEx prec (Apply op l r) | opPrec <= prec = (prec, "(" ++ formatted ++ ")") | otherwise = (prec, formatted) where opPrec = precedence op formatted = let (lp, ls) = formatEx opPrec l (_, rs) = formatEx lp r in ls ++ show op ++ rs precedence :: Operand -> Int precedence Mul = 9 precedence Div = 8 precedence Add = 5 precedence Sub = 4 instance Show Operand where show Add = "+" show Sub = "-" show Mul = "*" show Div = "/"
CarstenKoenig/DOS2015
Countdown/CountdownFast.hs
unlicense
6,056
0
11
1,285
1,601
878
723
86
1
{-# LANGUAGE CPP #-} module Main (main) where import Data.List.Split import Generator import Options.Applicative version = "1.0" data Input = Input { includes :: String , name :: String, baseName :: String, properties :: String, interactive :: Bool } deriving Show input :: Parser Input input = Input <$> strOption ( long "includes" <> short 'i' <> metavar "LIST" <> help "List of comma separated header files to include (Eg. string,vector,boost)" ) <*> strOption ( long "name" <> short 'n' <> metavar "CLASS NAME" <> help "Name of the class" ) <*> strOption ( long "baseName" <> short 'b' <> metavar "BASE" <> help "Name of the base class" ) <*> strOption ( long "properties" <> short 'p' <> metavar "LIST" <> help "List of comma separated properties in the format - type:name (Eg. s:name, i:age)" ) <*> switch ( long "interactive" <> short 'e' <> help "Enable interactive mode" ) handler :: Input -> IO () handler (Input _ _ _ _ True) = interactiveMode handler (Input is n pn ps _) = do let includes = map (\s -> Include s) $ splitComma is let properties = map (\(t, n) -> ClassProperty n (propertyType t)) $ parseProperties ps let cls = Class includes n pn properties wClass cls parseProperties :: String -> [(String, String)] parseProperties ps = map (\p -> toTuple $ splitOn ":" p) $ splitComma ps where toTuple l = (head l, last l) main :: IO () main = execParser opts >>= handler where opts = info (helper <*> input) ( fullDesc <> progDesc "Generate C++ class" <> header "source-generator - Source code generator" ) interactiveMode :: IO () interactiveMode = do putStrLn $ "Source Generator v" ++ version putStrLn "Class name" className <- getLine putStrLn "Include files" includeFiles <- getLine let includes = map (\s -> Include s) $ splitComma includeFiles putStrLn "Parent name" parentName <- getLine putStrLn "Properties" propertyInput <- readProperties let properties = map (\(t, n) -> ClassProperty n (propertyType t)) propertyInput let cls = Class includes className parentName properties wClass cls putStrLn $ "Class " ++ className ++ " written to gen dir" readProperties :: IO [(String, String)] readProperties = do putStrLn "Add property? (y,n)" answer <- getLine case answer of "n" -> return [] "y" -> do putStrLn "Property type (s, i, b, f, sl, il)" pType <- getLine putStrLn "Property name" pName <- getLine let property = (pType, pName) nextProperties <- readProperties return $ property : nextProperties propertyType :: String -> PropertyType propertyType "s" = String propertyType "i" = Int propertyType "b" = Bool propertyType "f" = Float propertyType "sl" = StringList propertyType "il" = IntList splitComma :: String -> [String] splitComma = splitOn ","
curiousily/source-generator
Main.hs
apache-2.0
3,251
0
16
1,016
917
447
470
93
2
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# OPTIONS_GHC -fno-warn-unrecognised-pragmas #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {- # ANN module "HLint: ignore Functor law" #-} {- # ANN module "HLint: ignore Evaluate" #-} {- # ANN module "HLint: ignore Use ." #-} module StatNLP.ContextSpec where import qualified Data.FingerTree as FT import Data.Foldable (foldl') import Data.Maybe import Data.Monoid import qualified Data.Sequence as Seq import Test.Hspec hiding (after, before) import Test.QuickCheck import StatNLP.Context import StatNLP.Types instance Arbitrary a => Arbitrary (Context a) where arbitrary = do before <- arbitrary `suchThat` (>=0) after <- arbitrary `suchThat` (>=0) Context before after <$> fmap (Seq.fromList . take before) (infiniteListOf arbitrary) <*> arbitrary <*> fmap (Seq.fromList . take after) (infiniteListOf arbitrary) sumc :: Num a => Context a -> a sumc (Context _ _ as c bs) = c + foldl' (+) 0 as + foldl' (+) 0 bs spec :: Spec spec = do describe "Context" $ do describe "Functor" $ do it "should satisfy fmap id == id." $ property $ \(c :: Context Int) -> fmap id c == id c it "should satisfy fmap (f . g) == fmap f . fmap g." $ property $ \(c :: Context Int) -> fmap ((* 2) . (+ 7)) c == (fmap (* 2) . fmap (+ 7)) c describe "pushR" $ do it "should maintain the size of the left context." $ property $ \(c :: Context Int) (xs :: [Int]) -> length (_contextBefore $ foldl' (flip pushR) c xs) == _contextBeforeN c it "should maintain the size of the right context." $ property $ \(c :: Context Int) (xs :: [Int]) -> length (_contextAfter $ foldl' (flip pushR) c xs) == _contextAfterN c it "should shift everything over one." $ (0 `pushR` Context 2 2 [1 :: Int, 2] 3 [4, 5]) `shouldBe` Context 2 2 [0, 1] 2 [3, 4] describe "pushL" $ do it "should maintain the size of the left context." $ property $ \(c :: Context Int) (xs :: [Int]) -> length (_contextBefore $ foldl' pushL c xs) == _contextBeforeN c it "should maintain the size of the right context." $ property $ \(c :: Context Int) (xs :: [Int]) -> length (_contextAfter $ foldl' pushL c xs) == _contextAfterN c it "should shift everything over one." $ (Context 2 2 [1 :: Int, 2] 3 [4, 5] `pushL` 6) `shouldBe` Context 2 2 [2, 3] 4 [5, 6] describe "shiftL" $ do it "should shift to nothing on an empty context." $ shiftL (Context 2 2 [1 :: Int, 2] 3 []) `shouldSatisfy` isNothing it "should shift to something on an existing context." $ shiftL (Context 2 2 [1 :: Int, 2] 3 [4]) `shouldSatisfy` isJust describe "shiftR" $ do it "should shift to nothing on an empty context." $ shiftR (Context 2 2 [] 1 [2 :: Int, 3]) `shouldSatisfy` isNothing it "should shift to something on an existing context." $ shiftR (Context 2 2 [1 :: Int] 2 [3, 4]) `shouldSatisfy` isJust describe "MeasuredContext" $ do let goodbye = appendLeft (MContext 10 FT.empty) ([ "good-bye" , "cruel" , "world" ] :: [Token SpanPos PlainToken]) today = appendLeft (MContext 10 FT.empty) ([ "today" , "is" , "the" , "first" , "day" , "of" , "the" , "," , "rest" , "of" , "my" , "life" , "." ] :: [Token SpanPos PlainToken]) describe "pushLeft" $ do it "should allow one to push context into it." $ getContext (pushLeft ("howdy" :: Token SpanPos PlainToken) (MContext 10 FT.empty)) `shouldBe` ["howdy"] it "should limit the amount of data in the context." $ getContext goodbye `shouldBe` ["cruel", "world"] it "should allow one item of data over the limit." $ FT.measure (_mContextSeq goodbye) `shouldBe` Sum 12 describe "appendLeft" $ do it "should push multiple items into the context." $ let c = appendLeft (MContext 100 FT.empty) (["one", "two", "three"] :: [Token SpanPos PlainToken]) in getContext c `shouldBe` ["one", "two", "three"] it "should push lots of things into the list." $ getContext today `shouldBe` ["of", "my", "life", "."] describe "getContext" $ it "should return the context as a list." $ getContext today `shouldBe` ["of", "my", "life", "."]
erochest/stat-nlp
specs/StatNLP/ContextSpec.hs
apache-2.0
6,113
0
21
2,818
1,460
766
694
108
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} module Language.K3.Interpreter.Builtins.Math where import Control.Monad.State import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Type import Language.K3.Interpreter.Data.Types import Language.K3.Interpreter.Data.Accessors genMathBuiltin :: Identifier -> K3 Type -> Maybe (Interpretation Value) -- random :: int -> int genMathBuiltin "random" _ = Just $ vfun $ \x -> case x of VInt upper -> liftIO (Random.randomRIO (0::Int, upper)) >>= return . VInt _ -> throwE $ RunTimeInterpretationError $ "Expected int but got " ++ show x -- randomFraction :: () -> real genMathBuiltin "randomFraction" _ = Just $ vfun $ \_ -> liftIO Random.randomIO >>= return . VReal -- hash :: forall a . a -> int genMathBuiltin "hash" _ = Just $ vfun $ \v -> valueHash v -- range :: int -> collection {i : int} @ { Collection } genMathBuiltin "range" _ = Just $ vfun $ \(VInt upper) -> initialAnnotatedCollection "Collection" $ map (\i -> VRecord (insertMember "i" (VInt i, MemImmut) $ emptyMembers)) [0..(upper-1)] -- truncate :: int -> real genMathBuiltin "truncate" _ = Just $ vfun $ \x -> case x of VReal r -> return $ VInt $ truncate r _ -> throwE $ RunTimeInterpretationError $ "Expected real but got " ++ show x -- real_of_int :: real -> int genMathBuiltin "real_of_int" _ = Just $ vfun $ \x -> case x of VInt i -> return $ VReal $ fromIntegral i _ -> throwE $ RunTimeInterpretationError $ "Expected int but got " ++ show x -- get_max_int :: () -> int genMathBuiltin "get_max_int" _ = Just $ vfun $ \_ -> return $ VInt maxBound genMathBuiltin _ _ = Nothing
yliu120/K3
src/Language/K3/Interpreter/Builtins/Math.hs
apache-2.0
1,726
0
16
342
494
263
231
28
4
main :: IO () main = print "Thanks Carlos" -- doubleMe x = x + x
carlospatinos/experiments
haskell/main.hs
apache-2.0
68
0
6
19
20
10
10
2
1
module Application.Hoodle.Cache.Job where startJob :: IO () startJob = do putStrLn "job started"
wavewave/hoodle-cache
lib/Application/Hoodle/Cache/Job.hs
bsd-2-clause
102
0
7
18
29
16
13
4
1
-- | Maintainer: Jelmer Vernooij <[email protected]> module Propellor.Property.Logcheck ( ReportLevel (Workstation, Server, Paranoid), Service, defaultPrefix, ignoreFilePath, ignoreLines, installed, ) where import Propellor.Base import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.File as File data ReportLevel = Workstation | Server | Paranoid type Service = String instance Show ReportLevel where show Workstation = "workstation" show Server = "server" show Paranoid = "paranoid" -- The common prefix used by default in syslog lines. defaultPrefix :: String defaultPrefix = "^\\w{3} [ :[:digit:]]{11} [._[:alnum:]-]+ " ignoreFilePath :: ReportLevel -> Service -> FilePath ignoreFilePath t n = "/etc/logcheck/ignore.d." ++ (show t) </> n ignoreLines :: ReportLevel -> Service -> [String] -> Property NoInfo ignoreLines t n ls = (ignoreFilePath t n) `File.containsLines` ls `describe` ("logcheck ignore lines for " ++ n ++ "(" ++ (show t) ++ ")") installed :: Property NoInfo installed = Apt.installed ["logcheck"]
np/propellor
src/Propellor/Property/Logcheck.hs
bsd-2-clause
1,063
14
10
158
276
160
116
27
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Graphomania.Shumov.Offheap ( readShumov , offheapVertices ) where import Control.DeepSeq import Control.Lens.Fold import Control.Lens.Internal.Getter import Control.Monad.Primitive import Control.Monad.ST import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.Int import Data.MonoTraversable import GHC.Generics (Generic) import Offheap.Get newtype ShumovOffheap = ShumovOffheap { unShumov :: ByteString } deriving (Generic) instance NFData ShumovOffheap data ShumovVertexOffheap = ShumovVertexOffheap { _idSize :: !Int16 , _edgeCount :: !Int32 } deriving ( Show, Eq, Ord ) type instance Element ShumovOffheap = ShumovVertexOffheap instance MonoFoldable ShumovOffheap where {-# INLINE ofoldr #-} ofoldr f z = go z . unShumov where go z s | BS.null s = z | otherwise = let (x, xs) = runGetStrict getShumovVertexOffheap s in f x (go z xs) ofoldMap = error "Data.Graph.Shumov.ofoldMap" ofoldr1Ex = error "Data.Graph.Shumov.ofoldr1Ex" ofoldl1Ex' = error "Data.Graph.Shumov.ofoldl1Ex'" {-# INLINE ofoldl' #-} ofoldl' f v = go v . unShumov where go !a !s | BS.null s = a | otherwise = let (x, xs) = runGetStrict getShumovVertexOffheap s in go (f a x) xs {-# INLINE ofoldlM #-} ofoldlM f v = go v . unShumov where go !a !s | BS.null s = pure a | otherwise = let (x, xs) = runGetStrict getShumovVertexOffheap s in f a x >>= flip go xs runGetStrict :: Get (ST s) a -> ByteString -> (a, ByteString) runGetStrict get bs = unsafeInlineST (runByteString get bs) getShumovVertexOffheap :: Get (ST s) ShumovVertexOffheap getShumovVertexOffheap = do idSize <- getInt16Host skip (fromIntegral idSize) edgeCount <- getInt32Host skip (fromIntegral (edgeCount * 10)) return $ ShumovVertexOffheap idSize edgeCount readShumov :: FilePath -> IO ShumovOffheap readShumov = fmap ShumovOffheap . BS.readFile -- TODO: Check lens performance type FoldShumovOffheap = Fold ShumovOffheap ShumovVertexOffheap {-# INLINE offheapVertices #-} offheapVertices :: FoldShumovOffheap offheapVertices f = go . unShumov where go s | BS.null s = noEffect | otherwise = let (x, xs) = runGetStrict getShumovVertexOffheap s in f x *> go xs
schernichkin/BSPM
graphomania/src/Graphomania/Shumov/Offheap.hs
bsd-3-clause
2,956
0
13
826
720
368
352
73
1
module Parse.Module (moduleDef, getModuleName, imports) where import Control.Applicative ((<$>), (<*>)) import Data.List (intercalate) import Text.Parsec hiding (newline,spaces) import Parse.Helpers import SourceSyntax.Module (ImportMethod(..), Imports) varList :: IParser [String] varList = commaSep1 (var <|> parens symOp) getModuleName :: String -> Maybe String getModuleName source = case iParse getModuleName source of Right name -> Just name Left _ -> Nothing where getModuleName = do optional freshLine (names, _) <- moduleDef return (intercalate "." names) moduleDef :: IParser ([String], [String]) moduleDef = do try (reserved "module") whitespace names <- dotSep1 capVar <?> "name of module" whitespace exports <- option [] (parens varList) whitespace <?> "reserved word 'where'" reserved "where" return (names, exports) imports :: IParser Imports imports = option [] ((:) <$> import' <*> many (try (freshLine >> import'))) import' :: IParser (String, ImportMethod) import' = do reserved "import" whitespace name <- intercalate "." <$> dotSep1 capVar (,) name <$> option (As name) method where method :: IParser ImportMethod method = try $ do whitespace as' <|> importing' as' :: IParser ImportMethod as' = do reserved "as" whitespace As <$> capVar <?> "alias for module" importing' :: IParser ImportMethod importing' = parens (choice [ const (Hiding []) <$> string ".." , Importing <$> varList ] <?> "listing of imported values (x,y,z)")
deadfoxygrandpa/Elm
compiler/Parse/Module.hs
bsd-3-clause
1,666
0
16
424
535
271
264
48
2
{-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} module Compile.Compile where import Bytecode.Definition import Bytecode.Instruction import Bytecode.Primitive import Compile.Recapture import Compile.SimpleLambda import Compile.Variable import Syntax.Ast import Bound import Control.Applicative import Control.Monad.Except import Control.Monad.State import Control.Monad.Writer import qualified Data.Set as Set import qualified Data.Text as Text import qualified Data.Traversable as Traversable newtype Compile a = Compile { unCompile :: Except String a } deriving ( Functor, Applicative, Monad , MonadError String ) compile :: [Declaration] -> Compile ([SimpleLambda], [Definition Symbol]) compile declarations = do when (Set.size symbolsInScope /= length symbolsInScopeList) $ throwError "Duplicate symbolsl" simpleLambdas <- concat <$> mapM (toSimpleLambdas allSymbolsInScope) declarations definitions <- mapM toDefinition simpleLambdas return (simpleLambdas, definitions) where symbolsInScopeList = map (\(FunctionDeclaration ident _) -> ident) declarations symbolsInScope = Set.fromList symbolsInScopeList allSymbolsInScope = symbolsInScope `Set.union` primitiveSymbols primitiveSymbols = Set.fromList $ definitionSymbol <$> primitives liftEither :: Either String a -> Compile a liftEither e = Compile $ ExceptT (return e) runCompile :: Compile a -> Either String a runCompile (Compile e) = runExcept e toSimpleLambdas :: Set.Set Text.Text -> Declaration -> Compile [SimpleLambda] toSimpleLambdas symbolsInScope (FunctionDeclaration identifier topExpr) = do let recapturedExpr = lambdaLift (recapture topExpr) resolvedExpr <- resolveSymbols symbolsInScope recapturedExpr let (lambdas, _newCounter) = toSimpleLambdas' 0 resolvedExpr return lambdas where createSymbol counter = identifier <> Text.pack (replicate counter '\\') toSimpleLambdas' :: Int -> Exp Int Variable -> ([SimpleLambda], Int) toSimpleLambdas' counter expr = case expr of Lam args e -> let (body, others, newCounter) = toSimpleLambdaBody (counter + 1) (instantiate (Var . Captured) e) in (SimpleLambda (createSymbol counter) (length args) body : others, newCounter) _ -> let (body, others, newCounter) = toSimpleLambdaBody (counter + 1) expr in (SimpleLambda (createSymbol counter) 0 body : others, newCounter) toSimpleLambdaBody :: Int -> Exp Int Variable -> (SimpleLambdaBody, [SimpleLambda], Int) toSimpleLambdaBody counter expr = case expr of Var variable -> (SimpleVar variable, [], counter) Lam{} -> let (lambdas, newCounter) = toSimpleLambdas' counter expr in (SimpleVar $ External (createSymbol counter), lambdas, newCounter) App expr0 expr1 -> let (body0, others0, newCounter0) = toSimpleLambdaBody counter expr0 (body1, others1, newCounter1) = toSimpleLambdaBody newCounter0 expr1 in (SimpleApp body0 body1, others0 <> others1, newCounter1) Lit int -> (SimpleLit int, [], counter) data TopStackThunkType = TopStackThunkAddr | TopStackThunkValue deriving (Show) expectThunkValue :: (TopStackThunkType, [Instruction Symbol]) -> Compile [Instruction Symbol] expectThunkValue (TopStackThunkValue, instrs) = return instrs expectThunkValue _ = throwError "expectThunkValue: got thunk addr" toThunkAddr :: (TopStackThunkType, [Instruction Symbol]) -> [Instruction Symbol] toThunkAddr (TopStackThunkValue, instrs) = instrs ++ [CreateThunk] toThunkAddr (TopStackThunkAddr, instrs) = instrs toThunkValue :: (TopStackThunkType, [Instruction Symbol]) -> [Instruction Symbol] toThunkValue (TopStackThunkValue, instrs) = instrs toThunkValue (TopStackThunkAddr, instrs) = instrs ++ [Whnf] -- the returned arguments are in reverse order (the rightmost is the first in the list) flattenApplication :: SimpleLambdaBody -> (SimpleLambdaBody, [SimpleLambdaBody]) flattenApplication (SimpleApp expr0 expr1) = let (headExpr, args) = flattenApplication expr0 in (headExpr, expr1 : args) flattenApplication expr = (expr, []) toDefinition :: SimpleLambda -> Compile (Definition Symbol) toDefinition (SimpleLambda lambdaName arity topLambdaBody) = Definition lambdaName <$> defBody where defBody | arity /= 0 = do closureCreated <- toThunkValue <$> topLevelToBytecode topLambdaBody return $ DefinitionBodyLambda arity $ map Cont $ reverse $ closureCreated <> [Enter 0, Shift arity] | otherwise = DefinitionBodyCaf <$> (expectThunkValue =<< topLevelToBytecode topLambdaBody) topLevelToBytecode :: SimpleLambdaBody -> Compile (TopStackThunkType, [Instruction Symbol]) topLevelToBytecode body = let (ret, stackOffset) = runState (toBytecode body) 0 in do when (stackOffset /= 1) $ throwError ("Stack offset is " <> show stackOffset <> "\n" <> show ret) return ret toBytecode :: SimpleLambdaBody -> State Int (TopStackThunkType, [Instruction Symbol]) toBytecode lambdaBody = case lambdaBody of SimpleApp{} -> do let (headExpr, args) = flattenApplication lambdaBody argBytecodes <- forM args $ \arg -> toThunkAddr <$> toBytecode arg headBytecode <- toThunkAddr <$> toBytecode headExpr let argN = length args modify (\stackOffset -> stackOffset - argN) return ( TopStackThunkValue , concat argBytecodes -- push argument thunks onto stack <> headBytecode -- evaluate head <> [CreateClosure argN] -- create closure ) SimpleVar variable -> do code <- case variable of Captured n -> do stackOffset <- get return [Push (PushableStackElem (n + stackOffset))] External symbol -> do return [Push (PushableKnownThunk symbol)] modify (+ 1) return (TopStackThunkAddr, code) SimpleLit lit -> do modify (+ 1) return (TopStackThunkValue, [Push (PushableImmediate lit)]) resolveSymbols :: Set.Set Text.Text -> Exp Int Identifier -> Compile (Exp Int Variable) resolveSymbols symbolsInScope expr = Traversable.forM expr $ \ident -> do -- when (ident `Set.notMember` symbolsInScope) $ throwError $ "Cannot resolve symbol " <> show ident return (External ident) getArity :: Exp Int a -> Int getArity (Lam is _) = length is getArity _ = 0
exFalso/lambda
src/lib/Compile/Compile.hs
bsd-3-clause
6,710
0
24
1,480
1,888
968
920
125
5
{-# LANGUAGE QuasiQuotes, LambdaCase, RecordWildCards #-} module ExampleSpec where import Wrecker import qualified Wrecker.Statistics as Stats import Test.Hspec import qualified Server as Server import qualified Client as Client import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as H import Control.Concurrent import Network.Wai.Handler.Warp (Port) import Data.Maybe (fromJust) import Control.Concurrent.NextRef (NextRef) import qualified Control.Concurrent.NextRef as NextRef import Control.Applicative {- This file tests how well `wrecker` can detect a "signal". Essentially we increase the time of server and see how close `wrecker` gets to detecting the increase. The precision of `threadDelay` is not great at least for small values. So we record the actual times on the server and compare against the measured values. The model we use client observed time(delay) = travel time + server overhead + request time(delay) We call `travel time + server overhead` `overhead` and compute it by measuring overhead = client observed time(~ 0) - request time(~ 0) We assume that `overhead` is the same regardless of the delays injected to slow down `request time`. (this appears to be false unfortunately). Then we compare client observed time(10 milliseconds) - overhead ~ recorded from the server(10 millisecond delay) Telling the server to sleep 10 milliseconds actually slows it down around 12 FWIW. `wrecker` is consistently overestimating the times. I don't know if this an issue with wrecker or something about the interplay between delaying the request and the travel time or the server overhead. There are many issues with this "test". The the number of iterations should be based on some statistically stopping conditioning. Additionally the `Approx` equality should really be something like a statistical test. The gc is an issue for getting good data. Running with -I0 helps, -qg might? -} sleepAmount :: Int -- microseconds sleepAmount = 10000 -- 10 milliseconds data Gaussian = Gaussian { mean :: Double , variance :: Double } deriving (Show, Eq) subtractGaussian :: Gaussian -> Gaussian -> Gaussian subtractGaussian x y = Gaussian (mean x - mean y) (variance x - variance y) urlStatsToDist :: HashMap String ResultStatistics -> Server.Root Gaussian urlStatsToDist stats = let gaussians = map (\(key, value) -> ( Stats.urlToPathPieceKey key , toDist value ) ) $ H.toList stats Just root = lookup "/root" gaussians Just products = lookup "/products" gaussians Just login = lookup "/login" gaussians Just usersIndex = lookup "/users/0" gaussians Just cartsIndex = lookup "/carts/0" gaussians Just cartsIndexItems = lookup "/carts/0/items" gaussians Just checkout = lookup "/checkout" gaussians in Server.Root {..} substractDist :: Server.Root Gaussian -> Server.Root Gaussian -> Server.Root Gaussian substractDist x y = Server.Root { Server.root = subtractGaussian (Server.root x) (Server.root y) , Server.products = subtractGaussian (Server.products x) (Server.products y) , Server.login = subtractGaussian (Server.login x) (Server.login y) , Server.usersIndex = subtractGaussian (Server.usersIndex x) (Server.usersIndex y) , Server.cartsIndex = subtractGaussian (Server.cartsIndex x) (Server.cartsIndex y) , Server.cartsIndexItems = subtractGaussian (Server.cartsIndexItems x) (Server.cartsIndexItems y) , Server.checkout = subtractGaussian (Server.checkout x) (Server.checkout y) } -- Create a distribution for sleeping rootDistribution :: Server.RootInt rootDistribution = pure sleepAmount main :: IO () main = hspec spec toDist :: ResultStatistics -> Gaussian toDist x = let stats = rs2xx x in Gaussian (Stats.mean stats) (Stats.variance stats) class Approx a where approx :: a -> a -> Bool instance Approx Double where approx x y = abs (x - y) < 0.001 instance Approx Gaussian where approx x y = approx (mean x) (mean y) && approx (variance x) (variance y) instance Approx a => Approx (Server.Root a) where approx x y = approx (Server.root x) (Server.root y) && approx (Server.products x) (Server.products y) && approx (Server.cartsIndex x) (Server.cartsIndex y) && approx (Server.cartsIndexItems x) (Server.cartsIndexItems y) && approx (Server.usersIndex x) (Server.usersIndex y) && approx (Server.checkout x) (Server.checkout y) && approx (Server.login x) (Server.login y) runWrecker :: Int -> IO AllStats runWrecker port = do let key = "key" fromJust . H.lookup key <$> Wrecker.run (defaultOptions { runStyle = RunCount 200 , concurrency = 1 , displayMode = Interactive } ) [ (key, Client.testScript port) ] calculateOverhead :: IO (Server.Root Gaussian) calculateOverhead = do (port, _, threadId, ref) <- Server.run $ pure 1 allStats <- runWrecker port -- This how long a 'null' request takes serverStats <- NextRef.readLast ref putStrLn $ Stats.pprStats Nothing Path serverStats killThread threadId return $ substractDist (urlStatsToDist $ aPerUrl allStats ) (urlStatsToDist $ aPerUrl serverStats) start :: IO (Port, ThreadId, Server.Root Gaussian, NextRef AllStats) start = do overhead <- calculateOverhead (port, _, threadId, ref) <- Server.run rootDistribution return (port, threadId, overhead, ref) stop :: (Port, ThreadId, Server.Root Gaussian, NextRef AllStats) -> IO () stop (_, threadId, _, _) = killThread threadId shouldBeApprox :: (Show a, Approx a) => a -> a -> IO () shouldBeApprox x y = shouldSatisfy (x, y) (uncurry approx) spec :: Spec spec = beforeAll start $ afterAll stop $ describe "Wrecker" $ it "measure requests somewhat accurately" $ \(port, _, overhead, ref) -> do allStats <- urlStatsToDist . aPerUrl <$> runWrecker port expectedDist <- urlStatsToDist . aPerUrl <$> NextRef.readLast ref let adjustedDist = substractDist allStats overhead adjustedDist `shouldBeApprox` expectedDist
skedgeme/wrecker
test/ExampleSpec.hs
bsd-3-clause
6,978
0
15
2,055
1,565
803
762
108
1
{-# LANGUAGE FlexibleContexts, RankNTypes #-} module Cloud.AWS.CloudWatch ( -- * CloudWatch Environment CloudWatch , runCloudWatch , runCloudWatchwithManager , setRegion , apiVersion -- * Metric , module Cloud.AWS.CloudWatch.Metric , module Cloud.AWS.CloudWatch.Alarm ) where import Data.Text (Text) import Control.Monad.IO.Class (MonadIO) import qualified Control.Monad.State as State import Control.Monad.Trans.Resource (MonadResource, MonadBaseControl) import qualified Network.HTTP.Conduit as HTTP import Data.Monoid ((<>)) import Cloud.AWS.Class import Cloud.AWS.Lib.Query (textToBS) import Cloud.AWS.CloudWatch.Internal import Cloud.AWS.CloudWatch.Metric import Cloud.AWS.CloudWatch.Alarm initialCloudWatchContext :: HTTP.Manager -> AWSContext initialCloudWatchContext mgr = AWSContext { manager = mgr , endpoint = "monitoring.amazonaws.com" , lastRequestId = Nothing } runCloudWatch :: MonadIO m => CloudWatch m a -> m a runCloudWatch = runAWS initialCloudWatchContext runCloudWatchwithManager :: Monad m => HTTP.Manager -> AWSSettings -> CloudWatch m a -> m a runCloudWatchwithManager mgr = runAWSwithManager mgr initialCloudWatchContext setRegion :: (MonadBaseControl IO m, MonadResource m) => Text -> CloudWatch m () setRegion region = do ctx <- State.get State.put ctx { endpoint = "monitoring." <> textToBS region <> ".amazonaws.com" }
worksap-ate/aws-sdk
Cloud/AWS/CloudWatch.hs
bsd-3-clause
1,472
0
12
280
344
202
142
40
1
module Pkgs.Parser ( parse, parseAll, parsePkg, parseIface ) where import Data.Maybe (isJust, fromMaybe) import Data.Either (partitionEithers) import Control.Monad import Control.Applicative ((<$>), (<*>)) import Text.Parsec import Text.Parsec.String -- import Text.Parser.Char (char) import Text.Parsec.Prim import Text.Parsec.Combinator import Pkgs.Syntax ---------------------------------------------------------------------- -- Parse Packages and Terms -- ---------------------------------------------------------------------- parseAll :: Parser [Toplevel] parseAll = many1 (liftM P parsePkg <|> liftM I parseIface) <* eof parsePkg :: Parser PkgTerm parsePkg = Pkg <$> (stringWS "pkg" *> parsePVName) <*> parseArgs parseParam <*> parseImpl <*> parsePBody parseArgs :: Parser a -> Parser [a] parseArgs p = liftM (fromMaybe []) $ optionMaybe $ parens $ argList p parseImpl :: Parser IVName parseImpl = stringWS "impl" *> parseIVName -- parsePBody :: Parser PBody -- parsePBody = braces $ liftM2 PBody (bodyList parseImport <* sep) -- (bodyList parseDef) parsePBody = braces $ do eithers <- bodyList (liftM Left parseImport <|> liftM Right parseDef) let (imports, defs) = partitionEithers eithers return $ PBody imports defs parseImport :: Parser PImport parseImport = PImport <$> (stringWS "import" >> parsePName) <*> (charWS ':' *> parseIVName) <*> (stringWS "as" *> parsePExpr) parsePExpr :: Parser PExpr parsePExpr = PExpr <$> parsePName <*> do args <- parseArgs parseName return $ map Var args parseDef :: Parser Def parseDef = parseTyDef <|> parseFunDef parseTyDef = TypeDef <$> (stringWS "type" *> parseName) <*> (stringWS "=" *> parseType) parseFunDef = FunDef <$> (stringWS "fun" *> parseVarName) <*> (stringWS ":" *> parseType) <*> (stringWS "=" *> parseExpr) parseExpr :: Parser Expr parseExpr = do expr1 <- parseLam <|> parseVarOrProj <|> parseIntVal <|> parseUnit <|> parens parseExpr appExpr <- optionMaybe parseExpr addExpr <- optionMaybe (charWS '+' *> parseExpr) return $ case (appExpr, addExpr) of (Just expr2, Nothing) -> App expr1 expr2 (Nothing, Just expr2) -> Plus expr1 expr2 (Nothing, Nothing) -> expr1 parseVarOrProj = do var <- parseVarName isDot <- liftM isJust $ optionMaybe $ char '.' if isDot then Proj (Var var) <$> parseVarName else return $ Var var parseLam = Lam <$> (charWS '\\' *> charWS '(' *> parseVarName) <*> (charWS ':' *> parseType <* charWS ')') <*> (charWS '.' *> parseExpr) parseProj = Proj <$> (Var <$> parsePVar) <*> (charWS '.' >> parseVarName) parseVar = Var <$> parseVarName parseIntVal = IntVal <$> int parseUnit = stringWS "unit" >> return Unit :: Parser Expr ---------------------------------------------------------------------- -- Parse Interfaces and Types -- ---------------------------------------------------------------------- parseIface :: Parser IfaceTerm parseIface = Iface <$> (stringWS "iface" *> parseIVName) <*> parseArgs parseParam <*> parseSubType <*> parseIBody parseParam :: Parser PArg parseParam = PArg <$> (parseName <* stringWS ":") <*> parseIExpr parseIExpr :: Parser IExpr parseIExpr = IExpr <$> parseIVName <*> parseArgs parseName parseSubType :: Parser (Maybe IVName) parseSubType = optionMaybe (stringWS "<:" >> parseIVName) parseIBody :: Parser IBody parseIBody = IBody <$> braces (bodyList parseDecl) parseDecl :: Parser Decl parseDecl = parseTyDecl <|> parseFunDecl parseTyDecl = TypeDecl <$> (stringWS "type" >> parseName) parseFunDecl = FunDecl <$> (stringWS "fun" >> parseName) <*> (charWS ':' >> parseType) parseType :: Parser Type parseType = do ty <- parseIntType <|> parseUnitType <|> parseTypeNameOrProj <|> parens parseType isArrow <- liftM isJust $ optionMaybe (stringWS "->") if isArrow then Arrow ty <$> parseType else return ty parseTypeNameOrProj = do name <- parseName isDot <- liftM isJust $ optionMaybe $ char '.' if isDot then ProjType name <$> parseTyName else return $ TypeName name parseTypeName = TypeName <$> parseTyName parseIntType = stringWS "Int" >> return IntType :: Parser Type parseUnitType = stringWS "Unit" >> return UnitType :: Parser Type ---------------------------------------------------------------------- -- Naming and Versioning -- ---------------------------------------------------------------------- data Version = Version Int Int instance Show Version where show (Version x y) = "v" ++ show x ++ "." ++ show y parsePVName :: Parser IVName parsePVName = do name <- many1 letter char '-' version <- parseVersion return $ name ++ "-" ++ show version parseName :: Parser VarName parseName = do l <- letter rest <- many (letter <|> digit) spaces return (l:rest) parsePVar = parseName parseVarName = parseName parseTyName = parseName parsePName = parseName parseIVName = parsePVName parseVersion :: Parser Version parseVersion = do char 'v' x <- int y <- optionMaybe (charWS '.' >> int) return $ case y of Just y' -> Version x y' Nothing -> Version x 0 --------------------------- -- helpers bodyList :: Parser a -> Parser [a] bodyList p = p `sepBy` sep sep = optional $ charWS ';' enclosing :: Char -> Char -> Parser a -> Parser a enclosing left right parse = charWS left *> parse <* charWS right parens = enclosing '(' ')' braces = enclosing '{' '}' argList :: Parser a -> Parser [a] argList p = p `sepBy` charWS ',' int :: Parser Int int = read <$> (many1 digit <* spaces) charWS :: Char -> Parser Char charWS c = char c <* spaces stringWS :: String -> Parser () stringWS s = string s >> spaces
markflorisson/packages
Pkgs/Parser.hs
bsd-3-clause
6,245
0
12
1,623
1,766
889
877
138
3
module RPF.Domain where import Data.Map (Map) import qualified Data.Map as M hiding (Map) import Data.Maybe import Network.DNS.Types (Domain) type DomainTable = Map Domain Bool domainMatch :: Domain -> DomainTable -> Bool domainMatch dom = fromMaybe False . M.lookup dom makeDomainTable :: [Domain] -> DomainTable makeDomainTable ds = M.fromList $ zip ds (repeat True)
kazu-yamamoto/rpf
RPF/Domain.hs
bsd-3-clause
376
0
8
60
127
71
56
10
1
{- A module containing additional functions for printing. In particular, this includes functions for producing SMT-LIB output that can be processed by Z3 -} module HOCHC.Printing(printOut,pprint,printInd,smtPrint,smtPrint2,printEnv,printLog, deand,printLong) where import Data.List import HOCHC.DataTypes import HOCHC.Simplify import HOCHC.Parser(legiblise) import HOCHC.Utils import HOCHC.Transform(vlist,slist,occursIn,split') base :: Term -> Variable base (Apply a b) = base a base (Variable x) = x base other = error ("Printing.hs, base: \n" ++ show other) smtPrint :: ((DeltaEnv,Gamma,Term,Term),Bool) -> String smtPrint ((d,g,t,gt),s) = legiblise (unlines [ "(echo \"a result of unsat means that there is a model for the program clauses in which the goal clause does not hold\")", unlines $ map smtDecFun (d++[("goal_",Bool)]), smtTerm' (t `aand` aimplies gt (Variable "goal_")), "(query goal_"++(if s then "" else " :print-certificate true")++")" ]) smtl smtl = [ ("and","∧"), ("=>","⇒"), ("or","∨"), ("not","¬")] smtDecFun :: (Variable,Sort) -> String smtDecFun (v,s) = "(declare-rel {} ({}))" % [v, intercalate " " $ map prnS ss] where (ss,Bool) = fromRight $ slist s smtTerm' :: Term -> String smtTerm' t = unlines $ map (\(x,Int) -> "(declare-var {} Int)" % [x]) vss ++ map (\ t -> "(rule {})" % [smtTerm t]) ts where (t',vss) = pullOutAllQuantifiers True t ts = deand t' deand :: Term -> [Term] deand (Apply (Apply (Constant "∧") t1) t2) = deand t1 ++ deand t2 deand t = [t] smtTerm :: Term -> String smtTerm (Apply (Apply (Constant c) t1) t2) | c == "≠" = "(not (= {} {}))"%[smtTerm t1, smtTerm t2] | c `elem` binaryOps = "({} {} {})"%[c, smtTerm t1, smtTerm t2] smtTerm (Apply (Constant c) t) | c `elem` logicalUnary = "({} {})"%[c, smtTerm t] | c `elem` logicalQuantifiers = case (c,t) of ("∀",(Lambda x Int body)) -> "(forall (({} Int))\n {})"%[x,smtTerm body] _ -> error "bad quantifier" smtTerm (Lambda a s body) = error "unquantified lambda" smtTerm (Variable v) = v smtTerm (Constant c) = c smtTerm (Apply a b) = "({} {})"% [smtApp a,smtTerm b] smtApp (Apply a b) = "{} {}"% [smtApp a,smtTerm b] smtApp x = smtTerm x -- Prints conjunctive terms on separate lines printLong :: Term -> String printLong (Apply (Apply (Constant "∧") t1) t2) = printLong t1 ++ '\n':printLong t2 printLong x = prnt x --prints conjunctive terms on separate lines and indents foralls printInd' :: Int -> [(Variable,Sort)] -> Term -> String printInd' n vss (Apply (Constant "∀") (Lambda x s t)) = printInd' n ((x,s):vss) t printInd' n (vs:vss) t = replicate n ' ' ++'∀':intercalate "," (map (\(v,s)->"{}:{}"%[v,prns s])(vs:vss)) ++ "\n" ++ printInd' (n+2+2*length vss) [] t printInd' n [] (Apply (Apply (Constant "∧") t1) t2) = printInd' n [] t1 ++ '\n':printInd' n [] t2 printInd' n [] x = replicate n ' ' ++ prnt x printOut = printLong.simp.stripQuantifiers printInd = printInd' 0 [] pprint = putStrLn.printLong.simp.stripQuantifiers smtPrint2:: ((DeltaEnv,Gamma,Term,Term),Bool) -> String smtPrint2 ((d,g,t,gt),s) = legiblise (unlines [ "(set-logic HORN)", unlines $ map smtDecFun2 d, smtTerm2' (pullOutAllQuantifiers True t), let (t,qs)=(pullOutAllQuantifiers False gt) in smtTerm2' (aimplies t (Constant "false"), qs), "(echo \"a result of sat means that there is a model for the program clauses in which the goal clause does not hold\")", "(check-sat)", (if s then "" else "(get-model)") ]) smtl smtDecFun2 :: (Variable,Sort) -> String smtDecFun2 (v,s) = "(declare-fun {} ({}) {})" % [v, intercalate " " $ map prnS ss, prnS sb] where (ss,sb) = fromRight $ slist s smtTerm2' :: (Term,[(String,Sort)]) -> String smtTerm2' (t,[]) = "(assert {})" % [smtTerm t] smtTerm2' (t,d) = unlines $ map (\ t -> "(assert (forall ({}) {}))" % [concatMap (\(x,y) -> "({} {})"%[x,prnS y]) (filter ((`occursIn` t) . fst) d), smtTerm t]) ts where ts = deand t --logic program format - suitable for Long's defunctionalisation printLog :: (DeltaEnv,Term,Term) -> String printLog (d,t,g) = unlines[ "environment", printEnv d, "program", unlines$ map (printLogLine d)$ deand t, "goal", show$ removeNeq g] printLogLine :: DeltaEnv -> Term -> String printLogLine d clause = let Right (body,(args,n)) = split' clause Just s = lookup n d in "{} := {};"%[n, foldr (\(v,s) b -> ("\\\\{} : {}. "%[v,prns s])++b) (show$ removeNeq body) (zip args$ fst$ fromRight$ slist s)] printEnv :: DeltaEnv -> String printEnv [] = "" printEnv (("main",_):d) = printEnv d printEnv ((v,s):d) = v++" : "++prns s++"\n"++ printEnv d removeNeq :: Term -> Term removeNeq (Apply (Apply (Constant "≠") a) b) = let app2 c = (Apply (Apply (Constant c) a) b) in aor (app2 "<") (app2 ">") removeNeq (Constant "false") = aequals (Constant "1") (Constant "0") removeNeq (Constant "true") = aequals (Constant "1") (Constant "1") removeNeq t = appdown removeNeq t
penteract/HigherOrderHornRefinement
HOCHC/Printing.hs
bsd-3-clause
5,049
0
16
980
2,173
1,159
1,014
101
2
module Wyas.EvalSpec where import Test.QuickCheck import Test.Hspec import Wyas import Wyas.Eval spec :: Spec spec = return ()
parsonsmatt/wyas
test/Wyas/EvalSpec.hs
bsd-3-clause
130
0
6
21
39
23
16
7
1
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-} {-| Module : PolyPaver.Input.SPARK Description : parser of SPARK vcg and siv files Copyright : (c) Michal Konecny, Jan Duracz License : BSD3 Maintainer : [email protected] Stability : experimental Portability : portable Parser of TPTP files as PolyPaver problems. Based on http://www.cs.miami.edu/~tptp/TPTP/SyntaxBNF.html. -} module PolyPaver.Input.TPTP ( parseTPTP ) where import PolyPaver.Form import PolyPaver.Input.Misc (withConsumed, removeDisjointHypothesesAddBox, traceRuleDoIt) import Data.Char (ord, isUpper, isLower, isSpace) import qualified Data.List as List (partition) import Text.Parsec import Text.Parsec.String (Parser) import Text.Parsec.Token import Text.Parsec.Expr (buildExpressionParser, Operator(..), Assoc(..)) --import Text.Parsec.Prim import Text.Parsec.Language (emptyDef) import Data.Functor.Identity (Identity) import Data.Maybe (catMaybes) import Debug.Trace (trace) _ = trace -- prevent unused import warning _ = traceRuleDoIt traceRule :: String -> Parser a -> Parser a traceRule _ = id --traceRule = traceRuleDoIt parseTPTP :: String {-^ description of the source (eg file name) for error reporting -} -> String {-^ the contents of the TPTP file -} -> [(String, Form (), [(Int, (Rational, Rational), Bool)])] {-^ the formula and the bounding box for its variables -} parseTPTP sourceDescription s = case parse tptp_file sourceDescription s of Right formulas -> map removeDisjointHypothesesAddBox $ mergeHypothesesIntoConjectures $ map insertNameToForm formulas Left err -> error $ "parse error in " ++ show err where insertNameToForm (name, formrole, form) = (name, formrole, insertLabel name form) mergeHypothesesIntoConjectures formulas = map addHypotheses conjecturesNRF where addHypotheses (name, "negated_conjecture", anticonj) = (name, joinHypothesesAndConclusion (hypotheses, Not anticonj)) addHypotheses (name, _formrole, conj) = (name, joinHypothesesAndConclusion (hypotheses, conj)) hypotheses = map dropNameRole hypothesesNRF where dropNameRole (_name , _formrole , form) = form (hypothesesNRF, conjecturesNRF) = List.partition canAssume formulas where canAssume (_name, formrole, _form) = formrole `elem` ["axiom", "hypothesis", "definition", "assumption", "fi_domain", "fi_functors", "fi_predicates", "type"] tptp_file :: Parser [(String, String, Form ())] tptp_file = traceRule ("tptp_file") $ do maybeFormulas <- many1 tptp_input optional m_whiteSpace eof return $ catMaybes maybeFormulas tptp_input :: Parser (Maybe (String, String, Form ())) tptp_input = traceRule ("tptp_input") $ do optional m_whiteSpace (include <|> (fmap Just annotated_formula)) include :: Parser (Maybe a) include = traceRule ("include") $ do (_, original) <- withConsumed includeAux trace ("Warning: ignoring " ++ original) $ return Nothing where includeAux = do string "include" m_parens term m_dot return Nothing annotated_formula :: Parser (String, String, Form ()) annotated_formula = traceRule ("annotated_formula") $ ((try thf_annotated) <|> (try tff_annotated) <|> fof_annotated <|> cnf_annotated <|> tpi_annotated) tpi_annotated, thf_annotated, tff_annotated, fof_annotated, cnf_annotated :: Parser (String, String, Form ()) tpi_annotated = formula_annotated "tpi" fof_formula_allow_quant thf_annotated = formula_annotated "thf" $ parserFail "thf not supported" tff_annotated = formula_annotated "tff" $ parserFail "tff not supported" fof_annotated = formula_annotated "fof" fof_formula_allow_quant cnf_annotated = formula_annotated "cnf" $ parserFail "cnf not supported" formula_annotated :: String -> Parser (Form ()) -> Parser (String, String, Form ()) formula_annotated flavour formulaParser = traceRule ("formula_annotated " ++ flavour) $ do optional m_whiteSpace string flavour string "(" name <- m_identifier m_comma -- trace ("name = " ++ name) $ return () formrole <- formula_role m_comma -- trace ("formrole = " ++ formrole) $ return () form <- formulaParser optional annotations m_symbol ")" m_dot return (name, formrole, form) annotations :: Parser a annotations = traceRule ("annotations") $ do m_comma parserFail "annotations not supported" formula_role :: Parser String formula_role = choice $ map try $ map string $ ["axiom", "hypothesis", "definition", "assumption", "lemma", "theorem", "conjecture", "negated_conjecture", "plain", "fi_domain", "fi_functors", "fi_predicates", "type", "unknown"] fof_formula_allow_quant :: Parser (Form ()) fof_formula_allow_quant = traceRule ("fof_formula_allow_quant") $ (try fof_logic_formula_allow_quant <|> fof_sequent) fof_sequent :: Parser (Form ()) fof_sequent = traceRule ("fof_sequent") $ do string "[" parserFail "fof_sequent not supported" fof_logic_formula_allow_quant :: Parser (Form ()) fof_logic_formula_allow_quant = traceRule ("fof_logic_formula_allow_quant") $ (try fof_binary_formula <|> fof_unitary_formula_allow_quant) fof_logic_formula :: Parser (Form ()) fof_logic_formula = traceRule ("fof_logic_formula") $ (try fof_binary_formula <|> fof_unitary_formula) fof_binary_formula :: Parser (Form ()) fof_binary_formula = traceRule ("fof_binary_formula") $ (try fof_binary_nonassoc <|> fof_binary_assoc) fof_binary_nonassoc :: Parser (Form ()) fof_binary_nonassoc = traceRule ("fof_binary_nonassoc") $ do form1 <- fof_unitary_formula optional m_whiteSpace binOp <- binary_connective optional m_whiteSpace form2 <- fof_unitary_formula return $ form1 `binOp` form2 binary_connective :: Parser (Form l -> Form l -> Form l) binary_connective = traceRule ("binary_connective") $ (foldr (<|>) (parserFail "Expecting a TPTP binary logical connective.") $ map connective_parser connectives) where connectives = [("<=>", Nothing), ("=>", Just Implies), -- ("<=", Just (flip Implies)), -- removed to avoid clash with leq ("<~>", Nothing), ("~|", Nothing), ("~&", Nothing)] connective_parser (symb, Nothing) = do try $ m_reservedOp symb parserFail (symb ++ " not supported") connective_parser (symb, Just makeFormula) = do m_reservedOp symb return makeFormula unary_connective :: Parser (Form l -> Form l) unary_connective = traceRule ("unary_connective") $ (foldr (<|>) (parserFail "Expecting a TPTP unary logical connective.") $ map connective_parser connectives) where connectives = [("~", Just Not)] connective_parser (symb, Nothing) = do try $ m_reservedOp symb parserFail (symb ++ " not supported") connective_parser (symb, Just makeFormula) = do m_reservedOp symb return makeFormula fof_binary_assoc :: Parser (Form ()) fof_binary_assoc = traceRule ("fof_binary_assoc") $ (try fof_or_formula) <|> fof_and_formula fof_or_formula :: Parser (Form ()) fof_or_formula = traceRule ("fof_or_formula") $ fof_binary_assoc_op "|" Or fof_and_formula :: Parser (Form ()) fof_and_formula = traceRule ("fof_and_formula") $ fof_binary_assoc_op "&" And fof_binary_assoc_op :: String -> (Form () -> Form () -> Form ()) -> Parser (Form ()) fof_binary_assoc_op opSymbol binOp = traceRule ("fof_binary_assoc_op") $ (try option1) <|> option2 where option1 = do f1 <- fof_unitary_formula m_symbol opSymbol f2 <- fof_unitary_formula return $ f1 `binOp` f2 option2 = do f1 <- fof_unitary_formula -- swapped L<->R in this TPTP rule to remove left recursion m_symbol opSymbol f2 <- fof_binary_assoc_op opSymbol binOp return $ f1 `binOp` f2 fof_unitary_formula_allow_quant :: Parser (Form ()) fof_unitary_formula_allow_quant = traceRule ("fof_unitary_formula_allow_quant") $ (fof_quantified_formula <|> fof_quantified_formula_error "?" <|> try (fof_unary_formula) <|> try (atomic_formula) <|> m_parens fof_logic_formula) fof_unitary_formula :: Parser (Form ()) fof_unitary_formula = traceRule ("fof_unitary_formula") $ (fof_quantified_formula_error "!" <|> fof_quantified_formula_error "?" <|> try (fof_unary_formula) <|> try (atomic_formula) <|> m_parens fof_logic_formula) fof_quantified_formula_error :: String -> Parser (Form ()) fof_quantified_formula_error quantifier = traceRule ("fof_quantified_formula_error " ++ quantifier) $ do m_reservedOp quantifier parserFail $ "quantified formulas not supported, except top level `for all'" undefined fof_quantified_formula :: Parser (Form ()) fof_quantified_formula = traceRule ("fof_quantified_formula") $ do m_reservedOp "!" -- trace ("fof_quantified_formula: `!'") $ return () _vars <- m_brackets fof_variable_list optional m_whiteSpace m_reservedOp ":" -- trace ("fof_quantified_formula: `:'") $ return () optional m_whiteSpace f <- fof_unitary_formula_allow_quant return $ f fof_variable_list :: Parser [String] fof_variable_list = traceRule ("fof_variable_list") $ do optional m_whiteSpace v1 <- m_UpperWord -- originally: variable optional m_whiteSpace maybeVRest <- optionMaybe $ (m_comma >> fof_variable_list) case maybeVRest of Just vRest -> return $ v1 : vRest Nothing -> return [v1] fof_unary_formula :: Parser (Form ()) fof_unary_formula = traceRule ("fof_unary_formula") $ (try option1) <|> option2 where option1 = do upOp <- unary_connective f <- fof_unitary_formula return $ upOp f option2 = fol_infix_unary fol_infix_unary :: Parser (Form ()) fol_infix_unary = traceRule ("fol_infix_unary") $ do tL <- term -- trace ("fol_infix_unary: got term: " ++ show tL) $ return () optional m_whiteSpace m_reservedOp "!=" optional m_whiteSpace tR <- term return $ Neq "" tL tR atomic_formula :: Parser (Form ()) atomic_formula = traceRule ("atomic_formula") $ (try defined_atomic_formula) <|> (try system_term) <|> plain_term defined_atomic_formula :: Parser (Form ()) defined_atomic_formula = traceRule ("defined_atomic_formula") $ (try defined_plain_term) <|> defined_infix_formula system_term :: Parser (Form ()) system_term = traceRule ("system_term") $ do string "$$" parserFail "system_term ($$...) not supported" defined_plain_term :: Parser (Form ()) defined_plain_term = traceRule ("defined_plain_term") $ do string "$" parserFail "defined_plain_term ($...) not supported" defined_infix_formula :: Parser (Form ()) defined_infix_formula = traceRule ("defined_infix_formula") $ do tL <- term -- trace ("defined_infix_formula: got term " ++ show tL) $ return () optional m_whiteSpace relOp <- binary_relation -- trace "defined_infix_formula: `='" $ return () optional m_whiteSpace tR <- term return $ relOp tL tR binary_relation :: Parser (Term l -> Term l -> Form l) binary_relation = traceRule ("binary_relation") $ foldr (<|>) (parserFail "Expecting a TPTP binary relation.") $ map relation_parser relations where relations = [("=", Eq ""), ("<", Le ""), ("<=", Leq ""), (">", Ge ""), (">=", Geq "") ] relation_parser (symb, makeFormula) = do m_reservedOp symb return makeFormula plain_term :: Parser (Form ()) plain_term = -- deviating from TPTP in a manner similar to Metitarski predicate predicate :: Parser (Form ()) predicate = traceRule ("predicate") $ do pname <- m_AtomicWord maybeArgs <- optionMaybe $ m_parens $ sepBy term (m_symbol ",") let args = case maybeArgs of Just args1 -> args1; Nothing -> [] return $ decodePred pname args decodePred :: String -> [Term ()] -> Form () decodePred pname _args = -- error $ "decodePred: unknown predicate " ++ pname IsInt "" (var pname) -- TODO: change IsInt -> IsTrue term :: Parser (Term ()) term = -- deviating from TPTP in a manner similar to Metitarski buildExpressionParser termTable atomicTerm <?> "term" termTable :: [[Operator String () Identity (Term ())]] termTable = [ [prefix "-" negate] , [binary "^" (termOp2 IntPower) AssocLeft] , [binary "**" (termOp2 IntPower) AssocLeft] , [binary "/" (/) AssocLeft] ++ (binaryV ["(/)","/:"] (/:) AssocLeft) , [binary "*" (*) AssocLeft] ++ (binaryV ["(*)","*:"] (*:) AssocLeft) , [binary "-" (-) AssocLeft] ++ (binaryV ["(-)","-:"] (-:) AssocLeft) , [binary "+" (+) AssocLeft] ++ (binaryV ["(+)","+:"] (+:) AssocLeft) ] where binaryV names fun assoc = map (\name -> binary name fun assoc) names binary name fun assoc = Infix (do{ m_reservedOp name; return fun }) assoc prefix name fun = Prefix (do{ m_reservedOp name; return fun }) atomicTerm :: Parser (Term ()) atomicTerm = traceRule ("atomicTerm") $ m_parens term <|> absBrackets term <|> try fncall <|> (try $ fmap (fromRational . toRational) m_float) <|> fmap (fromInteger) m_integer <|> (try $ fmap var m_UpperWord) <|> (try $ fmap constant m_AtomicWord) <|> interval_literal absBrackets :: Num b => Parser b -> Parser b absBrackets p = do m_symbol "|" res <- p m_symbol "|" return $ abs res interval_literal :: Parser (Term ()) interval_literal = do m_symbol "[" lb <- term (m_symbol "," <|> m_symbol "..") ub <- term m_symbol "]" return $ hull lb ub fncall :: Parser (Term ()) fncall = do ((fname, args), original) <- withConsumed $ do fname <- m_AtomicWord args <- m_parens $ sepBy term (m_symbol ",") return (fname, args) return $ decodeFn original fname args var :: String -> Term () var name = termVar n name where n = sum $ zipWith (*) [1..] $ map ord name constant :: String -> Term () constant name = -- trace -- ( -- "\nWarning: treating the term " ++ show name ++ " as a variable\n" ++ -- " because the constant " ++ show name ++ " is not recognised by PolyPaver." -- ) $ var name decodeFn :: String -> String -> [Term ()] -> Term () decodeFn _ "exp" [arg1] = exp arg1 decodeFn _ "sqrt" [arg1] = sqrt arg1 decodeFn _ "eps_rel" [mantissaBitsT, expBitsT] = withPrec (floor mantissaBits) (floor expBits) termOp0 FEpsRel where (Term (Lit mantissaBits, _)) = mantissaBitsT (Term (Lit expBits, _)) = expBitsT decodeFn _ "eps_abs" [mantissaBitsT, expBitsT] = withPrec (floor mantissaBits) (floor expBits) termOp0 FEpsAbs where (Term (Lit mantissaBits, _)) = mantissaBitsT (Term (Lit expBits, _)) = expBitsT decodeFn _ "round" [mantissaBitsT, expBitsT, _roundingModeT, arg] = withPrec (floor mantissaBits) (floor expBits) termOp1 FRound arg where (Term (Lit mantissaBits, _)) = mantissaBitsT (Term (Lit expBits, _)) = expBitsT decodeFn _ "eps_rel_single" [] = withPrec 24 8 termOp0 FEpsRel decodeFn _ "eps_abs_single" [] = withPrec 24 8 termOp0 FEpsAbs decodeFn _ "round_single" [_roundingModeT, arg] = withPrec 24 8 termOp1 FRound arg decodeFn _ "eps_rel_double" [] = withPrec 53 11 termOp0 FEpsRel decodeFn _ "eps_abs_double" [] = withPrec 53 11 termOp0 FEpsAbs decodeFn _ "round_double" [_roundingModeT, arg] = withPrec 53 11 termOp1 FRound arg decodeFn original fn _args = trace ( "\nWarning: treating the term " ++ show originalNoSpaces ++ " as a variable\n" ++ " because the function " ++ show fn ++ " is not recognised by PolyPaver." ) $ var originalNoSpaces where originalNoSpaces = filter (not . isSpace) original withPrec :: Int -> Int -> (s -> t) -> (Int -> Int -> s) -> t withPrec mantissaBits expBits termBuilder op = (termBuilder $ op epsrelE epsabsE) where epsrelE = mantissaBits - 1 -- TODO sharpen this if rounding to nearest epsabsE = 2^(expBits - 1) - 2 m_UpperWord :: Parser String m_UpperWord = do name <- m_identifier if isUpper (head name) then return name else parserFail "Expecting an identifier starting with a upper-case letter." m_LowerWord :: Parser String m_LowerWord = do name <- m_identifier if isLower (head name) then return name else parserFail "Expecting an identifier starting with a lower-case letter." m_AtomicWord :: Parser String m_AtomicWord = m_LowerWord <|> single_quoted where single_quoted = do string "'" name <- many $ noneOf "'\n\r" string "'" return name m_integer :: Parser Integer m_identifier :: Parser String m_symbol :: String -> Parser String m_reservedOp :: String -> Parser () m_comma :: Parser String m_dot :: Parser String --m_reserved :: String -> Parser () m_whiteSpace :: Parser () m_float :: Parser Double m_parens :: ParsecT String t Identity a -> ParsecT String t Identity a m_brackets :: ParsecT String t Identity a -> ParsecT String t Identity a TokenParser{ parens = m_parens , brackets = m_brackets -- , stringLiteral = m_stringLiteral_do , identifier = m_identifier , reservedOp = m_reservedOp -- , reserved = m_reserved , symbol = m_symbol , dot = m_dot , comma = m_comma , integer = m_integer , float = m_float , whiteSpace = m_whiteSpace } = makeTokenParser tokenDef tokenDef :: LanguageDef st tokenDef = emptyDef{ commentStart = "/*" , commentEnd = "*/" , commentLine = "%" , identStart = letter , identLetter = alphaNum <|> (oneOf "_") , opStart = oneOf "><=-+*/!?:&|~" , opLetter = oneOf "=>~|&" , reservedOpNames = [">", "<", ">=", "<=", "=", "!=", "-", "+", "*", "/", ":", "!", "?", "~", "&", "|", "<=>", "=>", "<=", "<~>", "~|", "~&"] }
michalkonecny/polypaver
src/PolyPaver/Input/TPTP.hs
bsd-3-clause
18,971
0
15
4,862
5,129
2,634
2,495
491
3
{-# LANGUAGE ScopedTypeVariables #-} module TestFSM where import System.IO import Control.Monad.State import Control.Exception data Event = LoYes | LoNo | LoNum -- buttons on your phone | ReYes | ReNo | ReNum -- buttons on his phone getEvent :: IO Event getEvent = getChar >>= \c -> case c of 'y' -> return LoYes 'n' -> return LoNo '0' -> return LoNum 'Y' -> return ReYes 'N' -> return ReNo '1' -> return ReNum _ -> getEvent type UserState = String type NodeId = String data App = App { name :: NodeId, handler :: Event -> StateT UserState IO (Maybe App) -- can put state-specific stuff like ring tone, display props, etc here } idle, ringing, waiting, talking :: App idle = App "idle" $ \e -> case e of LoNum -> lift $ putStrLn "\tCalling somebody" >> return ( Just waiting ) ReNum -> lift $ putStrLn "\tIt's for you-hoo" >> return ( Just ringing ) LoNo -> lift $ putStrLn "\tQuitting" >> return Nothing ReNo -> lift $ putStrLn "\tQuitting" >> return Nothing _ -> return ( Just idle ) waiting = App "waiting" $ \e -> case e of ReYes -> lift $ putStrLn "\tHe accepted" >> return ( Just talking ) ReNo -> lift $ putStrLn "\tHe rejected" >> return ( Just idle ) LoNo -> lift $ putStrLn "\tI got bored" >> return ( Just idle ) _ -> return ( Just waiting ) ringing = App "ringing" $ \e -> case e of LoYes -> lift $ putStrLn "\tI accepted" >> return ( Just talking ) LoNo -> lift $ putStrLn "\tI rejected" >> return ( Just idle ) ReNo -> lift $ putStrLn "\tHe got bored" >> return ( Just idle ) _ -> return ( Just ringing ) talking = App "talking" $ \e -> case e of LoNo -> lift $ putStrLn "\tI'm hanging up" >> return ( Just idle ) ReNo -> lift $ putStrLn "\tHe hung up" >> return ( Just idle ) _ -> return ( Just talking ) getApp :: NodeId -> App getApp "idle" = idle getApp "waiting" = waiting getApp "ringing" = ringing getApp "talking" = talking getApp n = error $ "No state found for " ++ n run :: App -> IO () run st = do e <- getEvent let machine = handler st e (mApp, nState) <- runStateT machine "" maybe (return ()) run mApp -- let (eff, app) = runState handler st -- undefined -- -- >>= maybe (return ()) run -- main = hSetBuffering stdin NoBuffering >> -- so you don't have to hit return run idle run2 :: App -> Event -> UserState -> IO (Maybe App, UserState) run2 app = runStateT . handler app runApp :: NodeId -> UserState -> IO () runApp nodeId userState = do e <- getEvent (mApp, userState') <- run2 (getApp nodeId) e userState case mApp of Nothing -> writeFile "./temp" "" >> print "Done" Just app -> writeFile "./temp" (show (name app, userState')) main2 = do stFile <- readFileMaybe "./temp" case (stFile >>= readMaybe) :: Maybe (NodeId, UserState) of Nothing -> runApp "idle" "" Just (nodeId, userState) -> runApp nodeId userState readMaybe :: (Read a) => String -> Maybe a readMaybe s = case reads s of [] -> Nothing [(a, _)] -> Just a readFileMaybe :: String -> IO (Maybe String) readFileMaybe path = do stFile <- try $ readFile path case stFile of Left (e :: IOException) -> return Nothing Right f -> return $ Just f
homam/fsm-conversational-ui
src/TestFSM.hs
bsd-3-clause
3,396
0
14
948
1,170
582
588
82
7
module AI.API.GameTree ( alphabeta , negascout , minimax ) where import Types import Game import AI.Eval import AI.Types import Data.Tree.Game_tree.Game_tree import qualified Data.Tree.Game_tree.Negascout as Algo newtype GTSimple b = GTSimple { unGTSimple :: Position b } instance Board b => Game_tree (GTSimple b) where is_terminal = isOver . unGTSimple node_value = simpleEval . unGTSimple children = map GTSimple . nextPositions . unGTSimple newtype GTThreatBased b = GTThreatBased{ unGTThreatBased :: Position b } deriving Show instance Board b => Game_tree (GTThreatBased b) where is_terminal = isOver . unGTThreatBased node_value = threatBasedEval . unGTThreatBased children = map GTThreatBased . nextPositions . unGTThreatBased alphabeta :: Board b => Evaluation -> Position b -> Depth -> (PV, Score) alphabeta SimpleEval r d = let (pv, score) = Algo.alpha_beta_search (GTSimple r) d realPV = tail $ map (head . pMoves . unGTSimple) pv in (realPV, score) alphabeta ThreatBasedEval r d = let (pv, score) = Algo.alpha_beta_search (GTThreatBased r) d realPV = tail $ map (head . pMoves . unGTThreatBased) pv in (realPV, score) negascout :: Board b => Evaluation -> Position b -> Depth -> (PV, Score) negascout SimpleEval r d = let (pv, score) = Algo.negascout (GTSimple r) d realPV = tail $ map (head . pMoves . unGTSimple) pv in (realPV, score) negascout ThreatBasedEval r d = let (pv, score) = Algo.negascout (GTThreatBased r) d realPV = tail $ map (head . pMoves . unGTThreatBased) pv in (realPV, score) minimax :: Board b => Evaluation -> Position b -> Depth -> (PV, Score) minimax SimpleEval r d = let (pv, score) = Algo.negamax (GTSimple r) d realPV = tail $ map (head . pMoves . unGTSimple) pv in (realPV, score) minimax ThreatBasedEval r d = let (pv, score) = Algo.negamax (GTThreatBased r) d realPV = tail $ map (head . pMoves . unGTThreatBased) pv in (realPV, score)
sphynx/hamisado
AI/API/GameTree.hs
bsd-3-clause
1,977
0
13
400
741
394
347
47
1
module Turbinado.Server.Network ( receiveRequest -- :: Handle -> IO Request , sendResponse -- :: Handle -> Response -> IO () ) where import Data.Maybe import Network.Socket import Network.HTTP hiding (receiveHTTP, respondHTTP) import Network.HTTP.Stream import Network.StreamSocket import Network.URI import qualified System.Environment as Env import System.IO import Turbinado.Controller.Monad import Turbinado.Server.Exception import Turbinado.Environment.Logger import Turbinado.Environment.Types import Turbinado.Environment.Request import Turbinado.Environment.Response import Turbinado.Server.StandardResponse import Turbinado.Utility.Data -- | Read the request from client. receiveRequest :: Maybe Socket -> Controller () receiveRequest Nothing = do e <- getEnvironment acceptCGI receiveRequest (Just sock) = do req <- liftIO $ receiveHTTP sock case req of Left e -> throwTurbinado $ BadRequest $ "In receiveRequest : " ++ show e Right r -> do e <- get put $ e {Turbinado.Environment.Types.getRequest = Just r} -- | Get the 'Response' from the 'Environment' and send -- it back to the client. sendResponse :: Maybe Socket -> Environment -> IO () sendResponse Nothing e = respondCGI $ fromJust' "Network : sendResponse" $ Turbinado.Environment.Types.getResponse e sendResponse (Just sock) e = do respondHTTP sock $ fromJust' "Network : sendResponse" $ Turbinado.Environment.Types.getResponse e -- | Pull a CGI request from stdin acceptCGI :: Controller () acceptCGI = do body <- liftIO $ hGetContents stdin hdrs <- liftIO $ Env.getEnvironment let rqheaders = parseHeaders $ extractHTTPHeaders hdrs rquri = fromJust' "Network: acceptCGI: parseURI failed" $ parseURI $ fromJust' "Network: acceptCGI: No REQUEST_URI in hdrs" $ lookup "SCRIPT_URI" hdrs rqmethod = fromJust' "Network: acceptCGI: REQUEST_METHOD invalid" $ flip lookup rqMethodMap $ fromJust' "Network: acceptCGI: No REQUEST_METHOD in hdrs" $ lookup "REQUEST_METHOD" hdrs case rqheaders of Left err -> errorResponse $ show err Right r -> do e' <- getEnvironment setEnvironment $ e' { Turbinado.Environment.Types.getRequest = Just Request { rqURI = rquri , rqMethod = rqmethod , rqHeaders = r , rqBody = body } } matchRqMethod :: String -> RequestMethod matchRqMethod m = fromJust' "Turbinado.Server.Network:matchRqMethod" $ lookup m [ ("GET", GET) , ("POST", POST) , ("HEAD", HEAD) , ("PUT" , PUT) , ("DELETE", DELETE) ] -- | Convert the HTTP.Response to a CGI response for stdout. respondCGI :: Response String -> IO () respondCGI r = do let message = (unlines $ drop 1 $ lines $ show r) ++ "\n\n" ++ rspBody r -- need to drop the first line from the response for CGI hPutStr stdout message hFlush stdout -- | Convert from HTTP_SOME_FLAG to Some-Flag for HTTP.parseHeaders extractHTTPHeaders :: [(String, String)] -> [String] extractHTTPHeaders [] = [] extractHTTPHeaders (('H':'T':'T':'P':'_':k,v):hs) = (convertUnderscores k ++ ": " ++ v) : extractHTTPHeaders hs where convertUnderscores [] = [] convertUnderscores ('_':ss) = '-' : convertUnderscores ss convertUnderscores (s :ss) = s : convertUnderscores ss extractHTTPHeaders ((k,v) : hs) = extractHTTPHeaders hs -- | Lifted from Network.HTTP rqMethodMap :: [(String, RequestMethod)] rqMethodMap = [("HEAD", HEAD), ("PUT", PUT), ("GET", GET), ("POST", POST), ("DELETE", DELETE), ("OPTIONS", OPTIONS), ("TRACE", TRACE)]
alsonkemp/turbinado-website
Turbinado/Server/Network.hs
bsd-3-clause
4,376
0
17
1,504
966
519
447
75
3
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TemplateHaskell #-} -- -- | The core language, almost all transformations and optimisations take place -- on this form. -- -- River Core is a functional programming language whose syntactic structure -- guarantees that programs are always in Administrative Normal Form [1]. -- -- This particular flavour of ANF is heavily inspired by the one presented in -- [2] where a formal mapping from Static Single Assignment (SSA) form [3] to -- ANF is presented. [2] also demonstrates that algorithms which work over -- the SSA form can similarly be translated to work over ANF. -- -- 1. The Essence of Compiling with Continuations -- Cormac Flanagan, Amr Sabry, Bruce F. Duba and Matthias Felleisen (1993) -- https://users.soe.ucsc.edu/~cormac/papers/pldi93.pdf -- -- 2. A Functional Perspective on SSA Optimisation Algorithms -- Manuel M. T. Chakravarty, Gabriele Keller and Patryk Zadarnowski (2003) -- https://www.jantar.org/papers/chakravarty03perspective.pdf -- -- 3. Efficiently computing static single assignment form and the control dependence graph. -- Ron Cytron, Jeanne Ferrante, Barry K. Rosen, Mark N. Wegman, and Kenneth F. Zadeck (1991) -- http://www.cs.utexas.edu/~pingali/CS380C/2010/papers/ssaCytron.pdf -- module River.Core.Syntax ( Program(..) , Term(..) , Tail(..) , Atom(..) , Bindings(..) , Binding(..) , takeName ) where import Control.DeepSeq (NFData) import Data.Bifunctor.TH (deriveBifunctor, deriveBifoldable, deriveBitraversable) import Data.Data (Data) import Data.Typeable (Typeable) import GHC.Generics (Generic) data Program k p n a = Program !a !(Term k p n a) deriving (Eq, Ord, Read, Show, Functor, Foldable, Traversable, Data, Typeable, Generic, NFData) data Term k p n a = Return !a !(Tail p n a) | If !a !k !(Atom n a) !(Term k p n a) !(Term k p n a) | Let !a ![n] !(Tail p n a) !(Term k p n a) | LetRec !a !(Bindings k p n a) !(Term k p n a) deriving (Eq, Ord, Read, Show, Functor, Foldable, Traversable, Data, Typeable, Generic, NFData) data Tail p n a = Copy !a ![Atom n a] | Call !a !n ![Atom n a] | Prim !a !p ![Atom n a] deriving (Eq, Ord, Read, Show, Functor, Foldable, Traversable, Data, Typeable, Generic, NFData) data Atom n a = Immediate !a !Integer | Variable !a !n deriving (Eq, Ord, Read, Show, Functor, Foldable, Traversable, Data, Typeable, Generic, NFData) data Bindings k p n a = Bindings !a [(n, Binding k p n a)] deriving (Eq, Ord, Read, Show, Functor, Foldable, Traversable, Data, Typeable, Generic, NFData) data Binding k p n a = Lambda !a ![n] !(Term k p n a) deriving (Eq, Ord, Read, Show, Functor, Foldable, Traversable, Data, Typeable, Generic, NFData) takeName :: Atom n a -> Maybe n takeName = \case Immediate _ _ -> Nothing Variable _ n -> Just n $(deriveBifunctor ''Program) $(deriveBifoldable ''Program) $(deriveBitraversable ''Program) $(deriveBifunctor ''Term) $(deriveBifoldable ''Term) $(deriveBitraversable ''Term) $(deriveBifunctor ''Tail) $(deriveBifoldable ''Tail) $(deriveBitraversable ''Tail) $(deriveBifunctor ''Atom) $(deriveBifoldable ''Atom) $(deriveBitraversable ''Atom) $(deriveBifunctor ''Bindings) $(deriveBifoldable ''Bindings) $(deriveBitraversable ''Bindings) $(deriveBifunctor ''Binding) $(deriveBifoldable ''Binding) $(deriveBitraversable ''Binding)
jystic/river
src/River/Core/Syntax.hs
bsd-3-clause
3,675
0
9
708
1,029
534
495
133
2
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.SeamlessCubeMap -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.SeamlessCubeMap ( -- * Extension Support glGetARBSeamlessCubeMap, gl_ARB_seamless_cube_map, -- * Enums pattern GL_TEXTURE_CUBE_MAP_SEAMLESS ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/SeamlessCubeMap.hs
bsd-3-clause
668
0
5
91
47
36
11
7
0
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[HsBinds]{Abstract syntax: top-level bindings and signatures} Datatype for: @BindGroup@, @Bind@, @Sig@, @Bind@. -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE BangPatterns #-} module HsBinds where import {-# SOURCE #-} HsExpr ( pprExpr, LHsExpr, MatchGroup, pprFunBind, GRHSs, pprPatBind ) import {-# SOURCE #-} HsPat ( LPat ) import PlaceHolder ( PostTc,PostRn,DataId ) import HsTypes import PprCore () import CoreSyn import TcEvidence import Type import Name import NameSet import BasicTypes import Outputable import SrcLoc import Var import Bag import FastString import BooleanFormula (LBooleanFormula) import DynFlags import Data.Data hiding ( Fixity ) import Data.List hiding ( foldr ) import Data.Ord import Data.Foldable ( Foldable(..) ) {- ************************************************************************ * * \subsection{Bindings: @BindGroup@} * * ************************************************************************ Global bindings (where clauses) -} -- During renaming, we need bindings where the left-hand sides -- have been renamed but the the right-hand sides have not. -- the ...LR datatypes are parametrized by two id types, -- one for the left and one for the right. -- Other than during renaming, these will be the same. type HsLocalBinds id = HsLocalBindsLR id id -- | Bindings in a 'let' expression -- or a 'where' clause data HsLocalBindsLR idL idR = HsValBinds (HsValBindsLR idL idR) -- There should be no pattern synonyms in the HsValBindsLR -- These are *local* (not top level) bindings -- The parser accepts them, however, leaving the the -- renamer to report them | HsIPBinds (HsIPBinds idR) | EmptyLocalBinds deriving (Typeable) deriving instance (DataId idL, DataId idR) => Data (HsLocalBindsLR idL idR) type HsValBinds id = HsValBindsLR id id -- | Value bindings (not implicit parameters) -- Used for both top level and nested bindings -- May contain pattern synonym bindings data HsValBindsLR idL idR = -- | Before renaming RHS; idR is always RdrName -- Not dependency analysed -- Recursive by default ValBindsIn (LHsBindsLR idL idR) [LSig idR] -- | After renaming RHS; idR can be Name or Id -- Dependency analysed, -- later bindings in the list may depend on earlier -- ones. | ValBindsOut [(RecFlag, LHsBinds idL)] [LSig Name] deriving (Typeable) deriving instance (DataId idL, DataId idR) => Data (HsValBindsLR idL idR) type LHsBind id = LHsBindLR id id type LHsBinds id = LHsBindsLR id id type HsBind id = HsBindLR id id type LHsBindsLR idL idR = Bag (LHsBindLR idL idR) type LHsBindLR idL idR = Located (HsBindLR idL idR) data HsBindLR idL idR = -- | FunBind is used for both functions @f x = e@ -- and variables @f = \x -> e@ -- -- Reason 1: Special case for type inference: see 'TcBinds.tcMonoBinds'. -- -- Reason 2: Instance decls can only have FunBinds, which is convenient. -- If you change this, you'll need to change e.g. rnMethodBinds -- -- But note that the form @f :: a->a = ...@ -- parses as a pattern binding, just like -- @(f :: a -> a) = ... @ -- -- 'ApiAnnotation.AnnKeywordId's -- -- - 'ApiAnnotation.AnnFunId', attached to each element of fun_matches -- -- - 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation FunBind { fun_id :: Located idL, -- Note [fun_id in Match] in HsExpr fun_matches :: MatchGroup idR (LHsExpr idR), -- ^ The payload fun_co_fn :: HsWrapper, -- ^ Coercion from the type of the MatchGroup to the type of -- the Id. Example: -- -- @ -- f :: Int -> forall a. a -> a -- f x y = y -- @ -- -- Then the MatchGroup will have type (Int -> a' -> a') -- (with a free type variable a'). The coercion will take -- a CoreExpr of this type and convert it to a CoreExpr of -- type Int -> forall a'. a' -> a' -- Notice that the coercion captures the free a'. bind_fvs :: PostRn idL NameSet, -- ^ After the renamer, this contains -- the locally-bound -- free variables of this defn. -- See Note [Bind free vars] fun_tick :: [Tickish Id] -- ^ Ticks to put on the rhs, if any } -- | The pattern is never a simple variable; -- That case is done by FunBind -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnBang', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation | PatBind { pat_lhs :: LPat idL, pat_rhs :: GRHSs idR (LHsExpr idR), pat_rhs_ty :: PostTc idR Type, -- ^ Type of the GRHSs bind_fvs :: PostRn idL NameSet, -- ^ See Note [Bind free vars] pat_ticks :: ([Tickish Id], [[Tickish Id]]) -- ^ Ticks to put on the rhs, if any, and ticks to put on -- the bound variables. } -- | Dictionary binding and suchlike. -- All VarBinds are introduced by the type checker | VarBind { var_id :: idL, var_rhs :: LHsExpr idR, -- ^ Located only for consistency var_inline :: Bool -- ^ True <=> inline this binding regardless -- (used for implication constraints only) } | AbsBinds { -- Binds abstraction; TRANSLATION abs_tvs :: [TyVar], abs_ev_vars :: [EvVar], -- ^ Includes equality constraints -- | AbsBinds only gets used when idL = idR after renaming, -- but these need to be idL's for the collect... code in HsUtil -- to have the right type abs_exports :: [ABExport idL], -- | Evidence bindings -- Why a list? See TcInstDcls -- Note [Typechecking plan for instance declarations] abs_ev_binds :: [TcEvBinds], -- | Typechecked user bindings abs_binds :: LHsBinds idL } | AbsBindsSig { -- Simpler form of AbsBinds, used with a type sig -- in tcPolyCheck. Produces simpler desugaring and -- is necessary to avoid #11405, comment:3. abs_tvs :: [TyVar], abs_ev_vars :: [EvVar], abs_sig_export :: idL, -- like abe_poly abs_sig_prags :: TcSpecPrags, abs_sig_ev_bind :: TcEvBinds, -- no list needed here abs_sig_bind :: LHsBind idL -- always only one, and it's always a -- FunBind } | PatSynBind (PatSynBind idL idR) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern', -- 'ApiAnnotation.AnnLarrow','ApiAnnotation.AnnEqual', -- 'ApiAnnotation.AnnWhere' -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId idL, DataId idR) => Data (HsBindLR idL idR) -- Consider (AbsBinds tvs ds [(ftvs, poly_f, mono_f) binds] -- -- Creates bindings for (polymorphic, overloaded) poly_f -- in terms of monomorphic, non-overloaded mono_f -- -- Invariants: -- 1. 'binds' binds mono_f -- 2. ftvs is a subset of tvs -- 3. ftvs includes all tyvars free in ds -- -- See Note [AbsBinds] data ABExport id = ABE { abe_poly :: id -- ^ Any INLINE pragmas is attached to this Id , abe_mono :: id , abe_wrap :: HsWrapper -- ^ See Note [ABExport wrapper] -- Shape: (forall abs_tvs. abs_ev_vars => abe_mono) ~ abe_poly , abe_prags :: TcSpecPrags -- ^ SPECIALISE pragmas } deriving (Data, Typeable) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnLarrow' -- 'ApiAnnotation.AnnWhere','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@, -- For details on above see note [Api annotations] in ApiAnnotation data PatSynBind idL idR = PSB { psb_id :: Located idL, -- ^ Name of the pattern synonym psb_fvs :: PostRn idR NameSet, -- ^ See Note [Bind free vars] psb_args :: HsPatSynDetails (Located idR), -- ^ Formal parameter names psb_def :: LPat idR, -- ^ Right-hand side psb_dir :: HsPatSynDir idR -- ^ Directionality } deriving (Typeable) deriving instance (DataId idL, DataId idR) => Data (PatSynBind idL idR) {- Note [AbsBinds] ~~~~~~~~~~~~~~~ The AbsBinds constructor is used in the output of the type checker, to record *typechecked* and *generalised* bindings. Consider a module M, with this top-level binding, where there is no type signature for M.reverse, M.reverse [] = [] M.reverse (x:xs) = M.reverse xs ++ [x] In Hindley-Milner, a recursive binding is typechecked with the *recursive* uses being *monomorphic*. So after typechecking *and* desugaring we will get something like this M.reverse :: forall a. [a] -> [a] = /\a. letrec reverse :: [a] -> [a] = \xs -> case xs of [] -> [] (x:xs) -> reverse xs ++ [x] in reverse Notice that 'M.reverse' is polymorphic as expected, but there is a local definition for plain 'reverse' which is *monomorphic*. The type variable 'a' scopes over the entire letrec. That's after desugaring. What about after type checking but before desugaring? That's where AbsBinds comes in. It looks like this: AbsBinds { abs_tvs = [a] , abs_exports = [ABE { abe_poly = M.reverse :: forall a. [a] -> [a], , abe_mono = reverse :: [a] -> [a]}] , abs_binds = { reverse :: [a] -> [a] = \xs -> case xs of [] -> [] (x:xs) -> reverse xs ++ [x] } } Here, * abs_tvs says what type variables are abstracted over the binding group, just 'a' in this case. * abs_binds is the *monomorphic* bindings of the group * abs_exports describes how to get the polymorphic Id 'M.reverse' from the monomorphic one 'reverse' Notice that the *original* function (the polymorphic one you thought you were defining) appears in the abe_poly field of the abs_exports. The bindings in abs_binds are for fresh, local, Ids with a *monomorphic* Id. If there is a group of mutually recursive (see Note [Polymorphic recursion]) functions without type signatures, we get one AbsBinds with the monomorphic versions of the bindings in abs_binds, and one element of abe_exports for each variable bound in the mutually recursive group. This is true even for pattern bindings. Example: (f,g) = (\x -> x, f) After type checking we get AbsBinds { abs_tvs = [a] , abs_exports = [ ABE { abe_poly = M.f :: forall a. a -> a , abe_mono = f :: a -> a } , ABE { abe_poly = M.g :: forall a. a -> a , abe_mono = g :: a -> a }] , abs_binds = { (f,g) = (\x -> x, f) } Note [Polymorphic recursion] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider Rec { f x = ...(g ef)... ; g :: forall a. [a] -> [a] ; g y = ...(f eg)... } These bindings /are/ mutually recursive (f calls g, and g calls f). But we can use the type signature for g to break the recursion, like this: 1. Add g :: forall a. [a] -> [a] to the type environment 2. Typecheck the definition of f, all by itself, including generalising it to find its most general type, say f :: forall b. b -> b -> [b] 3. Extend the type environment with that type for f 4. Typecheck the definition of g, all by itself, checking that it has the type claimed by its signature Steps 2 and 4 each generate a separate AbsBinds, so we end up with Rec { AbsBinds { ...for f ... } ; AbsBinds { ...for g ... } } This approach allows both f and to call each other polymorphically, even though only g has a signature. We get an AbsBinds that encompasses multiple source-program bindings only when * Each binding in the group has at least one binder that lacks a user type signature * The group forms a strongly connected component Note [ABExport wrapper] ~~~~~~~~~~~~~~~~~~~~~~~ Consider (f,g) = (\x.x, \y.y) This ultimately desugars to something like this: tup :: forall a b. (a->a, b->b) tup = /\a b. (\x:a.x, \y:b.y) f :: forall a. a -> a f = /\a. case tup a Any of (fm::a->a,gm:Any->Any) -> fm ...similarly for g... The abe_wrap field deals with impedance-matching between (/\a b. case tup a b of { (f,g) -> f }) and the thing we really want, which may have fewer type variables. The action happens in TcBinds.mkExport. Note [Bind free vars] ~~~~~~~~~~~~~~~~~~~~~ The bind_fvs field of FunBind and PatBind records the free variables of the definition. It is used for two purposes a) Dependency analysis prior to type checking (see TcBinds.tc_group) b) Deciding whether we can do generalisation of the binding (see TcBinds.decideGeneralisationPlan) Specifically, * bind_fvs includes all free vars that are defined in this module (including top-level things and lexically scoped type variables) * bind_fvs excludes imported vars; this is just to keep the set smaller * Before renaming, and after typechecking, the field is unused; it's just an error thunk -} instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsLocalBindsLR idL idR) where ppr (HsValBinds bs) = ppr bs ppr (HsIPBinds bs) = ppr bs ppr EmptyLocalBinds = empty instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsValBindsLR idL idR) where ppr (ValBindsIn binds sigs) = pprDeclList (pprLHsBindsForUser binds sigs) ppr (ValBindsOut sccs sigs) = getPprStyle $ \ sty -> if debugStyle sty then -- Print with sccs showing vcat (map ppr sigs) $$ vcat (map ppr_scc sccs) else pprDeclList (pprLHsBindsForUser (unionManyBags (map snd sccs)) sigs) where ppr_scc (rec_flag, binds) = pp_rec rec_flag <+> pprLHsBinds binds pp_rec Recursive = text "rec" pp_rec NonRecursive = text "nonrec" pprLHsBinds :: (OutputableBndr idL, OutputableBndr idR) => LHsBindsLR idL idR -> SDoc pprLHsBinds binds | isEmptyLHsBinds binds = empty | otherwise = pprDeclList (map ppr (bagToList binds)) pprLHsBindsForUser :: (OutputableBndr idL, OutputableBndr idR, OutputableBndr id2) => LHsBindsLR idL idR -> [LSig id2] -> [SDoc] -- pprLHsBindsForUser is different to pprLHsBinds because -- a) No braces: 'let' and 'where' include a list of HsBindGroups -- and we don't want several groups of bindings each -- with braces around -- b) Sort by location before printing -- c) Include signatures pprLHsBindsForUser binds sigs = map snd (sort_by_loc decls) where decls :: [(SrcSpan, SDoc)] decls = [(loc, ppr sig) | L loc sig <- sigs] ++ [(loc, ppr bind) | L loc bind <- bagToList binds] sort_by_loc decls = sortBy (comparing fst) decls pprDeclList :: [SDoc] -> SDoc -- Braces with a space -- Print a bunch of declarations -- One could choose { d1; d2; ... }, using 'sep' -- or d1 -- d2 -- .. -- using vcat -- At the moment we chose the latter -- Also we do the 'pprDeeperList' thing. pprDeclList ds = pprDeeperList vcat ds ------------ emptyLocalBinds :: HsLocalBindsLR a b emptyLocalBinds = EmptyLocalBinds isEmptyLocalBinds :: HsLocalBindsLR a b -> Bool isEmptyLocalBinds (HsValBinds ds) = isEmptyValBinds ds isEmptyLocalBinds (HsIPBinds ds) = isEmptyIPBinds ds isEmptyLocalBinds EmptyLocalBinds = True isEmptyValBinds :: HsValBindsLR a b -> Bool isEmptyValBinds (ValBindsIn ds sigs) = isEmptyLHsBinds ds && null sigs isEmptyValBinds (ValBindsOut ds sigs) = null ds && null sigs emptyValBindsIn, emptyValBindsOut :: HsValBindsLR a b emptyValBindsIn = ValBindsIn emptyBag [] emptyValBindsOut = ValBindsOut [] [] emptyLHsBinds :: LHsBindsLR idL idR emptyLHsBinds = emptyBag isEmptyLHsBinds :: LHsBindsLR idL idR -> Bool isEmptyLHsBinds = isEmptyBag ------------ plusHsValBinds :: HsValBinds a -> HsValBinds a -> HsValBinds a plusHsValBinds (ValBindsIn ds1 sigs1) (ValBindsIn ds2 sigs2) = ValBindsIn (ds1 `unionBags` ds2) (sigs1 ++ sigs2) plusHsValBinds (ValBindsOut ds1 sigs1) (ValBindsOut ds2 sigs2) = ValBindsOut (ds1 ++ ds2) (sigs1 ++ sigs2) plusHsValBinds _ _ = panic "HsBinds.plusHsValBinds" {- What AbsBinds means ~~~~~~~~~~~~~~~~~~~ AbsBinds tvs [d1,d2] [(tvs1, f1p, f1m), (tvs2, f2p, f2m)] BIND means f1p = /\ tvs -> \ [d1,d2] -> letrec DBINDS and BIND in fm gp = ...same again, with gm instead of fm This is a pretty bad translation, because it duplicates all the bindings. So the desugarer tries to do a better job: fp = /\ [a,b] -> \ [d1,d2] -> case tp [a,b] [d1,d2] of (fm,gm) -> fm ..ditto for gp.. tp = /\ [a,b] -> \ [d1,d2] -> letrec DBINDS and BIND in (fm,gm) -} instance (OutputableBndr idL, OutputableBndr idR) => Outputable (HsBindLR idL idR) where ppr mbind = ppr_monobind mbind ppr_monobind :: (OutputableBndr idL, OutputableBndr idR) => HsBindLR idL idR -> SDoc ppr_monobind (PatBind { pat_lhs = pat, pat_rhs = grhss }) = pprPatBind pat grhss ppr_monobind (VarBind { var_id = var, var_rhs = rhs }) = sep [pprBndr CaseBind var, nest 2 $ equals <+> pprExpr (unLoc rhs)] ppr_monobind (FunBind { fun_id = fun, fun_co_fn = wrap, fun_matches = matches, fun_tick = ticks }) = pprTicks empty (if null ticks then empty else text "-- ticks = " <> ppr ticks) $$ ifPprDebug (pprBndr LetBind (unLoc fun)) $$ pprFunBind (unLoc fun) matches $$ ifPprDebug (ppr wrap) ppr_monobind (PatSynBind psb) = ppr psb ppr_monobind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dictvars , abs_exports = exports, abs_binds = val_binds , abs_ev_binds = ev_binds }) = sdocWithDynFlags $ \ dflags -> if gopt Opt_PrintTypecheckerElaboration dflags then -- Show extra information (bug number: #10662) hang (text "AbsBinds" <+> brackets (interpp'SP tyvars) <+> brackets (interpp'SP dictvars)) 2 $ braces $ vcat [ text "Exports:" <+> brackets (sep (punctuate comma (map ppr exports))) , text "Exported types:" <+> vcat [pprBndr LetBind (abe_poly ex) | ex <- exports] , text "Binds:" <+> pprLHsBinds val_binds , text "Evidence:" <+> ppr ev_binds ] else pprLHsBinds val_binds ppr_monobind (AbsBindsSig { abs_tvs = tyvars , abs_ev_vars = dictvars , abs_sig_ev_bind = ev_bind , abs_sig_bind = bind }) = sdocWithDynFlags $ \ dflags -> if gopt Opt_PrintTypecheckerElaboration dflags then hang (text "AbsBindsSig" <+> brackets (interpp'SP tyvars) <+> brackets (interpp'SP dictvars)) 2 $ braces $ vcat [ text "Bind:" <+> ppr bind , text "Evidence:" <+> ppr ev_bind ] else ppr bind instance (OutputableBndr id) => Outputable (ABExport id) where ppr (ABE { abe_wrap = wrap, abe_poly = gbl, abe_mono = lcl, abe_prags = prags }) = vcat [ ppr gbl <+> text "<=" <+> ppr lcl , nest 2 (pprTcSpecPrags prags) , nest 2 (text "wrap:" <+> ppr wrap)] instance (OutputableBndr idL, OutputableBndr idR) => Outputable (PatSynBind idL idR) where ppr (PSB{ psb_id = L _ psyn, psb_args = details, psb_def = pat, psb_dir = dir }) = ppr_lhs <+> ppr_rhs where ppr_lhs = text "pattern" <+> ppr_details ppr_simple syntax = syntax <+> ppr pat ppr_details = case details of InfixPatSyn v1 v2 -> hsep [ppr v1, pprInfixOcc psyn, ppr v2] PrefixPatSyn vs -> hsep (pprPrefixOcc psyn : map ppr vs) RecordPatSyn vs -> pprPrefixOcc psyn <> braces (sep (punctuate comma (map ppr vs))) ppr_rhs = case dir of Unidirectional -> ppr_simple (text "<-") ImplicitBidirectional -> ppr_simple equals ExplicitBidirectional mg -> ppr_simple (text "<-") <+> ptext (sLit "where") $$ (nest 2 $ pprFunBind psyn mg) pprTicks :: SDoc -> SDoc -> SDoc -- Print stuff about ticks only when -dppr-debug is on, to avoid -- them appearing in error messages (from the desugarer); see Trac # 3263 -- Also print ticks in dumpStyle, so that -ddump-hpc actually does -- something useful. pprTicks pp_no_debug pp_when_debug = getPprStyle (\ sty -> if debugStyle sty || dumpStyle sty then pp_when_debug else pp_no_debug) {- ************************************************************************ * * Implicit parameter bindings * * ************************************************************************ -} data HsIPBinds id = IPBinds [LIPBind id] TcEvBinds -- Only in typechecker output; binds -- uses of the implicit parameters deriving (Typeable) deriving instance (DataId id) => Data (HsIPBinds id) isEmptyIPBinds :: HsIPBinds id -> Bool isEmptyIPBinds (IPBinds is ds) = null is && isEmptyTcEvBinds ds type LIPBind id = Located (IPBind id) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a -- list -- For details on above see note [Api annotations] in ApiAnnotation -- | Implicit parameter bindings. -- -- These bindings start off as (Left "x") in the parser and stay -- that way until after type-checking when they are replaced with -- (Right d), where "d" is the name of the dictionary holding the -- evidence for the implicit parameter. -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnEqual' -- For details on above see note [Api annotations] in ApiAnnotation data IPBind id = IPBind (Either (Located HsIPName) id) (LHsExpr id) deriving (Typeable) deriving instance (DataId name) => Data (IPBind name) instance (OutputableBndr id) => Outputable (HsIPBinds id) where ppr (IPBinds bs ds) = pprDeeperList vcat (map ppr bs) $$ ifPprDebug (ppr ds) instance (OutputableBndr id) => Outputable (IPBind id) where ppr (IPBind lr rhs) = name <+> equals <+> pprExpr (unLoc rhs) where name = case lr of Left (L _ ip) -> pprBndr LetBind ip Right id -> pprBndr LetBind id {- ************************************************************************ * * \subsection{@Sig@: type signatures and value-modifying user pragmas} * * ************************************************************************ It is convenient to lump ``value-modifying'' user-pragmas (e.g., ``specialise this function to these four types...'') in with type signatures. Then all the machinery to move them into place, etc., serves for both. -} type LSig name = Located (Sig name) -- | Signatures and pragmas data Sig name = -- | An ordinary type signature -- -- > f :: Num a => a -> a -- -- After renaming, this list of Names contains the named and unnamed -- wildcards brought into scope by this signature. For a signature -- @_ -> _a -> Bool@, the renamer will give the unnamed wildcard @_@ -- a freshly generated name, e.g. @_w@. @_w@ and the named wildcard @_a@ -- are then both replaced with fresh meta vars in the type. Their names -- are stored in the type signature that brought them into scope, in -- this third field to be more specific. -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon', -- 'ApiAnnotation.AnnComma' -- For details on above see note [Api annotations] in ApiAnnotation TypeSig [Located name] -- LHS of the signature; e.g. f,g,h :: blah (LHsSigWcType name) -- RHS of the signature; can have wildcards -- | A pattern synonym type signature -- -- > pattern Single :: () => (Show a) => a -> [a] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnPattern', -- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnForall' -- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow' -- For details on above see note [Api annotations] in ApiAnnotation | PatSynSig (Located name) (LHsSigType name) -- P :: forall a b. Req => Prov => ty -- | A signature for a class method -- False: ordinary class-method signature -- True: default class method signature -- e.g. class C a where -- op :: a -> a -- Ordinary -- default op :: Eq a => a -> a -- Generic default -- No wildcards allowed here -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDefault', -- 'ApiAnnotation.AnnDcolon' | ClassOpSig Bool [Located name] (LHsSigType name) -- | A type signature in generated code, notably the code -- generated for record selectors. We simply record -- the desired Id itself, replete with its name, type -- and IdDetails. Otherwise it's just like a type -- signature: there should be an accompanying binding | IdSig Id -- | An ordinary fixity declaration -- -- > infixl 8 *** -- -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnInfix', -- 'ApiAnnotation.AnnVal' -- For details on above see note [Api annotations] in ApiAnnotation | FixSig (FixitySig name) -- | An inline pragma -- -- > {#- INLINE f #-} -- -- - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpen' @'{-\# INLINE'@ and @'['@, -- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnTilde', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | InlineSig (Located name) -- Function name InlinePragma -- Never defaultInlinePragma -- | A specialisation pragma -- -- > {-# SPECIALISE f :: Int -> Int #-} -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen' @'{-\# SPECIALISE'@ and @'['@, -- 'ApiAnnotation.AnnTilde', -- 'ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnClose' @']'@ and @'\#-}'@, -- 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | SpecSig (Located name) -- Specialise a function or datatype ... [LHsSigType name] -- ... to these types InlinePragma -- The pragma on SPECIALISE_INLINE form. -- If it's just defaultInlinePragma, then we said -- SPECIALISE, not SPECIALISE_INLINE -- | A specialisation pragma for instance declarations only -- -- > {-# SPECIALISE instance Eq [Int] #-} -- -- (Class tys); should be a specialisation of the -- current instance declaration -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnInstance','ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | SpecInstSig SourceText (LHsSigType name) -- Note [Pragma source text] in BasicTypes -- | A minimal complete definition pragma -- -- > {-# MINIMAL a | (b, c | (d | e)) #-} -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnVbar','ApiAnnotation.AnnComma', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | MinimalSig SourceText (LBooleanFormula (Located name)) -- Note [Pragma source text] in BasicTypes deriving (Typeable) deriving instance (DataId name) => Data (Sig name) type LFixitySig name = Located (FixitySig name) data FixitySig name = FixitySig [Located name] Fixity deriving (Data, Typeable) -- | TsSpecPrags conveys pragmas from the type checker to the desugarer data TcSpecPrags = IsDefaultMethod -- ^ Super-specialised: a default method should -- be macro-expanded at every call site | SpecPrags [LTcSpecPrag] deriving (Data, Typeable) type LTcSpecPrag = Located TcSpecPrag data TcSpecPrag = SpecPrag Id HsWrapper InlinePragma -- ^ The Id to be specialised, an wrapper that specialises the -- polymorphic function, and inlining spec for the specialised function deriving (Data, Typeable) noSpecPrags :: TcSpecPrags noSpecPrags = SpecPrags [] hasSpecPrags :: TcSpecPrags -> Bool hasSpecPrags (SpecPrags ps) = not (null ps) hasSpecPrags IsDefaultMethod = False isDefaultMethod :: TcSpecPrags -> Bool isDefaultMethod IsDefaultMethod = True isDefaultMethod (SpecPrags {}) = False isFixityLSig :: LSig name -> Bool isFixityLSig (L _ (FixSig {})) = True isFixityLSig _ = False isTypeLSig :: LSig name -> Bool -- Type signatures isTypeLSig (L _(TypeSig {})) = True isTypeLSig (L _(ClassOpSig {})) = True isTypeLSig (L _(IdSig {})) = True isTypeLSig _ = False isSpecLSig :: LSig name -> Bool isSpecLSig (L _(SpecSig {})) = True isSpecLSig _ = False isSpecInstLSig :: LSig name -> Bool isSpecInstLSig (L _ (SpecInstSig {})) = True isSpecInstLSig _ = False isPragLSig :: LSig name -> Bool -- Identifies pragmas isPragLSig (L _ (SpecSig {})) = True isPragLSig (L _ (InlineSig {})) = True isPragLSig _ = False isInlineLSig :: LSig name -> Bool -- Identifies inline pragmas isInlineLSig (L _ (InlineSig {})) = True isInlineLSig _ = False isMinimalLSig :: LSig name -> Bool isMinimalLSig (L _ (MinimalSig {})) = True isMinimalLSig _ = False hsSigDoc :: Sig name -> SDoc hsSigDoc (TypeSig {}) = text "type signature" hsSigDoc (PatSynSig {}) = text "pattern synonym signature" hsSigDoc (ClassOpSig is_deflt _ _) | is_deflt = text "default type signature" | otherwise = text "class method signature" hsSigDoc (IdSig {}) = text "id signature" hsSigDoc (SpecSig {}) = text "SPECIALISE pragma" hsSigDoc (InlineSig _ prag) = ppr (inlinePragmaSpec prag) <+> text "pragma" hsSigDoc (SpecInstSig {}) = text "SPECIALISE instance pragma" hsSigDoc (FixSig {}) = text "fixity declaration" hsSigDoc (MinimalSig {}) = text "MINIMAL pragma" {- Check if signatures overlap; this is used when checking for duplicate signatures. Since some of the signatures contain a list of names, testing for equality is not enough -- we have to check if they overlap. -} instance (OutputableBndr name) => Outputable (Sig name) where ppr sig = ppr_sig sig ppr_sig :: OutputableBndr name => Sig name -> SDoc ppr_sig (TypeSig vars ty) = pprVarSig (map unLoc vars) (ppr ty) ppr_sig (ClassOpSig is_deflt vars ty) | is_deflt = text "default" <+> pprVarSig (map unLoc vars) (ppr ty) | otherwise = pprVarSig (map unLoc vars) (ppr ty) ppr_sig (IdSig id) = pprVarSig [id] (ppr (varType id)) ppr_sig (FixSig fix_sig) = ppr fix_sig ppr_sig (SpecSig var ty inl) = pragBrackets (pprSpec (unLoc var) (interpp'SP ty) inl) ppr_sig (InlineSig var inl) = pragBrackets (ppr inl <+> pprPrefixOcc (unLoc var)) ppr_sig (SpecInstSig _ ty) = pragBrackets (text "SPECIALIZE instance" <+> ppr ty) ppr_sig (MinimalSig _ bf) = pragBrackets (pprMinimalSig bf) ppr_sig (PatSynSig name sig_ty) = text "pattern" <+> pprPrefixOcc (unLoc name) <+> dcolon <+> ppr sig_ty instance OutputableBndr name => Outputable (FixitySig name) where ppr (FixitySig names fixity) = sep [ppr fixity, pprops] where pprops = hsep $ punctuate comma (map (pprInfixOcc . unLoc) names) pragBrackets :: SDoc -> SDoc pragBrackets doc = text "{-#" <+> doc <+> ptext (sLit "#-}") pprVarSig :: (OutputableBndr id) => [id] -> SDoc -> SDoc pprVarSig vars pp_ty = sep [pprvars <+> dcolon, nest 2 pp_ty] where pprvars = hsep $ punctuate comma (map pprPrefixOcc vars) pprSpec :: (OutputableBndr id) => id -> SDoc -> InlinePragma -> SDoc pprSpec var pp_ty inl = text "SPECIALIZE" <+> pp_inl <+> pprVarSig [var] pp_ty where pp_inl | isDefaultInlinePragma inl = empty | otherwise = ppr inl pprTcSpecPrags :: TcSpecPrags -> SDoc pprTcSpecPrags IsDefaultMethod = text "<default method>" pprTcSpecPrags (SpecPrags ps) = vcat (map (ppr . unLoc) ps) instance Outputable TcSpecPrag where ppr (SpecPrag var _ inl) = pprSpec var (text "<type>") inl pprMinimalSig :: OutputableBndr name => LBooleanFormula (Located name) -> SDoc pprMinimalSig (L _ bf) = text "MINIMAL" <+> ppr (fmap unLoc bf) {- ************************************************************************ * * \subsection[PatSynBind]{A pattern synonym definition} * * ************************************************************************ -} data HsPatSynDetails a = InfixPatSyn a a | PrefixPatSyn [a] | RecordPatSyn [RecordPatSynField a] deriving (Typeable, Data) -- See Note [Record PatSyn Fields] data RecordPatSynField a = RecordPatSynField { recordPatSynSelectorId :: a -- Selector name visible in rest of the file , recordPatSynPatVar :: a -- Filled in by renamer, the name used internally -- by the pattern } deriving (Typeable, Data) {- Note [Record PatSyn Fields] Consider the following two pattern synonyms. pattern P x y = ([x,True], [y,'v']) pattern Q{ x, y } =([x,True], [y,'v']) In P, we just have two local binders, x and y. In Q, we have local binders but also top-level record selectors x :: ([Bool], [Char]) -> Bool and similarly for y. It would make sense to support record-like syntax pattern Q{ x=x1, y=y1 } = ([x1,True], [y1,'v']) when we have a different name for the local and top-level binder the distinction between the two names clear -} instance Functor RecordPatSynField where fmap f (RecordPatSynField visible hidden) = RecordPatSynField (f visible) (f hidden) instance Outputable a => Outputable (RecordPatSynField a) where ppr (RecordPatSynField v _) = ppr v instance Foldable RecordPatSynField where foldMap f (RecordPatSynField visible hidden) = f visible `mappend` f hidden instance Traversable RecordPatSynField where traverse f (RecordPatSynField visible hidden) = RecordPatSynField <$> f visible <*> f hidden instance Functor HsPatSynDetails where fmap f (InfixPatSyn left right) = InfixPatSyn (f left) (f right) fmap f (PrefixPatSyn args) = PrefixPatSyn (fmap f args) fmap f (RecordPatSyn args) = RecordPatSyn (map (fmap f) args) instance Foldable HsPatSynDetails where foldMap f (InfixPatSyn left right) = f left `mappend` f right foldMap f (PrefixPatSyn args) = foldMap f args foldMap f (RecordPatSyn args) = foldMap (foldMap f) args foldl1 f (InfixPatSyn left right) = left `f` right foldl1 f (PrefixPatSyn args) = Data.List.foldl1 f args foldl1 f (RecordPatSyn args) = Data.List.foldl1 f (map (Data.Foldable.foldl1 f) args) foldr1 f (InfixPatSyn left right) = left `f` right foldr1 f (PrefixPatSyn args) = Data.List.foldr1 f args foldr1 f (RecordPatSyn args) = Data.List.foldr1 f (map (Data.Foldable.foldr1 f) args) length (InfixPatSyn _ _) = 2 length (PrefixPatSyn args) = Data.List.length args length (RecordPatSyn args) = Data.List.length args null (InfixPatSyn _ _) = False null (PrefixPatSyn args) = Data.List.null args null (RecordPatSyn args) = Data.List.null args toList (InfixPatSyn left right) = [left, right] toList (PrefixPatSyn args) = args toList (RecordPatSyn args) = foldMap toList args instance Traversable HsPatSynDetails where traverse f (InfixPatSyn left right) = InfixPatSyn <$> f left <*> f right traverse f (PrefixPatSyn args) = PrefixPatSyn <$> traverse f args traverse f (RecordPatSyn args) = RecordPatSyn <$> traverse (traverse f) args data HsPatSynDir id = Unidirectional | ImplicitBidirectional | ExplicitBidirectional (MatchGroup id (LHsExpr id)) deriving (Typeable) deriving instance (DataId id) => Data (HsPatSynDir id)
mcschroeder/ghc
compiler/hsSyn/HsBinds.hs
bsd-3-clause
39,008
0
18
11,260
6,190
3,335
2,855
415
4
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Model ( Post(..), runDb, doMigration, -- * interface insertPost, getNPosts, getPostBySlug, getPostById, deletePostBySlug, insertPosts ) where import Database.Persist import Database.Persist.TH import Database.Persist.Sqlite import Database.Persist.Postgresql import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (runStderrLoggingT) import Data.Text import Data.Time.Clock (UTCTime) import qualified Data.List as List share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Post json title Text content Text slug String created UTCTime default=now() UniqueSlug slug deriving Show |] runDb :: SqlPersistM a -> IO a runDb query = do let connStr = "host=localhost user=rishi dbname=rishi" runStderrLoggingT $ withPostgresqlPool connStr 10 $ \pool -> liftIO $ runSqlPersistMPool query pool doMigration :: IO () doMigration = runDb (runMigration migrateAll) -- INTERFACE insertPost :: Post -> IO (Maybe (Key Post)) insertPost = runDb . insertUnique insertPosts :: [Post] -> IO [Key Post] insertPosts = runDb . insertMany deletePostBySlug :: String -> IO () deletePostBySlug s = runDb $ deleteBy $ UniqueSlug s getNPosts :: Int -> IO [Entity Post] getNPosts n = runDb $ selectList ([] :: [Filter Post]) [LimitTo n, Desc PostCreated] getPostBySlug :: String -> IO (Maybe (Entity Post)) getPostBySlug s = runDb $ getBy $ UniqueSlug s getPostById :: Integer -> IO (Maybe (Entity Post)) getPostById i = runDb $ do posts <- selectList [PostId ==. toKey i] [] if List.null posts then return Nothing else return $ Just (List.head posts) -- * Utilities toKey :: ToBackendKey SqlBackend a => Integer -> Key a toKey i = toSqlKey (fromIntegral (i :: Integer)) -- main :: IO () -- main = runDb $ do -- time <- liftIO getCurrentTime -- postId <- insert $ Post "Bar" "Second Random content" "bar" time -- post <- get postId -- liftIO $ print post
ashutoshrishi/blogserver
src/Model.hs
bsd-3-clause
2,419
0
13
536
574
312
262
50
2
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {- | These declarations allow the use of a DirectionalSeq, which is a Seq that uses a phantom type to identify the ordering of the elements in the sequence (Forward or Reverse). The constructors are not exported from this module so that a DirectionalSeq can only be constructed by the functions in this module. -} module Types.DirectionalSeq where import Prelude () import Prelude.MH import qualified Data.Sequence as Seq data Chronological data Retrograde class SeqDirection a instance SeqDirection Chronological instance SeqDirection Retrograde data SeqDirection dir => DirectionalSeq dir a = DSeq { dseq :: Seq a } deriving (Show, Functor, Foldable, Traversable) emptyDirSeq :: DirectionalSeq dir a emptyDirSeq = DSeq mempty appendDirSeq :: DirectionalSeq dir a -> DirectionalSeq dir a -> DirectionalSeq dir a appendDirSeq a b = DSeq $ mappend (dseq a) (dseq b) onDirectedSeq :: SeqDirection dir => (Seq a -> Seq b) -> DirectionalSeq dir a -> DirectionalSeq dir b onDirectedSeq f = DSeq . f . dseq -- | Uses a start-predicate and and end-predicate to -- identify (the first matching) subset that is delineated by -- start-predicate and end-predicate (inclusive). It will then call -- the passed operation function on the subset messages to get back a -- (possibly modified) set of messages, along with an extracted value. -- The 'onDirSeqSubset' function will replace the original subset of -- messages with the set returned by the operation function and return -- the resulting message list along with the extracted value. onDirSeqSubset :: SeqDirection dir => (e -> Bool) -> (e -> Bool) -> (DirectionalSeq dir e -> (DirectionalSeq dir e, a)) -> DirectionalSeq dir e -> (DirectionalSeq dir e, a) onDirSeqSubset startPred endPred op entries = let ml = dseq entries (bl, ml1) = Seq.breakl startPred ml (ml2, el) = Seq.breakl endPred ml1 -- move match from start of el to end of ml2 (ml2', el') = if not (Seq.null el) then (ml2 <> Seq.take 1 el, Seq.drop 1 el) else (ml2, el) (ml3, rval) = op $ DSeq ml2' in (DSeq bl `appendDirSeq` ml3 `appendDirSeq` DSeq el', rval) -- | dirSeqBreakl splits the DirectionalSeq into a tuple where the -- first element is the (possibly empty) DirectionalSeq of all -- elements from the start for which the predicate returns false; the -- second tuple element is the remainder of the list, starting with -- the first element for which the predicate matched. dirSeqBreakl :: SeqDirection dir => (e -> Bool) -> DirectionalSeq dir e -> (DirectionalSeq dir e, DirectionalSeq dir e) dirSeqBreakl isMatch entries = let (removed, remaining) = Seq.breakl isMatch $ dseq entries in (DSeq removed, DSeq remaining) -- | dirSeqPartition splits the DirectionalSeq into a tuple of two -- DirectionalSeq elements: the first contains all elements for which -- the predicate is true and the second contains all elements for -- which the predicate is false. dirSeqPartition :: SeqDirection dir => (e -> Bool) -> DirectionalSeq dir e -> (DirectionalSeq dir e, DirectionalSeq dir e) dirSeqPartition isMatch entries = let (match, nomatch) = Seq.partition isMatch $ dseq entries in (DSeq match, DSeq nomatch) withDirSeqHead :: SeqDirection dir => (e -> r) -> DirectionalSeq dir e -> Maybe r withDirSeqHead op entries = case Seq.viewl (dseq entries) of Seq.EmptyL -> Nothing e Seq.:< _ -> Just $ op e
aisamanra/matterhorn
src/Types/DirectionalSeq.hs
bsd-3-clause
3,733
0
13
882
794
414
380
-1
-1
{-# LANGUAGE OverloadedStrings #-} module PeerTrader.Route.P2PPicks (p2ppicksHandler) where import Snap.Core import Snap.Extras.JSON (writeJSON) import Snap.Extras.TextUtils (readBS) import Control.Applicative ((<|>)) import Data.Aeson import qualified Data.Text as T import Database.Groundhog (AutoKey) import Database.Groundhog.Utils.Postgresql (intToKey) import Application import Logging (debugM) import P2PPicks.Types (P2PPicksType) import PeerTrader.Database import PeerTrader.Socket.Web (deactivateStrategy) import PeerTrader.Strategy import PeerTrader.Strategy.JSON import PeerTrader.Strategy.Strategy -- | 'GET' requests go to 'autoFilterStatus' -- 'POST' requests go to 'acceptAF' -- 'PUT' requests go to 'putAF' -- 'DELETE' requests go to 'deleteAutoFilter' p2ppicksHandler :: AppHandler () p2ppicksHandler = method GET p2ppicksStatus <|> method POST acceptP2PPicks <|> method PUT putP2PPicks <|> method DELETE deleteP2PPicks p2ppicksStatus :: AppHandler () p2ppicksStatus = withCurrentUser_ $ \n -> do p2ps <- queryStrategies n :: AppHandler [Entity (Strategy P2PPicksType)] writeJSON p2ps acceptP2PPicks :: AppHandler () acceptP2PPicks = withCurrentUser_ $ \n -> do p2p <- addOwnerValidate n :: AppHandler (Strategy P2PPicksType) debugM "P2PPicks" $ "Received p2ppicks from user (" ++ T.unpack n ++ "): " ++ show p2p Just p2pid <- insertStrategy n p2p writeJSON $ object [ "id" .= p2pid ] putP2PPicks :: AppHandler () putP2PPicks = withCurrentUser_ $ \n -> do p2p <- addOwnerValidate n :: AppHandler (Entity (Strategy P2PPicksType)) debugM "P2PPicks" $ "Received update to p2ppicks from user (" ++ T.unpack n ++ "): " ++ show p2p -- kill thread, update in database deactivateStrategy n updateStrategy p2p deleteP2PPicks :: AppHandler () deleteP2PPicks = withCurrentUser_ $ \n -> do Just p2pid <- getParam "id" debugM "P2PPicks" $ "Delete p2ppicks from user (" ++ T.unpack n ++ "): " ++ show p2pid deactivateStrategy n let stratKey = intToKey (readBS p2pid) :: AutoKey (Strategy P2PPicksType) deleteStrategy stratKey
WraithM/peertrader-backend
src/PeerTrader/Route/P2PPicks.hs
bsd-3-clause
2,460
0
14
696
562
288
274
50
1
-- | Defines document template module Text.PDF.Slave.Template( TemplateName , TemplateInput , TemplateBody , TemplateBibtex , DependencyBody , BibTexBody , TemplateDependency(..) , Template(..) , TemplateDependencyFile(..) , TemplateFile(..) ) where import Control.Monad (mzero, unless) import Data.ByteString (ByteString) import Data.Monoid import Data.Text as T import Data.Aeson import GHC.Generics import qualified Data.ByteString.Base64 as B64 import qualified Data.Map.Strict as M import qualified Data.Text.Encoding as T -- | Template unique name type TemplateName = Text -- | A template takes simple YAML document as input type TemplateInput = Value -- | Template body is text with .htex content type TemplateBody = Text -- | Template can define additional bibtex database type TemplateBibtex = Text -- | Dependency can be a binary file type DependencyBody = ByteString -- | Content of bibtex file type BibTexBody = Text -- | Template has different types of dependencies, each type of the dependecy -- has own affect on rendering pipe. data TemplateDependency = -- | Bibtex file for references to other documents. Need call to bibtex BibtexDep BibTexBody -- | HTex file that need to be compiled to .tex file | TemplateDep Template -- | HTex file that need to be compiled to .pdf file | TemplatePdfDep Template -- | Any other file that doesn't need a compilation (listings, images, etc) | OtherDep DependencyBody deriving (Generic, Show) instance FromJSON TemplateDependency where parseJSON val@(Object o) = do depType <- o .: "type" case T.toLower . T.strip $ depType of "bibtex" -> BibtexDep <$> o .: "body" "template" -> TemplateDep <$> parseJSON val "template_pdf" -> TemplatePdfDep <$> parseJSON val "other" -> do (t :: Text) <- o .: "body" either (\e -> fail $ "Cannot decode dependency body (base64): " <> e) (return . OtherDep) $ B64.decode . T.encodeUtf8 $ t _ -> fail $ "Unknown template type " <> unpack depType parseJSON _ = mzero instance ToJSON TemplateDependency where toJSON d = case d of BibtexDep body -> object [ "type" .= ("bibtex" :: Text) , "body" .= body ] TemplateDep body -> let Object o1 = object [ "type" .= ("template" :: Text) ] Object o2 = toJSON body in Object (o1 <> o2) TemplatePdfDep body -> let Object o1 = object [ "type" .= ("template_pdf" :: Text) ] Object o2 = toJSON body in Object (o1 <> o2) OtherDep bs -> object [ "type" .= ("other" :: Text) , "body" .= (T.decodeUtf8 . B64.encode $ bs) ] -- | Description of document template data Template = Template { -- | Template has human readable name templateName :: TemplateName -- | Template expects input in YAML format , templateInput :: Maybe TemplateInput -- | Template contents , templateBody :: TemplateBody -- | Template dependencies (bibtex, listings, other htex files) , templateDeps :: M.Map TemplateName TemplateDependency -- | Additional flags for `haskintex` , templateHaskintexOpts :: [Text] } deriving (Generic, Show) instance FromJSON Template where parseJSON (Object o) = do flag <- o .: "bundle" unless flag $ fail "Expected bundle template format, but got ordinary template" Template <$> o .: "name" <*> o .:? "input" <*> o .: "body" <*> o .:? "dependencies" .!= mempty <*> o .:? "haskintex-opts" .!= mempty parseJSON _ = mzero instance ToJSON Template where toJSON Template{..} = object [ "name" .= templateName , "input" .= templateInput , "body" .= templateBody , "dependencies" .= templateDeps , "haskintex-opts" .= templateHaskintexOpts , "bundle" .= True ] -- | Same as 'TemplateDependency' but keeps contents in separate files data TemplateDependencyFile = -- | Bibtex file for references to other documents. Need call to bibtex. -- Name of dependency is a filename with contents. BibtexDepFile -- | HTex file that need to be compiled to .tex file -- Name of dependency defines a subfolder for the template. | TemplateDepFile TemplateFile -- | HTex file that need to be compiled to .pdf file -- Name of dependency deinfes a subfolder for the template. | TemplatePdfDepFile TemplateFile -- | Any other file that doesn't need a compilation (listings, images, etc) -- Name of dependency is a filename with contents. | OtherDepFile deriving (Generic, Show) instance FromJSON TemplateDependencyFile where parseJSON val@(Object o) = do depType <- o .: "type" case T.toLower . T.strip $ depType of "bibtex" -> pure BibtexDepFile "template" -> TemplateDepFile <$> parseJSON val "template_pdf" -> TemplatePdfDepFile <$> parseJSON val "other" -> pure OtherDepFile _ -> fail $ "Unknown template type " <> unpack depType parseJSON _ = mzero instance ToJSON TemplateDependencyFile where toJSON d = case d of BibtexDepFile -> object [ "type" .= ("bibtex" :: Text) ] TemplateDepFile body -> let Object o1 = object [ "type" .= ("template" :: Text) ] Object o2 = toJSON body in Object (o1 <> o2) TemplatePdfDepFile body -> let Object o1 = object [ "type" .= ("template_pdf" :: Text) ] Object o2 = toJSON body in Object (o1 <> o2) OtherDepFile -> object [ "type" .= ("other" :: Text) ] -- | Same as 'Template', but holds info about template content and dependencies -- in other files. data TemplateFile = TemplateFile { -- | Template has human readable name templateFileName :: TemplateName -- | Template expects input in JSON format. The field contains filename of the YAML file. , templateFileInput :: Maybe Text -- | Template contents filename. , templateFileBody :: Text -- | Template dependencies (bibtex, listings, other htex files) , templateFileDeps :: M.Map TemplateName TemplateDependencyFile -- | Additional flags for `haskintex` , templateFileHaskintexOpts :: [Text] } deriving (Generic, Show) instance FromJSON TemplateFile where parseJSON (Object o) = do mflag <- o .:? "bundle" case mflag of Just True -> fail "Expected ordinary template format, but got bundle template" _ -> return () TemplateFile <$> o .: "name" <*> o .:? "input" <*> o .: "body" <*> o .:? "dependencies" .!= mempty <*> o .:? "haskintex-opts" .!= mempty parseJSON _ = mzero instance ToJSON TemplateFile where toJSON TemplateFile{..} = object [ "name" .= templateFileName , "input" .= templateFileInput , "body" .= templateFileBody , "dependencies" .= templateFileDeps , "haskintex-opts" .= templateFileHaskintexOpts ]
NCrashed/pdf-slave
pdf-slave-template/src/Text/PDF/Slave/Template.hs
bsd-3-clause
6,978
4
21
1,764
1,478
790
688
-1
-1
#!/usr/local/bin/runghc {-# LANGUAGE OverloadedStrings #-} import Interactive info = "Math trainer n3 : cubes of n" main = interactive info (\x -> x*x*x)
alexander31415926535/Liftconsole
math-tutor3.hs
bsd-3-clause
159
0
9
28
37
21
16
4
1
{-| Module : Diplomacy.OrderValidation Description : Definition of order validation Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Diplomacy.OrderValidation ( ValidityCharacterization(..) , ArgumentList(..) , ValidityCriterion(..) , SomeValidityCriterion(..) , AdjustSetValidityCriterion(..) , ValidityTag , AdjustSetValidityTag , synthesize , analyze , moveVOC , supportVOC , convoyVOC , surrenderVOC , withdrawVOC , AdjustSubjects(..) , disbandSubjectVOC , buildSubjectVOC , continueSubjectVOC , adjustSubjectsVOC ) where import GHC.Exts (Constraint) import Control.Monad import Control.Applicative import qualified Data.Map as M import qualified Data.Set as S import Data.MapUtil import Data.AtLeast import Data.Functor.Identity import Data.Functor.Constant import Data.Functor.Compose import Data.List as L import Diplomacy.GreatPower import Diplomacy.Aligned import Diplomacy.Unit import Diplomacy.Phase import Diplomacy.Subject import Diplomacy.OrderType import Diplomacy.OrderObject import Diplomacy.Order import Diplomacy.Province import Diplomacy.Zone import Diplomacy.ZonedSubject import Diplomacy.Occupation import Diplomacy.Dislodgement import Diplomacy.Control import Diplomacy.SupplyCentreDeficit import Diplomacy.OrderResolution import Debug.Trace -- Each one of these constructors is associated with a set. data ValidityCriterion (phase :: Phase) (order :: OrderType) where MoveValidSubject :: ValidityCriterion Typical Move MoveUnitCanOccupy :: ValidityCriterion Typical Move MoveReachable :: ValidityCriterion Typical Move SupportValidSubject :: ValidityCriterion Typical Support SupporterAdjacent :: ValidityCriterion Typical Support SupporterCanOccupy :: ValidityCriterion Typical Support SupportedCanDoMove :: ValidityCriterion Typical Support ConvoyValidSubject :: ValidityCriterion Typical Convoy ConvoyValidConvoySubject :: ValidityCriterion Typical Convoy ConvoyValidConvoyTarget :: ValidityCriterion Typical Convoy SurrenderValidSubject :: ValidityCriterion Retreat Surrender WithdrawValidSubject :: ValidityCriterion Retreat Withdraw WithdrawAdjacent :: ValidityCriterion Retreat Withdraw WithdrawUnoccupiedZone :: ValidityCriterion Retreat Withdraw WithdrawUncontestedZone :: ValidityCriterion Retreat Withdraw WithdrawNotDislodgingZone :: ValidityCriterion Retreat Withdraw ContinueValidSubject :: ValidityCriterion Adjust Continue DisbandValidSubject :: ValidityCriterion Adjust Disband BuildValidSubject :: ValidityCriterion Adjust Build deriving instance Show (ValidityCriterion phase order) deriving instance Eq (ValidityCriterion phase order) deriving instance Ord (ValidityCriterion phase order) data SomeValidityCriterion (phase :: Phase) where SomeValidityCriterion :: ValidityCriterion phase order -> SomeValidityCriterion phase instance Show (SomeValidityCriterion phase) where show (SomeValidityCriterion vc) = case vc of MoveValidSubject -> show vc MoveUnitCanOccupy -> show vc MoveReachable -> show vc SupportValidSubject -> show vc SupporterAdjacent -> show vc SupporterCanOccupy -> show vc SupportedCanDoMove -> show vc ConvoyValidSubject -> show vc ConvoyValidConvoySubject -> show vc ConvoyValidConvoyTarget -> show vc SurrenderValidSubject -> show vc WithdrawValidSubject -> show vc WithdrawAdjacent -> show vc WithdrawUnoccupiedZone -> show vc WithdrawUncontestedZone -> show vc WithdrawNotDislodgingZone -> show vc ContinueValidSubject -> show vc DisbandValidSubject -> show vc BuildValidSubject -> show vc instance Eq (SomeValidityCriterion phase) where SomeValidityCriterion vc1 == SomeValidityCriterion vc2 = case (vc1, vc2) of (MoveValidSubject, MoveValidSubject) -> True (MoveUnitCanOccupy, MoveUnitCanOccupy) -> True (MoveReachable, MoveReachable) -> True (SupportValidSubject, SupportValidSubject) -> True (SupporterAdjacent, SupporterAdjacent) -> True (SupporterCanOccupy, SupporterCanOccupy) -> True (SupportedCanDoMove, SupportedCanDoMove) -> True (ConvoyValidSubject, ConvoyValidSubject) -> True (ConvoyValidConvoySubject, ConvoyValidConvoySubject) -> True (ConvoyValidConvoyTarget, ConvoyValidConvoyTarget) -> True (SurrenderValidSubject, SurrenderValidSubject) -> True (WithdrawValidSubject, WithdrawValidSubject) -> True (WithdrawAdjacent, WithdrawAdjacent) -> True (WithdrawUnoccupiedZone, WithdrawUnoccupiedZone) -> True (WithdrawUncontestedZone, WithdrawUncontestedZone) -> True (WithdrawNotDislodgingZone, WithdrawNotDislodgingZone) -> True (ContinueValidSubject, ContinueValidSubject) -> True (DisbandValidSubject, DisbandValidSubject) -> True (BuildValidSubject, BuildValidSubject) -> True _ -> False instance Ord (SomeValidityCriterion phase) where SomeValidityCriterion vc1 `compare` SomeValidityCriterion vc2 = show vc1 `compare` show vc2 data AdjustSetValidityCriterion where RequiredNumberOfDisbands :: AdjustSetValidityCriterion AdmissibleNumberOfBuilds :: AdjustSetValidityCriterion OnlyContinues :: AdjustSetValidityCriterion deriving instance Eq AdjustSetValidityCriterion deriving instance Ord AdjustSetValidityCriterion deriving instance Show AdjustSetValidityCriterion -- | All ProvinceTargets which a unit can legally occupy. unitCanOccupy :: Unit -> S.Set ProvinceTarget unitCanOccupy unit = case unit of Army -> S.map Normal . S.filter (not . isWater) $ S.fromList [minBound..maxBound] Fleet -> S.fromList $ do pr <- [minBound..maxBound] guard (not (isInland pr)) case provinceCoasts pr of [] -> return $ Normal pr xs -> fmap Special xs -- | All places to which a unit could possibly move (without regard for -- occupation rules as specified by unitCanOccupy). -- The Occupation parameter is needed to determine which convoys are possible. -- If it's nothing, we don't consider convoy routes. validMoveAdjacency :: Maybe Occupation -> Subject -> S.Set ProvinceTarget validMoveAdjacency occupation subject = case subjectUnit subject of Army -> case occupation of Nothing -> S.fromList $ neighbours pt Just o -> (S.fromList $ neighbours pt) `S.union` (S.map Normal (convoyTargets o pr)) Fleet -> S.fromList $ do n <- neighbours pt let np = ptProvince n let ppt = ptProvince pt -- If we have two coastal places, we must guarantee that they have a -- common coast. guard (not (isCoastal np) || not (isCoastal ppt) || not (null (commonCoasts pt n))) return n where pt = subjectProvinceTarget subject pr = ptProvince pt convoyPaths :: Occupation -> Province -> [(Province, [Province])] convoyPaths occupation pr = filter ((/=) pr . fst) . fmap (\(x, y, z) -> (x, y : z)) . paths occupiedByFleet pickCoastal . pure $ pr where occupiedByFleet pr = case provinceOccupier pr occupation of Just aunit -> alignedThing aunit == Fleet _ -> False pickCoastal pr = if isCoastal pr then Just pr else Nothing convoyTargets :: Occupation -> Province -> S.Set Province convoyTargets occupation = S.fromList . fmap fst . convoyPaths occupation validMoveTargets :: Maybe Occupation -> Subject -> S.Set ProvinceTarget validMoveTargets maybeOccupation subject = (validMoveAdjacency maybeOccupation subject) `S.intersection` (unitCanOccupy (subjectUnit subject)) -- | Valid support targets are any place where this subject could move without -- a convoy (this excludes the subject's own province target), and such that -- the common coast constraint is relaxed (a Fleet in Marseilles can support -- into Spain NC for example). validSupportTargets :: Subject -> S.Set ProvinceTarget validSupportTargets subject = S.fromList $ do x <- S.toList $ validMoveAdjacency Nothing subject guard (S.member x (unitCanOccupy (subjectUnit subject))) provinceTargetCluster x -- | Given two ProvinceTargets--the place from which support comes, and the -- place to which support is directed--we can use an Occupation to discover -- every subject which could be supported by this hypothetical supporter. validSupportSubjects :: Occupation -> ProvinceTarget -- ^ Source -> ProvinceTarget -- ^ Target -> S.Set Subject validSupportSubjects occupation source target = M.foldWithKey f S.empty occupation where f zone aunit = if Zone source /= zone -- validMoveTargets will give us non-hold targets, so we explicitly -- handle the case of a hold. && (Zone target == zone -- If the subject here could move to the target, then it's a valid -- support target. We are careful *not* to use Zone-equality here, -- because in the case of supporting fleets into coastal territories, -- we want to rule out supporting to an unreachable coast. || S.member target (validMoveTargets (Just occupation) subject')) then S.insert subject' else id where subject' = (alignedThing aunit, zoneProvinceTarget zone) -- | Subjects which could act as convoyers: fleets in water. validConvoyers :: Maybe GreatPower -> Occupation -> S.Set Subject validConvoyers greatPower = M.foldWithKey f S.empty where f zone aunit = case unit of Fleet -> if isWater (ptProvince pt) && ( greatPower == Nothing || greatPower == Just (alignedGreatPower aunit) ) then S.insert (unit, pt) else id _ -> id where pt = zoneProvinceTarget zone unit = alignedThing aunit -- | Subjects which could be convoyed: armies on coasts. validConvoySubjects :: Occupation -> S.Set Subject validConvoySubjects = M.foldWithKey f S.empty where f zone aunit = if unit == Army && isCoastal (ptProvince pt) then S.insert (unit, pt) else id where unit = alignedThing aunit pt = zoneProvinceTarget zone -- | Valid convoy destinations: those reachable by some path of fleets in -- water which includes the convoyer subject, and initiates at the convoying -- subject's province target. validConvoyTargets :: Occupation -> Subject -> Subject -> S.Set ProvinceTarget validConvoyTargets occupation subjectConvoyer subjectConvoyed = let allConvoyPaths = convoyPaths occupation prConvoyed convoyPathsWithThis = filter (elem prConvoyer . snd) allConvoyPaths in S.fromList (fmap (Normal . fst) convoyPathsWithThis) where prConvoyer = ptProvince (subjectProvinceTarget subjectConvoyer) prConvoyed = ptProvince (subjectProvinceTarget subjectConvoyed) -- Would be nice to have difference, to simulate "not". Then we could say -- "not contested", "not attacking province" and "not occupied" and providing -- those contested, attacking province, and occupied sets, rather than -- providing their complements. -- -- Ok, so for withdraw, we wish to say -- -- subject : valid subject -- target : valid unconvoyed move target -- & not contested area -- & not dislodging province (of subject's province target) -- & not occupied province setOfAllProvinceTargets :: S.Set ProvinceTarget setOfAllProvinceTargets = S.fromList [minBound..maxBound] setOfAllZones :: S.Set Zone setOfAllZones = S.map Zone setOfAllProvinceTargets zoneSetToProvinceTargetSet :: S.Set Zone -> S.Set ProvinceTarget zoneSetToProvinceTargetSet = S.fold f S.empty where f zone = S.union (S.fromList (provinceTargetCluster (zoneProvinceTarget zone))) occupiedZones :: Occupation -> S.Set Zone occupiedZones = S.map (Zone . snd) . S.fromList . allSubjects Nothing -- A zone is contested iff there is at least one bounced move order to it, and -- no successful move order to it. contestedZones :: M.Map Zone (Aligned Unit, SomeResolved OrderObject Typical) -> S.Set Zone contestedZones = M.foldWithKey g S.empty . M.fold f M.empty where f :: (Aligned Unit, SomeResolved OrderObject Typical) -> M.Map Zone Bool -> M.Map Zone Bool f (aunit, SomeResolved (object, res)) = case object of MoveObject pt -> case res of Just (MoveBounced _) -> M.alter alteration (Zone pt) _ -> id where alteration (Just bool) = case res of Nothing -> Just False _ -> Just bool alteration Nothing = case res of Nothing -> Just False _ -> Just True _ -> id g :: Zone -> Bool -> S.Set Zone -> S.Set Zone g zone bool = case bool of True -> S.insert zone False -> id -- | The Zone, if any, which dislodged a unit in this Zone, without the -- use of a convoy! dislodgingZones :: M.Map Zone (Aligned Unit, SomeResolved OrderObject Typical) -> Zone -> S.Set Zone dislodgingZones resolved zone = M.foldWithKey f S.empty resolved where f :: Zone -> (Aligned Unit, SomeResolved OrderObject Typical) -> S.Set Zone -> S.Set Zone f zone' (aunit, SomeResolved (object, res)) = case object of MoveObject pt -> if Zone pt == zone then case (routes, res) of ([], Nothing) -> S.insert zone' _ -> id else id where routes = successfulConvoyRoutes (convoyRoutes resolved subject pt) subject = (alignedThing aunit, zoneProvinceTarget zone') _ -> id {- data AdjustPhaseOrderSet where AdjustPhaseOrderSet :: Maybe (Either (S.Set (Order Adjust Build)) (S.Set (Order Adjust Disband))) -> S.Set (Order Adjust Continue) -> AdjustPhaseOrderSet validAdjustOrderSet :: GreatPower -> Occupation -> Control -> Maybe (Either (S.Set (Order Adjust Build)) (S.Set (Order Adjust Disband))) validAdjustOrderSet greatPower occupation control -- All possible sets of build orders: | deficit < 0 = Just . Left $ allBuildOrderSets | deficit > 0 = Just . Right $ allDisbandOrderSets | otherwise = Nothing where deficit = supplyCentreDeficit greatPower occupation control -- To construct all build order sets, we take all subsets of the home -- supply centres of cardinality at most |deficit| and for each of these, -- make a subject for each kind of unit which can occupy that place. Note -- that in the case of special areas like St. Petersburg, we have 3 options! allBuildOrderSets = flattenSet $ (S.map . S.map) (\s -> Order (s, BuildObject)) allBuildOrderSubjects -- To construct all disband order sets, we take all subsets of this great -- power's subjects of cardinality exactly deficit. -- All subsets of the home supply centres, for each unit which can go -- there. allDisbandOrderSets = S.empty -- New strategy: -- We have all of the valid ProvinceTargets. -- For each of these, get the set of all pairs with units which can go -- there. -- Now pick from this set of sets; all ways to pick one from each set -- without going over |deficit| --allBuildOrderSubjects :: S.Set (S.Set Subject) --allBuildOrderSubjects = S.map (S.filter (\(unit, pt) -> S.member pt (unitCanOccupy unit))) . (S.map (setCartesianProduct (S.fromList [minBound..maxBound]))) $ allBuildOrderProvinceTargetSets allBuildOrderSubjects :: S.Set (S.Set Subject) allBuildOrderSubjects = foldr (\i -> S.union (pickSet i candidateSubjectSets)) S.empty [0..(abs deficit)] --allBuildOrderSubjects = S.filter ((flip (<=)) (abs deficit) . S.size) (powerSet candidateSubjects) --candidateSubjects :: S.Set Subject --candidateSubjects = S.filter (\(unit, pt) -> S.member pt (unitCanOccupy unit)) ((setCartesianProduct (S.fromList [minBound..maxBound])) candidateSupplyCentreSet) candidateSubjectSets :: S.Set (S.Set Subject) candidateSubjectSets = S.map (\pt -> S.filter (\(unit, pt) -> S.member pt (unitCanOccupy unit)) (setCartesianProduct (S.fromList [minBound..maxBound]) (S.singleton pt))) candidateSupplyCentreSet -} -- All continue order subjects which would make sense without any other orders -- in context. candidateContinueSubjects :: GreatPower -> Occupation -> S.Set Subject candidateContinueSubjects greatPower = S.fromList . allSubjects (Just greatPower) -- All disband order subjects which would make sense without any other orders -- in context. candidateDisbandSubjects :: GreatPower -> Occupation -> S.Set Subject candidateDisbandSubjects greatPower = S.fromList . allSubjects (Just greatPower) -- All build subjects which would make sense without any other adjust orders -- in context: unoccupied home supply centre controlled by this great power -- which the unit could legally occupy. candidateBuildSubjects :: GreatPower -> Occupation -> Control -> S.Set Subject candidateBuildSubjects greatPower occupation control = let candidateTargets = S.fromList $ candidateSupplyCentreTargets greatPower occupation control units :: S.Set Unit units = S.fromList $ [minBound..maxBound] candidateSubjects :: S.Set Subject candidateSubjects = setCartesianProduct units candidateTargets in S.filter (\(u, pt) -> pt `S.member` unitCanOccupy u) candidateSubjects candidateSupplyCentreTargets :: GreatPower -> Occupation -> Control -> [ProvinceTarget] candidateSupplyCentreTargets greatPower occupation control = filter (not . (flip zoneOccupied) occupation . Zone) (controlledHomeSupplyCentreTargets greatPower control) controlledHomeSupplyCentreTargets :: GreatPower -> Control -> [ProvinceTarget] controlledHomeSupplyCentreTargets greatPower control = (controlledHomeSupplyCentres greatPower control >>= provinceTargets) controlledHomeSupplyCentres :: GreatPower -> Control -> [Province] controlledHomeSupplyCentres greatPower control = filter ((==) (Just greatPower) . (flip controller) control) (homeSupplyCentres greatPower) homeSupplyCentres :: GreatPower -> [Province] homeSupplyCentres greatPower = filter (isHome greatPower) supplyCentres setCartesianProduct :: (Ord t, Ord s) => S.Set t -> S.Set s -> S.Set (t, s) setCartesianProduct xs ys = S.foldr (\x -> S.union (S.map ((,) x) ys)) S.empty xs powerSet :: Ord a => S.Set a -> S.Set (S.Set a) powerSet = S.fold powerSetFold (S.singleton (S.empty)) where powerSetFold :: Ord a => a -> S.Set (S.Set a) -> S.Set (S.Set a) powerSetFold elem pset = S.union (S.map (S.insert elem) pset) pset flattenSet :: Ord a => S.Set (S.Set a) -> S.Set a flattenSet = S.foldr S.union S.empty setComplement :: Ord a => S.Set a -> S.Set a -> S.Set a setComplement relativeTo = S.filter (not . (flip S.member) relativeTo) -- Pick 1 thing from each of the sets to get a set of cardinality at most -- n. -- If there are m sets in the input set, you get a set of cardinality -- at most m. -- If n < 0 you get the empty set. pickSet :: Ord a => Int -> S.Set (S.Set a) -> S.Set (S.Set a) pickSet n sets | n <= 0 = S.singleton S.empty | otherwise = case S.size sets of 0 -> S.empty m -> let xs = S.findMin sets xss = S.delete xs sets in case S.size xs of 0 -> pickSet n xss l -> let rest = pickSet (n-1) xss in S.map (\(y, ys) -> S.insert y ys) (setCartesianProduct xs rest) `S.union` pickSet n xss choose :: Ord a => Int -> S.Set a -> S.Set (S.Set a) choose n set | n <= 0 = S.singleton (S.empty) | otherwise = case S.size set of 0 -> S.empty m -> let x = S.findMin set withoutX = choose n (S.delete x set) withX = S.map (S.insert x) (choose (n-1) (S.delete x set)) in withX `S.union` withoutX newtype Intersection t = Intersection [t] newtype Union t = Union [t] evalIntersection :: t -> (t -> t -> t) -> Intersection t -> t evalIntersection empty intersect (Intersection is) = foldr intersect empty is evalUnion :: t -> (t -> t -> t) -> Union t -> t evalUnion empty union (Union us) = foldr union empty us -- TBD better name, obviously. -- No Functor superclass because, due to constraints on the element type, this -- may not really be a Functor. class SuitableFunctor (f :: * -> *) where type SuitableFunctorConstraint f :: * -> Constraint suitableEmpty :: f t suitableUnion :: SuitableFunctorConstraint f t => f t -> f t -> f t suitableIntersect :: SuitableFunctorConstraint f t => f t -> f t -> f t suitableMember :: SuitableFunctorConstraint f t => t -> f t -> Bool suitableFmap :: ( SuitableFunctorConstraint f t , SuitableFunctorConstraint f s ) => (t -> s) -> f t -> f s suitablePure :: SuitableFunctorConstraint f t => t -> f t -- Instead of <*> we offer bundle, which can be used with -- suitableFmap and uncurry to emulate <*>. suitableBundle :: ( SuitableFunctorConstraint f t , SuitableFunctorConstraint f s ) => f t -> f s -> f (t, s) suitableJoin :: SuitableFunctorConstraint f t => f (f t) -> f t suitableBind :: ( SuitableFunctorConstraint f t , SuitableFunctorConstraint f (f s) , SuitableFunctorConstraint f s ) => f t -> (t -> f s) -> f s suitableBind x k = suitableJoin (suitableFmap k x) instance SuitableFunctor [] where type SuitableFunctorConstraint [] = Eq suitableEmpty = [] suitableUnion = union suitableIntersect = intersect suitableMember = elem suitableFmap = fmap suitableBundle = cartesianProduct where cartesianProduct :: (Eq a, Eq b) => [a] -> [b] -> [(a, b)] cartesianProduct xs ys = foldr (\x -> suitableUnion (fmap ((,) x) ys)) suitableEmpty xs suitablePure = pure suitableJoin = join -- Shit, can't throw functions into a set! -- Ok, so Ap is out; but can implement it with join instead. instance SuitableFunctor S.Set where type SuitableFunctorConstraint S.Set = Ord suitableEmpty = S.empty suitableUnion = S.union suitableIntersect = S.intersection suitableMember = S.member suitableFmap = S.map suitableBundle = setCartesianProduct suitablePure = S.singleton suitableJoin = S.foldr suitableUnion suitableEmpty -- Description of validity is here: given the prior arguments, produce a -- tagged union of intersections for the next argument. data ValidityCharacterization (g :: * -> *) (f :: * -> *) (k :: [*]) where VCNil :: ( SuitableFunctor f ) => ValidityCharacterization g f '[] VCCons :: ( SuitableFunctor f , SuitableFunctorConstraint f t ) => (ArgumentList Identity Identity ts -> TaggedIntersectionOfUnions g f t) -> ValidityCharacterization g f ts -> ValidityCharacterization g f (t ': ts) validityCharacterizationTrans :: (forall s . g s -> h s) -> ValidityCharacterization g f ts -> ValidityCharacterization h f ts validityCharacterizationTrans natTrans vc = case vc of VCNil -> VCNil VCCons f rest -> VCCons (taggedIntersectionOfUnionsTrans natTrans . f) (validityCharacterizationTrans natTrans rest) -- Each thing which we intersect is endowed with a tag (the functor g). type TaggedIntersectionOfUnions (g :: * -> *) (f :: * -> *) (t :: *) = Intersection (g (Union (f t))) taggedIntersectionOfUnionsTrans :: (forall s . g s -> h s) -> TaggedIntersectionOfUnions g f t -> TaggedIntersectionOfUnions h f t taggedIntersectionOfUnionsTrans trans iou = case iou of Intersection is -> Intersection (fmap trans is) evalTaggedIntersectionOfUnions :: ( SuitableFunctor f , SuitableFunctorConstraint f t ) => (forall s . g s -> s) -> TaggedIntersectionOfUnions g f t -> f t evalTaggedIntersectionOfUnions exitG (Intersection is) = -- Must take special care here, since we have no identity under intersection. -- This is unfortunate, but necessary if we want to admit [] and Set as -- suitable functors! case is of [] -> suitableEmpty [x] -> evalUnion suitableEmpty suitableUnion (exitG x) x : xs -> suitableIntersect (evalUnion suitableEmpty suitableUnion (exitG x)) (evalTaggedIntersectionOfUnions exitG (Intersection xs)) checkTaggedIntersectionOfUnions :: ( SuitableFunctor f , SuitableFunctorConstraint f t ) => (forall s . g s -> s) -> (forall s . g s -> r) -> r -> (r -> r -> r) -> t -> TaggedIntersectionOfUnions g f t -> r checkTaggedIntersectionOfUnions exitG inMonoid mempty mappend x (Intersection is) = foldr (\xs b -> if suitableMember x (evalUnion suitableEmpty suitableUnion (exitG xs)) then b else mappend (inMonoid xs) b) mempty is data ArgumentList (g :: * -> *) (f :: * -> *) (k :: [*]) where ALNil :: ArgumentList g f '[] ALCons :: g (f t) -> ArgumentList g f ts -> ArgumentList g f (t ': ts) type family Every (c :: * -> Constraint) (ts :: [*]) :: Constraint where Every c '[] = () Every c (t ': ts) = (c t, Every c ts) instance Every Show ts => Show (ArgumentList Identity Identity ts) where show al = case al of ALNil -> "ALNil" ALCons (Identity (Identity x)) rest -> "ALCons " ++ show x ++ " (" ++ show rest ++ ")" instance Every Eq ts => Eq (ArgumentList Identity Identity ts) where x == y = case (x, y) of (ALNil, ALNil) -> True (ALCons (Identity (Identity x')) xs, ALCons (Identity (Identity y')) ys) -> x' == y' && xs == ys instance (Every Ord ts, Every Eq ts) => Ord (ArgumentList Identity Identity ts) where x `compare` y = case (x, y) of (ALNil, ALNil) -> EQ (ALCons (Identity (Identity x')) xs, ALCons (Identity (Identity y')) ys) -> case x' `compare` y' of LT -> LT GT -> GT EQ -> xs `compare` ys argListTrans :: (forall s . g s -> h s) -> ArgumentList g f ts -> ArgumentList h f ts argListTrans natTrans argList = case argList of ALNil -> ALNil ALCons x rest -> ALCons (natTrans x) (argListTrans natTrans rest) argListTrans1 :: Functor g => (forall s . f s -> h s) -> ArgumentList g f ts -> ArgumentList g h ts argListTrans1 natTrans argList = case argList of ALNil -> ALNil ALCons x rest -> ALCons (fmap natTrans x) (argListTrans1 natTrans rest) -- This function is to use the VCCons constructor functions to build an f -- coontaining all argument lists. Obviously, the SuitableFunctor must be -- capable of carrying ArgumentList Identity Identity ts -- -- No, we should never have to union or intersect on f's containing -- ArgumentList values, right? evalValidityCharacterization :: ( SuitableFunctor f , ValidityCharacterizationConstraint f ts ) => ValidityCharacterization Identity f ts -> f (ArgumentList Identity Identity ts) evalValidityCharacterization vc = case vc of VCNil -> suitablePure ALNil VCCons next rest -> let rest' = evalValidityCharacterization rest in suitableBind rest' $ \xs -> suitableBind (evalTaggedIntersectionOfUnions runIdentity (next xs)) $ \y -> suitablePure (ALCons (Identity (Identity y)) xs) type family ValidityCharacterizationConstraint (f :: * -> *) (ts :: [*]) :: Constraint where ValidityCharacterizationConstraint f '[] = ( SuitableFunctorConstraint f (ArgumentList Identity Identity '[]) ) ValidityCharacterizationConstraint f (t ': ts) = ( SuitableFunctorConstraint f t , SuitableFunctorConstraint f (f t) , SuitableFunctorConstraint f (f (ArgumentList Identity Identity (t ': ts))) , SuitableFunctorConstraint f (t, ArgumentList Identity Identity ts) , SuitableFunctorConstraint f (ArgumentList Identity Identity (t ': ts)) , SuitableFunctorConstraint f (ArgumentList Identity Identity ts) , ValidityCharacterizationConstraint f ts ) type Constructor ts t = ArgumentList Identity Identity ts -> t type Deconstructor ts t = t -> ArgumentList Identity Identity ts -- | VOC is an acronym for Valid Order Characterization type VOC g f ts t = (Constructor ts t, Deconstructor ts t, ValidityCharacterization g f ts) synthesize :: ( SuitableFunctor f , SuitableFunctorConstraint f (ArgumentList Identity Identity ts) , SuitableFunctorConstraint f t , ValidityCharacterizationConstraint f ts ) => (forall s . g s -> Identity s) -> VOC g f ts t -> f t synthesize trans (cons, _, vc) = let fArgList = evalValidityCharacterization (validityCharacterizationTrans trans vc) in suitableFmap cons fArgList analyze :: (forall s . g s -> s) -> (forall s . g s -> r) -> r -> (r -> r -> r) -> VOC g f ts t -> t -> r analyze exitG inMonoid mempty mappend (_, uncons, vd) x = -- We unconstruct into an argument list, and now we must compare its -- members with the description let challenge = uncons x in analyze' exitG inMonoid mempty mappend challenge vd where analyze' :: (forall s . g s -> s) -> (forall s . g s -> r) -> r -> (r -> r -> r) -> ArgumentList Identity Identity ts -> ValidityCharacterization g f ts -> r analyze' exitG inMonoid mempty mappend challenge vd = case (challenge, vd) of (ALNil, VCNil) -> mempty (ALCons (Identity (Identity x)) rest, VCCons f rest') -> let possibilities = f rest -- So here we are. possibilities is an intersection of unions. -- When evaluated (intersection taken) they give the set of all -- valid arguments here. -- BUT here we don't just take the intersection! No, we need -- to check membership in EACH of the intersectands, and if we -- find there's no membership, we must grab the tag and mappend -- it. here = checkTaggedIntersectionOfUnions exitG inMonoid mempty mappend x possibilities there = analyze' exitG inMonoid mempty mappend rest rest' in here `mappend` there -- Simple example case to see if things are working somewhat well. type ValidityTag phase order = (,) (ValidityCriterion phase order) type AdjustSetValidityTag = (,) (AdjustSetValidityCriterion) moveVOC :: GreatPower -> Occupation -> VOC (ValidityTag Typical Move) S.Set '[ProvinceTarget, Subject] (Order Typical Move) moveVOC greatPower occupation = (cons, uncons, vc) where vc :: ValidityCharacterization (ValidityTag Typical Move) S.Set '[ProvinceTarget, Subject] vc = VCCons (\(ALCons (Identity (Identity subject)) ALNil) -> Intersection [ (MoveUnitCanOccupy, Union [unitCanOccupy (subjectUnit subject)]) , (MoveReachable, Union [S.singleton (subjectProvinceTarget subject), validMoveAdjacency (Just occupation) subject]) ]) . VCCons (\ALNil -> Intersection [(MoveValidSubject, Union [S.fromList (allSubjects (Just greatPower) occupation)])]) $ VCNil cons :: ArgumentList Identity Identity '[ProvinceTarget, Subject] -> Order Typical Move cons argList = case argList of ALCons (Identity (Identity pt)) (ALCons (Identity (Identity subject)) ALNil) -> Order (subject, MoveObject pt) uncons :: Order Typical Move -> ArgumentList Identity Identity '[ProvinceTarget, Subject] uncons (Order (subject, MoveObject pt)) = ALCons (return (return pt)) (ALCons (return (return subject)) ALNil) supportVOC :: GreatPower -> Occupation -> VOC (ValidityTag Typical Support) S.Set '[Subject, ProvinceTarget, Subject] (Order Typical Support) supportVOC greatPower occupation = (cons, uncons, vc) where vc :: ValidityCharacterization (ValidityTag Typical Support) S.Set '[Subject, ProvinceTarget, Subject] vc = -- Given a subject for the supporter, and a target for the support, we -- characterize every valid subject which can be supported. VCCons (\(ALCons (Identity (Identity pt)) (ALCons (Identity (Identity subject1)) ALNil)) -> Intersection [ (SupportedCanDoMove, Union [S.filter (/= subject1) (validSupportSubjects occupation (subjectProvinceTarget subject1) pt)]) ]) -- Given a subject (the one who offers support), we check every place -- into which that supporter could offer support; that's every place -- where it could move without a convoy (or one of the special coasts -- of that place). . VCCons (\(ALCons (Identity (Identity subject)) ALNil) -> Intersection [ (SupporterAdjacent, Union [validSupportTargets subject]) ]) . VCCons (\ALNil -> Intersection [(SupportValidSubject, Union [S.fromList (allSubjects (Just greatPower) occupation)])]) $ VCNil cons :: ArgumentList Identity Identity '[Subject, ProvinceTarget, Subject] -> Order Typical Support cons argList = case argList of ALCons (Identity (Identity subject2)) (ALCons (Identity (Identity pt)) (ALCons (Identity (Identity subject1)) ALNil)) -> Order (subject1, SupportObject subject2 pt) uncons :: Order Typical Support -> ArgumentList Identity Identity '[Subject, ProvinceTarget, Subject] uncons order = case order of Order (subject1, SupportObject subject2 pt) -> ALCons (Identity (Identity subject2)) (ALCons (Identity (Identity pt)) (ALCons (Identity (Identity subject1)) ALNil)) convoyVOC :: GreatPower -> Occupation -> VOC (ValidityTag Typical Convoy) S.Set '[ProvinceTarget, Subject, Subject] (Order Typical Convoy) convoyVOC greatPower occupation = (cons, uncons, vc) where vc :: ValidityCharacterization (ValidityTag Typical Convoy) S.Set '[ProvinceTarget, Subject, Subject] vc = VCCons (\(ALCons (Identity (Identity convoyed)) (ALCons (Identity (Identity convoyer)) ALNil)) -> Intersection [ (ConvoyValidConvoyTarget, Union [validConvoyTargets occupation convoyer convoyed]) ]) . VCCons (\(ALCons (Identity (Identity subject)) ALNil) -> Intersection [ (ConvoyValidConvoySubject, Union [validConvoySubjects occupation]) ]) . VCCons (\ALNil -> Intersection [ (ConvoyValidSubject, Union [validConvoyers (Just greatPower) occupation]) ]) $ VCNil cons :: ArgumentList Identity Identity '[ProvinceTarget, Subject, Subject] -> Order Typical Convoy cons al = case al of ALCons (Identity (Identity pt)) (ALCons (Identity (Identity convoyed)) (ALCons (Identity (Identity convoyer)) ALNil)) -> Order (convoyer, ConvoyObject convoyed pt) uncons :: Order Typical Convoy -> ArgumentList Identity Identity '[ProvinceTarget, Subject, Subject] uncons order = case order of Order (convoyer, ConvoyObject convoyed pt) -> ALCons (Identity (Identity pt)) (ALCons (Identity (Identity convoyed)) (ALCons (Identity (Identity convoyer)) ALNil)) surrenderVOC :: GreatPower -> Dislodgement -> VOC (ValidityTag Retreat Surrender) S.Set '[Subject] (Order Retreat Surrender) surrenderVOC greatPower dislodgement = (cons, uncons, vc) where vc = VCCons (\ALNil -> Intersection [ (SurrenderValidSubject, Union [S.fromList (allSubjects (Just greatPower) dislodgement)]) ]) $ VCNil cons :: ArgumentList Identity Identity '[Subject] -> Order Retreat Surrender cons al = case al of ALCons (Identity (Identity subject)) ALNil -> Order (subject, SurrenderObject) uncons :: Order Retreat Surrender -> ArgumentList Identity Identity '[Subject] uncons order = case order of Order (subject, SurrenderObject) -> ALCons (Identity (Identity subject)) ALNil withdrawVOC :: GreatPower -> M.Map Zone (Aligned Unit, SomeResolved OrderObject Typical) -> VOC (ValidityTag Retreat Withdraw) S.Set '[ProvinceTarget, Subject] (Order Retreat Withdraw) withdrawVOC greatPower resolved = (cons, uncons, vc) where (dislodgement, occupation) = dislodgementAndOccupation resolved vc = VCCons (\(ALCons (Identity (Identity subject)) ALNil) -> Intersection [ (WithdrawAdjacent, Union [validMoveTargets Nothing subject]) , (WithdrawNotDislodgingZone, Union [zoneSetToProvinceTargetSet $ S.difference setOfAllZones (dislodgingZones resolved (Zone (subjectProvinceTarget subject)))]) , (WithdrawUncontestedZone, Union [zoneSetToProvinceTargetSet $ S.difference setOfAllZones (contestedZones resolved)]) , (WithdrawUnoccupiedZone, Union [zoneSetToProvinceTargetSet $ S.difference setOfAllZones (occupiedZones occupation)]) ]) . VCCons (\ALNil -> Intersection [ (WithdrawValidSubject, Union [S.fromList (allSubjects (Just greatPower) dislodgement)]) ]) $ VCNil cons :: ArgumentList Identity Identity '[ProvinceTarget, Subject] -> Order Retreat Withdraw cons al = case al of ALCons (Identity (Identity pt)) (ALCons (Identity (Identity subject)) ALNil) -> Order (subject, WithdrawObject pt) uncons :: Order Retreat Withdraw -> ArgumentList Identity Identity '[ProvinceTarget, Subject] uncons order = case order of Order (subject, WithdrawObject pt) -> ALCons (Identity (Identity pt)) (ALCons (Identity (Identity subject)) ALNil) continueSubjectVOC :: GreatPower -> Occupation -> VOC (ValidityTag Adjust Continue) S.Set '[Subject] Subject continueSubjectVOC greatPower occupation = (cons, uncons, vc) where vc :: ValidityCharacterization (ValidityTag Adjust Continue) S.Set '[Subject] vc = VCCons (\ALNil -> Intersection [(ContinueValidSubject, Union [candidateContinueSubjects greatPower occupation])]) $ VCNil cons :: ArgumentList Identity Identity '[Subject] -> Subject cons al = case al of ALCons (Identity (Identity subject)) ALNil -> subject uncons :: Subject -> ArgumentList Identity Identity '[Subject] uncons subject = ALCons (Identity (Identity subject)) ALNil disbandSubjectVOC :: GreatPower -> Occupation -> VOC (ValidityTag Adjust Disband) S.Set '[Subject] Subject disbandSubjectVOC greatPower occupation = (cons, uncons, vc) where vc :: ValidityCharacterization (ValidityTag Adjust Disband) S.Set '[Subject] vc = VCCons (\ALNil -> Intersection [(DisbandValidSubject, Union [candidateDisbandSubjects greatPower occupation])]) $ VCNil cons :: ArgumentList Identity Identity '[Subject] -> Subject cons al = case al of ALCons (Identity (Identity subject)) ALNil -> subject uncons :: Subject -> ArgumentList Identity Identity '[Subject] uncons subject = ALCons (Identity (Identity subject)) ALNil -- Not a very useful factoring. Oh well, can make it sharper later if needed. buildSubjectVOC :: GreatPower -> Occupation -> Control -> VOC (ValidityTag Adjust Build) S.Set '[Subject] Subject buildSubjectVOC greatPower occupation control = (cons, uncons, vc) where vc :: ValidityCharacterization (ValidityTag Adjust Build) S.Set '[Subject] vc = VCCons (\ALNil -> Intersection [(BuildValidSubject, Union [candidateBuildSubjects greatPower occupation control])]) $ VCNil cons :: ArgumentList Identity Identity '[Subject] -> Subject cons al = case al of ALCons (Identity (Identity subject)) ALNil -> subject uncons :: Subject -> ArgumentList Identity Identity '[Subject] uncons subject = ALCons (Identity (Identity subject)) ALNil -- Next up: given the set of adjust orders (special datatype or really -- a set of SomeOrder?) give the valid subsets. Special datatype. data AdjustSubjects = AdjustSubjects { buildSubjects :: S.Set Subject , disbandSubjects :: S.Set Subject , continueSubjects :: S.Set Subject } deriving (Eq, Ord, Show) -- Here we assume that all of the subjects are valid according to -- the characterizations with the SAME occupation, control, and great power. -- -- Really though, what should be the output? Sets of SomeOrder are annoying, -- because the Ord instance there is not trivial. Why not sets of -- AdjustSubjects as we have here? -- For 0 deficit, we give the singleton set of the AdjustSubjects in -- which we make the build and disband sets empty. -- For > 0 deficit, we take all deficit-element subsets of the disband -- subjects, and for each of them we throw in the complement relative to -- the continue subjects, and no build subjects. -- For < 0 deficit, we take all (-deficit)-element or less subsets of the -- build subjects, and for each of them we throw in the complement relative -- to the continue subjects, and no disband subjects. adjustSubjectsVOC :: GreatPower -> Occupation -> Control -> AdjustSubjects -> VOC AdjustSetValidityTag S.Set '[AdjustSubjects] AdjustSubjects adjustSubjectsVOC greatPower occupation control subjects = (cons, uncons, vc) where deficit = supplyCentreDeficit greatPower occupation control vc :: ValidityCharacterization AdjustSetValidityTag S.Set '[AdjustSubjects] vc = VCCons (\ALNil -> tiu) $ VCNil cons :: ArgumentList Identity Identity '[AdjustSubjects] -> AdjustSubjects cons al = case al of ALCons (Identity (Identity x)) ALNil -> x uncons :: AdjustSubjects -> ArgumentList Identity Identity '[AdjustSubjects] uncons x = ALCons (Identity (Identity x)) ALNil tiu :: TaggedIntersectionOfUnions AdjustSetValidityTag S.Set AdjustSubjects tiu | deficit > 0 = let disbandSets = choose deficit disbands pairs = S.map (\xs -> (xs, continues `S.difference` xs)) disbandSets valids :: S.Set AdjustSubjects valids = S.map (\(disbands, continues) -> AdjustSubjects S.empty disbands continues) pairs in Intersection [(RequiredNumberOfDisbands, Union (fmap S.singleton (S.toList valids)))] | deficit < 0 = let buildSetsUnzoned :: [S.Set (S.Set Subject)] buildSetsUnzoned = fmap (\n -> choose n builds) [0..(-deficit)] -- buildSetsUnzoned is not quite what we want; its -- member sets may include subjects of the same -- zone. A fleet in Marseilles and an army in -- Marseilles, for instance. To remedy this, we -- set-map each one to and from ZonedSubjectDull, -- whose Eq/Ord instances ignore the unit and uses -- zone-equality. Then, to rule out duplicate sets, -- we do this again with the ZonedSubjectSharp -- type, which uses zone-equality but does not -- ignore the unit. This ensure that, for instance, -- the sets {(Fleet, Marseilles)} and -- {(Army, Marseilles)} can coexist in buildSets. buildSets :: [S.Set (S.Set Subject)] buildSets = fmap (S.map (S.map zonedSubjectSharp) . (S.map (S.map (ZonedSubjectSharp . zonedSubjectDull) . (S.map ZonedSubjectDull)))) buildSetsUnzoned pairs :: [S.Set (S.Set Subject, S.Set Subject)] pairs = (fmap . S.map) (\xs -> (xs, continues `S.difference` xs)) buildSets valids :: [S.Set AdjustSubjects] valids = (fmap . S.map) (\(builds, continues) -> AdjustSubjects builds S.empty continues) pairs in Intersection [(AdmissibleNumberOfBuilds, Union valids)] | otherwise = Intersection [(OnlyContinues, Union [S.singleton (AdjustSubjects S.empty S.empty continues)])] builds = buildSubjects subjects disbands = disbandSubjects subjects continues = continueSubjects subjects
avieth/diplomacy
Diplomacy/OrderValidation.hs
bsd-3-clause
45,631
369
21
11,150
10,701
5,732
4,969
-1
-1
module Util (normalizeFields) where import Data.Char import Data.List normalizeFields :: String -> [String] -> [String] normalizeFields name fields = map toSnakeCase xs where xs | all (uncapitalize name `isPrefixOf`) fields = map (drop (length name)) fields | otherwise = fields uncapitalize :: String -> String uncapitalize "" = "" uncapitalize (x:xs) = toLower x : xs toSnakeCase :: String -> String toSnakeCase = foldr f [] . uncapitalize where f x xs | isUpper x = '_' : toLower x : xs | otherwise = x : xs
beni55/json-fu
src/Util.hs
mit
580
0
12
157
215
109
106
16
1
{- DATX02-17-26, automated assessment of imperative programs. - Copyright, 2017, see AUTHORS.md. - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} {-# LANGUAGE LambdaCase #-} -- | Normalizer for transforming compound assignment in to assignment. module Norm.SumsOfProducts (normSOP) where import Norm.NormCS stage :: Int stage = 5 -- | Numerical expressions to SOP form normSOP :: NormCUR normSOP = makeRule' "sums_of_products.expr" [stage] execSOP -- | executes normalization of compund assignments execSOP :: NormCUA execSOP = normEvery $ \case ENum Mul (ENum Add x y) z -> change $ add (mul x z) (mul y z) ENum Mul z (ENum Add x y) -> change $ add (mul z x) (mul z y) ENum Add x y -> if add x y /= (ENum Add x y) then change $ add x y else unique $ add x y ENum Mul x y -> if mul x y /= (ENum Mul x y) then change $ mul x y else unique $ mul x y x -> unique x is :: Integer -> Expr -> Bool is i = \case ELit (Int j) -> i == j ELit (Word j) -> i == j ELit (Float j) -> fromInteger i == j ELit (Double j) -> fromInteger i == j _ -> False mul :: Expr -> Expr -> Expr mul = curry $ \case (ENum Add a b, r) -> add (mul a r) (mul b r) (l, ENum Add a b) -> add (mul l a) (mul l b) (l, r) | is 1 l -> r | is 1 r -> l | otherwise -> ENum Mul l r add :: Expr -> Expr -> Expr add = curry $ \case (x, ENum Add y z) -> add (add x y) z (x, y) | is 0 x -> y | is 0 y -> x | otherwise -> ENum Add x y
DATX02-17-26/DATX02-17-26
libsrc/Norm/SumsOfProducts.hs
gpl-2.0
2,375
0
12
762
665
330
335
41
7
module Main where import Geometry import Drawing main = drawPicture myPicture myPicture points = drawTriangle (a,b,c) & drawLabels [a,b,c] ["A","B","C"] & message $ "angle(ABC)=" ++ shownum (angle a b c) ++ ", angle(BCA)=" ++ shownum (angle b c a) ++ ", angle(CAB)=" ++ shownum (angle c a b) where [a,b,c] = take 3 points
alphalambda/hsmath
src/Learn/Geometry/demo09anglemeasure.hs
gpl-2.0
419
0
14
151
154
82
72
10
1
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Github.Auth as Github import qualified Github.Issues as Github import Report -- The example requires wl-pprint module "The Wadler/Leijen Pretty Printer" import Text.PrettyPrint.ANSI.Leijen auth :: Maybe Github.Auth auth = Just $ Github.EnterpriseOAuth "https://github.example.com/api" "1a79a4d60de6718e8e5b326e338ae533" mkIssue :: ReportedIssue -> Doc mkIssue (Issue n t h) = hsep [ fill 5 (text ("#" ++ (show n))), fill 50 (text t), fill 5 (text (show h))] vissues :: ([Doc], [Doc], [Doc]) -> Doc vissues (x, y, z) = hsep [(vcat x), align (vcat y), align (vcat z)] mkDoc :: Report -> Doc mkDoc (Report issues total) = vsep [ text "Report for the milestone", (vsep . map mkIssue) issues, text ("Total hours : " ++ (show total) ++" hours") ] mkFullDoc :: [Github.Issue] -> Doc mkFullDoc = mkDoc . prepareReport -- The public repo is used as private are quite sensitive for this report -- -- The main idea is to use labels like 1h, 2h etc for man-hour estimation of issues -- on private repos for development "on hire" -- -- This tool is used to generate report on work done for the customer -- main :: IO () main = do let limitations = [Github.OnlyClosed, Github.MilestoneId 4] possibleIssues <- Github.issuesForRepo' auth "paulrzcz" "hquantlib" limitations case possibleIssues of (Left err) -> putStrLn $ "Error: " ++ show err (Right issues) -> putDoc $ mkFullDoc issues
jwiegley/github
samples/Issues/IssueReport/IssuesEnterprise.hs
bsd-3-clause
1,598
0
13
388
436
235
201
31
2
module Tandoori.Typing.UnifyPred (substMono, resolvePred, satisfies) where import Tandoori.Typing import Tandoori.Typing.Monad import Tandoori.Typing.Error import Tandoori.Typing.Unify import Tandoori.Typing.Substitute import Tandoori.Typing.MonoEnv import MonadUtils (anyM) import Control.Monad.Error import Control.Applicative import Data.Maybe import qualified Data.Set as Set import Data.Set (Set) substMono θ m = mapMonoM' (return . substTy θ) (substPreds θ) m substPred :: Subst -> PolyPred -> ErrorT TypingError Typing [PolyPred] substPred θ (cls, α) = resolvePred (cls, substTy θ (TyVar α)) substPreds :: Subst -> Set PolyPred -> ErrorT TypingError Typing (Set PolyPred) substPreds θ ctx = do πs <- concat <$> (mapM (substPred θ) $ Set.toList ctx) Set.fromList <$> lift (simplifyCtx πs) substCtx :: Subst -> PolyCtx -> ErrorT TypingError Typing PolyCtx substCtx θ ctx = concat <$> mapM (substPred θ) ctx resolvePred :: OverPred -> ErrorT TypingError Typing PolyCtx resolvePred (cls, τ) = case τ of TyVar α -> return [(cls, α)] τ -> do let κ = fromJust $ tyCon τ instData <- lift $ askInstance cls κ case instData of Nothing -> throwError $ TypingError Nothing $ UnfulfilledPredicate (cls, τ) Just (PolyTy ctx τ') -> do θ <- fitDeclTy τ τ' substCtx θ ctx simplifyCtx :: PolyCtx -> Typing PolyCtx simplifyCtx [] = return [] simplifyCtx (π:πs) = do isRedundant <- anyM (π `isSuperOf`) πs πs' <- filterM (`isNotSuperOf` π) πs if isRedundant then simplifyCtx πs else (π:) <$> simplifyCtx πs' where π `isNotSuperOf` π' = not <$> (π `isSuperOf` π') isSuperOf :: PolyPred -> PolyPred -> Typing Bool (cls, α) `isSuperOf` (cls', α') | α /= α' = return False | otherwise = do supers <- askSupers cls' return $ cls `elem` supers satisfies :: PolyCtx -> PolyCtx -> Typing Bool general `satisfies` specific = and <$> mapM hasSuper specific where hasSuper π = or <$> mapM (π `isSuperOf`) general
bitemyapp/tandoori
src/Tandoori/Typing/UnifyPred.hs
bsd-3-clause
2,395
0
16
751
764
397
367
46
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module MockedEnv where import Control.Monad.Catch import Control.Monad.Trans.Reader import Control.Monad.IO.Class import Tinc.Fail import Control.Monad.Trans.Class newtype WithEnv e a = WithEnv (ReaderT e IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask) instance Fail (WithEnv e) where die = WithEnv . lift . die withEnv :: e -> WithEnv e a -> IO a withEnv e (WithEnv action) = runReaderT action e
sol/tinc
test/MockedEnv.hs
mit
542
0
7
125
157
88
69
13
1
{-# LANGUAGE PatternGuards, ScopedTypeVariables #-} module Main where import Prelude hiding ( mod, id, mapM ) import GHC --import Packages import HscTypes ( isBootSummary ) import Digraph ( flattenSCCs ) import DriverPhases ( isHaskellSrcFilename ) import HscTypes ( msHsFilePath ) import Name ( getOccString ) --import ErrUtils ( printBagOfErrors ) import Panic ( panic ) import DynFlags ( defaultFatalMessager, defaultFlushOut ) import Bag import Exception import FastString import MonadUtils ( liftIO ) import SrcLoc import Distribution.Simple.GHC ( componentGhcOptions ) import Distribution.Simple.Configure ( getPersistBuildConfig ) import Distribution.Simple.Compiler ( compilerVersion ) import Distribution.Simple.Program.GHC ( renderGhcOptions ) import Distribution.PackageDescription ( library, libBuildInfo ) import Distribution.Simple.LocalBuildInfo import qualified Distribution.Verbosity as V import Control.Monad hiding (mapM) import System.Environment import System.Console.GetOpt import System.Exit import System.IO import Data.List as List hiding ( group ) import Data.Traversable (mapM) import Data.Map ( Map ) import qualified Data.Map as M --import UniqFM --import Debug.Trace -- search for definitions of things -- we do this by parsing the source and grabbing top-level definitions -- We generate both CTAGS and ETAGS format tags files -- The former is for use in most sensible editors, while EMACS uses ETAGS ---------------------------------- ---- CENTRAL DATA TYPES ---------- type FileName = String type ThingName = String -- name of a defined entity in a Haskell program -- A definition we have found (we know its containing module, name, and location) data FoundThing = FoundThing ModuleName ThingName RealSrcLoc -- Data we have obtained from a file (list of things we found) data FileData = FileData FileName [FoundThing] (Map Int String) --- invariant (not checked): every found thing has a source location in that file? ------------------------------ -------- MAIN PROGRAM -------- main :: IO () main = do progName <- getProgName let usageString = "Usage: " ++ progName ++ " [OPTION...] [-- GHC OPTION... --] [files...]" args <- getArgs let (ghcArgs', ourArgs, unbalanced) = splitArgs args let (flags, filenames, errs) = getOpt Permute options ourArgs let (hsfiles, otherfiles) = List.partition isHaskellSrcFilename filenames let ghc_topdir = case [ d | FlagTopDir d <- flags ] of [] -> "" (x:_) -> x mapM_ (\n -> putStr $ "Warning: ignoring non-Haskellish file " ++ n ++ "\n") otherfiles if unbalanced || errs /= [] || elem FlagHelp flags || hsfiles == [] then do putStr $ unlines errs putStr $ usageInfo usageString options exitWith (ExitFailure 1) else return () ghcArgs <- case [ d | FlagUseCabalConfig d <- flags ] of [distPref] -> do cabalOpts <- flagsFromCabal distPref return (cabalOpts ++ ghcArgs') [] -> return ghcArgs' _ -> error "Too many --use-cabal-config flags" print ghcArgs let modes = getMode flags let openFileMode = if elem FlagAppend flags then AppendMode else WriteMode ctags_hdl <- if CTags `elem` modes then Just `liftM` openFile "tags" openFileMode else return Nothing etags_hdl <- if ETags `elem` modes then Just `liftM` openFile "TAGS" openFileMode else return Nothing GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ runGhc (Just ghc_topdir) $ do --liftIO $ print "starting up session" dflags <- getSessionDynFlags (pflags, unrec, warns) <- parseDynamicFlags dflags{ verbosity=1 } (map noLoc ghcArgs) unless (null unrec) $ liftIO $ putStrLn $ "Unrecognised options:\n" ++ show (map unLoc unrec) liftIO $ mapM_ putStrLn (map unLoc warns) let dflags2 = pflags { hscTarget = HscNothing } -- don't generate anything -- liftIO $ print ("pkgDB", case (pkgDatabase dflags2) of Nothing -> 0 -- Just m -> sizeUFM m) _ <- setSessionDynFlags dflags2 --liftIO $ print (length pkgs) GHC.defaultCleanupHandler dflags2 $ do targetsAtOneGo hsfiles (ctags_hdl,etags_hdl) mapM_ (mapM (liftIO . hClose)) [ctags_hdl, etags_hdl] ---------------------------------------------- ---------- ARGUMENT PROCESSING -------------- data Flag = FlagETags | FlagCTags | FlagBoth | FlagAppend | FlagHelp | FlagTopDir FilePath | FlagUseCabalConfig FilePath | FlagFilesFromCabal deriving (Ord, Eq, Show) -- ^Represents options passed to the program data Mode = ETags | CTags deriving Eq getMode :: [Flag] -> [Mode] getMode fs = go (concatMap modeLike fs) where go [] = [ETags,CTags] go [x] = [x] go more = nub more modeLike FlagETags = [ETags] modeLike FlagCTags = [CTags] modeLike FlagBoth = [ETags,CTags] modeLike _ = [] splitArgs :: [String] -> ([String], [String], Bool) -- ^Pull out arguments between -- for GHC splitArgs args0 = split [] [] False args0 where split ghc' tags' unbal ("--" : args) = split tags' ghc' (not unbal) args split ghc' tags' unbal (arg : args) = split ghc' (arg:tags') unbal args split ghc' tags' unbal [] = (reverse ghc', reverse tags', unbal) options :: [OptDescr Flag] -- supports getopt options = [ Option "" ["topdir"] (ReqArg FlagTopDir "DIR") "root of GHC installation (optional)" , Option "c" ["ctags"] (NoArg FlagCTags) "generate CTAGS file (ctags)" , Option "e" ["etags"] (NoArg FlagETags) "generate ETAGS file (etags)" , Option "b" ["both"] (NoArg FlagBoth) ("generate both CTAGS and ETAGS") , Option "a" ["append"] (NoArg FlagAppend) ("append to existing CTAGS and/or ETAGS file(s)") , Option "" ["use-cabal-config"] (ReqArg FlagUseCabalConfig "DIR") "use local cabal configuration from dist dir" , Option "" ["files-from-cabal"] (NoArg FlagFilesFromCabal) "use files from cabal" , Option "h" ["help"] (NoArg FlagHelp) "This help" ] flagsFromCabal :: FilePath -> IO [String] flagsFromCabal distPref = do lbi <- getPersistBuildConfig distPref let pd = localPkgDescr lbi findLibraryConfig [] = Nothing findLibraryConfig ((CLibName, clbi, _) : _) = Just clbi findLibraryConfig (_ : xs) = findLibraryConfig xs mLibraryConfig = findLibraryConfig (componentsConfigs lbi) case (library pd, mLibraryConfig) of (Just lib, Just clbi) -> let bi = libBuildInfo lib odir = buildDir lbi opts = componentGhcOptions V.normal lbi bi clbi odir version = compilerVersion (compiler lbi) in return $ renderGhcOptions version opts _ -> error "no library" ---------------------------------------------------------------- --- LOADING HASKELL SOURCE --- (these bits actually run the compiler and produce abstract syntax) safeLoad :: LoadHowMuch -> Ghc SuccessFlag -- like GHC.load, but does not stop process on exception safeLoad mode = do _dflags <- getSessionDynFlags ghandle (\(e :: SomeException) -> liftIO (print e) >> return Failed ) $ handleSourceError (\e -> printException e >> return Failed) $ load mode targetsAtOneGo :: [FileName] -> (Maybe Handle, Maybe Handle) -> Ghc () -- load a list of targets targetsAtOneGo hsfiles handles = do targets <- mapM (\f -> guessTarget f Nothing) hsfiles setTargets targets modgraph <- depanal [] False let mods = flattenSCCs $ topSortModuleGraph False modgraph Nothing graphData mods handles fileTarget :: FileName -> Target fileTarget filename = Target (TargetFile filename Nothing) True Nothing --------------------------------------------------------------- ----- CRAWLING ABSTRACT SYNTAX TO SNAFFLE THE DEFINITIONS ----- graphData :: ModuleGraph -> (Maybe Handle, Maybe Handle) -> Ghc () graphData graph handles = do mapM_ foundthings graph where foundthings ms = let filename = msHsFilePath ms modname = moduleName $ ms_mod ms in handleSourceError (\e -> do printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ putStrLn ("loading " ++ filename) mod <- loadModule =<< typecheckModule =<< parseModule ms case mod of _ | isBootSummary ms -> return () _ | Just s <- renamedSource mod -> liftIO (writeTagsData handles =<< fileData filename modname s) _otherwise -> liftIO $ exitWith (ExitFailure 1) fileData :: FileName -> ModuleName -> RenamedSource -> IO FileData fileData filename modname (group, _imports, _lie, _doc) = do -- lie is related to type checking and so is irrelevant -- imports contains import declarations and no definitions -- doc and haddock seem haddock-related; let's hope to ignore them ls <- lines `fmap` readFile filename let line_map = M.fromAscList $ zip [1..] ls line_map' <- evaluate line_map return $ FileData filename (boundValues modname group) line_map' boundValues :: ModuleName -> HsGroup Name -> [FoundThing] -- ^Finds all the top-level definitions in a module boundValues mod group = let vals = case hs_valds group of ValBindsOut nest _sigs -> [ x | (_rec, binds) <- nest , bind <- bagToList binds , x <- boundThings mod bind ] _other -> error "boundValues" tys = [ n | ns <- map hsLTyClDeclBinders (tyClGroupConcat (hs_tyclds group)) , n <- map found ns ] fors = concat $ map forBound (hs_fords group) where forBound lford = case unLoc lford of ForeignImport n _ _ _ -> [found n] ForeignExport { } -> [] in vals ++ tys ++ fors where found = foundOfLName mod startOfLocated :: Located a -> RealSrcLoc startOfLocated lHs = case getLoc lHs of RealSrcSpan l -> realSrcSpanStart l UnhelpfulSpan _ -> panic "startOfLocated UnhelpfulSpan" foundOfLName :: ModuleName -> Located Name -> FoundThing foundOfLName mod id = FoundThing mod (getOccString $ unLoc id) (startOfLocated id) boundThings :: ModuleName -> LHsBind Name -> [FoundThing] boundThings modname lbinding = case unLoc lbinding of FunBind { fun_id = id } -> [thing id] PatBind { pat_lhs = lhs } -> patThings lhs [] VarBind { var_id = id } -> [FoundThing modname (getOccString id) (startOfLocated lbinding)] AbsBinds { } -> [] -- nothing interesting in a type abstraction PatSynBind { patsyn_id = id } -> [thing id] where thing = foundOfLName modname patThings lpat tl = let loc = startOfLocated lpat lid id = FoundThing modname (getOccString id) loc in case unLoc lpat of WildPat _ -> tl VarPat name -> lid name : tl LazyPat p -> patThings p tl AsPat id p -> patThings p (thing id : tl) ParPat p -> patThings p tl BangPat p -> patThings p tl ListPat ps _ _ -> foldr patThings tl ps TuplePat ps _ _ -> foldr patThings tl ps PArrPat ps _ -> foldr patThings tl ps ConPatIn _ conargs -> conArgs conargs tl ConPatOut{ pat_args = conargs } -> conArgs conargs tl LitPat _ -> tl NPat _ _ _ -> tl -- form of literal pattern? NPlusKPat id _ _ _ -> thing id : tl SigPatIn p _ -> patThings p tl SigPatOut p _ -> patThings p tl _ -> error "boundThings" conArgs (PrefixCon ps) tl = foldr patThings tl ps conArgs (RecCon (HsRecFields { rec_flds = flds })) tl = foldr (\f tl' -> patThings (hsRecFieldArg f) tl') tl flds conArgs (InfixCon p1 p2) tl = patThings p1 $ patThings p2 tl -- stuff for dealing with ctags output format writeTagsData :: (Maybe Handle, Maybe Handle) -> FileData -> IO () writeTagsData (mb_ctags_hdl, mb_etags_hdl) fd = do maybe (return ()) (\hdl -> writectagsfile hdl fd) mb_ctags_hdl maybe (return ()) (\hdl -> writeetagsfile hdl fd) mb_etags_hdl writectagsfile :: Handle -> FileData -> IO () writectagsfile ctagsfile filedata = do let things = getfoundthings filedata mapM_ (\x -> hPutStrLn ctagsfile $ dumpthing False x) things mapM_ (\x -> hPutStrLn ctagsfile $ dumpthing True x) things getfoundthings :: FileData -> [FoundThing] getfoundthings (FileData _filename things _src_lines) = things dumpthing :: Bool -> FoundThing -> String dumpthing showmod (FoundThing modname name loc) = fullname ++ "\t" ++ filename ++ "\t" ++ (show line) where line = srcLocLine loc filename = unpackFS $ srcLocFile loc fullname = if showmod then moduleNameString modname ++ "." ++ name else name -- stuff for dealing with etags output format writeetagsfile :: Handle -> FileData -> IO () writeetagsfile etagsfile = hPutStr etagsfile . e_dumpfiledata e_dumpfiledata :: FileData -> String e_dumpfiledata (FileData filename things line_map) = "\x0c\n" ++ filename ++ "," ++ (show thingslength) ++ "\n" ++ thingsdump where thingsdump = concat $ map (e_dumpthing line_map) things thingslength = length thingsdump e_dumpthing :: Map Int String -> FoundThing -> String e_dumpthing src_lines (FoundThing modname name loc) = tagline name ++ tagline (moduleNameString modname ++ "." ++ name) where tagline n = src_code ++ "\x7f" ++ n ++ "\x01" ++ (show line) ++ "," ++ (show $ column) ++ "\n" line = srcLocLine loc column = srcLocCol loc src_code = case M.lookup line src_lines of Just l -> take (column + length name) l Nothing -> --trace (show ("not found: ", moduleNameString modname, name, line, column)) name
lukexi/ghc-7.8-arm64
utils/ghctags/Main.hs
bsd-3-clause
14,738
33
21
4,256
3,893
1,983
1,910
275
23
{-# LANGUAGE UnliftedNewtypes #-} main :: IO () main = return () newtype Baz = Baz (Show Int)
sdiehl/ghc
testsuite/tests/typecheck/should_fail/UnliftedNewtypesFail.hs
bsd-3-clause
96
0
7
20
36
19
17
4
1
module Compose where import Prelude hiding (Monad(..)) -- | TODO -- | -- | 1. default methods are currently not supported -- | ie. if we remove the definition of fail method it fails -- | as I assume that dictionaries are Non Recursive -- | -- | 2. check what happens if we import the instance (it should work) data ST s a = ST {runState :: s -> (a,s)} {-@ data ST s a <p :: s -> Prop, q :: s -> s -> Prop, r :: s -> a -> Prop> = ST (runState :: x:s<p> -> (a<r x>, s<q x>)) @-} {-@ runState :: forall <p :: s -> Prop, q :: s -> s -> Prop, r :: s -> a -> Prop>. ST <p, q, r> s a -> x:s<p> -> (a<r x>, s<q x>) @-} class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b instance Monad (ST s) where {-@ instance Monad ST s where return :: forall s a <p :: s -> Prop >. x:a -> ST <p, {\s v -> v == s}, {\s v -> x == v}> s a; >>= :: forall s a b < pref :: s -> Prop, postf :: s -> s -> Prop , pre :: s -> Prop, postg :: s -> s -> Prop , post :: s -> s -> Prop , rg :: s -> a -> Prop , rf :: s -> b -> Prop , r :: s -> b -> Prop , pref0 :: a -> Prop >. {x::s<pre> |- a<rg x> <: a<pref0>} {x::s<pre>, y::s<postg x> |- b<rf y> <: b<r x>} {xx::s<pre>, w::s<postg xx> |- s<postf w> <: s<post xx>} {ww::s<pre> |- s<postg ww> <: s<pref>} (ST <pre, postg, rg> s a) -> (a<pref0> -> ST <pref, postf, rf> s b) -> (ST <pre, post, r> s b) ; >> :: forall s a b < pref :: s -> Prop, postf :: s -> s -> Prop , pre :: s -> Prop, postg :: s -> s -> Prop , post :: s -> s -> Prop , rg :: s -> a -> Prop , rf :: s -> b -> Prop , r :: s -> b -> Prop >. {x::s<pre>, y::s<postg x> |- b<rf y> <: b<r x>} {xx::s<pre>, w::s<postg xx> |- s<postf w> <: s<post xx>} {ww::s<pre> |- s<postg ww> <: s<pref>} (ST <pre, postg, rg> s a) -> (ST <pref, postf, rf> s b) -> (ST <pre, post, r> s b) @-} return x = ST $ \s -> (x, s) (ST g) >>= f = ST (\x -> case g x of {(y, s) -> (runState (f y)) s}) (ST g) >> f = ST (\x -> case g x of {(y, s) -> (runState f) s}) {-@ incr :: ST <{\x -> true}, {\x v -> v = x + 1}, {\x v -> v = x}> Int Int @-} incr :: ST Int Int incr = ST $ \x -> (x, x + 1) {-@ foo :: ST <{\x -> true}, {\x v -> true}, {\x v -> v = 0}> Bool Int @-} foo :: ST Bool Int foo = return 0 {-@ incr2 :: ST <{\x -> true}, {\x v -> v = x + 3}, {\x v -> v = x + 2}> Int Int @-} incr2 :: ST Int Int incr2 = incr >> incr run :: (Int, Int) {-@ run :: ({v:Int | v = 1}, {v:Int | v = 2}) @-} run = (runState incr2) 0 {-@ cmp :: forall < pref :: s -> Prop, postf :: s -> s -> Prop , pre :: s -> Prop, postg :: s -> s -> Prop , post :: s -> s -> Prop , rg :: s -> a -> Prop , rf :: s -> b -> Prop , r :: s -> b -> Prop >. {x::s<pre>, y::s<postg x> |- b<rf y> <: b<r x>} {xx::s<pre>, w::s<postg xx> |- s<postf w> <: s<post xx>} {ww::s<pre> |- s<postg ww> <: s<pref>} (ST <pre, postg, rg> s a) -> (ST <pref, postf, rf> s b) -> (ST <pre, post, r> s b) @-} cmp :: (ST s a) -> (ST s b) -> (ST s b) m `cmp` f = m `bind` (\_ -> f) {-@ bind :: forall < pref :: s -> Prop, postf :: s -> s -> Prop , pre :: s -> Prop, postg :: s -> s -> Prop , post :: s -> s -> Prop , rg :: s -> a -> Prop , rf :: s -> b -> Prop , r :: s -> b -> Prop , pref0 :: a -> Prop >. {x::s<pre> |- a<rg x> <: a<pref0>} {x::s<pre>, y::s<postg x> |- b<rf y> <: b<r x>} {xx::s<pre>, w::s<postg xx> |- s<postf w> <: s<post xx>} {ww::s<pre> |- s<postg ww> <: s<pref>} (ST <pre, postg, rg> s a) -> (a<pref0> -> ST <pref, postf, rf> s b) -> (ST <pre, post, r> s b) @-} bind :: (ST s a) -> (a -> ST s b) -> (ST s b) bind (ST g) f = ST (\x -> case g x of {(y, s) -> (runState (f y)) s})
ssaavedra/liquidhaskell
tests/neg/StateConstraints0.hs
bsd-3-clause
4,256
0
16
1,621
559
307
252
27
1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- | Parsing the top of a Haskell source file to get its module name, -- imports and options. -- -- (c) Simon Marlow 2005 -- (c) Lemmih 2006 -- ----------------------------------------------------------------------------- module HeaderInfo ( getImports , mkPrelImports -- used by the renamer too , getOptionsFromFile, getOptions , optionsErrorMsgs, checkProcessArgsResult ) where #include "HsVersions.h" import RdrName import HscTypes import Parser ( parseHeader ) import Lexer import FastString import HsSyn import Module import PrelNames import StringBuffer import SrcLoc import DynFlags import ErrUtils import Util import Outputable import Pretty () import Maybes import Bag ( emptyBag, listToBag, unitBag ) import MonadUtils import Exception import Control.Monad import System.IO import System.IO.Unsafe import Data.List ------------------------------------------------------------------------------ -- | Parse the imports of a source file. -- -- Throws a 'SourceError' if parsing fails. getImports :: DynFlags -> StringBuffer -- ^ Parse this. -> FilePath -- ^ Filename the buffer came from. Used for -- reporting parse error locations. -> FilePath -- ^ The original source filename (used for locations -- in the function result) -> IO ([Located (ImportDecl RdrName)], [Located (ImportDecl RdrName)], Located ModuleName) -- ^ The source imports, normal imports, and the module name. getImports dflags buf filename source_filename = do let loc = mkRealSrcLoc (mkFastString filename) 1 1 case unP parseHeader (mkPState dflags buf loc) of PFailed span err -> parseError dflags span err POk pst rdr_module -> do let _ms@(_warns, errs) = getMessages pst -- don't log warnings: they'll be reported when we parse the file -- for real. See #2500. ms = (emptyBag, errs) -- logWarnings warns if errorsFound dflags ms then throwIO $ mkSrcErr errs else case rdr_module of L _ (HsModule mb_mod _ imps _ _ _) -> let main_loc = srcLocSpan (mkSrcLoc (mkFastString source_filename) 1 1) mod = mb_mod `orElse` L main_loc mAIN_NAME (src_idecls, ord_idecls) = partition (ideclSource.unLoc) imps -- GHC.Prim doesn't exist physically, so don't go looking for it. ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc . ideclName . unLoc) ord_idecls implicit_prelude = xopt Opt_ImplicitPrelude dflags implicit_imports = mkPrelImports (unLoc mod) main_loc implicit_prelude imps in return (src_idecls, implicit_imports ++ ordinary_imps, mod) mkPrelImports :: ModuleName -> SrcSpan -- Attribute the "import Prelude" to this location -> Bool -> [LImportDecl RdrName] -> [LImportDecl RdrName] -- Consruct the implicit declaration "import Prelude" (or not) -- -- NB: opt_NoImplicitPrelude is slightly different to import Prelude (); -- because the former doesn't even look at Prelude.hi for instance -- declarations, whereas the latter does. mkPrelImports this_mod loc implicit_prelude import_decls | this_mod == pRELUDE_NAME || explicit_prelude_import || not implicit_prelude = [] | otherwise = [preludeImportDecl] where explicit_prelude_import = notNull [ () | L _ (ImportDecl { ideclName = mod , ideclPkgQual = Nothing }) <- import_decls , unLoc mod == pRELUDE_NAME ] preludeImportDecl :: LImportDecl RdrName preludeImportDecl = L loc $ ImportDecl { ideclSourceSrc = Nothing, ideclName = L loc pRELUDE_NAME, ideclPkgQual = Nothing, ideclSource = False, ideclSafe = False, -- Not a safe import ideclQualified = False, ideclImplicit = True, -- Implicit! ideclAs = Nothing, ideclHiding = Nothing } parseError :: DynFlags -> SrcSpan -> MsgDoc -> IO a parseError dflags span err = throwOneError $ mkPlainErrMsg dflags span err -------------------------------------------------------------- -- Get options -------------------------------------------------------------- -- | Parse OPTIONS and LANGUAGE pragmas of the source file. -- -- Throws a 'SourceError' if flag parsing fails (including unsupported flags.) getOptionsFromFile :: DynFlags -> FilePath -- ^ Input file -> IO [Located String] -- ^ Parsed options, if any. getOptionsFromFile dflags filename = Exception.bracket (openBinaryFile filename ReadMode) (hClose) (\handle -> do opts <- fmap (getOptions' dflags) (lazyGetToks dflags' filename handle) seqList opts $ return opts) where -- We don't need to get haddock doc tokens when we're just -- getting the options from pragmas, and lazily lexing them -- correctly is a little tricky: If there is "\n" or "\n-" -- left at the end of a buffer then the haddock doc may -- continue past the end of the buffer, despite the fact that -- we already have an apparently-complete token. -- We therefore just turn Opt_Haddock off when doing the lazy -- lex. dflags' = gopt_unset dflags Opt_Haddock blockSize :: Int -- blockSize = 17 -- for testing :-) blockSize = 1024 lazyGetToks :: DynFlags -> FilePath -> Handle -> IO [Located Token] lazyGetToks dflags filename handle = do buf <- hGetStringBufferBlock handle blockSize unsafeInterleaveIO $ lazyLexBuf handle (pragState dflags buf loc) False blockSize where loc = mkRealSrcLoc (mkFastString filename) 1 1 lazyLexBuf :: Handle -> PState -> Bool -> Int -> IO [Located Token] lazyLexBuf handle state eof size = do case unP (lexer False return) state of POk state' t -> do -- pprTrace "lazyLexBuf" (text (show (buffer state'))) (return ()) if atEnd (buffer state') && not eof -- if this token reached the end of the buffer, and we haven't -- necessarily read up to the end of the file, then the token might -- be truncated, so read some more of the file and lex it again. then getMore handle state size else case t of L _ ITeof -> return [t] _other -> do rest <- lazyLexBuf handle state' eof size return (t : rest) _ | not eof -> getMore handle state size | otherwise -> return [L (RealSrcSpan (last_loc state)) ITeof] -- parser assumes an ITeof sentinel at the end getMore :: Handle -> PState -> Int -> IO [Located Token] getMore handle state size = do -- pprTrace "getMore" (text (show (buffer state))) (return ()) let new_size = size * 2 -- double the buffer size each time we read a new block. This -- counteracts the quadratic slowdown we otherwise get for very -- large module names (#5981) nextbuf <- hGetStringBufferBlock handle new_size if (len nextbuf == 0) then lazyLexBuf handle state True new_size else do newbuf <- appendStringBuffers (buffer state) nextbuf unsafeInterleaveIO $ lazyLexBuf handle state{buffer=newbuf} False new_size getToks :: DynFlags -> FilePath -> StringBuffer -> [Located Token] getToks dflags filename buf = lexAll (pragState dflags buf loc) where loc = mkRealSrcLoc (mkFastString filename) 1 1 lexAll state = case unP (lexer False return) state of POk _ t@(L _ ITeof) -> [t] POk state' t -> t : lexAll state' _ -> [L (RealSrcSpan (last_loc state)) ITeof] -- | Parse OPTIONS and LANGUAGE pragmas of the source file. -- -- Throws a 'SourceError' if flag parsing fails (including unsupported flags.) getOptions :: DynFlags -> StringBuffer -- ^ Input Buffer -> FilePath -- ^ Source filename. Used for location info. -> [Located String] -- ^ Parsed options. getOptions dflags buf filename = getOptions' dflags (getToks dflags filename buf) -- The token parser is written manually because Happy can't -- return a partial result when it encounters a lexer error. -- We want to extract options before the buffer is passed through -- CPP, so we can't use the same trick as 'getImports'. getOptions' :: DynFlags -> [Located Token] -- Input buffer -> [Located String] -- Options. getOptions' dflags toks = parseToks toks where getToken (L _loc tok) = tok getLoc (L loc _tok) = loc parseToks (open:close:xs) | IToptions_prag str <- getToken open , ITclose_prag <- getToken close = map (L (getLoc open)) (words str) ++ parseToks xs parseToks (open:close:xs) | ITinclude_prag str <- getToken open , ITclose_prag <- getToken close = map (L (getLoc open)) ["-#include",removeSpaces str] ++ parseToks xs parseToks (open:close:xs) | ITdocOptions str <- getToken open , ITclose_prag <- getToken close = map (L (getLoc open)) ["-haddock-opts", removeSpaces str] ++ parseToks xs parseToks (open:xs) | ITdocOptionsOld str <- getToken open = map (L (getLoc open)) ["-haddock-opts", removeSpaces str] ++ parseToks xs parseToks (open:xs) | ITlanguage_prag <- getToken open = parseLanguage xs parseToks _ = [] parseLanguage (L loc (ITconid fs):rest) = checkExtension dflags (L loc fs) : case rest of (L _loc ITcomma):more -> parseLanguage more (L _loc ITclose_prag):more -> parseToks more (L loc _):_ -> languagePragParseError dflags loc [] -> panic "getOptions'.parseLanguage(1) went past eof token" parseLanguage (tok:_) = languagePragParseError dflags (getLoc tok) parseLanguage [] = panic "getOptions'.parseLanguage(2) went past eof token" ----------------------------------------------------------------------------- -- | Complain about non-dynamic flags in OPTIONS pragmas. -- -- Throws a 'SourceError' if the input list is non-empty claiming that the -- input flags are unknown. checkProcessArgsResult :: MonadIO m => DynFlags -> [Located String] -> m () checkProcessArgsResult dflags flags = when (notNull flags) $ liftIO $ throwIO $ mkSrcErr $ listToBag $ map mkMsg flags where mkMsg (L loc flag) = mkPlainErrMsg dflags loc $ (text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+> text flag) ----------------------------------------------------------------------------- checkExtension :: DynFlags -> Located FastString -> Located String checkExtension dflags (L l ext) -- Checks if a given extension is valid, and if so returns -- its corresponding flag. Otherwise it throws an exception. = let ext' = unpackFS ext in if ext' `elem` supportedLanguagesAndExtensions then L l ("-X"++ext') else unsupportedExtnError dflags l ext' languagePragParseError :: DynFlags -> SrcSpan -> a languagePragParseError dflags loc = throw $ mkSrcErr $ unitBag $ (mkPlainErrMsg dflags loc $ vcat [ text "Cannot parse LANGUAGE pragma" , text "Expecting comma-separated list of language options," , text "each starting with a capital letter" , nest 2 (text "E.g. {-# LANGUAGE TemplateHaskell, GADTs #-}") ]) unsupportedExtnError :: DynFlags -> SrcSpan -> String -> a unsupportedExtnError dflags loc unsup = throw $ mkSrcErr $ unitBag $ mkPlainErrMsg dflags loc $ text "Unsupported extension: " <> text unsup $$ if null suggestions then Outputable.empty else text "Perhaps you meant" <+> quotedListWithOr (map text suggestions) where suggestions = fuzzyMatch unsup supportedLanguagesAndExtensions optionsErrorMsgs :: DynFlags -> [String] -> [Located String] -> FilePath -> Messages optionsErrorMsgs dflags unhandled_flags flags_lines _filename = (emptyBag, listToBag (map mkMsg unhandled_flags_lines)) where unhandled_flags_lines = [ L l f | f <- unhandled_flags, L l f' <- flags_lines, f == f' ] mkMsg (L flagSpan flag) = ErrUtils.mkPlainErrMsg dflags flagSpan $ text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+> text flag
TomMD/ghc
compiler/main/HeaderInfo.hs
bsd-3-clause
13,425
1
28
4,110
2,723
1,400
1,323
212
11
{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -O -Wno-inline-rule-shadowing #-} -- Rules are ignored without -O module Orphans where import GHC.Exts (IsList(..)) -- Some orphan things instance IsList Bool where type Item Bool = Double fromList = undefined toList = undefined {-# RULES "myrule1" id id = id #-} -- And some non-orphan things data X = X [Int] instance IsList X where type Item X = Int fromList = undefined toList = undefined f :: X -> X f x = x {-# RULES "myrule2" id f = f #-}
ezyang/ghc
testsuite/tests/showIface/Orphans.hs
bsd-3-clause
510
0
7
108
108
65
43
17
1
-- !!! Check that we can have a type for main that is more general than IO a -- main :: forall a.a certainly also has type IO a, so it should be fine. module Main(main) where main :: a main = error "not much luck"
hferreiro/replay
testsuite/tests/typecheck/should_compile/tc120.hs
bsd-3-clause
219
0
5
51
24
15
9
3
1
{-# htermination zipWithM :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m [c] #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_zipWithM_1.hs
mit
96
0
3
23
5
3
2
1
0
{-# LANGUAGE GADTs, RankNTypes #-} module Vyom.Data.Run where -- Runtime representation for values - -- runtime environment (h) -> the actual value (a) newtype Run h a = Run { run :: h -> a } -- UTILITY -- Basic ops for Run rop0 :: a -> Run h a rop0 = Run . const rop1 :: (a -> b) -> Run h a -> Run h b rop1 f a = Run $ \h -> f (run a h) rop2 :: (a -> b -> c) -> Run h a -> Run h b -> Run h c rop2 f a b = Run $ \h -> f (run a h) (run b h) rop3 :: (a -> b -> c -> d) -> Run h a -> Run h b -> Run h c -> Run h d rop3 f a b c = Run $ \h -> f (run a h) (run b h) (run c h)
ajnsit/vyom
src/Vyom/Data/Run.hs
mit
578
0
9
168
309
161
148
11
1
module Unison.Codebase.Serialization.PutT where import Data.Bytes.Put import qualified Data.Serialize.Put as Ser import Data.Serialize.Put ( PutM , runPutM ) newtype PutT m a = PutT { unPutT :: m (PutM a) } instance Monad m => MonadPut (PutT m) where putWord8 = PutT . pure . putWord8 {-# INLINE putWord8 #-} putByteString = PutT . pure . putByteString {-# INLINE putByteString #-} putLazyByteString = PutT . pure . putLazyByteString {-# INLINE putLazyByteString #-} flush = PutT $ pure flush {-# INLINE flush #-} putWord16le = PutT . pure . putWord16le {-# INLINE putWord16le #-} putWord16be = PutT . pure . putWord16be {-# INLINE putWord16be #-} putWord16host = PutT . pure . putWord16host {-# INLINE putWord16host #-} putWord32le = PutT . pure . putWord32le {-# INLINE putWord32le #-} putWord32be = PutT . pure . putWord32be {-# INLINE putWord32be #-} putWord32host = PutT . pure . putWord32host {-# INLINE putWord32host #-} putWord64le = PutT . pure . putWord64le {-# INLINE putWord64le #-} putWord64be = PutT . pure . putWord64be {-# INLINE putWord64be #-} putWord64host = PutT . pure . putWord64host {-# INLINE putWord64host #-} putWordhost = PutT . pure . putWordhost {-# INLINE putWordhost #-} instance Functor m => Functor (PutT m) where fmap f (PutT m) = PutT $ fmap (fmap f) m instance Applicative m => Applicative (PutT m) where pure = PutT . pure . pure (PutT f) <*> (PutT a) = PutT $ (<*>) <$> f <*> a instance Monad m => Monad (PutT m) where (PutT m) >>= f = PutT $ do putm <- m let (a, bs) = runPutM putm putm' <- unPutT $ f a let (b, bs') = runPutM putm' pure $ do Ser.putByteString bs Ser.putByteString bs' pure b
unisonweb/platform
parser-typechecker/src/Unison/Codebase/Serialization/PutT.hs
mit
1,893
0
13
545
530
281
249
50
0
-- |This module contains 'toIsabelle' definitions of all the core Zeno types. module Zeno.Isabellable.Core () where import Prelude () import Zeno.Prelude import Zeno.Core import Zeno.Isabellable.Class import qualified Data.Map as Map import qualified Data.Text as Text instance Isabellable Id where toIsabelle = fromString . ("z_" ++) . show instance Isabellable ZBindings where toIsabelle binds = "\n\nfun " ++ decls_s ++ "\nwhere\n " ++ exprs_s where flat = flattenBindings binds exprs_s = intercalate "\n| " $ do (fun, expr) <- flat let (vars, expr') = flattenLambdas expr return $ "\"" ++ (toIsabelle . unflattenApp . map Var) (fun : vars) ++ " = " ++ (runIndented . indent . toIsabelleI) expr' ++ "\"" decls_s = intercalate "\nand " $ do (var, _) <- flat let var_name = toIsabelle var type_s = " :: " ++ (quote . toIsabelle . getType) var return $ if (isOperator . Text.unpack) var_name then (toIsabelle . varId) var ++ type_s ++ " (infix \"" ++ var_name ++ "\" 42)" else var_name ++ type_s instance Isabellable ZVar where toIsabelle var = case varName var of Nothing -> toIsabelle (varId var) Just name -> (fromString . convertName) name where convertName :: String -> String convertName [':'] = "#" convertName ('$':'c':xs) = convertName xs convertName ('[':']':[]) = "[]" convertName name' = id . prefixOperator . replace '/' '!' $ name where name = convert name' prefixOperator s | isOperator s = "Z" ++ s | otherwise = s instance Isabellable ZEquality where toIsabelle (x :=: y) = case toIsabelle y of "True" -> toIsabelle x "False" -> "~(" ++ toIsabelle x ++ ")" y' -> toIsabelle x ++ " = " ++ y' instance Isabellable ZClause where toIsabelle (Clause goal conds) | null conds = toIsabelle goal | otherwise = conds' ++ " ==> " ++ toIsabelle goal where conds' | length conds == 1 = toIsabelle (head conds) | otherwise = "[| " ++ intercalate "; " (map toIsabelle conds) ++ " |]" instance Isabellable ZQuantified where toIsabelle (Quantified vars obj) | null vars = toIsabelle obj | otherwise = "!! " ++ concatMap isaTyped vars ++ ". " ++ toIsabelle obj where isaTyped var = "(" ++ toIsabelle var ++ " :: " ++ toIsabelle (getType var) ++ ") " instance Isabellable ZHypothesis where toIsabelle = toIsabelle . hypClause instance Isabellable ZExpr where toIsabelleI Err = error $ "Cannot yet have _|_ in our Isabelle/HOL output; " ++ "all your functions must be total. " toIsabelleI (Var var) = do var' <- toIsabelleI var if (isOperator . Text.unpack) var' && var' /= "[]" then toIsabelleI (varId var) else return var' toIsabelleI (flattenApp -> Var fun : args) | (show fun == "(,)" && length args == 2) || (show fun == "(,,)" && length args == 3) || (show fun == "(,,,)" && length args == 4) = do args' <- mapM toIsabelleI args return $ "(" ++ intercalate ", " args' ++ ")" toIsabelleI (App (App (Var fun) arg1) arg2) | (isOperator . Text.unpack . toIsabelle) fun = do arg1' <- toIsabelleI arg1 arg2' <- toIsabelleI arg2 let arg1_s = if isTerm arg1 then arg1' else "(" ++ arg1' ++ ")" arg2_s = if isTerm arg2 then arg2' else "(" ++ arg2' ++ ")" fun_s = toIsabelle fun if fun_s == "#" && arg2_s == "[]" then return $ "[" ++ arg1_s ++ "]" else return $ "(" ++ arg1_s ++ " " ++ fun_s ++ " " ++ arg2_s ++ ")" toIsabelleI (App x y) = do x' <- toIsabelleI x y' <- toIsabelleI y let y'' = if isApp y && Text.head y' /= '(' then "(" ++ y' ++ ")" else y' return $ x' ++ " " ++ y'' toIsabelleI (Lam var rhs) = do rhs' <- toIsabelleI rhs return $ "(%" ++ toIsabelle var ++ ". " ++ rhs' ++ ")" toIsabelleI expr@(Let binds rhs) = do case flattenBindings binds of _ : _ : _ -> error $ "Cannot have mutually recursive let bindings within an Isabelle/HOL expression." ++ "\nThese can crop up with pre-defined type-class functions and I haven't " ++ "created a fix yet." [(var, expr)] -> do i <- indentation expr' <- toIsabelleI expr rhs' <- toIsabelleI rhs return $ i ++ "(let " ++ toIsabelle var ++ " = " ++ expr' ++ i ++ "in " ++ rhs' ++ ")" toIsabelleI (Cse _ expr alts) = indent $ do expr' <- toIsabelleI expr alts' <- mapM toIsabelleI alts i <- indentation let alts_s = intercalate (i ++ "| ") (reverse alts') return $ i ++ "(case " ++ expr' ++ " of" ++ i ++ " " ++ alts_s ++ ")" instance Isabellable ZAlt where toIsabelleI (Alt con vars rhs) = do rhs' <- indent (toIsabelleI rhs) return $ lhs ++ " => " ++ rhs' where lhs = case con of AltCon var -> toIsabelle $ unflattenApp (map Var (var : vars)) AltDefault -> "_" instance Isabellable ZDataType where toIsabelle (DataType _ name args cons) = "\n\ndatatype" ++ fromString args_s ++ " " ++ fromString (convert name) ++ "\n = " ++ con_decl where args' = map (("'" ++) . show) (reverse args) args_s = concatMap (" " ++) args' con_decl = intercalate "\n | " con_decls con_decls = do con <- cons let con_name = toIsabelle con con_type = snd (flattenForAllType (getType con)) arg_types = butlast (flattenFunType con_type) arg_list = concatMap ((" " ++) . quote . toIsabelle) arg_types return $ if (isOperator . Text.unpack) con_name then toIsabelle (varId con) ++ arg_list ++ " (infix \"" ++ con_name ++ "\" 42)" else con_name ++ arg_list instance Isabellable ZType where toIsabelle (VarType var) = (fromString . convert . show) var toIsabelle (PolyVarType id) = fromString $ "'" ++ show id toIsabelle (ForAllType _ rhs) = toIsabelle rhs toIsabelle (flattenAppType -> VarType fun : args) | (show fun == "(,)" && length args == 2) || (show fun == "(,,)" && length args == 3) || (show fun == "(,,,)" && length args == 4) = (intercalate " * " . map toIsabelle) args toIsabelle (AppType fun arg) = arg' ++ " " ++ fun' where arg' = if isFunType arg || isAppType arg then "(" ++ toIsabelle arg ++ ")" else toIsabelle arg fun' = if isFunType fun then "(" ++ toIsabelle fun ++ ")" else toIsabelle fun toIsabelle (FunType arg res) = arg' ++ " => " ++ toIsabelle res where arg' = if isFunType arg then "(" ++ toIsabelle arg ++ ")" else toIsabelle arg
Gurmeet-Singh/Zeno
src/Zeno/Isabellable/Core.hs
mit
6,784
0
21
1,985
2,346
1,147
1,199
-1
-1
bools :: [Bool] bools = [True] nums :: [[Int]] nums = [[1]] add :: Int -> Int -> Int -> Int add x y z = x+y+z copy :: a -> (a,a) copy a = (a,a) apply :: (a -> b) -> a -> b apply f a = f a second :: [a] -> a second xs = head (tail xs) swap :: (a,a) -> (a,a) swap (x,y) = (y,x) pair :: a -> a -> (a,a) pair x y = (x,y) palindrome :: Eq a => [a] -> Bool palindrome xs = reverse xs == xs twice :: (a -> a) -> a -> a twice f x = f (f x)
craynafinal/cs557_functional_languages
practice/week1/ch3.hs
mit
441
0
7
123
316
174
142
20
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} import Confetti import Data.Maybe import Data.Version (showVersion) import Paths_confetti (version) import System.Console.CmdArgs import System.Console.CmdArgs.Implicit import System.Environment import System.Exit import Text.Printf import qualified Data.Text as T -- Structure for our command line arguments data MainArgs = MainArgs { group_name :: String , variant_prefix :: ConfigVariantPrefix , force :: Bool } deriving (Show, Data, Typeable, Eq) argParser :: MainArgs argParser = MainArgs { group_name = def &= argPos 0 &= typ "GROUP_NAME" , variant_prefix = def &= argPos 1 &= typ "VARIANT_PREFIX" &= opt (Nothing :: Maybe String) , force = def &= help "If the target already exists as a regular file, back it up and then create a link" } &= summary ("confetti " ++ showVersion version) &= program "confetti" &= verbosity &= help "Easily swap groups of config files" confettiArgs :: IO MainArgs confettiArgs = cmdArgs argParser -- it seems to be a bug in cmdargs, we parse Just "Nothing" when nothing is supplied :/ correctDefault (Just "Nothing") = Nothing correctDefault x = x main :: IO () main = do parsed <- confettiArgs let variantPrefix = correctDefault $ variant_prefix parsed printf "Setting %s to %s\n" (group_name parsed) (showPrefix variantPrefix) specPath <- absolutePath "~/.confetti.yml" group <- parseGroup specPath (T.pack $ group_name parsed) let validatedGroup = group >>= validateSpec either (printFail . show) (runSpec (variantPrefix) (force parsed)) validatedGroup -- Run our configuration spec. Prints whatever error message we get back, -- or a success message runSpec :: ConfigVariantPrefix -> Bool -> ConfigGroup -> IO () runSpec prefix shouldForce group = applySpec (ConfigSpec group prefix shouldForce) >>= \maybeError -> maybe (printSuccess "Success (ノ◕ヮ◕)ノ*:・゚✧") (printFail . show) maybeError
aviaviavi/confetti
app/Main.hs
mit
2,161
0
14
518
486
254
232
48
1
module Euler.E39 where import Data.Function (on) import Data.List (maximumBy) euler39 :: Int -> Int euler39 n = maximumBy (compare `on` numTriangles) [1..n] numTriangles :: Int -> Int numTriangles = length . findTriangles findTriangles :: Int -> [ (Int, Int, Int) ] findTriangles n = [ (x, y, (n - y - x)) | x <- [1..n], y <- [x..n], isValidRightTriangle x y (n - y - x) -- NYXNYXNYXNYX ] isValidRightTriangle :: Int -> Int -> Int -> Bool isValidRightTriangle x y z | x * x + y * y == z * z = True | otherwise = False main :: IO () main = print $ euler39 1000
D4r1/project-euler
Euler/E39.hs
mit
589
10
12
140
277
150
127
19
1
import Prelude hiding ((&&)) -- True && True = True -- _ && _ = False --a && b = if a -- then -- if b -- then True -- else False -- else -- False a && b = if b then a else False mult = \ x -> (\ y -> (\ z -> x * y * z)) remove n xs = take n xs ++ drop (n + 1) xs funct :: Int -> [a] -> [a] funct x xs = take (x + 1) xs ++ drop x xs e3 x = x * 2 e4 (x, y) = x e5 (x, y, z) = z e6 x y = x * y e7 (x, y) = (y, x) e8 x y = (y, x) e9 [x, y] = (x, True) e10 (x, y) = [x, y] e13 x y = x + y * y e15 xs ys = (head xs, head ys)
jugalps/edX
FP101x/week3/test.hs
mit
599
0
11
241
328
184
144
16
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} module Cilia.CI.Travis(getInternalRepos) where import Prelude import qualified Data.Maybe as DM import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.ByteString.Char8 as BSC import Lens.Micro.TH(makeLenses) import Lens.Micro((^.), (.~), (&)) import Data.Time.Clock(UTCTime) import Data.Time.ISO8601 as TI import qualified Data.Text.Format as TF import Data.Aeson( FromJSON(..) , withObject , (.:?) , (.:)) import GHC.Generics import qualified Network.Wreq as W import Control.Exception as E import Network.HTTP.Client hiding(responseBody) import qualified Cilia.CI.InternalRepo as IR import Cilia.CI.InternalRepo(InternalRepo(..)) import qualified Cilia.Config as C data BuildState = Passed | Created | Started | Failed | Unknown deriving(Ord, Eq, Show) instance FromJSON BuildState where parseJSON "failed" = return Failed parseJSON "passed" = return Passed parseJSON "created" = return Created parseJSON "started" = return Started parseJSON _ = return Unknown type BuildNumber = T.Text type Slug = T.Text data Repo = Repo { _slug :: Maybe Slug , _description :: Maybe T.Text , _lastBuildState :: Maybe BuildState , _lastBuildNumber :: Maybe BuildNumber , _lastBuildDuration :: Maybe Int , _lastBuildFinishedAt :: Maybe UTCTime , _active :: Maybe Bool }deriving(Ord, Eq, Show) makeLenses ''Repo instance FromJSON Repo where parseJSON = withObject "repo" $ \o -> Repo <$> o .: "slug" <*> o .:? "description" <*> o .:? "last_build_state" <*> o .:? "last_build_number" <*> o .:? "last_build_duration" <*> fmap parseTimestamp (o .:? "last_build_finished_at") <*> o.:? "active" where parseTimestamp :: Maybe String -> Maybe UTCTime parseTimestamp tsStr = case tsStr of Nothing -> Nothing (Just ts) -> TI.parseISO8601 ts mapBuildState :: BuildState -> IR.BuildState mapBuildState Passed = IR.Passed mapBuildState Failed = IR.Failed mapBuildState Created = IR.Running mapBuildState Started = IR.Running mapBuildState Unknown = IR.Unknown -- TODO: get complete list of possible states getLastBuildState :: Repo -> IR.BuildState getLastBuildState tr = case tr ^. lastBuildState of Just s -> mapBuildState s Nothing -> if DM.isNothing (tr ^. lastBuildFinishedAt) then IR.Running else IR.Unknown instance IR.ToInternalRepo Repo where toInternalRepo travisRepo = InternalRepo { IR._slug = travisRepo ^. slug , IR._description = travisRepo ^. description , IR._lastBuildState = Just $ getLastBuildState travisRepo , IR._lastBuildNumber = travisRepo ^. lastBuildNumber , IR._lastBuildDuration = travisRepo ^. lastBuildDuration , IR._lastBuildFinishedAt = travisRepo ^. lastBuildFinishedAt , IR._active = travisRepo ^. active } data ReposResponse = ReposResponse { repos :: [Repo] } deriving (Eq, Show, Generic) instance FromJSON ReposResponse -- makeLenses ''ReposResponse type Resp = W.Response ReposResponse -- at least Accept header required, see https://docs.travis-ci.com/api#making-requests opts :: W.Options opts = W.defaults & W.header "Accept" .~ ["application/vnd.travis-ci.2+json"] & W.header "User-Agent" .~ ["cilia-useragent"] handler :: HttpException -> IO (Either String Resp) handler (StatusCodeException s _ _ ) = return $ Left $ BSC.unpack (s ^. W.statusMessage) handler e = return $ Left (show e) getInternalRepos :: C.TravisSection -> IO (Either String [IR.InternalRepo]) getInternalRepos travisSection = do let userName' = travisSection ^. C.userName let reposUrl = TL.unpack $ TF.format "https://api.travis-ci.org/repos/{}" (TF.Only userName') eitherR <- (Right <$> (W.asJSON =<< W.getWith opts reposUrl)) `E.catch` handler :: IO (Either String Resp) case eitherR of (Right r) -> do let r' = repos (r ^. W.responseBody) return $ Right $ fmap IR.toInternalRepo r' (Left s) -> return $ Left s
bbiskup/cilia
src-lib/Cilia/CI/Travis.hs
mit
4,396
0
20
1,071
1,182
650
532
107
3
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiWayIf #-} module Model.Common where import GHC.Generics import Data.Aeson import Data.Text as T newtype Uuid = Uuid Text deriving (Show, Eq, Generic) instance FromJSON Uuid where parseJSON (String s) = if | T.length s == 36 -> return $ Uuid s | otherwise -> fail "could not parse UUID" parseJSON _ = fail "could not parse UUID" instance ToJSON Uuid uuidToText (Uuid s) = s
gip/cinq-cloches-ledger
src/Model/Common.hs
mit
494
0
12
112
140
73
67
15
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings, NoImplicitPrelude #-} module Stackage.BuildPlanSpec (spec) where import qualified Data.Map as Map import qualified Data.Map.Strict as M import qualified Data.Set as S import Data.Yaml import qualified Data.Yaml as Y import Distribution.Version import Network.HTTP.Client import Network.HTTP.Client.TLS (tlsManagerSettings) import Stackage.BuildConstraints import Stackage.BuildPlan import Stackage.CheckBuildPlan import Stackage.PackageDescription import Stackage.Prelude import Stackage.UpdateBuildPlan import Test.Hspec spec :: Spec spec = do it "simple package set" $ check testBuildConstraints $ makePackageSet [("foo", [0, 0, 0], [("bar", thisV [0, 0, 0])]) ,("bar", [0, 0, 0], [])] it "bad version range on depdendency fails" $ badBuildPlan $ makePackageSet [("foo", [0, 0, 0], [("bar", thisV [1, 1, 0])]) ,("bar", [0, 0, 0], [])] it "nonexistent package fails to check" $ badBuildPlan $ makePackageSet [("foo", [0, 0, 0], [("nonexistent", thisV [0, 0, 0])]) ,("bar", [0, 0, 0], [])] it "mutual cycles fail to check" $ badBuildPlan $ makePackageSet [("foo", [0, 0, 0], [("bar", thisV [0, 0, 0])]) ,("bar", [0, 0, 0], [("foo", thisV [0, 0, 0])])] it "nested cycles fail to check" $ badBuildPlan $ makePackageSet [("foo", [0, 0, 0], [("bar", thisV [0, 0, 0])]) ,("bar", [0, 0, 0], [("mu", thisV [0, 0, 0])]) ,("mu", [0, 0, 0], [("foo", thisV [0, 0, 0])])] it "default package set checks ok" $ check defaultBuildConstraints getLatestAllowedPlans -- | Checking should be considered a bad build plan. badBuildPlan :: (BuildConstraints -> IO (Map PackageName PackagePlan)) -> void -> IO () badBuildPlan m _ = do mu <- try (check testBuildConstraints m) case mu of Left (_ :: BadBuildPlan) -> return () Right () -> error "Expected bad build plan." -- | Check build plan with the given package set getter. check :: (Manager -> IO BuildConstraints) -> (BuildConstraints -> IO (Map PackageName PackagePlan)) -> IO () check readPlanFile getPlans = withManager tlsManagerSettings $ \man -> do bc <- readPlanFile man plans <- getPlans bc bp <- newBuildPlan plans bc let bs = Y.encode bp ebp' = Y.decodeEither bs bp' <- either error return ebp' let allPackages = Map.keysSet (bpPackages bp) ++ Map.keysSet (bpPackages bp') forM_ allPackages $ \name -> (name, lookup name (bpPackages bp')) `shouldBe` (name, lookup name (bpPackages bp)) bpGithubUsers bp' `shouldBe` bpGithubUsers bp when (bp' /= bp) $ error "bp' /= bp" bp2 <- updateBuildPlan plans bp when (dropVersionRanges bp2 /= dropVersionRanges bp) $ error "bp2 /= bp" checkBuildPlan bp where dropVersionRanges bp = bp { bpPackages = map go $ bpPackages bp } where go pb = pb { ppConstraints = go' $ ppConstraints pb } go' pc = pc { pcVersionRange = anyVersion } -- | Make a package set from a convenient data structure. makePackageSet :: [(String,[Int],[(String,VersionRange)])] -> BuildConstraints -> IO (Map PackageName PackagePlan) makePackageSet ps _ = return $ M.fromList $ map (\(name,ver,deps) -> ( PackageName name , dummyPackage ver $ M.fromList $ map (\(dname,dver) -> ( PackageName dname , DepInfo {diComponents = S.fromList [CompLibrary] ,diRange = dver})) deps)) ps where dummyPackage v deps = PackagePlan {ppVersion = Version v [] ,ppGithubPings = mempty ,ppUsers = mempty ,ppConstraints = PackageConstraints {pcVersionRange = anyV ,pcMaintainer = Nothing ,pcTests = Don'tBuild ,pcHaddocks = Don'tBuild ,pcBuildBenchmarks = False ,pcFlagOverrides = mempty ,pcEnableLibProfile = False} ,ppDesc = SimpleDesc {sdPackages = deps ,sdTools = mempty ,sdProvidedExes = mempty ,sdModules = mempty}} -- | This exact version is required. thisV :: [Int] -> VersionRange thisV ver = thisVersion (Version ver []) -- | Accept any version. anyV :: VersionRange anyV = anyVersion -- | Test plan. testBuildConstraints :: void -> IO BuildConstraints testBuildConstraints _ = decodeFileEither (fpToString fp) >>= either throwIO toBC where fp = "test/test-build-constraints.yaml"
k0001/stackage
test/Stackage/BuildPlanSpec.hs
mit
5,124
0
18
1,722
1,486
829
657
121
2
module Dist3 where import Context import DB3 import Measure import Network.Socket.Internal (withSocketsDo) import Network.Socket (close) import Control.Concurrent (forkIO,threadDelay) import Network -- (PortID(PortNumber),listenOn,accept,connectTo) import System.IO (hGetLine,hPutStrLn,hClose,hFlush) import Control.Monad (forever) ------------------------------------------------------ -- Optimizations / distribution ------------------------------------------------------ slave :: String -> PortNumber -> IO () slave file port = withSocketsDo $ do dta <- readFile file let db = read dta :: Graph sock <- listenOn $ PortNumber port slavebody db sock slavebody db sock = forever $ do (handle, host, port) <- accept sock query <- hGetLine handle let pat = read query :: Graph let r = answer pat db ([],[]) hPutStrLn handle (show r) hFlush handle hClose handle -- master with n slaves master' hosts q = withSocketsDo $ do let ns = map (\h -> connectTo (fst h) (PortNumber (snd h))) hosts r <- sequence (map (\n -> transmit n q) ns) p <- perf concat r let m = "Get result in " ++ (show $ fst p) putStrLn m master'' hosts q = withSocketsDo $ do let ns = map (\h -> connectTo (fst h) (PortNumber (snd h))) hosts r <- sequence (map (\n -> transmit n q) ns) p <- perf concat r print (map snd (snd p)) transmit n q = do h <- n hPutStrLn h q hFlush h rep <- hGetLine h let r = read rep :: [([String], [[String]])] hClose h return r end n = do h <- n hClose h
thiry/DComp
src/Dist3.hs
gpl-2.0
1,488
0
18
278
633
311
322
46
1
{-| Module : Constants Description : IVI's constant values -} module Constants ( -- * Strings iviName , iviExtension , iviDirname -- * Paths , iviDirectory ) where import System.Directory (getHomeDirectory) import System.FilePath.Posix ((</>)) iviName, iviExtension, iviDirname :: String -- | The name of the program. This is constant, yes. iviName = "IVI" -- | The extension for ivi config files iviExtension = "ivi" -- | The name of the ivi config directory iviDirname = "." ++ iviName -- | The users IVI directory iviDirectory :: IO FilePath iviDirectory = getHomeDirectory >>= (\x -> return $ x </> iviDirname)
NorfairKing/IVI
src/Constants.hs
gpl-2.0
658
0
9
142
109
70
39
13
1
{-# LANGUAGE TemplateHaskell #-} {-| Some common types. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.HTools.Types ( Idx , Ndx , Gdx , NameAssoc , Score , Weight , GroupID , defaultGroupID , AllocPolicy(..) , allocPolicyFromRaw , allocPolicyToRaw , NetworkID , InstanceStatus(..) , instanceStatusFromRaw , instanceStatusToRaw , RSpec(..) , AllocInfo(..) , AllocStats , DynUtil(..) , zeroUtil , baseUtil , addUtil , subUtil , defReservedDiskRatio , unitMem , unitCpu , unitDsk , unitSpindle , unknownField , Placement , IMove(..) , DiskTemplate(..) , diskTemplateToRaw , diskTemplateFromRaw , MirrorType(..) , templateMirrorType , MoveJob , JobSet , Element(..) , FailMode(..) , FailStats , OpResult , opToResult , EvacMode(..) , ISpec(..) , MinMaxISpecs(..) , IPolicy(..) , defIPolicy , rspecFromISpec , AutoRepairType(..) , autoRepairTypeToRaw , autoRepairTypeFromRaw , AutoRepairResult(..) , autoRepairResultToRaw , autoRepairResultFromRaw , AutoRepairPolicy(..) , AutoRepairSuspendTime(..) , AutoRepairData(..) , AutoRepairStatus(..) ) where import qualified Data.Map as M import System.Time (ClockTime) import qualified Ganeti.Constants as C import qualified Ganeti.THH as THH import Ganeti.BasicTypes import Ganeti.Types -- | The instance index type. type Idx = Int -- | The node index type. type Ndx = Int -- | The group index type. type Gdx = Int -- | The type used to hold name-to-idx mappings. type NameAssoc = M.Map String Int -- | A separate name for the cluster score type. type Score = Double -- | A separate name for a weight metric. type Weight = Double -- | The Group UUID type. type GroupID = String -- | Default group UUID (just a string, not a real UUID). defaultGroupID :: GroupID defaultGroupID = "00000000-0000-0000-0000-000000000000" -- | Mirroring type. data MirrorType = MirrorNone -- ^ No mirroring/movability | MirrorInternal -- ^ DRBD-type mirroring | MirrorExternal -- ^ Shared-storage type mirroring deriving (Eq, Show) -- | Correspondence between disk template and mirror type. templateMirrorType :: DiskTemplate -> MirrorType templateMirrorType DTDiskless = MirrorExternal templateMirrorType DTFile = MirrorNone templateMirrorType DTSharedFile = MirrorExternal templateMirrorType DTPlain = MirrorNone templateMirrorType DTBlock = MirrorExternal templateMirrorType DTDrbd8 = MirrorInternal templateMirrorType DTRbd = MirrorExternal templateMirrorType DTExt = MirrorExternal -- | The resource spec type. data RSpec = RSpec { rspecCpu :: Int -- ^ Requested VCPUs , rspecMem :: Int -- ^ Requested memory , rspecDsk :: Int -- ^ Requested disk , rspecSpn :: Int -- ^ Requested spindles } deriving (Show, Eq) -- | Allocation stats type. This is used instead of 'RSpec' (which was -- used at first), because we need to track more stats. The actual -- data can refer either to allocated, or available, etc. values -- depending on the context. See also -- 'Cluster.computeAllocationDelta'. data AllocInfo = AllocInfo { allocInfoVCpus :: Int -- ^ VCPUs , allocInfoNCpus :: Double -- ^ Normalised CPUs , allocInfoMem :: Int -- ^ Memory , allocInfoDisk :: Int -- ^ Disk , allocInfoSpn :: Int -- ^ Spindles } deriving (Show, Eq) -- | Currently used, possibly to allocate, unallocable. type AllocStats = (AllocInfo, AllocInfo, AllocInfo) -- | The network UUID type. type NetworkID = String -- | Instance specification type. $(THH.buildObject "ISpec" "iSpec" [ THH.renameField "MemorySize" $ THH.simpleField C.ispecMemSize [t| Int |] , THH.renameField "CpuCount" $ THH.simpleField C.ispecCpuCount [t| Int |] , THH.renameField "DiskSize" $ THH.simpleField C.ispecDiskSize [t| Int |] , THH.renameField "DiskCount" $ THH.simpleField C.ispecDiskCount [t| Int |] , THH.renameField "NicCount" $ THH.simpleField C.ispecNicCount [t| Int |] , THH.renameField "SpindleUse" $ THH.simpleField C.ispecSpindleUse [t| Int |] ]) -- | The default minimum ispec. defMinISpec :: ISpec defMinISpec = ISpec { iSpecMemorySize = C.ispecsMinmaxDefaultsMinMemorySize , iSpecCpuCount = C.ispecsMinmaxDefaultsMinCpuCount , iSpecDiskSize = C.ispecsMinmaxDefaultsMinDiskSize , iSpecDiskCount = C.ispecsMinmaxDefaultsMinDiskCount , iSpecNicCount = C.ispecsMinmaxDefaultsMinNicCount , iSpecSpindleUse = C.ispecsMinmaxDefaultsMinSpindleUse } -- | The default standard ispec. defStdISpec :: ISpec defStdISpec = ISpec { iSpecMemorySize = C.ipolicyDefaultsStdMemorySize , iSpecCpuCount = C.ipolicyDefaultsStdCpuCount , iSpecDiskSize = C.ipolicyDefaultsStdDiskSize , iSpecDiskCount = C.ipolicyDefaultsStdDiskCount , iSpecNicCount = C.ipolicyDefaultsStdNicCount , iSpecSpindleUse = C.ipolicyDefaultsStdSpindleUse } -- | The default max ispec. defMaxISpec :: ISpec defMaxISpec = ISpec { iSpecMemorySize = C.ispecsMinmaxDefaultsMaxMemorySize , iSpecCpuCount = C.ispecsMinmaxDefaultsMaxCpuCount , iSpecDiskSize = C.ispecsMinmaxDefaultsMaxDiskSize , iSpecDiskCount = C.ispecsMinmaxDefaultsMaxDiskCount , iSpecNicCount = C.ispecsMinmaxDefaultsMaxNicCount , iSpecSpindleUse = C.ispecsMinmaxDefaultsMaxSpindleUse } -- | Minimum and maximum instance specs type. $(THH.buildObject "MinMaxISpecs" "minMaxISpecs" [ THH.renameField "MinSpec" $ THH.simpleField "min" [t| ISpec |] , THH.renameField "MaxSpec" $ THH.simpleField "max" [t| ISpec |] ]) -- | Defult minimum and maximum instance specs. defMinMaxISpecs :: [MinMaxISpecs] defMinMaxISpecs = [MinMaxISpecs { minMaxISpecsMinSpec = defMinISpec , minMaxISpecsMaxSpec = defMaxISpec }] -- | Instance policy type. $(THH.buildObject "IPolicy" "iPolicy" [ THH.renameField "MinMaxISpecs" $ THH.simpleField C.ispecsMinmax [t| [MinMaxISpecs] |] , THH.renameField "StdSpec" $ THH.simpleField C.ispecsStd [t| ISpec |] , THH.renameField "DiskTemplates" $ THH.simpleField C.ipolicyDts [t| [DiskTemplate] |] , THH.renameField "VcpuRatio" $ THH.simpleField C.ipolicyVcpuRatio [t| Double |] , THH.renameField "SpindleRatio" $ THH.simpleField C.ipolicySpindleRatio [t| Double |] ]) -- | Converts an ISpec type to a RSpec one. rspecFromISpec :: ISpec -> RSpec rspecFromISpec ispec = RSpec { rspecCpu = iSpecCpuCount ispec , rspecMem = iSpecMemorySize ispec , rspecDsk = iSpecDiskSize ispec , rspecSpn = iSpecSpindleUse ispec } -- | The default instance policy. defIPolicy :: IPolicy defIPolicy = IPolicy { iPolicyMinMaxISpecs = defMinMaxISpecs , iPolicyStdSpec = defStdISpec -- hardcoding here since Constants.hs exports the -- string values, not the actual type; and in -- htools, we are mostly looking at DRBD , iPolicyDiskTemplates = [minBound..maxBound] , iPolicyVcpuRatio = C.ipolicyDefaultsVcpuRatio , iPolicySpindleRatio = C.ipolicyDefaultsSpindleRatio } -- | The dynamic resource specs of a machine (i.e. load or load -- capacity, as opposed to size). data DynUtil = DynUtil { cpuWeight :: Weight -- ^ Standardised CPU usage , memWeight :: Weight -- ^ Standardised memory load , dskWeight :: Weight -- ^ Standardised disk I\/O usage , netWeight :: Weight -- ^ Standardised network usage } deriving (Show, Eq) -- | Initial empty utilisation. zeroUtil :: DynUtil zeroUtil = DynUtil { cpuWeight = 0, memWeight = 0 , dskWeight = 0, netWeight = 0 } -- | Base utilisation (used when no actual utilisation data is -- supplied). baseUtil :: DynUtil baseUtil = DynUtil { cpuWeight = 1, memWeight = 1 , dskWeight = 1, netWeight = 1 } -- | Sum two utilisation records. addUtil :: DynUtil -> DynUtil -> DynUtil addUtil (DynUtil a1 a2 a3 a4) (DynUtil b1 b2 b3 b4) = DynUtil (a1+b1) (a2+b2) (a3+b3) (a4+b4) -- | Substracts one utilisation record from another. subUtil :: DynUtil -> DynUtil -> DynUtil subUtil (DynUtil a1 a2 a3 a4) (DynUtil b1 b2 b3 b4) = DynUtil (a1-b1) (a2-b2) (a3-b3) (a4-b4) -- | The description of an instance placement. It contains the -- instance index, the new primary and secondary node, the move being -- performed and the score of the cluster after the move. type Placement = (Idx, Ndx, Ndx, IMove, Score) -- | An instance move definition. data IMove = Failover -- ^ Failover the instance (f) | FailoverToAny Ndx -- ^ Failover to a random node -- (fa:np), for shared storage | ReplacePrimary Ndx -- ^ Replace primary (f, r:np, f) | ReplaceSecondary Ndx -- ^ Replace secondary (r:ns) | ReplaceAndFailover Ndx -- ^ Replace secondary, failover (r:np, f) | FailoverAndReplace Ndx -- ^ Failover, replace secondary (f, r:ns) deriving (Show) -- | Formatted solution output for one move (involved nodes and -- commands. type MoveJob = ([Ndx], Idx, IMove, [String]) -- | Unknown field in table output. unknownField :: String unknownField = "<unknown field>" -- | A list of command elements. type JobSet = [MoveJob] -- | Default max disk usage ratio. defReservedDiskRatio :: Double defReservedDiskRatio = 0 -- | Base memory unit. unitMem :: Int unitMem = 64 -- | Base disk unit. unitDsk :: Int unitDsk = 256 -- | Base vcpus unit. unitCpu :: Int unitCpu = 1 -- | Base spindles unit. unitSpindle :: Int unitSpindle = 1 -- | Reason for an operation's falure. data FailMode = FailMem -- ^ Failed due to not enough RAM | FailDisk -- ^ Failed due to not enough disk | FailCPU -- ^ Failed due to not enough CPU capacity | FailN1 -- ^ Failed due to not passing N1 checks | FailTags -- ^ Failed due to tag exclusion | FailDiskCount -- ^ Failed due to wrong number of disks | FailSpindles -- ^ Failed due to wrong/missing spindles | FailInternal -- ^ Internal error deriving (Eq, Enum, Bounded, Show) -- | List with failure statistics. type FailStats = [(FailMode, Int)] -- | Either-like data-type customized for our failure modes. -- -- The failure values for this monad track the specific allocation -- failures, so this is not a general error-monad (compare with the -- 'Result' data type). One downside is that this type cannot encode a -- generic failure mode, hence our way to build a FailMode from string -- will instead raise an exception. type OpResult = GenericResult FailMode -- | 'FromString' instance for 'FailMode' designed to catch unintended -- use as a general monad. instance FromString FailMode where mkFromString v = error $ "Programming error: OpResult used as generic monad" ++ v -- | Conversion from 'OpResult' to 'Result'. opToResult :: OpResult a -> Result a opToResult (Bad f) = Bad $ show f opToResult (Ok v) = Ok v -- | A generic class for items that have updateable names and indices. class Element a where -- | Returns the name of the element nameOf :: a -> String -- | Returns all the known names of the element allNames :: a -> [String] -- | Returns the index of the element idxOf :: a -> Int -- | Updates the alias of the element setAlias :: a -> String -> a -- | Compute the alias by stripping a given suffix (domain) from -- the name computeAlias :: String -> a -> a computeAlias dom e = setAlias e alias where alias = take (length name - length dom) name name = nameOf e -- | Updates the index of the element setIdx :: a -> Int -> a -- | The iallocator node-evacuate evac_mode type. $(THH.declareSADT "EvacMode" [ ("ChangePrimary", 'C.iallocatorNevacPri) , ("ChangeSecondary", 'C.iallocatorNevacSec) , ("ChangeAll", 'C.iallocatorNevacAll) ]) $(THH.makeJSONInstance ''EvacMode) -- | The repair modes for the auto-repair tool. $(THH.declareSADT "AutoRepairType" -- Order is important here: from least destructive to most. [ ("ArFixStorage", 'C.autoRepairFixStorage) , ("ArMigrate", 'C.autoRepairMigrate) , ("ArFailover", 'C.autoRepairFailover) , ("ArReinstall", 'C.autoRepairReinstall) ]) -- | The possible auto-repair results. $(THH.declareSADT "AutoRepairResult" -- Order is important here: higher results take precedence when an object -- has several result annotations attached. [ ("ArEnoperm", 'C.autoRepairEnoperm) , ("ArSuccess", 'C.autoRepairSuccess) , ("ArFailure", 'C.autoRepairFailure) ]) -- | The possible auto-repair policy for a given instance. data AutoRepairPolicy = ArEnabled AutoRepairType -- ^ Auto-repair explicitly enabled | ArSuspended AutoRepairSuspendTime -- ^ Suspended temporarily, or forever | ArNotEnabled -- ^ Auto-repair not explicitly enabled deriving (Eq, Show) -- | The suspend timeout for 'ArSuspended'. data AutoRepairSuspendTime = Forever -- ^ Permanently suspended | Until ClockTime -- ^ Suspended up to a certain time deriving (Eq, Show) -- | The possible auto-repair states for any given instance. data AutoRepairStatus = ArHealthy (Maybe AutoRepairData) -- ^ No problems detected with the instance | ArNeedsRepair AutoRepairData -- ^ Instance has problems, no action taken | ArPendingRepair AutoRepairData -- ^ Repair jobs ongoing for the instance | ArFailedRepair AutoRepairData -- ^ Some repair jobs for the instance failed deriving (Eq, Show) -- | The data accompanying a repair operation (future, pending, or failed). data AutoRepairData = AutoRepairData { arType :: AutoRepairType , arUuid :: String , arTime :: ClockTime , arJobs :: [JobId] , arResult :: Maybe AutoRepairResult , arTag :: String } deriving (Eq, Show)
narurien/ganeti-ceph
src/Ganeti/HTools/Types.hs
gpl-2.0
15,496
0
12
4,006
2,430
1,485
945
261
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} module Moonbase.DBus ( Call , Signal , Help , Usage , Com(..) , Nameable(..) , withoutHelp , packName, unpackName , moonbaseBusName , moonbaseCliBusName , moonbaseInterfaceName , moonbaseObjectPath , withInterface , withObjectPath , connectDBus -- re-expors , DBus.ObjectPath , DBus.InterfaceName , DBus.MemberName , DBus.Variant ) where import Control.Concurrent.STM.TVar import Control.Lens import Control.Monad.Reader import Control.Monad.State import qualified DBus import qualified DBus.Client as DBus import Data.Char (isUpper, toLower, toUpper) import qualified Data.Map as M import Data.Maybe import Moonbase.Core type Call = (DBus.ObjectPath, DBus.InterfaceName, DBus.MemberName) type Signal = String type Help = String type Usage = String class (Moonbase rt m) => Com rt m where call :: Call -> [DBus.Variant] -> MB rt m [DBus.Variant] call_ :: Call -> [DBus.Variant] -> MB rt m () on :: (Nameable a) => a -> Help -> Usage -> ([String] -> MB rt m String) -> MB rt m () callback :: (Signal -> MB rt m ()) -> MB rt m () class Nameable a where prepareName :: a -> (String, String) instance Nameable String where prepareName n = (packName n, lower) where lower = map toLower n instance Nameable (String, String) where prepareName (n, a) = (packName n, a) withoutHelp :: String withoutHelp = "No help is available." packName :: String -> String packName [] = [] packName (' ':xs) = packName xs packName ('-':x:xs) = toUpper x : packName xs packName ('_':x:xs) = toUpper x : packName xs packName (x:xs) = x : packName xs unpackName :: String -> String unpackName [] = [] unpackName (x:xs) | isUpper x = '-' : toLower x : unpackName xs | otherwise = x : unpackName xs moonbaseBusName :: DBus.BusName moonbaseBusName = "org.moonbase" moonbaseCliBusName :: DBus.BusName moonbaseCliBusName = "org.moonbase.cli" moonbaseInterfaceName :: DBus.InterfaceName moonbaseInterfaceName = "org.moonbase" moonbaseObjectPath :: DBus.ObjectPath moonbaseObjectPath = "/org/moonbase" withInterface :: String -> DBus.InterfaceName withInterface name = DBus.interfaceName_ $ DBus.formatInterfaceName moonbaseInterfaceName ++ "." ++ name withObjectPath :: String -> DBus.ObjectPath withObjectPath name = DBus.objectPath_ $ DBus.formatObjectPath moonbaseObjectPath ++ "/" ++ name connectDBus :: DBus.BusName -> IO (Maybe DBus.Client) connectDBus bus = do client <- DBus.connectSession name <- DBus.requestName client bus [] return $ case name of DBus.NamePrimaryOwner -> Just client _ -> Nothing
felixsch/moonbase
src/Moonbase/DBus.hs
gpl-3.0
2,960
0
14
711
878
478
400
83
2
{-# LANGUAGE TemplateHaskell #-} module Haemu.Instruction ( sliced , instruction , Instruction(..) , datalength , dataflags , condition , optype , opcode , dataBlock , int ) where import Haemu.Types import Data.Word import Data.Bits import qualified Data.Vector.Unboxed as V import Control.Lens import Control.Monad -- | This represents an instruction as it is used throughout the program. data Instruction = Instruction { _optype :: Optype , _opcode :: Opcode , _dataflags :: Dataflags , _condition :: Condition , _dataBlock :: DataBlock } deriving (Show, Eq) makeLenses ''Instruction -- | A lens for a sliced part of some bits. @sliced n m@ views m bits, starting with bit n (where -- n = 0 starts with the first bit). The sliced part is readjusted, such that the first bit of the -- sliced part is the bit at position n in the original. -- Warning: This is only a valid lens if you don't set it to a value greater than 2^m - 1, in which -- case all higher bits will be cut off. sliced :: (Functor f, Bits a, Num a) => Int -> Int -> (a -> f a) -> a -> f a sliced n m = lens t s where mask = (1 `shiftL` m - 1) `shiftL` n t x = (x .&. mask) `shiftR` n s x v = (x .&. complement mask) .|. ((v `shiftL` n) .&. mask) -- | Parse / serialize an instruction from / to a vector of Word16. -- Format of vector (if seen as one big chunk of memory): -- first 4 bits: count of datablocks (must match with the actual length) -- bits 4 - 8: register / value flags specifing whether the given parameter is a register or a value -- bits 8 - 16: condition. Used as a guard. If the guard doesn't match, the instruction is not executed. -- bits 16 - 20: optype. Instructions can have differnent types (like arithmetic or logical) -- bits 20 - 32: opcode. An per-optype unique indentifier for the instruction. -- bits 32 - end: Datablocks -- Warning: There may be at most 15 data blocks in the instruction for this to be a valid prism. instruction :: Prism' (V.Vector Word16) Instruction instruction = prism' f t where f (Instruction ot oc df c d) = V.cons b1 $ V.cons b2 d where b1 = 0 & sliced 0 4 . int .~ l & sliced 4 4 . int .~ df & sliced 8 8 . int .~ c b2 = 0 & sliced 0 4 . int .~ ot & sliced 4 12 . int .~ oc l = V.length d t b = do l <- b ^? ix 0 . sliced 0 4 . int df <- b ^? ix 0 . sliced 4 4 . int c <- b ^? ix 0 . sliced 8 8 . int ot <- b ^? ix 1 . sliced 0 4 . int oc <- b ^? ix 1 . sliced 4 12 . int let d = V.drop 2 b guard $ V.length d == l return $ Instruction ot oc df c d -- | An iso converting from one integral type to another one. Warning: This only a valid iso -- when no overflows or underflows happen. int :: (Integral a, Integral b) => Iso' a b int = iso fromIntegral fromIntegral -- | The length of the data attached to some instruction datalength :: Getter Instruction Int datalength = dataBlock . to V.length
bennofs/haemu
src/Haemu/Instruction.hs
gpl-3.0
3,026
0
18
794
737
389
348
-1
-1
{- Copyright (C) 2014 Ellis Whitehead This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> -} {-# LANGUAGE OverloadedStrings #-} module OnTopOfThings.Data.Time where import Control.Applicative ((<$>), (<*>), empty) import Control.Monad (mplus, msum) import Data.List (intercalate) import Data.Maybe (catMaybes, fromMaybe) import Data.Time.Calendar import Data.Time.Clock import Data.Time.Format import Data.Time.ISO8601 import Data.Time.LocalTime import System.Locale (defaultTimeLocale) import Utils data Time = Time { otimeDay :: Day , otimeHour :: Maybe Int , otimeMinute :: Maybe Int , otimeSecond :: Maybe Int , otimeZone :: Maybe TimeZone } instance Show Time where show time = formatTime' time instance Eq Time where tm1 == tm2 = compare tm1 tm2 == EQ instance Ord Time where compare (Time day1 hour1_ minute1_ second1_ tz1_) (Time day2 hour2_ minute2_ second2_ tz2_) = case compare day1 day2 of EQ -> compare l1 l2 where -- TODO: get information from the timezone too! l1 = [fromMaybe 0 hour1_, fromMaybe 0 minute1_, fromMaybe 0 second1_] l2 = [fromMaybe 0 hour2_, fromMaybe 0 minute2_, fromMaybe 0 second2_] x -> x -- For some time handling notes, see: <http://tab.snarc.org/posts/haskell/2011-12-16-date-in-haskell.html> parseTime' :: TimeZone -> String -> Validation Time parseTime' tz s = msum x `maybeToValidation` ["Could not parse time: "++s] where l = [("%FT%T%QZ", 3, True), ("%Y-%m-%d", 0, False), ("%Y-%m-%dT%H:%M", 2, False), ("%Y-%m-%dT%H:%M:%S", 3, False), ("%Y-%m-%dT%H:%M%Z", 2, True), ("%Y-%m-%dT%H:%M:%S%Z", 3, True)] x = map step l step :: (String, Int, Bool) -> Maybe Time step (format, n, hasTz) = case (parseTime defaultTimeLocale format s :: Maybe ZonedTime) of Nothing -> Nothing Just zoned -> Just $ zonedToTimeN zoned n hasTz --parseTimeDate :: String -> Maybe Day --parseTimeDate s = -- (fn "%Y-%m-%d") `mplus` (fn "%m/%d/%Y") `mplus` (fn "%d.%m.%Y") -- where -- fn :: String -> Maybe Day -- fn format = parseTime defaultTimeLocale format s -- --parseTimeTime :: String -> Maybe TimeOfDay --parseTimeTime s = -- (fn "%H:%M") `mplus` (fn "%H:%M:%S") `mplus` (fn "%Hh") -- where -- fn format = parseTime defaultTimeLocale format s formatTime' :: Time -> String formatTime' (Time day hour minute second zone) = d_s ++ t_s ++ z_s where d_s = formatTime defaultTimeLocale "%Y-%m-%d" day t_s = case (hour, minute, second) of (Just h, Nothing, _) -> "T" ++ (formatTime defaultTimeLocale "%H:%M" difftime) where difftime = timeToTimeOfDay (fromIntegral (h*60*60) :: DiffTime) (Just h, Just m, Nothing) -> "T" ++ (formatTime defaultTimeLocale "%H:%M" difftime) where difftime = timeToTimeOfDay (fromIntegral ((h*60 + m)*60) :: DiffTime) (Just h, Just m, Just s) -> "T" ++ (formatTime defaultTimeLocale "%H:%M:%S" difftime) where difftime = timeToTimeOfDay (fromIntegral ((h*60 + m)*60 + s) :: DiffTime) _ -> "" z_s = case zone of Just tz -> formatTime defaultTimeLocale "%Z" tz _ -> "" zonedToTime :: ZonedTime -> Time zonedToTime zoned = Time day (Just (todHour tod)) (Just (todMin tod)) (Just (round $ todSec tod)) (Just tz) where local = zonedTimeToLocalTime zoned day = localDay local tod = localTimeOfDay local tz = zonedTimeZone zoned zonedToTimeN :: ZonedTime -> Int -> Bool -> Time zonedToTimeN zoned n hasTz = Time day (ifn 1 (todHour tod)) (ifn 2 (todMin tod)) (ifn 3 (round $ todSec tod)) (if hasTz then Just tz else Nothing) where local = zonedTimeToLocalTime zoned day = localDay local tod = localTimeOfDay local tz = zonedTimeZone zoned ifn n' _ | n' > n = Nothing ifn n' x = Just x utcToTime :: UTCTime -> TimeZone -> Time utcToTime utc tz = zonedToTime (utcToZonedTime tz utc)
ellis/OnTopOfThings
old-20150308/src/OnTopOfThings/Data/Time.hs
gpl-3.0
4,361
0
20
837
1,197
647
550
70
5
module Main where import Control.Applicative import Control.Monad import Control.Monad.Reader import Control.Monad.Error import System.FilePath import System.Directory import System.Log.Logger -- -- import HEP.Automation.MadGraph.Card import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Model.SM -- import HEP.Automation.MadGraph.Model.ADMXQLD211 import HEP.Automation.MadGraph.Run import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Type import HEP.Parser.LHE.Sanitizer.Type import HEP.Storage.WebDAV -- import qualified Paths_madgraph_auto as PMadGraph import qualified Paths_madgraph_auto_model as PModel -- | getScriptSetup :: IO ScriptSetup getScriptSetup = do homedir <- getHomeDirectory mdldir <- (</> "template") <$> PModel.getDataDir rundir <- (</> "template") <$> PMadGraph.getDataDir return $ SS { modeltmpldir = mdldir , runtmpldir = rundir , sandboxdir = homedir </> "temp/montecarlo/sandbox" , mg5base = homedir </> "temp/montecarlo/MG5_aMC_v2_1_0" , mcrundir = homedir </> "temp/montecarlo/mcrun" , pythia8dir = "" , pythia8toHEPEVT = "" , hepevt2stdhep = "" } -- | processSetup :: ProcessSetup SM processSetup = PS { model = SM , process = MGProc [] ["p p > t t~"] , processBrief = "ttbar" , workname = "TestTTBar" , hashSalt = HashSalt Nothing } -- | pset :: ModelParam SM pset = SMParam -- | rsetup :: RunSetup rsetup = RS { numevent = 10000 , machine = LHC7 ATLAS , rgrun = Auto -- Fixed , rgscale = 200.0 , match = NoMatch , cut = NoCut , pythia = NoPYTHIA -- RunPYTHIA , lhesanitizer = [Replace [(9000201,1000022),(-9000201,1000022)]] , pgs = RunPGS (Cone 0.4, WithTau) , uploadhep = NoUploadHEP , setnum = 1 } -- | getWSetup :: IO (WorkSetup SM) getWSetup = WS <$> getScriptSetup <*> pure processSetup <*> pure pset <*> pure rsetup <*> pure (WebDAVRemoteDir "") main :: IO () main = do updateGlobalLogger "MadGraphAuto" (setLevel DEBUG) work =<< getWSetup -- | work :: (WorkSetup SM) -> IO () work wsetup = do r <- flip runReaderT wsetup . runErrorT $ do WS ssetup psetup _ rs _ <- ask let wb = mcrundir ssetup wn = workname psetup b <- liftIO $ (doesDirectoryExist (wb </> wn)) when (not b) $ createWorkDir ssetup psetup cardPrepare generateEvents case (lhesanitizer rs, pythia rs) of ([], _) -> return () (_:_, RunPYTHIA8) -> return () (_:_, RunPYTHIA) -> do sanitizeLHE runPYTHIA runPGS runClean (_:_, NoPYTHIA) -> do sanitizeLHE cleanHepFiles print r return ()
wavewave/madgraph-auto
test/madgraphRun.hs
gpl-3.0
2,973
0
16
902
782
436
346
82
4
-- -- Copyright (c) 2017 Daniel Gonçalves da Silva - https://github.com/danielgoncalvesti -- GPL version 3 or later (see http://www.gnu.org/copyleft/gpl.html) -- module Main where import System.Environment verifyValue :: Integer -> Bool verifyValue x | x < -1 || x == 2 = True | otherwise = False -- | The main function main :: IO () main = do print(verifyValue (-2))
danielgoncalvesti/BIGDATA2017
Atividade01/Haskell/Activity1/Exercises1/Ex5.hs
gpl-3.0
387
0
11
78
92
49
43
8
1
{- | An encapsulation of a grid-based GUI, where rows and columns of textures are rendered at 1:1 aspect ratio, and specific parts of the grid can be labelled with the intent of locating mouse clicks. -} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} module Jelly.Arrangement where import Jelly.Prelude import Jelly.SDL import Foreign (alloca, nullPtr, peek, with) import Foreign.C (CInt) import qualified Graphics.UI.SDL as SDL data Arrangement a = Whole SDL.Texture | Crop SDL.Rect SDL.Texture | Rectangle (CInt, CInt) SDL.Color | Arrangement a `Beside` Arrangement a -- ^ left, right | Arrangement a `Above` Arrangement a -- ^ above, below | Arrangement a `Behind` Arrangement a -- ^ back, front | Label a (Arrangement a) deriving (Eq, Show, Functor) zeroSpace :: Arrangement a zeroSpace = space (0, 0) space :: (CInt, CInt) -> Arrangement a space (x, y) = Rectangle (x, y) $ SDL.Color 0 0 0 0 row, column, layers :: [Arrangement a] -> Arrangement a row = foldr Beside zeroSpace column = foldr Above zeroSpace layers = foldr Behind zeroSpace -- | Given a location, finds the label that it is located in, as well as its -- position within the label. findLabel :: (CInt, CInt) -> Arrangement a -> IO (Maybe (a, (CInt, CInt))) findLabel (x, y) = \case Whole {} -> pure Nothing Crop {} -> pure Nothing Rectangle {} -> pure Nothing Label lbl arr -> do (w, h) <- getDims arr pure $ do guard $ (0 <= x && x < w) && (0 <= y && y < h) Just (lbl, (x, y)) a0 `Beside` a1 -> do w <- getWidth a0 if x < w then findLabel (x , y) a0 else findLabel (x - w, y) a1 a0 `Above` a1 -> do h <- getHeight a0 if y < h then findLabel (x, y ) a0 else findLabel (x, y - h) a1 a0 `Behind` a1 -> findLabel (x, y) a1 >>= \case Just res -> pure $ Just res Nothing -> findLabel (x, y) a0 getDims :: Arrangement a -> IO (CInt, CInt) getDims (Whole tex) = alloca $ \pw -> alloca $ \ph -> do zero $ SDL.queryTexture tex nullPtr nullPtr pw ph liftA2 (,) (peek pw) (peek ph) getDims (Crop (SDL.Rect _ _ w h) _) = pure (w, h) getDims (a0 `Beside` a1) = do (w0, h0) <- getDims a0 (w1, h1) <- getDims a1 pure (w0 + w1, max h0 h1) getDims (a0 `Above` a1) = do (w0, h0) <- getDims a0 (w1, h1) <- getDims a1 pure (max w0 w1, h0 + h1) getDims (a0 `Behind` a1) = do (w0, h0) <- getDims a0 (w1, h1) <- getDims a1 pure (max w0 w1, max h0 h1) getDims (Rectangle dims _) = pure dims getDims (Label _ arr) = getDims arr getWidth, getHeight :: Arrangement a -> IO CInt getWidth = fmap fst . getDims getHeight = fmap snd . getDims render :: SDL.Renderer -> (CInt, CInt) -> Arrangement a -> IO () render rend pn arrange = do (windowW, windowH) <- alloca $ \pw -> alloca $ \ph -> do zero $ SDL.getRendererOutputSize rend pw ph liftA2 (,) (peek pw) (peek ph) let go (x, y) arr = when (x < windowW && y < windowH) $ case arr of Whole tex -> do (w, h) <- getDims arr zero $ with (SDL.Rect x y w h) $ SDL.renderCopy rend tex nullPtr Crop r tex -> zero $ with r $ \p0 -> with (SDL.Rect x y (SDL.rectW r) (SDL.rectH r)) $ \p1 -> SDL.renderCopy rend tex p0 p1 a0 `Beside` a1 -> do w <- getWidth a0 go (x , y) a0 go (x + w, y) a1 a0 `Above` a1 -> do h <- getHeight a0 go (x, y ) a0 go (x, y + h) a1 a0 `Behind` a1 -> do go (x, y) a0 go (x, y) a1 Rectangle _ (SDL.Color _ _ _ 0) -> pure () Rectangle (0, _) _ -> pure () Rectangle (_, 0) _ -> pure () Rectangle (w, h) (SDL.Color r g b a) -> do zero $ SDL.setRenderDrawColor rend r g b a zero $ with (SDL.Rect x y w h) $ SDL.renderDrawRect rend Label _ ar -> go (x, y) ar go pn arrange
mtolly/jelly
src/Jelly/Arrangement.hs
gpl-3.0
4,035
0
22
1,231
1,749
901
848
103
10
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE GADTs #-} module Network.HTTP.WebSub.Subscriber ( SubscriptionId(..) , SubscribeError(..) , SubscribeResult(..) , ContentDistributionCallback , Client(..) , Subscriptions , newSubscriptions , subscribe , awaitActiveSubscription , deny , verify , distributeContent , distributeContentAuthenticated ) where import Control.Concurrent.MVar import Control.Monad.Except import Crypto.Hash import Crypto.MAC.HMAC import Data.ByteArray (convert, constEq) import qualified Data.ByteString as BS import qualified Data.ByteString.Base16 as Base16 import qualified Data.ByteString.Char8 as C import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Data.Hashable import Data.Maybe (fromMaybe, maybe) import Data.Time import System.Random import Network.HTTP.WebSub import Network.URI -- | A unique ID for a subscription. newtype SubscriptionId = SubscriptionId BS.ByteString deriving (Show, Eq) instance Hashable SubscriptionId where hashWithSalt salt = hashWithSalt salt . show -- | The different types of errors that can occur when subscribing to -- a topic. data SubscribeError = InvalidHub Hub | SubscriptionDenied Denial | VerificationFailed | UnexpectedError BS.ByteString deriving (Show, Eq, Ord) -- | The result of subscribing to a topic successfully, including -- when, and in how many seconds, the subscription expires. This value -- is ultimately decided by the hub, as per the WebSub specification. data SubscribeResult = SubscribeResult { topic :: Topic , expires :: UTCTime , leaseSeconds :: Int } deriving (Show, Eq, Ord) -- | A Client sends subscription requests to hubs, and extracts valid -- 'Hub' values from 'Topic' HTTP resource headers. class Client c where requestSubscription :: c -> Hub -> SubscriptionRequest CallbackURI -> ExceptT SubscribeError IO () getHubLinks :: c -> Topic -> IO [Hub] -- | A callback function, returning an 'IO' action, is evaluated when -- the content is distributed for the corresponding subscription. type ContentDistributionCallback = ContentDistribution () -> IO () -- | A pending subscription, i.e. on that has not been denied or -- verified yet. data Pending = Pending (SubscriptionRequest ContentDistributionCallback) (MVar (Either SubscribeError Subscription)) -- | A subscription that has been verified, and that is considered -- active. data Subscription = Subscription (SubscriptionRequest ContentDistributionCallback) SubscribeResult -- | The 'Subscriptions' structure holds all data needed to request -- new subscriptions, and to distribute content for existing -- subscriptions. This data structure is the center of the -- "Subscriptions" module. data Subscriptions c = Subscriptions { baseUri :: URI , client :: c , pending :: MVar (HashMap SubscriptionId Pending) , active :: MVar (HashMap SubscriptionId Subscription) } -- | A 'Subscriptions' value is itself a 'Client', by proxying the -- underlying 'Client'. instance Client c => Client (Subscriptions c) where requestSubscription = requestSubscription . client getHubLinks = getHubLinks . client -- | Create a 'Subscriptions' value using a base 'URI' and a 'Client'. newSubscriptions :: URI -> c -> IO (Subscriptions c) newSubscriptions baseUri client = Subscriptions baseUri client <$> newMVar HM.empty <*> newMVar HM.empty -- Generates a new random subscription ID string. randomIdStr :: IO String randomIdStr = do gen <- newStdGen -- TODO: Improve this? return (take 32 (randomRs ('a','z') gen)) createPending :: Subscriptions c -> SubscriptionId -> SubscriptionRequest ContentDistributionCallback -> ExceptT SubscribeError IO () createPending subscriptions subscriptionId req = do ready <- lift newEmptyMVar lift $ modifyMVar_ (pending subscriptions) (return . HM.insert subscriptionId (Pending req ready)) activate :: Subscriptions c -> SubscriptionId -> Subscription -> IO () activate subscriptions subscriptionId subscription = modifyMVar_ (active subscriptions) (return . HM.insert subscriptionId subscription) findPendingSubscription :: Subscriptions c -> SubscriptionId -> IO (Maybe Pending) findPendingSubscription subscriptions subscriptionId = HM.lookup subscriptionId <$> readMVar (pending subscriptions) findActiveSubscription :: Subscriptions c -> SubscriptionId -> IO (Maybe Subscription) findActiveSubscription subscriptions subscriptionId = HM.lookup subscriptionId <$> readMVar (active subscriptions) subscribe :: Client c => Subscriptions c -> Hub -> SubscriptionRequest ContentDistributionCallback -> IO (Either SubscribeError SubscriptionId) subscribe subscriptions hub req = runExceptT $ do idStr <- lift randomIdStr let base = baseUri subscriptions callbackUri = CallbackURI (base {uriPath = uriPath base ++ "/" ++ idStr}) subscriptionId = SubscriptionId (C.pack idStr) -- First create a pending subscription. createPending subscriptions subscriptionId req -- Then request the subscription from the hub. The hub might -- synchronously validate and verify the subscription, thus the -- subscription has to be created and added as pending before. requestSubscription (client subscriptions) hub $ req {callback = callbackUri} return subscriptionId awaitActiveSubscription :: Client c => Subscriptions c -> SubscriptionId -> IO (Either SubscribeError SubscribeResult) awaitActiveSubscription subscriptions subscriptionId = runExceptT $ do Pending _ pendingResult <- do pending <- lift (findPendingSubscription subscriptions subscriptionId) maybe (throwError (UnexpectedError "Pending subscription not found.")) return pending Subscription req res <- ExceptT (readMVar pendingResult) lift $ removePending subscriptions subscriptionId return res removePending :: Subscriptions c -> SubscriptionId -> IO () removePending subscriptions subscriptionId = modifyMVar_ (pending subscriptions) (return . HM.delete subscriptionId) deny :: Subscriptions c -> SubscriptionId -> Denial -> IO Bool deny subscriptions subscriptionId denial = findPendingSubscription subscriptions subscriptionId >>= \case Just (Pending _ result) -> putMVar result (Left (SubscriptionDenied denial)) *> return True Nothing -> return False verify :: Subscriptions c -> SubscriptionId -> VerificationRequest -> IO Bool verify subscriptions subscriptionId verReq@VerificationRequest { topic = verTopic , leaseSeconds = verLeaseSeconds } = findPendingSubscription subscriptions subscriptionId >>= \case Just (Pending subReq@SubscriptionRequest { topic = subTopic , leaseSeconds = subLeaseSeconds , callback } result) | verTopic == subTopic -> do now <- getCurrentTime let seconds = fromMaybe subLeaseSeconds verLeaseSeconds expires = fromIntegral seconds `addUTCTime` now sub = Subscription subReq SubscribeResult {topic = verTopic, expires = expires, leaseSeconds = seconds} activate subscriptions subscriptionId sub putMVar result (Right sub) return True | otherwise -> do putMVar result (Left VerificationFailed) return False Nothing -> return False distributeContent :: Subscriptions c -> SubscriptionId -> ContentDistribution () -> IO Bool distributeContent subscriptions subscriptionId distribution = findActiveSubscription subscriptions subscriptionId >>= \case Just (Subscription SubscriptionRequest {callback, secret = Nothing} _) -> callback distribution *> return True _ -> return False isValidDigest :: Secret -> BS.ByteString -> ContentDigest -> Bool isValidDigest secret body digest = case (digest' secret digest body, Base16.decode (signature digest)) of (Just expected, (fromHub, rest)) | BS.null rest -> expected `constEq` fromHub _ -> False where digest' :: Secret -> ContentDigest -> BS.ByteString -> Maybe BS.ByteString digest' (Secret secret) ContentDigest {method} body | method == "sha1" = Just (convert (hmac secret body :: HMAC SHA1)) | method == "sha256" = Just (convert (hmac secret body :: HMAC SHA256)) | method == "sha384" = Just (convert (hmac secret body :: HMAC SHA384)) | method == "sha512" = Just (convert (hmac secret body :: HMAC SHA512)) | otherwise = Nothing distributeContentAuthenticated :: Subscriptions c -> SubscriptionId -> ContentDistribution ContentDigest -> IO Bool distributeContentAuthenticated subscriptions subscriptionId distribution = findActiveSubscription subscriptions subscriptionId >>= \case Just (Subscription req _) -> distributeReq req Nothing -> return False where distributeReq :: SubscriptionRequest ContentDistributionCallback -> IO Bool distributeReq SubscriptionRequest {callback, secret} = do let shouldDistribute = case (secret, distribution) of (Just secret, ContentDistribution {body, digest}) -> isValidDigest secret body digest _ -> True when shouldDistribute (callback distribution {digest = ()}) return shouldDistribute
owickstrom/websub
src/Network/HTTP/WebSub/Subscriber.hs
mpl-2.0
10,006
0
17
2,320
2,231
1,143
1,088
215
3
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.DFAReporting -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Manages your DoubleClick Campaign Manager ad campaigns and reports. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> module Network.Google.DFAReporting ( -- * Service Configuration dFAReportingService -- * OAuth Scopes , dFAReportingScope , ddmconversionsScope , dfatraffickingScope -- * API Declaration , DFAReportingAPI -- * Resources -- ** dfareporting.accountActiveAdSummaries.get , module Network.Google.Resource.DFAReporting.AccountActiveAdSummaries.Get -- ** dfareporting.accountPermissionGroups.get , module Network.Google.Resource.DFAReporting.AccountPermissionGroups.Get -- ** dfareporting.accountPermissionGroups.list , module Network.Google.Resource.DFAReporting.AccountPermissionGroups.List -- ** dfareporting.accountPermissions.get , module Network.Google.Resource.DFAReporting.AccountPermissions.Get -- ** dfareporting.accountPermissions.list , module Network.Google.Resource.DFAReporting.AccountPermissions.List -- ** dfareporting.accountUserProfiles.get , module Network.Google.Resource.DFAReporting.AccountUserProFiles.Get -- ** dfareporting.accountUserProfiles.insert , module Network.Google.Resource.DFAReporting.AccountUserProFiles.Insert -- ** dfareporting.accountUserProfiles.list , module Network.Google.Resource.DFAReporting.AccountUserProFiles.List -- ** dfareporting.accountUserProfiles.patch , module Network.Google.Resource.DFAReporting.AccountUserProFiles.Patch -- ** dfareporting.accountUserProfiles.update , module Network.Google.Resource.DFAReporting.AccountUserProFiles.Update -- ** dfareporting.accounts.get , module Network.Google.Resource.DFAReporting.Accounts.Get -- ** dfareporting.accounts.list , module Network.Google.Resource.DFAReporting.Accounts.List -- ** dfareporting.accounts.patch , module Network.Google.Resource.DFAReporting.Accounts.Patch -- ** dfareporting.accounts.update , module Network.Google.Resource.DFAReporting.Accounts.Update -- ** dfareporting.ads.get , module Network.Google.Resource.DFAReporting.Ads.Get -- ** dfareporting.ads.insert , module Network.Google.Resource.DFAReporting.Ads.Insert -- ** dfareporting.ads.list , module Network.Google.Resource.DFAReporting.Ads.List -- ** dfareporting.ads.patch , module Network.Google.Resource.DFAReporting.Ads.Patch -- ** dfareporting.ads.update , module Network.Google.Resource.DFAReporting.Ads.Update -- ** dfareporting.advertiserGroups.delete , module Network.Google.Resource.DFAReporting.AdvertiserGroups.Delete -- ** dfareporting.advertiserGroups.get , module Network.Google.Resource.DFAReporting.AdvertiserGroups.Get -- ** dfareporting.advertiserGroups.insert , module Network.Google.Resource.DFAReporting.AdvertiserGroups.Insert -- ** dfareporting.advertiserGroups.list , module Network.Google.Resource.DFAReporting.AdvertiserGroups.List -- ** dfareporting.advertiserGroups.patch , module Network.Google.Resource.DFAReporting.AdvertiserGroups.Patch -- ** dfareporting.advertiserGroups.update , module Network.Google.Resource.DFAReporting.AdvertiserGroups.Update -- ** dfareporting.advertisers.get , module Network.Google.Resource.DFAReporting.Advertisers.Get -- ** dfareporting.advertisers.insert , module Network.Google.Resource.DFAReporting.Advertisers.Insert -- ** dfareporting.advertisers.list , module Network.Google.Resource.DFAReporting.Advertisers.List -- ** dfareporting.advertisers.patch , module Network.Google.Resource.DFAReporting.Advertisers.Patch -- ** dfareporting.advertisers.update , module Network.Google.Resource.DFAReporting.Advertisers.Update -- ** dfareporting.browsers.list , module Network.Google.Resource.DFAReporting.Browsers.List -- ** dfareporting.campaignCreativeAssociations.insert , module Network.Google.Resource.DFAReporting.CampaignCreativeAssociations.Insert -- ** dfareporting.campaignCreativeAssociations.list , module Network.Google.Resource.DFAReporting.CampaignCreativeAssociations.List -- ** dfareporting.campaigns.get , module Network.Google.Resource.DFAReporting.Campaigns.Get -- ** dfareporting.campaigns.insert , module Network.Google.Resource.DFAReporting.Campaigns.Insert -- ** dfareporting.campaigns.list , module Network.Google.Resource.DFAReporting.Campaigns.List -- ** dfareporting.campaigns.patch , module Network.Google.Resource.DFAReporting.Campaigns.Patch -- ** dfareporting.campaigns.update , module Network.Google.Resource.DFAReporting.Campaigns.Update -- ** dfareporting.changeLogs.get , module Network.Google.Resource.DFAReporting.ChangeLogs.Get -- ** dfareporting.changeLogs.list , module Network.Google.Resource.DFAReporting.ChangeLogs.List -- ** dfareporting.cities.list , module Network.Google.Resource.DFAReporting.Cities.List -- ** dfareporting.connectionTypes.get , module Network.Google.Resource.DFAReporting.ConnectionTypes.Get -- ** dfareporting.connectionTypes.list , module Network.Google.Resource.DFAReporting.ConnectionTypes.List -- ** dfareporting.contentCategories.delete , module Network.Google.Resource.DFAReporting.ContentCategories.Delete -- ** dfareporting.contentCategories.get , module Network.Google.Resource.DFAReporting.ContentCategories.Get -- ** dfareporting.contentCategories.insert , module Network.Google.Resource.DFAReporting.ContentCategories.Insert -- ** dfareporting.contentCategories.list , module Network.Google.Resource.DFAReporting.ContentCategories.List -- ** dfareporting.contentCategories.patch , module Network.Google.Resource.DFAReporting.ContentCategories.Patch -- ** dfareporting.contentCategories.update , module Network.Google.Resource.DFAReporting.ContentCategories.Update -- ** dfareporting.conversions.batchinsert , module Network.Google.Resource.DFAReporting.Conversions.Batchinsert -- ** dfareporting.countries.get , module Network.Google.Resource.DFAReporting.Countries.Get -- ** dfareporting.countries.list , module Network.Google.Resource.DFAReporting.Countries.List -- ** dfareporting.creativeAssets.insert , module Network.Google.Resource.DFAReporting.CreativeAssets.Insert -- ** dfareporting.creativeFieldValues.delete , module Network.Google.Resource.DFAReporting.CreativeFieldValues.Delete -- ** dfareporting.creativeFieldValues.get , module Network.Google.Resource.DFAReporting.CreativeFieldValues.Get -- ** dfareporting.creativeFieldValues.insert , module Network.Google.Resource.DFAReporting.CreativeFieldValues.Insert -- ** dfareporting.creativeFieldValues.list , module Network.Google.Resource.DFAReporting.CreativeFieldValues.List -- ** dfareporting.creativeFieldValues.patch , module Network.Google.Resource.DFAReporting.CreativeFieldValues.Patch -- ** dfareporting.creativeFieldValues.update , module Network.Google.Resource.DFAReporting.CreativeFieldValues.Update -- ** dfareporting.creativeFields.delete , module Network.Google.Resource.DFAReporting.CreativeFields.Delete -- ** dfareporting.creativeFields.get , module Network.Google.Resource.DFAReporting.CreativeFields.Get -- ** dfareporting.creativeFields.insert , module Network.Google.Resource.DFAReporting.CreativeFields.Insert -- ** dfareporting.creativeFields.list , module Network.Google.Resource.DFAReporting.CreativeFields.List -- ** dfareporting.creativeFields.patch , module Network.Google.Resource.DFAReporting.CreativeFields.Patch -- ** dfareporting.creativeFields.update , module Network.Google.Resource.DFAReporting.CreativeFields.Update -- ** dfareporting.creativeGroups.get , module Network.Google.Resource.DFAReporting.CreativeGroups.Get -- ** dfareporting.creativeGroups.insert , module Network.Google.Resource.DFAReporting.CreativeGroups.Insert -- ** dfareporting.creativeGroups.list , module Network.Google.Resource.DFAReporting.CreativeGroups.List -- ** dfareporting.creativeGroups.patch , module Network.Google.Resource.DFAReporting.CreativeGroups.Patch -- ** dfareporting.creativeGroups.update , module Network.Google.Resource.DFAReporting.CreativeGroups.Update -- ** dfareporting.creatives.get , module Network.Google.Resource.DFAReporting.Creatives.Get -- ** dfareporting.creatives.insert , module Network.Google.Resource.DFAReporting.Creatives.Insert -- ** dfareporting.creatives.list , module Network.Google.Resource.DFAReporting.Creatives.List -- ** dfareporting.creatives.patch , module Network.Google.Resource.DFAReporting.Creatives.Patch -- ** dfareporting.creatives.update , module Network.Google.Resource.DFAReporting.Creatives.Update -- ** dfareporting.dimensionValues.query , module Network.Google.Resource.DFAReporting.DimensionValues.Query -- ** dfareporting.directorySiteContacts.get , module Network.Google.Resource.DFAReporting.DirectorySiteContacts.Get -- ** dfareporting.directorySiteContacts.list , module Network.Google.Resource.DFAReporting.DirectorySiteContacts.List -- ** dfareporting.directorySites.get , module Network.Google.Resource.DFAReporting.DirectorySites.Get -- ** dfareporting.directorySites.insert , module Network.Google.Resource.DFAReporting.DirectorySites.Insert -- ** dfareporting.directorySites.list , module Network.Google.Resource.DFAReporting.DirectorySites.List -- ** dfareporting.dynamicTargetingKeys.delete , module Network.Google.Resource.DFAReporting.DynamicTargetingKeys.Delete -- ** dfareporting.dynamicTargetingKeys.insert , module Network.Google.Resource.DFAReporting.DynamicTargetingKeys.Insert -- ** dfareporting.dynamicTargetingKeys.list , module Network.Google.Resource.DFAReporting.DynamicTargetingKeys.List -- ** dfareporting.eventTags.delete , module Network.Google.Resource.DFAReporting.EventTags.Delete -- ** dfareporting.eventTags.get , module Network.Google.Resource.DFAReporting.EventTags.Get -- ** dfareporting.eventTags.insert , module Network.Google.Resource.DFAReporting.EventTags.Insert -- ** dfareporting.eventTags.list , module Network.Google.Resource.DFAReporting.EventTags.List -- ** dfareporting.eventTags.patch , module Network.Google.Resource.DFAReporting.EventTags.Patch -- ** dfareporting.eventTags.update , module Network.Google.Resource.DFAReporting.EventTags.Update -- ** dfareporting.files.get , module Network.Google.Resource.DFAReporting.Files.Get -- ** dfareporting.files.list , module Network.Google.Resource.DFAReporting.Files.List -- ** dfareporting.floodlightActivities.delete , module Network.Google.Resource.DFAReporting.FloodlightActivities.Delete -- ** dfareporting.floodlightActivities.generatetag , module Network.Google.Resource.DFAReporting.FloodlightActivities.Generatetag -- ** dfareporting.floodlightActivities.get , module Network.Google.Resource.DFAReporting.FloodlightActivities.Get -- ** dfareporting.floodlightActivities.insert , module Network.Google.Resource.DFAReporting.FloodlightActivities.Insert -- ** dfareporting.floodlightActivities.list , module Network.Google.Resource.DFAReporting.FloodlightActivities.List -- ** dfareporting.floodlightActivities.patch , module Network.Google.Resource.DFAReporting.FloodlightActivities.Patch -- ** dfareporting.floodlightActivities.update , module Network.Google.Resource.DFAReporting.FloodlightActivities.Update -- ** dfareporting.floodlightActivityGroups.get , module Network.Google.Resource.DFAReporting.FloodlightActivityGroups.Get -- ** dfareporting.floodlightActivityGroups.insert , module Network.Google.Resource.DFAReporting.FloodlightActivityGroups.Insert -- ** dfareporting.floodlightActivityGroups.list , module Network.Google.Resource.DFAReporting.FloodlightActivityGroups.List -- ** dfareporting.floodlightActivityGroups.patch , module Network.Google.Resource.DFAReporting.FloodlightActivityGroups.Patch -- ** dfareporting.floodlightActivityGroups.update , module Network.Google.Resource.DFAReporting.FloodlightActivityGroups.Update -- ** dfareporting.floodlightConfigurations.get , module Network.Google.Resource.DFAReporting.FloodlightConfigurations.Get -- ** dfareporting.floodlightConfigurations.list , module Network.Google.Resource.DFAReporting.FloodlightConfigurations.List -- ** dfareporting.floodlightConfigurations.patch , module Network.Google.Resource.DFAReporting.FloodlightConfigurations.Patch -- ** dfareporting.floodlightConfigurations.update , module Network.Google.Resource.DFAReporting.FloodlightConfigurations.Update -- ** dfareporting.inventoryItems.get , module Network.Google.Resource.DFAReporting.InventoryItems.Get -- ** dfareporting.inventoryItems.list , module Network.Google.Resource.DFAReporting.InventoryItems.List -- ** dfareporting.landingPages.delete , module Network.Google.Resource.DFAReporting.LandingPages.Delete -- ** dfareporting.landingPages.get , module Network.Google.Resource.DFAReporting.LandingPages.Get -- ** dfareporting.landingPages.insert , module Network.Google.Resource.DFAReporting.LandingPages.Insert -- ** dfareporting.landingPages.list , module Network.Google.Resource.DFAReporting.LandingPages.List -- ** dfareporting.landingPages.patch , module Network.Google.Resource.DFAReporting.LandingPages.Patch -- ** dfareporting.landingPages.update , module Network.Google.Resource.DFAReporting.LandingPages.Update -- ** dfareporting.languages.list , module Network.Google.Resource.DFAReporting.Languages.List -- ** dfareporting.metros.list , module Network.Google.Resource.DFAReporting.Metros.List -- ** dfareporting.mobileCarriers.get , module Network.Google.Resource.DFAReporting.MobileCarriers.Get -- ** dfareporting.mobileCarriers.list , module Network.Google.Resource.DFAReporting.MobileCarriers.List -- ** dfareporting.operatingSystemVersions.get , module Network.Google.Resource.DFAReporting.OperatingSystemVersions.Get -- ** dfareporting.operatingSystemVersions.list , module Network.Google.Resource.DFAReporting.OperatingSystemVersions.List -- ** dfareporting.operatingSystems.get , module Network.Google.Resource.DFAReporting.OperatingSystems.Get -- ** dfareporting.operatingSystems.list , module Network.Google.Resource.DFAReporting.OperatingSystems.List -- ** dfareporting.orderDocuments.get , module Network.Google.Resource.DFAReporting.OrderDocuments.Get -- ** dfareporting.orderDocuments.list , module Network.Google.Resource.DFAReporting.OrderDocuments.List -- ** dfareporting.orders.get , module Network.Google.Resource.DFAReporting.Orders.Get -- ** dfareporting.orders.list , module Network.Google.Resource.DFAReporting.Orders.List -- ** dfareporting.placementGroups.get , module Network.Google.Resource.DFAReporting.PlacementGroups.Get -- ** dfareporting.placementGroups.insert , module Network.Google.Resource.DFAReporting.PlacementGroups.Insert -- ** dfareporting.placementGroups.list , module Network.Google.Resource.DFAReporting.PlacementGroups.List -- ** dfareporting.placementGroups.patch , module Network.Google.Resource.DFAReporting.PlacementGroups.Patch -- ** dfareporting.placementGroups.update , module Network.Google.Resource.DFAReporting.PlacementGroups.Update -- ** dfareporting.placementStrategies.delete , module Network.Google.Resource.DFAReporting.PlacementStrategies.Delete -- ** dfareporting.placementStrategies.get , module Network.Google.Resource.DFAReporting.PlacementStrategies.Get -- ** dfareporting.placementStrategies.insert , module Network.Google.Resource.DFAReporting.PlacementStrategies.Insert -- ** dfareporting.placementStrategies.list , module Network.Google.Resource.DFAReporting.PlacementStrategies.List -- ** dfareporting.placementStrategies.patch , module Network.Google.Resource.DFAReporting.PlacementStrategies.Patch -- ** dfareporting.placementStrategies.update , module Network.Google.Resource.DFAReporting.PlacementStrategies.Update -- ** dfareporting.placements.generatetags , module Network.Google.Resource.DFAReporting.Placements.Generatetags -- ** dfareporting.placements.get , module Network.Google.Resource.DFAReporting.Placements.Get -- ** dfareporting.placements.insert , module Network.Google.Resource.DFAReporting.Placements.Insert -- ** dfareporting.placements.list , module Network.Google.Resource.DFAReporting.Placements.List -- ** dfareporting.placements.patch , module Network.Google.Resource.DFAReporting.Placements.Patch -- ** dfareporting.placements.update , module Network.Google.Resource.DFAReporting.Placements.Update -- ** dfareporting.platformTypes.get , module Network.Google.Resource.DFAReporting.PlatformTypes.Get -- ** dfareporting.platformTypes.list , module Network.Google.Resource.DFAReporting.PlatformTypes.List -- ** dfareporting.postalCodes.get , module Network.Google.Resource.DFAReporting.PostalCodes.Get -- ** dfareporting.postalCodes.list , module Network.Google.Resource.DFAReporting.PostalCodes.List -- ** dfareporting.projects.get , module Network.Google.Resource.DFAReporting.Projects.Get -- ** dfareporting.projects.list , module Network.Google.Resource.DFAReporting.Projects.List -- ** dfareporting.regions.list , module Network.Google.Resource.DFAReporting.Regions.List -- ** dfareporting.remarketingListShares.get , module Network.Google.Resource.DFAReporting.RemarketingListShares.Get -- ** dfareporting.remarketingListShares.patch , module Network.Google.Resource.DFAReporting.RemarketingListShares.Patch -- ** dfareporting.remarketingListShares.update , module Network.Google.Resource.DFAReporting.RemarketingListShares.Update -- ** dfareporting.remarketingLists.get , module Network.Google.Resource.DFAReporting.RemarketingLists.Get -- ** dfareporting.remarketingLists.insert , module Network.Google.Resource.DFAReporting.RemarketingLists.Insert -- ** dfareporting.remarketingLists.list , module Network.Google.Resource.DFAReporting.RemarketingLists.List -- ** dfareporting.remarketingLists.patch , module Network.Google.Resource.DFAReporting.RemarketingLists.Patch -- ** dfareporting.remarketingLists.update , module Network.Google.Resource.DFAReporting.RemarketingLists.Update -- ** dfareporting.reports.compatibleFields.query , module Network.Google.Resource.DFAReporting.Reports.CompatibleFields.Query -- ** dfareporting.reports.delete , module Network.Google.Resource.DFAReporting.Reports.Delete -- ** dfareporting.reports.files.get , module Network.Google.Resource.DFAReporting.Reports.Files.Get -- ** dfareporting.reports.files.list , module Network.Google.Resource.DFAReporting.Reports.Files.List -- ** dfareporting.reports.get , module Network.Google.Resource.DFAReporting.Reports.Get -- ** dfareporting.reports.insert , module Network.Google.Resource.DFAReporting.Reports.Insert -- ** dfareporting.reports.list , module Network.Google.Resource.DFAReporting.Reports.List -- ** dfareporting.reports.patch , module Network.Google.Resource.DFAReporting.Reports.Patch -- ** dfareporting.reports.run , module Network.Google.Resource.DFAReporting.Reports.Run -- ** dfareporting.reports.update , module Network.Google.Resource.DFAReporting.Reports.Update -- ** dfareporting.sites.get , module Network.Google.Resource.DFAReporting.Sites.Get -- ** dfareporting.sites.insert , module Network.Google.Resource.DFAReporting.Sites.Insert -- ** dfareporting.sites.list , module Network.Google.Resource.DFAReporting.Sites.List -- ** dfareporting.sites.patch , module Network.Google.Resource.DFAReporting.Sites.Patch -- ** dfareporting.sites.update , module Network.Google.Resource.DFAReporting.Sites.Update -- ** dfareporting.sizes.get , module Network.Google.Resource.DFAReporting.Sizes.Get -- ** dfareporting.sizes.insert , module Network.Google.Resource.DFAReporting.Sizes.Insert -- ** dfareporting.sizes.list , module Network.Google.Resource.DFAReporting.Sizes.List -- ** dfareporting.subaccounts.get , module Network.Google.Resource.DFAReporting.SubAccounts.Get -- ** dfareporting.subaccounts.insert , module Network.Google.Resource.DFAReporting.SubAccounts.Insert -- ** dfareporting.subaccounts.list , module Network.Google.Resource.DFAReporting.SubAccounts.List -- ** dfareporting.subaccounts.patch , module Network.Google.Resource.DFAReporting.SubAccounts.Patch -- ** dfareporting.subaccounts.update , module Network.Google.Resource.DFAReporting.SubAccounts.Update -- ** dfareporting.targetableRemarketingLists.get , module Network.Google.Resource.DFAReporting.TargetableRemarketingLists.Get -- ** dfareporting.targetableRemarketingLists.list , module Network.Google.Resource.DFAReporting.TargetableRemarketingLists.List -- ** dfareporting.targetingTemplates.get , module Network.Google.Resource.DFAReporting.TargetingTemplates.Get -- ** dfareporting.targetingTemplates.insert , module Network.Google.Resource.DFAReporting.TargetingTemplates.Insert -- ** dfareporting.targetingTemplates.list , module Network.Google.Resource.DFAReporting.TargetingTemplates.List -- ** dfareporting.targetingTemplates.patch , module Network.Google.Resource.DFAReporting.TargetingTemplates.Patch -- ** dfareporting.targetingTemplates.update , module Network.Google.Resource.DFAReporting.TargetingTemplates.Update -- ** dfareporting.userProfiles.get , module Network.Google.Resource.DFAReporting.UserProFiles.Get -- ** dfareporting.userProfiles.list , module Network.Google.Resource.DFAReporting.UserProFiles.List -- ** dfareporting.userRolePermissionGroups.get , module Network.Google.Resource.DFAReporting.UserRolePermissionGroups.Get -- ** dfareporting.userRolePermissionGroups.list , module Network.Google.Resource.DFAReporting.UserRolePermissionGroups.List -- ** dfareporting.userRolePermissions.get , module Network.Google.Resource.DFAReporting.UserRolePermissions.Get -- ** dfareporting.userRolePermissions.list , module Network.Google.Resource.DFAReporting.UserRolePermissions.List -- ** dfareporting.userRoles.delete , module Network.Google.Resource.DFAReporting.UserRoles.Delete -- ** dfareporting.userRoles.get , module Network.Google.Resource.DFAReporting.UserRoles.Get -- ** dfareporting.userRoles.insert , module Network.Google.Resource.DFAReporting.UserRoles.Insert -- ** dfareporting.userRoles.list , module Network.Google.Resource.DFAReporting.UserRoles.List -- ** dfareporting.userRoles.patch , module Network.Google.Resource.DFAReporting.UserRoles.Patch -- ** dfareporting.userRoles.update , module Network.Google.Resource.DFAReporting.UserRoles.Update -- ** dfareporting.videoFormats.get , module Network.Google.Resource.DFAReporting.VideoFormats.Get -- ** dfareporting.videoFormats.list , module Network.Google.Resource.DFAReporting.VideoFormats.List -- * Types -- ** VideoOffSet , VideoOffSet , videoOffSet , vosOffSetPercentage , vosOffSetSeconds -- ** PlacementsListSortOrder , PlacementsListSortOrder (..) -- ** DateRangeRelativeDateRange , DateRangeRelativeDateRange (..) -- ** AdvertisersListSortField , AdvertisersListSortField (..) -- ** CreativeFieldsListSortOrder , CreativeFieldsListSortOrder (..) -- ** FileList , FileList , fileList , flEtag , flNextPageToken , flKind , flItems -- ** TargetingTemplatesListSortOrder , TargetingTemplatesListSortOrder (..) -- ** OptimizationActivity , OptimizationActivity , optimizationActivity , oaWeight , oaFloodlightActivityId , oaFloodlightActivityIdDimensionValue -- ** ListPopulationClause , ListPopulationClause , listPopulationClause , lpcTerms -- ** CreativeCustomEvent , CreativeCustomEvent , creativeCustomEvent , cceAdvertiserCustomEventId , cceAdvertiserCustomEventType , cceAdvertiserCustomEventName , cceExitURL , cceTargetType , ccePopupWindowProperties , cceVideoReportingId , cceId , cceArtworkLabel , cceArtworkType -- ** ClickTag , ClickTag , clickTag , ctValue , ctName , ctEventName -- ** CampaignsListResponse , CampaignsListResponse , campaignsListResponse , clrNextPageToken , clrCampaigns , clrKind -- ** GeoTargeting , GeoTargeting , geoTargeting , gtRegions , gtCountries , gtCities , gtMetros , gtExcludeCountries , gtPostalCodes -- ** UserRolesListSortField , UserRolesListSortField (..) -- ** VideoSettings , VideoSettings , videoSettings , vsKind , vsCompanionSettings , vsTranscodeSettings , vsSkippableSettings -- ** ReachReportCompatibleFields , ReachReportCompatibleFields , reachReportCompatibleFields , rrcfMetrics , rrcfReachByFrequencyMetrics , rrcfKind , rrcfDimensionFilters , rrcfPivotedActivityMetrics , rrcfDimensions -- ** Browser , Browser , browser , bMinorVersion , bKind , bBrowserVersionId , bMajorVersion , bName , bDartId -- ** FloodlightActivityTagFormat , FloodlightActivityTagFormat (..) -- ** OrderDocumentsListSortOrder , OrderDocumentsListSortOrder (..) -- ** CreativeGroupAssignment , CreativeGroupAssignment , creativeGroupAssignment , cgaCreativeGroupNumber , cgaCreativeGroupId -- ** CreativeAssetRole , CreativeAssetRole (..) -- ** DynamicTargetingKeysListObjectType , DynamicTargetingKeysListObjectType (..) -- ** RecipientDeliveryType , RecipientDeliveryType (..) -- ** ThirdPartyTrackingURLThirdPartyURLType , ThirdPartyTrackingURLThirdPartyURLType (..) -- ** DirectorySiteSettings , DirectorySiteSettings , directorySiteSettings , dssInterstitialPlacementAccepted , dssDfpSettings , dssVerificationTagOptOut , dssActiveViewOptOut , dssVideoActiveViewOptOut , dssInstreamVideoPlacementAccepted , dssNielsenOCROptOut -- ** TargetableRemarketingListsListSortOrder , TargetableRemarketingListsListSortOrder (..) -- ** CreativeAssetPositionLeftUnit , CreativeAssetPositionLeftUnit (..) -- ** PricingScheduleCapCostOption , PricingScheduleCapCostOption (..) -- ** ListPopulationRule , ListPopulationRule , listPopulationRule , lprFloodlightActivityName , lprFloodlightActivityId , lprListPopulationClauses -- ** UserRolePermissionAvailability , UserRolePermissionAvailability (..) -- ** PlacementVpaidAdapterChoice , PlacementVpaidAdapterChoice (..) -- ** DirectorySiteContactAssignmentVisibility , DirectorySiteContactAssignmentVisibility (..) -- ** SizesListResponse , SizesListResponse , sizesListResponse , slrKind , slrSizes -- ** PlacementCompatibility , PlacementCompatibility (..) -- ** CreativeRotation , CreativeRotation , creativeRotation , crWeightCalculationStrategy , crCreativeAssignments , crCreativeOptimizationConfigurationId , crType -- ** TechnologyTargeting , TechnologyTargeting , technologyTargeting , ttMobileCarriers , ttOperatingSystemVersions , ttPlatformTypes , ttBrowsers , ttConnectionTypes , ttOperatingSystems -- ** ListPopulationTermOperator , ListPopulationTermOperator (..) -- ** PlacementsListPaymentSource , PlacementsListPaymentSource (..) -- ** InventoryItem , InventoryItem , inventoryItem , iiPlacementStrategyId , iiEstimatedClickThroughRate , iiPricing , iiKind , iiAdvertiserId , iiRfpId , iiContentCategoryId , iiInPlan , iiAccountId , iiName , iiAdSlots , iiNegotiationChannelId , iiLastModifiedInfo , iiId , iiEstimatedConversionRate , iiProjectId , iiSubAccountId , iiType , iiOrderId , iiSiteId -- ** ProjectsListResponse , ProjectsListResponse , projectsListResponse , plrNextPageToken , plrKind , plrProjects -- ** AdsListResponse , AdsListResponse , adsListResponse , alrNextPageToken , alrKind , alrAds -- ** ReportsListSortField , ReportsListSortField (..) -- ** AdSlotCompatibility , AdSlotCompatibility (..) -- ** ListPopulationTerm , ListPopulationTerm , listPopulationTerm , lptOperator , lptValue , lptVariableFriendlyName , lptNegation , lptVariableName , lptRemarketingListId , lptType , lptContains -- ** TagSettings , TagSettings , tagSettings , tsDynamicTagEnabled , tsImageTagEnabled -- ** SubAccountsListResponse , SubAccountsListResponse , subAccountsListResponse , salrNextPageToken , salrKind , salrSubAccounts -- ** CampaignsListSortField , CampaignsListSortField (..) -- ** DirectorySiteContact , DirectorySiteContact , directorySiteContact , dscEmail , dscPhone , dscLastName , dscKind , dscAddress , dscRole , dscFirstName , dscId , dscTitle , dscType -- ** RegionsListResponse , RegionsListResponse , regionsListResponse , rlrKind , rlrRegions -- ** FloodlightActivityDynamicTag , FloodlightActivityDynamicTag , floodlightActivityDynamicTag , fadtTag , fadtName , fadtId -- ** VideoFormat , VideoFormat , videoFormat , vfKind , vfFileType , vfResolution , vfTargetBitRate , vfId -- ** AccountUserProFileTraffickerType , AccountUserProFileTraffickerType (..) -- ** DirectorySite , DirectorySite , directorySite , dsCurrencyId , dsSettings , dsInterstitialTagFormats , dsKind , dsURL , dsIdDimensionValue , dsInpageTagFormats , dsActive , dsName , dsId , dsCountryId , dsContactAssignments , dsDescription , dsParentId -- ** CreativeAssetMetadataDetectedFeaturesItem , CreativeAssetMetadataDetectedFeaturesItem (..) -- ** ReportFloodlightCriteriaReportProperties , ReportFloodlightCriteriaReportProperties , reportFloodlightCriteriaReportProperties , rfcrpIncludeUnattributedIPConversions , rfcrpIncludeUnattributedCookieConversions , rfcrpIncludeAttributedIPConversions -- ** FloodlightActivityGroup , FloodlightActivityGroup , floodlightActivityGroup , fagTagString , fagFloodlightConfigurationId , fagKind , fagAdvertiserId , fagAdvertiserIdDimensionValue , fagIdDimensionValue , fagAccountId , fagName , fagId , fagSubAccountId , fagType , fagFloodlightConfigurationIdDimensionValue -- ** AdsListCompatibility , AdsListCompatibility (..) -- ** CrossDimensionReachReportCompatibleFields , CrossDimensionReachReportCompatibleFields , crossDimensionReachReportCompatibleFields , cdrrcfMetrics , cdrrcfBreakdown , cdrrcfKind , cdrrcfDimensionFilters , cdrrcfOverlapMetrics -- ** FsCommand , FsCommand , fsCommand , fcPositionOption , fcLeft , fcWindowHeight , fcWindowWidth , fcTop -- ** PlacementAssignment , PlacementAssignment , placementAssignment , paPlacementId , paPlacementIdDimensionValue , paActive , paSSLRequired -- ** CreativeFieldValue , CreativeFieldValue , creativeFieldValue , cfvKind , cfvValue , cfvId -- ** EventTagStatus , EventTagStatus (..) -- ** SitesListSortField , SitesListSortField (..) -- ** DimensionValueRequest , DimensionValueRequest , dimensionValueRequest , dvrKind , dvrEndDate , dvrFilters , dvrStartDate , dvrDimensionName -- ** EventTagsListEventTagTypes , EventTagsListEventTagTypes (..) -- ** FloodlightConfigurationsListResponse , FloodlightConfigurationsListResponse , floodlightConfigurationsListResponse , fclrKind , fclrFloodlightConfigurations -- ** FloodlightActivitiesListResponse , FloodlightActivitiesListResponse , floodlightActivitiesListResponse , falrNextPageToken , falrKind , falrFloodlightActivities -- ** FileStatus , FileStatus (..) -- ** CreativeCustomEventArtworkType , CreativeCustomEventArtworkType (..) -- ** CreativeFieldAssignment , CreativeFieldAssignment , creativeFieldAssignment , cfaCreativeFieldId , cfaCreativeFieldValueId -- ** AdvertiserGroup , AdvertiserGroup , advertiserGroup , agKind , agAccountId , agName , agId -- ** TagData , TagData , tagData , tdClickTag , tdFormat , tdCreativeId , tdAdId , tdImpressionTag -- ** DayPartTargeting , DayPartTargeting , dayPartTargeting , dptDaysOfWeek , dptHoursOfDay , dptUserLocalTime -- ** CreativeOptimizationConfiguration , CreativeOptimizationConfiguration , creativeOptimizationConfiguration , cocOptimizationModel , cocName , cocOptimizationActivitys , cocId -- ** ReportCriteria , ReportCriteria , reportCriteria , rcMetricNames , rcCustomRichMediaEvents , rcDimensionFilters , rcActivities , rcDateRange , rcDimensions -- ** FloodlightConfigurationNATuralSearchConversionAttributionOption , FloodlightConfigurationNATuralSearchConversionAttributionOption (..) -- ** PlacementStrategiesListResponse , PlacementStrategiesListResponse , placementStrategiesListResponse , pslrPlacementStrategies , pslrNextPageToken , pslrKind -- ** CreativeAssetArtworkType , CreativeAssetArtworkType (..) -- ** SubAccount , SubAccount , subAccount , saKind , saAvailablePermissionIds , saAccountId , saName , saId -- ** InventoryItemsListResponse , InventoryItemsListResponse , inventoryItemsListResponse , iilrInventoryItems , iilrNextPageToken , iilrKind -- ** CustomFloodlightVariableType , CustomFloodlightVariableType (..) -- ** Ad , Ad , ad , aTargetingTemplateId , aCreativeGroupAssignments , aGeoTargeting , aCreativeRotation , aTechnologyTargeting , aAudienceSegmentId , aDayPartTargeting , aSize , aStartTime , aKind , aClickThroughURLSuffixProperties , aCampaignIdDimensionValue , aAdvertiserId , aAdvertiserIdDimensionValue , aSSLCompliant , aCampaignId , aIdDimensionValue , aClickThroughURL , aDeliverySchedule , aEventTagOverrides , aActive , aAccountId , aName , aKeyValueTargetingExpression , aEndTime , aCreateInfo , aLastModifiedInfo , aId , aSSLRequired , aComments , aSubAccountId , aType , aRemarketingListExpression , aLanguageTargeting , aDynamicClickTracker , aCompatibility , aArchived , aDefaultClickThroughEventTagProperties , aPlacementAssignments -- ** ConversionErrorCode , ConversionErrorCode (..) -- ** FloodlightActivitiesListSortOrder , FloodlightActivitiesListSortOrder (..) -- ** Project , Project , project , pTargetClicks , pClientBillingCode , pTargetCpmNanos , pTargetConversions , pBudget , pKind , pAdvertiserId , pEndDate , pOverview , pTargetImpressions , pStartDate , pTargetCpcNanos , pAccountId , pName , pLastModifiedInfo , pId , pAudienceAgeGroup , pSubAccountId , pTargetCpmActiveViewNanos , pAudienceGender , pClientName , pTargetCpaNanos -- ** FileFormat , FileFormat (..) -- ** EncryptionInfoEncryptionEntityType , EncryptionInfoEncryptionEntityType (..) -- ** PricingSchedulePricingType , PricingSchedulePricingType (..) -- ** ReportFloodlightCriteria , ReportFloodlightCriteria , reportFloodlightCriteria , rfcReportProperties , rfcMetricNames , rfcCustomRichMediaEvents , rfcDimensionFilters , rfcDateRange , rfcFloodlightConfigId , rfcDimensions -- ** CreativeCustomEventTargetType , CreativeCustomEventTargetType (..) -- ** ReportsListScope , ReportsListScope (..) -- ** Size , Size , size , sHeight , sKind , sWidth , sIab , sId -- ** CreativeAssetDurationType , CreativeAssetDurationType (..) -- ** TargetableRemarketingListListSource , TargetableRemarketingListListSource (..) -- ** ObjectFilter , ObjectFilter , objectFilter , ofStatus , ofKind , ofObjectIds -- ** SkippableSetting , SkippableSetting , skippableSetting , ssSkipOffSet , ssProgressOffSet , ssKind , ssSkippable -- ** CreativeGroupsListSortField , CreativeGroupsListSortField (..) -- ** ReportsConfiguration , ReportsConfiguration , reportsConfiguration , rcExposureToConversionEnabled , rcReportGenerationTimeZoneId , rcLookbackConfiguration -- ** PricingSchedule , PricingSchedule , pricingSchedule , psTestingStartDate , psFloodlightActivityId , psEndDate , psDisregardOverdelivery , psStartDate , psCapCostOption , psPricingType , psPricingPeriods , psFlighted -- ** PostalCode , PostalCode , postalCode , pcKind , pcCode , pcCountryCode , pcId , pcCountryDartId -- ** AccountPermissionsListResponse , AccountPermissionsListResponse , accountPermissionsListResponse , aplrKind , aplrAccountPermissions -- ** Country , Country , country , cKind , cName , cCountryCode , cDartId , cSSLEnabled -- ** PlacementsListSortField , PlacementsListSortField (..) -- ** CreativeBackupImageFeaturesItem , CreativeBackupImageFeaturesItem (..) -- ** OperatingSystemVersionsListResponse , OperatingSystemVersionsListResponse , operatingSystemVersionsListResponse , osvlrKind , osvlrOperatingSystemVersions -- ** ClickThroughURLSuffixProperties , ClickThroughURLSuffixProperties , clickThroughURLSuffixProperties , ctuspOverrideInheritedSuffix , ctuspClickThroughURLSuffix -- ** AdvertisersListSortOrder , AdvertisersListSortOrder (..) -- ** TargetingTemplatesListSortField , TargetingTemplatesListSortField (..) -- ** CreativeFieldsListSortField , CreativeFieldsListSortField (..) -- ** Pricing , Pricing , pricing , priEndDate , priStartDate , priGroupType , priPricingType , priFlights , priCapCostType -- ** AudienceSegmentGroup , AudienceSegmentGroup , audienceSegmentGroup , asgAudienceSegments , asgName , asgId -- ** OperatingSystem , OperatingSystem , operatingSystem , osDesktop , osKind , osName , osMobile , osDartId -- ** Flight , Flight , flight , fRateOrCost , fEndDate , fStartDate , fUnits -- ** UserDefinedVariableConfigurationVariableType , UserDefinedVariableConfigurationVariableType (..) -- ** FsCommandPositionOption , FsCommandPositionOption (..) -- ** CitiesListResponse , CitiesListResponse , citiesListResponse , citKind , citCities -- ** Dimension , Dimension , dimension , dKind , dName -- ** ReportReachCriteria , ReportReachCriteria , reportReachCriteria , rrcReachByFrequencyMetricNames , rrcEnableAllDimensionCombinations , rrcMetricNames , rrcCustomRichMediaEvents , rrcDimensionFilters , rrcActivities , rrcDateRange , rrcDimensions -- ** CustomRichMediaEvents , CustomRichMediaEvents , customRichMediaEvents , crmeKind , crmeFilteredEventIds -- ** LanguagesListResponse , LanguagesListResponse , languagesListResponse , llrKind , llrLanguages -- ** UserRolesListSortOrder , UserRolesListSortOrder (..) -- ** PlacementsListCompatibilities , PlacementsListCompatibilities (..) -- ** TargetableRemarketingListsListResponse , TargetableRemarketingListsListResponse , targetableRemarketingListsListResponse , trllrNextPageToken , trllrKind , trllrTargetableRemarketingLists -- ** OrderDocumentsListSortField , OrderDocumentsListSortField (..) -- ** CreativeCompatibilityItem , CreativeCompatibilityItem (..) -- ** ChangeLogsListResponse , ChangeLogsListResponse , changeLogsListResponse , cllrNextPageToken , cllrKind , cllrChangeLogs -- ** ReportDeliveryEmailOwnerDeliveryType , ReportDeliveryEmailOwnerDeliveryType (..) -- ** SiteContactContactType , SiteContactContactType (..) -- ** AccountUserProFile , AccountUserProFile , accountUserProFile , aupfEmail , aupfUserRoleFilter , aupfAdvertiserFilter , aupfUserRoleId , aupfKind , aupfLocale , aupfSiteFilter , aupfTraffickerType , aupfActive , aupfAccountId , aupfName , aupfId , aupfUserAccessType , aupfComments , aupfSubAccountId , aupfCampaignFilter -- ** ReportsListSortOrder , ReportsListSortOrder (..) -- ** DimensionValue , DimensionValue , dimensionValue , dvEtag , dvKind , dvValue , dvMatchType , dvDimensionName , dvId -- ** TargetableRemarketingListsListSortField , TargetableRemarketingListsListSortField (..) -- ** CampaignsListSortOrder , CampaignsListSortOrder (..) -- ** Activities , Activities , activities , actKind , actMetricNames , actFilters -- ** FloodlightActivityGroupsListType , FloodlightActivityGroupsListType (..) -- ** FloodlightConfigurationFirstDayOfWeek , FloodlightConfigurationFirstDayOfWeek (..) -- ** UserRolePermissionGroupsListResponse , UserRolePermissionGroupsListResponse , userRolePermissionGroupsListResponse , urpglrUserRolePermissionGroups , urpglrKind -- ** PlacementTag , PlacementTag , placementTag , ptPlacementId , ptTagDatas -- ** DeliverySchedulePriority , DeliverySchedulePriority (..) -- ** FloodlightActivitiesListFloodlightActivityGroupType , FloodlightActivitiesListFloodlightActivityGroupType (..) -- ** RemarketingListsListResponse , RemarketingListsListResponse , remarketingListsListResponse , rllrNextPageToken , rllrRemarketingLists , rllrKind -- ** DynamicTargetingKey , DynamicTargetingKey , dynamicTargetingKey , dtkObjectType , dtkKind , dtkObjectId , dtkName -- ** Creative , Creative , creative , creConvertFlashToHTML5 , creBackupImageTargetWindow , creRenderingIdDimensionValue , creCustomKeyValues , creSkipOffSet , creVideoDuration , creRenderingId , creThirdPartyBackupImageImpressionsURL , creFsCommand , creAllowScriptAccess , creHTMLCodeLocked , creRequiredFlashPluginVersion , creAuthoringTool , creSize , creThirdPartyURLs , creProgressOffSet , creCounterCustomEvents , creKind , creSSLOverride , creHTMLCode , creAdvertiserId , creRequiredFlashVersion , creBackgRoundColor , creAdTagKeys , creSkippable , creSSLCompliant , creIdDimensionValue , creBackupImageReportingLabel , creCommercialId , creActive , creExitCustomEvents , creAccountId , creBackupImageClickThroughURL , creName , creOverrideCss , creVideoDescription , creClickTags , creAdParameters , creVersion , creLatestTraffickedCreativeId , creThirdPartyRichMediaImpressionsURL , creDynamicAssetSelection , creLastModifiedInfo , creId , creAuthoringSource , creStudioAdvertiserId , creCreativeAssets , creSubAccountId , creType , creTimerCustomEvents , creCreativeAssetSelection , creStudioCreativeId , creCompatibility , creBackupImageFeatures , creArtworkType , creArchived , creCompanionCreatives , creTotalFileSize , creStudioTraffickedCreativeId , creRedirectURL , creAutoAdvanceImages , creCreativeFieldAssignments -- ** SiteContact , SiteContact , siteContact , scEmail , scPhone , scLastName , scAddress , scFirstName , scId , scTitle , scContactType -- ** CreativeAuthoringSource , CreativeAuthoringSource (..) -- ** AccountsListResponse , AccountsListResponse , accountsListResponse , accNextPageToken , accAccounts , accKind -- ** DateRange , DateRange , dateRange , drKind , drEndDate , drStartDate , drRelativeDateRange -- ** FloodlightConfigurationStandardVariableTypesItem , FloodlightConfigurationStandardVariableTypesItem (..) -- ** Report , Report , report , rDelivery , rEtag , rOwnerProFileId , rSchedule , rPathToConversionCriteria , rKind , rFormat , rReachCriteria , rLastModifiedTime , rAccountId , rName , rId , rCrossDimensionReachCriteria , rType , rSubAccountId , rFloodlightCriteria , rCriteria , rFileName -- ** PlacementPaymentSource , PlacementPaymentSource (..) -- ** Rule , Rule , rule , rulTargetingTemplateId , rulName , rulAssetId -- ** ReportsFilesListSortOrder , ReportsFilesListSortOrder (..) -- ** Campaign , Campaign , campaign , camCreativeOptimizationConfiguration , camCreativeGroupIds , camNielsenOCREnabled , camKind , camClickThroughURLSuffixProperties , camAdvertiserId , camEndDate , camAdvertiserIdDimensionValue , camIdDimensionValue , camEventTagOverrides , camLookbackConfiguration , camStartDate , camAccountId , camName , camAdvertiserGroupId , camBillingInvoiceCode , camCreateInfo , camLastModifiedInfo , camId , camSubAccountId , camAdditionalCreativeOptimizationConfigurations , camExternalId , camComment , camAudienceSegmentGroups , camArchived , camTraffickerEmails , camDefaultClickThroughEventTagProperties -- ** InventoryItemsListSortField , InventoryItemsListSortField (..) -- ** EventTagType , EventTagType (..) -- ** CreativesListSortOrder , CreativesListSortOrder (..) -- ** InventoryItemsListType , InventoryItemsListType (..) -- ** ThirdPartyAuthenticationToken , ThirdPartyAuthenticationToken , thirdPartyAuthenticationToken , tpatValue , tpatName -- ** PopupWindowPropertiesPositionType , PopupWindowPropertiesPositionType (..) -- ** DirectorySiteContactRole , DirectorySiteContactRole (..) -- ** ClickThroughURL , ClickThroughURL , clickThroughURL , ctuDefaultLandingPage , ctuComputedClickThroughURL , ctuCustomClickThroughURL , ctuLandingPageId -- ** TagSettingKeywordOption , TagSettingKeywordOption (..) -- ** CreativeAuthoringTool , CreativeAuthoringTool (..) -- ** OrderContactContactType , OrderContactContactType (..) -- ** CreativeAssetIdType , CreativeAssetIdType (..) -- ** AccountUserProFilesListSortOrder , AccountUserProFilesListSortOrder (..) -- ** RemarketingListListSource , RemarketingListListSource (..) -- ** BrowsersListResponse , BrowsersListResponse , browsersListResponse , blrKind , blrBrowsers -- ** AccountUserProFileUserAccessType , AccountUserProFileUserAccessType (..) -- ** CreativeAssetStartTimeType , CreativeAssetStartTimeType (..) -- ** ProjectAudienceGender , ProjectAudienceGender (..) -- ** SiteSettings , SiteSettings , siteSettings , ssDisableNewCookie , ssVideoActiveViewOptOutTemplate , ssDisableBrandSafeAds , ssLookbackConfiguration , ssTagSetting , ssActiveViewOptOut , ssVpaidAdapterChoiceTemplate , ssCreativeSettings -- ** PlacementStrategiesListSortField , PlacementStrategiesListSortField (..) -- ** ContentCategoriesListResponse , ContentCategoriesListResponse , contentCategoriesListResponse , cclrNextPageToken , cclrKind , cclrContentCategories -- ** UserDefinedVariableConfigurationDataType , UserDefinedVariableConfigurationDataType (..) -- ** FloodlightActivityCacheBustingType , FloodlightActivityCacheBustingType (..) -- ** CreativesListResponse , CreativesListResponse , creativesListResponse , clrlNextPageToken , clrlKind , clrlCreatives -- ** CreativeGroupsListSortOrder , CreativeGroupsListSortOrder (..) -- ** OrderDocumentType , OrderDocumentType (..) -- ** TagDataFormat , TagDataFormat (..) -- ** Account , Account , account , aaAccountPermissionIds , aaMaximumImageSize , aaCurrencyId , aaReportsConfiguration , aaNielsenOCREnabled , aaKind , aaLocale , aaActive , aaAvailablePermissionIds , aaTeaserSizeLimit , aaActiveViewOptOut , aaShareReportsWithTwitter , aaName , aaAccountProFile , aaId , aaCountryId , aaActiveAdsLimitTier , aaDefaultCreativeSizeId , aaDescription -- ** ConversionsBatchInsertRequest , ConversionsBatchInsertRequest , conversionsBatchInsertRequest , cbirKind , cbirConversions , cbirEncryptionInfo -- ** AccountActiveAdSummaryActiveAdsLimitTier , AccountActiveAdSummaryActiveAdsLimitTier (..) -- ** CreativeAssetChildAssetType , CreativeAssetChildAssetType (..) -- ** PlacementGroupsListPlacementGroupType , PlacementGroupsListPlacementGroupType (..) -- ** AccountUserProFilesListResponse , AccountUserProFilesListResponse , accountUserProFilesListResponse , aupflrNextPageToken , aupflrAccountUserProFiles , aupflrKind -- ** ContentCategory , ContentCategory , contentCategory , conKind , conAccountId , conName , conId -- ** ObjectFilterStatus , ObjectFilterStatus (..) -- ** ReportCompatibleFields , ReportCompatibleFields , reportCompatibleFields , rcfMetrics , rcfKind , rcfDimensionFilters , rcfPivotedActivityMetrics , rcfDimensions -- ** CampaignCreativeAssociationsListSortOrder , CampaignCreativeAssociationsListSortOrder (..) -- ** DeliverySchedule , DeliverySchedule , deliverySchedule , dsHardCutoff , dsPriority , dsImpressionRatio , dsFrequencyCap -- ** RemarketingList , RemarketingList , remarketingList , rlListSize , rlListPopulationRule , rlLifeSpan , rlKind , rlAdvertiserId , rlAdvertiserIdDimensionValue , rlActive , rlAccountId , rlName , rlListSource , rlId , rlSubAccountId , rlDescription -- ** FloodlightActivitiesListSortField , FloodlightActivitiesListSortField (..) -- ** DynamicTargetingKeysListResponse , DynamicTargetingKeysListResponse , dynamicTargetingKeysListResponse , dtklrKind , dtklrDynamicTargetingKeys -- ** DimensionValueList , DimensionValueList , dimensionValueList , dvlEtag , dvlNextPageToken , dvlKind , dvlItems -- ** FloodlightReportCompatibleFields , FloodlightReportCompatibleFields , floodlightReportCompatibleFields , frcfMetrics , frcfKind , frcfDimensionFilters , frcfDimensions -- ** UserRolePermissionGroup , UserRolePermissionGroup , userRolePermissionGroup , urpgKind , urpgName , urpgId -- ** CreativesListTypes , CreativesListTypes (..) -- ** DirectorySiteInpageTagFormatsItem , DirectorySiteInpageTagFormatsItem (..) -- ** TagSetting , TagSetting , tagSetting , tsKeywordOption , tsIncludeClickThroughURLs , tsIncludeClickTracking , tsAdditionalKeyValues -- ** CreativeAssetWindowMode , CreativeAssetWindowMode (..) -- ** CreativeAssetAlignment , CreativeAssetAlignment (..) -- ** RemarketingListsListSortOrder , RemarketingListsListSortOrder (..) -- ** ReportPathToConversionCriteriaReportProperties , ReportPathToConversionCriteriaReportProperties , reportPathToConversionCriteriaReportProperties , rptccrpMaximumInteractionGap , rptccrpMaximumClickInteractions , rptccrpPivotOnInteractionPath , rptccrpMaximumImpressionInteractions , rptccrpIncludeUnattributedIPConversions , rptccrpImpressionsLookbackWindow , rptccrpClicksLookbackWindow , rptccrpIncludeUnattributedCookieConversions , rptccrpIncludeAttributedIPConversions -- ** UserRolePermissionsListResponse , UserRolePermissionsListResponse , userRolePermissionsListResponse , urplrKind , urplrUserRolePermissions -- ** PlacementGroupsListPricingTypes , PlacementGroupsListPricingTypes (..) -- ** DynamicTargetingKeysDeleteObjectType , DynamicTargetingKeysDeleteObjectType (..) -- ** AccountActiveAdsLimitTier , AccountActiveAdsLimitTier (..) -- ** AccountsListSortOrder , AccountsListSortOrder (..) -- ** PlacementGroupsListResponse , PlacementGroupsListResponse , placementGroupsListResponse , pglrNextPageToken , pglrKind , pglrPlacementGroups -- ** MobileCarrier , MobileCarrier , mobileCarrier , mcKind , mcName , mcCountryCode , mcId , mcCountryDartId -- ** LandingPage , LandingPage , landingPage , lpKind , lpDefault , lpURL , lpName , lpId -- ** ConnectionTypesListResponse , ConnectionTypesListResponse , connectionTypesListResponse , ctlrKind , ctlrConnectionTypes -- ** OrdersListResponse , OrdersListResponse , ordersListResponse , olrNextPageToken , olrKind , olrOrders -- ** ReportList , ReportList , reportList , repEtag , repNextPageToken , repKind , repItems -- ** CreativeGroup , CreativeGroup , creativeGroup , cgKind , cgAdvertiserId , cgAdvertiserIdDimensionValue , cgGroupNumber , cgAccountId , cgName , cgId , cgSubAccountId -- ** SubAccountsListSortField , SubAccountsListSortField (..) -- ** CampaignCreativeAssociation , CampaignCreativeAssociation , campaignCreativeAssociation , ccaKind , ccaCreativeId -- ** ConversionStatus , ConversionStatus , conversionStatus , csKind , csConversion , csErrors -- ** LookbackConfiguration , LookbackConfiguration , lookbackConfiguration , lcClickDuration , lcPostImpressionActivitiesDuration -- ** VideoFormatFileType , VideoFormatFileType (..) -- ** AdsListSortField , AdsListSortField (..) -- ** ProjectsListSortField , ProjectsListSortField (..) -- ** FloodlightActivityPublisherDynamicTag , FloodlightActivityPublisherDynamicTag , floodlightActivityPublisherDynamicTag , fapdtClickThrough , fapdtSiteIdDimensionValue , fapdtDynamicTag , fapdtDirectorySiteId , fapdtSiteId , fapdtViewThrough -- ** AdsListType , AdsListType (..) -- ** AccountActiveAdSummary , AccountActiveAdSummary , accountActiveAdSummary , aaasAvailableAds , aaasKind , aaasAccountId , aaasActiveAds , aaasActiveAdsLimitTier -- ** CreativeOptimizationConfigurationOptimizationModel , CreativeOptimizationConfigurationOptimizationModel (..) -- ** AccountPermissionLevel , AccountPermissionLevel (..) -- ** OffSetPosition , OffSetPosition , offSetPosition , ospLeft , ospTop -- ** Metric , Metric , metric , mKind , mName -- ** RemarketingListShare , RemarketingListShare , remarketingListShare , rlsSharedAdvertiserIds , rlsKind , rlsRemarketingListId , rlsSharedAccountIds -- ** EventTagsListResponse , EventTagsListResponse , eventTagsListResponse , etlrKind , etlrEventTags -- ** UserRolesListResponse , UserRolesListResponse , userRolesListResponse , urlrNextPageToken , urlrKind , urlrUserRoles -- ** ListPopulationTermType , ListPopulationTermType (..) -- ** AdvertiserGroupsListSortOrder , AdvertiserGroupsListSortOrder (..) -- ** CreativeFieldValuesListSortOrder , CreativeFieldValuesListSortOrder (..) -- ** SortedDimensionSortOrder , SortedDimensionSortOrder (..) -- ** CompatibleFields , CompatibleFields , compatibleFields , cfReachReportCompatibleFields , cfCrossDimensionReachReportCompatibleFields , cfKind , cfFloodlightReportCompatibleFields , cfReportCompatibleFields , cfPathToConversionReportCompatibleFields -- ** AudienceSegment , AudienceSegment , audienceSegment , asName , asId , asAllocation -- ** FilesListSortField , FilesListSortField (..) -- ** DirectorySiteInterstitialTagFormatsItem , DirectorySiteInterstitialTagFormatsItem (..) -- ** DfpSettings , DfpSettings , dfpSettings , dsPubPaidPlacementAccepted , dsDfpNetworkName , dsPublisherPortalOnly , dsProgrammaticPlacementAccepted , dsDfpNetworkCode -- ** EventTagsListSortField , EventTagsListSortField (..) -- ** PathToConversionReportCompatibleFields , PathToConversionReportCompatibleFields , pathToConversionReportCompatibleFields , ptcrcfMetrics , ptcrcfKind , ptcrcfConversionDimensions , ptcrcfCustomFloodlightVariables , ptcrcfPerInteractionDimensions -- ** InventoryItemType , InventoryItemType (..) -- ** CreativeAssetPositionTopUnit , CreativeAssetPositionTopUnit (..) -- ** City , City , city , ccMetroCode , ccRegionCode , ccKind , ccRegionDartId , ccMetroDmaId , ccName , ccCountryCode , ccCountryDartId , ccDartId -- ** PlatformType , PlatformType , platformType , ptKind , ptName , ptId -- ** FloodlightActivityFloodlightActivityGroupType , FloodlightActivityFloodlightActivityGroupType (..) -- ** DirectorySiteContactsListSortOrder , DirectorySiteContactsListSortOrder (..) -- ** PricingGroupType , PricingGroupType (..) -- ** KeyValueTargetingExpression , KeyValueTargetingExpression , keyValueTargetingExpression , kvteExpression -- ** CompanionClickThroughOverride , CompanionClickThroughOverride , companionClickThroughOverride , cctoCreativeId , cctoClickThroughURL -- ** FloodlightActivityGroupsListSortOrder , FloodlightActivityGroupsListSortOrder (..) -- ** CreativeRotationType , CreativeRotationType (..) -- ** OrdersListSortField , OrdersListSortField (..) -- ** PlacementGroupsListSortField , PlacementGroupsListSortField (..) -- ** DirectorySitesListSortOrder , DirectorySitesListSortOrder (..) -- ** AdvertisersListResponse , AdvertisersListResponse , advertisersListResponse , advNextPageToken , advKind , advAdvertisers -- ** CountriesListResponse , CountriesListResponse , countriesListResponse , couKind , couCountries -- ** AccountPermissionGroupsListResponse , AccountPermissionGroupsListResponse , accountPermissionGroupsListResponse , apglrKind , apglrAccountPermissionGroups -- ** PopupWindowProperties , PopupWindowProperties , popupWindowProperties , pwpOffSet , pwpDimension , pwpShowStatusBar , pwpShowMenuBar , pwpPositionType , pwpShowAddressBar , pwpShowScrollBar , pwpShowToolBar , pwpTitle -- ** CreativeAssetDetectedFeaturesItem , CreativeAssetDetectedFeaturesItem (..) -- ** FloodlightActivityGroupType , FloodlightActivityGroupType (..) -- ** DirectorySiteContactType , DirectorySiteContactType (..) -- ** EventTagOverride , EventTagOverride , eventTagOverride , etoEnabled , etoId -- ** PlacementsGeneratetagsTagFormats , PlacementsGeneratetagsTagFormats (..) -- ** AccountUserProFilesListSortField , AccountUserProFilesListSortField (..) -- ** OperatingSystemVersion , OperatingSystemVersion , operatingSystemVersion , osvMinorVersion , osvKind , osvOperatingSystem , osvMajorVersion , osvName , osvId -- ** InventoryItemsListSortOrder , InventoryItemsListSortOrder (..) -- ** PlacementStrategiesListSortOrder , PlacementStrategiesListSortOrder (..) -- ** AccountPermission , AccountPermission , accountPermission , acccKind , acccAccountProFiles , acccName , acccId , acccLevel , acccPermissionGroupId -- ** UserProFile , UserProFile , userProFile , upfEtag , upfKind , upfAccountName , upfProFileId , upfUserName , upfAccountId , upfSubAccountName , upfSubAccountId -- ** OperatingSystemsListResponse , OperatingSystemsListResponse , operatingSystemsListResponse , oslrKind , oslrOperatingSystems -- ** ReportDelivery , ReportDelivery , reportDelivery , rdEmailOwner , rdRecipients , rdMessage , rdEmailOwnerDeliveryType -- ** TargetableRemarketingList , TargetableRemarketingList , targetableRemarketingList , trlListSize , trlLifeSpan , trlKind , trlAdvertiserId , trlAdvertiserIdDimensionValue , trlActive , trlAccountId , trlName , trlListSource , trlId , trlSubAccountId , trlDescription -- ** ReportsFilesListSortField , ReportsFilesListSortField (..) -- ** PostalCodesListResponse , PostalCodesListResponse , postalCodesListResponse , pclrKind , pclrPostalCodes -- ** ChangeLog , ChangeLog , changeLog , chaUserProFileId , chaObjectType , chaUserProFileName , chaKind , chaObjectId , chaAction , chaTransactionId , chaOldValue , chaAccountId , chaNewValue , chaFieldName , chaId , chaSubAccountId , chaChangeTime -- ** Language , Language , language , lLanguageCode , lKind , lName , lId -- ** CreativesListSortField , CreativesListSortField (..) -- ** PlacementStrategy , PlacementStrategy , placementStrategy , psKind , psAccountId , psName , psId -- ** FloodlightActivity , FloodlightActivity , floodlightActivity , faCountingMethod , faTagString , faSecure , faExpectedURL , faFloodlightActivityGroupTagString , faFloodlightConfigurationId , faKind , faImageTagEnabled , faAdvertiserId , faAdvertiserIdDimensionValue , faSSLCompliant , faIdDimensionValue , faTagFormat , faCacheBustingType , faAccountId , faName , faPublisherTags , faFloodlightActivityGroupId , faHidden , faFloodlightActivityGroupType , faDefaultTags , faFloodlightActivityGroupName , faId , faSSLRequired , faUserDefinedVariableTypes , faSubAccountId , faNotes , faFloodlightConfigurationIdDimensionValue -- ** DayPartTargetingDaysOfWeekItem , DayPartTargetingDaysOfWeekItem (..) -- ** CustomFloodlightVariable , CustomFloodlightVariable , customFloodlightVariable , cusKind , cusValue , cusType -- ** CreativeRotationWeightCalculationStrategy , CreativeRotationWeightCalculationStrategy (..) -- ** FilesListScope , FilesListScope (..) -- ** ContentCategoriesListSortField , ContentCategoriesListSortField (..) -- ** ProjectAudienceAgeGroup , ProjectAudienceAgeGroup (..) -- ** PlatformTypesListResponse , PlatformTypesListResponse , platformTypesListResponse , ptlrKind , ptlrPlatformTypes -- ** AdType , AdType (..) -- ** LastModifiedInfo , LastModifiedInfo , lastModifiedInfo , lmiTime -- ** TargetWindow , TargetWindow , targetWindow , twCustomHTML , twTargetWindowOption -- ** ChangeLogsListAction , ChangeLogsListAction (..) -- ** CreativeArtworkType , CreativeArtworkType (..) -- ** PlacementStatus , PlacementStatus (..) -- ** AccountPermissionGroup , AccountPermissionGroup , accountPermissionGroup , apgpKind , apgpName , apgpId -- ** Advertiser , Advertiser , advertiser , advdOriginalFloodlightConfigurationId , advdStatus , advdFloodlightConfigurationId , advdKind , advdSuspended , advdIdDimensionValue , advdAccountId , advdDefaultEmail , advdName , advdAdvertiserGroupId , advdDefaultClickThroughEventTagId , advdId , advdSubAccountId , advdFloodlightConfigurationIdDimensionValue , advdClickThroughURLSuffix -- ** ReportScheduleRunsOnDayOfMonth , ReportScheduleRunsOnDayOfMonth (..) -- ** UserRole , UserRole , userRole , urParentUserRoleId , urKind , urDefaultUserRole , urAccountId , urName , urId , urPermissions , urSubAccountId -- ** FloodlightActivityUserDefinedVariableTypesItem , FloodlightActivityUserDefinedVariableTypesItem (..) -- ** EventTagSiteFilterType , EventTagSiteFilterType (..) -- ** ReportFormat , ReportFormat (..) -- ** PlacementGroupPlacementGroupType , PlacementGroupPlacementGroupType (..) -- ** VideoFormatsListResponse , VideoFormatsListResponse , videoFormatsListResponse , vflrKind , vflrVideoFormats -- ** DirectorySitesListResponse , DirectorySitesListResponse , directorySitesListResponse , dslrNextPageToken , dslrKind , dslrDirectorySites -- ** ConversionError , ConversionError , conversionError , ceKind , ceCode , ceMessage -- ** PricingPricingType , PricingPricingType (..) -- ** PricingSchedulePricingPeriod , PricingSchedulePricingPeriod , pricingSchedulePricingPeriod , psppEndDate , psppRateOrCostNanos , psppStartDate , psppUnits , psppPricingComment -- ** SubAccountsListSortOrder , SubAccountsListSortOrder (..) -- ** DirectorySiteContactsListResponse , DirectorySiteContactsListResponse , directorySiteContactsListResponse , dsclrNextPageToken , dsclrKind , dsclrDirectorySiteContacts -- ** Region , Region , region , regRegionCode , regKind , regName , regCountryCode , regCountryDartId , regDartId -- ** AdvertiserGroupsListResponse , AdvertiserGroupsListResponse , advertiserGroupsListResponse , aglrNextPageToken , aglrKind , aglrAdvertiserGroups -- ** AdsListSortOrder , AdsListSortOrder (..) -- ** ProjectsListSortOrder , ProjectsListSortOrder (..) -- ** CreativeAssignment , CreativeAssignment , creativeAssignment , caCreativeGroupAssignments , caStartTime , caWeight , caRichMediaExitOverrides , caSSLCompliant , caCreativeId , caClickThroughURL , caApplyEventTags , caActive , caSequence , caEndTime , caCompanionCreativeOverrides , caCreativeIdDimensionValue -- ** DimensionFilter , DimensionFilter , dimensionFilter , dfKind , dfValue , dfDimensionName -- ** UserProFileList , UserProFileList , userProFileList , upflEtag , upflKind , upflItems -- ** RemarketingListsListSortField , RemarketingListsListSortField (..) -- ** FloodlightConfiguration , FloodlightConfiguration , floodlightConfiguration , fcTagSettings , fcExposureToConversionEnabled , fcInAppAttributionTrackingEnabled , fcThirdPartyAuthenticationTokens , fcKind , fcAdvertiserId , fcAnalyticsDataSharingEnabled , fcAdvertiserIdDimensionValue , fcIdDimensionValue , fcLookbackConfiguration , fcAccountId , fcId , fcNATuralSearchConversionAttributionOption , fcUserDefinedVariableConfigurations , fcSubAccountId , fcFirstDayOfWeek , fcOmnitureSettings , fcStandardVariableTypes -- ** CompanionSetting , CompanionSetting , companionSetting , comKind , comImageOnly , comCompanionsDisabled , comEnabledSizes -- ** ReportScheduleRepeatsOnWeekDaysItem , ReportScheduleRepeatsOnWeekDaysItem (..) -- ** FloodlightActivityGroupsListResponse , FloodlightActivityGroupsListResponse , floodlightActivityGroupsListResponse , faglrNextPageToken , faglrKind , faglrFloodlightActivityGroups -- ** CreativeGroupAssignmentCreativeGroupNumber , CreativeGroupAssignmentCreativeGroupNumber (..) -- ** Conversion , Conversion , conversion , conoEncryptedUserIdCandidates , conoTimestampMicros , conoLimitAdTracking , conoEncryptedUserId , conoMobileDeviceId , conoFloodlightConfigurationId , conoKind , conoFloodlightActivityId , conoQuantity , conoValue , conoCustomVariables , conoChildDirectedTreatment , conoOrdinal -- ** CreativeFieldValuesListResponse , CreativeFieldValuesListResponse , creativeFieldValuesListResponse , cfvlrNextPageToken , cfvlrKind , cfvlrCreativeFieldValues -- ** SiteSettingsVpaidAdapterChoiceTemplate , SiteSettingsVpaidAdapterChoiceTemplate (..) -- ** AccountsListSortField , AccountsListSortField (..) -- ** RichMediaExitOverride , RichMediaExitOverride , richMediaExitOverride , rmeoEnabled , rmeoClickThroughURL , rmeoExitId -- ** AdvertisersListStatus , AdvertisersListStatus (..) -- ** DimensionValueMatchType , DimensionValueMatchType (..) -- ** SortedDimension , SortedDimension , sortedDimension , sdKind , sdSortOrder , sdName -- ** PlacementGroupsListSortOrder , PlacementGroupsListSortOrder (..) -- ** CreativeFieldsListResponse , CreativeFieldsListResponse , creativeFieldsListResponse , cflrNextPageToken , cflrKind , cflrCreativeFields -- ** TargetingTemplatesListResponse , TargetingTemplatesListResponse , targetingTemplatesListResponse , ttlrNextPageToken , ttlrKind , ttlrTargetingTemplates -- ** PlacementsGenerateTagsResponse , PlacementsGenerateTagsResponse , placementsGenerateTagsResponse , pgtrKind , pgtrPlacementTags -- ** CreativeAsset , CreativeAsset , creativeAsset , caaZIndex , caaPushdown , caaVideoDuration , caaOriginalBackup , caaWindowMode , caaFlashVersion , caaPushdownDuration , caaSize , caaVerticallyLocked , caaOffSet , caaStreamingServingURL , caaZipFilesize , caaTransparency , caaHideSelectionBoxes , caaSSLCompliant , caaFileSize , caaAssetIdentifier , caaCompanionCreativeIds , caaDurationType , caaProgressiveServingURL , caaIdDimensionValue , caaActive , caaRole , caaMimeType , caaPositionTopUnit , caaPositionLeftUnit , caaAlignment , caaExpandedDimension , caaZipFilename , caaActionScript3 , caaDisplayType , caaChildAssetType , caaCollapsedSize , caaId , caaBitRate , caaCustomStartTimeValue , caaStartTimeType , caaDuration , caaArtworkType , caaHideFlashObjects , caaDetectedFeatures , caaBackupImageExit , caaPosition , caaHorizontallyLocked -- ** AdCompatibility , AdCompatibility (..) -- ** CreativeFieldValuesListSortField , CreativeFieldValuesListSortField (..) -- ** LanguageTargeting , LanguageTargeting , languageTargeting , ltLanguages -- ** CreativeAssetSelection , CreativeAssetSelection , creativeAssetSelection , casRules , casDefaultAssetId -- ** PlacementsListResponse , PlacementsListResponse , placementsListResponse , plaNextPageToken , plaKind , plaPlacements -- ** FloodlightActivityGroupsListSortField , FloodlightActivityGroupsListSortField (..) -- ** OrdersListSortOrder , OrdersListSortOrder (..) -- ** ReportSchedule , ReportSchedule , reportSchedule , rsEvery , rsActive , rsRepeats , rsStartDate , rsExpirationDate , rsRunsOnDayOfMonth , rsRepeatsOnWeekDays -- ** ReportPathToConversionCriteria , ReportPathToConversionCriteria , reportPathToConversionCriteria , rptccReportProperties , rptccMetricNames , rptccCustomRichMediaEvents , rptccDateRange , rptccConversionDimensions , rptccCustomFloodlightVariables , rptccFloodlightConfigId , rptccActivityFilters , rptccPerInteractionDimensions -- ** MetrosListResponse , MetrosListResponse , metrosListResponse , mlrKind , mlrMetros -- ** AccountAccountProFile , AccountAccountProFile (..) -- ** ConversionsBatchInsertResponse , ConversionsBatchInsertResponse , conversionsBatchInsertResponse , cbirbStatus , cbirbKind , cbirbHasFailures -- ** OrderDocumentsListResponse , OrderDocumentsListResponse , orderDocumentsListResponse , odlrNextPageToken , odlrKind , odlrOrderDocuments -- ** Recipient , Recipient , recipient , recEmail , recKind , recDeliveryType -- ** CreativeType , CreativeType (..) -- ** FilesListSortOrder , FilesListSortOrder (..) -- ** AdvertiserGroupsListSortField , AdvertiserGroupsListSortField (..) -- ** TargetWindowTargetWindowOption , TargetWindowTargetWindowOption (..) -- ** DirectorySiteContactsListSortField , DirectorySiteContactsListSortField (..) -- ** PlacementsListPricingTypes , PlacementsListPricingTypes (..) -- ** EventTagsListSortOrder , EventTagsListSortOrder (..) -- ** EncryptionInfoEncryptionSource , EncryptionInfoEncryptionSource (..) -- ** DirectorySitesListSortField , DirectorySitesListSortField (..) -- ** Site , Site , site , sitiKind , sitiKeyName , sitiSiteContacts , sitiSiteSettings , sitiIdDimensionValue , sitiDirectorySiteIdDimensionValue , sitiAccountId , sitiName , sitiDirectorySiteId , sitiId , sitiSubAccountId , sitiApproved -- ** ReportCrossDimensionReachCriteriaDimension , ReportCrossDimensionReachCriteriaDimension (..) -- ** SitesListSortOrder , SitesListSortOrder (..) -- ** UserDefinedVariableConfiguration , UserDefinedVariableConfiguration , userDefinedVariableConfiguration , udvcReportName , udvcDataType , udvcVariableType -- ** ReportCrossDimensionReachCriteria , ReportCrossDimensionReachCriteria , reportCrossDimensionReachCriteria , rcdrcPivoted , rcdrcBreakdown , rcdrcDimension , rcdrcMetricNames , rcdrcDimensionFilters , rcdrcDateRange , rcdrcOverlapMetricNames -- ** FileURLs , FileURLs , fileURLs , fuBrowserURL , fuAPIURL -- ** CampaignCreativeAssociationsListResponse , CampaignCreativeAssociationsListResponse , campaignCreativeAssociationsListResponse , ccalrCampaignCreativeAssociations , ccalrNextPageToken , ccalrKind -- ** PlacementTagFormatsItem , PlacementTagFormatsItem (..) -- ** Order , Order , order , oSellerOrderId , oSellerOrganizationName , oKind , oAdvertiserId , oPlanningTermId , oAccountId , oName , oSiteNames , oLastModifiedInfo , oBuyerOrganizationName , oId , oBuyerInvoiceId , oComments , oProjectId , oSubAccountId , oNotes , oContacts , oSiteId , oTermsAndConditions , oApproverUserProFileIds -- ** CreativeAssetId , CreativeAssetId , creativeAssetId , caiName , caiType -- ** FrequencyCap , FrequencyCap , frequencyCap , fcImpressions , fcDuration -- ** File , File , file , filStatus , filEtag , filKind , filURLs , filReportId , filDateRange , filFormat , filLastModifiedTime , filId , filFileName -- ** CreativeSettings , CreativeSettings , creativeSettings , csIFrameHeader , csIFrameFooter -- ** DynamicTargetingKeyObjectType , DynamicTargetingKeyObjectType (..) -- ** ReportType , ReportType (..) -- ** CreativeAssetMetadataWarnedValidationRulesItem , CreativeAssetMetadataWarnedValidationRulesItem (..) -- ** CreativeGroupsListResponse , CreativeGroupsListResponse , creativeGroupsListResponse , cglrCreativeGroups , cglrNextPageToken , cglrKind -- ** AdSlotPaymentSourceType , AdSlotPaymentSourceType (..) -- ** MobileCarriersListResponse , MobileCarriersListResponse , mobileCarriersListResponse , mclrMobileCarriers , mclrKind -- ** LandingPagesListResponse , LandingPagesListResponse , landingPagesListResponse , lplrLandingPages , lplrKind -- ** AccountPermissionAccountProFilesItem , AccountPermissionAccountProFilesItem (..) -- ** CreativeAssetMetadata , CreativeAssetMetadata , creativeAssetMetadata , camaKind , camaAssetIdentifier , camaIdDimensionValue , camaClickTags , camaWarnedValidationRules , camaId , camaDetectedFeatures -- ** OmnitureSettings , OmnitureSettings , omnitureSettings , osOmnitureCostDataEnabled , osOmnitureIntegrationEnabled -- ** ConnectionType , ConnectionType , connectionType , cttKind , cttName , cttId -- ** CreativeCustomEventAdvertiserCustomEventType , CreativeCustomEventAdvertiserCustomEventType (..) -- ** PlacementGroup , PlacementGroup , placementGroup , plalPlacementStrategyId , plalSiteIdDimensionValue , plalPricingSchedule , plalKind , plalCampaignIdDimensionValue , plalAdvertiserId , plalAdvertiserIdDimensionValue , plalCampaignId , plalIdDimensionValue , plalPlacementGroupType , plalContentCategoryId , plalDirectorySiteIdDimensionValue , plalAccountId , plalName , plalDirectorySiteId , plalCreateInfo , plalChildPlacementIds , plalLastModifiedInfo , plalId , plalPrimaryPlacementId , plalSubAccountId , plalExternalId , plalComment , plalPrimaryPlacementIdDimensionValue , plalSiteId , plalArchived -- ** EventTag , EventTag , eventTag , etStatus , etExcludeFromAdxRequests , etEnabledByDefault , etKind , etCampaignIdDimensionValue , etAdvertiserId , etURL , etAdvertiserIdDimensionValue , etSSLCompliant , etCampaignId , etAccountId , etName , etURLEscapeLevels , etSiteIds , etId , etSubAccountId , etType , etSiteFilterType -- ** UserRolePermission , UserRolePermission , userRolePermission , useKind , useAvailability , useName , useId , usePermissionGroupId -- ** ChangeLogsListObjectType , ChangeLogsListObjectType (..) -- ** OrderContact , OrderContact , orderContact , ocSignatureUserProFileId , ocContactName , ocContactTitle , ocContactType , ocContactInfo -- ** TranscodeSetting , TranscodeSetting , transcodeSetting , tsKind , tsEnabledVideoFormats -- ** FloodlightActivitiesGenerateTagResponse , FloodlightActivitiesGenerateTagResponse , floodlightActivitiesGenerateTagResponse , fagtrFloodlightActivityTag , fagtrKind -- ** DirectorySiteContactAssignment , DirectorySiteContactAssignment , directorySiteContactAssignment , dscaVisibility , dscaContactId -- ** AdSlot , AdSlot , adSlot , assHeight , assPaymentSourceType , assLinkedPlacementId , assWidth , assPrimary , assName , assComment , assCompatibility -- ** ThirdPartyTrackingURL , ThirdPartyTrackingURL , thirdPartyTrackingURL , tptuURL , tptuThirdPartyURLType -- ** PricingCapCostType , PricingCapCostType (..) -- ** OrderDocument , OrderDocument , orderDocument , odSigned , odKind , odAdvertiserId , odLastSentTime , odAmendedOrderDocumentId , odLastSentRecipients , odEffectiveDate , odApprovedByUserProFileIds , odAccountId , odId , odProjectId , odTitle , odSubAccountId , odType , odOrderId , odCancelled , odCreatedInfo -- ** Metro , Metro , metro , metMetroCode , metKind , metName , metCountryCode , metDmaId , metCountryDartId , metDartId -- ** CreativeAssetDisplayType , CreativeAssetDisplayType (..) -- ** Placement , Placement , placement , p1Status , p1VideoSettings , p1PlacementStrategyId , p1TagFormats , p1SiteIdDimensionValue , p1PricingSchedule , p1Size , p1Kind , p1KeyName , p1CampaignIdDimensionValue , p1AdvertiserId , p1AdvertiserIdDimensionValue , p1CampaignId , p1IdDimensionValue , p1VpaidAdapterChoice , p1Primary , p1LookbackConfiguration , p1TagSetting , p1ContentCategoryId , p1DirectorySiteIdDimensionValue , p1AccountId , p1PaymentSource , p1Name , p1DirectorySiteId , p1CreateInfo , p1VideoActiveViewOptOut , p1LastModifiedInfo , p1Id , p1SSLRequired , p1SubAccountId , p1PlacementGroupIdDimensionValue , p1ExternalId , p1PlacementGroupId , p1Comment , p1SiteId , p1Compatibility , p1Archived , p1PaymentApproved , p1PublisherUpdateInfo -- ** FloodlightActivityCountingMethod , FloodlightActivityCountingMethod (..) -- ** EncryptionInfo , EncryptionInfo , encryptionInfo , eiEncryptionSource , eiKind , eiEncryptionEntityType , eiEncryptionEntityId -- ** SitesListResponse , SitesListResponse , sitesListResponse , sitNextPageToken , sitKind , sitSites -- ** ContentCategoriesListSortOrder , ContentCategoriesListSortOrder (..) -- ** TargetingTemplate , TargetingTemplate , targetingTemplate , ttGeoTargeting , ttTechnologyTargeting , ttDayPartTargeting , ttKind , ttAdvertiserId , ttAdvertiserIdDimensionValue , ttAccountId , ttName , ttKeyValueTargetingExpression , ttId , ttSubAccountId , ttLanguageTargeting , ttListTargetingExpression -- ** CreativeField , CreativeField , creativeField , cffKind , cffAdvertiserId , cffAdvertiserIdDimensionValue , cffAccountId , cffName , cffId , cffSubAccountId -- ** AdvertiserStatus , AdvertiserStatus (..) -- ** DefaultClickThroughEventTagProperties , DefaultClickThroughEventTagProperties , defaultClickThroughEventTagProperties , dctetpOverrideInheritedEventTag , dctetpDefaultClickThroughEventTagId -- ** ListTargetingExpression , ListTargetingExpression , listTargetingExpression , lteExpression ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude import Network.Google.Resource.DFAReporting.AccountActiveAdSummaries.Get import Network.Google.Resource.DFAReporting.AccountPermissionGroups.Get import Network.Google.Resource.DFAReporting.AccountPermissionGroups.List import Network.Google.Resource.DFAReporting.AccountPermissions.Get import Network.Google.Resource.DFAReporting.AccountPermissions.List import Network.Google.Resource.DFAReporting.Accounts.Get import Network.Google.Resource.DFAReporting.Accounts.List import Network.Google.Resource.DFAReporting.Accounts.Patch import Network.Google.Resource.DFAReporting.Accounts.Update import Network.Google.Resource.DFAReporting.AccountUserProFiles.Get import Network.Google.Resource.DFAReporting.AccountUserProFiles.Insert import Network.Google.Resource.DFAReporting.AccountUserProFiles.List import Network.Google.Resource.DFAReporting.AccountUserProFiles.Patch import Network.Google.Resource.DFAReporting.AccountUserProFiles.Update import Network.Google.Resource.DFAReporting.Ads.Get import Network.Google.Resource.DFAReporting.Ads.Insert import Network.Google.Resource.DFAReporting.Ads.List import Network.Google.Resource.DFAReporting.Ads.Patch import Network.Google.Resource.DFAReporting.Ads.Update import Network.Google.Resource.DFAReporting.AdvertiserGroups.Delete import Network.Google.Resource.DFAReporting.AdvertiserGroups.Get import Network.Google.Resource.DFAReporting.AdvertiserGroups.Insert import Network.Google.Resource.DFAReporting.AdvertiserGroups.List import Network.Google.Resource.DFAReporting.AdvertiserGroups.Patch import Network.Google.Resource.DFAReporting.AdvertiserGroups.Update import Network.Google.Resource.DFAReporting.Advertisers.Get import Network.Google.Resource.DFAReporting.Advertisers.Insert import Network.Google.Resource.DFAReporting.Advertisers.List import Network.Google.Resource.DFAReporting.Advertisers.Patch import Network.Google.Resource.DFAReporting.Advertisers.Update import Network.Google.Resource.DFAReporting.Browsers.List import Network.Google.Resource.DFAReporting.CampaignCreativeAssociations.Insert import Network.Google.Resource.DFAReporting.CampaignCreativeAssociations.List import Network.Google.Resource.DFAReporting.Campaigns.Get import Network.Google.Resource.DFAReporting.Campaigns.Insert import Network.Google.Resource.DFAReporting.Campaigns.List import Network.Google.Resource.DFAReporting.Campaigns.Patch import Network.Google.Resource.DFAReporting.Campaigns.Update import Network.Google.Resource.DFAReporting.ChangeLogs.Get import Network.Google.Resource.DFAReporting.ChangeLogs.List import Network.Google.Resource.DFAReporting.Cities.List import Network.Google.Resource.DFAReporting.ConnectionTypes.Get import Network.Google.Resource.DFAReporting.ConnectionTypes.List import Network.Google.Resource.DFAReporting.ContentCategories.Delete import Network.Google.Resource.DFAReporting.ContentCategories.Get import Network.Google.Resource.DFAReporting.ContentCategories.Insert import Network.Google.Resource.DFAReporting.ContentCategories.List import Network.Google.Resource.DFAReporting.ContentCategories.Patch import Network.Google.Resource.DFAReporting.ContentCategories.Update import Network.Google.Resource.DFAReporting.Conversions.Batchinsert import Network.Google.Resource.DFAReporting.Countries.Get import Network.Google.Resource.DFAReporting.Countries.List import Network.Google.Resource.DFAReporting.CreativeAssets.Insert import Network.Google.Resource.DFAReporting.CreativeFields.Delete import Network.Google.Resource.DFAReporting.CreativeFields.Get import Network.Google.Resource.DFAReporting.CreativeFields.Insert import Network.Google.Resource.DFAReporting.CreativeFields.List import Network.Google.Resource.DFAReporting.CreativeFields.Patch import Network.Google.Resource.DFAReporting.CreativeFields.Update import Network.Google.Resource.DFAReporting.CreativeFieldValues.Delete import Network.Google.Resource.DFAReporting.CreativeFieldValues.Get import Network.Google.Resource.DFAReporting.CreativeFieldValues.Insert import Network.Google.Resource.DFAReporting.CreativeFieldValues.List import Network.Google.Resource.DFAReporting.CreativeFieldValues.Patch import Network.Google.Resource.DFAReporting.CreativeFieldValues.Update import Network.Google.Resource.DFAReporting.CreativeGroups.Get import Network.Google.Resource.DFAReporting.CreativeGroups.Insert import Network.Google.Resource.DFAReporting.CreativeGroups.List import Network.Google.Resource.DFAReporting.CreativeGroups.Patch import Network.Google.Resource.DFAReporting.CreativeGroups.Update import Network.Google.Resource.DFAReporting.Creatives.Get import Network.Google.Resource.DFAReporting.Creatives.Insert import Network.Google.Resource.DFAReporting.Creatives.List import Network.Google.Resource.DFAReporting.Creatives.Patch import Network.Google.Resource.DFAReporting.Creatives.Update import Network.Google.Resource.DFAReporting.DimensionValues.Query import Network.Google.Resource.DFAReporting.DirectorySiteContacts.Get import Network.Google.Resource.DFAReporting.DirectorySiteContacts.List import Network.Google.Resource.DFAReporting.DirectorySites.Get import Network.Google.Resource.DFAReporting.DirectorySites.Insert import Network.Google.Resource.DFAReporting.DirectorySites.List import Network.Google.Resource.DFAReporting.DynamicTargetingKeys.Delete import Network.Google.Resource.DFAReporting.DynamicTargetingKeys.Insert import Network.Google.Resource.DFAReporting.DynamicTargetingKeys.List import Network.Google.Resource.DFAReporting.EventTags.Delete import Network.Google.Resource.DFAReporting.EventTags.Get import Network.Google.Resource.DFAReporting.EventTags.Insert import Network.Google.Resource.DFAReporting.EventTags.List import Network.Google.Resource.DFAReporting.EventTags.Patch import Network.Google.Resource.DFAReporting.EventTags.Update import Network.Google.Resource.DFAReporting.Files.Get import Network.Google.Resource.DFAReporting.Files.List import Network.Google.Resource.DFAReporting.FloodlightActivities.Delete import Network.Google.Resource.DFAReporting.FloodlightActivities.Generatetag import Network.Google.Resource.DFAReporting.FloodlightActivities.Get import Network.Google.Resource.DFAReporting.FloodlightActivities.Insert import Network.Google.Resource.DFAReporting.FloodlightActivities.List import Network.Google.Resource.DFAReporting.FloodlightActivities.Patch import Network.Google.Resource.DFAReporting.FloodlightActivities.Update import Network.Google.Resource.DFAReporting.FloodlightActivityGroups.Get import Network.Google.Resource.DFAReporting.FloodlightActivityGroups.Insert import Network.Google.Resource.DFAReporting.FloodlightActivityGroups.List import Network.Google.Resource.DFAReporting.FloodlightActivityGroups.Patch import Network.Google.Resource.DFAReporting.FloodlightActivityGroups.Update import Network.Google.Resource.DFAReporting.FloodlightConfigurations.Get import Network.Google.Resource.DFAReporting.FloodlightConfigurations.List import Network.Google.Resource.DFAReporting.FloodlightConfigurations.Patch import Network.Google.Resource.DFAReporting.FloodlightConfigurations.Update import Network.Google.Resource.DFAReporting.InventoryItems.Get import Network.Google.Resource.DFAReporting.InventoryItems.List import Network.Google.Resource.DFAReporting.LandingPages.Delete import Network.Google.Resource.DFAReporting.LandingPages.Get import Network.Google.Resource.DFAReporting.LandingPages.Insert import Network.Google.Resource.DFAReporting.LandingPages.List import Network.Google.Resource.DFAReporting.LandingPages.Patch import Network.Google.Resource.DFAReporting.LandingPages.Update import Network.Google.Resource.DFAReporting.Languages.List import Network.Google.Resource.DFAReporting.Metros.List import Network.Google.Resource.DFAReporting.MobileCarriers.Get import Network.Google.Resource.DFAReporting.MobileCarriers.List import Network.Google.Resource.DFAReporting.OperatingSystems.Get import Network.Google.Resource.DFAReporting.OperatingSystems.List import Network.Google.Resource.DFAReporting.OperatingSystemVersions.Get import Network.Google.Resource.DFAReporting.OperatingSystemVersions.List import Network.Google.Resource.DFAReporting.OrderDocuments.Get import Network.Google.Resource.DFAReporting.OrderDocuments.List import Network.Google.Resource.DFAReporting.Orders.Get import Network.Google.Resource.DFAReporting.Orders.List import Network.Google.Resource.DFAReporting.PlacementGroups.Get import Network.Google.Resource.DFAReporting.PlacementGroups.Insert import Network.Google.Resource.DFAReporting.PlacementGroups.List import Network.Google.Resource.DFAReporting.PlacementGroups.Patch import Network.Google.Resource.DFAReporting.PlacementGroups.Update import Network.Google.Resource.DFAReporting.Placements.Generatetags import Network.Google.Resource.DFAReporting.Placements.Get import Network.Google.Resource.DFAReporting.Placements.Insert import Network.Google.Resource.DFAReporting.Placements.List import Network.Google.Resource.DFAReporting.Placements.Patch import Network.Google.Resource.DFAReporting.Placements.Update import Network.Google.Resource.DFAReporting.PlacementStrategies.Delete import Network.Google.Resource.DFAReporting.PlacementStrategies.Get import Network.Google.Resource.DFAReporting.PlacementStrategies.Insert import Network.Google.Resource.DFAReporting.PlacementStrategies.List import Network.Google.Resource.DFAReporting.PlacementStrategies.Patch import Network.Google.Resource.DFAReporting.PlacementStrategies.Update import Network.Google.Resource.DFAReporting.PlatformTypes.Get import Network.Google.Resource.DFAReporting.PlatformTypes.List import Network.Google.Resource.DFAReporting.PostalCodes.Get import Network.Google.Resource.DFAReporting.PostalCodes.List import Network.Google.Resource.DFAReporting.Projects.Get import Network.Google.Resource.DFAReporting.Projects.List import Network.Google.Resource.DFAReporting.Regions.List import Network.Google.Resource.DFAReporting.RemarketingLists.Get import Network.Google.Resource.DFAReporting.RemarketingLists.Insert import Network.Google.Resource.DFAReporting.RemarketingLists.List import Network.Google.Resource.DFAReporting.RemarketingLists.Patch import Network.Google.Resource.DFAReporting.RemarketingLists.Update import Network.Google.Resource.DFAReporting.RemarketingListShares.Get import Network.Google.Resource.DFAReporting.RemarketingListShares.Patch import Network.Google.Resource.DFAReporting.RemarketingListShares.Update import Network.Google.Resource.DFAReporting.Reports.CompatibleFields.Query import Network.Google.Resource.DFAReporting.Reports.Delete import Network.Google.Resource.DFAReporting.Reports.Files.Get import Network.Google.Resource.DFAReporting.Reports.Files.List import Network.Google.Resource.DFAReporting.Reports.Get import Network.Google.Resource.DFAReporting.Reports.Insert import Network.Google.Resource.DFAReporting.Reports.List import Network.Google.Resource.DFAReporting.Reports.Patch import Network.Google.Resource.DFAReporting.Reports.Run import Network.Google.Resource.DFAReporting.Reports.Update import Network.Google.Resource.DFAReporting.Sites.Get import Network.Google.Resource.DFAReporting.Sites.Insert import Network.Google.Resource.DFAReporting.Sites.List import Network.Google.Resource.DFAReporting.Sites.Patch import Network.Google.Resource.DFAReporting.Sites.Update import Network.Google.Resource.DFAReporting.Sizes.Get import Network.Google.Resource.DFAReporting.Sizes.Insert import Network.Google.Resource.DFAReporting.Sizes.List import Network.Google.Resource.DFAReporting.SubAccounts.Get import Network.Google.Resource.DFAReporting.SubAccounts.Insert import Network.Google.Resource.DFAReporting.SubAccounts.List import Network.Google.Resource.DFAReporting.SubAccounts.Patch import Network.Google.Resource.DFAReporting.SubAccounts.Update import Network.Google.Resource.DFAReporting.TargetableRemarketingLists.Get import Network.Google.Resource.DFAReporting.TargetableRemarketingLists.List import Network.Google.Resource.DFAReporting.TargetingTemplates.Get import Network.Google.Resource.DFAReporting.TargetingTemplates.Insert import Network.Google.Resource.DFAReporting.TargetingTemplates.List import Network.Google.Resource.DFAReporting.TargetingTemplates.Patch import Network.Google.Resource.DFAReporting.TargetingTemplates.Update import Network.Google.Resource.DFAReporting.UserProFiles.Get import Network.Google.Resource.DFAReporting.UserProFiles.List import Network.Google.Resource.DFAReporting.UserRolePermissionGroups.Get import Network.Google.Resource.DFAReporting.UserRolePermissionGroups.List import Network.Google.Resource.DFAReporting.UserRolePermissions.Get import Network.Google.Resource.DFAReporting.UserRolePermissions.List import Network.Google.Resource.DFAReporting.UserRoles.Delete import Network.Google.Resource.DFAReporting.UserRoles.Get import Network.Google.Resource.DFAReporting.UserRoles.Insert import Network.Google.Resource.DFAReporting.UserRoles.List import Network.Google.Resource.DFAReporting.UserRoles.Patch import Network.Google.Resource.DFAReporting.UserRoles.Update import Network.Google.Resource.DFAReporting.VideoFormats.Get import Network.Google.Resource.DFAReporting.VideoFormats.List {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the DCM/DFA Reporting And Trafficking API service. type DFAReportingAPI = InventoryItemsListResource :<|> InventoryItemsGetResource :<|> PlacementStrategiesInsertResource :<|> PlacementStrategiesListResource :<|> PlacementStrategiesPatchResource :<|> PlacementStrategiesGetResource :<|> PlacementStrategiesDeleteResource :<|> PlacementStrategiesUpdateResource :<|> CampaignCreativeAssociationsInsertResource :<|> CampaignCreativeAssociationsListResource :<|> RemarketingListSharesPatchResource :<|> RemarketingListSharesGetResource :<|> RemarketingListSharesUpdateResource :<|> LandingPagesInsertResource :<|> LandingPagesListResource :<|> LandingPagesPatchResource :<|> LandingPagesGetResource :<|> LandingPagesDeleteResource :<|> LandingPagesUpdateResource :<|> MobileCarriersListResource :<|> MobileCarriersGetResource :<|> CreativeGroupsInsertResource :<|> CreativeGroupsListResource :<|> CreativeGroupsPatchResource :<|> CreativeGroupsGetResource :<|> CreativeGroupsUpdateResource :<|> RemarketingListsInsertResource :<|> RemarketingListsListResource :<|> RemarketingListsPatchResource :<|> RemarketingListsGetResource :<|> RemarketingListsUpdateResource :<|> AccountActiveAdSummariesGetResource :<|> UserRolePermissionGroupsListResource :<|> UserRolePermissionGroupsGetResource :<|> AccountsListResource :<|> AccountsPatchResource :<|> AccountsGetResource :<|> AccountsUpdateResource :<|> ReportsCompatibleFieldsQueryResource :<|> ReportsFilesListResource :<|> ReportsFilesGetResource :<|> ReportsInsertResource :<|> ReportsListResource :<|> ReportsPatchResource :<|> ReportsGetResource :<|> ReportsRunResource :<|> ReportsDeleteResource :<|> ReportsUpdateResource :<|> CampaignsInsertResource :<|> CampaignsListResource :<|> CampaignsPatchResource :<|> CampaignsGetResource :<|> CampaignsUpdateResource :<|> DynamicTargetingKeysInsertResource :<|> DynamicTargetingKeysListResource :<|> DynamicTargetingKeysDeleteResource :<|> AccountUserProFilesInsertResource :<|> AccountUserProFilesListResource :<|> AccountUserProFilesPatchResource :<|> AccountUserProFilesGetResource :<|> AccountUserProFilesUpdateResource :<|> CreativesInsertResource :<|> CreativesListResource :<|> CreativesPatchResource :<|> CreativesGetResource :<|> CreativesUpdateResource :<|> DimensionValuesQueryResource :<|> RegionsListResource :<|> FloodlightConfigurationsListResource :<|> FloodlightConfigurationsPatchResource :<|> FloodlightConfigurationsGetResource :<|> FloodlightConfigurationsUpdateResource :<|> ConversionsBatchinsertResource :<|> FloodlightActivitiesInsertResource :<|> FloodlightActivitiesListResource :<|> FloodlightActivitiesPatchResource :<|> FloodlightActivitiesGetResource :<|> FloodlightActivitiesGeneratetagResource :<|> FloodlightActivitiesDeleteResource :<|> FloodlightActivitiesUpdateResource :<|> UserRolesInsertResource :<|> UserRolesListResource :<|> UserRolesPatchResource :<|> UserRolesGetResource :<|> UserRolesDeleteResource :<|> UserRolesUpdateResource :<|> AccountPermissionGroupsListResource :<|> AccountPermissionGroupsGetResource :<|> AdvertisersInsertResource :<|> AdvertisersListResource :<|> AdvertisersPatchResource :<|> AdvertisersGetResource :<|> AdvertisersUpdateResource :<|> CountriesListResource :<|> CountriesGetResource :<|> AccountPermissionsListResource :<|> AccountPermissionsGetResource :<|> UserProFilesListResource :<|> UserProFilesGetResource :<|> OperatingSystemVersionsListResource :<|> OperatingSystemVersionsGetResource :<|> ChangeLogsListResource :<|> ChangeLogsGetResource :<|> CitiesListResource :<|> LanguagesListResource :<|> TargetableRemarketingListsListResource :<|> TargetableRemarketingListsGetResource :<|> PlatformTypesListResource :<|> PlatformTypesGetResource :<|> BrowsersListResource :<|> ContentCategoriesInsertResource :<|> ContentCategoriesListResource :<|> ContentCategoriesPatchResource :<|> ContentCategoriesGetResource :<|> ContentCategoriesDeleteResource :<|> ContentCategoriesUpdateResource :<|> PlacementsInsertResource :<|> PlacementsGeneratetagsResource :<|> PlacementsListResource :<|> PlacementsPatchResource :<|> PlacementsGetResource :<|> PlacementsUpdateResource :<|> MetrosListResource :<|> OrderDocumentsListResource :<|> OrderDocumentsGetResource :<|> CreativeFieldsInsertResource :<|> CreativeFieldsListResource :<|> CreativeFieldsPatchResource :<|> CreativeFieldsGetResource :<|> CreativeFieldsDeleteResource :<|> CreativeFieldsUpdateResource :<|> TargetingTemplatesInsertResource :<|> TargetingTemplatesListResource :<|> TargetingTemplatesPatchResource :<|> TargetingTemplatesGetResource :<|> TargetingTemplatesUpdateResource :<|> EventTagsInsertResource :<|> EventTagsListResource :<|> EventTagsPatchResource :<|> EventTagsGetResource :<|> EventTagsDeleteResource :<|> EventTagsUpdateResource :<|> FilesListResource :<|> FilesGetResource :<|> UserRolePermissionsListResource :<|> UserRolePermissionsGetResource :<|> PlacementGroupsInsertResource :<|> PlacementGroupsListResource :<|> PlacementGroupsPatchResource :<|> PlacementGroupsGetResource :<|> PlacementGroupsUpdateResource :<|> OrdersListResource :<|> OrdersGetResource :<|> ConnectionTypesListResource :<|> ConnectionTypesGetResource :<|> CreativeAssetsInsertResource :<|> SitesInsertResource :<|> SitesListResource :<|> SitesPatchResource :<|> SitesGetResource :<|> SitesUpdateResource :<|> PostalCodesListResource :<|> PostalCodesGetResource :<|> OperatingSystemsListResource :<|> OperatingSystemsGetResource :<|> SizesInsertResource :<|> SizesListResource :<|> SizesGetResource :<|> AdsInsertResource :<|> AdsListResource :<|> AdsPatchResource :<|> AdsGetResource :<|> AdsUpdateResource :<|> ProjectsListResource :<|> ProjectsGetResource :<|> SubAccountsInsertResource :<|> SubAccountsListResource :<|> SubAccountsPatchResource :<|> SubAccountsGetResource :<|> SubAccountsUpdateResource :<|> VideoFormatsListResource :<|> VideoFormatsGetResource :<|> CreativeFieldValuesInsertResource :<|> CreativeFieldValuesListResource :<|> CreativeFieldValuesPatchResource :<|> CreativeFieldValuesGetResource :<|> CreativeFieldValuesDeleteResource :<|> CreativeFieldValuesUpdateResource :<|> DirectorySitesInsertResource :<|> DirectorySitesListResource :<|> DirectorySitesGetResource :<|> AdvertiserGroupsInsertResource :<|> AdvertiserGroupsListResource :<|> AdvertiserGroupsPatchResource :<|> AdvertiserGroupsGetResource :<|> AdvertiserGroupsDeleteResource :<|> AdvertiserGroupsUpdateResource :<|> DirectorySiteContactsListResource :<|> DirectorySiteContactsGetResource :<|> FloodlightActivityGroupsInsertResource :<|> FloodlightActivityGroupsListResource :<|> FloodlightActivityGroupsPatchResource :<|> FloodlightActivityGroupsGetResource :<|> FloodlightActivityGroupsUpdateResource
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/DFAReporting.hs
mpl-2.0
108,660
0
207
22,544
11,890
8,546
3,344
2,542
0
{-# 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.Compute.URLMaps.Validate -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Runs static validation for the UrlMap. In particular, the tests of the -- provided UrlMap will be run. Calling this method does NOT create the -- UrlMap. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.urlMaps.validate@. module Network.Google.Resource.Compute.URLMaps.Validate ( -- * REST Resource URLMapsValidateResource -- * Creating a Request , urlMapsValidate , URLMapsValidate -- * Request Lenses , umvURLMap , umvProject , umvPayload ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.urlMaps.validate@ method which the -- 'URLMapsValidate' request conforms to. type URLMapsValidateResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "urlMaps" :> Capture "urlMap" Text :> "validate" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] URLMapsValidateRequest :> Post '[JSON] URLMapsValidateResponse -- | Runs static validation for the UrlMap. In particular, the tests of the -- provided UrlMap will be run. Calling this method does NOT create the -- UrlMap. -- -- /See:/ 'urlMapsValidate' smart constructor. data URLMapsValidate = URLMapsValidate' { _umvURLMap :: !Text , _umvProject :: !Text , _umvPayload :: !URLMapsValidateRequest } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'URLMapsValidate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'umvURLMap' -- -- * 'umvProject' -- -- * 'umvPayload' urlMapsValidate :: Text -- ^ 'umvURLMap' -> Text -- ^ 'umvProject' -> URLMapsValidateRequest -- ^ 'umvPayload' -> URLMapsValidate urlMapsValidate pUmvURLMap_ pUmvProject_ pUmvPayload_ = URLMapsValidate' { _umvURLMap = pUmvURLMap_ , _umvProject = pUmvProject_ , _umvPayload = pUmvPayload_ } -- | Name of the UrlMap resource to be validated as. umvURLMap :: Lens' URLMapsValidate Text umvURLMap = lens _umvURLMap (\ s a -> s{_umvURLMap = a}) -- | Project ID for this request. umvProject :: Lens' URLMapsValidate Text umvProject = lens _umvProject (\ s a -> s{_umvProject = a}) -- | Multipart request metadata. umvPayload :: Lens' URLMapsValidate URLMapsValidateRequest umvPayload = lens _umvPayload (\ s a -> s{_umvPayload = a}) instance GoogleRequest URLMapsValidate where type Rs URLMapsValidate = URLMapsValidateResponse type Scopes URLMapsValidate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient URLMapsValidate'{..} = go _umvProject _umvURLMap (Just AltJSON) _umvPayload computeService where go = buildClient (Proxy :: Proxy URLMapsValidateResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/URLMaps/Validate.hs
mpl-2.0
3,924
0
17
961
476
285
191
77
1
module Language.Interpreter.Dao.TestSuite where import Prelude hiding (error, undefined, print, putStr, putStrLn) import Language.Interpreter.Dao --import Control.Arrow import Control.Concurrent import Control.Exception import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans --import Data.Array.IArray import Data.Char import Data.Function import Data.List (stripPrefix, intercalate) import Data.List.NonEmpty (NonEmpty(..)) import Data.Semigroup import qualified Data.Text as Strict import qualified Data.Text.IO as Strict import System.Directory import System.Environment import System.IO.Unsafe import System.IO hiding (print, putStr, putStrLn) --import Debug.Trace ---------------------------------------------------------------------------------------------------- verbose :: Bool verbose = True report :: (Monad m, MonadIO m) => String -> m () report = liftIO . if verbose then putStrLn else const $ return () error :: String -> void error = throw . TestSuiteException . Strict.pack defaultTestConfigPath :: FilePath defaultTestConfigPath = "./dao-test-suite.config" ---------------------------------------------------------------------------------------------------- type ShortSwitch = Char type LongSwitch = String checkCommandLineParam :: ShortSwitch -> LongSwitch -> [String] -> IO (Maybe String, [String]) checkCommandLineParam short long args = loop id args where loop back = \ case a : b : ax | a == '-':short:"" || a == "--"++long -> return (Just b, back ax) a : ax -> let param = "--" ++ long ++ "=" in case stripPrefix param a of Nothing -> loop (back . (a :)) ax Just str -> return (Just str, back ax) [] -> return (Nothing, back []) checkCommandLineFlag :: Maybe ShortSwitch -> LongSwitch -> [String] -> IO (Maybe Bool, [String]) checkCommandLineFlag short long args = loop id args where loop back = \ case ('-':a:"") : ax | Just a == short -> return (Just True, back ax) a : ax | a == "--"++long -> return (Just True , back ax) a : ax | a == "--no-"++long -> return (Just False, back ax) a : ax -> loop (back . (a :)) ax [] -> return (Nothing, back []) ---------------------------------------------------------------------------------------------------- type TestLabel = String -- | Construct this type with the name of the function in which the failure occurred. Before -- throwing this exception, it is a good idea to call 'report' with an explanation of what went -- wrong. newtype TestSuiteException = TestSuiteException Strict.Text deriving (Eq, Ord) instance Show TestSuiteException where show (TestSuiteException msg) = "TEST FAILED on function " ++ Strict.unpack msg instance Exception TestSuiteException where {} stdoutLock :: MVar Handle stdoutLock = unsafePerformIO $ newMVar stdout {-# NOINLINE stdoutLock #-} putStr :: String -> IO () putStr msg = modifyMVar_ stdoutLock $ \ h -> do hSetBuffering h $ BlockBuffering $ Just 4096 hPutStr h msg hFlush h >>= evaluate return h putStrLn :: String -> IO () putStrLn = putStr . (++ "\n") >=> evaluate print :: Show a => a -> IO () print = putStrLn . show >=> evaluate ---------------------------------------------------------------------------------------------------- type Timeout t = t newtype TimeoutException = TimeoutException Float deriving (Eq, Ord, Show, Read, Num, Fractional) instance Exception TimeoutException where {} -- | 1.0 seconds. t1sec :: Timeout (Maybe Float) t1sec = Just 1.0 -- | 5.0 seconds. t5sec :: Timeout (Maybe Float) t5sec = Just 5.0 -- | 12.0 seconds. t12sec :: Timeout (Maybe Float) t12sec = Just 12.0 -- | 60.0 seconds. t60sec :: Timeout (Maybe Float) t60sec = Just 60.0 ---------------------------------------------------------------------------------------------------- data TestCount = TestCount { succeededTests :: !Int , failedTests :: !Int , startedTests :: !Int } deriving (Eq, Ord) instance Show TestCount where show (TestCount{ succeededTests=ok, failedTests=fail, startedTests=ntests }) = let total = ok + fail in if ntests == 0 then "(no results yet)" else show ok ++ " passed, " ++ show fail ++ " failed (" ++ percent ok total ++ "), completed " ++ show total ++ " of " ++ show ntests ++ " tests (" ++ percent total ntests ++ ")" instance Exception TestCount where {} percent :: Int -> Int -> String percent ok total = if total == 0 then "%" else let (lo, hi) = splitAt 2 $ show (round (realToFrac ok * 1000.0 / realToFrac total :: Float) :: Int) in reverse $ '%' : lo ++ '.' : hi testCount :: TestCount testCount = TestCount{ succeededTests = 0, failedTests = 0, startedTests = 0 } testsComplete :: TestCount -> Bool testsComplete tc = failedTests tc + succeededTests tc == startedTests tc incTestCount :: TestCount -> TestCount incTestCount tc = tc{ startedTests = startedTests tc + 1 } incSucceeded :: TestCount -> TestCount incSucceeded tc = tc{ succeededTests = succeededTests tc + 1 } incFailed :: TestCount -> TestCount incFailed tc = tc{ failedTests = failedTests tc + 1 } ---------------------------------------------------------------------------------------------------- data AsyncCtrl = AsyncCtrl { asyncSemaphore :: MVar (), asyncCount :: MVar TestCount } data TimerControlException = TimerReset | TimerStop | TimerHaltAll deriving (Eq, Ord, Enum, Show) instance Exception TimerControlException where {} newAsyncCtrl :: IO AsyncCtrl newAsyncCtrl = AsyncCtrl <$> newEmptyMVar <*> newMVar testCount asyncReport :: TestLabel -> AsyncCtrl -> IO () asyncReport label = readMVar . asyncCount >=> putStrLn . ((label ++ ": ") ++) . show isolateAsync :: AsyncCtrl -> TestLabel -> IO void -> IO ThreadId isolateAsync ctrl label test = do modifyMVar_ (asyncCount ctrl) $ evaluate . incTestCount forkIO $ do let count f = do modifyMVar_ (asyncCount ctrl) $ evaluate . f putMVar (asyncSemaphore ctrl) () result <- catches (Right <$> test) [ Handler $ \ (SomeAsyncException e) -> count incFailed >>= evaluate >> throwIO e , Handler $ \ e@(SomeException _) -> return (Left e) ] count incSucceeded case result of Left (SomeException e) -> putStrLn $ label ++ ": " ++ show e Right{} -> return () -- | This function creates an 'AsyncCtrl' and automatically waits for all tests to finish. Simply -- pass the list of tests __without__ wrapping each test with 'isolateAsync'. This function is -- itself synchronous i.e. it will block until the entire list of tests has completedTests, although all -- tests are evaluated in parallel. isolateAsyncSequence :: TestLabel -> Timeout (Maybe Float) -> [(TestLabel, IO ())] -> IO () isolateAsyncSequence label timeout tests = do ctrl <- newAsyncCtrl threads <- sequence $ uncurry (isolateAsync ctrl) <$> tests timerThread <- case timeout of Nothing -> return Nothing Just t -> liftM Just $ forkIO $ fix $ \ loop -> do timerCtrl <- (threadDelay (round $! t * 1000000) >> return TimerHaltAll) `catches` [Handler return] case timerCtrl of TimerStop -> return () TimerReset -> loop TimerHaltAll -> forM_ threads $ flip throwTo (TimeoutException t) fix $ \ loop -> do takeMVar (asyncSemaphore ctrl) tc <- readMVar (asyncCount ctrl) let report = when verbose $ putStrLn $ label ++ ": " ++ show tc if testsComplete tc then maybe (return ()) (`throwTo` TimerStop) timerThread >> report >> when (failedTests tc > 0) (throwIO tc) else report >> maybe (return ()) (`throwTo` TimerReset) timerThread >> loop ---------------------------------------------------------------------------------------------------- -- | Isolate a test in it's own thread, with an optional time limit, evaluating synchronously so -- that this function call does not return until the test completes or times out. isolateSyncTimed :: TestLabel -> Timeout (Maybe Float) -> IO void -> IO () isolateSyncTimed label timeout test = do mvar <- newEmptyMVar thread <- forkIO $ putMVar mvar =<< catches (Right <$> test) [ Handler $ \ (SomeAsyncException e) -> throwIO e , Handler $ \ e@(SomeException _) -> return (Left e) ] case timeout of Nothing -> return () Just t -> void $ forkIO $ do threadDelay $ round $ t * 1000000 throwTo thread $ TimeoutException t takeMVar mvar >>= \ case Left (SomeException e) -> putStrLn (label ++ '\n' : show e) >> throwIO e Right{} -> return () -- | Abbreviation for 'isolateSyncTimed' with a 'Prelude.Float' literal time limit. isolateSyncT :: TestLabel -> Timeout Float -> IO void -> IO () isolateSyncT label = isolateSyncTimed label . Just -- | Abbreviation for 'isolateSyncTimed' with a one second time limit. Use this for short, simple -- tests. isolateSync :: TestLabel -> IO void -> IO () isolateSync label = isolateSyncTimed label t1sec -- | Abbreviation for 'isolateSync'. isosy :: TestLabel -> IO void -> IO () isosy = isolateSync ---------------------------------------------------------------------------------------------------- -- Begin the actual tests. ---------------------------------------------------------------------------------------------------- data TestConfig = TestConfig { only_immediate_tests :: Bool -- ^ This disables all other tests regardless of whether they are set to 'True', and executes -- the 'immediate' function. This allows you to easily write a quick test case and run it -- immediately without running all other test cases. , do_parser_tests :: Bool , do_coder_tests :: Bool , do_eval_tests :: Bool , do_pattern_tests :: Bool } deriving (Eq, Ord, Show, Read) defaultTestConfig :: TestConfig defaultTestConfig = TestConfig { only_immediate_tests = False , do_parser_tests = True , do_coder_tests = True , do_eval_tests = True , do_pattern_tests = True } ---------------------------------------------------------------------------------------------------- test1Parse :: (Eq a, Show a, Read a) => a -> String -> IO () test1Parse expected str = do let fail = error ("test1Parse " ++ show (str :: String)) let wrong re a = do report $ re++" INCORRECT, what was expected:\n " ++ show expected ++ "\nWhat was parsed:\n " ++ show a fail let cantParse msg = report msg >> fail report $ "Parse: " ++ show str a <- case readsPrec 0 str of [] -> cantParse "Parser failed entirely" [(a, str)] -> do unless (null str) $ report $ let (rem, ignor) = splitAt 40 str in "WARNING: did not parse the whole string. Remainder is:\n "++show rem++ (if null ignor then "" else "...") return a ax -> cantParse $ (++) "Ambiguous parse:\n" $ zip [1::Int ..] ax >>= \ (i, (a, str)) -> flip (++) (show i ++ ": (" ++ show a ++ ") before "++show str++"\n") $ case i of i | i <= 9 -> " " i | i <= 99 -> " " i | i <= 999 -> " " _ -> "" if a /= expected then void $ wrong "Parse" a else do report $ "Parse success." let b = show a report $ "Re-parse: " ++ show b b <- readIO b if b /= expected then void $ wrong "Re-parse" b else do report $ "Re-parse success." testParsers :: IO () testParsers = do let test expr str = isosy ("On test input string " ++ show str) $ test1Parse expr str test (DaoString "Hello, world") (show ("Hello, world" :: String)) test (DaoInt 1) "1" test (DaoFloat 123.456) "123.456" test (DaoFloat 5.0) "5f" test (DaoFloat 0.5) "0.5" test (DaoFloat 0.5) "5.0e-1" test (DaoFloat 0.5) "5.0E-1" test (DaoFloat 50.5) "5.05E+1" test (DaoFloat 50.5) "5.05e+1" test (DaoFloat 50.5) "5.05E1" test (DaoFloat 50.5) "5.05e1" let atoms = fmap (DaoAtom . plainAtom) . Strict.words let ints = fmap DaoInt let form = \ case a:ax -> plainForm (a :| ax) [] -> error "in test program, \"form\" was passed an empty list" let list = daoList let dict = daoDict test (daoForm $ atoms "hello this is dao lisp") "(hello this is dao lisp)" test (daoList $ atoms "hello this is dao lisp") "[hello this is dao lisp]" test (daoForm $ atoms "one two three" ++ DaoFloat 123.456 : ints [4,5,6]) "(one two three 123.456 4 5 6)" test (daoForm [DaoVoid, DaoVoid]) "(()())" test (daoForm [DaoNull, DaoNull]) "([][])" test (daoForm1 [daoForm1 [DaoVoid]]) "((()))" test (daoForm1 [daoForm1 $ atoms "hello world"]) "((hello world))" test (daoForm $ atoms "TRUE FALSE" ++ [DaoTrue, DaoNull] ++ atoms "TRUE abc" ++ DaoVoid : DaoAtom "X123" : [] ) "(TRUE FALSE true false TRUE abc () X123)" test (dict [("one", DaoInt 1), ("two", DaoInt 2), ("three", DaoInt 3)]) "{ :three 3 :two 2 : one 1 }" test (dict [ ("-->", DaoString "arrow") , (":" , DaoString "colon") , ("," , DaoString "comma") , (";" , DaoString "semicolon") ]) "{ :--> \"arrow\" :: \"colon\" :, \"comma\" :; \"semicolon\" }" test (daoForm $ atoms "testing testing" ++ ints [1,2,3]) "(testing testing 1 2 3)" test (daoForm [DaoComma, DaoComma, DaoComma, DaoSemi, DaoSemi, DaoSemi, DaoColon, DaoColon, DaoColon] ) "(,,,;;;:::)" test (daoError "TestError" [("blame", DaoInt 0), ("suggest", DaoString "nothing")]) "error TestError {:blame 0 :suggest \"nothing\"}" let any = pattern1 $ patConst $ Single AnyExpr test (daoRule (atoms "d1 d2") (atoms "p1 p2") 0.1 any (form $ atoms "some action")) "rule [d1 d2] [p1 p2] 0.1 (any) (some action)" test (daoRule [] [] 2.0 any (form $ atoms "some action")) "rule 2.0 (any) (some action)" test (daoRule (atoms "d1") [] 30.0 any (form $ atoms "some action")) "rule [d1] (any) (some action) 30.0" test (daoRule (atoms "d1") (atoms "p1 p2 p3") 444.4 any (form $ atoms "some action")) "rule [d1] (any) (some action) 444.4 [p1 p2 p3]" test (daoRule (atoms "d1 d2") (atoms "p1") 5.0e-5 any (form $ atoms "some action")) "rule (any) 5.0e-5 [d1 d2] (some action) [p1]" isosy "form parser" $ test1Parse (daoForm $ atoms "one two -> three" ++ DaoTrue : DaoNull : ints [1,2,3] ++ DaoString "Hello, world!" : atoms "ten ==> twenty thirty" ++ ints [10,20,30] ++ DaoFloat 123.456 : (list $ atoms "four five || six" ++ ints [4,5,6] ++ DaoString "This is Dao Lisp!" : daoError "TestError" [("blame", DaoInt 0), ("suggest", DaoString "nothing")] : dict [] : atoms "forty fifty sixty" ++ ints [40,50,60] ++ [] ) : DaoFloat 456.789 : dict [("one", DaoInt 1), ("two", DaoInt 2), ("three", DaoInt 3)] : [] ) ( "(one two -> three true false 1 2 3 \"Hello, world!\" ten " ++ " ==> twenty thirty 10 20 30 123.456\n" ++ " [four five || six 4 5 6 \"This is Dao Lisp!\" " ++ " (error TestError {:blame 0 :suggest \"nothing\"})\n" ++ " {} forty fifty sixty 40 50 60]\n" ++ " 456.789 { :three 3 :two 2 :one 1})" ) ---------------------------------------------------------------------------------------------------- test1FormCoder :: (Eq a, Show a, Inlining a, Outlining a) => a -> [DaoExpr] -> IO () test1FormCoder expr expected = isosy ("On test input form " ++ show expr) $ do let fail = error $ "test1FormCoder " ++ show expected report $ "Encode: " ++ show expr ++ "\nExpecting: " ++ show expected let inlined = inlining expr when (inlined /= expected) $ do report $ (++) "Encoder incorrect.\nReturned: " . showList inlined . (++) "\nExpected: " . showList expected $ "" fail report $ "Decode: " ++ showList inlined ("\nExpecting: " ++ show expr) case runOutliner outline inlined of (MatchQuit err, rem) -> do report $ "Decoder backtracked: " ++ show err ++ "\nRemaining: " ++ show rem fail (MatchFail err, rem) -> do report $ "Decoder failed: " ++ show err ++ "\nRemaining: " ++ show rem fail (MatchOK decoded, rem) -> do when (expr /= decoded) $ do report $ (++) "Decoder incorrect.\nReturned: " $ showParen True (showsPrec 0 decoded) $ "\nExpected: " ++ show expr ++ "\nRemaining: " ++ show rem fail unless (null rem) $ do report $ (++) "WARNING, after decoding " $ showParen True (showsPrec 0 decoded) $ " there are unused arguments in the decoder stack:\n" ++ show rem report $ (++) "Encode/Decode OK: " . showList inlined . (++) " == " . showParen True (showsPrec 0 decoded) $ "" testCoders :: IO () testCoders = do let atoms = fmap (DaoAtom . plainAtom) . Strict.words let form = \ case [] -> error "In TestSuite main \"testCoders\": passed empty list to \"form\"" a:ax -> plainForm $ a :| ax let typf = form $ atoms "call some function" -- ExprPatUnit test1FormCoder (EqExpr $ DaoInt 1234) [DaoAtom "==", DaoInt 1234] test1FormCoder (NotEqExpr $ DaoString "Hello, world!") [DaoAtom "/=", DaoString "Hello, world!"] test1FormCoder (IsPrimType DaoVoidType) [DaoAtom "type==", DaoAtom "Void"] test1FormCoder (IsNotPrimType DaoNullType) [DaoAtom "type/=", DaoAtom "Null"] test1FormCoder (IsPrimType DaoIntType) [DaoAtom "type==", DaoAtom "Int"] test1FormCoder (IsNotPrimType DaoDictType) [DaoAtom "type/=", DaoAtom "Dict"] test1FormCoder (IsPrimType DaoCharType) [DaoAtom "type==", DaoAtom "Char"] test1FormCoder (AnyPrimType $ plainList $ DaoVoidType :| [DaoIntType]) [DaoAtom "type==", daoList $ atoms "Void Int"] test1FormCoder AnyExpr [DaoAtom "any"] test1FormCoder (TestExpr typf) [DaoAtom "$", DaoForm typf] -- GenPatternUnit ExprPatUnit let anyOfTyp = plainList $ DaoFloatType :| [DaoCharType] let testGenUnits = [ (CheckOnce, DaoAtom "*", DaoAtom "?") , (CheckLazy, DaoAtom "*?", DaoAtom "??") , (CheckGreedy, DaoAtom "*!", DaoAtom "?!") ] >>= \ (k, ka, kb) -> [ ( Single AnyExpr, [DaoAtom "any"]) , ( Single (TestExpr typf), [DaoAtom "$", DaoForm typf]) , ( AtMost 2 5 k AnyExpr , [DaoAtom "any", ka, DaoInt 2, DaoInt 5, DaoAtom "!"] ) , ( AtMost 3 6 k $ TestExpr typf , [DaoAtom "$", DaoForm typf, ka, DaoInt 3, DaoInt 6, DaoAtom "!"] ) , ( Single (IsPrimType DaoVoidType) , [DaoAtom "type==", DaoAtom "Void"] ) , ( Single (AnyPrimType anyOfTyp) , [DaoAtom "type==", daoList (atoms "Flo Char")] ) , ( ZeroOrOne k $ IsPrimType DaoVoidType , [DaoAtom "type==", DaoAtom "Void", kb] ) , ( ZeroOrOne k $ AnyPrimType anyOfTyp , [DaoAtom "type==", daoList (atoms "Flo Char"), kb] ) , ( AtLeast 123 k $ IsPrimType DaoVoidType , [DaoAtom "type==", DaoAtom "Void", ka, DaoInt 123] ) , ( AtLeast 0 k $ AnyPrimType anyOfTyp , [DaoAtom "type==", daoList (atoms "Flo Char"), ka, DaoInt 0] ) , ( AtMost 123 4567 k $ IsPrimType DaoVoidType , [DaoAtom "type==", DaoAtom "Void", ka, DaoInt 123, DaoInt 4567, DaoAtom "!"] ) , ( AtMost 0 3 k $ AnyPrimType anyOfTyp , [DaoAtom "type==", daoList (atoms "Flo Char"), ka, DaoInt 0, DaoInt 3, DaoAtom "!"] ) , ( FewerThan 123 4567 k $ IsPrimType DaoVoidType , [DaoAtom "type==", DaoAtom "Void", ka, DaoInt 123, DaoInt 4567] ) , ( FewerThan 0 3 k $ AnyPrimType anyOfTyp , [DaoAtom "type==", daoList (atoms "Flo Char"), ka, DaoInt 0, DaoInt 3] ) ] sequence_ $ fmap (uncurry test1FormCoder) testGenUnits let testTyped = testGenUnits >>= \ (obj, expr) -> [ (TypedPattern obj typf, expr ++ [DaoColon, DaoForm typf]) , (UntypedPattern obj, expr) ] sequence_ $ fmap (uncurry test1FormCoder) testTyped let testNamed = testTyped >>= \ (obj, expr) -> [ (NamedPattern "varname" obj, DaoColon : DaoAtom "varname" : case obj of UntypedPattern{} -> expr TypedPattern{} -> [daoForm expr] ) , (PatConst obj, expr) ] sequence_ $ fmap (uncurry test1FormCoder) testNamed let chunkNamed = \ case a:b:c:d:e:f:g:h:i:j:more -> [a] : [b,c] : [d,e,f] : [g,h,i,j] : chunkNamed more [] -> [] final -> [final] let seqPats = do (patvars, expr) <- unzip <$> chunkNamed testNamed case patvars of [] -> [] a:ax -> [(GenPatternSequence $ plainList (a :| ax), intercalate [DaoComma] expr)] sequence_ $ fmap (uncurry test1FormCoder) seqPats let chunkSeqPats = \ case a:b:c:d:more -> [a] : [b,c,d] : chunkSeqPats more [] -> [] final -> [final] let choicePats = do (patseqs, expr) <- unzip <$> chunkSeqPats seqPats case patseqs of [] -> [] a:ax -> [(GenPatternChoice $ plainList (a :| ax), intercalate [DaoSemi] expr)] sequence_ $ fmap (uncurry test1FormCoder) choicePats ---------------------------------------------------------------------------------------------------- testEnv :: Environment testEnv = newEnvironment $ extendBuiltins [ bif "print" $ DaoStrict $ matchAll $ lift . daoVoid . (filterEvalForms >=> liftIO . Strict.putStrLn . ("(print) " <>) . strInterpolate) ] runEval :: DaoEval DaoExpr -> IO DaoExpr runEval = evalDaoExprIO testEnv eval1 :: DaoExpr -> DaoExpr -> IO () eval1 fncall expecting = isosy ("testing evaluator:\n " ++ show fncall) $ do putStrLn $ "(eval " ++ show fncall ++ ")" result <- evalDaoIO testEnv fncall putStrLn $ "[result " ++ show result ++ "]" unless (result == expecting) $ error $ "[expecting " ++ show expecting ++ "]" testEvaluator :: IO () testEvaluator = do eval1 (daoFnCall "print" [DaoString "Hello, world!"]) DaoVoid eval1 (daoFnCall "+" $ DaoInt <$> [1,2,3,4,5]) (DaoInt 15) eval1 (daoFnCall "<=" $ DaoInt <$> [1,2,3,4,5]) DaoTrue eval1 (daoFnCall ">=" $ DaoInt <$> [5,4,3,2,1]) DaoTrue eval1 (daoFnCall "+" $ DaoInt <$> [1,2,3,4,0]) (DaoInt 10) eval1 (daoFnCall "<=" $ DaoInt <$> [1,2,3,4,0]) DaoNull eval1 (daoFnCall ">=" $ DaoInt <$> [4,3,2,1,5]) DaoNull eval1 (daoFnCall "interpolate" $ DaoString <$> ["Hello", ",", "world!"]) (DaoString "Hello,world!") flip eval1 DaoVoid $ daoFnCall "print" $ [ DaoString "\n [1,2,3,4,5] -> sum = " , daoFnCall "+" $ DaoInt <$> [1,2,3,4,5] , DaoString ", increasing? = " , daoFnCall "<=" $ DaoInt <$> [1,2,3,4,5] , DaoString "\n [1,2,3,4,0] -> sum = " , daoFnCall "+" $ DaoInt <$> [1,2,3,4,0] , DaoString ", increasing? = " , daoFnCall "<=" $ DaoInt <$> [1,2,3,4,0] , DaoString "\n (interpolate Hello, world!) = " , daoFnCall "interpolate" $ DaoString <$> ["Hello", ",", "world!"] ] let wdict = plainDict [("one", DaoInt 1), ("two", DaoInt 2), ("three", DaoInt 3)] let wlist = plainList $ DaoString "zero" :| (DaoString <$> ["one", "two", "three"]) eval1 (daoFnCall "get" [DaoAtom "two", DaoDict wdict]) (DaoInt 2) eval1 (daoFnCall "get" [DaoInt 1, DaoList wlist]) (DaoString "one") eval1 (daoFnCall "put" [DaoAtom "four", DaoInt 4, DaoDict wdict]) (DaoDict $ insertDict wdict [("four", DaoInt 4)]) eval1 (daoFnCall "put" [DaoInt 2, DaoString "TWO", DaoList wlist]) (DaoList $ insertList wlist [(2, DaoString "TWO")]) eval1 (daoFnCall "get" [daoList [DaoAtom "two", DaoAtom "one"], DaoDict wdict]) (daoList [DaoInt 2, DaoInt 1]) eval1 (daoFnCall "get" [daoList [DaoInt 1, DaoInt 2], DaoList wlist]) (daoList [DaoString "one", DaoString "two"]) eval1 ( daoFnCall "put" [ daoList [DaoColon, DaoAtom "four", DaoInt 4, DaoColon, DaoAtom "five", DaoInt 5] , DaoDict wdict ] ) (DaoDict $ insertDict wdict [("four", DaoInt 4), ("five", DaoInt 5)]) eval1 ( daoFnCall "put" [ daoList [DaoColon, DaoInt 2, DaoString "TWO", DaoColon, DaoInt 3, DaoString "THREE"] , DaoList wlist ] ) (DaoList $ insertList wlist [(2, DaoString "TWO"), (3, DaoString "THREE")]) match1 :: Show pat => (pat -> RuleMatcher DaoExpr) -> pat -> [DaoExpr] -> (MatchResult DaoExpr -> Maybe Error) -> IO () match1 execPat pat expr check = isosy ("testing pattern match: " ++ show pat) $ do putStrLn $ "(match) " ++ showList expr "\n(against) " ++ show pat result <- runEval $ do result <- runRuleMatcher (execPat pat) expr case check result of Just err -> throw err Nothing -> return $ DaoString $ Strict.pack $ "( Match success, got expected result:\n " ++ show result ++ "\n)" case result of DaoError err -> throw err DaoString str -> Strict.putStrLn str result -> print result expectOK :: DaoExpr -> MatchResult DaoExpr -> Maybe Error expectOK expect result = case result of MatchFail err -> Just err MatchQuit err -> Just err MatchOK value -> if expect == value then Nothing else Just $ plainError "test-suite" [("expecting", dao $ MatchOK expect), ("result", dao result)] expectQuit :: Atom -> MatchResult DaoExpr -> Maybe Error expectQuit clas result = case result of MatchQuit err -> if clas == getErrorClass err then Nothing else Just err MatchFail err -> Just err MatchOK {} -> Just $ plainError "test-suite" [("expecting", daoError clas []), ("result", dao result)] expectFail :: Atom -> MatchResult DaoExpr -> Maybe Error expectFail clas result = case result of MatchFail err -> if clas == getErrorClass err then Nothing else Just err MatchQuit err -> Just err MatchOK {} -> Just $ plainError "test-suite" [("expecting", daoError clas []), ("result", dao result)] testPatterns :: IO () testPatterns = do match1 matchExprPatUnit AnyExpr [DaoAtom "Success!"] (expectOK $ DaoAtom "Success!") match1 matchExprPatUnit AnyExpr [] (expectQuit "matching") match1 matchExprPatUnit (EqExpr $ DaoAtom "Success!") [DaoAtom "Success!"] (expectOK $ DaoAtom "Success!") match1 matchExprPatUnit (EqExpr $ DaoAtom "Success!") [DaoString "Shouldn't match!"] (expectQuit "pattern-match") match1 matchExprPatUnit (EqExpr $ DaoAtom "Success!") [] (expectQuit "matching") let fiveInts = DaoInt <$> [1,2,3,4,5] match1 matchGenPatternUnit' (AtLeast 3 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectOK $ daoList fiveInts) match1 matchGenPatternUnit' (AtLeast 5 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectOK $ daoList fiveInts) match1 matchGenPatternUnit' (AtLeast 6 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectQuit "matching") match1 matchGenPatternUnit' (AtLeast 3 CheckOnce $ IsPrimType DaoStringType) fiveInts (expectQuit "pattern-match") match1 matchGenPatternUnit' (AtLeast 3 CheckOnce $ IsPrimType DaoStringType) fiveInts (expectQuit "pattern-match") match1 matchGenPatternUnit' (AtLeast 0 CheckOnce $ IsPrimType DaoStringType) fiveInts (expectOK DaoNull) match1 matchGenPatternUnit' (FewerThan 0 3 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectOK $ daoList $ DaoInt <$> [1,2,3]) match1 matchGenPatternUnit' (FewerThan 0 3 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectOK $ daoList $ DaoInt <$> [1,2,3]) match1 matchGenPatternUnit' (FewerThan 0 3 CheckOnce $ IsPrimType DaoStringType) fiveInts (expectOK DaoNull) match1 matchGenPatternUnit' (FewerThan 1 3 CheckOnce $ IsPrimType DaoStringType) fiveInts (expectQuit "pattern-match") match1 matchGenPatternUnit' (FewerThan 6 7 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectQuit "matching") match1 matchGenPatternUnit' (FewerThan 5 7 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectOK $ daoList fiveInts) match1 matchGenPatternUnit' (AtMost 0 5 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectOK $ daoList fiveInts) match1 matchGenPatternUnit' (AtMost 0 4 CheckOnce $ IsPrimType DaoIntType) fiveInts (expectQuit "matching") match1 (flip matchTypedPattern return) ( TypedPattern (FewerThan 0 5 CheckOnce $ IsPrimType DaoIntType) (plainFnCall "?" [DaoAtom "<="]) ) fiveInts (expectOK $ daoList fiveInts) match1 (flip matchTypedPattern return) ( TypedPattern (FewerThan 0 5 CheckOnce $ IsPrimType DaoIntType) (plainFnCall "?" [DaoAtom ">="]) ) fiveInts (expectQuit "predicate") ---------------------------------------------------------------------------------------------------- usage :: String usage = unlines [ "<General Parameters>" , "" , " -? --help :" , " Print this document and exit immediately." , "" , " -i --immediate :" , " Disable all other tests and run only \"immediate\" tests" , "" , " -N <path> --new-config=<path> :" , " Create a new default configuration file at the given path," , " overwriting any existing configuration file without asking," , " and then exit immediately. If <path> is \".\", the default" , " configuration file is created in the currrent directory." , "" , "<Configuration file parameters>" , "" , " -c <path> --config=<path> :" , " Will read parameters from configuration file at the given path" , " and proceed with testing." , "" , " (The default config file path is "++show defaultTestConfigPath++")" , "" , "<Enabling/Disabling Tests>" , "" , " * Command line parameters override settings in the configuration file." , "" , " * If the default configuration file does not exist, all tests are" , " enabled by default." , "" , " --parsers --no-parsers : enable/disable parsing tests" , " --coders --no-coders : enable/disable coding tests" ] main :: IO () main = do (help, args) <- getArgs >>= checkCommandLineFlag (Just '?') "help" (newcfg, args) <- checkCommandLineParam 'N' "new-config" args help <- case help of Just True -> hPutStrLn stderr usage >> return True _ -> return False newcfg <- case newcfg of Just path -> do path <- pure $ if path == "." || path == "./" then defaultTestConfigPath else path writeFile path (show defaultTestConfig) return True _ -> return False unless (help || newcfg) $ do (customConfig, args) <- checkCommandLineParam 'c' "config" args let configPath = maybe defaultTestConfigPath id customConfig configExists <- doesFileExist configPath configured <- if configExists then readsPrec 0 <$> readFile configPath >>= \ case [(config, str)] | dropWhile isSpace str == "" -> return config _ -> fail $ "could not parse config file at path " ++ show configPath else return defaultTestConfig (doImmed , args) <- checkCommandLineFlag (Just 'i') "immediate" args (doParsers, args) <- checkCommandLineFlag Nothing "parsers" args (doCoders , _args) <- checkCommandLineFlag Nothing "coders" args configured <- pure $ configured { only_immediate_tests = maybe id const doImmed $ only_immediate_tests configured , do_parser_tests = maybe id const doParsers $ do_parser_tests configured , do_coder_tests = maybe id const doCoders $ do_coder_tests configured , do_eval_tests = maybe id const doCoders $ do_eval_tests configured , do_pattern_tests = maybe id const doCoders $ do_pattern_tests configured } let doTest lbl test f = if test configured then report ("\n<<<< " ++ lbl ++ " Tests >>>>\n") >> f else report ("(Configured to Skip " ++ lbl ++ " Tests.)") if only_immediate_tests configured then do report "\n<<<< IMMEDIATE TESTING MODE >>>>\n(All other tests are now disabled.)\n\n" immediate else do doTest "Parser" do_parser_tests testParsers doTest "Coders" do_coder_tests testCoders doTest "Evaluator" do_eval_tests testEvaluator doTest "Patterns" do_pattern_tests testPatterns ---------------------------------------------------------------------------------------------------- -- | This test allows you to quickly write an independent test case directly into the source code -- right here, and enable this test in the configuration file, or by the command line parameters. -- When this test is enabled, all other tests are disabled, allowing you to focus on a single -- problem. immediate :: IO () immediate = do ---------------------------------------------------------------------------------------------- o let wdict = plainDict [("one", DaoInt 1), ("two", DaoInt 2), ("three", DaoInt 3)] eval1 ( daoFnCall "put" [ daoList [DaoColon, DaoAtom "four", DaoInt 4, DaoColon, DaoAtom "five", DaoInt 5] , DaoDict wdict ] ) (DaoDict $ insertDict wdict [("four", DaoInt 4), ("five", DaoInt 5)]) ---------------------------------------------------------------------------------------------- o return ()
RaminHAL9001/Dao
src/Language/Interpreter/Dao/TestSuite.hs
agpl-3.0
33,488
0
23
7,982
10,482
5,269
5,213
-1
-1
module AbsoluteVal where absoluteVal :: Int -> Int absoluteVal a = if a > 0 then a else -a
thewoolleyman/haskellbook
04/09/chad/AbsoluteVal.hs
unlicense
92
0
6
20
35
20
15
3
2
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module Lib where import Data.Type.Equality import GHC.Base (Type) {- Writing and using proofs in Haskell September 27,2018 see also: “Proving stuff in Haskell” by Mads Buch - uses propositional equality to prove a theorem by showing that two haskell types are actually the same type e.g., a+b=b+a -} ------------------------------------------------------------------------------ -- Peano numbers data Nat = Z -- base | S Nat -- inductive ("recursive") {- values Z and S Z have type : Nat kinds 'Z and 'S 'Z have kind : Nat (not *) -- via DataKinds - they do not have any inhabitants - can circumvent that restriction (below)) could also write: data Z data S a but ability to unite those two types under a kind The Nat definition enables writing Nat in GADT and type family declarations ------------------------------------------------------------------------------ Type equality : two types are equal : propositional equality from Data.Type.Equality data a :~: b where Refl :: a :~: a ------------------------------------------------------------------------------ Type-level functions closed type family -} type family a + b where a + 'Z = a -- (1) a + 'S b = 'S (a + b) -- (2) {- The kind of this type family is deduced to be Nat -> Nat -> Nat ------------------------------------------------------------------------------ a proof -} -- type checker uses (1) to infer Z + Z = Z, where a = Z testEquality1 :: ('Z + 'Z) :~: 'Z testEquality1 = Refl -- testEquality 2 and 3 prove PLUS RIGHT IDENTITY -- type checker uses (1) to infer a + Z = Z, where a = a testEquality2 :: (a + 'Z) :~: a testEquality2 = Refl -- type checker uses (2) testEquality3 :: (a + 'S b) :~: 'S (a + b) testEquality3 = Refl {- PLUS LEFT IDENTITY needs more work. prove Z + a = a via induction on a initial thought: baseCase :: (Z + Z) :~: Z baseCase = Refl induction :: (Z + S a) :~: S a induction = ??? -- need to be able to use one proof in order to prove another one Data.Type.Equality -- given Refl proving a is same type as b -- and something of type r that could use the knowledge that a is b -- then type checker can infer r is well typed gcastWith :: (a :~: b) -> (a ~ b => r) -> r -} helper :: ('S 'Z + 'S 'Z) :~: 'S ('S 'Z + 'Z) -- this proposition is proved helper = Refl -- above proposition used to prove this proposition useHelper :: ('S 'Z + 'S 'Z) :~: 'S ('S 'Z) useHelper = gcastWith helper Refl {- ('S 'Z + 'S 'Z) :~: 'S ('S 'Z + 'Z) -> (Refl => r) -> 'S ('S 'Z) | | | v v v (a :~: b) -> (a ~ b => r) -> r Refl in useHelper says : I have S Z + S Z equal to S (S Z + Z) - from (1) : S Z + Z is S Z above is for concrete values need to prove forall : recurse to base case need to reflect a type to a value Idris : {a:Nat} -> (Z + S a) :~: S a ------------------------------------------------------------------------------ Singletons : 1-1 mapping between values and types -} data SNat :: Nat -> Type where SZ :: SNat 'Z SS :: SNat a -> SNat ('S a) {- type of SZ is SNat Z type of SS (SS (SZ)) is SNat (S (S Z)) ------------------------------------------------------------------------------ prove PLUS LEFT IDENTITY using SNat with induction base case type checks because - Refl value says (Z + Z) ~ Z -- via (1) - 'a' is Z is because 1st parameter is SZ :: SNat Z, so a ~ Z - similar to Idris: {a:Nat} -> (Z + S a) :~: S a -} plusLeftId :: SNat a -> ('Z + a) :~: a -- base case : a ~ Z plusLeftId SZ = Refl {- induction step : need to now prove for every type S a, assuming proof stands for a use the singleton for the successor: SS plusLeftId :: SNat a -> (Z + a) :~: a plusLeftId SZ = Refl plusLeftId (SS n) = Refl • Could not deduce: ('Z + n) ~ n from the context: m ~ 'S n bound by a pattern with constructor: SS :: forall (m :: Nat). SNat m -> SNat ('S m), in an equation for ‘plusLeftId’ need to tell type checker that the equality holds for n use gcastWith -} plusLeftId (SS n) = gcastWith (plusLeftId n) Refl {- (Z + n) :~: n -> Refl -> n | | | v v v (a :~: b) -> (a ~ b => r) -> r Here, Refl is the r, and, according to the error message, we need a ~ (Z + n) and b ~ n, or even better (Z + n) :~: n. But that’s the result type of plusLeftId itself, if we called it with n: -} callPlusLeftId :: 'S ('S ('S 'Z)) :~: 'S ('S ('S 'Z)) callPlusLeftId = plusLeftId (SS (SS (SS SZ))) {- ------------------------------------------------------------------------------ rewrite proof of PLUS RIGHT IDENTITY and axioms automatically got from type family, to use values: -} given1 :: SNat a -> (a + 'Z) :~: a given1 _ = Refl given2 :: SNat a -> SNat b -> (a + 'S b) :~: 'S (a + b) given2 _ _ = Refl plusRightId :: SNat a -> (a + 'Z) :~: a plusRightId = given1 plusRightId' :: SNat a -> (a + 'Z) :~: a plusRightId' n = gcastWith (given1 n) Refl {- ------------------------------------------------------------------------------ Proofs with multiple steps left identity in mathematical notation 0 + S(a) = S(0 + a) -- by (2) = S( a) -- by the induction hypothesis in Haskell Z + (S n) = S (Z + n) -- using type family definition = S n -- proved what is inside the S in previous line inductively ------------------------------------------------------------------------------ proof : ASSOCIATIVITY OF ADDITION : (a + b) + c = a + (b + c) -} (!+) :: SNat n -> SNat m -> SNat (n + m) n !+ SZ = n n !+ (SS m) = SS (n !+ m) {- BASE CASE, given a and b, c = 0 (a + b) + 0 step1: a + b -- by (1) for a + b step2: a + (b + 0) -- by (1) for b using x and y to clarify not talking about a and b: just defining steps based on two numbers step1 - need to use (1) : must pass something of type SNat n where n is type x + y (using singletons !+ step 2 - extract the part of the expression that we want to “transform” to something else - then use another proof function to drive the process want type ((a + b) + Z) :~: (a + (b + Z)) have types ((a + b) + Z) :~: (a + b) (a + b) :~: (a + (b + Z)) i.e., if type x same as type y, and type y same as type z, then type x same as type z -} (==>) :: a :~: b -> b :~: c -> a :~: c -- transitive property of :~: (propositional equality). Refl ==> Refl = Refl plusAssoc :: SNat a -> SNat b -> SNat c -> ((a + b) + c) :~: (a + (b + c)) plusAssoc a b SZ = let step1 :: SNat x -> SNat y -> ((x + y) + 'Z) :~: (x + y) step1 x y = gcastWith (given1 (x !+ y)) Refl -- (1) step2 :: SNat x -> SNat y -> (x + y) :~: (x + (y + 'Z)) step2 _x y = gcastWith (given1 y) Refl -- (1) in step1 a b ==> step2 a b {- ------------------------------------------------------------------------------ INDUCTIVE CASE, assuming (a + b) + c = a + (b + c) (a + b) + S(c) S((a + b) + c) -- by (2) S(a + (b + c)) -- by the induction hypothesis a + S(b + c) -- by (2) a + (b + S(c)) -- by (2) -} plusAssoc a b (SS c) = let step1 :: SNat x -> SNat y -> SNat ('S z) -> ((x + y) + 'S z) :~: 'S ((x + y) + z) step1 x y (SS z) = gcastWith (given2 (x !+ y) (SS z)) Refl -- (2) step2 :: SNat x -> SNat y -> SNat z -> 'S ((x + y) + z) :~: 'S (x + (y + z)) step2 x y z = gcastWith (plusAssoc x y z) Refl -- induction step3 :: SNat x -> SNat y -> SNat z -> 'S (x + (y + z)) :~: (x + 'S (y + z)) step3 x y z = gcastWith (given2 x (y !+ z)) Refl -- (2) step4 :: SNat x -> SNat y -> SNat z -> (x + 'S (y + z)) :~: (x + (y + 'S z)) step4 _ y z = gcastWith (given2 y z) Refl -- (2) in step1 a b (SS c) ==> step2 a b c ==> step3 a b c ==> step4 a b c ------------------------------------------------------------------------------ -- since all of above except are inferred automatically by the + type family -- only the induction step is needed to help the second step type-check plusAssocX :: SNat a -> SNat b -> SNat c -> ((a + b) + c) :~: (a + (b + c)) plusAssocX _ _ SZ = Refl plusAssocX a b (SS c) = gcastWith (plusAssoc a b c) Refl {- ------------------------------------------------------------------------------ using ScopedTypeVariables - use a forall in the let to bring fresh variables in scope - then define the steps inside it - using same names in the types so that we don’t have to pass variables to each step: -} plusAssocY :: SNat a -> SNat b -> SNat c -> ((a + b) + c) :~: (a + (b + c)) plusAssocY a b SZ = let proof :: forall x y . SNat x -> SNat y -> ((x + y) + 'Z) :~: (x + (y + 'Z)) proof x y = step1 ==> step2 where step1 :: ((x + y) + 'Z) :~: (x + y) step1 = gcastWith (given1 (x !+ y)) Refl step2 :: (x + y) :~: (x + (y + 'Z)) step2 = gcastWith (given1 y) Refl in proof a b plusAssocY a b (SS c) = let proof :: forall x y z . SNat x -> SNat y -> SNat z -> ((x + y) + 'S z) :~: (x + (y + 'S z)) proof x y z = step1 ==> step2 ==> step3 ==> step4 where step1 :: ((x + y) + 'S z) :~: 'S ((x + y) + z) step1 = gcastWith (given2 (x !+ y) (SS z)) Refl step2 :: 'S ((x + y) + z) :~: 'S (x + (y + z)) step2 = gcastWith (plusAssoc x y z) Refl step3 :: 'S (x + (y + z)) :~: (x + 'S (y + z)) step3 = gcastWith (given2 x (y !+ z)) Refl step4 :: (x + 'S (y + z)) :~: (x + (y + 'S z)) step4 = gcastWith (given2 y z) Refl in proof a b c {- ------------------------------------------------------------------------------ Commutativity Here’s the proof (in mathematical notation) for the property of commutativity of addition. What we want to prove is a+b=b+a: The base case b=0 is the left identity property. For the second base case b=1: First we prove it for a=0, which gives 0+1=1+0, the right identity property. Then we prove inductively, assuming a+1=1+a: = = = = = = S(a)+1S(a)+S(0)S(S(a)+0)S((a+1)+0)S(a+1)S(1+a)1+S(a)by definition of natural numbersby (2)by definition of natural numbersas proved by the base case for b=0by the induction hypothesisby (2) For the induction, assuming a+b=b+a: = = = = = = = a+S(b)a+(b+1)(a+b)+1(b+a)+1b+(a+1)b+(1+a)(b+1)+aS(b)+aby definition of natural numbersby associativityby the induction hypothesisby associativityby the base case for b=1by associativityby definition of natural numbers The proof is left as an exercise, but using the same pattern as in the associativity proof it should be pretty straightforward. The signature should be: plusComm :: SNat a -> SNat b -> (a + b) :~: (b + a) The proof (and even more proofs) can be found in the repo. Using the proofs It was a bit difficult to find a use case for the proofs on addition, but I quickly found an issue trying to append two length-indexed vectors. The vector definition and several operations are more or less the same as the ones in the Stitch paper: data Vec :: Nat -> * -> * where V0 :: Vec Z a (:>) :: a -> Vec n a -> Vec (S n) a infixr 5 :> I’m not going to go into detail here, but the most important part is that this vector type has its length in its type as extra information, and we need to reason about the length when manipulating it. One common example is appending two vectors. It is apparent that if one has length n and the other has length m, then the resulting vector will have length n + m. A naive first attemt would be the following: append :: Vec n a -> Vec m a -> Vec (n + m) a append V0 ys = ys append (x:>xs) ys = undefined -- let's wait for now But even the base case fails to typecheck: • Could not deduce: ('Z + m) ~ m from the context: n ~ 'Z The error says that the only concrete information we have is n ~ Z, because the first vector is the empty vector. And because we return ys, which has length m, the resulting type Z + m should be the same as m, but the type checker is not convinced. Let’s notice that what we need is to use the left identity property, and convince the checker: append :: Vec n a -> Vec m a -> Vec (n + m) a append V0 ys = gcastWith (plusLeftId ?) ys append (x:>xs) ys = undefined -- let's wait for now There is one important part missing: the actual length. All our proofs used singletons to help drive the checking process, but here there is no mention of a singleton. So let’s add it for now, and later we’ll try to make this process implicit. We’ll explicitly pass the lengths of both vectors: append :: SNat n -> SNat m -> Vec n a -> Vec m a -> Vec (n + m) a append SZ m V0 ys = gcastWith (plusLeftId m) ys append n m (x:>xs) ys = undefined -- let's wait for now OK, this works. Let’s try to do the next case where the first vector is nonempty. We’ll make it fail just to see the error message: append :: SNat n -> SNat m -> Vec n a -> Vec m a -> Vec (n + m) a append SZ m V0 ys = gcastWith (plusLeftId m) ys append n m (x:>xs) ys = x :> append ? m xs ys Uh-oh. How do we get the length of the first vector after we remove the first element? Luckily, that’s just n - 1. Let’s create a helper function to get the predecessor number of a singleton of Nat: spred :: SNat (S n) -> SNat n spred (SS n) = n This function is total, because there is no need for the case spred SZ. As a matter of fact, it wouldn’t type check because it would mean trying to do SZ :: SNat (S n) which doesn’t make sense. And because the first vector in the second case of append is not empty, we know that n is not SZ but SS .... append :: SNat n -> SNat m -> Vec n a -> Vec m a -> Vec (n + m) a append SZ m V0 ys = gcastWith (plusLeftId m) ys append n m (x:>xs) ys = x :> append (spred n) m xs ys This time we get this error: • Could not deduce: ('S n1 + m) ~ 'S (n1 + m) from the context: n ~ 'S n1 Where n1 is the type of the result of spred n. Let’s construct a proof for that: We need to prove S(a)+b=S(a+b). We can do an inductive proof which will be quicker (in the repo I use an inductive proof), but let’s try to do it in one pass: = = = S(a)+bb+S(a)S(b+a)S(a+b)by commutativityby (2)by commutativity And in Haskell: append :: SNat n -> SNat m -> Vec n a -> Vec m a -> Vec (n + m) a append SZ m V0 ys = gcastWith (plusIdenL m) ys append n m (x:>xs) ys = gcastWith (proof pn m) $ x :> app (spred n) m xs ys where pn = spred n proof :: forall x y. SNat x -> SNat y -> (S x + y) :~: S (x + y) proof x y = step1 ==> step2 ==> step3 where step1 :: (S x + y) :~: (y + S x) step1 = gcastWith (plusComm (SS x) y) Refl step2 :: (y + S x) :~: S (y + x) step2 = gcastWith (given2 y (SS x)) Refl step3 :: S (y + x) :~: S (x + y) step3 = gcastWith (plusComm y x) Refl And that’s the proof. Now appending two vectors should work. First, here’s an instance of Show for Vec: instance (Show a) => Show (Vec n a) where show v = "[" ++ go v where go :: (Show a') => Vec n' a' -> String go v = case v of V0 -> "]" (x :> xs) -> show x ++ sep ++ go xs where sep = case xs of V0 -> "" _ -> ", " And two example vectors: x = 1 :> 2 :> 3 :> 4 :> V0 lengthX = SS (SS (SS (SS SZ))) y = 5 :> 6 :> 7 :> 8 :> 9 :> V0 lengthY = SS (SS (SS (SS (SS SZ)))) > append lengthX lengthY x y [1, 2, 3, 4, 5, 6, 7, 8, 9] > :t append lengthX lengthY x y append lengthX lengthY x y :: Vec ('S ('S ('S ('S ('S ('S ('S ('S ('S 'Z))))))))) Integer We can also remove the need to have the length in a variable beforehand. To do that, we have to resort to type classes (again, this is described in the Stitch paper). We will construct a type class with a single method that can magically give an SNat depending on the instance we are using: class IsNat (n :: Nat) where nat :: SNat n instance IsNat Z where nat = SZ instance IsNat n => IsNat (S n) where nat = SS nat Then we can just use nat to get the length. The instance of IsNat to use is resolved thanks to the fact that the n in the constraint IsNat is the same n that is the vector length: vlength :: IsNat n => Vec n a -> SNat n vlength _ = nat > append (vlength x) (vlength y) x y [1, 2, 3, 4, 5, 6, 7, 8, 9] But I promised that we can have the length passed implicitly. Again, we’ll use the typeclass with some help from TypeApplications and ScopedTypeVariables: (+++) :: forall n m a. (IsNat n, IsNat m) => Vec n a -> Vec m a -> Vec (n + m) a (+++) = append (nat @n) (nat @m) > x +++ y [1, 2, 3, 4, 5, 6, 7, 8, 9] -}
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/type-level/2018-09-alex-peitsinis-writing-and-using-proofs/src/Lib.hs
unlicense
17,361
0
19
4,805
2,264
1,175
1,089
109
1
{-# LANGUAGE OverloadedStrings #-} module Main(main) where import Generator import Data.Text (Text) import Control.Applicative ((<$>)) import Control.Exception (fromException, handle, SomeException) import Control.Monad (forM_, forever, replicateM) import Control.Monad.Writer (liftIO) import Control.Concurrent (MVar, newMVar, modifyMVar_, readMVar, threadDelay) import System.Random (randomIO) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Network.WebSockets as WS -- |Client is a combination of the statement that we're running and the -- WS connection that we can send results to type Client = (Text, WS.Connection) -- |Server state is simply an array of active @Client@s type ServerState = [Client] -- |Named function that retuns an empty @ServerState@ newServerState :: ServerState newServerState = [] -- |Adds new client to the server state addClient :: Client -- ^ The client to be added -> ServerState -- ^ The current state -> ServerState -- ^ The state with the client added addClient client clients = client : clients -- |Removes an existing client from the server state removeClient :: Client -- ^ The client being removed -> ServerState -- ^ The current state (hopefully with the client included) -> ServerState -- ^ The state with the client removed removeClient client = filter ((/= fst client) . fst) -- |The handler for the application's work application :: MVar ServerState -- ^ The server state -> WS.ServerApp -- ^ The server app that will handle the work application state pending = do conn <- WS.acceptRequest pending query <- WS.receiveData conn clients <- liftIO $ readMVar state let client = (query, conn) case generator (T.unpack query) of Left err -> WS.sendTextData conn (T.pack $ show err) Right gen -> do { modifyMVar_ state $ return . addClient client ; perform state client gen } -- |Performs the query on behalf of the client, cleaning up after itself when the client disconnects perform :: MVar ServerState -- ^ The server state -> Client -- ^ The client tuple (the query to perform and the connection for the responses) -> Generator () -- ^ The value generator -> IO () -- ^ The output perform state client@(query, conn) gen = handle catchDisconnect $ do runGenerator gen threadDelay (\numbers -> WS.sendTextData conn (T.pack $ show numbers)) WS.sendClose conn (T.pack "") removeClient' state client where catchDisconnect :: SomeException -> IO () catchDisconnect _ = removeClient' state client removeClient' :: MVar ServerState -> Client -> IO () removeClient' state client = liftIO $ modifyMVar_ state $ return . removeClient client -- |The main entry point for the WS application main :: IO () main = do putStrLn "Server is running" state <- newMVar newServerState WS.runServer "0.0.0.0" 9160 $ application state
eigengo/hwsexp
ws/main/Main.hs
apache-2.0
3,020
0
14
664
665
357
308
53
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} -- | This assumes environment variables for the Github authentication -- information, `GITHUB_USER` and `GITHUB_PASSWD`. module Main where import Control.Applicative import Control.Error import Control.Monad.Writer import qualified Data.ByteString.Char8 as BS import Data.DList (toList) import Data.Monoid import qualified Data.Text as T import Data.Time import Github.Api import Github.Data import Github.Review import Network.URI import System.Environment import Text.Printf org :: GithubAccount org = GithubOrgName "scholarslab" samplePeriod :: Integer samplePeriod = 1 sampleMin :: Int sampleMin = 10 shortLine :: RepoCommit -> String shortLine (Repo{..}, Commit{..}) = let GitCommit{..} = commitGitCommit sha = take 8 commitSha commitDate = show . fromGithubDate $ gitUserDate gitCommitCommitter commitMessage = fromMaybe "<no commit message>" . listToMaybe $ lines gitCommitMessage url = maybe "<invalid URI>" (show . toGithubUri) $ parseURI commitUrl in printf "%s/%s: %s [%s] %s <%s>" (githubOwnerLogin repoOwner) repoName sha commitDate commitMessage url main :: IO () main = do user <- getEnv "GITHUB_USER" passwd <- getEnv "GITHUB_PASSWD" let auth = GithubBasicAuth (BS.pack user) (BS.pack passwd) getCommits = getAllRepoCommits' (Just auth) Nothing (item, log) <- runGithubInteraction 5 3 False 50 $ do repos <- getAccountRepos org limit <- liftIO $ offsetByDays samplePeriod <$> getCurrentTime allCommits <- sortByCommitDate . concat <$> mapM (`getCommits` sampleMin) repos liftIO $ putStrLn "Add commits." >> mapM_ (putStrLn . shortLine) allCommits let limited = getAfterOrMinimum (getCommitDate . snd) limit sampleMin allCommits liftIO $ putStrLn "\nShort list." >> mapM_ (putStrLn . shortLine) limited hoistEitherT . bimapEitherT (UserError . T.unpack) id $ pickRandom limited case item of Right x -> putStrLn "" >> putStrLn (shortLine x) >> print x Left e -> putStrLn $ "ERROR @" <> T.unpack (last log) <> ": " <> show e
erochest/gitreview-core
test/GitReviewTest.hs
apache-2.0
2,681
0
16
956
611
311
300
59
2