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 Elems where import Prelude hiding (elem) import Data.Set (Set (..)) ----------------------------------------------------------------------------- -- | 1. Reasoning about the Set of Elements in a List ----------------------- ----------------------------------------------------------------------------- -- | The set of `elems` of a list {-@ measure elems :: [a] -> (Set a) elems ([]) = (Set_empty 0) elems (x:xs) = (Set_cup (Set_sng x) (elems xs)) @-} -- | A few handy aliases {-@ predicate EqElts Xs Ys = elems Xs = elems Ys @-} {-@ predicate UnElts Xs Ys Zs = elems Xs = Set_cup (elems Ys) (elems Zs) @-} -- | Reasoning about `append` and `reverse` {-@ append :: xs:_ -> ys:_ -> {v:_ | UnElts v xs ys} @-} append [] ys = ys append (x:xs) ys = x : append xs ys {-@ reverse :: xs:_ -> {v:_ | EqElts v xs} @-} reverse xs = revAcc xs [] where revAcc [] acc = acc revAcc (x:xs) acc = revAcc xs (x:acc) -- But, there are limitations... {-@ append' :: xs:_ -> ys:_ -> {v:_ | UnElts v xs ys} @-} append' xs ys = foldr (:) ys xs ----------------------------------------------------------------------------- -- | 2. Checking for duplicates (xmonad) ------------------------------------ ----------------------------------------------------------------------------- -- | Is a list free of duplicates? {-@ measure nodups :: [a] -> Prop nodups ([]) = true nodups (x:xs) = (not (Set_mem x (elems xs)) && nodups xs) @-} -- | Weeding out duplicates. {-@ nub :: xs:_ -> {v:_ | nodups v && EqElts v xs} @-} nub xs = go xs [] where go (x:xs) l | x `elem` l = go xs l | otherwise = go xs (x:l) go [] l = l {-@ elem :: x:_ -> ys:_ -> {v:Bool | Prop v <=> Set_mem x (elems ys)} @-} elem x [] = False elem x (y:ys) = x == y || elem x ys ----------------------------------------------------------------------------- -- | 3. Associative Lookups ------------------------------------------------- ----------------------------------------------------------------------------- -- The dread "key-not-found". How can we fix it? find key ((k,v) : kvs) | key == k = v | otherwise = find key kvs find _ [] = die "Key not found! Lookup failed!" {-@ die :: {v:_ | false} -> b @-} die x = error x ---------------------------------------------------------------------------- -- | CHEAT AREA ------------------------------------------------------------ ---------------------------------------------------------------------------- {-@ predicate ValidKey K M = Set_mem K (keys M) @-} {-@ measure keys :: [(a, b)] -> (Set a) keys ([]) = (Set_empty 0) keys (kv:kvs) = (Set_cup (Set_sng (fst kv)) (keys kvs)) @-} -- # START ERRORS 2 (find, append') -- # END ERRORS 1 (append') {-@ find :: k:_ -> {m:_ | ValidKey k m} -> _ @-}
mightymoose/liquidhaskell
docs/slides/BOS14/hs/start/01_Elements.hs
bsd-3-clause
2,909
0
10
651
375
207
168
21
2
import Control.Monad import Data.List.Extra import Data.Maybe elf n = e where e = n*10 : replicate (n-1) 0 ++ e elves n = zipWith (+) (elf n) (0 : elves (n+1)) presents n = sum [if n `mod` i == 0 then i*10 else 0 | i <- [1..n `div` 2]] + (n*10) -- This is vastly too slow.
msullivan/advent-of-code
2015/A20a.hs
mit
282
2
10
68
170
89
81
9
2
import AI import Text.CSV import Data.List import System.Random import Text.Printf dataRowToTestData :: Record -> ([Double],[Double]) dataRowToTestData row = let nums = map (\(x,i) -> case i of -- convert 55th,56th and 57th column into range 0..1 -- otherwise large values cause troubles 55 -> ((read x) / 1200) 56 -> ((read x) / 10000) 57 -> ((read x) / 20000) _ -> read x ) (zip row [0..]) input = init nums output = [ last nums ] in (input,output) percentCorrect :: [ [ Double ] ] -> [ [ Double ] ] -> Double percentCorrect targets predictions = let numCorrect = length $ filter ( \(target,prediction) -> (round (head target)) == (round (head prediction)) ) $ zip targets predictions in (fromIntegral (100 * numCorrect)) / (genericLength targets) validateNNDataset :: NeuralNetwork -> [([Double],[Double])] -> Double validateNNDataset n ds = let (targets,predictions) = runNNDataset n ds in percentCorrect targets predictions main = do result <- parseCSVFromFile "spambase.data" case result of Left e -> putStrLn $ show e Right csv -> do -- last record is empty due to final \n, so we use (init csv) let dataSet = map dataRowToTestData (init csv) -- use 75% of rows for training and the rest for testing the performance let (trainDS,testDS) = splitAt 3451 dataSet let (n,gen') = createNN3 (mkStdGen 1) 57 60 1 let n' = trainNNDataset 0.1 n trainDS putStrLn $ printf "%.2f%%" $ validateNNDataset n' testDS
abresas/ai
tests/spambase/spambase.hs
mit
1,640
1
18
467
543
279
264
35
4
{-# LANGUAGE GADTs #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} module Ch20 where import Prelude hiding (not) import Data.Maybe import Data.Typeable -- We want to say: -- -- data D where Lam :: (D -> D) -> D -- -- but if we did this alone, we'd have no way to observe any value -- of type D; the only thing we'd be able to do would be to feed it -- another D as input, to no (observable) avail. So, we dirty our -- abstraction as below. data D x where Lam :: (D x -> D x) -> D x -- for observing convenience only... Prim :: (x -> x) -> D x Base :: x -> D x -- For niceness when constructing terms λ = Lam unD :: D x -> (D x -> D x) unD (Lam d) = d -- the ugly cases... unD (Prim f) = \case Base x -> Base (f x) Lam _ -> error "cannot apply primitive operation to lambda" Prim _ -> error "cannot apply primitive operation to another primitive operation" unD (Base _) = error "cannot apply primitive type as a function" infixl 9 · (·) :: D x -> D x -> D x (·) = unD -- Manipulating isomorphisms within a Scott domain class Scotty x t | t -> x where scrunch :: t -> D x stretch :: D x -> t instance Scotty x (D x) where scrunch = id stretch = id instance (Scotty x t, Scotty x s) => Scotty x (t -> s) where scrunch f = Lam (scrunch . f . stretch) stretch f = stretch . unD f . scrunch -- "Beam me up, Dr. Scott!" beam :: forall x t s. (Scotty x t, Scotty x s) => t -> s beam = stretch . scrunch type E = D Integer example :: E -> (E -> (E -> E) -> E) -> ((E -> E) -> E) -> ((E -> E) -> E) example = beam (Lam id) -- "Take me to church!" toChurchNum :: (Ord x, Num x) => x -> D x toChurchNum x | x > 0 = inc · toChurchNum (x - 1) toChurchNum x | x <= 0 = zero fromChurchNum :: (Enum x, Num x) => D x -> x fromChurchNum f = case f · Prim succ · Base 0 of Base x -> x Prim _ -> error "can't convert primitive operation to base type" Lam _ -> error $ "you can take the church out of the lambda, " ++ "but you can't take the lambda out of the church" -- natural numbers zero = λ $ \s -> λ $ \z -> z inc = λ $ \n -> λ $ \s -> λ $ \z -> --n · s · (s · z) s · (n · s · z) dec = λ $ \n -> λ $ \s -> λ $ \z -> n · (λ $ \g -> λ $ \h -> h · (g · s)) · (λ $ \u -> z) · (λ $ \u -> u) plus = λ $ \m -> λ $ \n -> λ $ \s -> λ $ \z -> m · s · (n · s · z) times = λ $ \m -> λ $ \n -> λ $ \s -> λ $ \z -> m · (n · s) · z -- booleans true = λ $ \f -> λ $ \t -> t false = λ $ \f -> λ $ \t -> f not = λ $ \b -> λ $ \f -> λ $ \t -> b · t · f isZero = λ $ \n -> n · (λ $ \_ -> true) · false leq = λ $ \m -> λ $ \n -> isZero · (n · dec · m) even = λ $ \n -> n · not · true -- lists nil = λ $ \c -> λ $ \n -> n cons = λ $ \x -> λ $ \xs -> λ $ \c -> λ $ \n -> c · x · (xs · c · n) -- What's the pattern? Hmm... -- Encoding general recursion -- This won't work in Haskell, because it fails the *occurs-check*: -- yy = \f -> (\g -> f (g g)) (\g -> f (g g)) -- However, with the -rectypes flag, its analogue in OCaml will type-check: -- -- fun f -> (fun g -> f (g g)) (fun g -> f (g g)) -- -- (but as discussed last class, that variant is too strict in a CBV language -- like OCaml, so it won't terminate and you need a CBV version instead): -- -- fun f -> (fun x a -> f (x x) a) (fun x a -> f (x x) a);; -- -- Regardless, we can embed the y-combinator in Haskell, even though -- Haskell has the occurs-check! y = λ $ \f -> (λ $ \g -> f · (g · g)) · (λ $ \g -> f · (g · g)) factorial = y · (λ $ \f -> λ $ \n -> isZero · n · (inc · zero) · (times · n · (f · (dec · n)))) -- Okay, but show me something new! ackermann' 0 n = n + 1 ackermann' m 0 = ackermann' (m - 1) 1 ackermann' m n = ackermann' (m - 1) (ackermann' m (n - 1)) ackermann = y · (λ $ \a -> λ $ \m -> λ $ \n -> isZero · m · (inc · n) · (isZero · n · (a · (dec · m) · (inc · zero)) · (a · (dec · m) · (a · m · (dec · n))))) -- Random junk to make REPL interaction more convenient instance Show x => Show (D x) where show (Lam _) = "Lam _" show (Prim _) = "Prim _" show (Base x) = "Base " ++ show x instance (Ord x, Num x) => Num (D x) where fromInteger = toChurchNum . fromInteger (+) = error "not implemented" (*) = error "not implemented" (-) = error "not implemented" abs = error "not implemented" signum = error "not implemented"
plclub/cis670-16fa
code/Ch21.hs
mit
5,053
0
21
1,584
1,774
967
807
117
3
module Handler.Mooc.Admin.ReviewRequest ( getAdminReviewRequestR , postAdminReviewRequestR ) where import Data.Time.Calendar (addDays, showGregorian) import qualified Database.Persist.Sql as P import Text.Shakespeare.Text (st) import Database.Esqueleto import Handler.Mooc.Admin import Import hiding ((/=.), (==.), (=.), (<.), isNothing, on, update, groupBy, count) import Import.BootstrapUtil import qualified Network.Mail.Mime as Mail data SendReviewParams = SendReviewParams { mexpertId :: Maybe (Key User) , mtaskId :: Maybe ExerciseId , onlyBefore :: UTCTime } type TaskData = (Entity Exercise, Int) getAdminReviewRequestR :: Handler Html getAdminReviewRequestR = do requireAdmin experts <- selectExperts tasks <- selectTasks defaultDay <- lift (getCurrentTime >>= return . addDays (-7) . utctDay) (reviewRequestFormWidget, _) <- generateFormPost $ reviewRequestForm experts tasks defaultDay adminLayout "Request reviews" $ do setTitle "qua-kit - request reviews" toWidgetHead $ [cassius| .form-inline .form-group display: inline-block margin-right: 15px |] $(widgetFile "mooc/admin/review-request") postAdminReviewRequestR :: Handler Html postAdminReviewRequestR = do requireAdmin experts <- selectExperts tasks <- selectTasks ((res, _), _) <- runFormPost $ reviewRequestForm experts tasks $ ModifiedJulianDay 0 case res of (FormSuccess params) -> reviewRequest params _ -> defaultLayout [whamlet|<p>Invalid input</p>|] reviewRequestForm :: [Entity User] -> [TaskData] -> Day -> Html -> MForm Handler (FormResult SendReviewParams, Widget) reviewRequestForm experts tasks defaultDay extra = do let expertsList = ("All experts", Nothing) : map (\(Entity usrId ex) -> (userName ex, Just usrId)) experts let toOption (Entity exId ex, ugCount) = (exerciseDescription ex ++ " (" ++ (pack $ show ugCount) ++ " in need of grading)", Just exId) let tasksList = ("All tasks", Nothing) : map toOption tasks (expertRes, expertView) <- mreq (bootstrapSelectFieldList expertsList) "" Nothing (taskRes, taskView) <- mreq (bootstrapSelectFieldList tasksList) "" Nothing (onlyBeforeRes, onlyBeforeView) <- mreq bootstrapDayField "" $ Just defaultDay let toTime day = UTCTime day $ fromInteger 0 let params = SendReviewParams <$> expertRes <*> taskRes <*> fmap toTime onlyBeforeRes let widget = do [whamlet| #{extra} ^{fvInput expertView} ^{fvInput taskView} ^{fvInput onlyBeforeView} <input type=submit value="Send Mail" class="btn btn-default"> |] return (params, widget) reviewRequest :: SendReviewParams -> Handler Html reviewRequest params = do let whereTask = maybe [] (\tId -> [CurrentScenarioExerciseId P.==. tId]) (mtaskId params) scenarios <- runDB $ selectList (whereTask ++ [ CurrentScenarioGrade P.==. Nothing , CurrentScenarioLastUpdate P.<. onlyBefore params ]) [] statusTxt <- if length scenarios > 0 then do render <- getUrlRender let toLink cSc = render . submissionR $ entityVal cSc let scLinks = fmap toLink scenarios browseLink = case mtaskId params of Nothing -> render BrowseProposalsForExpertsR Just i -> render BrowseProposalsForExpertsR <> "?exercise_id=" <> tshow (P.fromSqlKey i) case mexpertId params of Just expertId -> do mexpert <- runDB $ get expertId case mexpert of Just expert -> do sendReviewRequestMail (onlyBefore params) browseLink scLinks expert return "Email sent..." Nothing -> return "Expert not found" Nothing -> do experts <- selectExperts _ <- forM experts $ \(Entity _ ex) -> sendReviewRequestMail (onlyBefore params) browseLink scLinks ex return "Emails sent..." else return "No scenarios to review. Email not sent." setMessage statusTxt redirect AdminReviewRequestR sendReviewRequestMail :: UTCTime -> Text -> [Text] -> User -> Handler () sendReviewRequestMail beforeT browseLink scLinks expert = case userEmail expert of Just email -> do let mailText = [st|Dear #{userName expert}, We would like to let you know that #{show $ length scLinks} oldest design submissions require grading in qua-kit. Please, use the following link to see them (you don't need to grade designs submitted after #{showGregorian $ utctDay beforeT}): #{browseLink} Note on grading: You can set a grade from 1 to 5 {stars}. The grade accounts for 40% of actual user grade at edX. This means 1 star is equivalent to 0.6 of edX grade and 5 stars is equivalent to 1.0 of edX grade. Therefore, setting 1 star is a normal practice; but only really outstanding solutions deserve 5 stars, because 5 stars correspond to 100% rating in qua-kit gallery. Also, in the expert review form, you have to write at least 80 characters of explanation for the grade you give. Here is the full list of currently ungraded submissions: #{unlines scLinks} Thank you for your help! |] $(logDebug) mailText mailFrom <- appMailFrom liftIO $ Mail.renderSendMail $ Mail.simpleMail' (Mail.Address Nothing email) --to address mailFrom "Please help review the following submissions" --subject $ fromStrict mailText Nothing -> return () selectExperts :: Handler [Entity User] selectExperts = runDB $ selectList [UserRole P.==. UR_EXPERT, UserEmail P./<-. [Nothing]] [] selectTasks :: Handler [TaskData] selectTasks = fmap (fmap $ second unValue) . runDB $ select $ from $ \(InnerJoin scenario scProblem) -> do on $ scenario ^. CurrentScenarioExerciseId ==. scProblem ^. ExerciseId where_ $ isNothing (scenario ^. CurrentScenarioGrade) groupBy $ scProblem ^. ExerciseId return (scProblem, count $ scenario ^. CurrentScenarioId)
achirkin/qua-kit
apps/hs/qua-server/src/Handler/Mooc/Admin/ReviewRequest.hs
mit
6,246
0
23
1,586
1,438
726
712
-1
-1
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.ResourceTracker.ResourceTrackerService (ResourceTrackerService, resourceTrackerService, RegisterNodeManager, NodeHeartbeat, UnRegisterNodeManager, registerNodeManager, nodeHeartbeat, unRegisterNodeManager) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' import qualified Hadoop.Protos.YarnServerCommonServiceProtos.RegisterNodeManagerRequestProto as YarnServerCommonServiceProtos (RegisterNodeManagerRequestProto) import qualified Hadoop.Protos.YarnServerCommonServiceProtos.NodeHeartbeatRequestProto as YarnServerCommonServiceProtos (NodeHeartbeatRequestProto) import qualified Hadoop.Protos.YarnServerCommonServiceProtos.UnRegisterNodeManagerRequestProto as YarnServerCommonServiceProtos (UnRegisterNodeManagerRequestProto) import qualified Hadoop.Protos.YarnServerCommonServiceProtos.RegisterNodeManagerResponseProto as YarnServerCommonServiceProtos (RegisterNodeManagerResponseProto) import qualified Hadoop.Protos.YarnServerCommonServiceProtos.NodeHeartbeatResponseProto as YarnServerCommonServiceProtos (NodeHeartbeatResponseProto) import qualified Hadoop.Protos.YarnServerCommonServiceProtos.UnRegisterNodeManagerResponseProto as YarnServerCommonServiceProtos (UnRegisterNodeManagerResponseProto) type ResourceTrackerService = P'.Service '[RegisterNodeManager, NodeHeartbeat, UnRegisterNodeManager] resourceTrackerService :: ResourceTrackerService resourceTrackerService = P'.Service type RegisterNodeManager = P'.Method ".hadoop.yarn.ResourceTrackerService.registerNodeManager" YarnServerCommonServiceProtos.RegisterNodeManagerRequestProto YarnServerCommonServiceProtos.RegisterNodeManagerResponseProto type NodeHeartbeat = P'.Method ".hadoop.yarn.ResourceTrackerService.nodeHeartbeat" YarnServerCommonServiceProtos.NodeHeartbeatRequestProto YarnServerCommonServiceProtos.NodeHeartbeatResponseProto type UnRegisterNodeManager = P'.Method ".hadoop.yarn.ResourceTrackerService.unRegisterNodeManager" YarnServerCommonServiceProtos.UnRegisterNodeManagerRequestProto YarnServerCommonServiceProtos.UnRegisterNodeManagerResponseProto registerNodeManager :: RegisterNodeManager registerNodeManager = P'.Method nodeHeartbeat :: NodeHeartbeat nodeHeartbeat = P'.Method unRegisterNodeManager :: UnRegisterNodeManager unRegisterNodeManager = P'.Method
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/ResourceTracker/ResourceTrackerService.hs
mit
2,700
0
7
260
304
201
103
42
1
{-# LANGUAGE OverloadedStrings #-} -- | -- Module : Text.XML.Mapping -- Copyright : (c) Joseph Abrahamson 2013 -- License : MIT -- . -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- . module Text.XML.Mapping ( decode, Tag, module X, PE.ParseError ) where import qualified Data.ByteString as S import Text.XML.Expat.Tree hiding (QName) import Text.XML.Mapping.Internal.Class as X import qualified Text.XML.Mapping.Internal.ParseError as PE import Text.XML.Mapping.Internal.Parser import Text.XML.Mapping.Schema.Namespace as X import Text.XML.Mapping.Schema.SimpleType as X import Text.XML.Mapping.Types decode :: XML a => QName -> S.ByteString -> Either PE.ParseError a decode qn bs = case parse' defaultParseOptions bs of Left xpe -> Left $ PE.malformed xpe Right n -> runParser (qn #> xml) (Tag n)
tel/xml-mapping
src/Text/XML/Mapping.hs
mit
981
0
10
255
204
129
75
17
2
import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Functor List where fmap _ Nil = Nil fmap f (Cons x xs) = Cons (f x) (fmap f xs) instance Applicative List where pure x = Cons x Nil (<*>) Nil _ = Nil (<*>) _ Nil = Nil (<*>) (Cons f fs) xs = fmap f xs `append` (<*>) fs xs instance Arbitrary a => Arbitrary (List a) where arbitrary = do x <- arbitrary x' <- arbitrary elements [Nil, Cons x Nil, Cons x (Cons x' Nil)] instance EqProp a => EqProp (List a) where Nil =-= Nil = property True Cons x xs =-= Cons y ys = x =-= y .&. xs =-= ys _ =-= _ = property False append :: List a -> List a -> List a append Nil ys = ys append (Cons x xs) ys = Cons x (append xs ys) toMyList :: [a] -> List a toMyList [] = Nil toMyList (x:xs) = Cons x (toMyList xs) fromMyList :: List a -> [a] fromMyList Nil = [] fromMyList (Cons x xs) = x : (fromMyList xs) main = do let trigger = undefined :: List (Int, String, Int) quickBatch $ functor trigger quickBatch $ applicative trigger
JustinUnger/haskell-book
ch17/list-app.hs
mit
1,148
2
12
303
567
280
287
34
1
---------------------------------------- -- Eval.hs -- 評価器 -- -- 新入生SG お手本インタプリタ -- 2012/05/23 高島尚希 ---------------------------------------- module Eval where import Control.Monad import Control.Monad.Fix import Syntax -- 値 data Value = CONST ConstId | PRIM PrimId [Value] | LIST [Value] | TUPLE [Value] | FUN Id Expr Env | LEFT Value | RIGHT Value deriving Show -- 環境 type Env = [(Id,Value)] -- 評価 eval :: Expr -> Env -> IO Value eval (Const id) env = return $ CONST id eval (Prim id) env = return $ PRIM id [] eval Null env = return $ LIST [] eval (Var x) env = return v where (Just v) = lookup x env eval (Fun x e) env = do return $ FUN x e env eval (Let x e1 e2) env = do v1 <- eval e1 env eval e2 ((x,v1):env) eval (LetRec x e1 e2) env = do v1 <- mfix $ \v -> eval e1 ((x,v):env) eval e2 ((x,v1):env) eval (If e1 e2 e3) env = do CONST (Bool b) <- eval e1 env if b then eval e2 env else eval e3 env eval (Force e _) env = eval e env eval (Tuple es) env = do vs <- mapM (flip eval env) es return (TUPLE vs) eval (Match e cases) env = do v <- eval e env evalCases cases v env eval (App e1 e2) env = do v1 <- eval e1 env v2 <- eval e2 env case v1 of FUN x body fenv -> eval body ((x,v2):fenv) PRIM id arg -> evalPrim id arg v2 v -> error ("$$$" ++ show v1 ++ "," ++ show v2 ) -- undefined -- パターンマッチのケースを試す evalCases :: [(Pat, Expr, Expr)] -> Value -> Env -> IO Value evalCases [] v _ = error $ "pattern match failure: " ++ show v evalCases ((p,g,e):cs) v env = case patMatch p v of Nothing -> evalCases cs v env Just env' -> do CONST (Bool b) <- eval g (env' ++ env) if b then eval e (env' ++ env) else evalCases cs v env -- パターンマッチ patMatch :: Pat -> Value -> Maybe Env patMatch (PConst id1) (CONST id2) | id1 == id2 = Just [] | otherwise = Nothing patMatch PWild v = Just [] patMatch PNull (LIST []) = Just [] patMatch (PVar x) v = Just [(x,v)] patMatch (PCons p1 p2) (LIST (v1:v2)) = do {- ここは Maybe モナド -} env1 <- patMatch p1 v1 env2 <- patMatch p2 (LIST v2) return (env1 ++ env2) patMatch (PTuple ps) (TUPLE vs) = do es <- mapM (uncurry patMatch) (zip ps vs) return (concat es) patMatch (PLeft p) (LEFT v) = patMatch p v patMatch (PRight p) (RIGHT v) = patMatch p v patMatch _ _ = Nothing {- 失敗 -} -- プリミティブ関数 evalPrim :: PrimId -> [Value] -> Value -> IO Value evalPrim Neg [] (CONST (Int n)) = return $ CONST $ Int $ -n evalPrim Not [] (CONST (Bool b)) = return $ CONST $ Bool $ not b evalPrim FNeg [] (CONST (Double d)) = return $ CONST $ Double $ -d evalPrim Add [CONST (Int n1)] (CONST (Int n2)) = return $ CONST $ Int $ n1 + n2 evalPrim Sub [CONST (Int n1)] (CONST (Int n2)) = return $ CONST $ Int $ n1 - n2 evalPrim Mul [CONST (Int n1)] (CONST (Int n2)) = return $ CONST $ Int $ n1 * n2 evalPrim Div [CONST (Int n1)] (CONST (Int n2)) = return $ CONST $ Int $ n1 `div` n2 evalPrim Mod [CONST (Int n1)] (CONST (Int n2)) = return $ CONST $ Int $ n1 `mod` n2 evalPrim Add [CONST (Double d1)] (CONST (Double d2)) = return $ CONST $ Double $ d1 + d2 evalPrim Sub [CONST (Double d1)] (CONST (Double d2)) = return $ CONST $ Double $ d1 - d2 evalPrim Mul [CONST (Double d1)] (CONST (Double d2)) = return $ CONST $ Double $ d1 * d2 evalPrim Div [CONST (Double d1)] (CONST (Double d2)) = return $ CONST $ Double $ d1 / d2 evalPrim Lt [v1] v2 = return $ CONST $ Bool $ evalCmpLt v1 v2 evalPrim Gt [v1] v2 = return $ CONST $ Bool $ evalCmpLt v2 v1 evalPrim Le [v1] v2 = return $ CONST $ Bool $ not $ evalCmpLt v2 v1 evalPrim Ge [v1] v2 = return $ CONST $ Bool $ not $ evalCmpLt v1 v2 evalPrim Eq [v1] v2 = return $ CONST $ Bool $ not $ evalCmpLt v1 v2 || evalCmpLt v2 v1 evalPrim Ne [v1] v2 = return $ CONST $ Bool $ evalCmpLt v1 v2 || evalCmpLt v2 v1 evalPrim And [CONST (Bool b1)] (CONST (Bool b2)) = return $ CONST $ Bool $ b1 && b2 evalPrim Or [CONST (Bool b1)] (CONST (Bool b2)) = return $ CONST $ Bool $ b1 || b2 evalPrim Cons [v] (LIST vs) = return $ LIST $ v:vs evalPrim Append [LIST vs1] (LIST vs2) = return $ LIST $ vs1 ++ vs2 evalPrim MakeLeft [] v = return $ LEFT v evalPrim MakeRight [] v = return $ RIGHT v evalPrim Print [] v = evalPrint v >> return (CONST Unit) evalPrim Chr [] (CONST (Int n)) = return $ CONST $ Char $ toEnum n evalPrim Ord [] (CONST (Char c)) = return $ CONST $ Int $ fromEnum c evalPrim ToInt [] (CONST (Double d)) = return $ CONST $ Int $ fromEnum d evalPrim ToDouble [] (CONST (Int n)) = return $ CONST $ Double $ toEnum n evalPrim id vs v = return $ PRIM id (vs++[v]) -- 値の比較 evalCmpLt :: Value -> Value -> Bool evalCmpLt (CONST (Int n1)) (CONST (Int n2)) = n1 < n2 evalCmpLt (CONST (Bool b1)) (CONST (Bool b2)) = b1 < b2 evalCmpLt (CONST (Char c1)) (CONST (Char c2)) = c1 < c2 evalCmpLt (CONST (Double d1)) (CONST (Double d2)) = d1 < d2 evalCmpLt (CONST Unit) (CONST Unit) = False evalCmpLt (PRIM _ _) (PRIM _ _) = error "compare closures" evalCmpLt (LIST vs1) (LIST vs2) = and (map (uncurry evalCmpLt) (zip vs1 vs2)) evalCmpLt (TUPLE vs1) (TUPLE vs2) = and (map (uncurry evalCmpLt) (zip vs1 vs2)) evalCmpLt (FUN _ _ _) (FUN _ _ _) = error "compare closures" evalCmpLt (LEFT v1) (LEFT v2) = evalCmpLt v1 v2 evalCmpLt (RIGHT v1) (RIGHT v2) = evalCmpLt v1 v2 evalCmpLt _ _ = undefined -- 値の表示 evalPrint :: Value -> IO () evalPrint (CONST (Int n)) = putStr (show n) evalPrint (CONST (Bool True)) = putStr "True" evalPrint (CONST (Bool False)) = putStr "False" evalPrint (CONST (Char c)) = putStr (c:"") evalPrint (CONST (Double d)) = putStr (show d) evalPrint (CONST Unit) = putStr "()" evalPrint (PRIM _ _) = putStr "<closure>" evalPrint (FUN _ _ _) = putStr "<closure>" evalPrint (LIST []) = putStr "[]" evalPrint (LIST lis@(CONST (Char c):rest)) = putStr $ map getChar lis where getChar (CONST (Char c)) = c getChar _ = undefined evalPrint (LIST (v:vs)) = do putStr "[" evalPrint v mapM (\v -> putStr ", " >> evalPrint v) vs putStr "]" evalPrint (TUPLE []) = putStr "()" evalPrint (TUPLE (v:vs)) = do putStr "(" evalPrint v mapM (\v -> putStr ", " >> evalPrint v) vs putStr ")" evalPrint (LEFT v) = putStr "(Left " >> evalPrint v >> putStr ")" evalPrint (RIGHT v) = putStr "(Right " >> evalPrint v >> putStr ")" -- 初期環境 initEnv :: Env initEnv = [ ("not", PRIM Not []), ("Left", PRIM MakeLeft []), ("Right", PRIM MakeRight []), ("print", PRIM Print []), ("ord", PRIM Ord []), ("chr", PRIM Chr []), ("toInt", PRIM ToInt []), ("toDouble", PRIM ToDouble []) ] -- トップレベル式を評価する evalTop :: Id -> Expr -> Env -> IO Env evalTop x e env = do v <- mfix $ \v -> eval e ((x,v):env) return ((x,v):env)
lambdataro/Dive
Eval.hs
mit
6,842
0
15
1,553
3,609
1,798
1,811
155
4
module System.Himpy.Recipes.Load where import System.Himpy.Recipes.Utils import System.Himpy.Mib import System.Himpy.Types import System.Himpy.Logger import System.Himpy.Output.Riemann import Control.Concurrent.STM.TChan (TChan) load_tuple :: (Int, Double) -> (String, Double) load_tuple (x, y) = ("load-" ++ (show x), y) load_rcp :: TChan ([Metric]) -> TChan (String) -> HimpyHost -> IO () load_rcp chan logchan (Host host comm _) = do loads <- snmp_walk_num host comm hrProcessorLoad let agg_load = (foldr (+) 0.0 loads) / (fromIntegral $ length loads :: Double) let mtrs = snmp_metrics host "load" $ [("load-all", agg_load)] riemann_send chan mtrs
pyr/himpy
System/Himpy/Recipes/Load.hs
mit
678
0
13
112
249
139
110
16
1
{-# OPTIONS_HADDOCK show-extensions #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Safe #-} {-| Module : MPD.Core.CommandArg Copyright : (c) Joachim Fasting, 2014 License : MIT Maintainer : [email protected] Stability : unstable Portability : unportable -} module MPD.Core.CommandArg ( CommandArg(..) ) where import Data.Bool (bool) import qualified Data.Text as T class CommandArg a where fromArg :: a -> T.Text instance (CommandArg a) => CommandArg (Maybe a) where fromArg = maybe mempty fromArg instance (CommandArg a, CommandArg b) => CommandArg (Either a b) where fromArg = either fromArg fromArg instance (CommandArg a) => CommandArg [a] where fromArg = T.unwords . map fromArg instance CommandArg Int where fromArg = T.pack . show instance CommandArg Integer where fromArg = T.pack . show instance CommandArg Double where fromArg = T.pack . show instance CommandArg Bool where fromArg = bool "0" "1" instance CommandArg T.Text where fromArg = id
joachifm/nanompd
src/MPD/Core/CommandArg.hs
mit
1,006
0
8
188
256
140
116
24
0
import Test.Hspec import RaytracerEtapa3_1113331018 main :: IO () main = hspec $ do describe "Setup of .ppm image" $ do it "returns a string with x, y and z" $ do pixelToString (1, 2, 3) `shouldBe` "1 2 3\n" it "returns the value of p3" $ do p3 `shouldBe` "P3\n" it "return a line of comment" $ do (head comment) `shouldBe` '#' it "returns \\n as the last char of a String" $ do (last p3) `shouldBe` '\n' (last comment) `shouldBe` '\n' describe "a invalid string to the .ppm file" $ do it "returns a error message" $ do (create_text_to_ppm_file 2 3 []) `shouldBe` "Nao e possivel criar uma imagem sem pixels" describe "the creation of a string to the .ppm image" $ do it "returns a valid string for the file" $ do (create_text_to_ppm_file 2 3 [(1, 2, 3)]) `shouldBe` "P3\n# It's a .ppm imagem for a raytracer\n2 3\n255\n1 2 3\n" describe "the aritmethic operations for Coordenada" $ do it "returns vetorial sum of two vectors" $ do (Coordenada(1, 2, 3) $+ Coordenada(1, 2, 3)) `shouldBe` Coordenada(2, 4, 6) it "returns a vetorial minus of two vectors" $ do (Coordenada(1, 2, 3) $- Coordenada(1, 2, 3)) `shouldBe` Coordenada(0, 0, 0) it "returns each elements times escalar value" $ do (Coordenada(1, 2, 3) $* 3) `shouldBe` Coordenada(3, 6, 9) it "returns each elements divided by escalar value" $ do (Coordenada(3, 3, 3) $/ 3) `shouldBe` Coordenada(1, 1, 1) it "returns a sum of each element of the vector times its correpondent in the second one" $ do (Coordenada(1, 2, 3) $. Coordenada(1, 2, 3)) `shouldBe` 14 describe "the aritmethic operations for Pixel" $ do it "returns vetorial sum of two vectors" $ do (Pixel(1, 2, 3) $+ Pixel(1, 2, 3)) `shouldBe` Pixel(2, 4, 6) it "returns a vetorial minus of two vectors" $ do (Pixel(1, 2, 3) $- Pixel(1, 2, 3)) `shouldBe` Pixel(0, 0, 0) it "returns each elements times escalar value" $ do (Pixel(1, 2, 3) $* 3) `shouldBe` Pixel(3, 6, 9) it "returns each elements divided by escalar value" $ do (Pixel(3, 3, 3) $/ 3) `shouldBe` Pixel(1, 1, 1) it "returns a sum of each element of the vector times its correpondent in the second one" $ do (Pixel(1, 2, 3) $. Pixel(1, 2, 3)) `shouldBe` 14
lipemorais/haskellando
RaytracerEtapa3_1113331018Spec.hs
mit
2,325
1
18
573
817
427
390
42
1
module Y2021.M02.D24.Solution where import Data.Time {-- What's today's date? Today's Haskell problem is to get the current date as a YYYY-mm-dd-formatted string from ... wherever you get the current date. --} today :: IO String today = take 10 . show <$> getCurrentTime {-- >>> today "2021-02-24" --}
geophf/1HaskellADay
exercises/HAD/Y2021/M02/D24/Solution.hs
mit
307
0
7
53
39
23
16
4
1
{-# LANGUAGE OverloadedStrings #-} module Test where import Crypto.Cipher.RC4 import Control.Monad.ST import Data.Bits import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C import Data.List import Data.Word import System.Exit -- TODO: Be a bit more rigorous main :: IO () main = do ok <- stToIO $ check exp "key" "hello" 0 if ok then exitSuccess else exitFailure where exp = B.pack [0x63, 0x09, 0x58, 0x81, 0x4b] -- Given a key and some data, prints the encrypt :: B.ByteString -> B.ByteString -> Int -> ST s B.ByteString encrypt key txt off = do r <- schedule key discard off r combine txt r -- Yay functors check :: B.ByteString -> B.ByteString -> B.ByteString -> Int -> ST s Bool check expected = (fmap.fmap.fmap.fmap) (== expected) encrypt toHex :: B.ByteString -> String toHex = concatMap hex . B.unpack hex :: Word8 -> String hex w = map ((genericIndex "0123456789ABCDEF") . (`shiftR` 4)) [ w, w `shiftL` 4 ]
nickspinale/rc4
tests/Test.hs
mit
1,033
0
9
247
332
183
149
26
2
{-# LANGUAGE TemplateHaskell #-} module Main where import Test.Framework.TH import Test.Framework.Providers.HUnit import Test.HUnit import Discussion main :: IO () main = $(defaultMainGenerator) -------------------------------------------------------------------------------- x = Var "x" y = Var "y" z = Var "z" s = VarT $ Var "S_" k = VarT $ Var "K_" i = VarT $ Var "I_" case_unlambda_lambda_x_x = unlambda (Lambda [x] (VarT x)) @?= i case_unlambda_lambda_x_y = unlambda (Lambda [x] (VarT y)) @?= App [k, VarT y] case_unlambda_lambda_x_yx = unlambda (Lambda [x] (App [VarT y, VarT x])) @?= VarT y case_unlambda_lambda_x_xy = unlambda (Lambda [x] (App [VarT x, VarT y])) @?= App [s, i, App [k, VarT y]] case_unlambda_lambda_x_yz = unlambda (Lambda [x] (App [VarT y, VarT z])) @?= App [k, App [VarT y, VarT z]] case_unlambda_lambda_xy_xy = unlambda (Lambda [x, y] (App [VarT x, VarT y])) @?= i case_unlambda_lambda_xy_yx = unlambda (Lambda [x, y] (App [VarT y, VarT x])) @?= App [s, App[k, App[s, i]], k] case_unlambda_var = unlambda (VarT x) @?= VarT x case_unlambda_term = unlambda (App [Lambda [x, y] (App [VarT y, VarT x]), Lambda [z] (VarT z)]) @?= App [App [s, App [k, App [s, i]], k], i]
todays-mitsui/discussion
test/UnitConverter.hs
mit
1,237
0
14
232
595
314
281
34
1
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2018.M05.D25.Exercise where import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.FromRow import Database.PostgreSQL.Simple.Types import Network.HTTP.Conduit import Network.HTTP.Types hiding (Query) -- below imports available via 1HaskellADay import Store.SQL.Connection import Store.SQL.Util.Indexed import Store.SQL.Util.Logging {-- Okay, let's do a little testy-testy. Download some articles from the database, upload them to a rest endpoint, and eh, that's today's exercise. --} nerEndpoint :: FilePath nerEndpoint = "https://grby98heb8.execute-api.us-east-1.amazonaws.com/CORS" {-- The curl command is: curl -X POST -H "Content-Type: application/json" -d '{"text": "I am going to see Deadpool2 on Friday."}' Or whatever you're sending from the database. But you're going to do a HTTPS POST to the rest endpoint. So do that. AND get the response, AND get the response type (200, 400, 504) --} data S = S { txt :: String } instance FromRow S where fromRow = undefined fetchStmt :: Int -> Int -> Query fetchStmt n offset = undefined -- query looks like: [sql|SELECT id,full_text FROM article WHERE id > ? LIMIT (?)|] fetchIxArticle :: Connection -> Int -> Int -> IO (IxValue S) fetchIxArticle conn n off = undefined -- fetches n ar curlCmd :: String -> IO (Status, String) curlCmd text = undefined -- sends text, gets a response and status logStatus :: Connection -> (Status, String) -> IO () logStatus conn (stat, resp) = undefined -- And our application that brings it all together main' :: [String] -> IO () main' args = undefined
geophf/1HaskellADay
exercises/HAD/Y2018/M05/D25/Exercise.hs
mit
1,635
0
10
264
264
156
108
25
1
-- Generic: yes -- Type checked: yes data Node a = Node {value :: a, l :: Node a, r :: Node a} | Nil contains :: (Ord a) => Node a -> a -> Bool Nil `contains` x = False node `contains` x | x == value node = True | x < value node = l node `contains` x | x > value node = r node `contains` x add :: (Ord a) => a -> Node a -> Node a add x Nil = Node x Nil Nil add x node | x == value node = node | x < value node = node {l = add x (l node)} | x > value node = node {r = add x (r node)} tree = foldr add Nil [20, 15, 20, 10] main = print $ map (tree `contains`) $ [10, 15, 20, 1]
wyager/ManyBSTs
bst.hs
mit
679
1
10
251
365
184
181
13
1
{-# LANGUAGE TemplateHaskell #-} -- | Defines texture helper structures for the library. module Codec.Soten.Scene.Texture ( Texel(..) , texelA , texelR , texelG , texelB , Texture(..) , textureWidth , textureHeight , textureTexels , textureFormatHint , newTexture , checkFormat ) where import Data.Int (Int8) import Control.Lens (makeLenses, (^.)) import qualified Data.Vector as V -- | Helper structure to represent a texel in a ARGB8888 format. data Texel = Texel { -- | Alpha component. _texelA :: !Int8 -- | Red component. , _texelR :: !Int8 -- | Green component. , _texelG :: !Int8 -- | Blue component. , _texelB :: !Int8 } deriving (Show, Eq) makeLenses ''Texel -- | Helper structure to describe an embedded texture. data Texture = Texture { -- | Width of the texture, in pixels. _textureWidth :: !Int -- | Height of the texture, in pixels. , _textureHeight :: !Int -- | Data of the texture. , _textureTexels :: !(V.Vector Texel) -- | A hint from the loader to make it easier for applications -- to determine the type of embedded compressed textures. , _textureFormatHint :: !String } deriving Show makeLenses ''Texture -- | Initializes new 'Texture'. newTexture :: Texture newTexture = Texture { _textureWidth = 0 , _textureHeight = 0 , _textureTexels = V.empty , _textureFormatHint = "\NUL\NUL\NUL" } -- | Compare the format hint against a given string. checkFormat :: Texture -> String -> Bool checkFormat texture s = s == texture ^. textureFormatHint
triplepointfive/soten
src/Codec/Soten/Scene/Texture.hs
mit
1,654
0
12
433
283
174
109
58
1
module Main where import qualified Lib main :: IO () main = Lib.startServer
GetContented/substance
app/Main.hs
mit
78
0
6
15
25
15
10
4
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE QuasiQuotes #-} -- | -- Checks that you cannot chain Actions module Chaining where import Control.Biegunka chained_script_0 :: Script 'Actions () chained_script_0 = [sh| echo hello |] <~> [sh| echo bye |] -- STDERR -- Couldn't match type ‘'Sources’ with ‘'Actions’ -- Expected type: Script 'Actions () -- Actual type: Script 'Sources ()
biegunka/biegunka
test/typecheck/should_fail/Fail2.hs
mit
408
0
6
82
48
34
14
9
1
{-# language NoMonomorphismRestriction #-} module CSP.Property.Right_Linear where import CSP.Syntax import Autolib.Reporter import Autolib.ToDoc import Control.Monad ( guard, sequence, void ) import Data.Maybe ( isJust ) ok = isJust . result . check check :: ToDoc a => Process a -> Reporter () check p = silent $ do inform $ text "sind alle Rekursionen rechts-linear?" nested 2 $ void $ sequence $ do s @ (Fix q) <- subs p return $ do inform $ text "untersuche" </> toDoc s local q -- | return True if the free Point does occur -- (note: ignores nested Points, on purpose) local r = nested 2 $ do inform $ text "Teilterm" </> toDoc r nested 2 $ case r of Stop -> return False Pre x p -> local p Ext p q -> local2 p q Int p q -> local2 p q Seq p q -> do bad <- local p when bad $ reject $ text "ist nicht rechtslinear (Rekursion im linken Argument)" local q Par s p q -> do bad <- local2 p q when bad $ reject $ text "ist nicht rechtslinear (Rekursion unter Par)" return False Fix p -> return False Point -> return True local2 p q = do subs <- forM [ p, q ] local return $ or subs
marcellussiegburg/autotool
collection/src/CSP/Property/Right_Linear.hs
gpl-2.0
1,365
1
16
502
430
199
231
40
8
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} -- Hello-World of the cordova/phonegap application using Haskell. -- So that Haste-Haskell can be used to create hybrid smartphone applications -- The original JavaScript hello world is installed following the instructions of this page -- -- http://cordova.apache.org/docs/en/4.0.0/guide_cli_index.md.html#The%20Command-Line%20Interface -- -- follow the steps to install the hello world app. -- -- install the browser platform, the simplest one: -- -- $ cordova platform add browser -- -- $ cordova build -- -- $ cordova run -- -- install Haste and the last version of the Perch library -- -- cabal install haste -- -- git clone https://github.com/agocorona/haste-perch -- -- compile this program -- -- hastec cordova.hs -- -- gt the JavaScript file and substitute the index.js of the installed hello-world application -- -- rebuild -- -- cordova build -- -- cordova run -- import Haste import Haste.HPlay.View import Haste.HPlay.Cell import Data.Typeable data OnDeviceReady= OnDeviceReady deriving Typeable instance IsEvent OnDeviceReady (IO ()) where eventName= const "deviceready" buildHandler e cont= do setIOEventData OnDeviceReady cont >> return() data Op = Op (Double -> Double -> Double) deriving Typeable main :: IO () main = do runBody calculator return() cor= do wraw this `fire` OnDeviceReady wraw $ do forElems (".listening") $ this ! style "display:none" forElems (".received") $ do this ! style "display:block" br i "RUNNING a HASKELL program" br i "compiled with the HASTE compiler" br i "and hplayground" wbutton () "click here" at "app" Insert calculator display= boxCell "display" :: Cell String calculator= mk display (Just "0") ! style "text-align:right" <++ br **> button '1' **> button '2' **> button '3' **> mul <++ br **> button '4' **> button '5' **> button '6' **> div <++ br **> button '7' **> button '8' **> button '9' **> sum <++ br **> delc **> button '0' <** delline <|> dif <++ br **> enter where updateDisplay key= do v <- get display display .= key:v mul= wbutton (Op (*)) "*" >>= setSData div= wbutton (Op (/)) "/" >>= setSData sum= wbutton (Op (+)) "+" >>= setSData dif= wbutton (Op (-)) "-" >>= setSData enter= wbutton () " Enter " >> calculate button n= wbutton n [n] >>= updateDisplay delc= do wbutton () "C" v <- get display display .= reverse . tail $ reverse v delline= do wbutton () "CE" v <- get display display .= "0" calculate= do num'<- get display >>= return . read :: Widget Double num <- getSData :: Widget Double setSData num' Op op <- getSData display .= show $ op num num' delSData op
agocorona/tryhplay
examples/cordova-hplayground-copy.hs
gpl-3.0
2,992
7
30
798
785
374
411
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.IAM.Types.Product -- 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) -- module Network.Google.IAM.Types.Product where import Network.Google.IAM.Types.Sum import Network.Google.Prelude -- | The response of a lint operation. An empty response indicates the -- operation was able to fully execute and no lint issue was found. -- -- /See:/ 'lintPolicyResponse' smart constructor. newtype LintPolicyResponse = LintPolicyResponse' { _lprLintResults :: Maybe [LintResult] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LintPolicyResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lprLintResults' lintPolicyResponse :: LintPolicyResponse lintPolicyResponse = LintPolicyResponse' {_lprLintResults = Nothing} -- | List of lint results sorted by \`severity\` in descending order. lprLintResults :: Lens' LintPolicyResponse [LintResult] lprLintResults = lens _lprLintResults (\ s a -> s{_lprLintResults = a}) . _Default . _Coerce instance FromJSON LintPolicyResponse where parseJSON = withObject "LintPolicyResponse" (\ o -> LintPolicyResponse' <$> (o .:? "lintResults" .!= mempty)) instance ToJSON LintPolicyResponse where toJSON LintPolicyResponse'{..} = object (catMaybes [("lintResults" .=) <$> _lprLintResults]) -- | The \`Status\` type defines a logical error model that is suitable for -- different programming environments, including REST APIs and RPC APIs. It -- is used by [gRPC](https:\/\/github.com\/grpc). Each \`Status\` message -- contains three pieces of data: error code, error message, and error -- details. You can find out more about this error model and how to work -- with it in the [API Design -- Guide](https:\/\/cloud.google.com\/apis\/design\/errors). -- -- /See:/ 'status' smart constructor. data Status = Status' { _sDetails :: !(Maybe [StatusDetailsItem]) , _sCode :: !(Maybe (Textual Int32)) , _sMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Status' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sDetails' -- -- * 'sCode' -- -- * 'sMessage' status :: Status status = Status' {_sDetails = Nothing, _sCode = Nothing, _sMessage = Nothing} -- | A list of messages that carry the error details. There is a common set -- of message types for APIs to use. sDetails :: Lens' Status [StatusDetailsItem] sDetails = lens _sDetails (\ s a -> s{_sDetails = a}) . _Default . _Coerce -- | The status code, which should be an enum value of google.rpc.Code. sCode :: Lens' Status (Maybe Int32) sCode = lens _sCode (\ s a -> s{_sCode = a}) . mapping _Coerce -- | A developer-facing error message, which should be in English. Any -- user-facing error message should be localized and sent in the -- google.rpc.Status.details field, or localized by the client. sMessage :: Lens' Status (Maybe Text) sMessage = lens _sMessage (\ s a -> s{_sMessage = a}) instance FromJSON Status where parseJSON = withObject "Status" (\ o -> Status' <$> (o .:? "details" .!= mempty) <*> (o .:? "code") <*> (o .:? "message")) instance ToJSON Status where toJSON Status'{..} = object (catMaybes [("details" .=) <$> _sDetails, ("code" .=) <$> _sCode, ("message" .=) <$> _sMessage]) -- | A configuration for an external identity provider. -- -- /See:/ 'workLoadIdentityPoolProvider' smart constructor. data WorkLoadIdentityPoolProvider = WorkLoadIdentityPoolProvider' { _wlippState :: !(Maybe WorkLoadIdentityPoolProviderState) , _wlippAws :: !(Maybe Aws) , _wlippDisabled :: !(Maybe Bool) , _wlippAttributeCondition :: !(Maybe Text) , _wlippName :: !(Maybe Text) , _wlippDisplayName :: !(Maybe Text) , _wlippAttributeMApping :: !(Maybe WorkLoadIdentityPoolProviderAttributeMApping) , _wlippDescription :: !(Maybe Text) , _wlippOidc :: !(Maybe Oidc) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WorkLoadIdentityPoolProvider' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wlippState' -- -- * 'wlippAws' -- -- * 'wlippDisabled' -- -- * 'wlippAttributeCondition' -- -- * 'wlippName' -- -- * 'wlippDisplayName' -- -- * 'wlippAttributeMApping' -- -- * 'wlippDescription' -- -- * 'wlippOidc' workLoadIdentityPoolProvider :: WorkLoadIdentityPoolProvider workLoadIdentityPoolProvider = WorkLoadIdentityPoolProvider' { _wlippState = Nothing , _wlippAws = Nothing , _wlippDisabled = Nothing , _wlippAttributeCondition = Nothing , _wlippName = Nothing , _wlippDisplayName = Nothing , _wlippAttributeMApping = Nothing , _wlippDescription = Nothing , _wlippOidc = Nothing } -- | Output only. The state of the provider. wlippState :: Lens' WorkLoadIdentityPoolProvider (Maybe WorkLoadIdentityPoolProviderState) wlippState = lens _wlippState (\ s a -> s{_wlippState = a}) -- | An Amazon Web Services identity provider. wlippAws :: Lens' WorkLoadIdentityPoolProvider (Maybe Aws) wlippAws = lens _wlippAws (\ s a -> s{_wlippAws = a}) -- | Whether the provider is disabled. You cannot use a disabled provider to -- exchange tokens. However, existing tokens still grant access. wlippDisabled :: Lens' WorkLoadIdentityPoolProvider (Maybe Bool) wlippDisabled = lens _wlippDisabled (\ s a -> s{_wlippDisabled = a}) -- | [A Common Expression -- Language](https:\/\/opensource.google\/projects\/cel) expression, in -- plain text, to restrict what otherwise valid authentication credentials -- issued by the provider should not be accepted. The expression must -- output a boolean representing whether to allow the federation. The -- following keywords may be referenced in the expressions: * -- \`assertion\`: JSON representing the authentication credential issued by -- the provider. * \`google\`: The Google attributes mapped from the -- assertion in the \`attribute_mappings\`. * \`attribute\`: The custom -- attributes mapped from the assertion in the \`attribute_mappings\`. The -- maximum length of the attribute condition expression is 4096 characters. -- If unspecified, all valid authentication credential are accepted. The -- following example shows how to only allow credentials with a mapped -- \`google.groups\` value of \`admins\`: \`\`\` \"\'admins\' in -- google.groups\" \`\`\` wlippAttributeCondition :: Lens' WorkLoadIdentityPoolProvider (Maybe Text) wlippAttributeCondition = lens _wlippAttributeCondition (\ s a -> s{_wlippAttributeCondition = a}) -- | Output only. The resource name of the provider. wlippName :: Lens' WorkLoadIdentityPoolProvider (Maybe Text) wlippName = lens _wlippName (\ s a -> s{_wlippName = a}) -- | A display name for the provider. Cannot exceed 32 characters. wlippDisplayName :: Lens' WorkLoadIdentityPoolProvider (Maybe Text) wlippDisplayName = lens _wlippDisplayName (\ s a -> s{_wlippDisplayName = a}) -- | Maps attributes from authentication credentials issued by an external -- identity provider to Google Cloud attributes, such as \`subject\` and -- \`segment\`. Each key must be a string specifying the Google Cloud IAM -- attribute to map to. The following keys are supported: * -- \`google.subject\`: The principal IAM is authenticating. You can -- reference this value in IAM bindings. This is also the subject that -- appears in Cloud Logging logs. Cannot exceed 127 characters. * -- \`google.groups\`: Groups the external identity belongs to. You can -- grant groups access to resources using an IAM \`principalSet\` binding; -- access applies to all members of the group. You can also provide custom -- attributes by specifying \`attribute.{custom_attribute}\`, where -- \`{custom_attribute}\` is the name of the custom attribute to be mapped. -- You can define a maximum of 50 custom attributes. The maximum length of -- a mapped attribute key is 100 characters, and the key may only contain -- the characters [a-z0-9_]. You can reference these attributes in IAM -- policies to define fine-grained access for a workload to Google Cloud -- resources. For example: * \`google.subject\`: -- \`principal:\/\/iam.googleapis.com\/projects\/{project}\/locations\/{location}\/workloadIdentityPools\/{pool}\/subject\/{value}\` -- * \`google.groups\`: -- \`principalSet:\/\/iam.googleapis.com\/projects\/{project}\/locations\/{location}\/workloadIdentityPools\/{pool}\/group\/{value}\` -- * \`attribute.{custom_attribute}\`: -- \`principalSet:\/\/iam.googleapis.com\/projects\/{project}\/locations\/{location}\/workloadIdentityPools\/{pool}\/attribute.{custom_attribute}\/{value}\` -- Each value must be a [Common Expression Language] -- (https:\/\/opensource.google\/projects\/cel) function that maps an -- identity provider credential to the normalized attribute specified by -- the corresponding map key. You can use the \`assertion\` keyword in the -- expression to access a JSON representation of the authentication -- credential issued by the provider. The maximum length of an attribute -- mapping expression is 2048 characters. When evaluated, the total size of -- all mapped attributes must not exceed 8KB. For AWS providers, if no -- attribute mapping is defined, the following default mapping applies: -- \`\`\` { \"google.subject\":\"assertion.arn\", \"attribute.aws_role\": -- \"assertion.arn.contains(\'assumed-role\')\" \" ? -- assertion.arn.extract(\'{account_arn}assumed-role\/\')\" \" + -- \'assumed-role\/\'\" \" + -- assertion.arn.extract(\'assumed-role\/{role_name}\/\')\" \" : -- assertion.arn\", } \`\`\` If any custom attribute mappings are defined, -- they must include a mapping to the \`google.subject\` attribute. For -- OIDC providers, you must supply a custom mapping, which must include the -- \`google.subject\` attribute. For example, the following maps the -- \`sub\` claim of the incoming credential to the \`subject\` attribute on -- a Google token: \`\`\` {\"google.subject\": \"assertion.sub\"} \`\`\` wlippAttributeMApping :: Lens' WorkLoadIdentityPoolProvider (Maybe WorkLoadIdentityPoolProviderAttributeMApping) wlippAttributeMApping = lens _wlippAttributeMApping (\ s a -> s{_wlippAttributeMApping = a}) -- | A description for the provider. Cannot exceed 256 characters. wlippDescription :: Lens' WorkLoadIdentityPoolProvider (Maybe Text) wlippDescription = lens _wlippDescription (\ s a -> s{_wlippDescription = a}) -- | An OpenId Connect 1.0 identity provider. wlippOidc :: Lens' WorkLoadIdentityPoolProvider (Maybe Oidc) wlippOidc = lens _wlippOidc (\ s a -> s{_wlippOidc = a}) instance FromJSON WorkLoadIdentityPoolProvider where parseJSON = withObject "WorkLoadIdentityPoolProvider" (\ o -> WorkLoadIdentityPoolProvider' <$> (o .:? "state") <*> (o .:? "aws") <*> (o .:? "disabled") <*> (o .:? "attributeCondition") <*> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "attributeMapping") <*> (o .:? "description") <*> (o .:? "oidc")) instance ToJSON WorkLoadIdentityPoolProvider where toJSON WorkLoadIdentityPoolProvider'{..} = object (catMaybes [("state" .=) <$> _wlippState, ("aws" .=) <$> _wlippAws, ("disabled" .=) <$> _wlippDisabled, ("attributeCondition" .=) <$> _wlippAttributeCondition, ("name" .=) <$> _wlippName, ("displayName" .=) <$> _wlippDisplayName, ("attributeMapping" .=) <$> _wlippAttributeMApping, ("description" .=) <$> _wlippDescription, ("oidc" .=) <$> _wlippOidc]) -- | The request to undelete an existing role. -- -- /See:/ 'undeleteRoleRequest' smart constructor. newtype UndeleteRoleRequest = UndeleteRoleRequest' { _urrEtag :: Maybe Bytes } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UndeleteRoleRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'urrEtag' undeleteRoleRequest :: UndeleteRoleRequest undeleteRoleRequest = UndeleteRoleRequest' {_urrEtag = Nothing} -- | Used to perform a consistent read-modify-write. urrEtag :: Lens' UndeleteRoleRequest (Maybe ByteString) urrEtag = lens _urrEtag (\ s a -> s{_urrEtag = a}) . mapping _Bytes instance FromJSON UndeleteRoleRequest where parseJSON = withObject "UndeleteRoleRequest" (\ o -> UndeleteRoleRequest' <$> (o .:? "etag")) instance ToJSON UndeleteRoleRequest where toJSON UndeleteRoleRequest'{..} = object (catMaybes [("etag" .=) <$> _urrEtag]) -- | Specifies the audit configuration for a service. The configuration -- determines which permission types are logged, and what identities, if -- any, are exempted from logging. An AuditConfig must have one or more -- AuditLogConfigs. If there are AuditConfigs for both \`allServices\` and -- a specific service, the union of the two AuditConfigs is used for that -- service: the log_types specified in each AuditConfig are enabled, and -- the exempted_members in each AuditLogConfig are exempted. Example Policy -- with multiple AuditConfigs: { \"audit_configs\": [ { \"service\": -- \"allServices\", \"audit_log_configs\": [ { \"log_type\": \"DATA_READ\", -- \"exempted_members\": [ \"user:jose\'example.com\" ] }, { \"log_type\": -- \"DATA_WRITE\" }, { \"log_type\": \"ADMIN_READ\" } ] }, { \"service\": -- \"sampleservice.googleapis.com\", \"audit_log_configs\": [ { -- \"log_type\": \"DATA_READ\" }, { \"log_type\": \"DATA_WRITE\", -- \"exempted_members\": [ \"user:aliya\'example.com\" ] } ] } ] } For -- sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ -- logging. It also exempts jose\'example.com from DATA_READ logging, and -- aliya\'example.com from DATA_WRITE logging. -- -- /See:/ 'auditConfig' smart constructor. data AuditConfig = AuditConfig' { _acService :: !(Maybe Text) , _acAuditLogConfigs :: !(Maybe [AuditLogConfig]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuditConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acService' -- -- * 'acAuditLogConfigs' auditConfig :: AuditConfig auditConfig = AuditConfig' {_acService = Nothing, _acAuditLogConfigs = Nothing} -- | Specifies a service that will be enabled for audit logging. For example, -- \`storage.googleapis.com\`, \`cloudsql.googleapis.com\`. \`allServices\` -- is a special value that covers all services. acService :: Lens' AuditConfig (Maybe Text) acService = lens _acService (\ s a -> s{_acService = a}) -- | The configuration for logging of each type of permission. acAuditLogConfigs :: Lens' AuditConfig [AuditLogConfig] acAuditLogConfigs = lens _acAuditLogConfigs (\ s a -> s{_acAuditLogConfigs = a}) . _Default . _Coerce instance FromJSON AuditConfig where parseJSON = withObject "AuditConfig" (\ o -> AuditConfig' <$> (o .:? "service") <*> (o .:? "auditLogConfigs" .!= mempty)) instance ToJSON AuditConfig where toJSON AuditConfig'{..} = object (catMaybes [("service" .=) <$> _acService, ("auditLogConfigs" .=) <$> _acAuditLogConfigs]) -- | Represents a textual expression in the Common Expression Language (CEL) -- syntax. CEL is a C-like expression language. The syntax and semantics of -- CEL are documented at https:\/\/github.com\/google\/cel-spec. Example -- (Comparison): title: \"Summary size limit\" description: \"Determines if -- a summary is less than 100 chars\" expression: \"document.summary.size() -- \< 100\" Example (Equality): title: \"Requestor is owner\" description: -- \"Determines if requestor is the document owner\" expression: -- \"document.owner == request.auth.claims.email\" Example (Logic): title: -- \"Public documents\" description: \"Determine whether the document -- should be publicly visible\" expression: \"document.type != \'private\' -- && document.type != \'internal\'\" Example (Data Manipulation): title: -- \"Notification string\" description: \"Create a notification string with -- a timestamp.\" expression: \"\'New message received at \' + -- string(document.create_time)\" The exact variables and functions that -- may be referenced within an expression are determined by the service -- that evaluates it. See the service documentation for additional -- information. -- -- /See:/ 'expr' smart constructor. data Expr = Expr' { _eLocation :: !(Maybe Text) , _eExpression :: !(Maybe Text) , _eTitle :: !(Maybe Text) , _eDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Expr' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eLocation' -- -- * 'eExpression' -- -- * 'eTitle' -- -- * 'eDescription' expr :: Expr expr = Expr' { _eLocation = Nothing , _eExpression = Nothing , _eTitle = Nothing , _eDescription = Nothing } -- | Optional. String indicating the location of the expression for error -- reporting, e.g. a file name and a position in the file. eLocation :: Lens' Expr (Maybe Text) eLocation = lens _eLocation (\ s a -> s{_eLocation = a}) -- | Textual representation of an expression in Common Expression Language -- syntax. eExpression :: Lens' Expr (Maybe Text) eExpression = lens _eExpression (\ s a -> s{_eExpression = a}) -- | Optional. Title for the expression, i.e. a short string describing its -- purpose. This can be used e.g. in UIs which allow to enter the -- expression. eTitle :: Lens' Expr (Maybe Text) eTitle = lens _eTitle (\ s a -> s{_eTitle = a}) -- | Optional. Description of the expression. This is a longer text which -- describes the expression, e.g. when hovered over it in a UI. eDescription :: Lens' Expr (Maybe Text) eDescription = lens _eDescription (\ s a -> s{_eDescription = a}) instance FromJSON Expr where parseJSON = withObject "Expr" (\ o -> Expr' <$> (o .:? "location") <*> (o .:? "expression") <*> (o .:? "title") <*> (o .:? "description")) instance ToJSON Expr where toJSON Expr'{..} = object (catMaybes [("location" .=) <$> _eLocation, ("expression" .=) <$> _eExpression, ("title" .=) <$> _eTitle, ("description" .=) <$> _eDescription]) -- | The service account undelete request. -- -- /See:/ 'undeleteServiceAccountRequest' smart constructor. data UndeleteServiceAccountRequest = UndeleteServiceAccountRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UndeleteServiceAccountRequest' with the minimum fields required to make a request. -- undeleteServiceAccountRequest :: UndeleteServiceAccountRequest undeleteServiceAccountRequest = UndeleteServiceAccountRequest' instance FromJSON UndeleteServiceAccountRequest where parseJSON = withObject "UndeleteServiceAccountRequest" (\ o -> pure UndeleteServiceAccountRequest') instance ToJSON UndeleteServiceAccountRequest where toJSON = const emptyObject -- | Contains information about an auditable service. -- -- /See:/ 'auditableService' smart constructor. newtype AuditableService = AuditableService' { _asName :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuditableService' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asName' auditableService :: AuditableService auditableService = AuditableService' {_asName = Nothing} -- | Public name of the service. For example, the service name for Cloud IAM -- is \'iam.googleapis.com\'. asName :: Lens' AuditableService (Maybe Text) asName = lens _asName (\ s a -> s{_asName = a}) instance FromJSON AuditableService where parseJSON = withObject "AuditableService" (\ o -> AuditableService' <$> (o .:? "name")) instance ToJSON AuditableService where toJSON AuditableService'{..} = object (catMaybes [("name" .=) <$> _asName]) -- | A request to get the list of auditable services for a resource. -- -- /See:/ 'queryAuditableServicesRequest' smart constructor. newtype QueryAuditableServicesRequest = QueryAuditableServicesRequest' { _qasrFullResourceName :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'QueryAuditableServicesRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qasrFullResourceName' queryAuditableServicesRequest :: QueryAuditableServicesRequest queryAuditableServicesRequest = QueryAuditableServicesRequest' {_qasrFullResourceName = Nothing} -- | Required. The full resource name to query from the list of auditable -- services. The name follows the Google Cloud Platform resource format. -- For example, a Cloud Platform project with id \`my-project\` will be -- named \`\/\/cloudresourcemanager.googleapis.com\/projects\/my-project\`. qasrFullResourceName :: Lens' QueryAuditableServicesRequest (Maybe Text) qasrFullResourceName = lens _qasrFullResourceName (\ s a -> s{_qasrFullResourceName = a}) instance FromJSON QueryAuditableServicesRequest where parseJSON = withObject "QueryAuditableServicesRequest" (\ o -> QueryAuditableServicesRequest' <$> (o .:? "fullResourceName")) instance ToJSON QueryAuditableServicesRequest where toJSON QueryAuditableServicesRequest'{..} = object (catMaybes [("fullResourceName" .=) <$> _qasrFullResourceName]) -- | This resource represents a long-running operation that is the result of -- a network API call. -- -- /See:/ 'operation' smart constructor. data Operation = Operation' { _oDone :: !(Maybe Bool) , _oError :: !(Maybe Status) , _oResponse :: !(Maybe OperationResponse) , _oName :: !(Maybe Text) , _oMetadata :: !(Maybe OperationMetadata) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Operation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oDone' -- -- * 'oError' -- -- * 'oResponse' -- -- * 'oName' -- -- * 'oMetadata' operation :: Operation operation = Operation' { _oDone = Nothing , _oError = Nothing , _oResponse = Nothing , _oName = Nothing , _oMetadata = Nothing } -- | If the value is \`false\`, it means the operation is still in progress. -- If \`true\`, the operation is completed, and either \`error\` or -- \`response\` is available. oDone :: Lens' Operation (Maybe Bool) oDone = lens _oDone (\ s a -> s{_oDone = a}) -- | The error result of the operation in case of failure or cancellation. oError :: Lens' Operation (Maybe Status) oError = lens _oError (\ s a -> s{_oError = a}) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. oResponse :: Lens' Operation (Maybe OperationResponse) oResponse = lens _oResponse (\ s a -> s{_oResponse = a}) -- | The server-assigned name, which is only unique within the same service -- that originally returns it. If you use the default HTTP mapping, the -- \`name\` should be a resource name ending with -- \`operations\/{unique_id}\`. oName :: Lens' Operation (Maybe Text) oName = lens _oName (\ s a -> s{_oName = a}) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. oMetadata :: Lens' Operation (Maybe OperationMetadata) oMetadata = lens _oMetadata (\ s a -> s{_oMetadata = a}) instance FromJSON Operation where parseJSON = withObject "Operation" (\ o -> Operation' <$> (o .:? "done") <*> (o .:? "error") <*> (o .:? "response") <*> (o .:? "name") <*> (o .:? "metadata")) instance ToJSON Operation where toJSON Operation'{..} = object (catMaybes [("done" .=) <$> _oDone, ("error" .=) <$> _oError, ("response" .=) <$> _oResponse, ("name" .=) <$> _oName, ("metadata" .=) <$> _oMetadata]) -- | A generic empty message that you can re-use to avoid defining duplicated -- empty messages in your APIs. A typical example is to use it as the -- request or the response type of an API method. For instance: service Foo -- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The -- JSON representation for \`Empty\` is empty JSON object \`{}\`. -- -- /See:/ 'empty' smart constructor. data Empty = Empty' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Empty' with the minimum fields required to make a request. -- empty :: Empty empty = Empty' instance FromJSON Empty where parseJSON = withObject "Empty" (\ o -> pure Empty') instance ToJSON Empty where toJSON = const emptyObject -- | Represents an Amazon Web Services identity provider. -- -- /See:/ 'aws' smart constructor. newtype Aws = Aws' { _aAccountId :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Aws' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aAccountId' aws :: Aws aws = Aws' {_aAccountId = Nothing} -- | Required. The AWS account ID. aAccountId :: Lens' Aws (Maybe Text) aAccountId = lens _aAccountId (\ s a -> s{_aAccountId = a}) instance FromJSON Aws where parseJSON = withObject "Aws" (\ o -> Aws' <$> (o .:? "accountId")) instance ToJSON Aws where toJSON Aws'{..} = object (catMaybes [("accountId" .=) <$> _aAccountId]) -- | The response containing permissions which can be tested on a resource. -- -- /See:/ 'queryTestablePermissionsResponse' smart constructor. data QueryTestablePermissionsResponse = QueryTestablePermissionsResponse' { _qtprNextPageToken :: !(Maybe Text) , _qtprPermissions :: !(Maybe [Permission]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'QueryTestablePermissionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qtprNextPageToken' -- -- * 'qtprPermissions' queryTestablePermissionsResponse :: QueryTestablePermissionsResponse queryTestablePermissionsResponse = QueryTestablePermissionsResponse' {_qtprNextPageToken = Nothing, _qtprPermissions = Nothing} -- | To retrieve the next page of results, set -- \`QueryTestableRolesRequest.page_token\` to this value. qtprNextPageToken :: Lens' QueryTestablePermissionsResponse (Maybe Text) qtprNextPageToken = lens _qtprNextPageToken (\ s a -> s{_qtprNextPageToken = a}) -- | The Permissions testable on the requested resource. qtprPermissions :: Lens' QueryTestablePermissionsResponse [Permission] qtprPermissions = lens _qtprPermissions (\ s a -> s{_qtprPermissions = a}) . _Default . _Coerce instance FromJSON QueryTestablePermissionsResponse where parseJSON = withObject "QueryTestablePermissionsResponse" (\ o -> QueryTestablePermissionsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "permissions" .!= mempty)) instance ToJSON QueryTestablePermissionsResponse where toJSON QueryTestablePermissionsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _qtprNextPageToken, ("permissions" .=) <$> _qtprPermissions]) -- | Audit log information specific to Cloud IAM. This message is serialized -- as an \`Any\` type in the \`ServiceData\` message of an \`AuditLog\` -- message. -- -- /See:/ 'auditData' smart constructor. newtype AuditData = AuditData' { _adPolicyDelta :: Maybe PolicyDelta } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuditData' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adPolicyDelta' auditData :: AuditData auditData = AuditData' {_adPolicyDelta = Nothing} -- | Policy delta between the original policy and the newly set policy. adPolicyDelta :: Lens' AuditData (Maybe PolicyDelta) adPolicyDelta = lens _adPolicyDelta (\ s a -> s{_adPolicyDelta = a}) instance FromJSON AuditData where parseJSON = withObject "AuditData" (\ o -> AuditData' <$> (o .:? "policyDelta")) instance ToJSON AuditData where toJSON AuditData'{..} = object (catMaybes [("policyDelta" .=) <$> _adPolicyDelta]) -- | A response containing a list of auditable services for a resource. -- -- /See:/ 'queryAuditableServicesResponse' smart constructor. newtype QueryAuditableServicesResponse = QueryAuditableServicesResponse' { _qasrServices :: Maybe [AuditableService] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'QueryAuditableServicesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qasrServices' queryAuditableServicesResponse :: QueryAuditableServicesResponse queryAuditableServicesResponse = QueryAuditableServicesResponse' {_qasrServices = Nothing} -- | The auditable services for a resource. qasrServices :: Lens' QueryAuditableServicesResponse [AuditableService] qasrServices = lens _qasrServices (\ s a -> s{_qasrServices = a}) . _Default . _Coerce instance FromJSON QueryAuditableServicesResponse where parseJSON = withObject "QueryAuditableServicesResponse" (\ o -> QueryAuditableServicesResponse' <$> (o .:? "services" .!= mempty)) instance ToJSON QueryAuditableServicesResponse where toJSON QueryAuditableServicesResponse'{..} = object (catMaybes [("services" .=) <$> _qasrServices]) -- | Represents a service account key. A service account has two sets of -- key-pairs: user-managed, and system-managed. User-managed key-pairs can -- be created and deleted by users. Users are responsible for rotating -- these keys periodically to ensure security of their service accounts. -- Users retain the private key of these key-pairs, and Google retains ONLY -- the public key. System-managed keys are automatically rotated by Google, -- and are used for signing for a maximum of two weeks. The rotation -- process is probabilistic, and usage of the new key will gradually ramp -- up and down over the key\'s lifetime. If you cache the public key set -- for a service account, we recommend that you update the cache every 15 -- minutes. User-managed keys can be added and removed at any time, so it -- is important to update the cache frequently. For Google-managed keys, -- Google will publish a key at least 6 hours before it is first used for -- signing and will keep publishing it for at least 6 hours after it was -- last used for signing. Public keys for all service accounts are also -- published at the OAuth2 Service Account API. -- -- /See:/ 'serviceAccountKey' smart constructor. data ServiceAccountKey = ServiceAccountKey' { _sakValidAfterTime :: !(Maybe DateTime') , _sakKeyType :: !(Maybe ServiceAccountKeyKeyType) , _sakPrivateKeyData :: !(Maybe Bytes) , _sakPublicKeyData :: !(Maybe Bytes) , _sakName :: !(Maybe Text) , _sakPrivateKeyType :: !(Maybe ServiceAccountKeyPrivateKeyType) , _sakValidBeforeTime :: !(Maybe DateTime') , _sakKeyAlgorithm :: !(Maybe ServiceAccountKeyKeyAlgorithm) , _sakKeyOrigin :: !(Maybe ServiceAccountKeyKeyOrigin) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServiceAccountKey' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sakValidAfterTime' -- -- * 'sakKeyType' -- -- * 'sakPrivateKeyData' -- -- * 'sakPublicKeyData' -- -- * 'sakName' -- -- * 'sakPrivateKeyType' -- -- * 'sakValidBeforeTime' -- -- * 'sakKeyAlgorithm' -- -- * 'sakKeyOrigin' serviceAccountKey :: ServiceAccountKey serviceAccountKey = ServiceAccountKey' { _sakValidAfterTime = Nothing , _sakKeyType = Nothing , _sakPrivateKeyData = Nothing , _sakPublicKeyData = Nothing , _sakName = Nothing , _sakPrivateKeyType = Nothing , _sakValidBeforeTime = Nothing , _sakKeyAlgorithm = Nothing , _sakKeyOrigin = Nothing } -- | The key can be used after this timestamp. sakValidAfterTime :: Lens' ServiceAccountKey (Maybe UTCTime) sakValidAfterTime = lens _sakValidAfterTime (\ s a -> s{_sakValidAfterTime = a}) . mapping _DateTime -- | The key type. sakKeyType :: Lens' ServiceAccountKey (Maybe ServiceAccountKeyKeyType) sakKeyType = lens _sakKeyType (\ s a -> s{_sakKeyType = a}) -- | The private key data. Only provided in \`CreateServiceAccountKey\` -- responses. Make sure to keep the private key data secure because it -- allows for the assertion of the service account identity. When base64 -- decoded, the private key data can be used to authenticate with Google -- API client libraries and with gcloud auth activate-service-account. sakPrivateKeyData :: Lens' ServiceAccountKey (Maybe ByteString) sakPrivateKeyData = lens _sakPrivateKeyData (\ s a -> s{_sakPrivateKeyData = a}) . mapping _Bytes -- | The public key data. Only provided in \`GetServiceAccountKey\` -- responses. sakPublicKeyData :: Lens' ServiceAccountKey (Maybe ByteString) sakPublicKeyData = lens _sakPublicKeyData (\ s a -> s{_sakPublicKeyData = a}) . mapping _Bytes -- | The resource name of the service account key in the following format -- \`projects\/{PROJECT_ID}\/serviceAccounts\/{ACCOUNT}\/keys\/{key}\`. sakName :: Lens' ServiceAccountKey (Maybe Text) sakName = lens _sakName (\ s a -> s{_sakName = a}) -- | The output format for the private key. Only provided in -- \`CreateServiceAccountKey\` responses, not in \`GetServiceAccountKey\` -- or \`ListServiceAccountKey\` responses. Google never exposes -- system-managed private keys, and never retains user-managed private -- keys. sakPrivateKeyType :: Lens' ServiceAccountKey (Maybe ServiceAccountKeyPrivateKeyType) sakPrivateKeyType = lens _sakPrivateKeyType (\ s a -> s{_sakPrivateKeyType = a}) -- | The key can be used before this timestamp. For system-managed key pairs, -- this timestamp is the end time for the private key signing operation. -- The public key could still be used for verification for a few hours -- after this time. sakValidBeforeTime :: Lens' ServiceAccountKey (Maybe UTCTime) sakValidBeforeTime = lens _sakValidBeforeTime (\ s a -> s{_sakValidBeforeTime = a}) . mapping _DateTime -- | Specifies the algorithm (and possibly key size) for the key. sakKeyAlgorithm :: Lens' ServiceAccountKey (Maybe ServiceAccountKeyKeyAlgorithm) sakKeyAlgorithm = lens _sakKeyAlgorithm (\ s a -> s{_sakKeyAlgorithm = a}) -- | The key origin. sakKeyOrigin :: Lens' ServiceAccountKey (Maybe ServiceAccountKeyKeyOrigin) sakKeyOrigin = lens _sakKeyOrigin (\ s a -> s{_sakKeyOrigin = a}) instance FromJSON ServiceAccountKey where parseJSON = withObject "ServiceAccountKey" (\ o -> ServiceAccountKey' <$> (o .:? "validAfterTime") <*> (o .:? "keyType") <*> (o .:? "privateKeyData") <*> (o .:? "publicKeyData") <*> (o .:? "name") <*> (o .:? "privateKeyType") <*> (o .:? "validBeforeTime") <*> (o .:? "keyAlgorithm") <*> (o .:? "keyOrigin")) instance ToJSON ServiceAccountKey where toJSON ServiceAccountKey'{..} = object (catMaybes [("validAfterTime" .=) <$> _sakValidAfterTime, ("keyType" .=) <$> _sakKeyType, ("privateKeyData" .=) <$> _sakPrivateKeyData, ("publicKeyData" .=) <$> _sakPublicKeyData, ("name" .=) <$> _sakName, ("privateKeyType" .=) <$> _sakPrivateKeyType, ("validBeforeTime" .=) <$> _sakValidBeforeTime, ("keyAlgorithm" .=) <$> _sakKeyAlgorithm, ("keyOrigin" .=) <$> _sakKeyOrigin]) -- | A PermissionDelta message to record the added_permissions and -- removed_permissions inside a role. -- -- /See:/ 'permissionDelta' smart constructor. data PermissionDelta = PermissionDelta' { _pdAddedPermissions :: !(Maybe [Text]) , _pdRemovedPermissions :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PermissionDelta' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdAddedPermissions' -- -- * 'pdRemovedPermissions' permissionDelta :: PermissionDelta permissionDelta = PermissionDelta' {_pdAddedPermissions = Nothing, _pdRemovedPermissions = Nothing} -- | Added permissions. pdAddedPermissions :: Lens' PermissionDelta [Text] pdAddedPermissions = lens _pdAddedPermissions (\ s a -> s{_pdAddedPermissions = a}) . _Default . _Coerce -- | Removed permissions. pdRemovedPermissions :: Lens' PermissionDelta [Text] pdRemovedPermissions = lens _pdRemovedPermissions (\ s a -> s{_pdRemovedPermissions = a}) . _Default . _Coerce instance FromJSON PermissionDelta where parseJSON = withObject "PermissionDelta" (\ o -> PermissionDelta' <$> (o .:? "addedPermissions" .!= mempty) <*> (o .:? "removedPermissions" .!= mempty)) instance ToJSON PermissionDelta where toJSON PermissionDelta'{..} = object (catMaybes [("addedPermissions" .=) <$> _pdAddedPermissions, ("removedPermissions" .=) <$> _pdRemovedPermissions]) -- -- /See:/ 'statusDetailsItem' smart constructor. newtype StatusDetailsItem = StatusDetailsItem' { _sdiAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdiAddtional' statusDetailsItem :: HashMap Text JSONValue -- ^ 'sdiAddtional' -> StatusDetailsItem statusDetailsItem pSdiAddtional_ = StatusDetailsItem' {_sdiAddtional = _Coerce # pSdiAddtional_} -- | Properties of the object. Contains field \'type with type URL. sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue) sdiAddtional = lens _sdiAddtional (\ s a -> s{_sdiAddtional = a}) . _Coerce instance FromJSON StatusDetailsItem where parseJSON = withObject "StatusDetailsItem" (\ o -> StatusDetailsItem' <$> (parseJSONObject o)) instance ToJSON StatusDetailsItem where toJSON = toJSON . _sdiAddtional -- | Structured response of a single validation unit. -- -- /See:/ 'lintResult' smart constructor. data LintResult = LintResult' { _lrValidationUnitName :: !(Maybe Text) , _lrDebugMessage :: !(Maybe Text) , _lrLocationOffSet :: !(Maybe (Textual Int32)) , _lrSeverity :: !(Maybe LintResultSeverity) , _lrFieldName :: !(Maybe Text) , _lrLevel :: !(Maybe LintResultLevel) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LintResult' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lrValidationUnitName' -- -- * 'lrDebugMessage' -- -- * 'lrLocationOffSet' -- -- * 'lrSeverity' -- -- * 'lrFieldName' -- -- * 'lrLevel' lintResult :: LintResult lintResult = LintResult' { _lrValidationUnitName = Nothing , _lrDebugMessage = Nothing , _lrLocationOffSet = Nothing , _lrSeverity = Nothing , _lrFieldName = Nothing , _lrLevel = Nothing } -- | The validation unit name, for instance -- \"lintValidationUnits\/ConditionComplexityCheck\". lrValidationUnitName :: Lens' LintResult (Maybe Text) lrValidationUnitName = lens _lrValidationUnitName (\ s a -> s{_lrValidationUnitName = a}) -- | Human readable debug message associated with the issue. lrDebugMessage :: Lens' LintResult (Maybe Text) lrDebugMessage = lens _lrDebugMessage (\ s a -> s{_lrDebugMessage = a}) -- | 0-based character position of problematic construct within the object -- identified by \`field_name\`. Currently, this is populated only for -- condition expression. lrLocationOffSet :: Lens' LintResult (Maybe Int32) lrLocationOffSet = lens _lrLocationOffSet (\ s a -> s{_lrLocationOffSet = a}) . mapping _Coerce -- | The validation unit severity. lrSeverity :: Lens' LintResult (Maybe LintResultSeverity) lrSeverity = lens _lrSeverity (\ s a -> s{_lrSeverity = a}) -- | The name of the field for which this lint result is about. For nested -- messages \`field_name\` consists of names of the embedded fields -- separated by period character. The top-level qualifier is the input -- object to lint in the request. For example, the \`field_name\` value -- \`condition.expression\` identifies a lint result for the \`expression\` -- field of the provided condition. lrFieldName :: Lens' LintResult (Maybe Text) lrFieldName = lens _lrFieldName (\ s a -> s{_lrFieldName = a}) -- | The validation unit level. lrLevel :: Lens' LintResult (Maybe LintResultLevel) lrLevel = lens _lrLevel (\ s a -> s{_lrLevel = a}) instance FromJSON LintResult where parseJSON = withObject "LintResult" (\ o -> LintResult' <$> (o .:? "validationUnitName") <*> (o .:? "debugMessage") <*> (o .:? "locationOffset") <*> (o .:? "severity") <*> (o .:? "fieldName") <*> (o .:? "level")) instance ToJSON LintResult where toJSON LintResult'{..} = object (catMaybes [("validationUnitName" .=) <$> _lrValidationUnitName, ("debugMessage" .=) <$> _lrDebugMessage, ("locationOffset" .=) <$> _lrLocationOffSet, ("severity" .=) <$> _lrSeverity, ("fieldName" .=) <$> _lrFieldName, ("level" .=) <$> _lrLevel]) -- | Request message for UndeleteWorkloadIdentityPool. -- -- /See:/ 'undeleteWorkLoadIdentityPoolRequest' smart constructor. data UndeleteWorkLoadIdentityPoolRequest = UndeleteWorkLoadIdentityPoolRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UndeleteWorkLoadIdentityPoolRequest' with the minimum fields required to make a request. -- undeleteWorkLoadIdentityPoolRequest :: UndeleteWorkLoadIdentityPoolRequest undeleteWorkLoadIdentityPoolRequest = UndeleteWorkLoadIdentityPoolRequest' instance FromJSON UndeleteWorkLoadIdentityPoolRequest where parseJSON = withObject "UndeleteWorkLoadIdentityPoolRequest" (\ o -> pure UndeleteWorkLoadIdentityPoolRequest') instance ToJSON UndeleteWorkLoadIdentityPoolRequest where toJSON = const emptyObject -- | Response message for ListWorkloadIdentityPoolProviders. -- -- /See:/ 'listWorkLoadIdentityPoolProvidersResponse' smart constructor. data ListWorkLoadIdentityPoolProvidersResponse = ListWorkLoadIdentityPoolProvidersResponse' { _lwlipprNextPageToken :: !(Maybe Text) , _lwlipprWorkLoadIdentityPoolProviders :: !(Maybe [WorkLoadIdentityPoolProvider]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListWorkLoadIdentityPoolProvidersResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lwlipprNextPageToken' -- -- * 'lwlipprWorkLoadIdentityPoolProviders' listWorkLoadIdentityPoolProvidersResponse :: ListWorkLoadIdentityPoolProvidersResponse listWorkLoadIdentityPoolProvidersResponse = ListWorkLoadIdentityPoolProvidersResponse' { _lwlipprNextPageToken = Nothing , _lwlipprWorkLoadIdentityPoolProviders = Nothing } -- | A token, which can be sent as \`page_token\` to retrieve the next page. -- If this field is omitted, there are no subsequent pages. lwlipprNextPageToken :: Lens' ListWorkLoadIdentityPoolProvidersResponse (Maybe Text) lwlipprNextPageToken = lens _lwlipprNextPageToken (\ s a -> s{_lwlipprNextPageToken = a}) -- | A list of providers. lwlipprWorkLoadIdentityPoolProviders :: Lens' ListWorkLoadIdentityPoolProvidersResponse [WorkLoadIdentityPoolProvider] lwlipprWorkLoadIdentityPoolProviders = lens _lwlipprWorkLoadIdentityPoolProviders (\ s a -> s{_lwlipprWorkLoadIdentityPoolProviders = a}) . _Default . _Coerce instance FromJSON ListWorkLoadIdentityPoolProvidersResponse where parseJSON = withObject "ListWorkLoadIdentityPoolProvidersResponse" (\ o -> ListWorkLoadIdentityPoolProvidersResponse' <$> (o .:? "nextPageToken") <*> (o .:? "workloadIdentityPoolProviders" .!= mempty)) instance ToJSON ListWorkLoadIdentityPoolProvidersResponse where toJSON ListWorkLoadIdentityPoolProvidersResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lwlipprNextPageToken, ("workloadIdentityPoolProviders" .=) <$> _lwlipprWorkLoadIdentityPoolProviders]) -- | The service account key create request. -- -- /See:/ 'createServiceAccountKeyRequest' smart constructor. data CreateServiceAccountKeyRequest = CreateServiceAccountKeyRequest' { _csakrPrivateKeyType :: !(Maybe CreateServiceAccountKeyRequestPrivateKeyType) , _csakrKeyAlgorithm :: !(Maybe CreateServiceAccountKeyRequestKeyAlgorithm) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CreateServiceAccountKeyRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'csakrPrivateKeyType' -- -- * 'csakrKeyAlgorithm' createServiceAccountKeyRequest :: CreateServiceAccountKeyRequest createServiceAccountKeyRequest = CreateServiceAccountKeyRequest' {_csakrPrivateKeyType = Nothing, _csakrKeyAlgorithm = Nothing} -- | The output format of the private key. The default value is -- \`TYPE_GOOGLE_CREDENTIALS_FILE\`, which is the Google Credentials File -- format. csakrPrivateKeyType :: Lens' CreateServiceAccountKeyRequest (Maybe CreateServiceAccountKeyRequestPrivateKeyType) csakrPrivateKeyType = lens _csakrPrivateKeyType (\ s a -> s{_csakrPrivateKeyType = a}) -- | Which type of key and algorithm to use for the key. The default is -- currently a 2K RSA key. However this may change in the future. csakrKeyAlgorithm :: Lens' CreateServiceAccountKeyRequest (Maybe CreateServiceAccountKeyRequestKeyAlgorithm) csakrKeyAlgorithm = lens _csakrKeyAlgorithm (\ s a -> s{_csakrKeyAlgorithm = a}) instance FromJSON CreateServiceAccountKeyRequest where parseJSON = withObject "CreateServiceAccountKeyRequest" (\ o -> CreateServiceAccountKeyRequest' <$> (o .:? "privateKeyType") <*> (o .:? "keyAlgorithm")) instance ToJSON CreateServiceAccountKeyRequest where toJSON CreateServiceAccountKeyRequest'{..} = object (catMaybes [("privateKeyType" .=) <$> _csakrPrivateKeyType, ("keyAlgorithm" .=) <$> _csakrKeyAlgorithm]) -- | Request message for \`SetIamPolicy\` method. -- -- /See:/ 'setIAMPolicyRequest' smart constructor. data SetIAMPolicyRequest = SetIAMPolicyRequest' { _siprUpdateMask :: !(Maybe GFieldMask) , _siprPolicy :: !(Maybe Policy) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SetIAMPolicyRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'siprUpdateMask' -- -- * 'siprPolicy' setIAMPolicyRequest :: SetIAMPolicyRequest setIAMPolicyRequest = SetIAMPolicyRequest' {_siprUpdateMask = Nothing, _siprPolicy = Nothing} -- | OPTIONAL: A FieldMask specifying which fields of the policy to modify. -- Only the fields in the mask will be modified. If no mask is provided, -- the following default mask is used: \`paths: \"bindings, etag\"\` siprUpdateMask :: Lens' SetIAMPolicyRequest (Maybe GFieldMask) siprUpdateMask = lens _siprUpdateMask (\ s a -> s{_siprUpdateMask = a}) -- | REQUIRED: The complete policy to be applied to the \`resource\`. The -- size of the policy is limited to a few 10s of KB. An empty policy is a -- valid policy but certain Cloud Platform services (such as Projects) -- might reject them. siprPolicy :: Lens' SetIAMPolicyRequest (Maybe Policy) siprPolicy = lens _siprPolicy (\ s a -> s{_siprPolicy = a}) instance FromJSON SetIAMPolicyRequest where parseJSON = withObject "SetIAMPolicyRequest" (\ o -> SetIAMPolicyRequest' <$> (o .:? "updateMask") <*> (o .:? "policy")) instance ToJSON SetIAMPolicyRequest where toJSON SetIAMPolicyRequest'{..} = object (catMaybes [("updateMask" .=) <$> _siprUpdateMask, ("policy" .=) <$> _siprPolicy]) -- | Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The service account sign JWT response. -- -- /See:/ 'signJwtResponse' smart constructor. data SignJwtResponse = SignJwtResponse' { _sjrKeyId :: !(Maybe Text) , _sjrSignedJwt :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SignJwtResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sjrKeyId' -- -- * 'sjrSignedJwt' signJwtResponse :: SignJwtResponse signJwtResponse = SignJwtResponse' {_sjrKeyId = Nothing, _sjrSignedJwt = Nothing} -- | Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The id of the key used to sign the JWT. sjrKeyId :: Lens' SignJwtResponse (Maybe Text) sjrKeyId = lens _sjrKeyId (\ s a -> s{_sjrKeyId = a}) -- | Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The signed JWT. sjrSignedJwt :: Lens' SignJwtResponse (Maybe Text) sjrSignedJwt = lens _sjrSignedJwt (\ s a -> s{_sjrSignedJwt = a}) instance FromJSON SignJwtResponse where parseJSON = withObject "SignJwtResponse" (\ o -> SignJwtResponse' <$> (o .:? "keyId") <*> (o .:? "signedJwt")) instance ToJSON SignJwtResponse where toJSON SignJwtResponse'{..} = object (catMaybes [("keyId" .=) <$> _sjrKeyId, ("signedJwt" .=) <$> _sjrSignedJwt]) -- | One delta entry for Binding. Each individual change (only one member in -- each entry) to a binding will be a separate entry. -- -- /See:/ 'bindingDelta' smart constructor. data BindingDelta = BindingDelta' { _bdAction :: !(Maybe BindingDeltaAction) , _bdRole :: !(Maybe Text) , _bdMember :: !(Maybe Text) , _bdCondition :: !(Maybe Expr) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BindingDelta' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bdAction' -- -- * 'bdRole' -- -- * 'bdMember' -- -- * 'bdCondition' bindingDelta :: BindingDelta bindingDelta = BindingDelta' { _bdAction = Nothing , _bdRole = Nothing , _bdMember = Nothing , _bdCondition = Nothing } -- | The action that was performed on a Binding. Required bdAction :: Lens' BindingDelta (Maybe BindingDeltaAction) bdAction = lens _bdAction (\ s a -> s{_bdAction = a}) -- | Role that is assigned to \`members\`. For example, \`roles\/viewer\`, -- \`roles\/editor\`, or \`roles\/owner\`. Required bdRole :: Lens' BindingDelta (Maybe Text) bdRole = lens _bdRole (\ s a -> s{_bdRole = a}) -- | A single identity requesting access for a Cloud Platform resource. -- Follows the same format of Binding.members. Required bdMember :: Lens' BindingDelta (Maybe Text) bdMember = lens _bdMember (\ s a -> s{_bdMember = a}) -- | The condition that is associated with this binding. bdCondition :: Lens' BindingDelta (Maybe Expr) bdCondition = lens _bdCondition (\ s a -> s{_bdCondition = a}) instance FromJSON BindingDelta where parseJSON = withObject "BindingDelta" (\ o -> BindingDelta' <$> (o .:? "action") <*> (o .:? "role") <*> (o .:? "member") <*> (o .:? "condition")) instance ToJSON BindingDelta where toJSON BindingDelta'{..} = object (catMaybes [("action" .=) <$> _bdAction, ("role" .=) <$> _bdRole, ("member" .=) <$> _bdMember, ("condition" .=) <$> _bdCondition]) -- | Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The service account sign blob request. -- -- /See:/ 'signBlobRequest' smart constructor. newtype SignBlobRequest = SignBlobRequest' { _sbrBytesToSign :: Maybe Bytes } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SignBlobRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sbrBytesToSign' signBlobRequest :: SignBlobRequest signBlobRequest = SignBlobRequest' {_sbrBytesToSign = Nothing} -- | Required. Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The bytes to sign. sbrBytesToSign :: Lens' SignBlobRequest (Maybe ByteString) sbrBytesToSign = lens _sbrBytesToSign (\ s a -> s{_sbrBytesToSign = a}) . mapping _Bytes instance FromJSON SignBlobRequest where parseJSON = withObject "SignBlobRequest" (\ o -> SignBlobRequest' <$> (o .:? "bytesToSign")) instance ToJSON SignBlobRequest where toJSON SignBlobRequest'{..} = object (catMaybes [("bytesToSign" .=) <$> _sbrBytesToSign]) -- | The service account keys list response. -- -- /See:/ 'listServiceAccountKeysResponse' smart constructor. newtype ListServiceAccountKeysResponse = ListServiceAccountKeysResponse' { _lsakrKeys :: Maybe [ServiceAccountKey] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListServiceAccountKeysResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsakrKeys' listServiceAccountKeysResponse :: ListServiceAccountKeysResponse listServiceAccountKeysResponse = ListServiceAccountKeysResponse' {_lsakrKeys = Nothing} -- | The public keys for the service account. lsakrKeys :: Lens' ListServiceAccountKeysResponse [ServiceAccountKey] lsakrKeys = lens _lsakrKeys (\ s a -> s{_lsakrKeys = a}) . _Default . _Coerce instance FromJSON ListServiceAccountKeysResponse where parseJSON = withObject "ListServiceAccountKeysResponse" (\ o -> ListServiceAccountKeysResponse' <$> (o .:? "keys" .!= mempty)) instance ToJSON ListServiceAccountKeysResponse where toJSON ListServiceAccountKeysResponse'{..} = object (catMaybes [("keys" .=) <$> _lsakrKeys]) -- | The service account enable request. -- -- /See:/ 'enableServiceAccountRequest' smart constructor. data EnableServiceAccountRequest = EnableServiceAccountRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'EnableServiceAccountRequest' with the minimum fields required to make a request. -- enableServiceAccountRequest :: EnableServiceAccountRequest enableServiceAccountRequest = EnableServiceAccountRequest' instance FromJSON EnableServiceAccountRequest where parseJSON = withObject "EnableServiceAccountRequest" (\ o -> pure EnableServiceAccountRequest') instance ToJSON EnableServiceAccountRequest where toJSON = const emptyObject -- | A role in the Identity and Access Management API. -- -- /See:/ 'role'' smart constructor. data Role = Role' { _rStage :: !(Maybe RoleStage) , _rEtag :: !(Maybe Bytes) , _rIncludedPermissions :: !(Maybe [Text]) , _rName :: !(Maybe Text) , _rDeleted :: !(Maybe Bool) , _rTitle :: !(Maybe Text) , _rDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Role' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rStage' -- -- * 'rEtag' -- -- * 'rIncludedPermissions' -- -- * 'rName' -- -- * 'rDeleted' -- -- * 'rTitle' -- -- * 'rDescription' role' :: Role role' = Role' { _rStage = Nothing , _rEtag = Nothing , _rIncludedPermissions = Nothing , _rName = Nothing , _rDeleted = Nothing , _rTitle = Nothing , _rDescription = Nothing } -- | The current launch stage of the role. If the \`ALPHA\` launch stage has -- been selected for a role, the \`stage\` field will not be included in -- the returned definition for the role. rStage :: Lens' Role (Maybe RoleStage) rStage = lens _rStage (\ s a -> s{_rStage = a}) -- | Used to perform a consistent read-modify-write. rEtag :: Lens' Role (Maybe ByteString) rEtag = lens _rEtag (\ s a -> s{_rEtag = a}) . mapping _Bytes -- | The names of the permissions this role grants when bound in an IAM -- policy. rIncludedPermissions :: Lens' Role [Text] rIncludedPermissions = lens _rIncludedPermissions (\ s a -> s{_rIncludedPermissions = a}) . _Default . _Coerce -- | The name of the role. When Role is used in CreateRole, the role name -- must not be set. When Role is used in output and other input such as -- UpdateRole, the role name is the complete path, e.g., -- roles\/logging.viewer for predefined roles and -- organizations\/{ORGANIZATION_ID}\/roles\/logging.viewer for custom -- roles. rName :: Lens' Role (Maybe Text) rName = lens _rName (\ s a -> s{_rName = a}) -- | The current deleted state of the role. This field is read only. It will -- be ignored in calls to CreateRole and UpdateRole. rDeleted :: Lens' Role (Maybe Bool) rDeleted = lens _rDeleted (\ s a -> s{_rDeleted = a}) -- | Optional. A human-readable title for the role. Typically this is limited -- to 100 UTF-8 bytes. rTitle :: Lens' Role (Maybe Text) rTitle = lens _rTitle (\ s a -> s{_rTitle = a}) -- | Optional. A human-readable description for the role. rDescription :: Lens' Role (Maybe Text) rDescription = lens _rDescription (\ s a -> s{_rDescription = a}) instance FromJSON Role where parseJSON = withObject "Role" (\ o -> Role' <$> (o .:? "stage") <*> (o .:? "etag") <*> (o .:? "includedPermissions" .!= mempty) <*> (o .:? "name") <*> (o .:? "deleted") <*> (o .:? "title") <*> (o .:? "description")) instance ToJSON Role where toJSON Role'{..} = object (catMaybes [("stage" .=) <$> _rStage, ("etag" .=) <$> _rEtag, ("includedPermissions" .=) <$> _rIncludedPermissions, ("name" .=) <$> _rName, ("deleted" .=) <$> _rDeleted, ("title" .=) <$> _rTitle, ("description" .=) <$> _rDescription]) -- | An IAM service account. A service account is an account for an -- application or a virtual machine (VM) instance, not a person. You can -- use a service account to call Google APIs. To learn more, read the -- [overview of service -- accounts](https:\/\/cloud.google.com\/iam\/help\/service-accounts\/overview). -- When you create a service account, you specify the project ID that owns -- the service account, as well as a name that must be unique within the -- project. IAM uses these values to create an email address that -- identifies the service account. -- -- /See:/ 'serviceAccount' smart constructor. data ServiceAccount = ServiceAccount' { _saEmail :: !(Maybe Text) , _saEtag :: !(Maybe Bytes) , _saDisabled :: !(Maybe Bool) , _saUniqueId :: !(Maybe Text) , _saName :: !(Maybe Text) , _saDisplayName :: !(Maybe Text) , _saProjectId :: !(Maybe Text) , _saDescription :: !(Maybe Text) , _saOAuth2ClientId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServiceAccount' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'saEmail' -- -- * 'saEtag' -- -- * 'saDisabled' -- -- * 'saUniqueId' -- -- * 'saName' -- -- * 'saDisplayName' -- -- * 'saProjectId' -- -- * 'saDescription' -- -- * 'saOAuth2ClientId' serviceAccount :: ServiceAccount serviceAccount = ServiceAccount' { _saEmail = Nothing , _saEtag = Nothing , _saDisabled = Nothing , _saUniqueId = Nothing , _saName = Nothing , _saDisplayName = Nothing , _saProjectId = Nothing , _saDescription = Nothing , _saOAuth2ClientId = Nothing } -- | Output only. The email address of the service account. saEmail :: Lens' ServiceAccount (Maybe Text) saEmail = lens _saEmail (\ s a -> s{_saEmail = a}) -- | Deprecated. Do not use. saEtag :: Lens' ServiceAccount (Maybe ByteString) saEtag = lens _saEtag (\ s a -> s{_saEtag = a}) . mapping _Bytes -- | Output only. Whether the service account is disabled. saDisabled :: Lens' ServiceAccount (Maybe Bool) saDisabled = lens _saDisabled (\ s a -> s{_saDisabled = a}) -- | Output only. The unique, stable numeric ID for the service account. Each -- service account retains its unique ID even if you delete the service -- account. For example, if you delete a service account, then create a new -- service account with the same name, the new service account has a -- different unique ID than the deleted service account. saUniqueId :: Lens' ServiceAccount (Maybe Text) saUniqueId = lens _saUniqueId (\ s a -> s{_saUniqueId = a}) -- | The resource name of the service account. Use one of the following -- formats: * \`projects\/{PROJECT_ID}\/serviceAccounts\/{EMAIL_ADDRESS}\` -- * \`projects\/{PROJECT_ID}\/serviceAccounts\/{UNIQUE_ID}\` As an -- alternative, you can use the \`-\` wildcard character instead of the -- project ID: * \`projects\/-\/serviceAccounts\/{EMAIL_ADDRESS}\` * -- \`projects\/-\/serviceAccounts\/{UNIQUE_ID}\` When possible, avoid using -- the \`-\` wildcard character, because it can cause response messages to -- contain misleading error codes. For example, if you try to get the -- service account \`projects\/-\/serviceAccounts\/fake\'example.com\`, -- which does not exist, the response contains an HTTP \`403 Forbidden\` -- error instead of a \`404 Not Found\` error. saName :: Lens' ServiceAccount (Maybe Text) saName = lens _saName (\ s a -> s{_saName = a}) -- | Optional. A user-specified, human-readable name for the service account. -- The maximum length is 100 UTF-8 bytes. saDisplayName :: Lens' ServiceAccount (Maybe Text) saDisplayName = lens _saDisplayName (\ s a -> s{_saDisplayName = a}) -- | Output only. The ID of the project that owns the service account. saProjectId :: Lens' ServiceAccount (Maybe Text) saProjectId = lens _saProjectId (\ s a -> s{_saProjectId = a}) -- | Optional. A user-specified, human-readable description of the service -- account. The maximum length is 256 UTF-8 bytes. saDescription :: Lens' ServiceAccount (Maybe Text) saDescription = lens _saDescription (\ s a -> s{_saDescription = a}) -- | Output only. The OAuth 2.0 client ID for the service account. saOAuth2ClientId :: Lens' ServiceAccount (Maybe Text) saOAuth2ClientId = lens _saOAuth2ClientId (\ s a -> s{_saOAuth2ClientId = a}) instance FromJSON ServiceAccount where parseJSON = withObject "ServiceAccount" (\ o -> ServiceAccount' <$> (o .:? "email") <*> (o .:? "etag") <*> (o .:? "disabled") <*> (o .:? "uniqueId") <*> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "projectId") <*> (o .:? "description") <*> (o .:? "oauth2ClientId")) instance ToJSON ServiceAccount where toJSON ServiceAccount'{..} = object (catMaybes [("email" .=) <$> _saEmail, ("etag" .=) <$> _saEtag, ("disabled" .=) <$> _saDisabled, ("uniqueId" .=) <$> _saUniqueId, ("name" .=) <$> _saName, ("displayName" .=) <$> _saDisplayName, ("projectId" .=) <$> _saProjectId, ("description" .=) <$> _saDescription, ("oauth2ClientId" .=) <$> _saOAuth2ClientId]) -- | Maps attributes from authentication credentials issued by an external -- identity provider to Google Cloud attributes, such as \`subject\` and -- \`segment\`. Each key must be a string specifying the Google Cloud IAM -- attribute to map to. The following keys are supported: * -- \`google.subject\`: The principal IAM is authenticating. You can -- reference this value in IAM bindings. This is also the subject that -- appears in Cloud Logging logs. Cannot exceed 127 characters. * -- \`google.groups\`: Groups the external identity belongs to. You can -- grant groups access to resources using an IAM \`principalSet\` binding; -- access applies to all members of the group. You can also provide custom -- attributes by specifying \`attribute.{custom_attribute}\`, where -- \`{custom_attribute}\` is the name of the custom attribute to be mapped. -- You can define a maximum of 50 custom attributes. The maximum length of -- a mapped attribute key is 100 characters, and the key may only contain -- the characters [a-z0-9_]. You can reference these attributes in IAM -- policies to define fine-grained access for a workload to Google Cloud -- resources. For example: * \`google.subject\`: -- \`principal:\/\/iam.googleapis.com\/projects\/{project}\/locations\/{location}\/workloadIdentityPools\/{pool}\/subject\/{value}\` -- * \`google.groups\`: -- \`principalSet:\/\/iam.googleapis.com\/projects\/{project}\/locations\/{location}\/workloadIdentityPools\/{pool}\/group\/{value}\` -- * \`attribute.{custom_attribute}\`: -- \`principalSet:\/\/iam.googleapis.com\/projects\/{project}\/locations\/{location}\/workloadIdentityPools\/{pool}\/attribute.{custom_attribute}\/{value}\` -- Each value must be a [Common Expression Language] -- (https:\/\/opensource.google\/projects\/cel) function that maps an -- identity provider credential to the normalized attribute specified by -- the corresponding map key. You can use the \`assertion\` keyword in the -- expression to access a JSON representation of the authentication -- credential issued by the provider. The maximum length of an attribute -- mapping expression is 2048 characters. When evaluated, the total size of -- all mapped attributes must not exceed 8KB. For AWS providers, if no -- attribute mapping is defined, the following default mapping applies: -- \`\`\` { \"google.subject\":\"assertion.arn\", \"attribute.aws_role\": -- \"assertion.arn.contains(\'assumed-role\')\" \" ? -- assertion.arn.extract(\'{account_arn}assumed-role\/\')\" \" + -- \'assumed-role\/\'\" \" + -- assertion.arn.extract(\'assumed-role\/{role_name}\/\')\" \" : -- assertion.arn\", } \`\`\` If any custom attribute mappings are defined, -- they must include a mapping to the \`google.subject\` attribute. For -- OIDC providers, you must supply a custom mapping, which must include the -- \`google.subject\` attribute. For example, the following maps the -- \`sub\` claim of the incoming credential to the \`subject\` attribute on -- a Google token: \`\`\` {\"google.subject\": \"assertion.sub\"} \`\`\` -- -- /See:/ 'workLoadIdentityPoolProviderAttributeMApping' smart constructor. newtype WorkLoadIdentityPoolProviderAttributeMApping = WorkLoadIdentityPoolProviderAttributeMApping' { _wlippamaAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WorkLoadIdentityPoolProviderAttributeMApping' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wlippamaAddtional' workLoadIdentityPoolProviderAttributeMApping :: HashMap Text Text -- ^ 'wlippamaAddtional' -> WorkLoadIdentityPoolProviderAttributeMApping workLoadIdentityPoolProviderAttributeMApping pWlippamaAddtional_ = WorkLoadIdentityPoolProviderAttributeMApping' {_wlippamaAddtional = _Coerce # pWlippamaAddtional_} wlippamaAddtional :: Lens' WorkLoadIdentityPoolProviderAttributeMApping (HashMap Text Text) wlippamaAddtional = lens _wlippamaAddtional (\ s a -> s{_wlippamaAddtional = a}) . _Coerce instance FromJSON WorkLoadIdentityPoolProviderAttributeMApping where parseJSON = withObject "WorkLoadIdentityPoolProviderAttributeMApping" (\ o -> WorkLoadIdentityPoolProviderAttributeMApping' <$> (parseJSONObject o)) instance ToJSON WorkLoadIdentityPoolProviderAttributeMApping where toJSON = toJSON . _wlippamaAddtional -- | Response message for ListWorkloadIdentityPools. -- -- /See:/ 'listWorkLoadIdentityPoolsResponse' smart constructor. data ListWorkLoadIdentityPoolsResponse = ListWorkLoadIdentityPoolsResponse' { _lwliprNextPageToken :: !(Maybe Text) , _lwliprWorkLoadIdentityPools :: !(Maybe [WorkLoadIdentityPool]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListWorkLoadIdentityPoolsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lwliprNextPageToken' -- -- * 'lwliprWorkLoadIdentityPools' listWorkLoadIdentityPoolsResponse :: ListWorkLoadIdentityPoolsResponse listWorkLoadIdentityPoolsResponse = ListWorkLoadIdentityPoolsResponse' {_lwliprNextPageToken = Nothing, _lwliprWorkLoadIdentityPools = Nothing} -- | A token, which can be sent as \`page_token\` to retrieve the next page. -- If this field is omitted, there are no subsequent pages. lwliprNextPageToken :: Lens' ListWorkLoadIdentityPoolsResponse (Maybe Text) lwliprNextPageToken = lens _lwliprNextPageToken (\ s a -> s{_lwliprNextPageToken = a}) -- | A list of pools. lwliprWorkLoadIdentityPools :: Lens' ListWorkLoadIdentityPoolsResponse [WorkLoadIdentityPool] lwliprWorkLoadIdentityPools = lens _lwliprWorkLoadIdentityPools (\ s a -> s{_lwliprWorkLoadIdentityPools = a}) . _Default . _Coerce instance FromJSON ListWorkLoadIdentityPoolsResponse where parseJSON = withObject "ListWorkLoadIdentityPoolsResponse" (\ o -> ListWorkLoadIdentityPoolsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "workloadIdentityPools" .!= mempty)) instance ToJSON ListWorkLoadIdentityPoolsResponse where toJSON ListWorkLoadIdentityPoolsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lwliprNextPageToken, ("workloadIdentityPools" .=) <$> _lwliprWorkLoadIdentityPools]) -- | A request to get permissions which can be tested on a resource. -- -- /See:/ 'queryTestablePermissionsRequest' smart constructor. data QueryTestablePermissionsRequest = QueryTestablePermissionsRequest' { _qtprFullResourceName :: !(Maybe Text) , _qtprPageToken :: !(Maybe Text) , _qtprPageSize :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'QueryTestablePermissionsRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qtprFullResourceName' -- -- * 'qtprPageToken' -- -- * 'qtprPageSize' queryTestablePermissionsRequest :: QueryTestablePermissionsRequest queryTestablePermissionsRequest = QueryTestablePermissionsRequest' { _qtprFullResourceName = Nothing , _qtprPageToken = Nothing , _qtprPageSize = Nothing } -- | Required. The full resource name to query from the list of testable -- permissions. The name follows the Google Cloud Platform resource format. -- For example, a Cloud Platform project with id \`my-project\` will be -- named \`\/\/cloudresourcemanager.googleapis.com\/projects\/my-project\`. qtprFullResourceName :: Lens' QueryTestablePermissionsRequest (Maybe Text) qtprFullResourceName = lens _qtprFullResourceName (\ s a -> s{_qtprFullResourceName = a}) -- | Optional pagination token returned in an earlier -- QueryTestablePermissionsRequest. qtprPageToken :: Lens' QueryTestablePermissionsRequest (Maybe Text) qtprPageToken = lens _qtprPageToken (\ s a -> s{_qtprPageToken = a}) -- | Optional limit on the number of permissions to include in the response. -- The default is 100, and the maximum is 1,000. qtprPageSize :: Lens' QueryTestablePermissionsRequest (Maybe Int32) qtprPageSize = lens _qtprPageSize (\ s a -> s{_qtprPageSize = a}) . mapping _Coerce instance FromJSON QueryTestablePermissionsRequest where parseJSON = withObject "QueryTestablePermissionsRequest" (\ o -> QueryTestablePermissionsRequest' <$> (o .:? "fullResourceName") <*> (o .:? "pageToken") <*> (o .:? "pageSize")) instance ToJSON QueryTestablePermissionsRequest where toJSON QueryTestablePermissionsRequest'{..} = object (catMaybes [("fullResourceName" .=) <$> _qtprFullResourceName, ("pageToken" .=) <$> _qtprPageToken, ("pageSize" .=) <$> _qtprPageSize]) -- | Request message for UndeleteWorkloadIdentityPoolProvider. -- -- /See:/ 'undeleteWorkLoadIdentityPoolProviderRequest' smart constructor. data UndeleteWorkLoadIdentityPoolProviderRequest = UndeleteWorkLoadIdentityPoolProviderRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UndeleteWorkLoadIdentityPoolProviderRequest' with the minimum fields required to make a request. -- undeleteWorkLoadIdentityPoolProviderRequest :: UndeleteWorkLoadIdentityPoolProviderRequest undeleteWorkLoadIdentityPoolProviderRequest = UndeleteWorkLoadIdentityPoolProviderRequest' instance FromJSON UndeleteWorkLoadIdentityPoolProviderRequest where parseJSON = withObject "UndeleteWorkLoadIdentityPoolProviderRequest" (\ o -> pure UndeleteWorkLoadIdentityPoolProviderRequest') instance ToJSON UndeleteWorkLoadIdentityPoolProviderRequest where toJSON = const emptyObject -- | The grantable role query response. -- -- /See:/ 'queryGrantableRolesResponse' smart constructor. data QueryGrantableRolesResponse = QueryGrantableRolesResponse' { _qgrrRoles :: !(Maybe [Role]) , _qgrrNextPageToken :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'QueryGrantableRolesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qgrrRoles' -- -- * 'qgrrNextPageToken' queryGrantableRolesResponse :: QueryGrantableRolesResponse queryGrantableRolesResponse = QueryGrantableRolesResponse' {_qgrrRoles = Nothing, _qgrrNextPageToken = Nothing} -- | The list of matching roles. qgrrRoles :: Lens' QueryGrantableRolesResponse [Role] qgrrRoles = lens _qgrrRoles (\ s a -> s{_qgrrRoles = a}) . _Default . _Coerce -- | To retrieve the next page of results, set -- \`QueryGrantableRolesRequest.page_token\` to this value. qgrrNextPageToken :: Lens' QueryGrantableRolesResponse (Maybe Text) qgrrNextPageToken = lens _qgrrNextPageToken (\ s a -> s{_qgrrNextPageToken = a}) instance FromJSON QueryGrantableRolesResponse where parseJSON = withObject "QueryGrantableRolesResponse" (\ o -> QueryGrantableRolesResponse' <$> (o .:? "roles" .!= mempty) <*> (o .:? "nextPageToken")) instance ToJSON QueryGrantableRolesResponse where toJSON QueryGrantableRolesResponse'{..} = object (catMaybes [("roles" .=) <$> _qgrrRoles, ("nextPageToken" .=) <$> _qgrrNextPageToken]) -- | Request message for \`TestIamPermissions\` method. -- -- /See:/ 'testIAMPermissionsRequest' smart constructor. newtype TestIAMPermissionsRequest = TestIAMPermissionsRequest' { _tiprPermissions :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TestIAMPermissionsRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiprPermissions' testIAMPermissionsRequest :: TestIAMPermissionsRequest testIAMPermissionsRequest = TestIAMPermissionsRequest' {_tiprPermissions = Nothing} -- | The set of permissions to check for the \`resource\`. Permissions with -- wildcards (such as \'*\' or \'storage.*\') are not allowed. For more -- information see [IAM -- Overview](https:\/\/cloud.google.com\/iam\/docs\/overview#permissions). tiprPermissions :: Lens' TestIAMPermissionsRequest [Text] tiprPermissions = lens _tiprPermissions (\ s a -> s{_tiprPermissions = a}) . _Default . _Coerce instance FromJSON TestIAMPermissionsRequest where parseJSON = withObject "TestIAMPermissionsRequest" (\ o -> TestIAMPermissionsRequest' <$> (o .:? "permissions" .!= mempty)) instance ToJSON TestIAMPermissionsRequest where toJSON TestIAMPermissionsRequest'{..} = object (catMaybes [("permissions" .=) <$> _tiprPermissions]) -- | Audit log information specific to Cloud IAM admin APIs. This message is -- serialized as an \`Any\` type in the \`ServiceData\` message of an -- \`AuditLog\` message. -- -- /See:/ 'adminAuditData' smart constructor. newtype AdminAuditData = AdminAuditData' { _aadPermissionDelta :: Maybe PermissionDelta } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AdminAuditData' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aadPermissionDelta' adminAuditData :: AdminAuditData adminAuditData = AdminAuditData' {_aadPermissionDelta = Nothing} -- | The permission_delta when when creating or updating a Role. aadPermissionDelta :: Lens' AdminAuditData (Maybe PermissionDelta) aadPermissionDelta = lens _aadPermissionDelta (\ s a -> s{_aadPermissionDelta = a}) instance FromJSON AdminAuditData where parseJSON = withObject "AdminAuditData" (\ o -> AdminAuditData' <$> (o .:? "permissionDelta")) instance ToJSON AdminAuditData where toJSON AdminAuditData'{..} = object (catMaybes [("permissionDelta" .=) <$> _aadPermissionDelta]) -- -- /See:/ 'undeleteServiceAccountResponse' smart constructor. newtype UndeleteServiceAccountResponse = UndeleteServiceAccountResponse' { _usarRestoredAccount :: Maybe ServiceAccount } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UndeleteServiceAccountResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'usarRestoredAccount' undeleteServiceAccountResponse :: UndeleteServiceAccountResponse undeleteServiceAccountResponse = UndeleteServiceAccountResponse' {_usarRestoredAccount = Nothing} -- | Metadata for the restored service account. usarRestoredAccount :: Lens' UndeleteServiceAccountResponse (Maybe ServiceAccount) usarRestoredAccount = lens _usarRestoredAccount (\ s a -> s{_usarRestoredAccount = a}) instance FromJSON UndeleteServiceAccountResponse where parseJSON = withObject "UndeleteServiceAccountResponse" (\ o -> UndeleteServiceAccountResponse' <$> (o .:? "restoredAccount")) instance ToJSON UndeleteServiceAccountResponse where toJSON UndeleteServiceAccountResponse'{..} = object (catMaybes [("restoredAccount" .=) <$> _usarRestoredAccount]) -- | Represents a collection of external workload identities. You can define -- IAM policies to grant these identities access to Google Cloud resources. -- -- /See:/ 'workLoadIdentityPool' smart constructor. data WorkLoadIdentityPool = WorkLoadIdentityPool' { _wlipState :: !(Maybe WorkLoadIdentityPoolState) , _wlipDisabled :: !(Maybe Bool) , _wlipName :: !(Maybe Text) , _wlipDisplayName :: !(Maybe Text) , _wlipDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WorkLoadIdentityPool' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wlipState' -- -- * 'wlipDisabled' -- -- * 'wlipName' -- -- * 'wlipDisplayName' -- -- * 'wlipDescription' workLoadIdentityPool :: WorkLoadIdentityPool workLoadIdentityPool = WorkLoadIdentityPool' { _wlipState = Nothing , _wlipDisabled = Nothing , _wlipName = Nothing , _wlipDisplayName = Nothing , _wlipDescription = Nothing } -- | Output only. The state of the pool. wlipState :: Lens' WorkLoadIdentityPool (Maybe WorkLoadIdentityPoolState) wlipState = lens _wlipState (\ s a -> s{_wlipState = a}) -- | Whether the pool is disabled. You cannot use a disabled pool to exchange -- tokens, or use existing tokens to access resources. If the pool is -- re-enabled, existing tokens grant access again. wlipDisabled :: Lens' WorkLoadIdentityPool (Maybe Bool) wlipDisabled = lens _wlipDisabled (\ s a -> s{_wlipDisabled = a}) -- | Output only. The resource name of the pool. wlipName :: Lens' WorkLoadIdentityPool (Maybe Text) wlipName = lens _wlipName (\ s a -> s{_wlipName = a}) -- | A display name for the pool. Cannot exceed 32 characters. wlipDisplayName :: Lens' WorkLoadIdentityPool (Maybe Text) wlipDisplayName = lens _wlipDisplayName (\ s a -> s{_wlipDisplayName = a}) -- | A description of the pool. Cannot exceed 256 characters. wlipDescription :: Lens' WorkLoadIdentityPool (Maybe Text) wlipDescription = lens _wlipDescription (\ s a -> s{_wlipDescription = a}) instance FromJSON WorkLoadIdentityPool where parseJSON = withObject "WorkLoadIdentityPool" (\ o -> WorkLoadIdentityPool' <$> (o .:? "state") <*> (o .:? "disabled") <*> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "description")) instance ToJSON WorkLoadIdentityPool where toJSON WorkLoadIdentityPool'{..} = object (catMaybes [("state" .=) <$> _wlipState, ("disabled" .=) <$> _wlipDisabled, ("name" .=) <$> _wlipName, ("displayName" .=) <$> _wlipDisplayName, ("description" .=) <$> _wlipDescription]) -- | Response message for \`TestIamPermissions\` method. -- -- /See:/ 'testIAMPermissionsResponse' smart constructor. newtype TestIAMPermissionsResponse = TestIAMPermissionsResponse' { _tiamprPermissions :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TestIAMPermissionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiamprPermissions' testIAMPermissionsResponse :: TestIAMPermissionsResponse testIAMPermissionsResponse = TestIAMPermissionsResponse' {_tiamprPermissions = Nothing} -- | A subset of \`TestPermissionsRequest.permissions\` that the caller is -- allowed. tiamprPermissions :: Lens' TestIAMPermissionsResponse [Text] tiamprPermissions = lens _tiamprPermissions (\ s a -> s{_tiamprPermissions = a}) . _Default . _Coerce instance FromJSON TestIAMPermissionsResponse where parseJSON = withObject "TestIAMPermissionsResponse" (\ o -> TestIAMPermissionsResponse' <$> (o .:? "permissions" .!= mempty)) instance ToJSON TestIAMPermissionsResponse where toJSON TestIAMPermissionsResponse'{..} = object (catMaybes [("permissions" .=) <$> _tiamprPermissions]) -- | An Identity and Access Management (IAM) policy, which specifies access -- controls for Google Cloud resources. A \`Policy\` is a collection of -- \`bindings\`. A \`binding\` binds one or more \`members\` to a single -- \`role\`. Members can be user accounts, service accounts, Google groups, -- and domains (such as G Suite). A \`role\` is a named list of -- permissions; each \`role\` can be an IAM predefined role or a -- user-created custom role. For some types of Google Cloud resources, a -- \`binding\` can also specify a \`condition\`, which is a logical -- expression that allows access to a resource only if the expression -- evaluates to \`true\`. A condition can add constraints based on -- attributes of the request, the resource, or both. To learn which -- resources support conditions in their IAM policies, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). -- **JSON example:** { \"bindings\": [ { \"role\": -- \"roles\/resourcemanager.organizationAdmin\", \"members\": [ -- \"user:mike\'example.com\", \"group:admins\'example.com\", -- \"domain:google.com\", -- \"serviceAccount:my-project-id\'appspot.gserviceaccount.com\" ] }, { -- \"role\": \"roles\/resourcemanager.organizationViewer\", \"members\": [ -- \"user:eve\'example.com\" ], \"condition\": { \"title\": \"expirable -- access\", \"description\": \"Does not grant access after Sep 2020\", -- \"expression\": \"request.time \< -- timestamp(\'2020-10-01T00:00:00.000Z\')\", } } ], \"etag\": -- \"BwWWja0YfJA=\", \"version\": 3 } **YAML example:** bindings: - -- members: - user:mike\'example.com - group:admins\'example.com - -- domain:google.com - -- serviceAccount:my-project-id\'appspot.gserviceaccount.com role: -- roles\/resourcemanager.organizationAdmin - members: - -- user:eve\'example.com role: roles\/resourcemanager.organizationViewer -- condition: title: expirable access description: Does not grant access -- after Sep 2020 expression: request.time \< -- timestamp(\'2020-10-01T00:00:00.000Z\') - etag: BwWWja0YfJA= - version: -- 3 For a description of IAM and its features, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/docs\/). -- -- /See:/ 'policy' smart constructor. data Policy = Policy' { _pAuditConfigs :: !(Maybe [AuditConfig]) , _pEtag :: !(Maybe Bytes) , _pVersion :: !(Maybe (Textual Int32)) , _pBindings :: !(Maybe [Binding]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Policy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pAuditConfigs' -- -- * 'pEtag' -- -- * 'pVersion' -- -- * 'pBindings' policy :: Policy policy = Policy' { _pAuditConfigs = Nothing , _pEtag = Nothing , _pVersion = Nothing , _pBindings = Nothing } -- | Specifies cloud audit logging configuration for this policy. pAuditConfigs :: Lens' Policy [AuditConfig] pAuditConfigs = lens _pAuditConfigs (\ s a -> s{_pAuditConfigs = a}) . _Default . _Coerce -- | \`etag\` is used for optimistic concurrency control as a way to help -- prevent simultaneous updates of a policy from overwriting each other. It -- is strongly suggested that systems make use of the \`etag\` in the -- read-modify-write cycle to perform policy updates in order to avoid race -- conditions: An \`etag\` is returned in the response to \`getIamPolicy\`, -- and systems are expected to put that etag in the request to -- \`setIamPolicy\` to ensure that their change will be applied to the same -- version of the policy. **Important:** If you use IAM Conditions, you -- must include the \`etag\` field whenever you call \`setIamPolicy\`. If -- you omit this field, then IAM allows you to overwrite a version \`3\` -- policy with a version \`1\` policy, and all of the conditions in the -- version \`3\` policy are lost. pEtag :: Lens' Policy (Maybe ByteString) pEtag = lens _pEtag (\ s a -> s{_pEtag = a}) . mapping _Bytes -- | Specifies the format of the policy. Valid values are \`0\`, \`1\`, and -- \`3\`. Requests that specify an invalid value are rejected. Any -- operation that affects conditional role bindings must specify version -- \`3\`. This requirement applies to the following operations: * Getting a -- policy that includes a conditional role binding * Adding a conditional -- role binding to a policy * Changing a conditional role binding in a -- policy * Removing any role binding, with or without a condition, from a -- policy that includes conditions **Important:** If you use IAM -- Conditions, you must include the \`etag\` field whenever you call -- \`setIamPolicy\`. If you omit this field, then IAM allows you to -- overwrite a version \`3\` policy with a version \`1\` policy, and all of -- the conditions in the version \`3\` policy are lost. If a policy does -- not include any conditions, operations on that policy may specify any -- valid version or leave the field unset. To learn which resources support -- conditions in their IAM policies, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). pVersion :: Lens' Policy (Maybe Int32) pVersion = lens _pVersion (\ s a -> s{_pVersion = a}) . mapping _Coerce -- | Associates a list of \`members\` to a \`role\`. Optionally, may specify -- a \`condition\` that determines how and when the \`bindings\` are -- applied. Each of the \`bindings\` must contain at least one member. pBindings :: Lens' Policy [Binding] pBindings = lens _pBindings (\ s a -> s{_pBindings = a}) . _Default . _Coerce instance FromJSON Policy where parseJSON = withObject "Policy" (\ o -> Policy' <$> (o .:? "auditConfigs" .!= mempty) <*> (o .:? "etag") <*> (o .:? "version") <*> (o .:? "bindings" .!= mempty)) instance ToJSON Policy where toJSON Policy'{..} = object (catMaybes [("auditConfigs" .=) <$> _pAuditConfigs, ("etag" .=) <$> _pEtag, ("version" .=) <$> _pVersion, ("bindings" .=) <$> _pBindings]) -- | The difference delta between two policies. -- -- /See:/ 'policyDelta' smart constructor. newtype PolicyDelta = PolicyDelta' { _pdBindingDeltas :: Maybe [BindingDelta] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PolicyDelta' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdBindingDeltas' policyDelta :: PolicyDelta policyDelta = PolicyDelta' {_pdBindingDeltas = Nothing} -- | The delta for Bindings between two policies. pdBindingDeltas :: Lens' PolicyDelta [BindingDelta] pdBindingDeltas = lens _pdBindingDeltas (\ s a -> s{_pdBindingDeltas = a}) . _Default . _Coerce instance FromJSON PolicyDelta where parseJSON = withObject "PolicyDelta" (\ o -> PolicyDelta' <$> (o .:? "bindingDeltas" .!= mempty)) instance ToJSON PolicyDelta where toJSON PolicyDelta'{..} = object (catMaybes [("bindingDeltas" .=) <$> _pdBindingDeltas]) -- | The grantable role query request. -- -- /See:/ 'queryGrantableRolesRequest' smart constructor. data QueryGrantableRolesRequest = QueryGrantableRolesRequest' { _qgrrFullResourceName :: !(Maybe Text) , _qgrrView :: !(Maybe QueryGrantableRolesRequestView) , _qgrrPageToken :: !(Maybe Text) , _qgrrPageSize :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'QueryGrantableRolesRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qgrrFullResourceName' -- -- * 'qgrrView' -- -- * 'qgrrPageToken' -- -- * 'qgrrPageSize' queryGrantableRolesRequest :: QueryGrantableRolesRequest queryGrantableRolesRequest = QueryGrantableRolesRequest' { _qgrrFullResourceName = Nothing , _qgrrView = Nothing , _qgrrPageToken = Nothing , _qgrrPageSize = Nothing } -- | Required. The full resource name to query from the list of grantable -- roles. The name follows the Google Cloud Platform resource format. For -- example, a Cloud Platform project with id \`my-project\` will be named -- \`\/\/cloudresourcemanager.googleapis.com\/projects\/my-project\`. qgrrFullResourceName :: Lens' QueryGrantableRolesRequest (Maybe Text) qgrrFullResourceName = lens _qgrrFullResourceName (\ s a -> s{_qgrrFullResourceName = a}) qgrrView :: Lens' QueryGrantableRolesRequest (Maybe QueryGrantableRolesRequestView) qgrrView = lens _qgrrView (\ s a -> s{_qgrrView = a}) -- | Optional pagination token returned in an earlier -- QueryGrantableRolesResponse. qgrrPageToken :: Lens' QueryGrantableRolesRequest (Maybe Text) qgrrPageToken = lens _qgrrPageToken (\ s a -> s{_qgrrPageToken = a}) -- | Optional limit on the number of roles to include in the response. The -- default is 300, and the maximum is 1,000. qgrrPageSize :: Lens' QueryGrantableRolesRequest (Maybe Int32) qgrrPageSize = lens _qgrrPageSize (\ s a -> s{_qgrrPageSize = a}) . mapping _Coerce instance FromJSON QueryGrantableRolesRequest where parseJSON = withObject "QueryGrantableRolesRequest" (\ o -> QueryGrantableRolesRequest' <$> (o .:? "fullResourceName") <*> (o .:? "view") <*> (o .:? "pageToken") <*> (o .:? "pageSize")) instance ToJSON QueryGrantableRolesRequest where toJSON QueryGrantableRolesRequest'{..} = object (catMaybes [("fullResourceName" .=) <$> _qgrrFullResourceName, ("view" .=) <$> _qgrrView, ("pageToken" .=) <$> _qgrrPageToken, ("pageSize" .=) <$> _qgrrPageSize]) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. -- -- /See:/ 'operationMetadata' smart constructor. newtype OperationMetadata = OperationMetadata' { _omAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'omAddtional' operationMetadata :: HashMap Text JSONValue -- ^ 'omAddtional' -> OperationMetadata operationMetadata pOmAddtional_ = OperationMetadata' {_omAddtional = _Coerce # pOmAddtional_} -- | Properties of the object. Contains field \'type with type URL. omAddtional :: Lens' OperationMetadata (HashMap Text JSONValue) omAddtional = lens _omAddtional (\ s a -> s{_omAddtional = a}) . _Coerce instance FromJSON OperationMetadata where parseJSON = withObject "OperationMetadata" (\ o -> OperationMetadata' <$> (parseJSONObject o)) instance ToJSON OperationMetadata where toJSON = toJSON . _omAddtional -- | Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The service account sign JWT request. -- -- /See:/ 'signJwtRequest' smart constructor. newtype SignJwtRequest = SignJwtRequest' { _sjrPayload :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SignJwtRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sjrPayload' signJwtRequest :: SignJwtRequest signJwtRequest = SignJwtRequest' {_sjrPayload = Nothing} -- | Required. Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The JWT payload to sign. Must be a serialized JSON object that contains -- a JWT Claims Set. For example: \`{\"sub\": \"user\'example.com\", -- \"iat\": 313435}\` If the JWT Claims Set contains an expiration time -- (\`exp\`) claim, it must be an integer timestamp that is not in the past -- and no more than 1 hour in the future. If the JWT Claims Set does not -- contain an expiration time (\`exp\`) claim, this claim is added -- automatically, with a timestamp that is 1 hour in the future. sjrPayload :: Lens' SignJwtRequest (Maybe Text) sjrPayload = lens _sjrPayload (\ s a -> s{_sjrPayload = a}) instance FromJSON SignJwtRequest where parseJSON = withObject "SignJwtRequest" (\ o -> SignJwtRequest' <$> (o .:? "payload")) instance ToJSON SignJwtRequest where toJSON SignJwtRequest'{..} = object (catMaybes [("payload" .=) <$> _sjrPayload]) -- | The request for PatchServiceAccount. You can patch only the -- \`display_name\` and \`description\` fields. You must use the -- \`update_mask\` field to specify which of these fields you want to -- patch. Only the fields specified in the request are guaranteed to be -- returned in the response. Other fields may be empty in the response. -- -- /See:/ 'patchServiceAccountRequest' smart constructor. data PatchServiceAccountRequest = PatchServiceAccountRequest' { _psarUpdateMask :: !(Maybe GFieldMask) , _psarServiceAccount :: !(Maybe ServiceAccount) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PatchServiceAccountRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psarUpdateMask' -- -- * 'psarServiceAccount' patchServiceAccountRequest :: PatchServiceAccountRequest patchServiceAccountRequest = PatchServiceAccountRequest' {_psarUpdateMask = Nothing, _psarServiceAccount = Nothing} psarUpdateMask :: Lens' PatchServiceAccountRequest (Maybe GFieldMask) psarUpdateMask = lens _psarUpdateMask (\ s a -> s{_psarUpdateMask = a}) psarServiceAccount :: Lens' PatchServiceAccountRequest (Maybe ServiceAccount) psarServiceAccount = lens _psarServiceAccount (\ s a -> s{_psarServiceAccount = a}) instance FromJSON PatchServiceAccountRequest where parseJSON = withObject "PatchServiceAccountRequest" (\ o -> PatchServiceAccountRequest' <$> (o .:? "updateMask") <*> (o .:? "serviceAccount")) instance ToJSON PatchServiceAccountRequest where toJSON PatchServiceAccountRequest'{..} = object (catMaybes [("updateMask" .=) <$> _psarUpdateMask, ("serviceAccount" .=) <$> _psarServiceAccount]) -- | Provides the configuration for logging a type of permissions. Example: { -- \"audit_log_configs\": [ { \"log_type\": \"DATA_READ\", -- \"exempted_members\": [ \"user:jose\'example.com\" ] }, { \"log_type\": -- \"DATA_WRITE\" } ] } This enables \'DATA_READ\' and \'DATA_WRITE\' -- logging, while exempting jose\'example.com from DATA_READ logging. -- -- /See:/ 'auditLogConfig' smart constructor. data AuditLogConfig = AuditLogConfig' { _alcLogType :: !(Maybe AuditLogConfigLogType) , _alcExemptedMembers :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuditLogConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alcLogType' -- -- * 'alcExemptedMembers' auditLogConfig :: AuditLogConfig auditLogConfig = AuditLogConfig' {_alcLogType = Nothing, _alcExemptedMembers = Nothing} -- | The log type that this config enables. alcLogType :: Lens' AuditLogConfig (Maybe AuditLogConfigLogType) alcLogType = lens _alcLogType (\ s a -> s{_alcLogType = a}) -- | Specifies the identities that do not cause logging for this type of -- permission. Follows the same format of Binding.members. alcExemptedMembers :: Lens' AuditLogConfig [Text] alcExemptedMembers = lens _alcExemptedMembers (\ s a -> s{_alcExemptedMembers = a}) . _Default . _Coerce instance FromJSON AuditLogConfig where parseJSON = withObject "AuditLogConfig" (\ o -> AuditLogConfig' <$> (o .:? "logType") <*> (o .:? "exemptedMembers" .!= mempty)) instance ToJSON AuditLogConfig where toJSON AuditLogConfig'{..} = object (catMaybes [("logType" .=) <$> _alcLogType, ("exemptedMembers" .=) <$> _alcExemptedMembers]) -- | A permission which can be included by a role. -- -- /See:/ 'permission' smart constructor. data Permission = Permission' { _perStage :: !(Maybe PermissionStage) , _perPrimaryPermission :: !(Maybe Text) , _perOnlyInPredefinedRoles :: !(Maybe Bool) , _perCustomRolesSupportLevel :: !(Maybe PermissionCustomRolesSupportLevel) , _perName :: !(Maybe Text) , _perTitle :: !(Maybe Text) , _perAPIdisabled :: !(Maybe Bool) , _perDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Permission' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'perStage' -- -- * 'perPrimaryPermission' -- -- * 'perOnlyInPredefinedRoles' -- -- * 'perCustomRolesSupportLevel' -- -- * 'perName' -- -- * 'perTitle' -- -- * 'perAPIdisabled' -- -- * 'perDescription' permission :: Permission permission = Permission' { _perStage = Nothing , _perPrimaryPermission = Nothing , _perOnlyInPredefinedRoles = Nothing , _perCustomRolesSupportLevel = Nothing , _perName = Nothing , _perTitle = Nothing , _perAPIdisabled = Nothing , _perDescription = Nothing } -- | The current launch stage of the permission. perStage :: Lens' Permission (Maybe PermissionStage) perStage = lens _perStage (\ s a -> s{_perStage = a}) -- | The preferred name for this permission. If present, then this permission -- is an alias of, and equivalent to, the listed primary_permission. perPrimaryPermission :: Lens' Permission (Maybe Text) perPrimaryPermission = lens _perPrimaryPermission (\ s a -> s{_perPrimaryPermission = a}) perOnlyInPredefinedRoles :: Lens' Permission (Maybe Bool) perOnlyInPredefinedRoles = lens _perOnlyInPredefinedRoles (\ s a -> s{_perOnlyInPredefinedRoles = a}) -- | The current custom role support level. perCustomRolesSupportLevel :: Lens' Permission (Maybe PermissionCustomRolesSupportLevel) perCustomRolesSupportLevel = lens _perCustomRolesSupportLevel (\ s a -> s{_perCustomRolesSupportLevel = a}) -- | The name of this Permission. perName :: Lens' Permission (Maybe Text) perName = lens _perName (\ s a -> s{_perName = a}) -- | The title of this Permission. perTitle :: Lens' Permission (Maybe Text) perTitle = lens _perTitle (\ s a -> s{_perTitle = a}) -- | The service API associated with the permission is not enabled. perAPIdisabled :: Lens' Permission (Maybe Bool) perAPIdisabled = lens _perAPIdisabled (\ s a -> s{_perAPIdisabled = a}) -- | A brief description of what this Permission is used for. This permission -- can ONLY be used in predefined roles. perDescription :: Lens' Permission (Maybe Text) perDescription = lens _perDescription (\ s a -> s{_perDescription = a}) instance FromJSON Permission where parseJSON = withObject "Permission" (\ o -> Permission' <$> (o .:? "stage") <*> (o .:? "primaryPermission") <*> (o .:? "onlyInPredefinedRoles") <*> (o .:? "customRolesSupportLevel") <*> (o .:? "name") <*> (o .:? "title") <*> (o .:? "apiDisabled") <*> (o .:? "description")) instance ToJSON Permission where toJSON Permission'{..} = object (catMaybes [("stage" .=) <$> _perStage, ("primaryPermission" .=) <$> _perPrimaryPermission, ("onlyInPredefinedRoles" .=) <$> _perOnlyInPredefinedRoles, ("customRolesSupportLevel" .=) <$> _perCustomRolesSupportLevel, ("name" .=) <$> _perName, ("title" .=) <$> _perTitle, ("apiDisabled" .=) <$> _perAPIdisabled, ("description" .=) <$> _perDescription]) -- | Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The service account sign blob response. -- -- /See:/ 'signBlobResponse' smart constructor. data SignBlobResponse = SignBlobResponse' { _sbrSignature :: !(Maybe Bytes) , _sbrKeyId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SignBlobResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sbrSignature' -- -- * 'sbrKeyId' signBlobResponse :: SignBlobResponse signBlobResponse = SignBlobResponse' {_sbrSignature = Nothing, _sbrKeyId = Nothing} -- | Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The signed blob. sbrSignature :: Lens' SignBlobResponse (Maybe ByteString) sbrSignature = lens _sbrSignature (\ s a -> s{_sbrSignature = a}) . mapping _Bytes -- | Deprecated. [Migrate to Service Account Credentials -- API](https:\/\/cloud.google.com\/iam\/help\/credentials\/migrate-api). -- The id of the key used to sign the blob. sbrKeyId :: Lens' SignBlobResponse (Maybe Text) sbrKeyId = lens _sbrKeyId (\ s a -> s{_sbrKeyId = a}) instance FromJSON SignBlobResponse where parseJSON = withObject "SignBlobResponse" (\ o -> SignBlobResponse' <$> (o .:? "signature") <*> (o .:? "keyId")) instance ToJSON SignBlobResponse where toJSON SignBlobResponse'{..} = object (catMaybes [("signature" .=) <$> _sbrSignature, ("keyId" .=) <$> _sbrKeyId]) -- | The service account list response. -- -- /See:/ 'listServiceAccountsResponse' smart constructor. data ListServiceAccountsResponse = ListServiceAccountsResponse' { _lsarNextPageToken :: !(Maybe Text) , _lsarAccounts :: !(Maybe [ServiceAccount]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListServiceAccountsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsarNextPageToken' -- -- * 'lsarAccounts' listServiceAccountsResponse :: ListServiceAccountsResponse listServiceAccountsResponse = ListServiceAccountsResponse' {_lsarNextPageToken = Nothing, _lsarAccounts = Nothing} -- | To retrieve the next page of results, set -- ListServiceAccountsRequest.page_token to this value. lsarNextPageToken :: Lens' ListServiceAccountsResponse (Maybe Text) lsarNextPageToken = lens _lsarNextPageToken (\ s a -> s{_lsarNextPageToken = a}) -- | The list of matching service accounts. lsarAccounts :: Lens' ListServiceAccountsResponse [ServiceAccount] lsarAccounts = lens _lsarAccounts (\ s a -> s{_lsarAccounts = a}) . _Default . _Coerce instance FromJSON ListServiceAccountsResponse where parseJSON = withObject "ListServiceAccountsResponse" (\ o -> ListServiceAccountsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "accounts" .!= mempty)) instance ToJSON ListServiceAccountsResponse where toJSON ListServiceAccountsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lsarNextPageToken, ("accounts" .=) <$> _lsarAccounts]) -- | The request to lint a Cloud IAM policy object. -- -- /See:/ 'lintPolicyRequest' smart constructor. data LintPolicyRequest = LintPolicyRequest' { _lprFullResourceName :: !(Maybe Text) , _lprCondition :: !(Maybe Expr) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LintPolicyRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lprFullResourceName' -- -- * 'lprCondition' lintPolicyRequest :: LintPolicyRequest lintPolicyRequest = LintPolicyRequest' {_lprFullResourceName = Nothing, _lprCondition = Nothing} -- | The full resource name of the policy this lint request is about. The -- name follows the Google Cloud Platform (GCP) resource format. For -- example, a GCP project with ID \`my-project\` will be named -- \`\/\/cloudresourcemanager.googleapis.com\/projects\/my-project\`. The -- resource name is not used to read the policy instance from the Cloud IAM -- database. The candidate policy for lint has to be provided in the same -- request object. lprFullResourceName :: Lens' LintPolicyRequest (Maybe Text) lprFullResourceName = lens _lprFullResourceName (\ s a -> s{_lprFullResourceName = a}) -- | google.iam.v1.Binding.condition object to be linted. lprCondition :: Lens' LintPolicyRequest (Maybe Expr) lprCondition = lens _lprCondition (\ s a -> s{_lprCondition = a}) instance FromJSON LintPolicyRequest where parseJSON = withObject "LintPolicyRequest" (\ o -> LintPolicyRequest' <$> (o .:? "fullResourceName") <*> (o .:? "condition")) instance ToJSON LintPolicyRequest where toJSON LintPolicyRequest'{..} = object (catMaybes [("fullResourceName" .=) <$> _lprFullResourceName, ("condition" .=) <$> _lprCondition]) -- | The response containing the roles defined under a resource. -- -- /See:/ 'listRolesResponse' smart constructor. data ListRolesResponse = ListRolesResponse' { _lrrRoles :: !(Maybe [Role]) , _lrrNextPageToken :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListRolesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lrrRoles' -- -- * 'lrrNextPageToken' listRolesResponse :: ListRolesResponse listRolesResponse = ListRolesResponse' {_lrrRoles = Nothing, _lrrNextPageToken = Nothing} -- | The Roles defined on this resource. lrrRoles :: Lens' ListRolesResponse [Role] lrrRoles = lens _lrrRoles (\ s a -> s{_lrrRoles = a}) . _Default . _Coerce -- | To retrieve the next page of results, set -- \`ListRolesRequest.page_token\` to this value. lrrNextPageToken :: Lens' ListRolesResponse (Maybe Text) lrrNextPageToken = lens _lrrNextPageToken (\ s a -> s{_lrrNextPageToken = a}) instance FromJSON ListRolesResponse where parseJSON = withObject "ListRolesResponse" (\ o -> ListRolesResponse' <$> (o .:? "roles" .!= mempty) <*> (o .:? "nextPageToken")) instance ToJSON ListRolesResponse where toJSON ListRolesResponse'{..} = object (catMaybes [("roles" .=) <$> _lrrRoles, ("nextPageToken" .=) <$> _lrrNextPageToken]) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. -- -- /See:/ 'operationResponse' smart constructor. newtype OperationResponse = OperationResponse' { _orAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orAddtional' operationResponse :: HashMap Text JSONValue -- ^ 'orAddtional' -> OperationResponse operationResponse pOrAddtional_ = OperationResponse' {_orAddtional = _Coerce # pOrAddtional_} -- | Properties of the object. Contains field \'type with type URL. orAddtional :: Lens' OperationResponse (HashMap Text JSONValue) orAddtional = lens _orAddtional (\ s a -> s{_orAddtional = a}) . _Coerce instance FromJSON OperationResponse where parseJSON = withObject "OperationResponse" (\ o -> OperationResponse' <$> (parseJSONObject o)) instance ToJSON OperationResponse where toJSON = toJSON . _orAddtional -- | The service account create request. -- -- /See:/ 'createServiceAccountRequest' smart constructor. data CreateServiceAccountRequest = CreateServiceAccountRequest' { _csarServiceAccount :: !(Maybe ServiceAccount) , _csarAccountId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CreateServiceAccountRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'csarServiceAccount' -- -- * 'csarAccountId' createServiceAccountRequest :: CreateServiceAccountRequest createServiceAccountRequest = CreateServiceAccountRequest' {_csarServiceAccount = Nothing, _csarAccountId = Nothing} -- | The ServiceAccount resource to create. Currently, only the following -- values are user assignable: \`display_name\` and \`description\`. csarServiceAccount :: Lens' CreateServiceAccountRequest (Maybe ServiceAccount) csarServiceAccount = lens _csarServiceAccount (\ s a -> s{_csarServiceAccount = a}) -- | Required. The account id that is used to generate the service account -- email address and a stable unique id. It is unique within a project, -- must be 6-30 characters long, and match the regular expression -- \`[a-z]([-a-z0-9]*[a-z0-9])\` to comply with RFC1035. csarAccountId :: Lens' CreateServiceAccountRequest (Maybe Text) csarAccountId = lens _csarAccountId (\ s a -> s{_csarAccountId = a}) instance FromJSON CreateServiceAccountRequest where parseJSON = withObject "CreateServiceAccountRequest" (\ o -> CreateServiceAccountRequest' <$> (o .:? "serviceAccount") <*> (o .:? "accountId")) instance ToJSON CreateServiceAccountRequest where toJSON CreateServiceAccountRequest'{..} = object (catMaybes [("serviceAccount" .=) <$> _csarServiceAccount, ("accountId" .=) <$> _csarAccountId]) -- | Represents an OpenId Connect 1.0 identity provider. -- -- /See:/ 'oidc' smart constructor. data Oidc = Oidc' { _oAllowedAudiences :: !(Maybe [Text]) , _oIssuerURI :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Oidc' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oAllowedAudiences' -- -- * 'oIssuerURI' oidc :: Oidc oidc = Oidc' {_oAllowedAudiences = Nothing, _oIssuerURI = Nothing} -- | Acceptable values for the \`aud\` field (audience) in the OIDC token. -- Token exchange requests are rejected if the token audience does not -- match one of the configured values. Each audience may be at most 256 -- characters. A maximum of 10 audiences may be configured. If this list is -- empty, the OIDC token audience must be equal to the full canonical -- resource name of the WorkloadIdentityPoolProvider, with or without the -- HTTPS prefix. For example: \`\`\` -- \/\/iam.googleapis.com\/projects\/\/locations\/\/workloadIdentityPools\/\/providers\/ -- https:\/\/iam.googleapis.com\/projects\/\/locations\/\/workloadIdentityPools\/\/providers\/ -- \`\`\` oAllowedAudiences :: Lens' Oidc [Text] oAllowedAudiences = lens _oAllowedAudiences (\ s a -> s{_oAllowedAudiences = a}) . _Default . _Coerce -- | Required. The OIDC issuer URL. Must be an HTTPS endpoint. oIssuerURI :: Lens' Oidc (Maybe Text) oIssuerURI = lens _oIssuerURI (\ s a -> s{_oIssuerURI = a}) instance FromJSON Oidc where parseJSON = withObject "Oidc" (\ o -> Oidc' <$> (o .:? "allowedAudiences" .!= mempty) <*> (o .:? "issuerUri")) instance ToJSON Oidc where toJSON Oidc'{..} = object (catMaybes [("allowedAudiences" .=) <$> _oAllowedAudiences, ("issuerUri" .=) <$> _oIssuerURI]) -- | The request to create a new role. -- -- /See:/ 'createRoleRequest' smart constructor. data CreateRoleRequest = CreateRoleRequest' { _crrRoleId :: !(Maybe Text) , _crrRole :: !(Maybe Role) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CreateRoleRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'crrRoleId' -- -- * 'crrRole' createRoleRequest :: CreateRoleRequest createRoleRequest = CreateRoleRequest' {_crrRoleId = Nothing, _crrRole = Nothing} -- | The role ID to use for this role. A role ID may contain alphanumeric -- characters, underscores (\`_\`), and periods (\`.\`). It must contain a -- minimum of 3 characters and a maximum of 64 characters. crrRoleId :: Lens' CreateRoleRequest (Maybe Text) crrRoleId = lens _crrRoleId (\ s a -> s{_crrRoleId = a}) -- | The Role resource to create. crrRole :: Lens' CreateRoleRequest (Maybe Role) crrRole = lens _crrRole (\ s a -> s{_crrRole = a}) instance FromJSON CreateRoleRequest where parseJSON = withObject "CreateRoleRequest" (\ o -> CreateRoleRequest' <$> (o .:? "roleId") <*> (o .:? "role")) instance ToJSON CreateRoleRequest where toJSON CreateRoleRequest'{..} = object (catMaybes [("roleId" .=) <$> _crrRoleId, ("role" .=) <$> _crrRole]) -- | The service account key upload request. -- -- /See:/ 'uploadServiceAccountKeyRequest' smart constructor. newtype UploadServiceAccountKeyRequest = UploadServiceAccountKeyRequest' { _usakrPublicKeyData :: Maybe Bytes } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UploadServiceAccountKeyRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'usakrPublicKeyData' uploadServiceAccountKeyRequest :: UploadServiceAccountKeyRequest uploadServiceAccountKeyRequest = UploadServiceAccountKeyRequest' {_usakrPublicKeyData = Nothing} -- | A field that allows clients to upload their own public key. If set, use -- this public key data to create a service account key for given service -- account. Please note, the expected format for this field is X509_PEM. usakrPublicKeyData :: Lens' UploadServiceAccountKeyRequest (Maybe ByteString) usakrPublicKeyData = lens _usakrPublicKeyData (\ s a -> s{_usakrPublicKeyData = a}) . mapping _Bytes instance FromJSON UploadServiceAccountKeyRequest where parseJSON = withObject "UploadServiceAccountKeyRequest" (\ o -> UploadServiceAccountKeyRequest' <$> (o .:? "publicKeyData")) instance ToJSON UploadServiceAccountKeyRequest where toJSON UploadServiceAccountKeyRequest'{..} = object (catMaybes [("publicKeyData" .=) <$> _usakrPublicKeyData]) -- | Associates \`members\` with a \`role\`. -- -- /See:/ 'binding' smart constructor. data Binding = Binding' { _bMembers :: !(Maybe [Text]) , _bRole :: !(Maybe Text) , _bCondition :: !(Maybe Expr) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Binding' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bMembers' -- -- * 'bRole' -- -- * 'bCondition' binding :: Binding binding = Binding' {_bMembers = Nothing, _bRole = Nothing, _bCondition = Nothing} -- | Specifies the identities requesting access for a Cloud Platform -- resource. \`members\` can have the following values: * \`allUsers\`: A -- special identifier that represents anyone who is on the internet; with -- or without a Google account. * \`allAuthenticatedUsers\`: A special -- identifier that represents anyone who is authenticated with a Google -- account or a service account. * \`user:{emailid}\`: An email address -- that represents a specific Google account. For example, -- \`alice\'example.com\` . * \`serviceAccount:{emailid}\`: An email -- address that represents a service account. For example, -- \`my-other-app\'appspot.gserviceaccount.com\`. * \`group:{emailid}\`: An -- email address that represents a Google group. For example, -- \`admins\'example.com\`. * \`deleted:user:{emailid}?uid={uniqueid}\`: An -- email address (plus unique identifier) representing a user that has been -- recently deleted. For example, -- \`alice\'example.com?uid=123456789012345678901\`. If the user is -- recovered, this value reverts to \`user:{emailid}\` and the recovered -- user retains the role in the binding. * -- \`deleted:serviceAccount:{emailid}?uid={uniqueid}\`: An email address -- (plus unique identifier) representing a service account that has been -- recently deleted. For example, -- \`my-other-app\'appspot.gserviceaccount.com?uid=123456789012345678901\`. -- If the service account is undeleted, this value reverts to -- \`serviceAccount:{emailid}\` and the undeleted service account retains -- the role in the binding. * \`deleted:group:{emailid}?uid={uniqueid}\`: -- An email address (plus unique identifier) representing a Google group -- that has been recently deleted. For example, -- \`admins\'example.com?uid=123456789012345678901\`. If the group is -- recovered, this value reverts to \`group:{emailid}\` and the recovered -- group retains the role in the binding. * \`domain:{domain}\`: The G -- Suite domain (primary) that represents all the users of that domain. For -- example, \`google.com\` or \`example.com\`. bMembers :: Lens' Binding [Text] bMembers = lens _bMembers (\ s a -> s{_bMembers = a}) . _Default . _Coerce -- | Role that is assigned to \`members\`. For example, \`roles\/viewer\`, -- \`roles\/editor\`, or \`roles\/owner\`. bRole :: Lens' Binding (Maybe Text) bRole = lens _bRole (\ s a -> s{_bRole = a}) -- | The condition that is associated with this binding. If the condition -- evaluates to \`true\`, then this binding applies to the current request. -- If the condition evaluates to \`false\`, then this binding does not -- apply to the current request. However, a different role binding might -- grant the same role to one or more of the members in this binding. To -- learn which resources support conditions in their IAM policies, see the -- [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). bCondition :: Lens' Binding (Maybe Expr) bCondition = lens _bCondition (\ s a -> s{_bCondition = a}) instance FromJSON Binding where parseJSON = withObject "Binding" (\ o -> Binding' <$> (o .:? "members" .!= mempty) <*> (o .:? "role") <*> (o .:? "condition")) instance ToJSON Binding where toJSON Binding'{..} = object (catMaybes [("members" .=) <$> _bMembers, ("role" .=) <$> _bRole, ("condition" .=) <$> _bCondition]) -- | The service account disable request. -- -- /See:/ 'disableServiceAccountRequest' smart constructor. data DisableServiceAccountRequest = DisableServiceAccountRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DisableServiceAccountRequest' with the minimum fields required to make a request. -- disableServiceAccountRequest :: DisableServiceAccountRequest disableServiceAccountRequest = DisableServiceAccountRequest' instance FromJSON DisableServiceAccountRequest where parseJSON = withObject "DisableServiceAccountRequest" (\ o -> pure DisableServiceAccountRequest') instance ToJSON DisableServiceAccountRequest where toJSON = const emptyObject
brendanhay/gogol
gogol-iam/gen/Network/Google/IAM/Types/Product.hs
mpl-2.0
129,943
0
19
27,933
19,204
11,158
8,046
2,122
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Subnetworks.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 the specified subnetwork. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.subnetworks.delete@. module Network.Google.Resource.Compute.Subnetworks.Delete ( -- * REST Resource SubnetworksDeleteResource -- * Creating a Request , subnetworksDelete , SubnetworksDelete -- * Request Lenses , sdRequestId , sdProject , sdSubnetwork , sdRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.subnetworks.delete@ method which the -- 'SubnetworksDelete' request conforms to. type SubnetworksDeleteResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "subnetworks" :> Capture "subnetwork" Text :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Operation -- | Deletes the specified subnetwork. -- -- /See:/ 'subnetworksDelete' smart constructor. data SubnetworksDelete = SubnetworksDelete' { _sdRequestId :: !(Maybe Text) , _sdProject :: !Text , _sdSubnetwork :: !Text , _sdRegion :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SubnetworksDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdRequestId' -- -- * 'sdProject' -- -- * 'sdSubnetwork' -- -- * 'sdRegion' subnetworksDelete :: Text -- ^ 'sdProject' -> Text -- ^ 'sdSubnetwork' -> Text -- ^ 'sdRegion' -> SubnetworksDelete subnetworksDelete pSdProject_ pSdSubnetwork_ pSdRegion_ = SubnetworksDelete' { _sdRequestId = Nothing , _sdProject = pSdProject_ , _sdSubnetwork = pSdSubnetwork_ , _sdRegion = pSdRegion_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). sdRequestId :: Lens' SubnetworksDelete (Maybe Text) sdRequestId = lens _sdRequestId (\ s a -> s{_sdRequestId = a}) -- | Project ID for this request. sdProject :: Lens' SubnetworksDelete Text sdProject = lens _sdProject (\ s a -> s{_sdProject = a}) -- | Name of the Subnetwork resource to delete. sdSubnetwork :: Lens' SubnetworksDelete Text sdSubnetwork = lens _sdSubnetwork (\ s a -> s{_sdSubnetwork = a}) -- | Name of the region scoping this request. sdRegion :: Lens' SubnetworksDelete Text sdRegion = lens _sdRegion (\ s a -> s{_sdRegion = a}) instance GoogleRequest SubnetworksDelete where type Rs SubnetworksDelete = Operation type Scopes SubnetworksDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient SubnetworksDelete'{..} = go _sdProject _sdRegion _sdSubnetwork _sdRequestId (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy SubnetworksDeleteResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Subnetworks/Delete.hs
mpl-2.0
4,564
0
17
1,047
552
330
222
84
1
{-# LANGUAGE FlexibleContexts #-} import Data.IORef import RedBlack import Control.Monad.Identity import Control.Monad import Control.Monad.State test1 :: RedBlackMonad Int () m => m () test1 = do update (Nothing::(Maybe (Visit Int ()))) test2 :: RedBlackMonad Int () m => m () test2 = do update $ Just $ Visit (Red, 1::Int, Just ()) double :: State Integer () double = get >>= put . (* 2) runStateOn ref st = do readIORef ref >>= writeIORef ref . \s -> let (s', x) = runState st s in x --runStateOn ref st = atomicModifyIORef ref $ \s -> let (s', x) = runState st s in (x, s') main :: IO () main = do myRef <- newIORef (Root (Leaf::(Tree (Visit Int ())))) runStateOn myRef $ do test2 down L test2 readIORef myRef >>= putStrLn . show test ref n = replicateM_ n $ do runStateOn ref double readIORef ref >>= putStrLn . show
amiller/redblackmerkle
haskell/test_redblack.hs
agpl-3.0
857
2
16
187
373
178
195
27
1
{-# LANGUAGE OverloadedStrings, RecordWildCards, DataKinds #-} module Model.Slot ( module Model.Slot.Types , lookupSlot , lookupContainerSlot , auditSlotDownload , slotJSON ) where import Database.PostgreSQL.Typed.Types import qualified Data.String import qualified JSON import Service.DB import Model.Id import Model.Identity import Model.Audit import Model.Segment import Model.Container import Model.Slot.Types -- | Look up a Slot by its Id, gated by the running Identity's permission to view -- the Slot's Container's Volume. :) lookupSlot :: (MonadDB c m, MonadHasIdentity c m) => Id Slot -> m (Maybe Slot) lookupSlot (Id (SlotId cont seg)) = fmap (`Slot` seg) <$> lookupContainer cont -- | Look up a Slot by its Container's Id, gated by the running Identity's -- permission to view the Volume containing the Container (which contains the -- Slot). lookupContainerSlot :: (MonadDB c m, MonadHasIdentity c m) => Id Container -> m (Maybe Slot) lookupContainerSlot = lookupSlot . containerSlotId auditSlotDownload :: MonadAudit c m => Bool -> Slot -> m () auditSlotDownload success Slot{ slotContainer = c, slotSegment = seg } = do let _tenv_abUAX = unknownPGTypeEnv ai <- getAuditIdentity dbExecute1' -- [pgSQL|$INSERT INTO audit.slot (audit_action, audit_user, audit_ip, container, segment) VALUES -- (${if success then AuditActionOpen else AuditActionAttempt}, ${auditWho ai}, ${auditIp ai}, ${containerId $ containerRow c}, ${seg})|] (mapPrepQuery ((\ _p_abUAY _p_abUAZ _p_abUB0 _p_abUB1 _p_abUB2 -> (Data.String.fromString "INSERT INTO audit.slot (audit_action, audit_user, audit_ip, container, segment) VALUES\n\ \ ($1, $2, $3, $4, $5)", [Database.PostgreSQL.Typed.Types.pgEncodeParameter _tenv_abUAX (Database.PostgreSQL.Typed.Types.PGTypeProxy :: Database.PostgreSQL.Typed.Types.PGTypeName "audit.action") _p_abUAY, Database.PostgreSQL.Typed.Types.pgEncodeParameter _tenv_abUAX (Database.PostgreSQL.Typed.Types.PGTypeProxy :: Database.PostgreSQL.Typed.Types.PGTypeName "integer") _p_abUAZ, Database.PostgreSQL.Typed.Types.pgEncodeParameter _tenv_abUAX (Database.PostgreSQL.Typed.Types.PGTypeProxy :: Database.PostgreSQL.Typed.Types.PGTypeName "inet") _p_abUB0, Database.PostgreSQL.Typed.Types.pgEncodeParameter _tenv_abUAX (Database.PostgreSQL.Typed.Types.PGTypeProxy :: Database.PostgreSQL.Typed.Types.PGTypeName "integer") _p_abUB1, Database.PostgreSQL.Typed.Types.pgEncodeParameter _tenv_abUAX (Database.PostgreSQL.Typed.Types.PGTypeProxy :: Database.PostgreSQL.Typed.Types.PGTypeName "segment") _p_abUB2])) (if success then AuditActionOpen else AuditActionAttempt) (auditWho ai) (auditIp ai) (containerId $ containerRow c) seg) (\ [] -> ())) slotJSON :: JSON.ToObject o => Slot -> JSON.Record (Id Container) o slotJSON Slot{..} = containerJSON False slotContainer -- probably add bool to slotJSON `JSON.foldObjectIntoRec` segmentJSON slotSegment
databrary/databrary
src/Model/Slot.hs
agpl-3.0
3,581
0
19
1,025
616
354
262
65
2
module ProjectM36.TupleSet where import ProjectM36.Base import ProjectM36.Tuple import ProjectM36.Error import qualified Data.HashSet as HS import qualified Data.Vector as V import qualified Control.Parallel.Strategies as P import Data.Either emptyTupleSet :: RelationTupleSet emptyTupleSet = RelationTupleSet [] singletonTupleSet :: RelationTupleSet singletonTupleSet = RelationTupleSet [emptyTuple] --ensure that all maps have the same keys and key count verifyTupleSet :: Attributes -> RelationTupleSet -> Either RelationalError RelationTupleSet verifyTupleSet attrs tupleSet = do --check that all tuples have the same attributes and that the atom types match let tupleList = map (verifyTuple attrs) (asList tupleSet) `P.using` P.parListChunk chunkSize P.r0 chunkSize = (length . asList) tupleSet `div` 24 --let tupleList = P.parMap P.rdeepseq (verifyTuple attrs) (HS.toList tupleSet) if not (null (lefts tupleList)) then Left $ head (lefts tupleList) else return $ RelationTupleSet $ (HS.toList . HS.fromList) (rights tupleList) mkTupleSet :: Attributes -> [RelationTuple] -> Either RelationalError RelationTupleSet mkTupleSet attrs tuples = verifyTupleSet attrs (RelationTupleSet tuples) mkTupleSetFromList :: Attributes -> [[Atom]] -> Either RelationalError RelationTupleSet mkTupleSetFromList attrs atomMatrix = mkTupleSet attrs $ map (mkRelationTuple attrs . V.fromList) atomMatrix -- | Union two tuplesets while reordering their attribute/atom mapping properly. tupleSetUnion :: Attributes -> RelationTupleSet -> RelationTupleSet -> RelationTupleSet tupleSetUnion targetAttrs tupSet1 tupSet2 = RelationTupleSet $ HS.toList . HS.fromList $ reorder (asList tupSet1) ++ reorder (asList tupSet2) where reorder = map (reorderTuple targetAttrs)
agentm/project-m36
src/lib/ProjectM36/TupleSet.hs
unlicense
1,788
0
13
252
428
227
201
26
2
--init using length module Main where initUsingLength xs = take ( (length xs) - 1) xs
Crossroadsman/ProgrammingInHaskell
02/initUsingLength.hs
apache-2.0
92
0
9
22
31
17
14
2
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} -- | This module provides a typed interface for handling IRC commands. -- It lets you work in terms of e.g. 'Join' or 'PrivMsg' values instead -- of having to match on the raw 'Command' type. module Hircine.Command ( -- * Parsing and un-parsing commands IsCommand(..), Bytes, -- * Command types pattern Join, pattern Mode, pattern Nick, pattern Notice, pattern Pass, pattern Ping, pattern Pong, pattern PrivMsg, pattern Quit, pattern User, -- * Low-level machinery -- | This section contains the low-level machinery that makes this -- module work. You shouldn't need to deal with these routines -- unless you're adding a new command. ParsedCommand(..), ParamParser, runParamParser, IsParams(..), CommaSep(..), unCommaSep, ) where import Control.Applicative import Control.Monad.Trans.State.Strict import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B import Data.List import Data.Proxy import Data.String import GHC.TypeLits import Hircine.Core -- | Represents a type that can be converted to and from a raw 'Command'. class IsCommand a where fromCommand :: Command -> Maybe a toCommand :: a -> Command instance IsCommand Command where fromCommand = Just toCommand = id -- | Represents a validated IRC command. newtype ParsedCommand (method :: Symbol) params = ParsedCommand params deriving Show instance forall method params. (KnownSymbol method, IsParams params) => IsCommand (ParsedCommand method params) where fromCommand (Command method' params') | method == method' = ParsedCommand <$> runParamParser parseParams params' | otherwise = Nothing where method = fromString $ symbolVal (Proxy :: Proxy method) toCommand (ParsedCommand params) = Command method (renderParams params) where method = fromString $ symbolVal (Proxy :: Proxy method) -- | Convenient synonym for 'ByteString'. type Bytes = ByteString type ParamParser = StateT [Bytes] Maybe runParamParser :: Alternative f => ParamParser a -> [Bytes] -> f a runParamParser parse params' | Just (params, []) <- runStateT parse params' = pure params | otherwise = empty class IsParams a where parseParams :: ParamParser a renderParams :: a -> [Bytes] instance IsParams a => IsParams [a] where parseParams = many parseParams renderParams = concatMap renderParams instance IsParams () where parseParams = pure () renderParams _ = [] instance (IsParams a, IsParams b) => IsParams (a, b) where parseParams = (,) <$> parseParams <*> parseParams renderParams (a, b) = renderParams a ++ renderParams b instance (IsParams a, IsParams b, IsParams c) => IsParams (a, b, c) where parseParams = (,,) <$> parseParams <*> parseParams <*> parseParams renderParams (a, b, c) = renderParams a ++ renderParams b ++ renderParams c instance (IsParams a, IsParams b, IsParams c, IsParams d) => IsParams (a, b, c, d) where parseParams = (,,,) <$> parseParams <*> parseParams <*> parseParams <*> parseParams renderParams (a, b, c, d) = renderParams a ++ renderParams b ++ renderParams c ++ renderParams d instance (IsParams a, IsParams b, IsParams c, IsParams d, IsParams e) => IsParams (a, b, c, d, e) where parseParams = (,,,,) <$> parseParams <*> parseParams <*> parseParams <*> parseParams <*> parseParams renderParams (a, b, c, d, e) = renderParams a ++ renderParams b ++ renderParams c ++ renderParams d ++ renderParams e instance IsParams ByteString where parseParams = StateT uncons renderParams x = [x] newtype CommaSep a = CommaSep [a] deriving Show -- Written separately to make the Show instance prettier unCommaSep :: CommaSep a -> [a] unCommaSep (CommaSep a) = a instance IsParams a => IsParams (CommaSep a) where parseParams = do pieces <- B.split ',' <$> StateT uncons runParamParser (CommaSep <$> many parseParams) pieces renderParams (CommaSep xs) = [B.intercalate "," $ concatMap renderParams xs] instance IsParams a => IsParams (Maybe a) where parseParams = optional parseParams renderParams = foldMap renderParams pattern Join :: [Bytes] -> Maybe [Bytes] -> ParsedCommand "JOIN" (CommaSep Bytes, Maybe (CommaSep Bytes)) pattern Join channels keys <- ParsedCommand (CommaSep channels, fmap unCommaSep -> keys) where Join channels keys = ParsedCommand (CommaSep channels, CommaSep <$> keys) pattern Mode :: Bytes -> [Bytes] -> ParsedCommand "MODE" (Bytes, [Bytes]) pattern Mode channelOrNick args = ParsedCommand (channelOrNick, args) pattern Nick :: Bytes -> ParsedCommand "NICK" Bytes pattern Nick nick = ParsedCommand nick pattern Notice :: [Bytes] -> Bytes -> ParsedCommand "NOTICE" (CommaSep Bytes, Bytes) pattern Notice targets message = ParsedCommand (CommaSep targets, message) pattern Pass :: Bytes -> ParsedCommand "PASS" Bytes pattern Pass pass = ParsedCommand pass pattern Ping :: Bytes -> Maybe Bytes -> ParsedCommand "PING" (Bytes, Maybe Bytes) pattern Ping server1 server2 = ParsedCommand (server1, server2) pattern Pong :: Bytes -> Maybe Bytes -> ParsedCommand "PONG" (Bytes, Maybe Bytes) pattern Pong server1 server2 = ParsedCommand (server1, server2) pattern PrivMsg :: [Bytes] -> Bytes -> ParsedCommand "PRIVMSG" (CommaSep Bytes, Bytes) pattern PrivMsg targets message = ParsedCommand (CommaSep targets, message) pattern Quit :: Maybe Bytes -> ParsedCommand "QUIT" (Maybe Bytes) pattern Quit message = ParsedCommand message pattern User :: Bytes -> Bytes -> ParsedCommand "USER" (Bytes, Bytes, Bytes, Bytes) pattern User user realname <- ParsedCommand (user, _, _, realname) where User user realname = ParsedCommand (user, "0", "*", realname)
lfairy/hircine
Hircine/Command.hs
apache-2.0
6,000
0
12
1,169
1,774
945
829
116
1
module Delahaye.A337659 (a337659_list, a337659) where import Delahaye.A337655 (a337655) import Helpers.Delahaye (rowTable) a337659 :: Int -> Integer a337659 n = a337659_list !! (n-1) a337659_list :: [Integer] a337659_list = rowTable (+) a337655
peterokagey/haskellOEIS
src/Delahaye/A337659.hs
apache-2.0
247
0
7
32
82
48
34
7
1
{-# LANGUAGE Haskell2010 #-} module Example where -- | Example use. -- -- >>> split 1 -- () -- -- >>> split 2 -- () split :: Int -> () split _ = ()
haskell/haddock
latex-test/src/Example/Example.hs
bsd-2-clause
149
0
6
35
33
22
11
4
1
module Main where -- do a quick test for Darcs: import System.Directory.Tree import Control.Applicative import qualified Data.Foldable as F import System.Directory import System.Process import System.IO.Error(ioeGetErrorType,isPermissionErrorType) import Control.Monad(void) testDir :: FilePath testDir = "/tmp/TESTDIR-LKJHBAE" main :: IO () main = do putStrLn "-- The following tests will either fail with an error " putStrLn "-- message or with an 'undefined' error" -- write our testing directory structure to disk. We include Failed -- constructors which should be discarded: _:/written <- writeDirectory testTree putStrLn "OK" if (fmap (const ()) (filterDir (not . failed) $dirTree testTree)) == filterDir (not . failed) written then return () else error "writeDirectory returned a tree that didn't match" putStrLn "OK" -- make file farthest to the right unreadable: (Dir _ [_,_,Dir "C" [_,_,File "G" p_unreadable]]) <- sortDir . dirTree <$> build testDir setPermissions p_unreadable emptyPermissions{readable = False, writable = True, executable = True, searchable = True} putStrLn "OK" -- read with lazy and standard functions, compare for equality. Also test that our crazy -- operator works correctly inline with <$>: tL <- readDirectoryWithL readFile testDir t@(_:/Dir _ [_,_,Dir "C" [unreadable_constr,_,_]]) <- sortDir </$> id <$> readDirectory testDir if t == tL then return () else error "lazy read /= standard read" putStrLn "OK" -- make sure the unreadable file left the correct error type in a Failed: if isPermissionErrorType $ ioeGetErrorType $ err unreadable_constr then return () else error "wrong error type for Failed file read" putStrLn "OK" -- run lazy fold, concating file contents. compare for equality: tL_again <- sortDir </$> readDirectoryWithL readFile testDir let tL_concated = F.concat $ dirTree tL_again if tL_concated == "abcdef" then return () else error "foldable broke" putStrLn "OK" -- get a lazy DirTree at root directory with lazy Directory traversal: putStrLn "-- If lazy IO is not working, we should be stalled right now " putStrLn "-- as we try to read in the whole root directory tree." putStrLn "-- Go ahead and press CTRL-C if you've read this far" mapM_ putStr =<< (map name . contents . dirTree) <$> readDirectoryWithL readFile "/" putStrLn "\nOK" let undefinedOrdFailed = Failed undefined undefined :: DirTree Char undefinedOrdDir = Dir undefined undefined :: DirTree Char undefinedOrdFile = File undefined undefined :: DirTree Char -- simple equality and sorting if Dir "d" [File "b" "b",File "a" "a"] == Dir "d" [File "a" "a", File "b" "b"] && -- recursive sort order, enforces non-recursive sorting of Dirs Dir "d" [Dir "b" undefined,File "a" "a"] /= Dir "d" [File "a" "a", Dir "c" undefined] && -- check ordering of constructors: undefinedOrdFailed < undefinedOrdDir && undefinedOrdDir < undefinedOrdFile && -- check ordering by dir contents list length: Dir "d" [File "b" "b",File "a" "a"] > Dir "d" [File "a" "a"] && -- recursive ordering on contents: Dir "d" [File "b" "b", Dir "c" [File "a" "b"]] > Dir "d" [File "b" "b", Dir "c" [File "a" "a"]] then putStrLn "OK" else error "Ord/Eq instance is messed up" if Dir "d" [File "b" "b",File "a" "a"] `equalShape` Dir "d" [File "a" undefined, File "b" undefined] then putStrLn "OK" else error "equalShape or comparinghape functions broken" -- clean up by removing the directory: void $ system $ "rm -r " ++ testDir putStrLn "SUCCESS" testTree :: AnchoredDirTree String testTree = "" :/ Dir testDir [dA , dB , dC , Failed "FAAAIIILL" undefined] where dA = Dir "A" [dA1 , dA2 , Failed "FAIL" undefined] dA1 = Dir "A1" [File "A" "a", File "B" "b"] dA2 = Dir "A2" [File "C" "c"] dB = Dir "B" [File "D" "d"] dC = Dir "C" [File "E" "e", File "F" "f", File "G" "g"]
jberryman/directory-tree
Test.hs
bsd-2-clause
4,367
0
21
1,208
1,087
542
545
67
7
{-# LANGUAGE FlexibleInstances, FlexibleContexts, MultiParamTypeClasses #-} module Data.TrieMap.ProdMap.Searchable () where import Data.TrieMap.ProdMap.Base import Data.TrieMap.ProdMap.Zippable () import Prelude hiding (lookup) instance (Searchable (TrieMap k1) k1, Searchable (TrieMap k2) k2, TrieKey k2) => Searchable (TrieMap (k1, k2)) (k1, k2) where search (k1, k2) (PMap m) nomatch match = search k1 m nomatch1 match1 where nomatch1 h1 = nomatch (PHole h1 (singleZip k2)) match1 m' h1 = search k2 m' nomatch2 match2 where nomatch2 h2 = nomatch (PHole h1 h2) match2 a h2 = match a (PHole h1 h2) singleZip (k1, k2) = PHole (singleZip k1) (singleZip k2) lookup (k1, k2) (PMap m) = lookup k1 m >>= lookup k2 insertWith f (k1, k2) a (PMap m) = PMap $ insertWith (insertWith f k2 a) k1 (singleton k2 a) m alter f (k1, k2) (PMap m) = PMap $ alter g k1 m where g Nothing = singleton k2 <$> f Nothing g (Just m') = guardNull $ alter f k2 m'
lowasser/TrieMap
Data/TrieMap/ProdMap/Searchable.hs
bsd-3-clause
994
0
12
216
430
224
206
18
0
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} -- | Given a Copper files, change every Cleared posting to -- a Reconciled one. module Penny.Reconciler where import qualified Control.Exception as Exception import qualified Control.Lens as Lens import qualified Data.Text as X import Penny.Copper import Penny.Copper.Copperize (TracompriError) import Penny.Copper.Terminalizers import Penny.Copper.Tracompri import Penny.Cursor import Penny.Prelude import Penny.Tranche import Penny.Transaction import Penny.Unix.Diff -- | Reconciles a file by changing all postings with a @C@ flag to an -- @R@ flag. Makes no changes on disk; returns result as the output of @diff@. reconciler :: FilePath -- ^ Reconcile this file -> IO Patch reconciler filename = do copperInput <- readFile filename tracompris <- either Exception.throwIO return $ reconcileFile (filename, copperInput) formatted <- either (Exception.throwIO . CopperizationFailed) return . Lens.over Lens._Left (\(CopperizationError a) -> a) . accuerrToEither . copperizeAndFormat $ tracompris let result = X.pack . toList . fmap fst . t'WholeFile $ formatted diff filename result data ReconcilerFailure = ParseConvertProofFailed (ParseConvertProofError Loc) | CopperizationFailed (NonEmptySeq (TracompriError Cursor)) deriving Show instance Exception.Exception ReconcilerFailure reconcileFile :: (FilePath, Text) -> Either ReconcilerFailure (Seq (Tracompri Cursor)) reconcileFile copperInput = do tracompris <- Lens.over Lens._Left ParseConvertProofFailed . parseConvertProof . Lens.over Lens._1 Right $ copperInput return (Lens.over traverseFlags reconcileFlag tracompris) -- | Marks a flag as @R@ if it is presently @C@. reconcileFlag :: Text -> Text reconcileFlag x | x == "C" = "R" | otherwise = x traverseFlags :: Lens.Traversal' (Seq (Tracompri a)) Text traverseFlags = traverse . _Tracompri'Transaction . postings . traverse . flag
massysett/penny
penny/lib/Penny/Reconciler.hs
bsd-3-clause
2,035
0
16
340
468
248
220
55
1
module Types.Session ( module RPC.Util , SessionId (..) , SessionMap (..) , Session (..) , ShellRead (..) , SessionWriteCount (..) , DirSep , ReadPointer , HostName , PortNumber ) where import RPC.Util import Control.Applicative ((<$>),(<*>)) import qualified Data.Map as Map -------------------------------------------------------------------------------- newtype SessionId = SessionId { getSessionId :: Int } deriving (Show,Ord,Eq) instance ToObject SessionId where toObject = toObject . getSessionId instance FromObject SessionId where fromObject obj = SessionId <$> fromObject obj -------------------------------------------------------------------------------- newtype SessionMap = SessionMap { getSessionMap :: Map.Map SessionId Session } deriving (Show) instance FromObject SessionMap where fromObject obj = SessionMap <$> fromObject obj -------------------------------------------------------------------------------- data Session = Session { sessType , sessTunnelLocal , sessTunnelPeer , sessViaExploit , sessViaPayload , sessDesc , sessInfo , sessWorkspace , sessHost :: HostName , sessPort :: PortNumber , sessTargetHost , sessUsername , sessUUID , sessExploitUUID , sessRoutes :: String } deriving (Show) instance FromObject Session where fromObject obj = do m <- fromObject obj Session <$> (fromObject =<< Map.lookup "type" m) <*> (fromObject =<< Map.lookup "tunnel_local" m) <*> (fromObject =<< Map.lookup "tunnel_peer" m) <*> (fromObject =<< Map.lookup "via_exploit" m) <*> (fromObject =<< Map.lookup "via_payload" m) <*> (fromObject =<< Map.lookup "desc" m) <*> (fromObject =<< Map.lookup "info" m) <*> (fromObject =<< Map.lookup "workspace" m) <*> (fromObject =<< Map.lookup "session_host" m) <*> (fromObject =<< Map.lookup "session_port" m) <*> (fromObject =<< Map.lookup "target_host" m) <*> (fromObject =<< Map.lookup "username" m) <*> (fromObject =<< Map.lookup "uuid" m) <*> (fromObject =<< Map.lookup "exploit_uuid" m) <*> (fromObject =<< Map.lookup "routes" m) -------------------------------------------------------------------------------- data ShellRead = ShellRead { readSeq :: Maybe ReadPointer , readData :: String } deriving (Eq,Show) instance FromObject ShellRead where fromObject obj = ShellRead <$> lookupField "seq" obj <*> lookupField "data" obj -------------------------------------------------------------------------------- newtype SessionWriteCount = SessionWriteCount { sessionWriteCount :: String } deriving (Eq,Show) instance FromObject SessionWriteCount where fromObject obj = SessionWriteCount <$> lookupField "write_count" obj -------------------------------------------------------------------------------- type ReadPointer = String type HostName = String type PortNumber = Int type DirSep = String
GaloisInc/msf-haskell
src/Types/Session.hs
bsd-3-clause
3,107
0
26
679
714
405
309
78
0
{-# LANGUAGE OverloadedStrings #-} module Cauterize.Specification.ParserSpec ( spec ) where import Cauterize.Specification.Types import Cauterize.Specification.Parser import Cauterize.CommonTypes import Test.Hspec import Data.Either spec :: Spec spec = do describe "parseSpecification" $ do it "parses a specification" $ do let s = parseSpecification synFoo s `shouldSatisfy` isRight s `shouldSatisfy` hasSynNamedFoo it "parses a formatted specification" $ do let r = do s <- parseSpecification synFoo let f = formatSpecification s s' <- parseSpecification f return (s == s') r `shouldBe` (Right True) where synFoo = "(type foo synonym (fingerprint 0cb7bd78634eba6f3633dbf0a5f69537aa1916df) (size 1 1) (depth 1) u8)" hasSynNamedFoo (Right (Specification { specTypes = [Type { typeName = n, typeDesc = Synonym _, typeDepth = 1 }] })) = unIdentifier n == "foo" hasSynNamedFoo _ = False
cauterize-tools/cauterize
tests/Cauterize/Specification/ParserSpec.hs
bsd-3-clause
1,188
0
21
426
254
131
123
32
2
{-# LANGUAGE RecordWildCards #-} module Day13 where import Data.Bits import Data.Dequeue import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set type Pos = (Int, Int) input0 = 10 input1 = 1358 input2 = 1362 expr :: Pos -> Int expr (x, y) = x*x + 3*x + 2*x*y + y + y*y isOpen :: Pos -> Bool isOpen p = even . popCount $ expr p + input1 valid :: Pos -> Bool valid p@(x,y) = x >= 0 && y >= 0 && isOpen p dirs :: [Pos] dirs = [(0,1), (0,-1), (1,0), (-1,0)] neighbours :: Pos -> [Pos] neighbours (x,y) = filter valid $ map (\(dx, dy) -> (x + dx, y + dy)) dirs data State = State { visited :: Set (Pos, Int) , next :: BankersDequeue (Pos, Int) } initialState = State Set.empty (pushBack empty ((1,1), 0)) walk :: Pos -> State -> State walk dest s@State{..} = if current == dest then s else State visited' next' where ((current, dist), rest) = fromJust $ popFront next visited' = Set.insert (current, dist) visited unvisNeigh = map (\p -> (p, dist + 1)) . filter (\p -> not $ p `elem` (Set.map fst visited)) $ neighbours current next' = foldl pushBack rest unvisNeigh dest0 :: (Int, Int) dest0 = (7, 4) dest1 :: (Int, Int) dest1 = (31, 39) solve :: Pos -> [State] solve dest = iterate (walk dest) initialState
mbernat/aoc16-haskell
src/Day13.hs
bsd-3-clause
1,264
0
15
280
640
363
277
38
2
{- OPTIONS_GHC -fplugin Brisk.Plugin #-} {- OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-} {-# LANGUAGE TemplateHaskell #-} module SpawnSym (main) where import Control.Monad (forM, foldM) import Control.Distributed.Process import Control.Distributed.BriskStatic import Control.Distributed.Process.Closure import Control.Distributed.Process.SymmetricProcess import GHC.Base.Brisk p :: ProcessId -> Process () p who = do self <- getSelfPid c <- liftIO $ getChar msg <- if c == 'x' then return (0 :: Int) else return 1 send who msg expect :: Process () return () remotable ['p] ack :: ProcessId -> Process () ack p = send p () broadCast :: SymSet ProcessId -> Process () broadCast pids = do foldM go 0 pids foldM go' () pids return () where go _ p = expect :: Process Int go' _ = ack main :: [NodeId] -> Process () main nodes = do me <- getSelfPid symSet <- spawnSymmetric nodes $ $(mkBriskClosure 'p) me broadCast symSet return ()
abakst/brisk-prelude
tests/pos/SpawnSym.hs
bsd-3-clause
1,093
0
12
310
346
173
173
30
2
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE OverloadedStrings #-} module Generate (html, js) where import Control.Monad (forM_, when) import Data.Maybe (fromMaybe) import System.Directory import System.Exit import System.FilePath import System.Process import System.IO (hGetContents) import Text.Blaze (preEscapedToMarkup) import Text.Blaze.Html5 ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import qualified Elm.Internal.Utils as Elm -- | Using a page title and the full source of an Elm program, compile down to -- a valid HTML document. html :: FilePath -> Bool -> IO H.Html html filePath doDebug = do src <- readFile filePath compilerResult <- compile filePath return . buildPage $ formatResult src compilerResult where script = H.script ! A.type_ "text/javascript" formatResult src compilerResult = case compilerResult of Right jsSrc -> do script $ preEscapedToMarkup jsSrc script $ preEscapedToMarkup $ runFullscreen src Left err -> H.span ! A.style "font-family: monospace;" $ forM_ (lines err) $ \line -> do preEscapedToMarkup (addSpaces line) H.br attachDebugger moduleName = case doDebug of True -> "Elm.debugFullscreen(" ++ moduleName ++ ", \"" ++ filePath ++ "\");" False -> "Elm.fullscreen(" ++ moduleName ++ ");" runFullscreen src = let moduleName = "Elm." ++ fromMaybe "Main" (Elm.moduleName src) in "var runningElmModule = " ++ (attachDebugger moduleName) insertDebuggerScript = case doDebug of True -> script ! A.src (H.toValue ("/debugger.js" :: String)) $ "" False -> return () buildPage content = H.docTypeHtml $ do H.head $ do H.meta ! A.charset "UTF-8" H.title . H.toHtml $ takeFileName filePath H.style ! A.type_ "text/css" $ preEscapedToMarkup ("a:link {text-decoration: none; color: rgb(15,102,230);}\n\ \a:visited {text-decoration: none}\n\ \a:active {text-decoration: none}\n\ \a:hover {text-decoration: underline; color: rgb(234,21,122);}\n\ \html,body {height: 100%; margin: 0px;}" :: String) H.body $ do script ! A.src (H.toValue ("/elm-runtime.js" :: String)) $ "" insertDebuggerScript content -- | Creates the javascript for the elm program and returns it as a -- JSONified string with either success:<code> or error:<message> js :: FilePath -> IO String js filePath = do output <- compile filePath return (either (wrap "error") (wrap "success") output) where wrap :: String -> String -> String wrap typ msg = "{ " ++ show typ ++ " : " ++ show msg ++ " }" addSpaces :: String -> String addSpaces str = case str of ' ' : ' ' : rest -> " &nbsp;" ++ addSpaces rest c : rest -> c : addSpaces rest [] -> [] compile :: FilePath -> IO (Either String String) compile filePath = do (_, Just hout, Just herr, p) <- createProcess (proc "elm" $ args fileName) { cwd = Just directory , std_out = CreatePipe , std_err = CreatePipe } exitCode <- waitForProcess p stdout <- exitCode `seq` hGetContents hout stderr <- exitCode `seq` hGetContents herr case exitCode of ExitFailure _ -> do removeEverything directory fileName return (Left (stdout ++ stderr)) ExitSuccess -> do result <- readFile (directory </> "build" </> fileName `replaceExtension` "js") length result `seq` (removeEverything directory fileName) return (Right result) where (directory, fileName) = splitFileName filePath args file = [ "--make" , "--only-js" , file ] removeEverything :: FilePath -> FilePath -> IO () removeEverything dir file = do remove "cache" "elmi" remove "cache" "elmo" remove "build" "js" where remove :: String -> String -> IO () remove subdir ext = do let path = dir </> subdir </> file`replaceExtension` ext exists <- doesFileExist path when exists (removeFile path)
alisheikh/elm-server
server/Generate.hs
bsd-3-clause
4,449
0
18
1,372
1,163
583
580
97
4
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_HADDOCK not-home #-} #include "overlapping-compat.h" -- | A collection of basic Content-Types (also known as Internet Media -- Types, or MIME types). Additionally, this module provides classes that -- encapsulate how to serialize or deserialize values to or from -- a particular Content-Type. -- -- Content-Types are used in `ReqBody` and the method combinators: -- -- >>> type MyEndpoint = ReqBody '[JSON, PlainText] Book :> Get '[JSON, PlainText] Book -- -- Meaning the endpoint accepts requests of Content-Type @application/json@ -- or @text/plain;charset-utf8@, and returns data in either one of those -- formats (depending on the @Accept@ header). -- -- If you would like to support Content-Types beyond those provided here, -- then: -- -- (1) Declare a new data type with no constructors (e.g. @data HTML@). -- (2) Make an instance of it for `Accept`. -- (3) If you want to be able to serialize data *into* that -- Content-Type, make an instance of it for `MimeRender`. -- (4) If you want to be able to deserialize data *from* that -- Content-Type, make an instance of it for `MimeUnrender`. -- -- Note that roles are reversed in @servant-server@ and @servant-client@: -- to be able to serve (or even typecheck) a @Get '[JSON, XML] MyData@, -- you'll need to have the appropriate `MimeRender` instances in scope, -- whereas to query that endpoint with @servant-client@, you'll need -- a `MimeUnrender` instance in scope. module Servant.API.ContentTypes ( -- * Provided Content-Types JSON , PlainText , FormUrlEncoded , OctetStream -- * Building your own Content-Type , Accept(..) , MimeRender(..) , MimeUnrender(..) -- * NoContent , NoContent(..) -- * Internal , AcceptHeader(..) , AllCTRender(..) , AllCTUnrender(..) , AllMime(..) , AllMimeRender(..) , AllMimeUnrender(..) , eitherDecodeLenient , canHandleAcceptH ) where import Control.Arrow (left) import Control.Monad.Compat import Data.Aeson (FromJSON(..), ToJSON(..), encode) import Data.Aeson.Parser (value) import Data.Aeson.Types (parseEither) import Data.Attoparsec.ByteString.Char8 (endOfInput, parseOnly, skipSpace, (<?>)) import qualified Data.ByteString as BS import Data.ByteString.Lazy (ByteString, fromStrict, toStrict) import qualified Data.ByteString.Lazy.Char8 as BC import Data.Maybe (isJust) import Data.String.Conversions (cs) import qualified Data.Text as TextS import qualified Data.Text.Encoding as TextS import qualified Data.Text.Lazy as TextL import qualified Data.Text.Lazy.Encoding as TextL import Data.Typeable import GHC.Generics (Generic) import qualified Network.HTTP.Media as M import Web.FormUrlEncoded (FromForm, ToForm, urlEncodeAsForm, urlDecodeAsForm) import Prelude () import Prelude.Compat -- * Provided content types data JSON deriving Typeable data PlainText deriving Typeable data FormUrlEncoded deriving Typeable data OctetStream deriving Typeable -- * Accept class -- | Instances of 'Accept' represent mimetypes. They are used for matching -- against the @Accept@ HTTP header of the request, and for setting the -- @Content-Type@ header of the response -- -- Example: -- -- >>> import Network.HTTP.Media ((//), (/:)) -- >>> data HTML -- >>> :{ --instance Accept HTML where -- contentType _ = "text" // "html" /: ("charset", "utf-8") -- :} -- class Accept ctype where contentType :: Proxy ctype -> M.MediaType -- | @application/json@ instance Accept JSON where contentType _ = "application" M.// "json" -- | @application/x-www-form-urlencoded@ instance Accept FormUrlEncoded where contentType _ = "application" M.// "x-www-form-urlencoded" -- | @text/plain;charset=utf-8@ instance Accept PlainText where contentType _ = "text" M.// "plain" M./: ("charset", "utf-8") -- | @application/octet-stream@ instance Accept OctetStream where contentType _ = "application" M.// "octet-stream" newtype AcceptHeader = AcceptHeader BS.ByteString deriving (Eq, Show, Read, Typeable, Generic) -- * Render (serializing) -- | Instantiate this class to register a way of serializing a type based -- on the @Accept@ header. -- -- Example: -- -- > data MyContentType -- > -- > instance Accept MyContentType where -- > contentType _ = "example" // "prs.me.mine" /: ("charset", "utf-8") -- > -- > instance Show a => MimeRender MyContentType a where -- > mimeRender _ val = pack ("This is MINE! " ++ show val) -- > -- > type MyAPI = "path" :> Get '[MyContentType] Int -- class Accept ctype => MimeRender ctype a where mimeRender :: Proxy ctype -> a -> ByteString class (AllMime list) => AllCTRender (list :: [*]) a where -- If the Accept header can be matched, returns (Just) a tuple of the -- Content-Type and response (serialization of @a@ into the appropriate -- mimetype). handleAcceptH :: Proxy list -> AcceptHeader -> a -> Maybe (ByteString, ByteString) instance OVERLAPPABLE_ (Accept ct, AllMime cts, AllMimeRender (ct ': cts) a) => AllCTRender (ct ': cts) a where handleAcceptH _ (AcceptHeader accept) val = M.mapAcceptMedia lkup accept where pctyps = Proxy :: Proxy (ct ': cts) amrs = allMimeRender pctyps val lkup = fmap (\(a,b) -> (a, (fromStrict $ M.renderHeader a, b))) amrs -------------------------------------------------------------------------- -- * Unrender -- | Instantiate this class to register a way of deserializing a type based -- on the request's @Content-Type@ header. -- -- >>> import Network.HTTP.Media hiding (Accept) -- >>> import qualified Data.ByteString.Lazy.Char8 as BSC -- >>> data MyContentType = MyContentType String -- -- >>> :{ --instance Accept MyContentType where -- contentType _ = "example" // "prs.me.mine" /: ("charset", "utf-8") -- :} -- -- >>> :{ --instance Read a => MimeUnrender MyContentType a where -- mimeUnrender _ bs = case BSC.take 12 bs of -- "MyContentType" -> return . read . BSC.unpack $ BSC.drop 12 bs -- _ -> Left "didn't start with the magic incantation" -- :} -- -- >>> type MyAPI = "path" :> ReqBody '[MyContentType] Int :> Get '[JSON] Int -- class Accept ctype => MimeUnrender ctype a where mimeUnrender :: Proxy ctype -> ByteString -> Either String a class AllCTUnrender (list :: [*]) a where handleCTypeH :: Proxy list -> ByteString -- Content-Type header -> ByteString -- Request body -> Maybe (Either String a) instance ( AllMimeUnrender ctyps a ) => AllCTUnrender ctyps a where handleCTypeH _ ctypeH body = M.mapContentMedia lkup (cs ctypeH) where lkup = allMimeUnrender (Proxy :: Proxy ctyps) body -------------------------------------------------------------------------- -- * Utils (Internal) class AllMime (list :: [*]) where allMime :: Proxy list -> [M.MediaType] instance AllMime '[] where allMime _ = [] instance (Accept ctyp, AllMime ctyps) => AllMime (ctyp ': ctyps) where allMime _ = (contentType pctyp):allMime pctyps where pctyp = Proxy :: Proxy ctyp pctyps = Proxy :: Proxy ctyps canHandleAcceptH :: AllMime list => Proxy list -> AcceptHeader -> Bool canHandleAcceptH p (AcceptHeader h ) = isJust $ M.matchAccept (allMime p) h -------------------------------------------------------------------------- -- Check that all elements of list are instances of MimeRender -------------------------------------------------------------------------- class (AllMime list) => AllMimeRender (list :: [*]) a where allMimeRender :: Proxy list -> a -- value to serialize -> [(M.MediaType, ByteString)] -- content-types/response pairs instance OVERLAPPABLE_ ( MimeRender ctyp a ) => AllMimeRender '[ctyp] a where allMimeRender _ a = [(contentType pctyp, mimeRender pctyp a)] where pctyp = Proxy :: Proxy ctyp instance OVERLAPPABLE_ ( MimeRender ctyp a , AllMimeRender (ctyp' ': ctyps) a ) => AllMimeRender (ctyp ': ctyp' ': ctyps) a where allMimeRender _ a = (contentType pctyp, mimeRender pctyp a) :(allMimeRender pctyps a) where pctyp = Proxy :: Proxy ctyp pctyps = Proxy :: Proxy (ctyp' ': ctyps) -- Ideally we would like to declare a 'MimeRender a NoContent' instance, and -- then this would be taken care of. However there is no more specific instance -- between that and 'MimeRender JSON a', so we do this instead instance OVERLAPPING_ ( Accept ctyp ) => AllMimeRender '[ctyp] NoContent where allMimeRender _ _ = [(contentType pctyp, "")] where pctyp = Proxy :: Proxy ctyp instance OVERLAPPING_ ( AllMime (ctyp ': ctyp' ': ctyps) ) => AllMimeRender (ctyp ': ctyp' ': ctyps) NoContent where allMimeRender p _ = zip (allMime p) (repeat "") -------------------------------------------------------------------------- -- Check that all elements of list are instances of MimeUnrender -------------------------------------------------------------------------- class (AllMime list) => AllMimeUnrender (list :: [*]) a where allMimeUnrender :: Proxy list -> ByteString -> [(M.MediaType, Either String a)] instance AllMimeUnrender '[] a where allMimeUnrender _ _ = [] instance ( MimeUnrender ctyp a , AllMimeUnrender ctyps a ) => AllMimeUnrender (ctyp ': ctyps) a where allMimeUnrender _ val = (contentType pctyp, mimeUnrender pctyp val) :(allMimeUnrender pctyps val) where pctyp = Proxy :: Proxy ctyp pctyps = Proxy :: Proxy ctyps -------------------------------------------------------------------------- -- * MimeRender Instances -- | `encode` instance OVERLAPPABLE_ ToJSON a => MimeRender JSON a where mimeRender _ = encode -- | @urlEncodeAsForm@ -- Note that the @mimeUnrender p (mimeRender p x) == Right x@ law only -- holds if every element of x is non-null (i.e., not @("", "")@) instance OVERLAPPABLE_ ToForm a => MimeRender FormUrlEncoded a where mimeRender _ = urlEncodeAsForm -- | `TextL.encodeUtf8` instance MimeRender PlainText TextL.Text where mimeRender _ = TextL.encodeUtf8 -- | @fromStrict . TextS.encodeUtf8@ instance MimeRender PlainText TextS.Text where mimeRender _ = fromStrict . TextS.encodeUtf8 -- | @BC.pack@ instance MimeRender PlainText String where mimeRender _ = BC.pack -- | @id@ instance MimeRender OctetStream ByteString where mimeRender _ = id -- | `fromStrict` instance MimeRender OctetStream BS.ByteString where mimeRender _ = fromStrict -- | A type for responses without content-body. data NoContent = NoContent deriving (Show, Eq, Read, Generic) -------------------------------------------------------------------------- -- * MimeUnrender Instances -- | Like 'Data.Aeson.eitherDecode' but allows all JSON values instead of just -- objects and arrays. -- -- Will handle trailing whitespace, but not trailing junk. ie. -- -- >>> eitherDecodeLenient "1 " :: Either String Int -- Right 1 -- -- >>> eitherDecodeLenient "1 junk" :: Either String Int -- Left "trailing junk after valid JSON: endOfInput" eitherDecodeLenient :: FromJSON a => ByteString -> Either String a eitherDecodeLenient input = parseOnly parser (cs input) >>= parseEither parseJSON where parser = skipSpace *> Data.Aeson.Parser.value <* skipSpace <* (endOfInput <?> "trailing junk after valid JSON") -- | `eitherDecode` instance FromJSON a => MimeUnrender JSON a where mimeUnrender _ = eitherDecodeLenient -- | @urlDecodeAsForm@ -- Note that the @mimeUnrender p (mimeRender p x) == Right x@ law only -- holds if every element of x is non-null (i.e., not @("", "")@) instance FromForm a => MimeUnrender FormUrlEncoded a where mimeUnrender _ = left TextS.unpack . urlDecodeAsForm -- | @left show . TextL.decodeUtf8'@ instance MimeUnrender PlainText TextL.Text where mimeUnrender _ = left show . TextL.decodeUtf8' -- | @left show . TextS.decodeUtf8' . toStrict@ instance MimeUnrender PlainText TextS.Text where mimeUnrender _ = left show . TextS.decodeUtf8' . toStrict -- | @Right . BC.unpack@ instance MimeUnrender PlainText String where mimeUnrender _ = Right . BC.unpack -- | @Right . id@ instance MimeUnrender OctetStream ByteString where mimeUnrender _ = Right . id -- | @Right . toStrict@ instance MimeUnrender OctetStream BS.ByteString where mimeUnrender _ = Right . toStrict -- $setup -- >>> import Servant.API -- >>> import Data.Aeson -- >>> import Data.Text -- >>> data Book -- >>> instance ToJSON Book where { toJSON = undefined }
zerobuzz/servant
servant/src/Servant/API/ContentTypes.hs
bsd-3-clause
13,854
0
15
3,326
2,300
1,315
985
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- | This module implements the Curved servers to receive/serve metrics. -- Note these are simple TCP (and later, UDP) servers, not an HTTP server -- to provide beautiful rendering of the metrics. -- TODO Probably call this module Protocol instead of Carbon. module Curved.Carbon where import Control.Applicative ((<$>)) import Control.Monad (forever) import Control.Concurrent (forkIO) import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as SC import qualified Data.Map as M import Data.Serialize.Get (getWord32be, runGet) import Data.Serialize.Put (putWord32be, runPut) --import qualified Data.Text as T import Language.Python.Pickle (dictGetString, pickle, unpickle, Value(..)) import Network (accept, listenOn, PortID(..), PortNumber, Socket) import qualified Network.Socket as N (accept, sClose) import qualified Network.Socket.ByteString as NS import System.IO (hClose, hGetLine, hIsEOF, hSetBuffering, BufferMode(..), Handle) import Data.Whisper import Data.Whisper.Store --import Curved.Cache (push, readPoints, Store) -- | Receive metrics on the given port. Messages have the form: -- metric-name value timestamp receivePoints :: Store -> PortNumber -> IO () receivePoints store port = do sock <- listenOn $ PortNumber port forever $ do (handle, _, _) <- accept sock -- hSetBuffering handle NoBuffering forkIO $ processPoints store handle -- | Handle a single message of the form: -- metric-name value timestamp processPoints :: Store -> Handle -> IO () processPoints store handle = do eof <- hIsEOF handle if eof then hClose handle else do line <- hGetLine handle case words line of [metric, value_, timestamp_] -> case (validMetricName metric, reads value_, reads timestamp_) of (True, [(value :: Double, "")], [(timestamp :: Int, "")]) -> do push store metric timestamp value processPoints store handle _ -> hClose handle _ -> hClose handle -- | Predicate to test if a metric name is valid (metric names are used as -- filenames, the most important thing is the metric name can not contain a -- slash). validMetricName :: String -> Bool validMetricName metric = all (`elem` (['a'..'z'] ++ ['0'..'9'] ++ ".-")) metric && length metric > 0 receiveQueries :: Store -> PortNumber -> IO () receiveQueries store port = do sock <- listenOn $ PortNumber port forever $ do (sock', _) <- N.accept sock -- hSetBuffering handle NoBuffering forkIO $ processQueries store sock' -- | Receive requests for metric data processQueries :: Store -> Socket -> IO () processQueries store sock = do -- Loop on the same handle: the client can issue -- multiple requests on the same connection. ms <- receive sock 4 case ms of Nothing -> N.sClose sock -- TODO log corrupt queries Just s -> do let esize = runGet getWord32be s case esize of -- TODO is it possible to have a Left here ? Left _ -> N.sClose sock Right size -> do mcontent <- receive sock $ fromIntegral size case mcontent of Nothing -> N.sClose sock -- TODO log corrupt queries Just content -> do response <- processQuery store content case response of Left err -> N.sClose sock >> print err -- TODO log corrupt queries Right r -> NS.send sock r >> processQueries store sock data Query = CacheQuery S.ByteString -- ^ Query the cache for a specific metric name. deriving Show processQuery :: Store -> S.ByteString -> IO (Either String S.ByteString) processQuery store s = case parseQuery s of Left err -> return $ Left err Right query -> do response <- processQuery' store query let r = pickle response return . Right $ runPut (putWord32be . fromIntegral $ S.length r) `S.append` r parseQuery :: S.ByteString -> Either String Query parseQuery s = do value <- unpickle s typ <- value `dictGetString` "type" case typ of "cache-query" -> CacheQuery <$> value `dictGetString` "metric" x -> Left $ "parseQuery: unknown query type." ++ show x processQuery' :: Store -> Query -> IO Value processQuery' store (CacheQuery metric) = do --datapoints <- readPoints store (SC.unpack metric) let datapoints = [] -- read from non-existing cache. return . Dict $ M.fromList[(BinString "datapoints", List $ tuple datapoints)] where tuple = map (\(Point a b) -> Tuple [BinInt a, BinFloat b]) receive :: Socket -> Int -> IO (Maybe S.ByteString) receive sock n = loop 0 [] where bufferSize = 4096 loop alreadyRead ss = do let r = min (n - alreadyRead) bufferSize s <- NS.recv sock r if S.length s + alreadyRead == n then return . Just . S.concat $ reverse (s : ss) else if S.length s == r then loop (alreadyRead + S.length s) (s : ss) else return Nothing
noteed/curved
Curved/Carbon.hs
bsd-3-clause
5,002
0
27
1,157
1,395
726
669
100
5
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE UnicodeSyntax #-} {-| [@ISO639-1@] pt [@ISO639-2@] por [@ISO639-3@] por [@Native name@] Português [@English name@] Portuguese -} module Text.Numeral.Language.POR ( -- * Language entry entry -- * Conversions , cardinal , ordinal -- * Structure , cardinal_struct , ordinal_struct -- * Bounds , bounds ) where ------------------------------------------------------------------------------- -- Imports ------------------------------------------------------------------------------- import "base" Data.Bool ( otherwise ) import "base" Data.Function ( ($), const, fix ) import "base" Data.Maybe ( Maybe(Just) ) import "base" Data.Ord ( (<) ) import "base" Prelude ( Integral, (-), negate ) import "base-unicode-symbols" Data.Eq.Unicode ( (≡) ) import "base-unicode-symbols" Data.Function.Unicode ( (∘) ) import "base-unicode-symbols" Data.List.Unicode ( (∉) ) import "base-unicode-symbols" Data.Monoid.Unicode ( (⊕) ) import "base-unicode-symbols" Data.Ord.Unicode ( (≤) ) import "base-unicode-symbols" Prelude.Unicode ( ℤ ) import qualified "containers" Data.Map as M ( fromList, lookup ) import "this" Text.Numeral import qualified "this" Text.Numeral.BigNum as BN import qualified "this" Text.Numeral.Exp as E import "this" Text.Numeral.Grammar as G import "this" Text.Numeral.Misc ( dec ) import "this" Text.Numeral.Entry import "text" Data.Text ( Text ) ------------------------------------------------------------------------------- -- POR ------------------------------------------------------------------------------- entry ∷ Entry entry = emptyEntry { entIso639_1 = Just "pt" , entIso639_2 = ["por"] , entIso639_3 = Just "por" , entNativeNames = ["Português"] , entEnglishName = Just "Portuguese" , entCardinal = Just Conversion { toNumeral = cardinal , toStructure = cardinal_struct } , entOrdinal = Just Conversion { toNumeral = ordinal , toStructure = ordinal_struct } } cardinal ∷ (G.Feminine i, G.Masculine i, Integral α, E.Scale α) ⇒ i → α → Maybe Text cardinal inf = cardinalRepr inf ∘ cardinal_struct ordinal ∷ (G.Feminine i, G.Masculine i, G.Singular i, Integral α, E.Scale α) ⇒ i → α → Maybe Text ordinal inf = ordinalRepr inf ∘ ordinal_struct cardinal_struct ∷ ( Integral α, E.Scale α , E.Unknown β, E.Lit β, E.Neg β, E.Add β, E.Mul β, E.Scale β , E.Inflection β, G.Masculine (E.Inf β) ) ⇒ α → β cardinal_struct = pos $ fix $ rule `combine` shortScale1_pt where rule = findRule ( 0, lit ) [ ( 11, add 10 L ) , ( 16, add 10 R ) , ( 20, mul 10 R L) , ( 100, step 100 10 R L) , (1000, step 1000 1000 R L) ] (dec 6 - 1) ordinal_struct ∷ ( Integral α, E.Scale α , E.Unknown β, E.Lit β, E.Neg β, E.Add β, E.Mul β, E.Scale β , E.Inflection β, G.Masculine (E.Inf β) ) ⇒ α → β ordinal_struct = pos $ fix $ rule `combine` shortScale1_pt where rule = findRule ( 0, lit ) [ ( 11, add 10 R ) , ( 20, mul 10 R L) , ( 100, step 100 10 R L) , (1000, step 1000 1000 R L) ] (dec 6 - 1) -- | Like 'shortScale1' with the difference that all scale elements -- are masculine. shortScale1_pt ∷ ( Integral α, E.Scale α , E.Unknown β, E.Lit β, E.Add β, E.Mul β, E.Scale β , E.Inflection β, G.Masculine (E.Inf β) ) ⇒ Rule α β shortScale1_pt = mulScale1_es 3 3 R L BN.rule where mulScale1_es = mulScale_ $ \f m s _ → masculineMul (f m) s masculineMul x y = E.inflection (G.masculine) $ E.mul x y bounds ∷ (Integral α) ⇒ (α, α) bounds = let x = dec 60000 - 1 in (negate x, x) cardinalRepr ∷ (G.Feminine i) ⇒ i → Exp i → Maybe Text cardinalRepr = render defaultRepr { reprValue = \inf n → M.lookup n (syms inf) , reprScale = shortScaleRepr , reprAdd = Just (⊞) , reprMul = Just (⊡) , reprNeg = Just $ \_ _ → "menos " } where (Lit 10 ⊞ Lit n ) _ | n < 8 = "as" | n ≡ 8 = "" | otherwise = "a" (Lit _ ⊞ Lit 10) _ = "" (_ ⊞ _ ) _ = " e " (_ ⊡ Lit 10 ) _ = "" (_ ⊡ Lit 100) _ = "" (_ ⊡ _ ) _ = " " syms inf = M.fromList [ (0, const "zero") , (1, \c → case c of CtxAdd _ (Lit 10) _ → "on" _ | G.isFeminine inf → "uma" | otherwise → "um" ) , (2, \c → case c of CtxAdd _ (Lit 10) _ → "do" CtxMul _ (Lit 10) _ → "vin" CtxMul _ (Lit 100) _ → "duz" _ | G.isFeminine inf → "duas" | otherwise → "dois" ) , (3, \c → case c of CtxAdd _ (Lit 10) _ → "tre" CtxMul _ (Lit 10) _ → "trin" CtxMul _ (Lit 100) _ → "trez" _ → "três" ) , (4, \c → case c of CtxAdd _ (Lit 10) _ → "cator" CtxMul _ (Lit 10) _ → "quaren" _ → "quatro" ) , (5, \c → case c of CtxAdd _ (Lit 10) _ → "quin" CtxMul _ (Lit 10) _ → "cinquen" CtxMul _ (Lit 100) _ → "quin" _ → "cinco" ) , (6, \c → case c of CtxMul _ (Lit 10) _ → "sessen" _ → "seis" ) , (7, \c → case c of CtxMul _ (Lit 10) _ → "seten" _ → "sete" ) , (8, \c → case c of CtxMul _ (Lit 10) _ → "oiten" _ → "oito" ) , (9, \c → case c of CtxMul _ (Lit 10) _ → "noven" _ → "nove" ) , (10, \c → case c of CtxAdd R (Lit _) _ → "ze" CtxMul R (Lit 2) _ → "te" CtxMul R (Lit _) _ → "ta" _ → "dez" ) , (100, \c → case c of CtxAdd {} → "cento" CtxMul _ (Lit n) _ | n ≤ 3 → if G.isFeminine inf then "entas" else "entos" | n ≡ 5 → if G.isFeminine inf then "hentas" else "hentos" | n ≤ 9 → if G.isFeminine inf then "centas" else "centos" | otherwise → "cem" _ → "cem" ) , (1000, const "mil") ] ordinalRepr ∷ (G.Feminine i, G.Singular i) ⇒ i → Exp i → Maybe Text ordinalRepr = render defaultRepr { reprValue = \inf n → M.lookup n (syms inf) , reprScale = shortScaleRepr , reprAdd = Just (⊞) , reprMul = Just (⊡) , reprNeg = Just $ \_ _ → "menos " } where (Lit _ ⊞ Lit 10) _ = "" (_ ⊞ _ ) _ = " " (_ ⊡ Lit 10 ) _ = "" (_ ⊡ Lit 100) _ = "" (_ ⊡ _ ) _ = " " syms inf = M.fromList [ (0, const "zero") , (1, \c → case c of _ → "primeir" ⊕ postFix ) , (2, \c → case c of CtxMul _ (Lit 10) _ → "vi" CtxMul _ (Lit 100) _ → "du" _ → "segund" ⊕ postFix ) , (3, \c → case c of CtxMul _ (Lit 10) _ → "tri" CtxMul _ (Lit 100) _ → "tre" _ → "terceir" ⊕ postFix ) , (4, \c → case c of CtxMul _ (Lit 10) _ → "quadra" CtxMul _ (Lit 100) _ → "quadrin" _ → "quart" ⊕ postFix ) , (5, \c → case c of CtxMul _ (Lit 10) _ → "qüinqua" CtxMul _ (Lit 100) _ → "qüin" _ → "quint" ⊕ postFix ) , (6, \c → case c of CtxMul _ (Lit 10) _ → "sexa" CtxMul _ (Lit 100) _ → "sex" _ → "sext" ⊕ postFix ) , (7, \c → case c of CtxMul _ (Lit 10) _ → "septua" CtxMul _ (Lit 100) _ → "setin" _ → "sétim" ⊕ postFix ) , (8, \c → case c of CtxMul _ (Lit 10) _ → "octo" CtxMul _ (Lit 100) _ → "octin" _ → "oitav" ⊕ postFix ) , (9, \c → case c of CtxMul _ (Lit 10) _ → "nona" CtxMul _ (Lit 100) _ → "non" _ → "non" ⊕ postFix ) , (10, \c → case c of CtxAdd R (Lit _) _ → "ze" CtxMul R (Lit _) _ | isOutside R c → "gésim" ⊕ postFix | otherwise → "gésimo" _ | isOutside R c → "décim" ⊕ postFix | otherwise → "décimo" ) , (100, \c → case c of CtxAdd {} → "cento" CtxMul _ (Lit n) _ | n ∉ [2,3,6] → "gentésim" ⊕ postFix _ → "centésim" ⊕ postFix ) , (1000, const $ "milésim" ⊕ postFix) ] where postFix = if G.isFeminine inf then if G.isSingular inf then "a" else "as" else if G.isSingular inf then "o" else "os" shortScaleRepr ∷ i → ℤ → ℤ → Exp i → Ctx (Exp i) → Maybe Text shortScaleRepr = BN.scaleRepr (BN.quantityName "ilhão" "ilhões") [(4, BN.forms "quatr" "quator" "quator" "quatra" "quatri")]
telser/numerals
src/Text/Numeral/Language/POR.hs
bsd-3-clause
11,734
66
16
5,618
3,289
1,786
1,503
224
29
-- | Some styles for choice calculus expressions. module Language.TTF.CC.Pretty where import System.Console.ANSI (Color(..)) import Language.TTF.Pretty styleOp = color Blue styleKey = color Blue ++ bold styleDim = color Green styleTag = color Green styleVar = color Red
walkie/CC-TaglessFinal
src/Language/TTF/CC/Pretty.hs
bsd-3-clause
276
0
6
43
74
43
31
8
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} module Main where import Network.Protocol.Snmp.AgentX import Data.ByteString.Char8 (ByteString, pack, unpack) import System.Directory import System.FilePath import Control.Monad.IO.Class (liftIO) import Control.Applicative import System.Process import Control.Exception import Control.Concurrent import Data.Maybe (fromMaybe) import Data.Time import System.Exit import Data.Map.Strict (Map, (!)) import qualified Data.Map.Strict as Map import Control.Monad import Data.Binary import System.IO.Temp import Prelude -- | Container for dictionary (script name -> PVal) data Handle = Handle { exitCodeHandle :: ScriptName -> PVal , optionsHandle :: ScriptName -> PVal , outputHandle :: ScriptName -> PVal , errorsHandle :: ScriptName -> PVal , statusHandle :: ScriptName -> PVal } -- | options for scripts type Options = [String] type ScriptName = String data ScriptValues = ScriptValues { exitCode :: Value -- ^ returned value, int , output :: Value -- ^ output, string , errors :: Value -- ^ errors, string , options :: Value -- ^ options, string , status :: Value -- ^ 0 - disabled, 1 - enabled , lastExec :: UTCTime -- ^ last execute time } -- | path to folder with users scripts scriptsPath :: FilePath scriptsPath = "scripts" -- | path to folder with users scripts scriptsAliasesPath :: FilePath scriptsAliasesPath = "scripts_aliases" -- | path to folder with nagios plugins nagiosPluginsPath :: FilePath nagiosPluginsPath = "nagios" -- | path to nagios plugins aliases nagiosAliasesPath :: FilePath nagiosAliasesPath = "nagios_aliases" -- | state path statePath :: FilePath statePath = "script-to-snmp-state" -- | snmp agent -- execute scripts and checks in scriptPath and nagiosScriptsPath -- return result as SNMP main :: IO () main = do (configVersion, st) <- handle emptyMap (decodeFile statePath) mv <- newMVar st cv <- newMVar configVersion exitStatus <- newEmptyMVar handle (putMVar exitStatus) $ agent "/var/agentx/master" [1,3,6,1,4,1,44729] Nothing (mibs (mkHandle cv mv)) _ <- readMVar exitStatus :: IO ExitCode putStrLn "save status" newst <- Map.filter (\x -> status x == enabled True || status x == enabled False || options x /= str "") <$> readMVar mv print newst newcv <- readMVar cv when (st /= newst) $ encodeFile statePath (newcv, newst) where emptyMap :: SomeException -> IO (Integer, Map ScriptName ScriptValues) emptyMap _ = return (1, Map.empty) -- | build MIB tree mibs :: Handle -> [MIB] mibs h = [ mkObject 0 "Fixmon" "about" Nothing , mkObjectType 0 "about" "agent-name" Nothing (bstr "script-to-snmp") , mkObjectType 1 "about" "version" Nothing (bstr "0.1") , mkObjectType 2 "about" "config_version" Nothing save , mkObject 1 "Fixmon" "scripts" Nothing , mkObject 1 "scripts" "scripts_table" (Just (table h scriptsPath scriptsAliasesPath)) -- , mkObject 2 "Fixmon" "nagios" (Just (scripts h nagiosScriptsPath)) , mkObject 2 "Fixmon" "nagios" Nothing , mkObject 1 "nagios" "nagios_table" (Just (table h nagiosPluginsPath nagiosAliasesPath)) ] table :: Handle -> FilePath -> FilePath -> Update table h fp afp = Update $ do files <- liftIO $ getDeepDirectoryContents fp aliases <- liftIO $ getDeepDirectoryContents afp return $ mkTable h "nagios_table" Nothing object (map (fp </>) files ++ map (afp </>) aliases) type Obj = [(String, Handle -> FilePath -> PVal)] object :: Obj object = [ ("name" , \_ n -> bstr (pack (takeFileName n))) , ("status" , \h n -> statusHandle h n) , ("opts" , \h n -> optionsHandle h n) , ("exitCode", \h n -> exitCodeHandle h n) , ("stderr" , \h n -> errorsHandle h n) , ("stdout" , \h n -> outputHandle h n) ] mkTable :: Handle -> String -> Maybe Context -> Obj -> [FilePath] -> [MIB] mkTable h parent mc obj scripts' = let count = length scripts' size = length obj tableHead = [ mkObject 1 parent "table_size" Nothing , mkObjectType 0 "table_size" "table_size" mc (rsValue (Gaude32 $ fromIntegral count)) , mkObject 2 parent "table_body" Nothing , mkObject 1 "table_body" "table_rows" Nothing ] indexes :: [MIB] indexes = mkObject 1 "table_rows" "indexes" Nothing : map (\x -> mkObjectType x "indexes" "" mc (rsValue (Integer $ fromIntegral x))) [1 .. (fromIntegral count)] row :: Integer -> (String, Handle -> String -> PVal) -> [MIB] row n (name, pv) = mkObject n "table_rows" name Nothing : (map (\(x, fp) -> mkObjectType x name "" mc (pv h fp)) $ zip [1 .. (fromIntegral count)] scripts') rows = concatMap (\(i, x) -> row i x) (zip [2 .. (1 + fromIntegral size)] obj) in tableHead ++ indexes ++ rows -- | create handle mkHandle :: MVar Integer -> MVar (Map ScriptName ScriptValues) -> Handle mkHandle cv mv = Handle { exitCodeHandle = Read . vread exitCode , optionsHandle = \sn -> rwValue (vread options sn) (commitOpts sn) (testOpts sn) (undoOpts sn) , outputHandle = Read . vread output , errorsHandle = Read . vread errors , statusHandle = \sn -> rwValue (vread status sn) (commitStatus sn) (testStatus sn) (undoOpts sn) } where zeroTime = UTCTime (toEnum 0) (toEnum 0) -- execute script , make getter for ro result and reexecute vread f sn = do -- execute script by script name, modify mv runScript sn m <- readMVar mv return . f $ m ! sn -- setter for Options commitOpts sn v = do runScript sn updateVersion modifyMVar_ mv (return . Map.update (\x -> Just $ x { options = v, lastExec = zeroTime }) sn) return NoCommitError -- Options must be string testOpts _ (String _) = return NoTestError testOpts _ _ = return WrongValue -- Nothing here undoOpts _ _ = return NoUndoError testStatus _ (Integer 0) = return NoTestError testStatus _ (Integer 1) = return NoTestError testStatus _ (Integer 2) = return NoTestError testStatus sn (Integer 3) = do -- only aliases can be removed if (isNotAlias sn) then return NoAccess else return NoTestError testStatus _ (Integer _) = return BadValue testStatus _ _ = return WrongValue commitStatus sn (Integer 2) = do updateVersion -- add alias let f = takeFileName sn aliasDirectory <- createTempDirectory (getAliasDirectory sn) f copyFile sn (aliasDirectory </> f) runScript (aliasDirectory </> f) return NoCommitError commitStatus sn (Integer 3) = do updateVersion -- remove alias let d = dropFileName sn if (isNotAlias sn) then return CommitFailed else do removeFile sn removeDirectory d modifyMVar_ mv (return . Map.delete sn) return NoCommitError commitStatus sn v = do updateVersion runScript sn let vv = if (isNotAlias sn) then v else addTen v modifyMVar_ mv (return . Map.update (\x -> Just x { status = vv, lastExec = zeroTime }) sn) return NoCommitError addTen (Integer x) = Integer $ x + 10 addTen _ = undefined -- update verion updateVersion = modifyMVar_ cv (return . succ) -- If first run, execute script, save ScriptValues to Map -- if other run, check timeout after last execute, when > 5s execute, or return last result runScript :: ScriptName -> IO () runScript sn = modifyMVar_ mv $ \st -> maybe (runAndUpdate st Nothing Nothing) (checkAndReturn st) $ Map.lookup sn st where runAndUpdate st opts' status' = do let String options' = fromMaybe (String "") opts' status'' = fromMaybe (disabled $ isNotAlias sn) status' if status'' == enabled (isNotAlias sn) then do (c, o, e) <- catch (readProcessWithExitCode sn (words . unpack $ options') []) (\(problem::SomeException) -> return (ExitFailure (-1), "", show problem)) now <- getCurrentTime let val = ScriptValues (exitToValue c) (str o) (str e) (String options') (enabled $ isNotAlias sn) now return $ Map.insert sn val st else do now <- getCurrentTime let val = ScriptValues (exitToValue $ ExitFailure (-1)) (str "") (str "") (String options') (disabled $ isNotAlias sn) now return $ Map.insert sn val st checkAndReturn st val = do now <- getCurrentTime if diffUTCTime now (lastExec val) > 5 then runAndUpdate st (Just $ options val) (Just $ status val) else return st -- | helpers bstr :: ByteString -> PVal bstr x = rsValue (String x) str :: String -> Value str x = String (pack x) enabled :: Bool -> Value enabled True = Integer 1 enabled False = Integer 11 disabled :: Bool -> Value disabled True = Integer 0 disabled False = Integer 10 exitToValue :: ExitCode -> Value exitToValue ExitSuccess = Integer 0 exitToValue (ExitFailure i) = Integer $ fromIntegral i getDeepDirectoryContents :: FilePath -> IO [FilePath] getDeepDirectoryContents fp = do files <- filter (`notElem` [".", ".."]) <$> getDirectoryContents fp concat <$> mapM fun files where fun :: FilePath -> IO [FilePath] fun x = do isD <- doesDirectoryExist (fp </> x) if isD then do f <- filter (`notElem` [".", ".."]) <$> getDirectoryContents (fp </> x) concat <$> mapM (\y -> fun (x </> y)) f else return [x] base :: FilePath -> FilePath base = head . splitDirectories isScripts :: FilePath -> Bool isScripts fp = scriptsPath == base fp isNagiosPlugin :: FilePath -> Bool isNagiosPlugin fp = nagiosPluginsPath == base fp getAliasDirectory :: FilePath -> FilePath getAliasDirectory fp | isScripts fp = scriptsAliasesPath | otherwise = nagiosAliasesPath isNotAlias :: FilePath -> Bool isNotAlias fp = nagiosPluginsPath == (base fp) || scriptsPath == (base fp) -- | here must be state saver save :: PVal save = rwValue readV commit test undo where test _ = return NoTestError commit _ = return NoCommitError undo _ = return NoUndoError readV = return $ String "success" instance Binary ScriptValues where put sv = do let String s = options sv Integer i = status sv put s >> put i get = do s <- get i <- get return $ ScriptValues (String "") (String "") (String "") (String s) (Integer i) (UTCTime (toEnum 0) (toEnum 0)) instance Eq ScriptValues where a == b = options a == options b && status a == status b instance Show ScriptValues where show a = show (options a)
chemist/script-to-snmp
src/Main.hs
bsd-3-clause
11,165
0
22
3,057
3,513
1,800
1,713
234
15
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Templates.Components where import Control.Lens ((^.)) import Data.Monoid ((<>)) import Data.Text (Text, intercalate, pack) import Text.InterpolatedString.Perl6 (q) import Types import Types.PropTypes indexTemplate :: Template indexTemplate = Template "index.js" [q| import COMPONENT from './COMPONENT'; export default COMPONENT; |] stringifyPropTypes :: Int -> Maybe [Prop] -> Text stringifyPropTypes nSpaces ts = case ts of Nothing -> "" Just xs -> intercalate (",\n" <> spaces) $ pack . show <$> xs where spaces = pack . take nSpaces $ cycle " " propNames :: Maybe [Prop] -> Text propNames ts = case ts of Nothing -> "" Just xs -> intercalate ", " $ fmap (^. name) xs reasonProps :: Maybe [Prop] -> Text reasonProps ts = case ts of Nothing -> "" Just xs -> intercalate " " $ fmap (\x -> ("::" <>) $ (^. name) x) xs reasonJSProps :: Maybe [Prop] -> Text reasonJSProps ts = case ts of Nothing -> "" Just xs -> intercalate " " $ fmap (\x -> (\y -> y <> "::jsProps##" <> y) $ (^. name) x) xs
tpoulsen/generate-component
src/Templates/Components.hs
bsd-3-clause
1,231
0
16
352
401
216
185
32
2
module Control.Monad.Code.Opcode where import Data.Word nop :: Word8 nop = 0x00 aconst_null :: Word8 aconst_null = 0x01 iconst_m1 :: Word8 iconst_m1 = 0x02 iconst_0 :: Word8 iconst_0 = 0x03 iconst_1 :: Word8 iconst_1 = 0x04 iconst_2 :: Word8 iconst_2 = 0x05 iconst_3 :: Word8 iconst_3 = 0x06 iconst_4 :: Word8 iconst_4 = 0x07 iconst_5 :: Word8 iconst_5 = 0x08 lconst_0 :: Word8 lconst_0 = 0x09 lconst_1 :: Word8 lconst_1 = 0x0a fconst_0 :: Word8 fconst_0 = 0x0b fconst_1 :: Word8 fconst_1 = 0x0c fconst_2 :: Word8 fconst_2 = 0x0d dconst_0 :: Word8 dconst_0 = 0x0e dconst_1 :: Word8 dconst_1 = 0x0f bipush :: Word8 bipush = 0x10 sipush :: Word8 sipush = 0x11 ldc :: Word8 ldc = 0x12 ldc_w :: Word8 ldc_w = 0x13 ldc2_w :: Word8 ldc2_w = 0x14 iload :: Word8 iload = 0x15 lload :: Word8 lload = 0x16 fload :: Word8 fload = 0x17 dload :: Word8 dload = 0x18 aload :: Word8 aload = 0x19 iload_0 :: Word8 iload_0 = 0x1a iload_1 :: Word8 iload_1 = 0x1b iload_2 :: Word8 iload_2 = 0x1c iload_3 :: Word8 iload_3 = 0x1d lload_0 :: Word8 lload_0 = 0x1e lload_1 :: Word8 lload_1 = 0x1f lload_2 :: Word8 lload_2 = 0x20 lload_3 :: Word8 lload_3 = 0x21 fload_0 :: Word8 fload_0 = 0x22 fload_1 :: Word8 fload_1 = 0x23 fload_2 :: Word8 fload_2 = 0x24 fload_3 :: Word8 fload_3 = 0x25 dload_0 :: Word8 dload_0 = 0x26 dload_1 :: Word8 dload_1 = 0x27 dload_2 :: Word8 dload_2 = 0x28 dload_3 :: Word8 dload_3 = 0x29 aload_0 :: Word8 aload_0 = 0x2a aload_1 :: Word8 aload_1 = 0x2b aload_2 :: Word8 aload_2 = 0x2c aload_3 :: Word8 aload_3 = 0x2d iaload :: Word8 iaload = 0x2e laload :: Word8 laload = 0x2f faload :: Word8 faload = 0x30 daload :: Word8 daload = 0x31 aaload :: Word8 aaload = 0x32 baload :: Word8 baload = 0x33 caload :: Word8 caload = 0x34 saload :: Word8 saload = 0x35 istore :: Word8 istore = 0x36 lstore :: Word8 lstore = 0x37 fstore :: Word8 fstore = 0x38 dstore :: Word8 dstore = 0x39 astore :: Word8 astore = 0x3a istore_0 :: Word8 istore_0 = 0x3b istore_1 :: Word8 istore_1 = 0x3c istore_2 :: Word8 istore_2 = 0x3d istore_3 :: Word8 istore_3 = 0x3e lstore_0 :: Word8 lstore_0 = 0x3f lstore_1 :: Word8 lstore_1 = 0x40 lstore_2 :: Word8 lstore_2 = 0x41 lstore_3 :: Word8 lstore_3 = 0x42 fstore_0 :: Word8 fstore_0 = 0x43 fstore_1 :: Word8 fstore_1 = 0x44 fstore_2 :: Word8 fstore_2 = 0x45 fstore_3 :: Word8 fstore_3 = 0x46 dstore_0 :: Word8 dstore_0 = 0x47 dstore_1 :: Word8 dstore_1 = 0x48 dstore_2 :: Word8 dstore_2 = 0x49 dstore_3 :: Word8 dstore_3 = 0x4a astore_0 :: Word8 astore_0 = 0x4b astore_1 :: Word8 astore_1 = 0x4c astore_2 :: Word8 astore_2 = 0x4d astore_3 :: Word8 astore_3 = 0x4e iastore :: Word8 iastore = 0x4f lastore :: Word8 lastore = 0x50 fastore :: Word8 fastore = 0x51 dastore :: Word8 dastore = 0x52 aastore :: Word8 aastore = 0x53 bastore :: Word8 bastore = 0x54 castore :: Word8 castore = 0x55 sastore :: Word8 sastore = 0x56 pop :: Word8 pop = 0x57 pop2 :: Word8 pop2 = 0x58 dup :: Word8 dup = 0x59 dup_x1 :: Word8 dup_x1 = 0x5a dup_x2 :: Word8 dup_x2 = 0x5b dup2 :: Word8 dup2 = 0x5c dup2_x1 :: Word8 dup2_x1 = 0x5d dup2_x2 :: Word8 dup2_x2 = 0x5e swap :: Word8 swap = 0x5f iadd :: Word8 iadd = 0x60 ladd :: Word8 ladd = 0x61 fadd :: Word8 fadd = 0x62 dadd :: Word8 dadd = 0x63 isub :: Word8 isub = 0x64 lsub :: Word8 lsub = 0x65 fsub :: Word8 fsub = 0x66 dsub :: Word8 dsub = 0x67 imul :: Word8 imul = 0x68 lmul :: Word8 lmul = 0x69 fmul :: Word8 fmul = 0x6a dmul :: Word8 dmul = 0x6b idiv :: Word8 idiv = 0x6c ldiv :: Word8 ldiv = 0x6d fdiv :: Word8 fdiv = 0x6e ddiv :: Word8 ddiv = 0x6f irem :: Word8 irem = 0x70 lrem :: Word8 lrem = 0x71 frem :: Word8 frem = 0x72 drem :: Word8 drem = 0x73 ineg :: Word8 ineg = 0x74 lneg :: Word8 lneg = 0x75 fneg :: Word8 fneg = 0x76 dneg :: Word8 dneg = 0x77 ishl :: Word8 ishl = 0x78 lshl :: Word8 lshl = 0x79 ishr :: Word8 ishr = 0x7a lshr :: Word8 lshr = 0x7b iushr :: Word8 iushr = 0x7c lushr :: Word8 lushr = 0x7d iand :: Word8 iand = 0x7e land :: Word8 land = 0x7f ior :: Word8 ior = 0x80 lor :: Word8 lor = 0x81 ixor :: Word8 ixor = 0x82 lxor :: Word8 lxor = 0x83 iinc :: Word8 iinc = 0x84 i2l :: Word8 i2l = 0x85 i2f :: Word8 i2f = 0x86 i2d :: Word8 i2d = 0x87 l2i :: Word8 l2i = 0x88 l2f :: Word8 l2f = 0x89 l2d :: Word8 l2d = 0x8a f2i :: Word8 f2i = 0x8b f2l :: Word8 f2l = 0x8c f2d :: Word8 f2d = 0x8d d2i :: Word8 d2i = 0x8e d2l :: Word8 d2l = 0x8f d2f :: Word8 d2f = 0x90 i2b :: Word8 i2b = 0x91 i2c :: Word8 i2c = 0x92 i2s :: Word8 i2s = 0x93 lcmp :: Word8 lcmp = 0x94 fcmpl :: Word8 fcmpl = 0x95 fcmpg :: Word8 fcmpg = 0x96 dcmpl :: Word8 dcmpl = 0x97 dcmpg :: Word8 dcmpg = 0x98 ifeq :: Word8 ifeq = 0x99 ifne :: Word8 ifne = 0x9a iflt :: Word8 iflt = 0x9b ifge :: Word8 ifge = 0x9c ifgt :: Word8 ifgt = 0x9d ifle :: Word8 ifle = 0x9e if_icmpeq :: Word8 if_icmpeq = 0x9f if_icmpne :: Word8 if_icmpne = 0xa0 if_icmplt :: Word8 if_icmplt = 0xa1 if_icmpge :: Word8 if_icmpge = 0xa2 if_icmpgt :: Word8 if_icmpgt = 0xa3 if_icmple :: Word8 if_icmple = 0xa4 if_acmpeq :: Word8 if_acmpeq = 0xa5 if_acmpne :: Word8 if_acmpne = 0xa6 goto :: Word8 goto = 0xa7 jsr :: Word8 jsr = 0xa8 ret :: Word8 ret = 0xa9 tableswitch :: Word8 tableswitch = 0xaa lookupswitch :: Word8 lookupswitch = 0xab ireturn :: Word8 ireturn = 0xac lreturn :: Word8 lreturn = 0xad freturn :: Word8 freturn = 0xae dreturn :: Word8 dreturn = 0xaf areturn :: Word8 areturn = 0xb0 return :: Word8 return = 0xb1 getstatic :: Word8 getstatic = 0xb2 putstatic :: Word8 putstatic = 0xb3 getfield :: Word8 getfield = 0xb4 putfield :: Word8 putfield = 0xb5 invokevirtual :: Word8 invokevirtual = 0xb6 invokespecial :: Word8 invokespecial = 0xb7 invokestatic :: Word8 invokestatic = 0xb8 invokeinterface :: Word8 invokeinterface = 0xb9 xxxunusedxxx1 :: Word8 xxxunusedxxx1 = 0xba new :: Word8 new = 0xbb newarray :: Word8 newarray = 0xbc anewarray :: Word8 anewarray = 0xbd arraylength :: Word8 arraylength = 0xbe athrow :: Word8 athrow = 0xbf checkcast :: Word8 checkcast = 0xc0 instanceof :: Word8 instanceof = 0xc1 monitorenter :: Word8 monitorenter = 0xc2 monitorexit :: Word8 monitorexit = 0xc3 wide :: Word8 wide = 0xc4 multianewarray :: Word8 multianewarray = 0xc5 ifnull :: Word8 ifnull = 0xc6 ifnonnull :: Word8 ifnonnull = 0xc7 goto_w :: Word8 goto_w = 0xc8 jsr_w :: Word8 jsr_w = 0xc9 breakpoint :: Word8 breakpoint = 0xca impdep1 :: Word8 impdep1 = 0xfe impdep2 :: Word8 impdep2 = 0xff
sonyandy/tnt
Control/Monad/Code/Opcode.hs
bsd-3-clause
6,531
0
4
1,440
2,063
1,239
824
412
1
module Main where import Control.Applicative ((<$>)) import Control.Arrow ((&&&)) import Control.Monad (join) import Data.Char (isNumber, toLower, toUpper) import Data.Function (on) import Data.List (intersperse, isPrefixOf, isInfixOf, notElem, sortBy) import Data.Map (Map, elems, filterWithKey, fromList, keys, mapKeys, toList, union) import Data.Maybe (mapMaybe) import Language.C.Analysis (runTrav_) import Language.C.Analysis.AstAnalysis (analyseAST) import Language.C.Analysis.SemRep (GlobalDecls(..), TagDef(EnumDef), EnumType(..), Enumerator(..)) import Language.C.Data.Ident (Ident(..)) import Language.C.Data.InputStream (inputStreamFromString) import Language.C.Data.Position (Position(..)) import Language.C.Parser (parseC) import Language.C.Pretty (pretty) import Language.C.Syntax.Constants (getCInteger) import Language.C.Syntax.AST (CExpr(..), CConst(CIntConst), CBinaryOp(..)) import System.Environment (getArgs) import System.Process (readProcess) import Text.Regex.PCRE ((=~)) main = do [out] <- getArgs let inc = mkIncludeBlock includeFiles defines <- getDefinitions inc enums <- getEnums inc let (exports, definitions) = outputs defines enums prelude = [ "{-# LANGUAGE GeneralizedNewtypeDeriving #-}", "module System.Linux.Netlink.Constants (" ++ join (intersperse ", " $ join exports) ++ ") where", "", "import Data.Bits", ""] writeFile out $ unlines (prelude ++ join definitions) outputs :: Map String Integer -> [Map String Integer] -> ([[String]], [[String]]) outputs d e = let define r = selectDefines r d enum r = selectEnum r e in map fst &&& map snd $ [mkEnum "AddressFamily" $ define "^AF_", mkEnum "MessageType" $ union (define "^NLMSG_(?!ALIGNTO)") (enum "^RTM_"), mkFlag "MessageFlags" $ define "^NLM_F_", mkEnum "LinkType" $ define "^ARPHRD_", mkFlag "LinkFlags" $ define "^IFF_", mkEnum "LinkAttrType" $ enum "^IFLA_", mkFlag "AddrFlags" $ define "^IFA_F_", mkEnum "Scope" $ enum "^RT_SCOPE_", mkEnum "AddrAttrType" $ enum "^IFA_", mkEnum "RouteTableId" $ enum "^RT_TABLE_", mkEnum "RouteProto" $ define "^RTPROT_", mkEnum "RouteType" $ enum "^RTN_", mkFlag "RouteFlags" $ define "^RTM_F_", mkEnum "RouteAttrType" $ enum "^RTA_"] includeFiles :: [String] includeFiles = [ "sys/types.h" , "sys/socket.h" , "linux/if.h" , "linux/if_tun.h" , "linux/if_arp.h" , "linux/if_link.h" , "linux/netlink.h" , "linux/rtnetlink.h" ] mkIncludeBlock :: [String] -> String mkIncludeBlock = unlines . map (\e -> "#include <" ++ e ++ ">") mkFlag :: String -> Map String Integer -> ([String], [String]) mkFlag name vals = (name : map fst values, ty : "" : join (map makeConst values)) where ty = ("newtype " ++ name ++ " = " ++ name ++ " Int deriving (Bits, Eq, Enum, Integral, Num, Ord, Real, Show)") makeConst (n, v) = [n ++ " :: (Num a, Bits a) => a", n ++ " = " ++ show v] values = sortBy (compare `on` snd) . toList . mapKeys ("f" ++) $ vals mkEnum :: String -> Map String Integer -> ([String], [String]) mkEnum name vals = (name : map fst values, ty : "" : join (map makeConst values)) where ty = ("newtype " ++ name ++ " = " ++ name ++ " Int deriving (Eq, Enum, Integral, Num, Ord, Real, Show)") makeConst (n, v) = [n ++ " :: (Num a) => a", n ++ " = " ++ show v] values = sortBy (compare `on` snd) . toList . mapKeys ('e' :) $ vals selectDefines :: String -> Map String Integer -> Map String Integer selectDefines regex defines = filterWithKey (\k v -> k =~ regex) defines selectEnum :: String -> [Map String Integer] -> Map String Integer selectEnum regex enums = head $ filter (all (=~ regex) . keys) enums full :: String -> String full regex = "^" ++ regex ++ "$" getEnums :: String -> IO [Map String Integer] getEnums source = do parsed <- flip parseC initPos . inputStreamFromString <$> preprocessed let unit = gTags . fst . check $ runTrav_ (analyseAST $ check parsed) enums = mapMaybe getEnum (elems unit) return $ map cleanEnums enums where check (Left err) = error $ show err check (Right a) = a preprocessed = readProcess "gcc" ["-E", "-"] source initPos = Position "" 0 0 getEnum (EnumDef (EnumType _ es _ _)) = Just $ map getEnumValue es getEnum _ = Nothing getEnumValue (Enumerator (Ident s _ _) v _ _) = (s, evalCExpr v) cleanEnums = filterWithKey (\k v -> not ("_" `isPrefixOf` k)) . fromList evalCExpr :: CExpr -> Integer evalCExpr (CConst (CIntConst v _)) = getCInteger v evalCExpr (CBinary CAddOp a b _) = (evalCExpr a) + (evalCExpr b) evalCExpr other = error $ show (pretty other) getDefinitions :: String -> IO (Map String Integer) getDefinitions headers = do defines <- map words . lines <$> readDefines headers let isDefine (c:n:_) = c == "#define" && '(' `notElem` n && head n /= '_' hasValue = (>= 3) . length names = map (!! 1) $ filter (\d -> isDefine d && hasValue d) defines kludge = map (\n -> "@define \"" ++ n ++ "\" " ++ n) names defines2 <- map words . lines <$> preprocess (headers ++ unlines kludge) let isInteresting d = (hasValue d && head d == "@define" && (all isNumber (d !! 2) || "0x" `isPrefixOf` (d !! 2) && all isNumber (drop 2 (d !! 2)))) realDefines = map (take 2 . drop 1) $ filter isInteresting defines2 clean [k,v] = (init (tail k), read v) return $ fromList (map clean realDefines) where readDefines = readProcess "gcc" ["-E", "-dM", "-"] preprocess = readProcess "gcc" ["-E", "-"]
metachord/netlink-hs
scripts/Generate.hs
bsd-3-clause
6,154
0
18
1,728
2,114
1,122
992
129
3
{-# LANGUAGE FlexibleInstances,FlexibleContexts #-} module AI.Testing where import AI.Classification import AI.DataLoader import AI.RandomUtils -- import AI.Classification.SemiBoost import AI.Classification.Boosting import Control.Monad import Control.Monad.Writer import qualified Data.Map as Map import Data.Maybe import Debug.Trace import System.IO import System.Random ------------------------------------------------------------------------------- data TestConfig = TestConfig { ldr :: DataRate -- ^ labeled data rate , tdr :: DataRate -- ^ training data rate. Set equal to number of 1-(1/number of folds). , seed :: Int , inductive :: Bool , resultsDir :: String , dataDir :: String , datafile :: DatafileDesc , testAlg :: EnsembleContainer } deriving Show defTest = TestConfig { ldr = Relative 0.2 , tdr = Relative 0.8 , seed = 0 , inductive = True , resultsDir = "." , dataDir = "." , datafile = defDatafileDesc , testAlg = error "defTest: must specify which algorithm to test" } getDataRateFactor :: DataRate -> Int -> Double getDataRateFactor (Absolute amount) n = (fromIntegral amount)/(fromIntegral n) getDataRateFactor (Relative factor) _ = factor ------------------------------------------------------------------------------- runTests :: [TestConfig] -> IO () runTests ts = do sequence_ [ runTest t | t <- ts ] runTest :: TestConfig -> IO () runTest conf = do putStrLn $ "TEST = "++(show conf)++"-"++(modelName $ testAlg conf)++"-"++(show $ ldr conf)++"-"++(show $ seed conf) dm <- loadData $ applyDirPrefix (dataDir conf) (datafile conf) test2file conf $ do ds <- dm let bds = toBinaryData (datafileTrueClass $ datafile conf) ds return $ performTest conf bds performTest :: TestConfig -> TrainingData Bool -> Map.Map String [String] performTest conf bds = Map.insert "performance" (reverse $ map show $ perfTrace ens finaltestdata) aitrace where rgen = mkStdGen $ seed conf (ens,aitrace) = (runAI (seed conf) $ train (testAlg conf) ls (us)) (train_data,test_data) = randSplit rgen (getDataRateFactor (tdr conf) (length bds)) bds (ls,us) = s2ss rgen (getDataRateFactor (ldr conf) (length train_data)) train_data finaltestdata = if (inductive conf) then test_data else train_data test2file :: (Show a) => TestConfig -> Either a (Map.Map String [String]) -> IO () test2file conf (Left err) = putStrLn $ show err test2file conf (Right logai) = do let outfile = trace ("outfile="++(conf2filename conf $ testAlg conf)) $ conf2filename conf $ testAlg conf hout <- openFile outfile AppendMode putStrLn $ concat $ map ("\n"++) $ Map.findWithDefault [] "print" logai putStrLn "Writing next line to CSV" putStrLn $ csvLine "performance" hPutStrLn hout $ csvLine "performance" hPutStrLn hout $ csvLine "aveMargin" hPutStrLn hout $ csvLine "weights-mean" hPutStrLn hout $ csvLine "weights-stddev" hFlush hout putStrLn "Done." hClose hout where csvLine str = (show $ testAlg conf)++","++(show $ seed conf)++","++str++","++(list2csv $ reverse $ Map.findWithDefault ["csvLine error"] str logai) conf2filename :: (ClassifyModel model labelType) => TestConfig -> model -> String conf2filename conf model = (resultsDir conf)++"/"++(datafileName $ datafile conf)++"-"++(modelName model)++"-ldr="++(show $ ldr conf)++"-tdr="++(show $ tdr conf)++{-"-"++(show seed)++-}".csv" -- perfTrace (Ensemble params es) ds = [ errorRate $ genConfusionMatrix (classify $ Ensemble params $ drop i es) ds | i <- [0..length es]] perfTrace (EC (Ensemble params es)) ds = [ errorRate $ genConfusionMatrix (classify $ Ensemble params $ drop i es) ds | i <- [0..length es]]
mikeizbicki/Classification
src/AI/Testing.hs
bsd-3-clause
3,850
0
17
801
1,218
622
596
75
2
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, TypeSynonymInstances, PatternGuards #-} module Idris.AbsSyntaxTree where import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Typecheck import Idris.Docstrings import IRTS.Lang import IRTS.CodegenCommon import Util.Pretty import Util.DynamicLinker import Idris.Colours import System.Console.Haskeline import System.IO import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Error import Data.Function (on) import Data.List hiding (group) import Data.Char import qualified Data.Map as M import qualified Data.Text as T import qualified Data.Map as M import Data.Either import qualified Data.Set as S import Data.Word (Word) import Data.Maybe (fromMaybe, mapMaybe) import Data.Traversable (Traversable) import Data.Foldable (Foldable) import Debug.Trace import Text.PrettyPrint.Annotated.Leijen data ElabWhat = ETypes | EDefns | EAll deriving (Show, Eq) -- Data to pass to recursively called elaborators; e.g. for where blocks, -- paramaterised declarations, etc. -- rec_elabDecl is used to pass the top level elaborator into other elaborators, -- so that we can have mutually recursive elaborators in separate modules without -- having to muck about with cyclic modules. data ElabInfo = EInfo { params :: [(Name, PTerm)], inblock :: Ctxt [Name], -- names in the block, and their params liftname :: Name -> Name, namespace :: Maybe [String], elabFC :: Maybe FC, rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl -> Idris () } toplevel :: ElabInfo toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented") eInfoNames :: ElabInfo -> [Name] eInfoNames info = map fst (params info) ++ M.keys (inblock info) data IOption = IOption { opt_logLevel :: Int, opt_typecase :: Bool, opt_typeintype :: Bool, opt_coverage :: Bool, opt_showimp :: Bool, -- ^^ show implicits opt_errContext :: Bool, opt_repl :: Bool, opt_verbose :: Bool, opt_nobanner :: Bool, opt_quiet :: Bool, opt_codegen :: Codegen, opt_outputTy :: OutputType, opt_ibcsubdir :: FilePath, opt_importdirs :: [FilePath], opt_triple :: String, opt_cpu :: String, opt_cmdline :: [Opt], -- remember whole command line opt_origerr :: Bool, opt_autoSolve :: Bool, -- ^ automatically apply "solve" tactic in prover opt_autoImport :: [FilePath], -- ^ e.g. Builtins+Prelude opt_optimise :: [Optimisation] } deriving (Show, Eq) defaultOpts = IOption { opt_logLevel = 0 , opt_typecase = False , opt_typeintype = False , opt_coverage = True , opt_showimp = False , opt_errContext = False , opt_repl = True , opt_verbose = True , opt_nobanner = False , opt_quiet = False , opt_codegen = Via "c" , opt_outputTy = Executable , opt_ibcsubdir = "" , opt_importdirs = [] , opt_triple = "" , opt_cpu = "" , opt_cmdline = [] , opt_origerr = False , opt_autoSolve = True , opt_autoImport = [] , opt_optimise = defaultOptimise } data PPOption = PPOption { ppopt_impl :: Bool -- ^^ whether to show implicits } deriving (Show) data Optimisation = PETransform -- partial eval and associated transforms deriving (Show, Eq) defaultOptimise = [PETransform] -- | Pretty printing options with default verbosity. defaultPPOption :: PPOption defaultPPOption = PPOption { ppopt_impl = False } -- | Pretty printing options with the most verbosity. verbosePPOption :: PPOption verbosePPOption = PPOption { ppopt_impl = True } -- | Get pretty printing options from the big options record. ppOption :: IOption -> PPOption ppOption opt = PPOption { ppopt_impl = opt_showimp opt } -- | Get pretty printing options from an idris state record. ppOptionIst :: IState -> PPOption ppOptionIst = ppOption . idris_options data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord) -- | The output mode in use data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle | IdeSlave Integer Handle -- ^ Send IDE output for some request ID to the handle deriving Show -- | How wide is the console? data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken | ColsWide Int -- ^ Manually specified - must be positive | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise -- | The global state used in the Idris monad data IState = IState { tt_ctxt :: Context, -- ^ All the currently defined names and their terms idris_constraints :: [(UConstraint, FC)], -- ^ A list of universe constraints and their corresponding source locations idris_infixes :: [FixDecl], -- ^ Currently defined infix operators idris_implicits :: Ctxt [PArg], idris_statics :: Ctxt [Bool], idris_classes :: Ctxt ClassInfo, idris_dsls :: Ctxt DSL, idris_optimisation :: Ctxt OptInfo, idris_datatypes :: Ctxt TypeInfo, idris_namehints :: Ctxt [Name], idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported -- ^ list of lhs/rhs, and a list of missing clauses idris_flags :: Ctxt [FnOpt], idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos idris_calledgraph :: Ctxt [Name], idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]), idris_tyinfodata :: Ctxt TIData, idris_fninfo :: Ctxt FnInfo, idris_transforms :: Ctxt [(Term, Term)], idris_totcheck :: [(FC, Name)], -- names to check totality on idris_defertotcheck :: [(FC, Name)], -- names to check at the end idris_totcheckfail :: [(FC, String)], idris_options :: IOption, idris_name :: Int, idris_lineapps :: [((FilePath, Int), PTerm)], -- ^ Full application LHS on source line idris_metavars :: [(Name, (Maybe Name, Int, Bool))], -- ^ The currently defined but not proven metavariables idris_coercions :: [Name], idris_errRev :: [(Term, Term)], syntax_rules :: SyntaxRules, syntax_keywords :: [String], imported :: [FilePath], -- ^ The imported modules idris_scprims :: [(Name, (Int, PrimFn))], idris_objs :: [(Codegen, FilePath)], idris_libs :: [(Codegen, String)], idris_cgflags :: [(Codegen, String)], idris_hdrs :: [(Codegen, String)], idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public proof_list :: [(Name, [String])], errSpan :: Maybe FC, parserWarnings :: [(FC, Err)], lastParse :: Maybe Name, indent_stack :: [Int], brace_stack :: [Maybe Int], lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed? idris_parsedSpan :: Maybe FC, hide_list :: [(Name, Maybe Accessibility)], default_access :: Accessibility, default_total :: Bool, ibc_write :: [IBCWrite], compiled_so :: Maybe String, idris_dynamic_libs :: [DynamicLib], idris_language_extensions :: [LanguageExt], idris_outputmode :: OutputMode, idris_colourRepl :: Bool, idris_colourTheme :: ColourTheme, idris_errorhandlers :: [Name], -- ^ Global error handlers idris_nameIdx :: (Int, Ctxt (Int, Name)), idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers module_aliases :: M.Map [T.Text] [T.Text], idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console? idris_postulates :: S.Set Name, idris_whocalls :: Maybe (M.Map Name [Name]), idris_callswho :: Maybe (M.Map Name [Name]), idris_repl_defs :: [Name] -- ^ List of names that were defined in the repl, and can be re-/un-defined } -- Required for parsers library, and therefore trifecta instance Show IState where show = const "{internal state}" data SizeChange = Smaller | Same | Bigger | Unknown deriving (Show, Eq) {-! deriving instance Binary SizeChange deriving instance NFData SizeChange !-} type SCGEntry = (Name, [Maybe (Int, SizeChange)]) type UsageReason = (Name, Int) -- fn_name, its_arg_number data CGInfo = CGInfo { argsdef :: [Name], calls :: [(Name, [[Name]])], scg :: [SCGEntry], argsused :: [Name], usedpos :: [(Int, [UsageReason])] } deriving Show {-! deriving instance Binary CGInfo deriving instance NFData CGInfo !-} primDefs = [sUN "unsafePerformPrimIO", sUN "mkLazyForeignPrim", sUN "mkForeignPrim", sUN "void"] -- information that needs writing for the current module's .ibc file data IBCWrite = IBCFix FixDecl | IBCImp Name | IBCStatic Name | IBCClass Name | IBCInstance Bool Name Name | IBCDSL Name | IBCData Name | IBCOpt Name | IBCMetavar Name | IBCSyntax Syntax | IBCKeyword String | IBCImport (Bool, FilePath) -- True = import public | IBCImportDir FilePath | IBCObj Codegen FilePath | IBCLib Codegen String | IBCCGFlag Codegen String | IBCDyLib String | IBCHeader Codegen String | IBCAccess Name Accessibility | IBCMetaInformation Name MetaInformation | IBCTotal Name Totality | IBCFlags Name [FnOpt] | IBCFnInfo Name FnInfo | IBCTrans Name (Term, Term) | IBCErrRev (Term, Term) | IBCCG Name | IBCDoc Name | IBCCoercion Name | IBCDef Name -- i.e. main context | IBCNameHint (Name, Name) | IBCLineApp FilePath Int PTerm | IBCErrorHandler Name | IBCFunctionErrorHandler Name Name Name | IBCPostulate Name | IBCTotCheckErr FC String | IBCParsedRegion FC deriving Show -- | The initial state for the compiler idrisInit :: IState idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext [] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] [] [] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] [] (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty AutomaticWidth S.empty Nothing Nothing [] -- | The monad for the main REPL - reading and processing files and updating -- global state (hence the IO inner monad). --type Idris = WriterT [Either String (IO ())] (State IState a)) type Idris = StateT IState (ErrorT Err IO) -- Commands in the REPL data Codegen = Via String -- | ViaC -- | ViaJava -- | ViaNode -- | ViaJavaScript -- | ViaLLVM | Bytecode deriving (Show, Eq) -- | REPL commands data Command = Quit | Help | Eval PTerm | NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name. | Undefine [Name] | Check PTerm | DocStr (Either Name Const) | TotCheck Name | Reload | Load FilePath (Maybe Int) -- up to maximum line number | ChangeDirectory FilePath | ModImport String | Edit | Compile Codegen String | Execute | ExecVal PTerm | Metavars | Prove Name | AddProof (Maybe Name) | RmProof Name | ShowProof Name | Proofs | Universes | LogLvl Int | Spec PTerm | HNF PTerm | TestInline PTerm | Defn Name | Missing Name | DynamicLink FilePath | ListDynamic | Pattelab PTerm | Search PTerm | CaseSplitAt Bool Int Name | AddClauseFrom Bool Int Name | AddProofClauseFrom Bool Int Name | AddMissing Bool Int Name | MakeWith Bool Int Name | MakeLemma Bool Int Name | DoProofSearch Bool Bool Int Name [Name] -- ^ the first bool is whether to update, -- the second is whether to search recursively (i.e. for the arguments) | SetOpt Opt | UnsetOpt Opt | NOP | SetColour ColourType IdrisColour | ColourOn | ColourOff | ListErrorHandlers | SetConsoleWidth ConsoleWidth | Apropos String | WhoCalls Name | CallsWho Name | MakeDoc String -- IdrisDoc | Warranty | PrintDef Name | PPrint OutputFmt Int PTerm | TransformInfo Name -- Debugging commands | DebugInfo Name | DebugUnify PTerm PTerm data OutputFmt = HTMLOutput | LaTeXOutput data Opt = Filename String | Quiet | NoBanner | ColourREPL Bool | Ideslave | IdeslaveSocket | ShowLibs | ShowLibdir | ShowIncs | NoBasePkgs | NoPrelude | NoBuiltins -- only for the really primitive stuff! | NoREPL | OLogging Int | Output String | TypeCase | TypeInType | DefaultTotal | DefaultPartial | WarnPartial | WarnReach | NoCoverage | ErrContext | ShowImpl | Verbose | Port String -- REPL TCP port | IBCSubDir String | ImportDir String | PkgBuild String | PkgInstall String | PkgClean String | PkgCheck String | PkgREPL String | PkgMkDoc String -- IdrisDoc | PkgTest String | WarnOnly | Pkg String | BCAsm String | DumpDefun String | DumpCases String | UseCodegen Codegen | OutputTy OutputType | Extension LanguageExt | InterpretScript String | EvalExpr String | TargetTriple String | TargetCPU String | OptLevel Int | AddOpt Optimisation | RemoveOpt Optimisation | Client String | ShowOrigErr | AutoWidth -- ^ Automatically adjust terminal width | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover deriving (Show, Eq) -- Parsed declarations data Fixity = Infixl { prec :: Int } | Infixr { prec :: Int } | InfixN { prec :: Int } | PrefixN { prec :: Int } deriving Eq {-! deriving instance Binary Fixity deriving instance NFData Fixity !-} instance Show Fixity where show (Infixl i) = "infixl " ++ show i show (Infixr i) = "infixr " ++ show i show (InfixN i) = "infix " ++ show i show (PrefixN i) = "prefix " ++ show i data FixDecl = Fix Fixity String deriving Eq instance Show FixDecl where show (Fix f s) = show f ++ " " ++ s {-! deriving instance Binary FixDecl deriving instance NFData FixDecl !-} instance Ord FixDecl where compare (Fix x _) (Fix y _) = compare (prec x) (prec y) data Static = Static | Dynamic deriving (Show, Eq) {-! deriving instance Binary Static deriving instance NFData Static !-} -- Mark bindings with their explicitness, and laziness data Plicity = Imp { pargopts :: [ArgOpt], pstatic :: Static, pparam :: Bool } | Exp { pargopts :: [ArgOpt], pstatic :: Static, pparam :: Bool } -- this is a param (rather than index) | Constraint { pargopts :: [ArgOpt], pstatic :: Static } | TacImp { pargopts :: [ArgOpt], pstatic :: Static, pscript :: PTerm } deriving (Show, Eq) {-! deriving instance Binary Plicity deriving instance NFData Plicity !-} impl = Imp [] Dynamic False expl = Exp [] Dynamic False expl_param = Exp [] Dynamic True constraint = Constraint [] Static tacimpl t = TacImp [] Dynamic t data FnOpt = Inlinable -- always evaluate when simplifying | TotalFn | PartialFn | CoveringFn | Coinductive | AssertTotal | Dictionary -- type class dictionary, eval only when -- a function argument, and further evaluation resutls | Implicit -- implicit coercion | NoImplicit -- do not apply implicit coercions | CExport String -- export, with a C name | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension | ErrorReverse -- ^^ attempt to reverse normalise before showing in error | Reflection -- a reflecting function, compile-time only | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names | Constructor -- Data constructor type deriving (Show, Eq) {-! deriving instance Binary FnOpt deriving instance NFData FnOpt !-} type FnOpts = [FnOpt] inlinable :: FnOpts -> Bool inlinable = elem Inlinable dictionary :: FnOpts -> Bool dictionary = elem Dictionary -- | Data declaration options data DataOpt = Codata -- ^ Set if the the data-type is coinductive | DefaultEliminator -- ^ Set if an eliminator should be generated for data type | DefaultCaseFun -- ^ Set if a case function should be generated for data type | DataErrRev deriving (Show, Eq) type DataOpts = [DataOpt] -- | Type provider - what to provide data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term | ProvPostulate t -- ^ goal type must be Type, so only term deriving (Show, Eq, Functor) type ProvideWhat = ProvideWhat' PTerm -- | Top-level declarations such as compiler directives, definitions, -- datatypes and typeclasses. data PDecl' t = PFix FC Fixity [String] -- ^ Fixity declaration | PTy (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC FnOpts Name t -- ^ Type declaration | PPostulate (Docstring (Either Err PTerm)) SyntaxInfo FC FnOpts Name t -- ^ Postulate | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause | PCAF FC Name t -- ^ Top level constant | PData (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration. | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block | PNamespace String [PDecl' t] -- ^ New namespace | PRecord (Docstring (Either Err PTerm)) SyntaxInfo FC Name t DataOpts (Docstring (Either Err PTerm)) Name t -- ^ Record declaration | PClass (Docstring (Either Err PTerm)) SyntaxInfo FC [t] -- constraints Name [(Name, t)] -- parameters [(Name, Docstring (Either Err PTerm))] -- parameter docstrings [PDecl' t] -- declarations -- ^ Type class: arguments are documentation, syntax info, source location, constraints, -- class name, parameters, method declarations | PInstance SyntaxInfo FC [t] -- constraints Name -- class [t] -- parameters t -- full instance type (Maybe Name) -- explicit name [PDecl' t] -- ^ Instance declaration: arguments are syntax info, source location, constraints, -- class name, parameters, full instance type, optional explicit name, and definitions | PDSL Name (DSL' t) -- ^ DSL declaration | PSyntax FC Syntax -- ^ Syntax definition | PMutual FC [PDecl' t] -- ^ Mutual block | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad. | PProvider SyntaxInfo FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If -- bool is True, lhs and rhs must be convertible deriving Functor {-! deriving instance Binary PDecl' deriving instance NFData PDecl' !-} -- For elaborator state type ElabD a = Elab' [PDecl] a -- | One clause of a top-level definition. Term arguments to constructors are: -- -- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause) -- -- 2. The list of extra 'with' patterns -- -- 3. The right-hand side -- -- 4. The where block (PDecl' t) data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition. | PWith FC Name t [t] t [PDecl' t] | PClauseR FC [t] t [PDecl' t] | PWithR FC [t] t [PDecl' t] deriving Functor {-! deriving instance Binary PClause' deriving instance NFData PClause' !-} -- | Data declaration data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype d_tcon :: t, -- ^ Type constructor d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, t, FC, [Name])] -- ^ Constructors } -- ^ Data declaration | PLaterdecl { d_name :: Name, d_tcon :: t } -- ^ "Placeholder" for data whose constructors are defined later deriving Functor {-! deriving instance Binary PData' deriving instance NFData PData' !-} -- Handy to get a free function for applying PTerm -> PTerm functions -- across a program, by deriving Functor type PDecl = PDecl' PTerm type PData = PData' PTerm type PClause = PClause' PTerm -- get all the names declared in a decl declared :: PDecl -> [Name] declared (PFix _ _ _) = [] declared (PTy _ _ _ _ _ n t) = [n] declared (PPostulate _ _ _ _ n t) = [n] declared (PClauses _ _ n _) = [] -- not a declaration declared (PCAF _ n _) = [n] declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _) = a declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n] declared (PParams _ _ ds) = concatMap declared ds declared (PNamespace _ ds) = concatMap declared ds declared (PRecord _ _ _ n _ _ _ c _) = [n, c] declared (PClass _ _ _ _ n _ _ ms) = n : concatMap declared ms declared (PInstance _ _ _ _ _ _ _ _) = [] declared (PDSL n _) = [n] declared (PSyntax _ _) = [] declared (PMutual _ ds) = concatMap declared ds declared (PDirective _) = [] -- get the names declared, not counting nested parameter blocks tldeclared :: PDecl -> [Name] tldeclared (PFix _ _ _) = [] tldeclared (PTy _ _ _ _ _ n t) = [n] tldeclared (PPostulate _ _ _ _ n t) = [n] tldeclared (PClauses _ _ n _) = [] -- not a declaration tldeclared (PRecord _ _ _ n _ _ _ c _) = [n, c] tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _) = a tldeclared (PParams _ _ ds) = [] tldeclared (PMutual _ ds) = concatMap tldeclared ds tldeclared (PNamespace _ ds) = concatMap tldeclared ds tldeclared (PClass _ _ _ _ n _ _ ms) = concatMap tldeclared ms tldeclared (PInstance _ _ _ _ _ _ _ _) = [] tldeclared _ = [] defined :: PDecl -> [Name] defined (PFix _ _ _) = [] defined (PTy _ _ _ _ _ n t) = [] defined (PPostulate _ _ _ _ n t) = [] defined (PClauses _ _ n _) = [n] -- not a declaration defined (PCAF _ n _) = [n] defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _) = a defined (PData _ _ _ _ _ (PLaterdecl n _)) = [] defined (PParams _ _ ds) = concatMap defined ds defined (PNamespace _ ds) = concatMap defined ds defined (PRecord _ _ _ n _ _ _ c _) = [n, c] defined (PClass _ _ _ _ n _ _ ms) = n : concatMap defined ms defined (PInstance _ _ _ _ _ _ _ _) = [] defined (PDSL n _) = [n] defined (PSyntax _ _) = [] defined (PMutual _ ds) = concatMap defined ds defined (PDirective _) = [] --defined _ = [] updateN :: [(Name, Name)] -> Name -> Name updateN ns n | Just n' <- lookup n ns = n' updateN _ n = n updateNs :: [(Name, Name)] -> PTerm -> PTerm updateNs [] t = t updateNs ns t = mapPT updateRef t where updateRef (PRef fc f) = PRef fc (updateN ns f) updateRef t = t -- updateDNs :: [(Name, Name)] -> PDecl -> PDecl -- updateDNs [] t = t -- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t -- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c) -- where updateCNs ns (PClause n l ts r ds) -- = PClause (updateN ns n) (fmap (updateNs ns) l) -- (map (fmap (updateNs ns)) ts) -- (fmap (updateNs ns) r) -- (map (updateDNs ns) ds) -- updateDNs ns c = c data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show) -- | High level language terms data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language | PRef FC Name -- ^ A reference to a variable | PInferRef FC Name -- ^ A name to be defined later | PPatvar FC Name -- ^ A pattern variable | PLam Name PTerm PTerm -- ^ A lambda abstraction | PPi Plicity Name PTerm PTerm -- ^ (n : t1) -> t2 | PLet Name PTerm PTerm PTerm -- ^ A let binding | PTyped PTerm PTerm -- ^ Term with explicit type | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x | PAppBind FC PTerm [PArg] -- ^ implicitly bound application | PMatchApp FC Name -- ^ Make an application by type matching | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs | PTrue FC PunInfo -- ^ Unit type..? | PRefl FC PTerm -- ^ The canonical proof of the equality type | PResolveTC FC -- ^ Solve this dictionary by type class resolution | PEq FC PTerm PTerm PTerm PTerm -- ^ Heterogeneous equality type: A = B | PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type | PPair FC PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration) | PDPair FC PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration) | PAs FC Name PTerm -- ^ @-pattern, valid LHS only | PAlternative Bool [PTerm] -- ^ True if only one may work. (| A, B, C|) | PHidden PTerm -- ^ Irrelevant or hidden pattern | PType -- ^ 'Type' type | PUniverse Universe -- ^ Some universe | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions | PConstant Const -- ^ Builtin types | Placeholder -- ^ Underscore | PDoBlock [PDo] -- ^ Do notation | PIdiom FC PTerm -- ^ Idiom brackets | PReturn FC | PMetavar Name -- ^ A metavariable, ?name | PProof [PTactic] -- ^ Proof script | PTactics [PTactic] -- ^ As PProof, but no auto solving | PElabError Err -- ^ Error to report on elaboration | PImpossible -- ^ Special case for declaring when an LHS can't typecheck | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces | PUnifyLog PTerm -- ^ dump a trace of unifications when building term | PNoImplicits PTerm -- ^ never run implicit converions on the term | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term]) | PUnquote PTerm -- ^ ,Term deriving Eq {-! deriving instance Binary PTerm deriving instance NFData PTerm !-} mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm mapPT f t = f (mpt t) where mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s) mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s) mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s) mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s) (fmap (mapPT f) g) mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as) mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as) mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os) mpt (PEq fc lt rt l r) = PEq fc (mapPT f lt) (mapPT f rt) (mapPT f l) (mapPT f r) mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r) mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r) mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r) mpt (PAlternative a as) = PAlternative a (map (mapPT f) as) mpt (PHidden t) = PHidden (mapPT f t) mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds) mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts) mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts) mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm) mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm) mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm) mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc) mpt x = x data PTactic' t = Intro [Name] | Intros | Focus Name | Refine Name [Bool] | Rewrite t | DoUnify | Induction t | CaseTac t | Equiv t | MatchRefine Name | LetTac Name t | LetTacTy Name t t | Exact t | Compute | Trivial | TCInstance | ProofSearch Bool Bool Int (Maybe Name) [Name] -- ^ the bool is whether to search recursively | Solve | Attack | ProofState | ProofTerm | Undo | Try (PTactic' t) (PTactic' t) | TSeq (PTactic' t) (PTactic' t) | ApplyTactic t -- see Language.Reflection module | ByReflection t | Reflect t | Fill t | GoalType String (PTactic' t) | TCheck t | TEval t | TDocStr (Either Name Const) | TSearch t | Skip | TFail [ErrorReportPart] | Qed | Abandon | SourceFC deriving (Show, Eq, Functor, Foldable, Traversable) {-! deriving instance Binary PTactic' deriving instance NFData PTactic' !-} instance Sized a => Sized (PTactic' a) where size (Intro nms) = 1 + size nms size Intros = 1 size (Focus nm) = 1 + size nm size (Refine nm bs) = 1 + size nm + length bs size (Rewrite t) = 1 + size t size (Induction t) = 1 + size t size (LetTac nm t) = 1 + size nm + size t size (Exact t) = 1 + size t size Compute = 1 size Trivial = 1 size Solve = 1 size Attack = 1 size ProofState = 1 size ProofTerm = 1 size Undo = 1 size (Try l r) = 1 + size l + size r size (TSeq l r) = 1 + size l + size r size (ApplyTactic t) = 1 + size t size (Reflect t) = 1 + size t size (Fill t) = 1 + size t size Qed = 1 size Abandon = 1 size Skip = 1 size (TFail ts) = 1 + size ts size SourceFC = 1 type PTactic = PTactic' PTerm data PDo' t = DoExp FC t | DoBind FC Name t | DoBindP FC t t [(t,t)] | DoLet FC Name t t | DoLetP FC t t deriving (Eq, Functor) {-! deriving instance Binary PDo' deriving instance NFData PDo' !-} instance Sized a => Sized (PDo' a) where size (DoExp fc t) = 1 + size fc + size t size (DoBind fc nm t) = 1 + size fc + size nm + size t size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r size (DoLetP fc l r) = 1 + size fc + size l + size r type PDo = PDo' PTerm -- The priority gives a hint as to elaboration order. Best to elaborate -- things early which will help give a more concrete type to other -- variables, e.g. a before (interpTy a). data PArg' t = PImp { priority :: Int, machine_inf :: Bool, -- true if the machine inferred it argopts :: [ArgOpt], pname :: Name, getTm :: t } | PExp { priority :: Int, argopts :: [ArgOpt], pname :: Name, getTm :: t } | PConstraint { priority :: Int, argopts :: [ArgOpt], pname :: Name, getTm :: t } | PTacImplicit { priority :: Int, argopts :: [ArgOpt], pname :: Name, getScript :: t, getTm :: t } deriving (Show, Eq, Functor) data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg deriving (Show, Eq) instance Sized a => Sized (PArg' a) where size (PImp p _ l nm trm) = 1 + size nm + size trm size (PExp p l nm trm) = 1 + size nm + size trm size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm {-! deriving instance Binary PArg' deriving instance NFData PArg' !-} pimp n t mach = PImp 1 mach [] n t pexp t = PExp 1 [] (sMN 0 "arg") t pconst t = PConstraint 1 [] (sMN 0 "carg") t ptacimp n s t = PTacImplicit 2 [] n s t type PArg = PArg' PTerm -- Type class data data ClassInfo = CI { instanceName :: Name, class_methods :: [(Name, (FnOpts, PTerm))], class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl class_default_superclasses :: [PDecl], class_params :: [Name], class_instances :: [Name] } deriving Show {-! deriving instance Binary ClassInfo deriving instance NFData ClassInfo !-} -- Type inference data data TIData = TIPartial -- ^ a function with a partially defined type | TISolution [Term] -- ^ possible solutions to a metavariable in a type deriving Show -- | Miscellaneous information about functions data FnInfo = FnInfo { fn_params :: [Int] } deriving Show {-! deriving instance Binary FnInfo !-} data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting detaggable :: Bool } deriving Show {-! deriving instance Binary OptInfo deriving instance NFData OptInfo !-} data TypeInfo = TI { con_names :: [Name], codata :: Bool, data_opts :: DataOpts, param_pos :: [Int], mutual_types :: [Name] } deriving Show {-! deriving instance Binary TypeInfo deriving instance NFData TypeInfo !-} -- Syntactic sugar info data DSL' t = DSL { dsl_bind :: t, dsl_return :: t, dsl_apply :: t, dsl_pure :: t, dsl_var :: Maybe t, index_first :: Maybe t, index_next :: Maybe t, dsl_lambda :: Maybe t, dsl_let :: Maybe t, dsl_pi :: Maybe t } deriving (Show, Functor) {-! deriving instance Binary DSL' deriving instance NFData DSL' !-} type DSL = DSL' PTerm data SynContext = PatternSyntax | TermSyntax | AnySyntax deriving Show {-! deriving instance Binary SynContext deriving instance NFData SynContext !-} data Syntax = Rule [SSymbol] PTerm SynContext deriving Show syntaxNames :: Syntax -> [Name] syntaxNames (Rule syms _ _) = mapMaybe ename syms where ename (Keyword n) = Just n ename _ = Nothing syntaxSymbols :: Syntax -> [SSymbol] syntaxSymbols (Rule ss _ _) = ss {-! deriving instance Binary Syntax deriving instance NFData Syntax !-} data SSymbol = Keyword Name | Symbol String | Binding Name | Expr Name | SimpleExpr Name deriving (Show, Eq) {-! deriving instance Binary SSymbol deriving instance NFData SSymbol !-} newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] } emptySyntaxRules :: SyntaxRules emptySyntaxRules = SyntaxRules [] updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules where newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr) ruleSort [] [] = EQ ruleSort [] _ = LT ruleSort _ [] = GT ruleSort (s1:ss1) (s2:ss2) = case symCompare s1 s2 of EQ -> ruleSort ss1 ss2 r -> r -- Better than creating Ord instance for SSymbol since -- in general this ordering does not really make sense. symCompare (Keyword n1) (Keyword n2) = compare n1 n2 symCompare (Keyword _) _ = LT symCompare (Symbol _) (Keyword _) = GT symCompare (Symbol s1) (Symbol s2) = compare s1 s2 symCompare (Symbol _) _ = LT symCompare (Binding _) (Keyword _) = GT symCompare (Binding _) (Symbol _) = GT symCompare (Binding b1) (Binding b2) = compare b1 b2 symCompare (Binding _) _ = LT symCompare (Expr _) (Keyword _) = GT symCompare (Expr _) (Symbol _) = GT symCompare (Expr _) (Binding _) = GT symCompare (Expr e1) (Expr e2) = compare e1 e2 symCompare (Expr _) _ = LT symCompare (SimpleExpr _) (Keyword _) = GT symCompare (SimpleExpr _) (Symbol _) = GT symCompare (SimpleExpr _) (Binding _) = GT symCompare (SimpleExpr _) (Expr _) = GT symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2 initDSL = DSL (PRef f (sUN ">>=")) (PRef f (sUN "return")) (PRef f (sUN "<$>")) (PRef f (sUN "pure")) Nothing Nothing Nothing Nothing Nothing Nothing where f = fileFC "(builtin)" data Using = UImplicit Name PTerm | UConstraint Name [Name] deriving (Show, Eq) {-! deriving instance Binary Using deriving instance NFData Using !-} data SyntaxInfo = Syn { using :: [Using], syn_params :: [(Name, PTerm)], syn_namespace :: [String], no_imp :: [Name], decoration :: Name -> Name, inPattern :: Bool, implicitAllowed :: Bool, maxline :: Maybe Int, mut_nesting :: Int, dsl_info :: DSL, syn_in_quasiquote :: Int } deriving Show {-! deriving instance NFData SyntaxInfo deriving instance Binary SyntaxInfo !-} defaultSyntax = Syn [] [] [] [] id False False Nothing 0 initDSL 0 expandNS :: SyntaxInfo -> Name -> Name expandNS syn n@(NS _ _) = n expandNS syn n = case syn_namespace syn of [] -> n xs -> sNS n xs -- For inferring types of things bi = fileFC "builtin" inferTy = sMN 0 "__Infer" inferCon = sMN 0 "__infer" inferDecl = PDatadecl inferTy PType [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType ( PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType")) (PRef bi inferTy)), bi, [])] inferOpts = [] infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t] infP = P (TCon 6 0) inferTy (TType (UVal 0)) getInferTerm, getInferType :: Term -> Term getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc getInferTerm (App (App _ _) tm) = tm getInferTerm tm = tm -- error ("getInferTerm " ++ show tm) getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc where toTy (Lam t) = Pi t (TType (UVar 0)) toTy (PVar t) = PVTy t toTy b = b getInferType (App (App _ ty) _) = ty -- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign primNames = [eqTy, eqCon, inferTy, inferCon] unitTy = sUN "Unit" unitCon = sUN "MkUnit" falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $ "The empty type, also known as the trivially false proposition." ++ "\n\n" ++ "Use `void` or `absurd` to prove anything if you have a variable " ++ "of type `Void` in scope." falseTy = sUN "Void" pairTy = sNS (sUN "Pair") ["Builtins"] pairCon = sNS (sUN "MkPair") ["Builtins"] eqTy = sUN "=" eqCon = sUN "Refl" eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $ "The propositional equality type. A proof that `x` = `y`." ++ "\n\n" ++ "To use such a proof, pattern-match on it, and the two equal things will " ++ "then need to be the _same_ pattern." ++ "\n\n" ++ "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++ "is possible to state equalities between values of potentially different " ++ "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++ "\n\n" ++ "You may need to use `(~=~)` to explicitly request heterogeneous equality." eqDecl = PDatadecl eqTy (piBindp impl [(n "A", PType), (n "B", PType)] (piBind [(n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))] PType)) [(reflDoc, reflParamDoc, eqCon, PPi impl (n "A") PType ( PPi impl (n "x") (PRef bi (n "A")) (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False, pimp (n "B") Placeholder False, pexp (PRef bi (n "x")), pexp (PRef bi (n "x"))])), bi, [])] where n a = sUN a reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "A proof that `x` in fact equals `x`. To construct this, you must have already " ++ "shown that both sides are in fact equal." reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"), (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")] eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"), (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality") ] where n a = sUN a eqOpts = [] -- Defined in builtins.idr sigmaTy = sNS (sUN "Sigma") ["Builtins"] existsCon = sNS (sUN "MkSigma") ["Builtins"] piBind :: [(Name, PTerm)] -> PTerm -> PTerm piBind = piBindp expl piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm piBindp p [] t = t piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t) -- Pretty-printing declarations and terms -- These "show" instances render to an absurdly wide screen because inserted line breaks -- could interfere with interactive editing, which calls "show". instance Show PTerm where showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm instance Show PDecl where showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d instance Show PClause where showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c instance Show PData where showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d instance Pretty PTerm OutputAnnotation where pretty = prettyImp defaultPPOption -- | Colourise annotations according to an Idris state. It ignores the names -- in the annotation, as there's no good way to show extended information on a -- terminal. consoleDecorate :: IState -> OutputAnnotation -> String -> String consoleDecorate ist _ | not (idris_colourRepl ist) = id consoleDecorate ist (AnnConst c) = let theme = idris_colourTheme ist in if constIsType c then colouriseType theme else colouriseData theme consoleDecorate ist (AnnData _ _) = colouriseData (idris_colourTheme ist) consoleDecorate ist (AnnType _ _) = colouriseType (idris_colourTheme ist) consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist) consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist) consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist) consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist theme = idris_colourTheme ist in case () of _ | isDConName n ctxt -> colouriseData theme _ | isFnName n ctxt -> colouriseFun theme _ | isTConName n ctxt -> colouriseType theme _ | isPostulateName n ist -> colourisePostulate theme _ | otherwise -> id -- don't colourise unknown names consoleDecorate ist (AnnFC _) = id consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt) where colour BoldText = IdrisColour Nothing True False True False colour UnderlineText = IdrisColour Nothing True True False False colour ItalicText = IdrisColour Nothing True False False True consoleDecorate ist (AnnTerm _ _) = id consoleDecorate ist (AnnSearchResult _) = id consoleDecorate ist (AnnErr _) = id isPostulateName :: Name -> IState -> Bool isPostulateName n ist = S.member n (idris_postulates ist) -- | Pretty-print a high-level closed Idris term with no information about precedence/associativity prettyImp :: PPOption -- ^^ pretty printing options -> PTerm -- ^^ the term to pretty-print -> Doc OutputAnnotation prettyImp impl = pprintPTerm impl [] [] [] -- | Serialise something to base64 using its Binary instance. -- | Do the right thing for rendering a term in an IState prettyIst :: IState -> PTerm -> Doc OutputAnnotation prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist) -- | Pretty-print a high-level Idris term in some bindings context with infix info pprintPTerm :: PPOption -- ^^ pretty printing options -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit -> [Name] -- ^^ names to always show in pi, even if not used -> [FixDecl] -- ^^ Fixity declarations -> PTerm -- ^^ the term to pretty-print -> Doc OutputAnnotation pprintPTerm ppo bnd docArgs infixes = prettySe 10 bnd where prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation prettySe p bnd (PQuote r) = text "![" <> pretty r <> text "]" prettySe p bnd (PPatvar fc n) = pretty n prettySe p bnd e | Just str <- slist p bnd e = str | Just n <- snat p e = annotate (AnnData "Nat" "") (text (show n)) prettySe p bnd (PRef fc n) = prettyName True (ppopt_impl ppo) bnd n prettySe p bnd (PLam n ty sc) = bracket p 2 . group . align . hang 2 $ text "\\" <> bindingOf n False <+> text "=>" <$> prettySe 10 ((n, False):bnd) sc prettySe p bnd (PLet n ty v sc) = bracket p 2 . group . align $ kwd "let" <+> (group . align . hang 2 $ bindingOf n False <+> text "=" <$> prettySe 10 bnd v) </> kwd "in" <+> (group . align . hang 2 $ prettySe 10 ((n, False):bnd) sc) prettySe p bnd (PPi (Exp l s _) n ty sc) | n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs = bracket p 2 . group $ enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+> st <> text "->" <$> prettySe 10 ((n, False):bnd) sc | otherwise = bracket p 2 . group $ group (prettySe 1 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc) where st = case s of Static -> text "[static]" <> space _ -> empty prettySe p bnd (PPi (Imp l s _) n ty sc) | ppopt_impl ppo = bracket p 2 $ lbrace <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+> st <> text "->" </> prettySe 10 ((n, True):bnd) sc | otherwise = prettySe 10 ((n, True):bnd) sc where st = case s of Static -> text "[static]" <> space _ -> empty prettySe p bnd (PPi (Constraint _ _) n ty sc) = bracket p 2 $ prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc prettySe p bnd (PPi (TacImp _ _ s) n ty sc) = bracket p 2 $ lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <> rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args | UN nm <- basename f , not (ppopt_impl ppo) && null (getShowArgs args) = prettyName True (ppopt_impl ppo) bnd f prettySe p bnd (PAppBind _ (PRef _ f) []) | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f prettySe p bnd (PApp _ (PRef _ op) args) -- infix operators | UN nm <- basename op , not (tnull nm) && (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) = case getShowArgs args of [] -> opName True [x] -> group (opName True <$> group (prettySe 0 bnd (getTm x))) [l,r] -> let precedence = fromMaybe 20 (fmap prec f) in bracket p precedence $ inFix (getTm l) (getTm r) (l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) -> bracket p 1 $ enclose lparen rparen (inFix (getTm l) (getTm r)) <+> align (group (vsep (map (prettyArgS bnd) rest))) as -> opName True <+> align (vsep (map (prettyArgS bnd) as)) where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op f = getFixity (opStr op) left l = case f of Nothing -> prettySe (-1) bnd l Just (Infixl p') -> prettySe p' bnd l Just f' -> prettySe (prec f'-1) bnd l right r = case f of Nothing -> prettySe (-1) bnd r Just (Infixr p') -> prettySe p' bnd r Just f' -> prettySe (prec f'-1) bnd r inFix l r = align . group $ (left l <+> opName False) <$> group (right r) prettySe p bnd (PApp _ hd@(PRef fc f) [tm]) -- symbols, like 'foo | PConstant (Idris.Core.TT.Str str) <- getTm tm, f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $ char '\'' <> prettySe 10 bnd (PRef fc (sUN str)) prettySe p bnd (PApp _ f as) = -- Normal prefix applications let args = getShowArgs as fp = prettySe 1 bnd f in bracket p 1 . group $ if ppopt_impl ppo then if null as then fp else fp <+> align (vsep (map (prettyArgS bnd) as)) else if null args then fp else fp <+> align (vsep (map (prettyArgS bnd) args)) prettySe p bnd (PCase _ scr cases) = align $ kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <$> indent 2 (vsep (map ppcase cases)) where ppcase (l, r) = nest nestingSize $ prettySe 10 ([(n, False) | n <- vars l] ++ bnd) l <+> text "=>" <+> prettySe 10 ([(n, False) | n <- vars l] ++ bnd) r -- Warning: this is a bit of a hack. At this stage, we don't have the -- global context, so we can't determine which names are constructors, -- which are types, and which are pattern variables on the LHS of the -- case pattern. We use the heuristic that names without a namespace -- are patvars, because right now case blocks in PTerms are always -- delaborated from TT before being sent to the pretty-printer. If they -- start getting printed directly, THIS WILL BREAK. -- Potential solution: add a list of known patvars to the cases in -- PCase, and have the delaborator fill it out, kind of like the pun -- disambiguation on PDPair. vars tm = filter noNS (allNamesIn tm) noNS (NS _ _) = False noNS _ = True prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm prettySe p bnd (PRefl _ _) = annName eqCon $ text "Refl" prettySe p bnd (PResolveTC _) = text "resolvetc" prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()" prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()" prettySe p bnd (PTrue _ TypeOrTerm) = text "()" prettySe p bnd (PEq _ lt rt l r) | ppopt_impl ppo = bracket p 1 $ enclose lparen rparen eq <+> align (group (vsep (map (prettyArgS bnd) [PImp 0 False [] (sUN "A") lt, PImp 0 False [] (sUN "B") rt, PExp 0 [] (sUN "x") l, PExp 0 [] (sUN "y") r]))) | otherwise = bracket p 2 . align . group $ prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r) where eq = annName eqTy (text "=") prettySe p bnd (PRewrite _ l r _) = bracket p 2 $ text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r prettySe p bnd (PTyped l r) = lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) . align . group . vsep . punctuate (ann comma) $ map (prettySe 10 bnd) elts where ann = case pun of TypeOrTerm -> id IsType -> annName pairTy IsTerm -> annName pairCon prettySe p bnd (PDPair _ TypeOrTerm l t r) = lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen prettySe p bnd (PDPair _ IsType (PRef _ n) t r) = annName sigmaTy lparen <> bindingOf n False <+> annName sigmaTy (text "**") <+> prettySe 10 ((n, False):bnd) r <> annName sigmaTy rparen prettySe p bnd (PDPair _ IsType l t r) = annName sigmaTy lparen <> prettySe 10 bnd l <+> annName sigmaTy (text "**") <+> prettySe 10 bnd r <> annName sigmaTy rparen prettySe p bnd (PDPair _ IsTerm l t r) = annName existsCon lparen <> prettySe 10 bnd l <+> annName existsCon (text "**") <+> prettySe 10 bnd r <> annName existsCon rparen prettySe p bnd (PAlternative a as) = lparen <> text "|" <> prettyAs <> text "|" <> rparen where prettyAs = foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as prettySe p bnd PType = annotate (AnnType "Type" "The type of types") $ text "Type" prettySe p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u) prettySe p bnd (PConstant c) = annotate (AnnConst c) (text (show c)) -- XXX: add pretty for tactics prettySe p bnd (PProof ts) = text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace prettySe p bnd (PTactics ts) = text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace prettySe p bnd (PMetavar n) = text "?" <> pretty n prettySe p bnd (PReturn f) = kwd "return" prettySe p bnd PImpossible = kwd "impossible" prettySe p bnd Placeholder = text "_" prettySe p bnd (PDoBlock _) = text "do block pretty not implemented" prettySe p bnd (PCoerced t) = prettySe p bnd t prettySe p bnd (PElabError s) = pretty s -- Quasiquote pprinting ignores bound vars prettySe p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe p [] t <> text ")" prettySe p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe p [] t <+> colon <+> prettySe p [] g <> text ")" prettySe p bnd (PUnquote t) = text "~" <> prettySe p bnd t prettySe p bnd _ = text "missing pretty-printer for term" prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm) prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm) prettyArgSe bnd arg = prettySe 0 bnd arg prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation annName n = annotate (AnnName n Nothing Nothing Nothing) opStr :: Name -> String opStr (NS n _) = opStr n opStr (UN n) = T.unpack n basename :: Name -> Name basename (NS n _) = basename n basename n = n slist' p bnd (PApp _ (PRef _ nil) _) | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just [] slist' p bnd (PRef _ nil) | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just [] slist' p bnd (PApp _ (PRef _ cons) args) | nsroot cons == sUN "::", (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args, all isImp imps, Just tl' <- slist' p bnd tl = Just (hd:tl') where isImp (PImp {}) = True isImp _ = False slist' _ _ tm = Nothing slist p bnd e | Just es <- slist' p bnd e = Just $ case es of [] -> annotate (AnnData "" "") $ text "[]" [x] -> enclose left right . group $ prettySe p bnd x xs -> (enclose left right . align . group . vsep . punctuate comma . map (prettySe p bnd)) xs where left = (annotate (AnnData "" "") (text "[")) right = (annotate (AnnData "" "") (text "]")) comma = (annotate (AnnData "" "") (text ",")) slist _ _ _ = Nothing pairElts :: PTerm -> Maybe [PTerm] pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts) | otherwise = Just [x, y] pairElts _ = Nothing natns = "Prelude.Nat." snat p (PRef _ z) | show z == (natns++"Z") || show z == "Z" = Just 0 snat p (PApp _ s [PExp {getTm=n}]) | show s == (natns++"S") || show s == "S", Just n' <- snat p n = Just $ 1 + n' snat _ _ = Nothing bracket outer inner doc | inner > outer = lparen <> doc <> rparen | otherwise = doc kwd = annotate AnnKeyword . text fixities :: M.Map String Fixity fixities = M.fromList [(s, f) | (Fix f s) <- infixes] getFixity :: String -> Maybe Fixity getFixity = flip M.lookup fixities -- | Pretty-printer helper for the binding site of a name bindingOf :: Name -- ^^ the bound name -> Bool -- ^^ whether the name is implicit -> Doc OutputAnnotation bindingOf n imp = annotate (AnnBoundName n imp) (text (show n)) -- | Pretty-printer helper for names that attaches the correct annotations prettyName :: Bool -- ^^ whether the name should be parenthesised if it is an infix operator -> Bool -- ^^ whether to show namespaces -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit -> Name -- ^^ the name to pprint -> Doc OutputAnnotation prettyName infixParen showNS bnd n | (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_" | (UN n') <- n, isPrefixOf "_" $ T.unpack n' = text "_" | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName where fullName = text nameSpace <> parenthesise (text (baseName n)) baseName (UN n) = T.unpack n baseName (NS n ns) = baseName n baseName (MN i s) = T.unpack s baseName other = show other nameSpace = case n of (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else "" _ -> "" isInfix = case baseName n of "" -> False (c : _) -> not (isAlpha c) parenthesise = if isInfix && infixParen then enclose lparen rparen else id showCImp :: PPOption -> PClause -> Doc OutputAnnotation showCImp ppo (PClause _ n l ws r w) = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r <+> text "where" <+> text (show w) where showWs [] = empty showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs showCImp ppo (PWith _ n l ws r w) = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r <+> braces (text (show w)) where showWs [] = empty showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs showDImp :: PPOption -> PData -> Doc OutputAnnotation showDImp ppo (PDatadecl n ty cons) = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$> (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons)) showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation showDecls o ds = vsep (map (showDeclImp o) ds) showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops)) showDeclImp o (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+> indent 2 (vsep (map (showCImp o) cs)) showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line) showDeclImp o (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line) showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn) showDeclImp o (PClass _ _ _ cs n ps _ ds) = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds showDeclImp o (PInstance _ _ cs n _ t _ ds) = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds showDeclImp _ _ = text "..." -- showDeclImp (PImport o) = "import " ++ o instance Show (Doc OutputAnnotation) where show = flip (displayS . renderCompact) "" getImps :: [PArg] -> [(Name, PTerm)] getImps [] = [] getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs getImps (_ : xs) = getImps xs getExps :: [PArg] -> [PTerm] getExps [] = [] getExps (PExp _ _ _ tm : xs) = tm : getExps xs getExps (_ : xs) = getExps xs getShowArgs :: [PArg] -> [PArg] getShowArgs [] = [] getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs getShowArgs (_ : xs) = getShowArgs xs getConsts :: [PArg] -> [PTerm] getConsts [] = [] getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs getConsts (_ : xs) = getConsts xs getAll :: [PArg] -> [PTerm] getAll = map getTm -- | Show Idris name showName :: Maybe IState -- ^^ the Idris state, for information about names and colours -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit -> PPOption -- ^^ pretty printing options -> Bool -- ^^ whether to colourise -> Name -- ^^ the term to show -> String showName ist bnd ppo colour n = case ist of Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n Nothing -> showbasic n where name = if ppopt_impl ppo then show n else showbasic n showbasic n@(UN _) = showCG n showbasic (MN i s) = str s showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n showbasic (SN s) = show s fst3 (x, _, _) = x colourise n t = let ctxt' = fmap tt_ctxt ist in case ctxt' of Nothing -> name Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name else colouriseBound t name | isDConName n ctxt -> colouriseData t name | isFnName n ctxt -> colouriseFun t name | isTConName n ctxt -> colouriseType t name -- The assumption is that if a name is not bound and does not exist in the -- global context, then we're somewhere in which implicit info has been lost -- (like error messages). Thus, unknown vars are colourised as implicits. | otherwise -> colouriseImplicit t name showTm :: IState -- ^^ the Idris state, for information about identifiers and colours -> PTerm -- ^^ the term to show -> String showTm ist = displayDecorated (consoleDecorate ist) . renderPretty 0.8 100000 . prettyImp (ppOptionIst ist) -- | Show a term with implicits, no colours showTmImpls :: PTerm -> String showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) "" instance Sized PTerm where size (PQuote rawTerm) = size rawTerm size (PRef fc name) = size name size (PLam name ty bdy) = 1 + size ty + size bdy size (PPi plicity name ty bdy) = 1 + size ty + size bdy size (PLet name ty def bdy) = 1 + size ty + size def + size bdy size (PTyped trm ty) = 1 + size trm + size ty size (PApp fc name args) = 1 + size args size (PAppBind fc name args) = 1 + size args size (PCase fc trm bdy) = 1 + size trm + size bdy size (PTrue fc _) = 1 size (PRefl fc _) = 1 size (PResolveTC fc) = 1 size (PEq fc _ _ left right) = 1 + size left + size right size (PRewrite fc left right _) = 1 + size left + size right size (PPair fc _ left right) = 1 + size left + size right size (PDPair fs _ left ty right) = 1 + size left + size ty + size right size (PAlternative a alts) = 1 + size alts size (PHidden hidden) = size hidden size (PUnifyLog tm) = size tm size (PDisamb _ tm) = size tm size (PNoImplicits tm) = size tm size PType = 1 size (PUniverse _) = 1 size (PConstant const) = 1 + size const size Placeholder = 1 size (PDoBlock dos) = 1 + size dos size (PIdiom fc term) = 1 + size term size (PReturn fc) = 1 size (PMetavar name) = 1 size (PProof tactics) = size tactics size (PElabError err) = size err size PImpossible = 1 size _ = 0 getPArity :: PTerm -> Int getPArity (PPi _ _ _ sc) = 1 + getPArity sc getPArity _ = 0 -- Return all names, free or globally bound, in the given term. allNamesIn :: PTerm -> [Name] allNamesIn tm = nub $ ni [] tm where -- TODO THINK added niTacImp, but is it right? ni env (PRef _ n) | not (n `elem` env) = [n] ni env (PPatvar _ n) = [n] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os) ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc ni env (PHidden tm) = ni env tm ni env (PEq _ _ _ l r) = ni env l ++ ni env r ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ _ l r) = ni env l ++ ni env r ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative a ls) = concatMap (ni env) ls ni env (PUnifyLog tm) = ni env tm ni env (PDisamb _ tm) = ni env tm ni env (PNoImplicits tm) = ni env tm ni env _ = [] niTacImp env (TacImp _ _ scr) = ni env scr niTacImp _ _ = [] -- Return all names defined in binders in the given term boundNamesIn :: PTerm -> [Name] boundNamesIn tm = nub $ ni tm where -- TODO THINK Added niTacImp, but is it right? ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as) ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as) ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os) ni (PLam n ty sc) = n : (ni ty ++ ni sc) ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc) ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc)) ni (PEq _ _ _ l r) = ni l ++ ni r ni (PRewrite _ l r _) = ni l ++ ni r ni (PTyped l r) = ni l ++ ni r ni (PPair _ _ l r) = ni l ++ ni r ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r ni (PAlternative a as) = concatMap (ni) as ni (PHidden tm) = ni tm ni (PUnifyLog tm) = ni tm ni (PDisamb _ tm) = ni tm ni (PNoImplicits tm) = ni tm ni _ = [] niTacImp (TacImp _ _ scr) = ni scr niTacImp _ = [] -- Return names which are valid implicits in the given term (type). implicitNamesIn :: [Name] -> IState -> PTerm -> [Name] implicitNamesIn uvars ist tm = nub $ ni [] tm where ni env (PRef _ n) | not (n `elem` env) = case lookupTy n (tt_ctxt ist) of [] -> [n] _ -> if n `elem` uvars then [n] else [] ni env (PApp _ f@(PRef _ n) as) | n `elem` uvars = ni env f ++ concatMap (ni env) (map getTm as) | otherwise = concatMap (ni env) (map getTm as) ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ -- names in 'os', not counting the names bound in the cases (nub (concatMap (ni env) (map snd os)) \\ nub (concatMap (ni env) (map fst os))) ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi p n ty sc) = ni env ty ++ ni (n:env) sc ni env (PEq _ _ _ l r) = ni env l ++ ni env r ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ _ l r) = ni env l ++ ni env r ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative a as) = concatMap (ni env) as ni env (PHidden tm) = ni env tm ni env (PUnifyLog tm) = ni env tm ni env (PDisamb _ tm) = ni env tm ni env (PNoImplicits tm) = ni env tm ni env _ = [] -- Return names which are free in the given term. namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name] namesIn uvars ist tm = nub $ ni [] tm where ni env (PRef _ n) | not (n `elem` env) = case lookupTy n (tt_ctxt ist) of [] -> [n] _ -> if n `elem` (map fst uvars) then [n] else [] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ -- names in 'os', not counting the names bound in the cases (nub (concatMap (ni env) (map snd os)) \\ nub (concatMap (ni env) (map fst os))) ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc ni env (PEq _ _ _ l r) = ni env l ++ ni env r ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ _ l r) = ni env l ++ ni env r ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative a as) = concatMap (ni env) as ni env (PHidden tm) = ni env tm ni env (PUnifyLog tm) = ni env tm ni env (PDisamb _ tm) = ni env tm ni env (PNoImplicits tm) = ni env tm ni env _ = [] niTacImp env (TacImp _ _ scr) = ni env scr niTacImp _ _ = [] -- Return which of the given names are used in the given term. usedNamesIn :: [Name] -> IState -> PTerm -> [Name] usedNamesIn vars ist tm = nub $ ni [] tm where -- TODO THINK added niTacImp, but is it right? ni env (PRef _ n) | n `elem` vars && not (n `elem` env) = case lookupDefExact n (tt_ctxt ist) of Nothing -> [n] _ -> [] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os) ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc ni env (PEq _ _ _ l r) = ni env l ++ ni env r ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ _ l r) = ni env l ++ ni env r ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative a as) = concatMap (ni env) as ni env (PHidden tm) = ni env tm ni env (PUnifyLog tm) = ni env tm ni env (PDisamb _ tm) = ni env tm ni env (PNoImplicits tm) = ni env tm ni env _ = [] niTacImp env (TacImp _ _ scr) = ni env scr niTacImp _ _ = [] -- Return the list of inaccessible (= dotted) positions for a name. getErasureInfo :: IState -> Name -> [Int] getErasureInfo ist n = case lookupCtxtExact n (idris_optimisation ist) of Just (Optimise inacc detagg) -> map fst inacc Nothing -> []
andyarvanitis/Idris-dev
src/Idris/AbsSyntaxTree.hs
bsd-3-clause
76,770
0
22
25,727
24,552
12,746
11,806
1,436
78
module DirUtils where import Prelude hiding (catch,ioError) import MUtils import List(isSuffixOf,nub) import AbstractIO import PathUtils(pathSep) optCreateDirectory d = unlessM (doesDirectoryExist d) (createDirectory d) getModificationTimeMaybe path = maybeM (getModificationTime path) {- do ifM (doesFileExist path) (Just # getModificationTime path) (return Nothing) -} -- GHC deficiency workaround: getModificationTime' path = getModificationTime path `catch` handle where handle err = if isDoesNotExistError err then fail $ "Missing: "++path else ioError err latestModTime paths = maximum # mapM getModificationTime' paths -- Remove a directory and its contents: rmR = system . unwords . ("rm -rf":) -- Expand directory names to all the Haskell files (.hs & .lhs) in that -- directory: expand fs = concat # mapM expand1 (nub fs) expand1 f = do isdir <- doesDirectoryExist f if isdir then do fs <- getDirectoryContents f return [f++[pathSep]++f'|f'<-fs,haskellSuffix f'] else return [f] haskellSuffix f = ".hs" `isSuffixOf` f || ".lhs" `isSuffixOf` f {- -- Recursively collect Haskell files from subdirectories: recurse = recurse' "" . nub recurse' path fs = concat # mapM (recurse1 path) fs recurse1 path f = do let path' = extend path f isdir <- doesDirectoryExist path' if isdir then if okDir f then do fs <- getDirectoryContents path' recurse' path' [f|f<-fs,f `notElem` [".",".."]] else return [] else if haskellSuffix f then return [path'] else return [] okDir f = f `notElem` ["objs","CVS","hi","tests","old","spec"] extend "" f = f extend "." f = f extend d f = d++"/"++f -}
forste/haReFork
tools/base/lib/DirUtils.hs
bsd-3-clause
1,721
4
14
374
303
161
142
22
2
{-# LANGUAGE ScopedTypeVariables, ImplicitParams, RecordWildCards #-} module Debug.GraphView(graphViewNew) where import Data.IORef import Data.List import Data.Maybe import Data.Tuple.Select import Data.Bits import Control.Monad import qualified Graphics.UI.Gtk as Gt import Util import Implicit import qualified Data.Graph.Inductive.Graph as G import qualified Data.Graph.Inductive.Tree as G import qualified Debug.DbgTypes as D import qualified Debug.IDE as D import GraphDraw -------------------------------------------------------------- -- Constants -------------------------------------------------------------- initLocation = (200, 50) childYOffset = 80 graphSearchStep = 30 tranAnnotStyle = GC {gcFG = (65535, 0, 0), gcLW=0, gcLS=True} stateAnnotStyle = GC {gcFG = (65535, 0, 0), gcLW=0, gcLS=True} labelStyle = GC {gcFG = (0, 0, 0), gcLW=0, gcLS=True} controllableStyle = GC {gcFG = (0 , 40000, 0), gcLW=2, gcLS=True} uncontrollableStyle = GC {gcFG = (65535, 0 , 0), gcLW=2, gcLS=True} neutralStyle = GC {gcFG = (40000, 40000, 40000), gcLW=2, gcLS=True} -- transitionStyle = GC {gcFG = (0, 40000, 0), gcLW=2, gcLS=True} subsetStyle = GC {gcFG = (40000, 40000, 40000), gcLW=1, gcLS=True} overlapStyle = GC {gcFG = (40000, 40000, 40000), gcLW=2, gcLS=False} eqStyle = GC {gcFG = (40000, 40000, 40000), gcLW=2, gcLS=True} --controllableStyle = ( GC {gcFG = (0 , 0, 40000), gcLW=2, gcLS=True} -- , GC {gcFG = (0 , 65535, 0), gcLW=0, gcLS=False}) --uncontrollableStyle = ( GC {gcFG = (0 , 0, 40000), gcLW=2, gcLS=True} -- , GC {gcFG = (65535, 0, 0), gcLW=0, gcLS=False}) defStateStyle = ( GC {gcFG = (0 , 0, 40000), gcLW=2, gcLS=True} , GC {gcFG = (40000, 40000, 40000), gcLW=0, gcLS=False}) -- show concrete nodes as smaller circles scaleConcreteNode = 0.5 -------------------------------------------------------------- -- Types -------------------------------------------------------------- data Edge a b d = EdgeTransition {eId :: Int, eTran :: D.Transition a b d} | EdgeSubset {eId :: Int} | EdgeOverlap {eId :: Int} | EdgeEq {eId :: Int} type TrGraph a b d = G.Gr (D.State a d) (Edge a b d) data GraphView c a b d = GraphView { gvModel :: D.RModel c a b d, gvGraphDraw :: RGraphDraw, gvGraph :: TrGraph a b d, gvSelectedState :: Maybe G.Node, gvSelectedTrans :: Maybe GEdgeId, gvLastEdgeId :: GEdgeId } type RGraphView c a b d = IORef (GraphView c a b d) -------------------------------------------------------------- -- View callbacks -------------------------------------------------------------- graphViewNew :: (D.Rel c v a s, D.Vals b, D.Vals d) => D.RModel c a b d -> IO (D.View a b d) graphViewNew model = do draw <- graphDrawNew ref <- newIORef $ GraphView { gvModel = model , gvGraphDraw = draw , gvGraph = G.empty , gvSelectedState = Nothing , gvSelectedTrans = Nothing , gvLastEdgeId = 0 } graphDrawSetCB draw $ graphDrawDefaultCB { onEdgeLeftClick = edgeLeftClick ref , onNodeLeftClick = nodeLeftClick ref , onNodeRightClick = nodeRightClick ref } let cb = D.ViewEvents { D.evtStateSelected = graphViewStateSelected ref , D.evtTransitionSelected = graphViewTransitionSelected ref , D.evtTRelUpdated = return () } return $ D.View { D.viewName = "Transition graph" , D.viewDefAlign = D.AlignCenter , D.viewShow = graphDrawConnect draw , D.viewHide = graphDrawDisconnect draw , D.viewGetWidget = graphDrawWidget draw , D.viewQuit = return True , D.viewCB = cb } graphViewStateSelected :: (D.Rel c v a s, D.Vals b, D.Vals d) => RGraphView c a b d -> Maybe (D.State a d) -> IO () graphViewStateSelected ref mstate = do -- If selected state is equal to one of states in the graph, highlight this state gv <- readIORef ref ctx <- D.modelCtx $ gvModel gv let ?m = ctx gv1 <- case mstate of Nothing -> setSelectedState gv Nothing Just s -> do (sid, gv') <- findOrCreateState gv Nothing s setSelectedState gv' (Just sid) gv2 <- setSelectedTrans gv1 Nothing writeIORef ref gv2 graphViewTransitionSelected :: (D.Rel c v a s, D.Vals b, D.Vals d) => RGraphView c a b d -> D.Transition a b d -> IO () graphViewTransitionSelected ref tran = do gv <- readIORef ref model <- readIORef $ gvModel gv let ?m = D.mCtx model -- Find or create from-state (fromid, gv1) <- findOrCreateState gv (gvSelectedState gv) $ D.tranFrom tran -- Find or create to-state (toid, gv2) <- findOrCreateState gv1 (Just fromid) $ D.tranTo tran -- Add transition (eid, gv3) <- findOrCreateTransition gv2 fromid toid tran gv4 <- setSelectedState gv3 Nothing gv5 <- setSelectedTrans gv4 (Just eid) writeIORef ref gv5 -------------------------------------------------------------- -- GraphDraw callbacks -------------------------------------------------------------- edgeLeftClick :: RGraphView c a b d -> (Int, Int, GEdgeId) -> IO () edgeLeftClick ref (_, _, eid) = do gv <- readIORef ref case findEdge gv eid of Just (EdgeTransition _ tran) -> D.modelSelectTransition (gvModel gv) tran _ -> return () nodeLeftClick :: RGraphView c a b d -> GNodeId -> IO () nodeLeftClick ref nid = do gv <- readIORef ref D.modelSelectState (gvModel gv) (Just $ getState gv nid) nodeRightClick :: (D.Rel c v a s, D.Vals b, D.Vals d) => RGraphView c a b d -> GNodeId -> IO () nodeRightClick ref nid = do gv <- readIORef ref let s = getState gv nid menu <- Gt.menuNew idelete <- Gt.menuItemNewWithLabel "Delete Node" _ <- Gt.on idelete Gt.menuItemActivate (deleteState ref nid) Gt.containerAdd menu idelete Gt.widgetShow idelete when (not $ D.isConcreteState s) $ do iconc <- Gt.menuItemNewWithLabel "Concretise Node" _ <- Gt.on iconc Gt.menuItemActivate (concretiseState ref nid) Gt.containerAdd menu iconc Gt.widgetShow iconc Gt.menuPopup menu Nothing -------------------------------------------------------------- -- Private functions -------------------------------------------------------------- findState :: (D.Rel c v a s, D.Vals d, ?m::c) => GraphView c a b d -> D.State a d -> Maybe G.Node findState gv s = fmap fst $ find (D.eqStates s . snd) $ G.labNodes $ gvGraph gv getState :: GraphView c a b d -> G.Node -> D.State a d getState gv nid = fromJust $ G.lab (gvGraph gv) nid findEdge :: GraphView c a b d -> GEdgeId -> Maybe (Edge a b d) findEdge gv eid = fmap sel3 $ find ((==eid) . eId . sel3) $ G.labEdges $ gvGraph gv findTransition :: (D.Rel c v a s, D.Vals b, D.Vals d, ?m::c) => GraphView c a b d -> G.Node -> G.Node -> D.Transition a b d -> Maybe GEdgeId findTransition gv fromid toid tran = fmap (\(_,_,e) -> eId e) $ find (\(fr,to,e) -> fr == fromid && to == toid && case e of EdgeTransition _ tran' -> D.eqTransitions tran' tran _ -> False) $ G.labEdges $ gvGraph gv getTransition :: GraphView c a b d -> GEdgeId -> D.Transition a b d getTransition gv eid = tran where Just (EdgeTransition _ tran) = findEdge gv eid setSelectedState :: (D.Rel c v a s, D.Vals b, ?m::c) => GraphView c a b d -> Maybe G.Node -> IO (GraphView c a b d) setSelectedState gv mid = do let gv' = gv {gvSelectedState = mid} -- Deselect previous active node case gvSelectedState gv of Nothing -> return () Just sid -> graphDrawSetNodeStyle (gvGraphDraw gv) sid $ stateStyle gv' sid -- Set new selection case mid of Nothing -> return () Just sid -> graphDrawSetNodeStyle (gvGraphDraw gv) sid $ stateStyle gv' sid return gv' setSelectedTrans :: (D.Rel c v a s, D.Vals b, ?m::c) => GraphView c a b d -> (Maybe GEdgeId) -> IO (GraphView c a b d) setSelectedTrans gv mid = do let gv' = gv {gvSelectedTrans = mid} -- Deselect previous active edge case gvSelectedTrans gv of Nothing -> return () Just eid -> do style <- transitionStyle gv' $ getTransition gv' eid graphDrawSetEdgeStyle (gvGraphDraw gv) eid style -- Set new selection case mid of Nothing -> return () Just eid -> do style <- transitionStyle gv' $ getTransition gv' eid graphDrawSetEdgeStyle (gvGraphDraw gv) eid (style {gcLW = gcLW style + 2}) return gv' findOrCreateState :: (D.Rel c v a s, D.Vals b, D.Vals d, ?m::c) => GraphView c a b d -> Maybe G.Node -> D.State a d -> IO (G.Node, GraphView c a b d) findOrCreateState gv mid s = case findState gv s of Just sid -> return (sid, gv) Nothing -> do coords <- chooseLocation gv mid createState gv coords s findOrCreateTransition :: (D.Rel c v a s, D.Vals b, D.Vals d, ?m::c) => GraphView c a b d -> G.Node -> G.Node -> D.Transition a b d -> IO (GEdgeId, GraphView c a b d) findOrCreateTransition gv fromid toid tran = do case findTransition gv fromid toid tran of Just eid -> return (eid, gv) Nothing -> createTransition gv fromid toid tran createState :: (D.Rel c v a s, D.Vals b, ?m::c) => GraphView c a b d -> (Double, Double) -> D.State a d -> IO (G.Node, GraphView c a b d) createState gv coords s = do let rel = D.sAbstract s sid = if G.order (gvGraph gv) == 0 then 0 else ((snd $ G.nodeRange (gvGraph gv)) + 1) gv' = gv {gvGraph = G.insNode (sid, s) (gvGraph gv)} (eqsets, other0) = partition ((.== rel) . D.sAbstract . getState gv) (G.nodes $ gvGraph gv) (subsets, other1) = partition ((.== t) . (.-> rel) . D.sAbstract . getState gv) other0 (supersets, other2) = partition ((.== t) . (rel .->) . D.sAbstract . getState gv) other1 overlaps = filter ((./= b) . (.& rel) . D.sAbstract . getState gv) other2 rscale = if isNothing (D.sConcrete s) then 1.0 else scaleConcreteNode (ls, as) = stateStyle gv' sid annots <- stateAnnots gv' rel graphDrawInsertNode (gvGraphDraw gv') sid annots coords rscale (ls, as) gv0 <- foldM (\_gv sid' -> (liftM snd) $ createEqEdge _gv sid sid') gv' eqsets gv1 <- foldM (\_gv sid' -> (liftM snd) $ createSubsetEdge _gv sid' sid) gv0 subsets gv2 <- foldM (\_gv sid' -> (liftM snd) $ createSubsetEdge _gv sid sid') gv1 supersets gv3 <- foldM (\_gv sid' -> (liftM snd) $ createOverlapEdge _gv sid sid') gv2 overlaps return (sid, gv3) deleteState :: RGraphView c a b d -> G.Node -> IO () deleteState ref nid = do gv <- readIORef ref graphDrawDeleteNode (gvGraphDraw gv) nid writeIORef ref $ gv {gvGraph = G.delNode nid (gvGraph gv)} case gvSelectedTrans gv of Nothing -> return () Just eid -> do gv' <- readIORef ref when (isNothing $ findEdge gv' eid) $ writeIORef ref $ gv' {gvSelectedTrans = Nothing} if Just nid == gvSelectedState gv then do modifyIORef ref $ \gv' -> gv' {gvSelectedState = Nothing} D.modelSelectState (gvModel gv) Nothing else return () concretiseState :: (D.Rel c v a s, D.Vals b, D.Vals d) => RGraphView c a b d -> G.Node -> IO () concretiseState ref nid = do gv <- readIORef ref ctx <- D.modelCtx $ gvModel gv let ?m = ctx let s = getState gv nid ms' <- D.modelConcretiseState (gvModel gv) (D.sAbstract s) case ms' of Nothing -> D.showMessage (gvModel gv) Gt.MessageError "Could not find concrete representative of the abstract state" Just s' -> do (nid', gv') <- findOrCreateState gv (Just nid) s' writeIORef ref gv' D.modelSelectState (gvModel gv') (Just $ getState gv' nid') createTransition :: (D.Rel c v a s, D.Vals b, ?m::c) => GraphView c a b d -> G.Node -> G.Node -> D.Transition a b d -> IO (GEdgeId, GraphView c a b d) createTransition gv fromid toid tran = do annots <- transitionAnnots gv tran style <- transitionStyle gv tran createEdge gv fromid toid (\eid -> EdgeTransition {eId = eid, eTran = tran}) annots style EndArrow True createSubsetEdge :: GraphView c a b d -> G.Node -> G.Node -> IO (GEdgeId, GraphView c a b d) createSubsetEdge gv fromid toid = createEdge gv fromid toid EdgeSubset [] subsetStyle EndDiamond False createEqEdge :: GraphView c a b d -> G.Node -> G.Node -> IO (GEdgeId, GraphView c a b d) createEqEdge gv fromid toid = createEdge gv fromid toid EdgeEq [] eqStyle EndNone False createOverlapEdge :: GraphView c a b d -> G.Node -> G.Node -> IO (GEdgeId, GraphView c a b d) createOverlapEdge gv fromid toid = createEdge gv fromid toid EdgeOverlap [] overlapStyle EndNone False createEdge :: GraphView c a b d -> G.Node -> G.Node -> (GEdgeId -> Edge a b d) -> [GAnnotation] -> GC -> EndStyle -> Bool -> IO (GEdgeId, GraphView c a b d) createEdge gv fromid toid f annots gc end visible = do let eid = gvLastEdgeId gv + 1 e = f eid gv' = gv { gvGraph = G.insEdge (fromid, toid, e) (gvGraph gv) , gvLastEdgeId = eid} graphDrawInsertEdge (gvGraphDraw gv') fromid toid eid annots gc end visible return (eid, gv') chooseLocation :: GraphView c a b d -> Maybe G.Node -> IO (Double, Double) chooseLocation gv Nothing = chooseLocationFrom gv initLocation chooseLocation gv (Just sid) = do (parentx, parenty) <- graphDrawGetNodeCoords (gvGraphDraw gv) sid chooseLocationFrom gv (parentx, parenty + childYOffset) -- Find unoccupied location next to given coordinates chooseLocationFrom :: GraphView c a b d -> (Double, Double) -> IO (Double, Double) chooseLocationFrom gv (x,y) = do ids <- graphDrawGetNodesAtLocation (gvGraphDraw gv) (x,y) case ids of [] -> return (x,y) _ -> chooseLocationFrom gv (x,y+graphSearchStep) stateStyle :: (D.Rel c v a s, D.Vals b, ?m::c) => GraphView c a b d -> G.Node -> (GC, GC) stateStyle gv sid = if Just sid == gvSelectedState gv then (ls{gcLW = gcLW ls + 1}, as{gcFG = map3 ((`shiftR` 1),(`shiftR` 1),(`shiftR` 1)) $ gcFG as}) else (ls,as) where (ls, as) = defStateStyle stateAnnots :: (D.Rel c v a s, ?m::c) => GraphView c a b d -> a -> IO [GAnnotation] stateAnnots gv srel = do staterels <- D.modelStateRels (gvModel gv) let supersets = map fst $ filter (\(_,r) -> (srel .-> r) .== t) staterels return $ map (\n -> GAnnotation n AnnotRight stateAnnotStyle) supersets transitionStyle :: (D.Rel c v a s, D.Vals b, ?m::c) => GraphView c a b d -> D.Transition a b d -> IO GC transitionStyle gv tran = do model <- readIORef $ gvModel gv cat <- D.transitionCategory model tran return $ case cat of D.TranControllable -> controllableStyle D.TranUncontrollable -> uncontrollableStyle _ -> neutralStyle transitionAnnots :: (D.Rel c v a s, ?m::c) => GraphView c a b d -> D.Transition a b d -> IO [GAnnotation] transitionAnnots gv tran = do model <- readIORef $ gvModel gv let tranrels = D.mTransRels model relnames = map sel1 $ filter (\(_,_,r) -> (D.tranRel model tran .& r) ./= b) tranrels labstr <- case D.tranSrc tran of Nothing -> transitionLabel (gvModel gv) (D.tranAbstractLabel tran) Just str -> return str return $ GAnnotation labstr AnnotRight labelStyle : map (\n -> GAnnotation n AnnotLeft tranAnnotStyle) relnames transitionLabel :: (D.Rel c v a s, ?m::c) => D.RModel c a b d -> a -> IO String transitionLabel rmodel rel = do lvars <- D.modelLabelVars rmodel let vals = maybe [] (map (\(v,i) -> (v, D.valStrFromInt (D.mvarType v) i))) (D.oneSatVal rel lvars) return $ intercalate "," $ map (\(var,val) -> D.mvarName var ++ "=" ++ val) vals
termite2/debug
Debug/GraphView.hs
bsd-3-clause
16,900
0
19
4,882
6,081
3,127
2,954
275
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} -- | This module defines a collection of simplification rules, as per -- "Futhark.Optimise.Simplifier.Rule". They are used in the -- simplifier. module Futhark.Optimise.Simplifier.Rules ( standardRules , IndexResult (..) ) where import Control.Applicative import Control.Monad import Data.Either import Data.Foldable (all) import Data.List hiding (all) import Data.Maybe import Data.Monoid import qualified Data.HashMap.Lazy as HM import qualified Data.HashSet as HS import qualified Futhark.Analysis.SymbolTable as ST import qualified Futhark.Analysis.UsageTable as UT import Futhark.Analysis.DataDependencies import Futhark.Optimise.Simplifier.ClosedForm import Futhark.Optimise.Simplifier.Rule import Futhark.Optimise.Simplifier.RuleM import qualified Futhark.Analysis.AlgSimplify as AS import qualified Futhark.Analysis.ScalExp as SE import Futhark.Representation.AST import Futhark.Construct import Futhark.Transform.Substitute import Futhark.Util import Prelude hiding (all) topDownRules :: (MonadBinder m, LocalScope (Lore m) m) => TopDownRules m topDownRules = [ hoistLoopInvariantMergeVariables , simplifyClosedFormLoop , simplifKnownIterationLoop , simplifyRearrange , simplifyRotate , letRule simplifyBinOp , letRule simplifyCmpOp , letRule simplifyUnOp , letRule simplifyConvOp , letRule simplifyAssert , letRule copyScratchToScratch , simplifyIndexIntoReshape , removeEmptySplits , removeSingletonSplits , simplifyConcat , evaluateBranch , simplifyBoolBranch , hoistBranchInvariant , simplifyScalExp , letRule simplifyIdentityReshape , letRule simplifyReshapeReshape , letRule simplifyReshapeScratch , letRule improveReshape , removeScratchValue , hackilySimplifyBranch , removeIdentityInPlace , simplifyBranchContext , simplifyBranchResultComparison ] bottomUpRules :: MonadBinder m => BottomUpRules m bottomUpRules = [ removeRedundantMergeVariables , removeDeadBranchResult , simplifyReplicate , simplifyIndex ] standardRules :: (MonadBinder m, LocalScope (Lore m) m) => RuleBook m standardRules = (topDownRules, bottomUpRules) -- This next one is tricky - it's easy enough to determine that some -- loop result is not used after the loop, but here, we must also make -- sure that it does not affect any other values. -- -- I do not claim that the current implementation of this rule is -- perfect, but it should suffice for many cases, and should never -- generate wrong code. removeRedundantMergeVariables :: MonadBinder m => BottomUpRule m removeRedundantMergeVariables (_, used) (Let pat _ (DoLoop ctx val form body)) | not $ all (explicitlyReturned . fst) val = let (ctx_es, val_es) = splitAt (length ctx) $ bodyResult body necessaryForReturned = findNecessaryForReturned explicitlyReturnedOrInForm (zip (map fst $ ctx++val) $ ctx_es++val_es) (dataDependencies body) resIsNecessary ((v,_), _) = explicitlyReturned v || paramName v `HS.member` necessaryForReturned || referencedInPat v || referencedInForm v (keep_ctx, discard_ctx) = partition resIsNecessary $ zip ctx ctx_es (keep_valpart, discard_valpart) = partition (resIsNecessary . snd) $ zip (patternValueElements pat) $ zip val val_es (keep_valpatelems, keep_val) = unzip keep_valpart (_discard_valpatelems, discard_val) = unzip discard_valpart (ctx', ctx_es') = unzip keep_ctx (val', val_es') = unzip keep_val body' = body { bodyResult = ctx_es' ++ val_es' } free_in_keeps = freeIn keep_valpatelems stillUsedContext pat_elem = patElemName pat_elem `HS.member` (free_in_keeps <> freeIn (filter (/=pat_elem) $ patternContextElements pat)) pat' = pat { patternValueElements = keep_valpatelems , patternContextElements = filter stillUsedContext $ patternContextElements pat } in if ctx' ++ val' == ctx ++ val then cannotSimplify else do -- We can't just remove the bindings in 'discard', since the loop -- body may still use their names in (now-dead) expressions. -- Hence, we add them inside the loop, fully aware that dead-code -- removal will eventually get rid of them. Some care is -- necessary to handle unique bindings. body'' <- insertBindingsM $ do mapM_ (uncurry letBindNames') $ dummyBindings discard_ctx mapM_ (uncurry letBindNames') $ dummyBindings discard_val return body' letBind_ pat' $ DoLoop ctx' val' form body'' where pat_used = map (`UT.used` used) $ patternValueNames pat used_vals = map fst $ filter snd $ zip (map (paramName . fst) val) pat_used explicitlyReturned = flip elem used_vals . paramName explicitlyReturnedOrInForm p = explicitlyReturned p || paramName p `HS.member` freeIn form patAnnotNames = freeIn $ map fst $ ctx++val referencedInPat = (`HS.member` patAnnotNames) . paramName referencedInForm = (`HS.member` freeIn form) . paramName dummyBindings = map dummyBinding dummyBinding ((p,e), _) | unique (paramDeclType p), Var v <- e = ([paramName p], PrimOp $ Copy v) | otherwise = ([paramName p], PrimOp $ SubExp e) removeRedundantMergeVariables _ _ = cannotSimplify findNecessaryForReturned :: (Param attr -> Bool) -> [(Param attr, SubExp)] -> HM.HashMap VName Names -> Names findNecessaryForReturned explicitlyReturned merge_and_res allDependencies = iterateNecessary mempty where iterateNecessary prev_necessary | necessary == prev_necessary = necessary | otherwise = iterateNecessary necessary where necessary = mconcat $ map dependencies returnedResultSubExps explicitlyReturnedOrNecessary param = explicitlyReturned param || paramName param `HS.member` prev_necessary returnedResultSubExps = map snd $ filter (explicitlyReturnedOrNecessary . fst) merge_and_res dependencies (Constant _) = HS.empty dependencies (Var v) = HM.lookupDefault (HS.singleton v) v allDependencies -- We may change the type of the loop if we hoist out a shape -- annotation, in which case we also need to tweak the bound pattern. hoistLoopInvariantMergeVariables :: forall m.MonadBinder m => TopDownRule m hoistLoopInvariantMergeVariables _ (Let pat _ (DoLoop ctx val form loopbody)) = -- Figure out which of the elements of loopresult are -- loop-invariant, and hoist them out. case foldr checkInvariance ([], explpat, [], []) $ zip merge res of ([], _, _, _) -> -- Nothing is invariant. cannotSimplify (invariant, explpat', merge', res') -> do -- We have moved something invariant out of the loop. let loopbody' = loopbody { bodyResult = res' } invariantShape :: (a, VName) -> Bool invariantShape (_, shapemerge) = shapemerge `elem` map (paramName . fst) merge' (implpat',implinvariant) = partition invariantShape implpat implinvariant' = [ (patElemIdent p, Var v) | (p,v) <- implinvariant ] implpat'' = map fst implpat' explpat'' = map fst explpat' (ctx', val') = splitAt (length implpat') merge' forM_ (invariant ++ implinvariant') $ \(v1,v2) -> letBindNames'_ [identName v1] $ PrimOp $ SubExp v2 letBind_ (Pattern implpat'' explpat'') $ DoLoop ctx' val' form loopbody' where merge = ctx ++ val res = bodyResult loopbody implpat = zip (patternContextElements pat) $ map paramName $ loopResultContext (map fst ctx) (map fst val) explpat = zip (patternValueElements pat) $ map (paramName . fst) val namesOfMergeParams = HS.fromList $ map (paramName . fst) $ ctx++val removeFromResult (mergeParam,mergeInit) explpat' = case partition ((==paramName mergeParam) . snd) explpat' of ([(patelem,_)], rest) -> (Just (patElemIdent patelem, mergeInit), rest) (_, _) -> (Nothing, explpat') checkInvariance ((mergeParam,mergeInit), resExp) (invariant, explpat', merge', resExps) | not (unique (paramDeclType mergeParam)) || arrayRank (paramDeclType mergeParam) == 1, isInvariant resExp = let (bnd, explpat'') = removeFromResult (mergeParam,mergeInit) explpat' in (maybe id (:) bnd $ (paramIdent mergeParam, mergeInit) : invariant, explpat'', merge', resExps) where -- A non-unique merge variable is invariant if the corresponding -- subexp in the result is EITHER: -- -- (0) a variable of the same name as the parameter, where -- all existential parameters are already known to be -- invariant isInvariant (Var v2) | paramName mergeParam == v2 = allExistentialInvariant (HS.fromList $ map (identName . fst) invariant) mergeParam -- (1) or identical to the initial value of the parameter. isInvariant _ = mergeInit == resExp checkInvariance ((mergeParam,mergeInit), resExp) (invariant, explpat', merge', resExps) = (invariant, explpat', (mergeParam,mergeInit):merge', resExp:resExps) allExistentialInvariant namesOfInvariant mergeParam = all (invariantOrNotMergeParam namesOfInvariant) (paramName mergeParam `HS.delete` freeIn mergeParam) invariantOrNotMergeParam namesOfInvariant name = not (name `HS.member` namesOfMergeParams) || name `HS.member` namesOfInvariant hoistLoopInvariantMergeVariables _ _ = cannotSimplify -- | A function that, given a variable name, returns its definition. type VarLookup lore = VName -> Maybe (Exp lore) -- | A function that, given a subexpression, returns its type. type TypeLookup = SubExp -> Maybe Type type LetTopDownRule lore u = VarLookup lore -> TypeLookup -> PrimOp lore -> Maybe (PrimOp lore) letRule :: MonadBinder m => LetTopDownRule (Lore m) u -> TopDownRule m letRule rule vtable (Let pat _ (PrimOp op)) = letBind_ pat =<< liftMaybe (PrimOp <$> rule defOf seType op) where defOf = (`ST.lookupExp` vtable) seType (Var v) = ST.lookupType v vtable seType (Constant v) = Just $ Prim $ primValueType v letRule _ _ _ = cannotSimplify simplifyClosedFormLoop :: MonadBinder m => TopDownRule m simplifyClosedFormLoop _ (Let pat _ (DoLoop [] val (ForLoop i bound) body)) = loopClosedForm pat val (HS.singleton i) bound body simplifyClosedFormLoop _ _ = cannotSimplify simplifKnownIterationLoop :: forall m.MonadBinder m => TopDownRule m simplifKnownIterationLoop _ (Let pat _ (DoLoop ctx val (ForLoop i (Constant (IntValue (Int32Value 1)))) body)) = do forM_ (ctx++val) $ \(mergevar, mergeinit) -> letBindNames' [paramName mergevar] $ PrimOp $ SubExp mergeinit letBindNames'_ [i] $ PrimOp $ SubExp $ constant (0 :: Int32) (loop_body_ctx, loop_body_val) <- splitAt (length ctx) <$> (mapM asVar =<< bodyBind body) let subst = HM.fromList $ zip (map (paramName . fst) ctx) loop_body_ctx ctx_params = substituteNames subst $ map fst ctx val_params = substituteNames subst $ map fst val res_context = loopResultContext ctx_params val_params forM_ (zip (patternContextElements pat) res_context) $ \(pat_elem, p) -> letBind_ (Pattern [] [pat_elem]) $ PrimOp $ SubExp $ Var $ paramName p forM_ (zip (patternValueElements pat) loop_body_val) $ \(pat_elem, v) -> letBind_ (Pattern [] [pat_elem]) $ PrimOp $ SubExp $ Var v where asVar (Var v) = return v asVar (Constant v) = letExp "named" $ PrimOp $ SubExp $ Constant v simplifKnownIterationLoop _ _ = cannotSimplify simplifyRearrange :: MonadBinder m => TopDownRule m -- Handle identity permutation. simplifyRearrange _ (Let pat _ (PrimOp (Rearrange _ perm v))) | sort perm == perm = letBind_ pat $ PrimOp $ SubExp $ Var v simplifyRearrange vtable (Let pat _ (PrimOp (Rearrange cs perm v))) | Just (Rearrange cs2 perm2 e) <- asPrimOp =<< ST.lookupExp v vtable = -- Rearranging a rearranging: compose the permutations. letBind_ pat $ PrimOp $ Rearrange (cs++cs2) (perm `rearrangeCompose` perm2) e simplifyRearrange vtable (Let pat _ (PrimOp (Rearrange cs perm v))) | Just (Rotate cs2 offsets v2) <- asPrimOp =<< ST.lookupExp v vtable, Just (Rearrange cs3 perm3 v3) <- asPrimOp =<< ST.lookupExp v2 vtable = do let offsets' = rearrangeShape (rearrangeInverse perm3) offsets rearrange_rotate <- letExp "rearrange_rotate" $ PrimOp $ Rotate cs2 offsets' v3 letBind_ pat $ PrimOp $ Rearrange (cs++cs3) (perm `rearrangeCompose` perm3) rearrange_rotate simplifyRearrange vtable (Let pat _ (PrimOp (Rearrange cs1 perm1 v1))) | Just (to_drop, to_take, cs2, 0, v2) <- isDropTake v1 vtable, Just (Rearrange cs3 perm3 v3) <- asPrimOp =<< ST.lookupExp v2 vtable, dim1:_ <- perm1, perm1 == rearrangeInverse perm3 = do to_drop' <- letSubExp "drop" =<< SE.fromScalExp to_drop to_take' <- letSubExp "take" =<< SE.fromScalExp to_take [_, v] <- letTupExp' "simplify_rearrange" $ PrimOp $ Split (cs1<>cs2<>cs3) dim1 [to_drop', to_take'] v3 letBind_ pat $ PrimOp $ SubExp v simplifyRearrange _ _ = cannotSimplify isDropTake :: VName -> ST.SymbolTable lore -> Maybe (SE.ScalExp, SE.ScalExp, Certificates, Int, VName) isDropTake v vtable = do Let pat _ (PrimOp (Split cs dim splits v')) <- ST.entryBinding =<< ST.lookup v vtable i <- elemIndex v $ patternValueNames pat return (prod $ take i splits, prod $ take 1 $ drop i splits, cs, dim, v') where prod = product . map SE.intSubExpToScalExp simplifyRotate :: MonadBinder m => TopDownRule m -- A zero-rotation is identity. simplifyRotate _ (Let pat _ (PrimOp (Rotate _ offsets v))) | all (==constant (0::Int32)) offsets = letBind_ pat $ PrimOp $ SubExp $ Var v simplifyRotate vtable (Let pat _ (PrimOp (Rotate cs offsets v))) | Just (Rearrange cs2 perm v2) <- asPrimOp =<< ST.lookupExp v vtable, Just (Rotate cs3 offsets2 v3) <- asPrimOp =<< ST.lookupExp v2 vtable = do let offsets2' = rearrangeShape (rearrangeInverse perm) offsets2 addOffsets x y = letSubExp "summed_offset" $ PrimOp $ BinOp (Add Int32) x y offsets' <- zipWithM addOffsets offsets offsets2' rotate_rearrange <- letExp "rotate_rearrange" $ PrimOp $ Rearrange cs2 perm v3 letBind_ pat $ PrimOp $ Rotate (cs++cs3) offsets' rotate_rearrange simplifyRotate _ _ = cannotSimplify simplifyReplicate :: MonadBinder m => BottomUpRule m simplifyReplicate (vtable, used) (Let pat _ (PrimOp (Replicate (Constant n) (Var v)))) | oneIsh n, not $ any (`UT.isConsumed` used) $ v : patternNames pat, Just shape <- arrayDims <$> ST.lookupType v vtable, not $ null shape = letBind_ pat $ PrimOp $ Reshape [] (map DimNew $ constant (1::Int32) : shape) v simplifyReplicate _ _ = cannotSimplify simplifyCmpOp :: LetTopDownRule lore u simplifyCmpOp _ _ (CmpOp cmp e1 e2) | e1 == e2 = binOpRes $ BoolValue $ case cmp of CmpEq{} -> True CmpSlt{} -> False CmpUlt{} -> False CmpSle{} -> True CmpUle{} -> True FCmpLt{} -> False FCmpLe{} -> True simplifyCmpOp _ _ (CmpOp cmp (Constant v1) (Constant v2)) = binOpRes =<< BoolValue <$> doCmpOp cmp v1 v2 simplifyCmpOp _ _ _ = Nothing simplifyBinOp :: LetTopDownRule lore u simplifyBinOp _ _ (BinOp op (Constant v1) (Constant v2)) | Just res <- doBinOp op v1 v2 = return $ SubExp $ Constant res simplifyBinOp _ _ (BinOp Add{} e1 e2) | isCt0 e1 = Just $ SubExp e2 | isCt0 e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp FAdd{} e1 e2) | isCt0 e1 = Just $ SubExp e2 | isCt0 e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp Sub{} e1 e2) | isCt0 e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp FSub{} e1 e2) | isCt0 e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp Mul{} e1 e2) | isCt0 e1 = Just $ SubExp e1 | isCt0 e2 = Just $ SubExp e2 | isCt1 e1 = Just $ SubExp e2 | isCt1 e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp FMul{} e1 e2) | isCt0 e1 = Just $ SubExp e1 | isCt0 e2 = Just $ SubExp e2 | isCt1 e1 = Just $ SubExp e2 | isCt1 e2 = Just $ SubExp e1 simplifyBinOp look _ (BinOp (SMod t) e1 e2) | isCt1 e2 = Just $ SubExp e1 | e1 == e2 = binOpRes $ IntValue $ intValue t (1 :: Int) | Var v1 <- e1, Just (PrimOp (BinOp SMod{} e3 e4)) <- look v1, e4 == e2 = Just $ SubExp e3 simplifyBinOp _ _ (BinOp SDiv{} e1 e2) | isCt0 e1 = Just $ SubExp e1 | isCt1 e2 = Just $ SubExp e1 | isCt0 e2 = Nothing simplifyBinOp _ _ (BinOp (SRem t) e1 e2) | isCt0 e2 = Just $ SubExp e1 | e1 == e2 = binOpRes $ IntValue $ intValue t (1 :: Int) simplifyBinOp _ _ (BinOp SQuot{} e1 e2) | isCt0 e1 = Just $ SubExp e1 | isCt1 e2 = Just $ SubExp e1 | isCt0 e2 = Nothing simplifyBinOp _ _ (BinOp (FPow t) e1 e2) | isCt0 e2 = Just $ SubExp $ floatConst t 1 | isCt0 e1 || isCt1 e1 || isCt1 e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp (Shl t) e1 e2) | isCt0 e2 = Just $ SubExp e1 | isCt0 e1 = Just $ SubExp $ intConst t 0 simplifyBinOp _ _ (BinOp AShr{} e1 e2) | isCt0 e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp (And t) e1 e2) | isCt0 e1 = Just $ SubExp $ intConst t 0 | isCt0 e2 = Just $ SubExp $ intConst t 0 | e1 == e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp Or{} e1 e2) | isCt0 e1 = Just $ SubExp e2 | isCt0 e2 = Just $ SubExp e1 | e1 == e2 = Just $ SubExp e1 simplifyBinOp _ _ (BinOp (Xor t) e1 e2) | isCt0 e1 = Just $ SubExp e2 | isCt0 e2 = Just $ SubExp e1 | e1 == e2 = Just $ SubExp $ intConst t 0 simplifyBinOp defOf _ (BinOp LogAnd e1 e2) | isCt0 e1 = Just $ SubExp $ Constant $ BoolValue False | isCt0 e2 = Just $ SubExp $ Constant $ BoolValue False | isCt1 e1 = Just $ SubExp e2 | isCt1 e2 = Just $ SubExp e1 | Var v <- e1, Just (UnOp Not e1') <- asPrimOp =<< defOf v, e1' == e2 = binOpRes $ BoolValue False | Var v <- e2, Just (UnOp Not e2') <- asPrimOp =<< defOf v, e2' == e1 = binOpRes $ BoolValue False simplifyBinOp defOf _ (BinOp LogOr e1 e2) | isCt0 e1 = Just $ SubExp e2 | isCt0 e2 = Just $ SubExp e1 | isCt1 e1 = Just $ SubExp $ Constant $ BoolValue True | isCt1 e2 = Just $ SubExp $ Constant $ BoolValue True | Var v <- e1, Just (UnOp Not e1') <- asPrimOp =<< defOf v, e1' == e2 = binOpRes $ BoolValue True | Var v <- e2, Just (UnOp Not e2') <- asPrimOp =<< defOf v, e2' == e1 = binOpRes $ BoolValue True simplifyBinOp _ _ _ = Nothing binOpRes :: PrimValue -> Maybe (PrimOp lore) binOpRes = Just . SubExp . Constant simplifyUnOp :: LetTopDownRule lore u simplifyUnOp _ _ (UnOp op (Constant v)) = binOpRes =<< doUnOp op v simplifyUnOp defOf _ (UnOp Not (Var v)) | Just (PrimOp (UnOp Not v2)) <- defOf v = Just $ SubExp v2 simplifyUnOp _ _ _ = Nothing simplifyConvOp :: LetTopDownRule lore u simplifyConvOp _ _ (ConvOp op (Constant v)) = binOpRes =<< doConvOp op v simplifyConvOp _ _ (ConvOp op se) | (from, to) <- convTypes op, from == to = Just $ SubExp se simplifyConvOp _ _ _ = Nothing -- If expression is true then just replace assertion. simplifyAssert :: LetTopDownRule lore u simplifyAssert _ _ (Assert (Constant (BoolValue True)) _) = Just $ SubExp $ Constant Checked simplifyAssert _ _ _ = Nothing simplifyIndex :: MonadBinder m => BottomUpRule m simplifyIndex (vtable, used) (Let pat@(Pattern [] [pe]) _ (PrimOp (Index cs idd inds))) | Just m <- simplifyIndexing vtable seType idd inds consumed = do res <- m case res of SubExpResult se -> letBind_ pat $ PrimOp $ SubExp se IndexResult extra_cs idd' inds' -> letBind_ pat $ PrimOp $ Index (cs++extra_cs) idd' inds' where consumed = patElemName pe `UT.isConsumed` used seType (Var v) = ST.lookupType v vtable seType (Constant v) = Just $ Prim $ primValueType v simplifyIndex _ _ = cannotSimplify data IndexResult = IndexResult Certificates VName [SubExp] | SubExpResult SubExp simplifyIndexing :: MonadBinder m => ST.SymbolTable lore -> TypeLookup -> VName -> [SubExp] -> Bool -> Maybe (m IndexResult) simplifyIndexing vtable seType idd inds consuming = case asPrimOp =<< defOf idd of Nothing -> Nothing Just (SubExp (Var v)) -> Just $ pure $ IndexResult [] v inds Just (Iota _ (Constant (IntValue (Int32Value 0))) (Constant (IntValue (Int32Value 1)))) | [ii] <- inds -> Just $ pure $ SubExpResult ii Just (Iota _ x s) | [ii] <- inds -> Just $ fmap SubExpResult $ letSubExp "index_iota" <=< SE.fromScalExp $ SE.intSubExpToScalExp ii * SE.intSubExpToScalExp s + SE.intSubExpToScalExp x Just (Rotate cs offsets a) | length offsets == length inds -> Just $ do dims <- arrayDims <$> lookupType a let adjust (i, o, d) = do i_m_o <- letSubExp "i_p_o" $ PrimOp $ BinOp (Add Int32) i o letSubExp "rot_i" $ PrimOp $ BinOp (SMod Int32) i_m_o d inds' <- mapM adjust $ zip3 inds offsets dims pure $ IndexResult cs a inds' Just (Index cs aa ais) -> Just $ pure $ IndexResult cs aa (ais ++ inds) Just (Replicate _ (Var vv)) | [_] <- inds, not consuming -> Just $ pure $ SubExpResult $ Var vv | _:is' <- inds, not consuming -> Just $ pure $ IndexResult [] vv is' Just (Replicate _ val@(Constant _)) | [_] <- inds, not consuming -> Just $ pure $ SubExpResult val Just (Rearrange cs perm src) | rearrangeReach perm <= length inds -> let inds' = rearrangeShape (take (length inds) $ rearrangeInverse perm) inds in Just $ pure $ IndexResult cs src inds' Just (Copy src) -- We cannot just remove a copy of a rearrange, because it might -- be important for coalescing. | Just (PrimOp Rearrange{}) <- defOf src -> Nothing | Just dims <- arrayDims <$> seType (Var src), length inds == length dims, not consuming -> Just $ pure $ IndexResult [] src inds Just (Reshape cs newshape src) | Just newdims <- shapeCoercion newshape, Just olddims <- arrayDims <$> seType (Var src), changed_dims <- zipWith (/=) newdims olddims, not $ or $ drop (length inds) changed_dims -> Just $ pure $ IndexResult cs src inds | Just newdims <- shapeCoercion newshape, Just olddims <- arrayDims <$> seType (Var src), length newshape == length inds, length olddims == length newdims -> Just $ pure $ IndexResult cs src inds Just (Reshape cs [_] v2) | Just [_] <- arrayDims <$> seType (Var v2) -> Just $ pure $ IndexResult cs v2 inds Just (Concat cs d x xs _) | Just (ibef, i, iaft) <- focusNth d inds -> Just $ do res_t <- stripArray (length inds) <$> lookupType x x_len <- arraySize d <$> lookupType x xs_lens <- mapM (fmap (arraySize d) . lookupType) xs let add n m = do added <- letSubExp "index_concat_add" $ PrimOp $ BinOp (Add Int32) n m return (added, n) (_, starts) <- mapAccumLM add x_len xs_lens let xs_and_starts = zip (reverse xs) starts let mkBranch [] = letSubExp "index_concat" $ PrimOp $ Index cs x (ibef++i:iaft) mkBranch ((x', start):xs_and_starts') = do cmp <- letSubExp "index_concat_cmp" $ PrimOp $ CmpOp (CmpSle Int32) start i (thisres, thisbnds) <- collectBindings $ do i' <- letSubExp "index_concat_i" $ PrimOp $ BinOp (Sub Int32) i start letSubExp "index_concat" $ PrimOp $ Index cs x' (ibef++i':iaft) thisbody <- mkBodyM thisbnds [thisres] (altres, altbnds) <- collectBindings $ mkBranch xs_and_starts' altbody <- mkBodyM altbnds [altres] letSubExp "index_concat_branch" $ If cmp thisbody altbody $ staticShapes [res_t] SubExpResult <$> mkBranch xs_and_starts Just (ArrayLit ses _) | Constant (IntValue (Int32Value i)) : inds' <- inds, Just se <- maybeNth i ses -> case inds' of [] -> Just $ pure $ SubExpResult se _ | Var v2 <- se -> Just $ pure $ IndexResult [] v2 inds' _ -> Nothing _ -> case ST.entryBinding =<< ST.lookup idd vtable of Just (Let split_pat _ (PrimOp (Split cs2 0 ns idd2))) | first_index : rest_indices <- inds -> Just $ do -- Figure out the extra offset that we should add to the first index. let plus = eBinOp (Add Int32) esum [] = return $ PrimOp $ SubExp $ constant (0 :: Int32) esum (x:xs) = foldl plus x xs patElem_and_offset <- zip (patternValueElements split_pat) <$> mapM esum (inits $ map eSubExp ns) case find ((==idd) . patElemName . fst) patElem_and_offset of Nothing -> fail "simplifyIndexing: could not find pattern element." Just (_, offset_e) -> do offset <- letSubExp "offset" offset_e offset_index <- letSubExp "offset_index" $ PrimOp $ BinOp (Add Int32) first_index offset return $ IndexResult cs2 idd2 (offset_index:rest_indices) _ -> Nothing where defOf = (`ST.lookupExp` vtable) simplifyIndexIntoReshape :: MonadBinder m => TopDownRule m simplifyIndexIntoReshape vtable (Let pat _ (PrimOp (Index cs idd inds))) | Just (Reshape cs2 newshape idd2) <- asPrimOp =<< ST.lookupExp idd vtable, length newshape == length inds = case shapeCoercion newshape of Just _ -> letBind_ pat $ PrimOp $ Index (cs++cs2) idd2 inds Nothing -> do -- Linearise indices and map to old index space. oldshape <- arrayDims <$> lookupType idd2 let new_inds = reshapeIndex (map SE.intSubExpToScalExp oldshape) (map SE.intSubExpToScalExp $ newDims newshape) (map SE.intSubExpToScalExp inds) new_inds' <- mapM (letSubExp "new_index" <=< SE.fromScalExp) new_inds letBind_ pat $ PrimOp $ Index (cs++cs2) idd2 new_inds' simplifyIndexIntoReshape _ _ = cannotSimplify removeEmptySplits :: MonadBinder m => TopDownRule m removeEmptySplits _ (Let pat _ (PrimOp (Split cs i ns arr))) | (pointless,sane) <- partition (isCt0 . snd) $ zip (patternValueElements pat) ns, not (null pointless) = do rt <- rowType <$> lookupType arr letBind_ (Pattern [] $ map fst sane) $ PrimOp $ Split cs i (map snd sane) arr forM_ pointless $ \(patElem,_) -> letBindNames' [patElemName patElem] $ PrimOp $ ArrayLit [] rt removeEmptySplits _ _ = cannotSimplify removeSingletonSplits :: MonadBinder m => TopDownRule m removeSingletonSplits _ (Let pat _ (PrimOp (Split _ _ [n] arr))) = do size <- arraySize 0 <$> lookupType arr if size == n then letBind_ pat $ PrimOp $ SubExp $ Var arr else cannotSimplify removeSingletonSplits _ _ = cannotSimplify simplifyConcat :: MonadBinder m => TopDownRule m -- concat@1(transpose(x),transpose(y)) == transpose(concat@0(x,y)) simplifyConcat vtable (Let pat _ (PrimOp (Concat cs i x xs new_d))) | Just r <- arrayRank <$> ST.lookupType x vtable, let perm = [i] ++ [0..i-1] ++ [i+1..r-1], Just (x',x_cs) <- transposedBy perm x, Just (xs',xs_cs) <- unzip <$> mapM (transposedBy perm) xs = do concat_rearrange <- letExp "concat_rearrange" $ PrimOp $ Concat (cs++x_cs++concat xs_cs) 0 x' xs' new_d letBind_ pat $ PrimOp $ Rearrange [] perm concat_rearrange where transposedBy perm1 v = case ST.lookupExp v vtable of Just (PrimOp (Rearrange vcs perm2 v')) | perm1 == perm2 -> Just (v', vcs) _ -> Nothing simplifyConcat _ _ = cannotSimplify evaluateBranch :: MonadBinder m => TopDownRule m evaluateBranch _ (Let pat _ (If e1 tb fb t)) | Just branch <- checkBranch = do let ses = bodyResult branch mapM_ addBinding $ bodyBindings branch ctx <- subExpShapeContext t ses let ses' = ctx ++ ses sequence_ [ letBind (Pattern [] [p]) $ PrimOp $ SubExp se | (p,se) <- zip (patternElements pat) ses'] where checkBranch | isCt1 e1 = Just tb | isCt0 e1 = Just fb | otherwise = Nothing evaluateBranch _ _ = cannotSimplify -- IMPROVE: This rule can be generalised to work in more cases, -- especially when the branches have bindings, or return more than one -- value. simplifyBoolBranch :: MonadBinder m => TopDownRule m -- if c then True else False == c simplifyBoolBranch _ (Let pat _ (If cond (Body _ [] [Constant (BoolValue True)]) (Body _ [] [Constant (BoolValue False)]) _)) = letBind_ pat $ PrimOp $ SubExp cond -- When seType(x)==bool, if c then x else y == (c && x) || (!c && y) simplifyBoolBranch _ (Let pat _ (If cond tb fb ts)) | Body _ [] [tres] <- tb, Body _ [] [fres] <- fb, patternSize pat == length ts, all (==Prim Bool) ts = do e <- eBinOp LogOr (pure $ PrimOp $ BinOp LogAnd cond tres) (eBinOp LogAnd (pure $ PrimOp $ UnOp Not cond) (pure $ PrimOp $ SubExp fres)) letBind_ pat e simplifyBoolBranch _ _ = cannotSimplify -- XXX: this is a nasty ad-hoc rule for handling a pattern that occurs -- due to limitations in shape analysis. A better way would be proper -- control flow analysis. -- -- XXX: another hack is due to missing CSE. hackilySimplifyBranch :: MonadBinder m => TopDownRule m hackilySimplifyBranch vtable (Let pat _ (If (Var cond_a) (Body _ [] [se1_a]) (Body _ [] [Var v]) _)) | Just (If (Var cond_b) (Body _ [] [se1_b]) (Body _ [] [_]) _) <- ST.lookupExp v vtable, let cond_a_e = ST.lookupExp cond_a vtable, let cond_b_e = ST.lookupExp cond_b vtable, se1_a == se1_b, cond_a == cond_b || (isJust cond_a_e && cond_a_e == cond_b_e) = letBind_ pat $ PrimOp $ SubExp $ Var v hackilySimplifyBranch _ _ = cannotSimplify hoistBranchInvariant :: MonadBinder m => TopDownRule m hoistBranchInvariant _ (Let pat _ (If e1 tb fb ret)) | patternSize pat == length ret = do let tses = bodyResult tb fses = bodyResult fb (pat', res, invariant) <- foldM branchInvariant ([], [], False) $ zip (patternElements pat) (zip tses fses) let (tses', fses') = unzip res tb' = tb { bodyResult = tses' } fb' = fb { bodyResult = fses' } if invariant -- Was something hoisted? then letBind_ (Pattern [] pat') =<< eIf (eSubExp e1) (pure tb') (pure fb') else cannotSimplify where branchInvariant (pat', res, invariant) (v, (tse, fse)) | tse == fse = do letBind_ (Pattern [] [v]) $ PrimOp $ SubExp tse return (pat', res, True) | otherwise = return (v:pat', (tse,fse):res, invariant) hoistBranchInvariant _ _ = cannotSimplify -- | Non-existentialise the parts of the context that are the same in -- both branches. simplifyBranchContext :: MonadBinder m => TopDownRule m simplifyBranchContext _ (Let pat _ e@(If cond tbranch fbranch _)) | not $ null $ patternContextElements pat = do ctx_res <- expContext pat e let old_ctx = patternContextElements pat (free_ctx, new_ctx) = partitionEithers $ zipWith ctxPatElemIsKnown old_ctx ctx_res if null free_ctx then cannotSimplify else do let subst = HM.fromList [ (patElemName pe, v) | (pe, Var v) <- free_ctx ] ret' = existentialiseExtTypes (HS.fromList $ map patElemName new_ctx) $ substituteNames subst $ staticShapes $ patternValueTypes pat pat' = (substituteNames subst pat) { patternContextElements = new_ctx } forM_ free_ctx $ \(name, se) -> letBind_ (Pattern [] [name]) $ PrimOp $ SubExp se letBind_ pat' $ If cond tbranch fbranch ret' where ctxPatElemIsKnown patElem (Just se) = Left (patElem, se) ctxPatElemIsKnown patElem _ = Right patElem simplifyBranchContext _ _ = cannotSimplify simplifyScalExp :: MonadBinder m => TopDownRule m simplifyScalExp vtable (Let pat _ e) = do res <- SE.toScalExp (`ST.lookupScalExp` vtable) e case res of -- If the sufficient condition is 'True', then it statically succeeds. Just se@(SE.RelExp SE.LTH0 _) | Right (SE.Val (BoolValue True)) <- mkDisj <$> AS.mkSuffConds se ranges -> letBind_ pat $ PrimOp $ SubExp $ Constant $ BoolValue True | SE.Val val <- AS.simplify se ranges -> letBind_ pat $ PrimOp $ SubExp $ Constant val Just se@(SE.RelExp SE.LEQ0 x) | let se' = SE.RelExp SE.LTH0 $ x - 1, Right (SE.Val (BoolValue True)) <- mkDisj <$> AS.mkSuffConds se' ranges -> letBind_ pat $ PrimOp $ SubExp $ Constant $ BoolValue True | SE.Val val <- AS.simplify se ranges -> letBind_ pat $ PrimOp $ SubExp $ Constant val _ -> cannotSimplify where ranges = ST.rangesRep vtable mkDisj [] = SE.Val $ BoolValue False mkDisj (x:xs) = foldl SE.SLogOr (mkConj x) $ map mkConj xs mkConj [] = SE.Val $ BoolValue True mkConj (x:xs) = foldl SE.SLogAnd x xs simplifyIdentityReshape :: LetTopDownRule lore u simplifyIdentityReshape _ seType (Reshape _ newshape v) | Just t <- seType $ Var v, newDims newshape == arrayDims t = -- No-op reshape. Just $ SubExp $ Var v simplifyIdentityReshape _ _ _ = Nothing simplifyReshapeReshape :: LetTopDownRule lore u simplifyReshapeReshape defOf _ (Reshape cs newshape v) | Just (Reshape cs2 oldshape v2) <- asPrimOp =<< defOf v = Just $ Reshape (cs++cs2) (fuseReshape oldshape newshape) v2 simplifyReshapeReshape _ _ _ = Nothing simplifyReshapeScratch :: LetTopDownRule lore u simplifyReshapeScratch defOf _ (Reshape _ newshape v) | Just (Scratch bt _) <- asPrimOp =<< defOf v = Just $ Scratch bt $ newDims newshape simplifyReshapeScratch _ _ _ = Nothing improveReshape :: LetTopDownRule lore u improveReshape _ seType (Reshape cs newshape v) | Just t <- seType $ Var v, newshape' <- informReshape (arrayDims t) newshape, newshape' /= newshape = Just $ Reshape cs newshape' v improveReshape _ _ _ = Nothing -- | If we are copying a scratch array (possibly indirectly), just turn it into a scratch by -- itself. copyScratchToScratch :: LetTopDownRule lore u copyScratchToScratch defOf seType (Copy src) = do t <- seType $ Var src if isActuallyScratch src then Just $ Scratch (elemType t) (arrayDims t) else Nothing where isActuallyScratch v = case asPrimOp =<< defOf v of Just Scratch{} -> True Just (Rearrange _ _ v') -> isActuallyScratch v' Just (Reshape _ _ v') -> isActuallyScratch v' _ -> False copyScratchToScratch _ _ _ = Nothing removeIdentityInPlace :: MonadBinder m => TopDownRule m removeIdentityInPlace vtable (Let (Pattern [] [d]) _ e) | BindInPlace _ dest destis <- patElemBindage d, arrayFrom e dest destis = letBind_ (Pattern [] [d { patElemBindage = BindVar}]) $ PrimOp $ SubExp $ Var dest where arrayFrom (PrimOp (Copy v)) dest destis | Just e' <- ST.lookupExp v vtable = arrayFrom e' dest destis arrayFrom (PrimOp (Index _ src srcis)) dest destis = src == dest && destis == srcis arrayFrom _ _ _ = False removeIdentityInPlace _ _ = cannotSimplify removeScratchValue :: MonadBinder m => TopDownRule m removeScratchValue _ (Let (Pattern [] [PatElem v (BindInPlace _ src _) _]) _ (PrimOp Scratch{})) = letBindNames'_ [v] $ PrimOp $ SubExp $ Var src removeScratchValue _ _ = cannotSimplify -- | Remove the return values of a branch, that are not actually used -- after a branch. Standard dead code removal can remove the branch -- if *none* of the return values are used, but this rule is more -- precise. removeDeadBranchResult :: MonadBinder m => BottomUpRule m removeDeadBranchResult (_, used) (Let pat _ (If e1 tb fb rettype)) | -- Only if there is no existential context... patternSize pat == length rettype, -- Figure out which of the names in 'pat' are used... patused <- map (`UT.used` used) $ patternNames pat, -- If they are not all used, then this rule applies. not (and patused) = -- Remove the parts of the branch-results that correspond to dead -- return value bindings. Note that this leaves dead code in the -- branch bodies, but that will be removed later. let tses = bodyResult tb fses = bodyResult fb pick = map snd . filter fst . zip patused tb' = tb { bodyResult = pick tses } fb' = fb { bodyResult = pick fses } pat' = pick $ patternElements pat in letBind_ (Pattern [] pat') =<< eIf (eSubExp e1) (pure tb') (pure fb') removeDeadBranchResult _ _ = cannotSimplify -- | If we are comparing X against the result of a branch of the form -- @if P then Y else Z@ then replace comparison with '(P && X == Y) || -- (!P && X == Z'). This may allow us to get rid of a branch, and the -- extra comparisons may be constant-folded out. Question: maybe we -- should have some more checks to ensure that we only do this if that -- is actually the case, such as if we will obtain at least one -- constant-to-constant comparison? simplifyBranchResultComparison :: MonadBinder m => TopDownRule m simplifyBranchResultComparison vtable (Let pat _ (PrimOp (CmpOp (CmpEq t) se1 se2))) | Just m <- simplifyWith se1 se2 = m | Just m <- simplifyWith se2 se1 = m where simplifyWith (Var v) x | Just bnd <- ST.entryBinding =<< ST.lookup v vtable, If p tbranch fbranch _ <- bindingExp bnd, Just (y, z) <- returns v (bindingPattern bnd) tbranch fbranch, HS.null $ freeIn y `HS.intersection` boundInBody tbranch, HS.null $ freeIn z `HS.intersection` boundInBody fbranch = Just $ do eq_x_y <- letSubExp "eq_x_y" $ PrimOp $ CmpOp (CmpEq t) x y eq_x_z <- letSubExp "eq_x_z" $ PrimOp $ CmpOp (CmpEq t) x z p_and_eq_x_y <- letSubExp "p_and_eq_x_y" $ PrimOp $ BinOp LogAnd p eq_x_y not_p <- letSubExp "not_p" $ PrimOp $ UnOp Not p not_p_and_eq_x_z <- letSubExp "p_and_eq_x_y" $ PrimOp $ BinOp LogAnd not_p eq_x_z letBind_ pat $ PrimOp $ BinOp LogOr p_and_eq_x_y not_p_and_eq_x_z simplifyWith _ _ = Nothing returns v ifpat tbranch fbranch = fmap snd $ find ((==v) . patElemName . fst) $ zip (patternValueElements ifpat) $ zip (bodyResult tbranch) (bodyResult fbranch) simplifyBranchResultComparison _ _ = cannotSimplify -- Some helper functions isCt1 :: SubExp -> Bool isCt1 (Constant v) = oneIsh v isCt1 _ = False isCt0 :: SubExp -> Bool isCt0 (Constant v) = zeroIsh v isCt0 _ = False
mrakgr/futhark
src/Futhark/Optimise/Simplifier/Rules.hs
bsd-3-clause
40,645
0
25
11,322
13,670
6,667
7,003
807
21
{-# LANGUAGE FlexibleContexts #-} module Language.Gator.Ops.XOR ( doXOr, doXOrN, (<^^>), ) where import Control.Monad.State import Language.Gator.Logic import Language.Gator.IO import Language.Gator.Gates import Language.Gator.Gates.XOR import Language.Gator.Ops.General nextXOR :: (MonadState Logic m) => m Name nextXOR = do idx <- nextIdxOf xorID return $ "xor" ++ (show idx) (<^^>) :: (Out a, Out b, MonadState Logic m) => a -> b -> m XOR a <^^> b = doXOr a b doXOr :: (Out a, Out b, MonadState Logic m) => a -> b -> m XOR doXOr a b = do n <- nextXOR doXOrN n a b newXOrN :: (MonadState Logic m) => Name -> m XOR newXOrN n = do i <- nextGateID let g = XOR n i g' = G_XOR g gateSets $ modify (g':) return g doXOrN :: (Out a, Out b, MonadState Logic m) => Name -> a -> b -> m XOR doXOrN = doOp2N newXOrN
sw17ch/gator
src/Language/Gator/Ops/XOR.hs
bsd-3-clause
867
0
10
213
366
193
173
30
1
{- | - Module : Monitoring - Description : Monitor execution of Dikunt plugins. - Copyright : (c) Magnus Stavngaard, 2016 - License : BSD-3 - Maintainer : [email protected] - Stability : experimental - Portability : POSIX - - Responsible for opening and maintaining a running copy of each executable - given. -} {-# LANGUAGE OverloadedStrings #-} module Monitoring ( -- | Functions for creating handling and stopping monitors. startMonitoring , writeAll , readContent , stopMonitoring -- Monitor type. , DikuntMonitor ) where import qualified Control.Concurrent as C import Control.Exception (catch, IOException) import Control.Monad (forever) import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as T import GHC.IO.Handle (hDuplicate) import qualified System.Environment as Sys import qualified System.IO as Sys import qualified System.Log.Logger as Log import qualified System.Process as Sys import Utils (extractTwo) {- | Represent a Dikunt process. Each process contains a path to the executable - a stdin, stdout and process handle. -} data DikuntProcess = DikuntProcess { location :: FilePath -- ^ Location of executable. , outputHandle :: Sys.Handle -- ^ File handle for process output. , inputHandle :: Sys.Handle -- ^ File handle for process input. , processHandle :: Sys.ProcessHandle -- ^ Handle for process. } {- | Main type of module. Handler for Dikunt plugins. When a monitor is - constructed the plugins are started and a thread is started that keeps track - of whether any plugin has stopped. If any plugin is stopped at any time it is - restarted. When the monitor is stopped the thread monitoring the plugins are - killed and the plugins are killed. -} type DikuntMonitor = C.MVar Monitor {- | Unix pipe (readend, writeend). -} type Pipe = (Sys.Handle, Sys.Handle) {- | Internal representation of a Dikunt monitor. -} data Monitor -- | Before monitoring thread is started the monitor is in this state. = SetupMonitor [DikuntProcess] Pipe -- | After monitoring thread is started the monitor is in this state. | Monitor [DikuntProcess] Pipe C.ThreadId {- | Start a process for each file in the list of executable files given. Each - file is given a new stdin but all shares the same stdout. Whenever a program - crashes it is restarted by the monitor and the handles are updated. The - monitor runs in a separate thread to allow starting stopped processes in the - background. -} startMonitoring :: [FilePath] -- ^ List of executable files. -> [String] -- ^ Arguments. -> IO DikuntMonitor startMonitoring execs args = do monitor <- startAll execs args >>= \m -> C.newMVar m monitorId <- C.forkIO $ monitorProcesses monitor args C.modifyMVar_ monitor $ \m -> return $ setThreadId m monitorId return monitor {- | Stop thread monitoring Dikunt plugins and stop the plugins. The function - blocks until all plugins are shut down. -} stopMonitoring :: DikuntMonitor -- ^ The monitor to shut down. -> IO () stopMonitoring monitor = C.withMVar monitor $ \m -> stopMonitor m >> closeProcesses (getProcesses m) where stopMonitor (Monitor _ _ monitorId) = C.killThread monitorId stopMonitor (SetupMonitor _ _) = return () closeProcesses = mapM_ $ waitClose . extractTwo processHandle location waitClose (h, loc) = do lInfo $ "Waiting for plugin \"" ++ loc ++ "\" to close down..." Sys.terminateProcess h Sys.waitForProcess h lInfo = Log.infoM "monitoring.stopMonitoring" {- | Write a message to all dikunt plugings in the monitor. -} writeAll :: DikuntMonitor -- The monitor specifying the plugins. -> T.Text -- The message to write. -> IO () writeAll monitor message = C.withMVar monitor $ \m -> do mapM_ (safePrint message . inputHandle) (getProcesses m) where safePrint msg h = T.hPutStrLn h msg `catch` (\e -> lError $ show (e :: IOException)) lError = Log.errorM "monitoring.writeAll" {- | Read all output that comes from any plugin in the monitor. -} readContent :: DikuntMonitor -- ^ The monitor to read from. -> IO T.Text readContent monitor = do handles <- C.withMVar monitor $ return . map outputHandle . getProcesses case handles of [] -> return "" (h:_) -> T.hGetContents h {- | Monitor all processes in monitor restarting them whenever they stop. The - monitor reports the error code of the process to the log before it is - restarted. The processes are restarted every 30 seconds (TODO: configure - sleep time). -} monitorProcesses :: C.MVar Monitor -- ^ The monitor to run. -> [String] -- ^ List of arguments to give to new processes. -> IO () monitorProcesses monitorMVar args = forever $ do C.threadDelay 30000000 -- Delay 30 seconds. monitor <- C.takeMVar monitorMVar let (processes, pipe) = (getProcesses monitor, getPipe monitor) processes' <- mapM (restartStopped pipe) processes C.putMVar monitorMVar $ setProcesses monitor processes' where restartStopped pipe process@(DikuntProcess loc _ _ pH) = do exitCodeMay <- Sys.getProcessExitCode pH case exitCodeMay of Just code -> do Log.errorM "monitoring.monitorProcesses" $ loc ++ " exited with exit code " ++ show code start pipe args loc Nothing -> return process {- | Start a process for each files given. -} startAll :: [FilePath] -- ^ Files to execute. -> [String] -- ^ Arguments. -> IO Monitor startAll files args = do pipe <- Sys.createPipe -- Pipe to use as stdout. processes <- mapM (start pipe args) files return $ SetupMonitor processes pipe {- | Starts a process. start (hRead, hWrite) args file - Starts the executable - file 'file' with the arguments 'args' and use (hRead, hWrite) as the output - pipe of the new process. -} start :: Pipe -- ^ Output pipe for new process. -> [String] -- ^ Arguments to executable. -> FilePath -- ^ Path to executable file. -> IO DikuntProcess start (houtRead, houtWrite) args file = do {- Don't buffer python stdin and stdout. -} environment <- fmap (\e -> ("PYTHONUNBUFFERED", "1"):e) Sys.getEnvironment dupHoutWrite <- hDuplicate houtWrite (Just hin, _, _, procHandle) <- Sys.createProcess (Sys.proc file args) { Sys.std_out = Sys.UseHandle dupHoutWrite , Sys.std_in = Sys.CreatePipe , Sys.env = Just environment } Sys.hSetBuffering hin Sys.LineBuffering return $ DikuntProcess file houtRead hin procHandle {- | Get the processes managed by the monitor. -} getProcesses :: Monitor -- ^ The monitor to get the processes from. -> [DikuntProcess] getProcesses (SetupMonitor processes _) = processes getProcesses (Monitor processes _ _) = processes {- | Change the processes in a monitor. -} setProcesses :: Monitor -- ^ Monitor to change processes in. -> [DikuntProcess] -- ^ The processes to change to. -> Monitor setProcesses (SetupMonitor _ pipe) procs = SetupMonitor procs pipe setProcesses (Monitor _ pipe monitorId) procs = Monitor procs pipe monitorId {- | Get pipe from monitor. -} getPipe :: Monitor -- ^ The monitor to get the pipe from. -> Pipe getPipe (SetupMonitor _ pipe) = pipe getPipe (Monitor _ pipe _) = pipe {- | Set the ID of the monitoring thread in the monitor. -} setThreadId :: Monitor -- ^ Monitor to change. -> C.ThreadId -- ^ ThreadId to change to. -> Monitor setThreadId (SetupMonitor procs pipe) = Monitor procs pipe setThreadId (Monitor procs pipe _) = Monitor procs pipe
bus000/Dikunt
src/Monitoring.hs
bsd-3-clause
7,747
0
18
1,757
1,443
763
680
119
2
{-# LANGUAGE PackageImports #-} import "hs-yesod-proto-builder" Application (develMain) import Prelude (IO) main :: IO () main = develMain
Greif-IT/hs-yesod-proto
hs-yesod-proto-builder/app/devel.hs
bsd-3-clause
140
0
6
19
34
20
14
5
1
module B1.Program.Chart.Screen ( drawScreen ) where import Control.Concurrent import Control.Concurrent.MVar import Control.Monad import Data.Maybe import Debug.Trace import Graphics.Rendering.OpenGL import Graphics.UI.GLFW import System.Directory import System.FilePath import System.IO import B1.Control.TaskManager import B1.Data.Action import B1.Data.Range import B1.Graphics.Rendering.OpenGL.Box import B1.Graphics.Rendering.OpenGL.BufferManager import B1.Graphics.Rendering.OpenGL.LineSegment import B1.Graphics.Rendering.OpenGL.Shapes import B1.Graphics.Rendering.OpenGL.Utils import B1.Program.Chart.Animation import B1.Program.Chart.Config import B1.Program.Chart.Dirty import B1.Program.Chart.Resources import qualified B1.Program.Chart.Chart as C import qualified B1.Program.Chart.ChartFrame as F import qualified B1.Program.Chart.Graph as G import qualified B1.Program.Chart.Header as H import qualified B1.Program.Chart.Overlay as O import qualified B1.Program.Chart.SideBar as S import qualified B1.Program.Chart.SymbolEntry as E configFileName = ".b1config" drawScreen :: Resources -> IO (Action Resources Dirty, Dirty) drawScreen resources = do configLock <- newEmptyMVar homeDirectory <- getHomeDirectory let configPath = homeDirectory ++ [pathSeparator] ++ configFileName config <- readConfig configPath let configSymbol = selectedSymbol config graphBounds = Just $ Box (-1, 1) (1, -0.1) volumeBounds = Just $ Box (-1, -0.1) (1, -0.4) stochasticBounds = Just $ Box (-1, -0.4) (1, -0.7) weeklyStochasticBounds = Just $ Box (-1, -0.7) (1, -1) options = F.FrameOptions { F.chartOptions = C.ChartOptions { C.headerOptions = H.HeaderOptions { H.fontSize = 18 , H.padding = 10 , H.statusStyle = H.LongStatus , H.button = H.AddButton } , C.graphOptions = G.GraphOptions { G.boundSet = G.GraphBoundSet { G.graphBounds = graphBounds , G.volumeBounds = volumeBounds , G.stochasticsBounds = stochasticBounds , G.weeklyStochasticsBounds = weeklyStochasticBounds , G.monthLineBounds = Just $ Box (-1, 1) (1, -1) , G.dividerLines = [ LineSegment (-1, -0.1) (1, -0.1) , LineSegment (-1, -0.4) (1, -0.4) , LineSegment (-1, -0.7) (1, -0.7) ] } , G.fontSize = 18 , G.maybeOverlayOptions = Just $ O.OverlayOptions { O.boundSet = O.OverlayBoundSet { O.graphBounds = graphBounds , O.volumeBounds = volumeBounds , O.stochasticBounds = stochasticBounds , O.weeklyStochasticBounds = weeklyStochasticBounds } } } , C.showRefreshButton = True } , F.inScaleAnimation = incomingScaleAnimation , F.inAlphaAnimation = incomingAlphaAnimation , F.outScaleAnimation = outgoingScaleAnimation , F.outAlphaAnimation = outgoingAlphaAnimation } inputFrameState <- F.newFrameState options (taskManager resources) configSymbol drawScreenLoop configPath S.SideBarInput { S.bounds = zeroBox , S.newSymbols = symbols config , S.selectedSymbol = configSymbol , S.draggedSymbol = Nothing , S.refreshRequested = False , S.inputState = S.newSideBarState } F.FrameInput { F.bounds = zeroBox , F.alpha = 1 , F.maybeSymbolRequest = Nothing , F.inputState = inputFrameState } E.SymbolEntryInput { E.bounds = zeroBox , E.inputState = E.newSymbolEntryState } ScreenState { sideBarOpen = False , sideBarWidthAnimation = animateOnce $ linearRange 0 0 30 , config = config , configLock = configLock } resources data ScreenState = ScreenState { sideBarOpen :: Bool , sideBarWidthAnimation :: Animation (GLfloat, Dirty) , config :: Config , configLock :: MVar Config } sideBarOpenWidth = 150 openSideBarAnimation = animateOnce $ linearRange 0 sideBarOpenWidth 10 closeSideBarAnimation = animateOnce $ linearRange sideBarOpenWidth 0 10 drawScreenLoop :: String -> S.SideBarInput -> F.FrameInput -> E.SymbolEntryInput -> ScreenState -> Resources -> IO (Action Resources Dirty, Dirty) drawScreenLoop configPath [email protected] { S.inputState = S.SideBarState { S.slots = slots } } frameInput symbolEntryInput screenState@ScreenState { sideBarOpen = sideBarOpen , sideBarWidthAnimation = sideBarWidthAnimation , config = config , configLock = configLock } resources = do frameOutput <- preservingMatrix $ do translateToCenter frameBounds F.drawChartFrame resources frameInput { F.bounds = frameBounds } sideBarOutput <- preservingMatrix $ do translateToCenter sideBarBounds S.drawSideBar resources sideBarInput { S.bounds = sideBarBounds } symbolEntryOutput <- preservingMatrix $ do translateToCenter frameBounds E.drawSymbolEntry resources symbolEntryInput { E.bounds = frameBounds } launchTasks $ taskManager resources let nextSymbols = S.symbols sideBarOutput nextSelectedSymbol = case F.selectedSymbol frameOutput of Just symbol -> Just symbol _ -> selectedSymbol config nextConfig = config { symbols = nextSymbols , selectedSymbol = nextSelectedSymbol } unless (config == nextConfig) $ do -- TODO: Extract this code into a separate ConfigManager module forkIO $ do traceIO $ "Saving configuration..." putMVar configLock nextConfig writeConfig configPath nextConfig takeMVar configLock return () return () control <- getKey LCTRL c <- getKey 'C' let (cleanSideBar, cleanFrame) = if control == Press && c == Press then (S.cleanSideBarState resources, F.cleanFrameState resources) else (return, return) nextSideBarState <- cleanSideBar $ S.outputState sideBarOutput nextFrameState <- cleanFrame $ F.outputState frameOutput let nextSideBarInput = sideBarInput { S.newSymbols = maybeToList $ F.buttonClickedSymbol frameOutput , S.selectedSymbol = F.selectedSymbol frameOutput , S.draggedSymbol = F.draggedSymbol frameOutput , S.refreshRequested = isJust $ F.refreshedSymbol frameOutput , S.inputState = nextSideBarState } nextMaybeSymbolRequest = listToMaybe $ catMaybes [ S.symbolRequest sideBarOutput , F.refreshedSymbol frameOutput , E.maybeEnteredSymbol symbolEntryOutput ] nextFrameInput = frameInput { F.maybeSymbolRequest = nextMaybeSymbolRequest , F.inputState = nextFrameState } nextSymbolEntryInput = symbolEntryInput { E.inputState = E.outputState symbolEntryOutput } nextScreenState = screenState { sideBarOpen = nextSideBarOpen , sideBarWidthAnimation = nextSideBarWidthAnimation , config = nextConfig } nextDirty = sideBarWidthDirty || nextSideBarWidthDirty || S.isDirty sideBarOutput || E.isDirty symbolEntryOutput || F.isDirty frameOutput return (Action (drawScreenLoop configPath nextSideBarInput nextFrameInput nextSymbolEntryInput nextScreenState), nextDirty) where (sideBarWidth, sideBarWidthDirty) = current sideBarWidthAnimation nextSideBarOpen = not $ null slots nextSideBarWidthAnimation | not sideBarOpen && nextSideBarOpen = openSideBarAnimation | sideBarOpen && not nextSideBarOpen = closeSideBarAnimation | otherwise = next sideBarWidthAnimation nextSideBarWidthDirty = snd . current $ nextSideBarWidthAnimation height = windowHeight resources sideBarTopPadding = 5 sideBarBounds = Box (0, height - sideBarTopPadding) (sideBarWidth, 0) frameBounds = Box (sideBarWidth, height) (windowWidth resources, 0) translateToCenter :: Box -> IO () translateToCenter bounds = translate $ vector3 translateX translateY 0 where translateX = boxLeft bounds + boxWidth bounds / 2 translateY = boxTop bounds - boxHeight bounds / 2
madjestic/b1
src/B1/Program/Chart/Screen.hs
bsd-3-clause
8,516
0
21
2,252
2,032
1,124
908
197
3
{-# LANGUAGE DeriveDataTypeable #-} module Elm.Internal.Name where import Control.Applicative import Control.Monad.Error import Data.Aeson import Data.Binary import qualified Data.Text as T import qualified Data.Maybe as Maybe import Data.Typeable data Name = Name { user :: String, project :: String } deriving (Typeable,Eq) instance Binary Name where get = Name <$> get <*> get put (Name user project) = put user >> put project instance Show Name where show name = user name ++ "/" ++ project name toFilePath :: Name -> FilePath toFilePath name = user name ++ "-" ++ project name fromString :: String -> Maybe Name fromString string = case break (=='/') string of ( user@(_:_), '/' : project@(_:_) ) | all (/='/') project -> Just (Name user project) _ -> Nothing fromString' :: String -> ErrorT String IO Name fromString' string = Maybe.maybe (throwError $ errorMsg string) return (fromString string) instance FromJSON Name where parseJSON (String text) = let string = T.unpack text in Maybe.maybe (fail $ errorMsg string) return (fromString string) parseJSON _ = fail "Project name must be a string." instance ToJSON Name where toJSON name = toJSON (show name) errorMsg string = unlines [ "Dependency file has an invalid name: " ++ string , "Must have format user/project and match a public github project." ]
deadfoxygrandpa/Elm
compiler/Elm/Internal/Name.hs
bsd-3-clause
1,413
0
12
310
460
240
220
39
2
{-# LANGUAGE RecordWildCards #-} {-# OPTIONS -Wall #-} ---------------------------------------------------------------------- {- | Module : Scope.Layer Copyright : Conrad Parker License : BSD3-style (see LICENSE) Maintainer : Conrad Parker <[email protected]> Stability : unstable Portability : unknown Layers -} ---------------------------------------------------------------------- module Scope.Layer ( -- * Layers addLayersFromFile , plotLayers ) where import Control.Applicative ((<$>), (<*>), (<|>)) import Control.Monad (foldM, join, replicateM, (>=>)) import Control.Monad.Trans (lift) import Data.ByteString (ByteString) import Data.Function (on) import qualified Data.IntMap as IM import qualified Data.Iteratee as I import qualified Data.Iteratee.IO.OffsetFd as OffI import Data.List (groupBy) import Data.Maybe (fromJust, listToMaybe) import Data.Offset import Data.Time.Clock import Data.ZoomCache.Numeric import System.Posix import qualified System.Random.MWC as MWC import Scope.Types hiding (b) import Scope.View ---------------------------------------------------------------------- -- Random, similar colors genColor :: RGB -> Double -> MWC.GenIO -> IO RGB genColor (r, g, b) a gen = do let a' = 1.0 - a r' <- MWC.uniformR (0.0, a') gen g' <- MWC.uniformR (0.0, a') gen b' <- MWC.uniformR (0.0, a') gen return (r*a + r', g*a + g', b*a * b') genColors :: Int -> RGB -> Double -> IO [RGB] genColors n rgb a = MWC.withSystemRandom (replicateM n . genColor rgb a) ---------------------------------------------------------------------- scopeBufSize :: Int scopeBufSize = 1024 openScopeFile :: ScopeRead -> FilePath -> IO ScopeFile openScopeFile (ScopeRead ReadMethods{..}) path = do fd <- openFd path ReadOnly Nothing defaultFileFlags let f = ScopeFile path fd undefined cf <- scopeEnum f (iterHeaders readIdentifiers) return f{scopeCF = cf} scopeEnum :: ScopeRender m => ScopeFile -> I.Iteratee (Offset ByteString) m a -> m a scopeEnum ScopeFile{..} iter = OffI.enumFdRandomOBS scopeBufSize fd iter >>= I.run layersFromFile :: ScopeRead -> ScopeFile -> IO ([ScopeLayer], Maybe (TimeStamp, TimeStamp), Maybe (UTCTime, UTCTime)) layersFromFile (ScopeRead ReadMethods{..}) file@ScopeFile{..} = do let base = baseUTC . cfGlobal $ scopeCF tracks = IM.keys . cfSpecs $ scopeCF colors <- genColors (length tracks) (0.9, 0.9, 0.9) (0.5) foldl1 merge <$> mapM (\t -> scopeEnum file (I.joinI $ enumBlock scopeCF $ iterListLayers base t)) (zip tracks colors) where merge :: ([ScopeLayer], Maybe (TimeStamp, TimeStamp), Maybe (UTCTime, UTCTime)) -> ([ScopeLayer], Maybe (TimeStamp, TimeStamp), Maybe (UTCTime, UTCTime)) -> ([ScopeLayer], Maybe (TimeStamp, TimeStamp), Maybe (UTCTime, UTCTime)) merge (ls1, bs1, ubs1) (ls2, bs2, ubs2) = (ls1 ++ ls2, unionBounds bs1 bs2, unionBounds ubs1 ubs2) iterListLayers base (trackNo, color) = listLayers base trackNo color <$> readExtents trackNo listLayers :: Maybe UTCTime -> TrackNo -> RGB -> LayerExtents -> ([ScopeLayer], Maybe (TimeStamp, TimeStamp), Maybe (UTCTime, UTCTime)) listLayers base trackNo rgb extents = ([ rawListLayer base trackNo extents , sListLayer base trackNo rgb extents ] , Just (entry, exit) , utcBounds (entry, exit) <$> base) where entry = startTime extents exit = endTime extents utcBounds (t1, t2) b = (ub t1, ub t2) where ub = utcTimeFromTimeStamp b rawListLayer :: Maybe UTCTime -> TrackNo -> LayerExtents -> ScopeLayer rawListLayer base trackNo extents = ScopeLayer $ Layer file trackNo base extents rawConvEnee (rawLayerPlot extents (0,0,0)) sListLayer :: Maybe UTCTime -> TrackNo -> RGB -> LayerExtents -> ScopeLayer sListLayer base trackNo rgb extents = ScopeLayer $ Layer file trackNo base extents summaryConvEnee (summaryLayerPlot extents rgb) addLayersFromFile :: ScopeRead -> FilePath -> Scope ui -> IO (Scope ui) addLayersFromFile reader path scope = do (newLayers, newBounds, newUTCBounds) <- layersFromFile reader =<< openScopeFile reader path let scope' = scopeUpdate newBounds newUTCBounds scope return $ scope' { layers = layers scope ++ newLayers } ---------------------------------------------------------------- plotLayers :: ScopeRender m => Scope ui -> m (Scope ui) plotLayers scope0 = foldM f scope0 layersByFile where f :: ScopeRender m => Scope ui -> [ScopeLayer] -> m (Scope ui) f scope ls = do file' <- plotFileLayers (lf . head $ ls) ls scope return (updateFiles file' scope) updateFiles :: ScopeFile -> Scope ui -> Scope ui updateFiles file scope = scope { layers = map u (layers scope) } where u (ScopeLayer l) | (fd . layerFile $ l) == (fd file) = ScopeLayer l{layerFile = file} | otherwise = ScopeLayer l layersByFile :: [[ScopeLayer]] layersByFile = groupBy ((==) `on` (fd . lf)) (layers scope0) lf (ScopeLayer l) = layerFile l plotFileLayers :: ScopeRender m => ScopeFile -> [ScopeLayer] -> Scope ui -> m ScopeFile plotFileLayers file layers scope = if (any visible layers) then scopeEnum file $ do I.seek 0 I.joinI $ enumBlock (scopeCF file) $ do seekTimeStamp (scopeCF file) seekStart I.joinI . (I.takeWhileE (before seekEnd) >=> I.take 1) $ I.sequence_ is cf <- maybe (scopeCF file) (blkFile . unwrapOffset) <$> I.peek return file{scopeCF = cf} else return file where v = view scope is = map (plotLayer scope) layers visible (ScopeLayer Layer{..}) = maybe False (< (endTime layerExtents)) seekStart && maybe False (> (startTime layerExtents)) seekEnd seekStart = ts (viewStartUTC scope v) <|> viewStartTime scope v seekEnd = ts (viewEndUTC scope v) <|> viewEndTime scope v ts = (timeStampFromUTCTime <$> base <*>) base :: Maybe UTCTime base = join . listToMaybe $ lBase <$> take 1 layers lBase (ScopeLayer l) = layerBaseUTC l plotLayer :: ScopeRender m => Scope ui -> ScopeLayer -> I.Iteratee [Offset Block] m () plotLayer scope (ScopeLayer Layer{..}) = I.joinI . filterTracks [layerTrackNo] . I.joinI . convEnee $ render plotter where render (LayerMap f initCmds) = do d0'm <- I.tryHead case d0'm of Just d0 -> do asdf <- I.foldM renderMap (toX d0, initCmds) lift $ mapM_ renderCmds (snd asdf) Nothing -> return () where renderMap (x0, prev) d = do let x = toX d cmds = f x0 (x-x0) d return (x, zipWith (++) prev cmds) render (LayerFold f initCmds b00) = do d0'm <- I.tryHead case d0'm of Just d0 -> do asdf <- I.foldM renderFold (toX d0, initCmds, b00) lift $ mapM_ renderCmds (mid asdf) Nothing -> return () where renderFold (x0, prev, b0) d = do let x = toX d (cmds, b) = f x0 (x-x0) b0 d return (x, zipWith (++) prev cmds, b) mid (_,x,_) = x toX :: Timestampable a => a -> Double toX = case (utcBounds scope, layerBaseUTC) of (Just _, Just base) -> toUTCX base _ -> toTSX toTSX :: Timestampable a => a -> Double toTSX = toDouble . timeStampToCanvas scope . fromJust . timestamp toUTCX :: Timestampable a => UTCTime -> a -> Double toUTCX base = toDouble . utcToCanvas scope . utcTimeFromTimeStamp base . fromJust . timestamp
kfish/scope
Scope/Layer.hs
bsd-3-clause
8,453
0
18
2,643
2,685
1,389
1,296
151
5
{-- snippet all --} module Main where import qualified PodMainGUI import Paths_pod(getDataFileName) main = do gladefn <- getDataFileName "podresources.glade" PodMainGUI.main gladefn {-- /snippet all --}
binesiyu/ifl
examples/ch23/PodCabalMain.hs
mit
217
0
8
39
41
23
18
6
1
-- | Extra information for blocks. -- * Forward links. -- * InMainChain flags. -- * Slots of the last 'blkSecurityParam' (at most) blocks -- (for chain quality check). module Pos.DB.Block.GState.BlockExtra ( resolveForwardLink , isBlockInMainChain , calcLastBlkSlots , upgradeLastSlotsVersion , getFirstGenesisBlockHash , BlockExtraOp (..) , buildBlockExtraOp , foldlUpWhileM , loadHashesUpWhile , loadHeadersUpWhile , loadBlocksUpWhile , initGStateBlockExtra , streamBlocks ) where import Universum hiding (init) import Data.Conduit (ConduitT, yield) import qualified Database.RocksDB as Rocks import Formatting (Format, bprint, build, later, (%)) import Serokell.Util.Text (listJson) import Pos.Binary.Class (serialize') import Pos.Chain.Block (Block, BlockHeader (..), HasHeaderHash, HeaderHash, LastBlkSlots, LastSlotInfo (..), headerHash, mainHeaderLeaderKey, prevBlockL) import qualified Pos.Chain.Block.Slog.LastBlkSlots as LastBlkSlots import Pos.Chain.Genesis (GenesisHash (..), configBlkSecurityParam, configEpochSlots) import qualified Pos.Chain.Genesis as Genesis import Pos.Core (BlockCount (..), FlatSlotId, SlotCount, addressHash, flattenEpochOrSlot, getEpochOrSlot, slotIdF, unflattenSlotId) import Pos.Core.Chrono (OldestFirst (..)) import Pos.Crypto (PublicKey, shortHashF) import Pos.DB (DBError (..), MonadDB, MonadDBRead (..), RocksBatchOp (..), getHeader, getTipHeader, gsDelete) import Pos.DB.Class (MonadBlockDBRead, SerializedBlock, getBlock) import Pos.DB.GState.Common (gsGetBi, gsPutBi) import Pos.Util.Util (maybeThrow) ---------------------------------------------------------------------------- -- Getters ---------------------------------------------------------------------------- -- | Tries to retrieve next block using current one (given a block/header). resolveForwardLink :: (HasHeaderHash a, MonadDBRead m) => a -> m (Maybe HeaderHash) resolveForwardLink x = gsGetBi (forwardLinkKey $ headerHash x) -- | Check if given hash representing block is in main chain. isBlockInMainChain :: (HasHeaderHash a, MonadDBRead m) => a -> m Bool isBlockInMainChain h = maybe False (\() -> True) <$> gsGetBi (mainChainKey $ headerHash h) -- | This function returns 'FlatSlotId's of the blocks whose depth is -- less than 'blkSecurityParam'. calcLastBlkSlots :: forall m . MonadDBRead m => Genesis.Config -> m LastBlkSlots calcLastBlkSlots genesisConfig = do xs <- calcLastSlotInfo genesisConfig pure $ LastBlkSlots.fromList (fromIntegral . getBlockCount $ configBlkSecurityParam genesisConfig) xs -- | This function acts as a one time conversion from version 1 to version 2 -- of the `LastBlkSlots` data type. upgradeLastSlotsVersion :: forall m . MonadDB m => Genesis.Config -> m () upgradeLastSlotsVersion _ = do -- Delete both the old keys, because this is no longer stored in the DB. gsDelete oldLastSlotsKey gsDelete lastSlotsKey2 where -- The old DB keys that we no longer use. oldLastSlotsKey :: ByteString oldLastSlotsKey = "e/ls/" lastSlotsKey2 :: ByteString lastSlotsKey2 = "e/ls2/" -- Get the 'LastSlotInfo' data for the last 'k' (security paramenter) starting -- at the current blockchain tip. calcLastSlotInfo :: MonadDBRead m => Genesis.Config -> m (OldestFirst [] LastSlotInfo) calcLastSlotInfo genesisConfig = do th <- getTipHeader let thfsid = flattenEpochOrSlot (configEpochSlots genesisConfig) $ getEpochOrSlot th lastfsid = if thfsid <= fromIntegral (configBlkSecurityParam genesisConfig - 1) then 0 else thfsid - fromIntegral (configBlkSecurityParam genesisConfig - 1) OldestFirst <$> convert th lastfsid [] where convert :: MonadDBRead m => BlockHeader -> FlatSlotId -> [LastSlotInfo] -> m [LastSlotInfo] convert bh lastFsid !acc = do let bhFsid = flattenEpochOrSlot (configEpochSlots genesisConfig) $ getEpochOrSlot bh if bhFsid < lastFsid then pure acc else do let ys = case leaderKey bh of Nothing -> acc Just lk -> LastSlotInfo bhFsid (addressHash lk) : acc mnbh <- getHeader $ view prevBlockL bh case mnbh of Nothing -> pure acc Just nbh -> convert nbh lastFsid ys leaderKey :: BlockHeader -> Maybe PublicKey leaderKey = \case BlockHeaderGenesis _ -> Nothing BlockHeaderMain bhm -> Just $ view mainHeaderLeaderKey bhm -- | Retrieves first genesis block hash. getFirstGenesisBlockHash :: MonadDBRead m => GenesisHash -> m HeaderHash getFirstGenesisBlockHash genesisHash = resolveForwardLink (getGenesisHash genesisHash :: HeaderHash) >>= maybeThrow (DBMalformed "Can't retrieve genesis block, maybe db is not initialized?") ---------------------------------------------------------------------------- -- BlockOp ---------------------------------------------------------------------------- data BlockExtraOp = AddForwardLink HeaderHash HeaderHash -- ^ Adds or overwrites forward link | RemoveForwardLink HeaderHash -- ^ Removes forward link | SetInMainChain Bool HeaderHash -- ^ Enables or disables "in main chain" status of the block | SetLastSlots LastBlkSlots -- ^ Updates list of slots for last blocks. deriving (Show) buildBlockExtraOp :: SlotCount -> Format r (BlockExtraOp -> r) buildBlockExtraOp epochSlots = later build' where build' (AddForwardLink from to) = bprint ("AddForwardLink from "%shortHashF%" to "%shortHashF) from to build' (RemoveForwardLink from) = bprint ("RemoveForwardLink from "%shortHashF) from build' (SetInMainChain flag h) = bprint ("SetInMainChain for "%shortHashF%": "%build) h flag build' (SetLastSlots slots) = bprint ("SetLastSlots: "%listJson) (map (bprint slotIdF . unflattenSlotId epochSlots . lsiFlatSlotId) $ LastBlkSlots.getList slots) instance RocksBatchOp BlockExtraOp where toBatchOp (AddForwardLink from to) = [Rocks.Put (forwardLinkKey from) (serialize' to)] toBatchOp (RemoveForwardLink from) = [Rocks.Del $ forwardLinkKey from] toBatchOp (SetInMainChain False h) = [Rocks.Del $ mainChainKey h] toBatchOp (SetInMainChain True h) = [Rocks.Put (mainChainKey h) (serialize' ()) ] toBatchOp (SetLastSlots _) = [{- No longer store this in the DB -}] ---------------------------------------------------------------------------- -- Loops on forward links ---------------------------------------------------------------------------- -- | Creates a Producer for blocks from a given HeaderHash, exclusive: the -- block for that hash is not produced, its child is the first thing produced. streamBlocks :: ( Monad m ) => (HeaderHash -> m (Maybe SerializedBlock)) -> (HeaderHash -> m (Maybe HeaderHash)) -> HeaderHash -> ConduitT () SerializedBlock m () streamBlocks loadBlock forwardLink base = do mFirst <- lift $ forwardLink base maybe (pure ()) loop mFirst where loop hhash = do mb <- lift $ loadBlock hhash case mb of Nothing -> pure () Just block -> do yield block mNext <- lift $ forwardLink hhash case mNext of Nothing -> pure () Just hhash' -> loop hhash' foldlUpWhileM :: forall a b m r . ( MonadDBRead m , HasHeaderHash a ) => (HeaderHash -> m (Maybe b)) -- ^ For each header we get b(lund) -> a -- ^ We start iterating from it -> (b -> Int -> Bool) -- ^ Condition on b and depth -> (r -> b -> m r) -- ^ Conversion function -> r -- ^ Starting value -> m r foldlUpWhileM getData start condition accM init = loadUpWhileDo (headerHash start) 0 init where loadUpWhileDo :: HeaderHash -> Int -> r -> m r loadUpWhileDo curH height !res = getData curH >>= \case Nothing -> pure res Just someData -> do mbNextLink <- resolveForwardLink curH if | not (condition someData height) -> pure res | Just nextLink <- mbNextLink -> do newRes <- accM res someData loadUpWhileDo nextLink (succ height) newRes | otherwise -> accM res someData -- Loads something from old to new. foldlUpWhileM for (OldestFirst []). loadUpWhile :: forall a b m . (MonadDBRead m, HasHeaderHash a) => (HeaderHash -> m (Maybe b)) -> a -> (b -> Int -> Bool) -> m (OldestFirst [] b) loadUpWhile morph start condition = OldestFirst . reverse <$> foldlUpWhileM morph start condition (\l e -> pure (e : l)) [] -- | Return hashes loaded up. Basically a forward links traversal. loadHashesUpWhile :: forall m a. (HasHeaderHash a, MonadDBRead m) => a -> (HeaderHash -> Int -> Bool) -> m (OldestFirst [] HeaderHash) loadHashesUpWhile = loadUpWhile (pure . Just) -- | Returns headers loaded up. loadHeadersUpWhile :: (MonadBlockDBRead m, HasHeaderHash a) => a -> (BlockHeader -> Int -> Bool) -> m (OldestFirst [] BlockHeader) loadHeadersUpWhile = loadUpWhile getHeader -- | Returns blocks loaded up. loadBlocksUpWhile :: (MonadBlockDBRead m, HasHeaderHash a) => GenesisHash -> a -> (Block -> Int -> Bool) -> m (OldestFirst [] Block) loadBlocksUpWhile genesisHash = loadUpWhile (getBlock genesisHash) ---------------------------------------------------------------------------- -- Initialization ---------------------------------------------------------------------------- initGStateBlockExtra :: MonadDB m => GenesisHash -> HeaderHash -> m () initGStateBlockExtra genesisHash firstGenesisHash = do gsPutBi (mainChainKey firstGenesisHash) () gsPutBi (forwardLinkKey $ getGenesisHash genesisHash) firstGenesisHash ---------------------------------------------------------------------------- -- Keys ---------------------------------------------------------------------------- forwardLinkKey :: HeaderHash -> ByteString forwardLinkKey h = "e/fl/" <> serialize' h mainChainKey :: HeaderHash -> ByteString mainChainKey h = "e/mc/" <> serialize' h
input-output-hk/pos-haskell-prototype
db/src/Pos/DB/Block/GState/BlockExtra.hs
mit
10,778
0
21
2,721
2,418
1,273
1,145
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving, RecordWildCards #-} module GMEParser (parseTipToiFile) where import qualified Data.ByteString.Lazy as B import qualified Data.ByteString.Lazy.Char8 as BC import qualified Data.Binary.Get as G import Text.Printf import Data.List import Data.Functor import Control.Applicative (Applicative, (<*>)) import Data.Maybe import Control.Monad import Control.Monad.Writer.Strict import Control.Monad.State.Strict import Control.Monad.Reader import Control.Monad.RWS.Strict import Control.Exception import Control.Arrow import Types import Constants import Cypher -- Reverse Engineering Monad newtype SGet a = SGet (RWS B.ByteString [Segment] Word32 a) deriving (Functor, Applicative, Monad) liftGet :: G.Get a -> SGet a liftGet act = SGet $ do offset <- get bytes <- ask when (offset > fromIntegral (B.length bytes)) $ do fail $ printf "Trying to read from offset 0x%08X, which is after the end of the file!" offset let (a, _, i) = G.runGetState act (B.drop (fromIntegral offset) bytes) 0 put (offset + fromIntegral i) return $ a jumpTo :: Offset -> SGet () jumpTo offset = SGet (put offset) lookAhead :: SGet a -> SGet a lookAhead (SGet act) = SGet $ do oldOffset <- get a <- act put oldOffset return a getAt :: Offset -> SGet a -> SGet a getAt offset act = lookAhead (jumpTo offset >> act) getSeg :: String -> SGet a -> SGet a getSeg desc (SGet act) = addStack desc $ SGet $ do offset <- get a <- censor (map addDesc) act newOffset <- get tell [(offset, newOffset - offset, [desc])] return a where addDesc (o,l,d) = (o,l,desc : d) addStack :: String -> SGet a -> SGet a addStack desc (SGet act1) = SGet $ rws $ \r s -> mapException annotate (runRWS act1 r s) where annotate (ErrorCall s) = ErrorCall (s ++ "\n when reading segment " ++ desc) getSegAt :: Offset -> String -> SGet a -> SGet a getSegAt offset desc act = getAt offset $ getSeg desc act indirection :: String -> SGet a -> SGet a indirection desc act = do position <- bytesRead offset <- getWord32 l <- getLength when (offset > l) $ do fail $ printf "Trying to read from offset 0x%08X, mentioned at 0x%08X, which is after the end of the file!" offset position getSegAt offset desc act indirectBS :: String -> SGet B.ByteString indirectBS desc = do offset <- getWord32 length <- getWord32 getSegAt offset desc (getBS length) maybeIndirection :: String -> SGet a -> SGet (Maybe a) maybeIndirection desc act = do offset <- getWord32 if offset == 0xFFFFFFFF || offset == 0x00000000 then return Nothing else Just <$> getSegAt offset desc act getLength :: SGet Word32 getLength = fromIntegral . B.length <$> getAllBytes getAllBytes :: SGet B.ByteString getAllBytes = SGet ask runSGet :: SGet a -> B.ByteString -> (a, Segments) runSGet (SGet act) bytes = second (sort . ((fromIntegral (B.length bytes), 0, ["End of file"]):)) $ evalRWS act bytes 0 getWord8 = liftGet G.getWord8 getWord16 = liftGet G.getWord16le getWord32 = liftGet G.getWord32le getBS :: Word32 -> SGet B.ByteString getBS n = liftGet $ G.getLazyByteString (fromIntegral n) bytesRead = SGet get getArray :: Integral a => SGet a -> SGet b -> SGet [b] getArray g1 g2 = do n <- g1 replicateM (fromIntegral n) g2 getArrayN :: Integral a => SGet a -> (Int -> SGet b) -> SGet [b] getArrayN g1 g2 = do n <- g1 mapM g2 [0.. fromIntegral n - 1] indirections :: Integral a => SGet a -> String -> SGet b -> SGet [b] indirections g1 prefix g2 = getArrayN g1 (\n -> indirection (prefix ++ show n) g2) -- Parsers getScripts :: SGet [(Word16, Maybe [Line ResReg])] getScripts = do last_code <- getWord16 0 <- getWord16 first_code <- getWord16 0 <- getWord16 forM [first_code .. last_code] $ \oid -> do l <- maybeIndirection (show oid) $ getScript return (oid,l) getScript :: SGet [Line ResReg] getScript = indirections getWord16 "Line " lineParser getTVal :: SGet (TVal ResReg) getTVal = do t <- getWord8 case t of 0 -> Reg <$> getWord16 1 -> Const <$> getWord16 _ -> fail $ "Unknown value tag " ++ show t lineParser :: SGet (Line ResReg) lineParser = begin where -- Find the occurrence of a header begin = do offset <- bytesRead -- Conditionals conds <- getArray getWord16 $ do v1 <- getTVal bytecode <- getBS 2 let op = fromMaybe (Unknowncond bytecode) $ lookup bytecode conditionals v2 <- getTVal return $ Cond v1 op v2 -- Actions cmds <- getArray getWord16 $ do r <- getWord16 bytecode <- getBS 2 case lookup bytecode actions of Just p -> p r Nothing -> do n <- getTVal return $ Unknown bytecode r n -- Audio links xs <- getArray getWord16 getWord16 return $ Line offset conds cmds xs expectWord8 n = do n' <- getWord8 when (n /= n') $ do b <- bytesRead fail $ printf "At position 0x%08X, expected %d/%02X, got %d/%02X" (b-1) n n n' n' conditionals = [ (B.pack [0xF9,0xFF], Eq) , (B.pack [0xFA,0xFF], Gt) , (B.pack [0xFB,0xFF], Lt) , (B.pack [0xFD,0xFF], GEq) , (B.pack [0xFE,0xFF], LEq) , (B.pack [0xFF,0xFF], NEq) ] actions = [ (B.pack [0xE8,0xFF], \r -> do unless (r == 0) $ fail "Non-zero register for Play command" Const n <- getTVal return (Play n)) , (B.pack [0x00,0xFC], \r -> do unless (r == 0) $ fail "Non-zero register for Random command" Const n <- getTVal return (Random (lowbyte n) (highbyte n))) , (B.pack [0xFF,0xFA], \r -> do unless (r == 0) $ fail "Non-zero register for Cancel command" Const 0xFFFF <- getTVal return Cancel) , (B.pack [0xFF,0xF8], \r -> do unless (r == 0) $ fail "Non-zero register for Jump command" v <- getTVal return (Jump v)) , (B.pack [0x00,0xFD], \r -> do unless (r == 0) $ fail "Non-zero register for Game command" Const a <- getTVal return (Game a)) , (B.pack [0xF8,0xFF], \r -> do _ <- getTVal return (Neg r)) ] ++ [ (B.pack (arithOpCode o), \r -> do n <- getTVal return (ArithOp o r n)) | o <- [minBound..maxBound] ] lowbyte, highbyte :: Word16 -> Word8 lowbyte n = fromIntegral (n `mod` 2^8) highbyte n = fromIntegral (n `div` 2^8) getBinaries :: SGet [(B.ByteString, B.ByteString)] getBinaries = do n <- getWord16 _ <- getBS 14 -- padding forM [0..n - 1] $ \n -> do offset <- getWord32 length <- getWord32 desc <- getBS 8 binary <- getSegAt offset (BC.unpack desc) (getBS length) return (desc, binary) getAudios :: Word32 -> SGet ([B.ByteString], Bool, Word8) getAudios rawXor = do until <- lookAhead getWord32 x <- case () of () | rawXor == knownRawXOR -> return knownXOR | otherwise -> lookAhead $ jumpTo until >> getXor offset <- bytesRead let n_entries = fromIntegral ((until - offset) `div` 8) at_doubled <- lookAhead $ do half1 <- getBS (n_entries * 8 `div` 2) half2 <- getBS (n_entries * 8 `div` 2) return $ half1 == half2 let n_entries' | at_doubled = n_entries `div` 2 | otherwise = n_entries decoded <- forM [0..n_entries'-1] $ \n -> do cypher x <$> indirectBS (show n) -- Fix segment when at_doubled $ lookAhead $ getSeg "Audio table copy" $ replicateM_ (fromIntegral n_entries') (getWord32 >> getWord32) return (decoded, at_doubled, x) getXor :: SGet Word8 getXor = do present <- getBS 4 -- Brute force, but that's ok here case [ n | n <- [0..0xFF] , let c = cypher n present , (magic,_) <- fileMagics , magic `B.isPrefixOf` c ] of [] -> fail "Could not find magic hash" (x:_) -> return x getChecksum :: SGet Word32 getChecksum = do l <- getLength getSegAt (l-4) "Checksum" $ getWord32 calcChecksum :: SGet Word32 calcChecksum = do l <- getLength bs <- getAt 0 $ getBS (fromIntegral l - 4) return $ B.foldl' (\s b -> fromIntegral b + s) 0 bs getPlayList :: SGet PlayList getPlayList = getArray getWord16 getWord16 getOidList :: SGet [OID] getOidList = getArray getWord16 getWord16 getGidList :: SGet [OID] getGidList = getArray getWord16 getWord16 getPlayListList :: SGet PlayListList getPlayListList = indirections getWord16 "" getPlayList getSubGame :: SGet SubGame getSubGame = do u <- getBS 20 oid1s <- getOidList oid2s <- getOidList oid3s <- getOidList plls <- indirections (return 9) "playlistlist " getPlayListList return (SubGame u oid1s oid2s oid3s plls) getGame :: SGet Game getGame = do t <- getWord16 case t of 6 -> do b <- getWord16 u1 <- getWord16 c <- getWord16 u2 <- getBS 18 plls <- indirections (return 7) "playlistlistA-" getPlayListList sg1s <- indirections (return b) "subgameA-" getSubGame sg2s <- indirections (return c) "subgameB-" getSubGame u3 <- getBS 20 pll2s <- indirections (return 10) "playlistlistB-" getPlayListList pl <- indirection "playlist" getPlayList return (Game6 u1 u2 plls sg1s sg2s u3 pll2s pl) 7 -> do (u1,c,u2,plls, sgs, u3, pll2s) <- common pll <- indirection "playlistlist" getPlayListList return (Game7 u1 c u2 plls sgs u3 pll2s pll) 8 -> do (u1,c,u2,plls, sgs, u3, pll2s) <- common oidl <- indirection "oidlist" getOidList gidl <- indirection "gidlist" getGidList pll1 <- indirection "playlistlist1" getPlayListList pll2 <- indirection "playlistlist2" getPlayListList return (Game8 u1 c u2 plls sgs u3 pll2s oidl gidl pll1 pll2) 253 -> do return Game253 _ -> do (u1,c,u2,plls, sgs, u3, pll2s) <- common return (UnknownGame t u1 c u2 plls sgs u3 pll2s) where common = do -- the common header of a non-type-6-game b <- getWord16 u1 <- getWord16 c <- getWord16 u2 <- getBS 10 plls <- indirections (return 5) "playlistlistA-" getPlayListList sgs <- indirections (return b) "subgame-" getSubGame u3 <- getBS 20 pll2s <- indirections (return 10) "playlistlistB-" getPlayListList return (u1, c, u2, plls, sgs, u3, pll2s) getInitialRegs :: SGet [Word16] getInitialRegs = getArray getWord16 getWord16 getSpecials :: SGet (Word16, Word16) getSpecials = (,) <$> getWord16 <*> getWord16 getTipToiFile :: SGet TipToiFile getTipToiFile = getSegAt 0x00 "Header" $ do ttScripts <- indirection "Scripts" getScripts ttRawXor <- getAt 0x001C getWord32 (ttAudioFiles, ttAudioFilesDoubles, ttAudioXor) <- indirection "Media" (getAudios ttRawXor) _ <- getWord32 -- Usually 0x0000238b _ <- indirection "Additional script" getScript ttGames <- indirection "Games" $ indirections getWord32 "" getGame ttProductId <- getWord32 ttInitialRegs <- indirection "Initial registers" getInitialRegs _ <- getWord32 -- raw Xor (ttComment, ttDate) <- do l <- getWord8 c <- getBS (fromIntegral l) d <- getBS 8 return (c,d) jumpTo 0x0071 ttWelcome <- indirection "initial play lists" $ getPlayListList jumpTo 0x0090 ttBinaries1 <- fromMaybe [] <$> maybeIndirection "Binaries 1" getBinaries ttSpecialOIDs <- maybeIndirection "specials symbols" getSpecials ttBinaries2 <- fromMaybe [] <$> maybeIndirection "Binaries 1" getBinaries jumpTo 0x00A0 ttBinaries3 <- fromMaybe [] <$> maybeIndirection "Single binary 1" getBinaries getWord32 --ignored ttBinaries4 <- fromMaybe [] <$> maybeIndirection "Single binary 2" getBinaries ttChecksum <- getChecksum ttChecksumCalc <- calcChecksum return $ TipToiFile {..} parseTipToiFile :: B.ByteString -> (TipToiFile, Segments) parseTipToiFile = runSGet getTipToiFile
christiannolte/tip-toi-reveng
src/GMEParser.hs
mit
12,407
0
19
3,454
4,393
2,163
2,230
322
5
module Graphics.Shaders (makeProgram) where import Graphics.Rendering.OpenGL import Control.Monad (guard, unless) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Maybe (MaybeT) import Data.ByteString as BS (readFile, ByteString) makeShader :: ShaderType -> ByteString -> MaybeT IO Shader makeShader shaderType shaderSource = do shader <- lift $ createShader shaderType lift $ shaderSourceBS shader $= shaderSource >> compileShader shader status <- lift $ get $ compileStatus shader unless status $ do infoLog <- lift $ get $ shaderInfoLog shader lift $ putStrLn ("Failed compiling shader:\n" ++ infoLog) >> deleteObjectName shader guard status return shader loadShader :: (ShaderType, FilePath) -> MaybeT IO Shader loadShader (shaderType, filePath) = lift (BS.readFile filePath) >>= \shaderSource -> makeShader shaderType shaderSource loadAndAttachShader :: Program -> (ShaderType, FilePath) -> MaybeT IO () loadAndAttachShader program shaderInfo = loadShader shaderInfo >>= \shader -> lift $ attachShader program shader makeProgram :: [(ShaderType, FilePath)] -> MaybeT IO Program makeProgram shaderList = do program <- lift createProgram shaders <- mapM loadShader shaderList lift $ mapM_ (attachShader program) shaders >> linkProgram program >> mapM_ (detachShader program) shaders >> deleteObjectNames shaders status <- lift $ get $ linkStatus program unless status $ do infoLog <- lift $ get $ programInfoLog program lift $ putStrLn ("Failed linking program:\n" ++ infoLog) >> deleteObjectName program guard status return program
sgillis/HaskHull
src/Graphics/Shaders.hs
gpl-3.0
1,763
0
14
413
512
251
261
45
1
{-| Module : Devel.Watch Description : Watch for changes in the current working direcory. Copyright : (c) 2015 Njagi Mwaniki License : MIT Maintainer : [email protected] Stability : experimental Portability : POSIX Actually checks only for modified files. Added or removed files don't trigger rebuilds. -} {-# LANGUAGE OverloadedStrings, CPP #-} module Devel.Watch where -- import IdeSession import Control.Monad.STM import Control.Concurrent.STM.TVar import System.FSNotify import Control.Monad (forever) import Control.Concurrent (threadDelay) -- import Devel.Types -- import Devel.Paths (getFilesToWatch) # if __GLASGOW_HASKELL__ < 710 import Data.Text (unpack) import Filesystem.Path.CurrentOS (toText) -- import qualified Filesystem.Path as FSP #endif import System.Directory (getCurrentDirectory) import System.FilePath (pathSeparator) import Devel.Paths watch :: TVar Bool -> [FilePath] -> [FilePath] -> IO () watch isDirty watchSource watchOther = do -- Get files to watch. files <- getFilesToWatch watchSource -- Making paths to watch a list of absolute paths. dir <- getCurrentDirectory let sourceToWatch = map (\fp -> dir ++ (pathSeparator: fp)) files let otherToWatch = map (\fp -> dir ++ (pathSeparator: fp)) watchOther -- Actual file watching. manager <- startManagerConf defaultConfig _ <- watchTree manager "." (const True) -- Last argument to watchTree. # if __GLASGOW_HASKELL__ >= 710 (\event -> do let getPath :: Event -> FilePath getPath (Added fp _) = fp getPath (Modified fp _) = fp getPath (Removed fp _) = fp isModified = getPath event `elem` (sourceToWatch ++ otherToWatch) atomically $ do readTVar isDirty >>= check . not writeTVar isDirty isModified) #else (\event -> do pathMod' <- case toText $ eventPath event of Right text -> return $ unpack text -- Gives an abs path Left text -> fail $ unpack text let isModified = pathMod' `elem` (sourceToWatch ++ otherToWatch) atomically $ do readTVar isDirty >>= check . not writeTVar isDirty isModified) #endif _ <- forever $ threadDelay maxBound stopManager manager checkForChange :: TVar Bool -> IO () checkForChange isDirty = atomically $ do readTVar isDirty >>= check writeTVar isDirty False
urbanslug/yesod-devel
src/Devel/Watch.hs
gpl-3.0
2,513
0
18
659
449
236
213
33
2
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Test.AWS.Route53.Internal -- Copyright : (c) 2013-2015 Brendan Hay -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Test.AWS.Route53.Internal where import Test.AWS.Prelude
fmapfmapfmap/amazonka
amazonka-route53/test/Test/AWS/Route53/Internal.hs
mpl-2.0
621
0
4
140
25
21
4
4
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.AutoScaling.DescribeLifecycleHookTypes -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Describes the available types of lifecycle hooks. -- -- /See:/ <http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_DescribeLifecycleHookTypes.html AWS API Reference> for DescribeLifecycleHookTypes. module Network.AWS.AutoScaling.DescribeLifecycleHookTypes ( -- * Creating a Request describeLifecycleHookTypes , DescribeLifecycleHookTypes -- * Destructuring the Response , describeLifecycleHookTypesResponse , DescribeLifecycleHookTypesResponse -- * Response Lenses , dlhtrsLifecycleHookTypes , dlhtrsResponseStatus ) where import Network.AWS.AutoScaling.Types import Network.AWS.AutoScaling.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeLifecycleHookTypes' smart constructor. data DescribeLifecycleHookTypes = DescribeLifecycleHookTypes' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeLifecycleHookTypes' with the minimum fields required to make a request. -- describeLifecycleHookTypes :: DescribeLifecycleHookTypes describeLifecycleHookTypes = DescribeLifecycleHookTypes' instance AWSRequest DescribeLifecycleHookTypes where type Rs DescribeLifecycleHookTypes = DescribeLifecycleHookTypesResponse request = postQuery autoScaling response = receiveXMLWrapper "DescribeLifecycleHookTypesResult" (\ s h x -> DescribeLifecycleHookTypesResponse' <$> (x .@? "LifecycleHookTypes" .!@ mempty >>= may (parseXMLList "member")) <*> (pure (fromEnum s))) instance ToHeaders DescribeLifecycleHookTypes where toHeaders = const mempty instance ToPath DescribeLifecycleHookTypes where toPath = const "/" instance ToQuery DescribeLifecycleHookTypes where toQuery = const (mconcat ["Action" =: ("DescribeLifecycleHookTypes" :: ByteString), "Version" =: ("2011-01-01" :: ByteString)]) -- | /See:/ 'describeLifecycleHookTypesResponse' smart constructor. data DescribeLifecycleHookTypesResponse = DescribeLifecycleHookTypesResponse' { _dlhtrsLifecycleHookTypes :: !(Maybe [Text]) , _dlhtrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeLifecycleHookTypesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dlhtrsLifecycleHookTypes' -- -- * 'dlhtrsResponseStatus' describeLifecycleHookTypesResponse :: Int -- ^ 'dlhtrsResponseStatus' -> DescribeLifecycleHookTypesResponse describeLifecycleHookTypesResponse pResponseStatus_ = DescribeLifecycleHookTypesResponse' { _dlhtrsLifecycleHookTypes = Nothing , _dlhtrsResponseStatus = pResponseStatus_ } -- | One or more of the following notification types: -- -- - 'autoscaling:EC2_INSTANCE_LAUNCHING' -- -- - 'autoscaling:EC2_INSTANCE_TERMINATING' -- dlhtrsLifecycleHookTypes :: Lens' DescribeLifecycleHookTypesResponse [Text] dlhtrsLifecycleHookTypes = lens _dlhtrsLifecycleHookTypes (\ s a -> s{_dlhtrsLifecycleHookTypes = a}) . _Default . _Coerce; -- | The response status code. dlhtrsResponseStatus :: Lens' DescribeLifecycleHookTypesResponse Int dlhtrsResponseStatus = lens _dlhtrsResponseStatus (\ s a -> s{_dlhtrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-autoscaling/gen/Network/AWS/AutoScaling/DescribeLifecycleHookTypes.hs
mpl-2.0
4,241
0
15
840
497
298
199
69
1
{- Copyright 2010-2012 Cognimeta Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Database.Perdure.Package( perdurePackage ) where perdurePackage :: String perdurePackage = "perdure-0.1.0"
bitemyapp/perdure
src/Database/Perdure/Package.hs
apache-2.0
704
0
4
126
23
15
8
4
1
module Main (main) where import Criterion.Main (bgroup, defaultMain) import qualified API.IBBench main :: IO () main = defaultMain [ bgroup "API.IB" API.IBBench.benchmarks ]
cmahon/interactive-brokers
benchmark/Bench.hs
bsd-3-clause
194
0
8
43
57
33
24
6
1
{-# LANGUAGE OverloadedStrings #-} module Bead.View.Content.SubmissionList.Page ( submissionList ) where import Control.Monad import Control.Monad.Trans.Class import Control.Monad.IO.Class import Data.String (fromString) import Data.Time import Text.Blaze.Html5 as H import Bead.Controller.UserStories import qualified Bead.Controller.Pages as Pages import qualified Bead.Domain.Entity.Assignment as Assignment import Bead.Domain.Shared.Evaluation import Bead.View.Content import qualified Bead.View.Content.Bootstrap as Bootstrap import Bead.View.Content.Submission.Common import Bead.View.Content.Utils import Bead.View.Markdown submissionList = ViewHandler submissionListPage data PageData = PageData { asKey :: AssignmentKey , smList :: SubmissionListDesc , uTime :: UserTimeConverter , smLimit :: SubmissionLimit } submissionListPage :: GETContentHandler submissionListPage = do ak <- getParameter assignmentKeyPrm -- TODO: Refactor use guards userStory $ do doesBlockAssignmentView ak page <- usersAssignment ak $ \assignment -> do case assignment of Nothing -> return invalidAssignment Just asg -> do now <- liftIO getCurrentTime case (Assignment.start asg > now) of True -> return assignmentNotStartedYet False -> do (sl,lmt) <- userStory $ (,) <$> submissionListDesc ak <*> assignmentSubmissionLimit ak tc <- userTimeZoneToLocalTimeConverter return $ submissionListContent $ PageData { asKey = ak , smList = sortSbmListDescendingByTime sl , uTime = tc , smLimit = lmt } return page submissionListContent :: PageData -> IHtml submissionListContent p = do msg <- getI18N return $ do let info = smList p -- Submission List Info Bootstrap.rowColMd12 $ Bootstrap.table $ tbody $ do (msg $ msg_SubmissionList_CourseOrGroup "Course, group:") .|. (slGroup info) (msg $ msg_SubmissionList_Admin "Teacher:") .|. (join $ slTeacher info) (msg $ msg_SubmissionList_Assignment "Assignment:") .|. (Assignment.name $ slAssignment info) (msg $ msg_SubmissionList_Deadline "Deadline:") .|. (showDate . (uTime p) . Assignment.end $ slAssignment info) maybe (return ()) (uncurry (.|.)) (remainingTries msg (smLimit p)) Bootstrap.rowColMd12 $ h2 $ fromString $ msg $ msg_SubmissionList_Description "Description" H.div # assignmentTextDiv $ (markdownToHtml . Assignment.desc . slAssignment . smList $ p) let submissions = slSubmissions info Bootstrap.rowColMd12 $ h2 $ fromString $ msg $ msg_SubmissionList_SubmittedSolutions "Submissions" either (userSubmissionTimes msg) (userSubmissionInfo msg) submissions where submissionDetails ak sk = Pages.submissionDetails ak sk () submissionLine msg (sk, time, status, _t) = do Bootstrap.listGroupLinkItem (routeOf $ submissionDetails (asKey p) sk) (do Bootstrap.badge (resolveStatus msg status); fromString . showDate $ (uTime p) time) resolveStatus msg = fromString . submissionInfoCata (msg $ msg_SubmissionList_NotFound "Not Found") (msg $ msg_SubmissionList_NotEvaluatedYet "Not evaluated yet") (bool (msg $ msg_SubmissionList_TestsPassed "Tests are passed") (msg $ msg_SubmissionList_TestsFailed "Tests are failed")) (const (evaluationResultMsg . evResult)) where evaluationResultMsg = evaluationResultCata (binaryCata (resultCata (msg $ msg_SubmissionList_Passed "Passed") (msg $ msg_SubmissionList_Failed "Failed"))) (percentageCata (fromString . scores)) scores (Scores []) = "0%" scores (Scores [p]) = concat [show . round $ 100 * p, "%"] scores _ = "???%" submissionTimeLine time = Bootstrap.listGroupTextItem $ showDate $ (uTime p) time userSubmissionInfo msg submissions = do Bootstrap.rowColMd12 $ H.p $ fromString $ msg $ msg_SubmissionList_Info "Comments may be added for submissions." userSubmission msg (submissionLine msg) submissions userSubmissionTimes msg = userSubmission msg submissionTimeLine userSubmission msg line submissions = if (not $ null submissions) then do Bootstrap.rowColMd12 $ Bootstrap.listGroup $ mapM_ line submissions else do (Bootstrap.rowColMd12 $ fromString $ msg $ msg_SubmissionList_NoSubmittedSolutions "There are no submissions.") invalidAssignment :: IHtml invalidAssignment = do msg <- getI18N return $ do Bootstrap.rowColMd12 $ p $ fromString $ msg $ msg_SubmissionList_NonAssociatedAssignment "This assignment cannot be accessed by this user." assignmentNotStartedYet :: IHtml assignmentNotStartedYet = do msg <- getI18N return $ do Bootstrap.rowColMd12 $ p $ fromString $ msg $ msg_SubmissionList_NonReachableAssignment "This assignment cannot be accessed." -- Creates a table line first element is a bold text and the second is a text infixl 7 .|. name .|. value = H.tr $ do H.td $ b $ fromString $ name H.td $ fromString value
pgj/bead
src/Bead/View/Content/SubmissionList/Page.hs
bsd-3-clause
5,325
0
26
1,283
1,346
688
658
108
4
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE CPP #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE DeriveDataTypeable #-} import Prelude import Yesod import Data.Text (Text) import Data.Time import Data.List ((\\)) import Data.Typeable (Typeable) import Database.Persist import Database.Persist.Sql (runMigration) import Database.Persist.Sqlite (runSqlite) import Database.Persist.TH import Database.Persist.Quasi import Control.Monad.IO.Class (liftIO) -- 移行元と移行先両方のスキーマを定義 share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User ident Text password Text Maybe salt Text UniqueUser ident deriving Typeable Article memberName Text user UserId title Text permaLink Text content Html createdOn UTCTime updatedOn UTCTime publishedOn UTCTime approved Bool count Int promoteHeadline Bool deriving Comment commenter Text user UserId body Textarea createdAt UTCTime updatedAt UTCTime articleId ArticleId deriving |] -- 移行元データベース database1 = "nomnichi.sqlite3" -- 移行先tempデータベース database2 = "temp_nomnichi.sqlite3" -- 移行元DBからデータを取得 getUsers = runSqlite database1 $ do users <- selectList [] [Asc UserId] return(users) getArticles = runSqlite database1 $ do articles <- selectList [] [Asc ArticleId] return(articles) getComments = runSqlite database1 $ do comments <- selectList [] [Asc CommentId] return(comments) -- 移行処理 main :: IO () main = runSqlite database2 $ do runMigration migrateAll users <- getUsers articles <- getArticles comments <- getComments let setUserTuple = zip (fmap entityKey users) (fmap (userIdent . entityVal) users) getUserIdFromUserName name = findVal name setUserTuple findVal val [] = (read "Key {unKey = PersistInt64 0}") :: UserId findVal val ((k,v):xs) | val == v = k | otherwise = findVal val xs insertComment x = insert $ Comment { commentCommenter = commentCommenter x, commentUser = getUserIdFromUserName $ commentCommenter x, commentBody = commentBody x, commentCreatedAt = commentCreatedAt x, commentUpdatedAt = commentUpdatedAt x, commentArticleId = commentArticleId x } insertArticle x = insertKey (entityKey x) $ Article { articleMemberName = (articleMemberName . entityVal) x, articleUser = getUserIdFromUserName $ (articleMemberName . entityVal )x, articleTitle = (articleTitle . entityVal) x, articlePermaLink = (articlePermaLink . entityVal) x, articleContent = (articleContent . entityVal) x, articleCreatedOn = (articleCreatedOn . entityVal) x, articleUpdatedOn = (articleUpdatedOn . entityVal) x, articlePublishedOn = (articlePublishedOn . entityVal) x, articleApproved = (articleApproved . entityVal) x, articleCount = (articleCount . entityVal) x, articlePromoteHeadline = (articlePromoteHeadline . entityVal) x } mapM_ insert $ fmap entityVal users mapM_ insertArticle articles mapM_ insertComment $ fmap entityVal comments return()
SuetakeY/nomnichi_yesod
db_migrate_first_20141016.hs
bsd-2-clause
3,686
5
17
867
781
404
377
72
2
-- test reification of explicit foralls in type families {-# LANGUAGE TypeFamilies, ExplicitForAll #-} module TH_reifyExplicitForAllFams where import System.IO import Language.Haskell.TH import Text.PrettyPrint.HughesPJ import Data.Proxy import Data.Kind $([d| data family F a data instance forall a. F (Maybe a) = MkF a |]) $([d| class C a where type G a b instance forall a. C [a] where type forall b. G [a] b = Proxy b |]) $([d| type family H a b where forall x y. H [x] (Proxy y) = Either x y forall z. H z z = Maybe z |]) $(return []) test :: () test = $(let display :: Name -> Q () display q = do { i <- reify q; runIO $ hPutStrLn stderr (pprint i) } in do { display ''F ; display ''C ; display ''G ; display ''H ; [| () |] })
sdiehl/ghc
testsuite/tests/th/TH_reifyExplicitForAllFams.hs
bsd-3-clause
853
0
16
264
197
107
90
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} module IHaskell.Display.Widgets.Selection.Select ( -- * The Select Widget Select, -- * Constructor mkSelect) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Control.Monad (when, join, void) import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.IORef (newIORef) import Data.Text (Text) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common -- | A 'Select' represents a Select widget from IPython.html.widgets. type Select = IPythonWidget SelectType -- | Create a new Select widget mkSelect :: IO Select mkSelect = do -- Default properties, with a random uuid uuid <- U.random let widgetState = WidgetState $ defaultSelectionWidget "SelectView" stateIO <- newIORef widgetState let widget = IPythonWidget uuid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the widget return widget instance IHaskellDisplay Select where display b = do widgetSendView b return $ Display [] instance IHaskellWidget Select where getCommUUID = uuid comm widget (Object dict1) _ = do let key1 = "sync_data" :: Text key2 = "selected_label" :: Text Just (Object dict2) = HM.lookup key1 dict1 Just (String label) = HM.lookup key2 dict2 opts <- getField widget Options case opts of OptionLabels _ -> void $ do setField' widget SelectedLabel label setField' widget SelectedValue label OptionDict ps -> case lookup label ps of Nothing -> return () Just value -> void $ do setField' widget SelectedLabel label setField' widget SelectedValue value triggerSelection widget
artuuge/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Selection/Select.hs
mit
2,163
0
17
554
474
248
226
51
1
{-| Module: Tidl.Generate.Pretty Description: Helpers for the pretty-printer Copyright 2015, Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Tidl.Generate.Pretty where import Control.Monad.Trans.State.Strict import Control.Applicative import Text.PrettyPrint as PP type Printer = State Doc runPrinter :: Printer a -> PP.Doc runPrinter f = snd (runState f PP.empty) sayln :: Doc -> Printer () sayln d' = modify (\d -> d $+$ d') sayln' :: String -> Printer() sayln' s' = sayln (PP.text s') in_braces :: Doc -> Doc in_braces x = lbrace $+$ (nest 2 x) $+$ rbrace in_parens :: Doc -> Doc in_parens x = lparen <> (nest 2 x) <> rparen vsepBy :: [Doc] -> Doc -> Doc vsepBy xs s = vcat $ punctuate s (filter (not . isEmpty) xs) sepBy :: [Doc] -> Doc -> Doc sepBy xs s = hsep $ punctuate s (filter (not . isEmpty) xs)
VishalRohra/orp
software/tools/tidl/src/Tidl/Generate/Pretty.hs
apache-2.0
1,348
0
10
264
308
163
145
19
1
{-# LANGUAGE DerivingVia #-} {-# LANGUAGE StandaloneDeriving #-} module DerivingViaFail2 where class C a data A = A deriving via Maybe instance C A
sdiehl/ghc
testsuite/tests/deriving/should_fail/deriving-via-fail2.hs
bsd-3-clause
149
0
5
25
32
18
14
-1
-1
module Main where import Test.Tasty import Test.Tasty.Options import qualified UnitTests.Distribution.Client.Sandbox import qualified UnitTests.Distribution.Client.UserConfig import qualified UnitTests.Distribution.Client.Targets import qualified UnitTests.Distribution.Client.GZipUtils import qualified UnitTests.Distribution.Client.Dependency.Modular.PSQ import qualified UnitTests.Distribution.Client.Dependency.Modular.Solver tests :: TestTree tests = testGroup "Unit Tests" [ testGroup "UnitTests.Distribution.Client.UserConfig" UnitTests.Distribution.Client.UserConfig.tests ,testGroup "Distribution.Client.Sandbox" UnitTests.Distribution.Client.Sandbox.tests ,testGroup "Distribution.Client.Targets" UnitTests.Distribution.Client.Targets.tests ,testGroup "Distribution.Client.GZipUtils" UnitTests.Distribution.Client.GZipUtils.tests ,testGroup "UnitTests.Distribution.Client.Dependency.Modular.PSQ" UnitTests.Distribution.Client.Dependency.Modular.PSQ.tests ,testGroup "UnitTests.Distribution.Client.Dependency.Modular.Solver" UnitTests.Distribution.Client.Dependency.Modular.Solver.tests ] -- Extra options for running the test suite extraOptions :: [OptionDescription] extraOptions = concat [ UnitTests.Distribution.Client.Dependency.Modular.Solver.options ] main :: IO () main = defaultMainWithIngredients (includingOptions extraOptions : defaultIngredients) tests
trskop/cabal
cabal-install/tests/UnitTests.hs
bsd-3-clause
1,470
0
8
177
221
143
78
30
1
{-# LANGUAGE TypeFamilies #-} module A2 where type family F a type instance F Int = Bool
olsner/ghc
testsuite/tests/driver/recomp016/A2.hs
bsd-3-clause
89
0
4
17
21
14
7
4
0
{-# LANGUAGE TypeFamilies, PolyKinds #-} module T11361a where class C a where type F (a :: k) :: * type F (x :: *) = x -- Not right!
ezyang/ghc
testsuite/tests/indexed-types/should_compile/T11361a.hs
bsd-3-clause
142
0
8
38
43
27
16
5
0
{-# LANGUAGE DeriveGeneric #-} module GenCannotDoRep1_3 where import GHC.Generics -- We do not support occurrences of the type variable except as the last -- argument data B a b = B (a, b) data T a = T (B a Int) deriving Generic1
olsner/ghc
testsuite/tests/generics/GenCannotDoRep1_3.hs
bsd-3-clause
240
0
8
53
50
32
18
5
0
{-# LANGUAGE GADTs #-} module ShouldCompile where data T where T1 :: Int -> T T2 :: Bool -> Bool -> T data S a where S1 :: a -> S a S2 :: Int -> S Int f (T1 i) = i>0 f (T2 a b) = a && b g :: S a -> a g (S1 x) = x g (S2 i) = i
urbanslug/ghc
testsuite/tests/gadt/gadt3.hs
bsd-3-clause
239
0
7
80
138
74
64
13
1
import System.Environment main = do [x] <- getArgs print (read x < (1e400 :: Double)) print (read x < (-1e400 :: Double)) print (read x == (0/0 :: Double)) -- the last doesn't get constant-folded to NaN, so we're not really -- testing properly here. Still, we might manage to constant fold -- this in the future, so I'll leave it in place.
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/codeGen/should_run/T1861.hs
bsd-3-clause
402
0
11
125
96
50
46
5
1
-- Mathematics/Fundamentals/Is Fibo {-# language TypeApplications #-} module HackerRank.Mathematics.IsFibo where import Sandbox.Util import Sandbox.Util.IO data IF = IsFibo | IsNotFibo deriving (Show) mkIF :: Bool -> IF mkIF True = IsFibo mkIF False = IsNotFibo main :: IO () main = do xs <- readInput @Integer let ifs = map (mkIF . isFib fibs) xs sequence_ $ map print ifs
4e6/sandbox
haskell/HackerRank/Mathematics/IsFibo.hs
mit
385
0
13
71
125
66
59
13
1
{-# htermination tanh :: Float -> Float #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_tanh_1.hs
mit
44
0
2
8
3
2
1
1
0
{-# LANGUAGE OverloadedStrings, TypeOperators, FlexibleContexts, FlexibleInstances, ExistentialQuantification #-} module Wf.Network.Wai ( FromWaiRequest(..) , ToWaiResponse(..) , toWaiApplication , UrlEncoded(..) ) where import Control.Exception (throwIO) import qualified Data.ByteString.Lazy as L (ByteString, empty, fromStrict) import qualified Data.ByteString.Lazy.Char8 as L (unpack) import qualified Data.Text.Encoding as T (encodeUtf8) import qualified Data.Aeson as DA (ToJSON, FromJSON, encode, decode) import qualified Network.Wai as Wai (Application, Request, httpVersion, requestMethod, requestHeaders, requestBody, strictRequestBody, pathInfo, rawPathInfo, queryString, rawQueryString, isSecure, remoteHost, strictRequestBody, Response, responseLBS, responseFile) import qualified Network.HTTP.Types as HTTP (parseQuery, renderQuery, hContentType) import Wf.Network.Http.Types (Request(..), Response(..), ResponseFilePath(..), UrlEncoded(..), JsonRequest(..), JsonResponse(..), JsonParseError(..), defaultResponse) import Wf.Network.Http.Response (json) toWaiApplication :: (FromWaiRequest request, ToWaiResponse response) => (request -> IO response) -> Wai.Application toWaiApplication app w respond = fromWaiRequest w >>= app >>= respond . toWaiResponse class FromWaiRequest a where fromWaiRequest :: Wai.Request -> IO a class ToWaiResponse a where toWaiResponse :: a -> Wai.Response instance FromWaiRequest (Wai.Request) where fromWaiRequest = return instance FromWaiRequest (Request L.ByteString) where fromWaiRequest w = return . fromWaiRequest' w =<< Wai.strictRequestBody w instance FromWaiRequest (Request ()) where fromWaiRequest = return . flip fromWaiRequest' () instance FromWaiRequest (Request UrlEncoded) where fromWaiRequest w = return . fromWaiRequest' w . UrlEncoded . HTTP.parseQuery =<< Wai.requestBody w instance DA.FromJSON a => FromWaiRequest (Request (JsonRequest a)) where fromWaiRequest w = do b <- Wai.strictRequestBody w case DA.decode b of Just a -> return . fromWaiRequest' w $ a Nothing -> throwIO . JsonParseError $ "cannot decode json: " ++ L.unpack b instance DA.FromJSON a => FromWaiRequest (JsonRequest a) where fromWaiRequest w = do b <- Wai.strictRequestBody w case DA.decode b of Just a -> return a Nothing -> throwIO . JsonParseError $ "cannot decode json: " ++ L.unpack b fromWaiRequest' :: Wai.Request -> body -> Request body fromWaiRequest' w b = Request { requestHttpVersion = Wai.httpVersion w , requestMethod = Wai.requestMethod w , requestHeaders = Wai.requestHeaders w , requestPath = fmap T.encodeUtf8 . Wai.pathInfo $ w , requestRawPath = Wai.rawPathInfo w , requestQuery = Wai.queryString w , requestRawQuery = Wai.rawQueryString w , requestRemoteHost = Wai.remoteHost w , requestIsSecure = Wai.isSecure w , requestBody = b } instance ToWaiResponse Wai.Response where toWaiResponse = id instance ToWaiResponse (Response L.ByteString) where toWaiResponse res = Wai.responseLBS (responseStatus res) (responseHeaders res) (responseBody res) instance ToWaiResponse (Response ()) where toWaiResponse res = Wai.responseLBS (responseStatus res) (responseHeaders res) L.empty instance ToWaiResponse (Response ResponseFilePath) where toWaiResponse res = Wai.responseFile (responseStatus res) (responseHeaders res) (unResponseFilePath $ responseBody res) Nothing instance ToWaiResponse (Response UrlEncoded) where toWaiResponse res = Wai.responseLBS (responseStatus res) headers b where b = L.fromStrict . HTTP.renderQuery False . unUrlEncoded . responseBody $ res headers = (HTTP.hContentType, "application/x-www-form-urlencoded") : responseHeaders res instance DA.ToJSON a => ToWaiResponse (Response (JsonResponse a)) where toWaiResponse res = toWaiResponse res' where b = DA.encode . responseBody $ res res' = json b res instance DA.ToJSON a => ToWaiResponse (JsonResponse a) where toWaiResponse a = toWaiResponse . json (DA.encode a) . defaultResponse $ ()
bigsleep/Wf
src/Wf/Network/Wai.hs
mit
4,185
0
13
746
1,230
661
569
74
1
import LTL main :: IO () main = putStrLn "Hello World"
jrraymond/ltl
app/Main.hs
mit
57
0
6
13
22
11
11
3
1
-- | -- Module: Math.NumberTheory.EisensteinIntegers -- Copyright: (c) 2018 Alexandre Rodrigues Baldé -- Licence: MIT -- Maintainer: Alexandre Rodrigues Baldé <[email protected]> -- -- This module exports functions for manipulating Eisenstein integers, including -- computing their prime factorisations. -- {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} module Math.NumberTheory.Quadratic.EisensteinIntegers ( EisensteinInteger(..) , ω , conjugate , norm , associates , ids -- * Primality functions , findPrime , primes ) where import Prelude hiding (quot, quotRem, gcd) import Control.DeepSeq import Data.Coerce import Data.Euclidean import Data.List (mapAccumL, partition) import Data.Maybe import Data.Ord (comparing) import qualified Data.Semiring as S import GHC.Generics (Generic) import Math.NumberTheory.Moduli.Sqrt import Math.NumberTheory.Primes.Types import qualified Math.NumberTheory.Primes as U import Math.NumberTheory.Utils (mergeBy) import Math.NumberTheory.Utils.FromIntegral infix 6 :+ -- | An Eisenstein integer is @a + bω@, where @a@ and @b@ are both integers. data EisensteinInteger = !Integer :+ !Integer deriving (Eq, Ord, Generic) instance NFData EisensteinInteger -- | The imaginary unit for Eisenstein integers, where -- -- > ω == (-1/2) + ((sqrt 3)/2)ι == exp(2*pi*ι/3) -- and @ι@ is the usual imaginary unit with @ι² == -1@. ω :: EisensteinInteger ω = 0 :+ 1 instance Show EisensteinInteger where show (a :+ b) | b == 0 = show a | a == 0 = s ++ b' | otherwise = show a ++ op ++ b' where b' = if abs b == 1 then "ω" else show (abs b) ++ "*ω" op = if b > 0 then "+" else "-" s = if b > 0 then "" else "-" instance Num EisensteinInteger where (+) (a :+ b) (c :+ d) = (a + c) :+ (b + d) (*) (a :+ b) (c :+ d) = (a * c - b * d) :+ (b * (c - d) + a * d) abs = fst . absSignum negate (a :+ b) = (-a) :+ (-b) fromInteger n = n :+ 0 signum = snd . absSignum instance S.Semiring EisensteinInteger where plus = (+) times = (*) zero = 0 :+ 0 one = 1 :+ 0 fromNatural n = fromIntegral n :+ 0 instance S.Ring EisensteinInteger where negate = negate -- | Returns an @EisensteinInteger@'s sign, and its associate in the first -- sextant. absSignum :: EisensteinInteger -> (EisensteinInteger, EisensteinInteger) absSignum 0 = (0, 0) absSignum z@(a :+ b) -- first sextant: 0 ≤ Arg(z) < π/3 | a > b && b >= 0 = (z, 1) -- second sextant: π/3 ≤ Arg(z) < 2π/3 | b >= a && a > 0 = (b :+ (b - a), 1 :+ 1) -- third sextant: 2π/3 ≤ Arg(z) < π | b > 0 && 0 >= a = ((b - a) :+ (-a), 0 :+ 1) -- fourth sextant: -π ≤ Arg(z) < -2π/3 | a < b && b <= 0 = (-z, -1) -- fifth sextant: -2π/3 ≤ Arg(η) < -π/3 | b <= a && a < 0 = ((-b) :+ (a - b), (-1) :+ (-1)) -- sixth sextant: -π/3 ≤ Arg(η) < 0 | otherwise = ((a - b) :+ a, 0 :+ (-1)) -- | List of all Eisenstein units, counterclockwise across all sextants, -- starting with @1@. ids :: [EisensteinInteger] ids = take 6 (iterate ((1 + ω) *) 1) -- | Produce a list of an @EisensteinInteger@'s associates. associates :: EisensteinInteger -> [EisensteinInteger] associates e = map (e *) ids instance GcdDomain EisensteinInteger instance Euclidean EisensteinInteger where degree = fromInteger . norm quotRem x (d :+ 0) = quotRemInt x d quotRem x y = (q, x - q * y) where (q, _) = quotRemInt (x * conjugate y) (norm y) quotRemInt :: EisensteinInteger -> Integer -> (EisensteinInteger, EisensteinInteger) quotRemInt z 1 = ( z, 0) quotRemInt z (-1) = (-z, 0) quotRemInt (a :+ b) c = (qa :+ qb, (ra - bumpA) :+ (rb - bumpB)) where halfC = abs c `quot` 2 bumpA = signum a * halfC bumpB = signum b * halfC (qa, ra) = (a + bumpA) `quotRem` c (qb, rb) = (b + bumpB) `quotRem` c -- | Conjugate a Eisenstein integer. conjugate :: EisensteinInteger -> EisensteinInteger conjugate (a :+ b) = (a - b) :+ (-b) -- | The square of the magnitude of a Eisenstein integer. norm :: EisensteinInteger -> Integer norm (a :+ b) = a*a - a * b + b*b -- | Checks if a given @EisensteinInteger@ is prime. @EisensteinInteger@s -- whose norm is a prime congruent to @0@ or @1@ modulo 3 are prime. -- See <http://thekeep.eiu.edu/theses/2467 Bandara, Sarada, "An Exposition of the Eisenstein Integers" (2016)>, -- page 12. isPrime :: EisensteinInteger -> Bool isPrime e | e == 0 = False -- Special case, @1 - ω@ is the only Eisenstein prime with norm @3@, -- and @abs (1 - ω) = 2 + ω@. | a' == 2 && b' == 1 = True | b' == 0 && a' `mod` 3 == 2 = isJust $ U.isPrime a' | nE `mod` 3 == 1 = isJust $ U.isPrime nE | otherwise = False where nE = norm e a' :+ b' = abs e -- | Remove @1 - ω@ factors from an @EisensteinInteger@, and calculate that -- prime's multiplicity in the number's factorisation. divideByThree :: EisensteinInteger -> (Word, EisensteinInteger) divideByThree = go 0 where go :: Word -> EisensteinInteger -> (Word, EisensteinInteger) go !n z@(a :+ b) | r1 == 0 && r2 == 0 = go (n + 1) (q1 :+ q2) | otherwise = (n, abs z) where -- @(a + a - b) :+ (a + b)@ is @z * (2 :+ 1)@, and @z * (2 :+ 1)/3@ -- is the same as @z / (1 :+ (-1))@. (q1, r1) = divMod (a + a - b) 3 (q2, r2) = divMod (a + b) 3 -- | Find an Eisenstein integer whose norm is the given prime number -- in the form @3k + 1@. -- -- >>> import Math.NumberTheory.Primes (nextPrime) -- >>> findPrime (nextPrime 7) -- Prime 3+2*ω findPrime :: Prime Integer -> U.Prime EisensteinInteger findPrime p = case (r, sqrtsModPrime (9 * q * q - 1) p) of (1, z : _) -> Prime $ abs $ gcd (unPrime p :+ 0) ((z - 3 * q) :+ 1) _ -> error "findPrime: argument must be prime p = 6k + 1" where (q, r) = unPrime p `quotRem` 6 -- | An infinite list of Eisenstein primes. Uses primes in @Z@ to exhaustively -- generate all Eisenstein primes in order of ascending norm. -- -- * Every prime is in the first sextant, so the list contains no associates. -- * Eisenstein primes from the whole complex plane can be generated by -- applying 'associates' to each prime in this list. -- -- >>> take 10 primes -- [Prime 2+ω,Prime 2,Prime 3+2*ω,Prime 3+ω,Prime 4+3*ω,Prime 4+ω,Prime 5+3*ω,Prime 5+2*ω,Prime 5,Prime 6+5*ω] primes :: [Prime EisensteinInteger] primes = coerce $ (2 :+ 1) : mergeBy (comparing norm) l r where leftPrimes, rightPrimes :: [Prime Integer] (leftPrimes, rightPrimes) = partition (\p -> unPrime p `mod` 3 == 2) [U.nextPrime 2 ..] rightPrimes' = filter (\prime -> unPrime prime `mod` 3 == 1) $ tail rightPrimes l = [unPrime p :+ 0 | p <- leftPrimes] r = [g | p <- rightPrimes', let x :+ y = unPrime (findPrime p), g <- [x :+ y, x :+ (x - y)]] -- | [Implementation notes for factorise function] -- -- Compute the prime factorisation of a Eisenstein integer. -- -- 1. This function works by factorising the norm of an Eisenstein integer -- and then, for each prime factor, finding the Eisenstein prime whose norm -- is said prime factor with @findPrime@. -- 2. This is only possible because the norm function of the Euclidean Domain of -- Eisenstein integers is multiplicative: @norm (e1 * e2) == norm e1 * norm e2@ -- for any two @EisensteinInteger@s @e1, e2@. -- 3. In the previously mentioned work <http://thekeep.eiu.edu/theses/2467 Bandara, Sarada, "An Exposition of the Eisenstein Integers" (2016)>, -- in Theorem 8.4 in Chapter 8, a way is given to express any Eisenstein -- integer @μ@ as @(-1)^a * ω^b * (1 - ω)^c * product [π_i^a_i | i <- [1..N]]@ -- where @a, b, c, a_i@ are nonnegative integers, @N > 1@ is an integer and -- @π_i@ are Eisenstein primes. -- -- Aplying @norm@ to both sides of the equation from Theorem 8.4: -- -- 1. @norm μ = norm ( (-1)^a * ω^b * (1 - ω)^c * product [ π_i^a_i | i <- [1..N]] ) ==@ -- 2. @norm μ = norm ((-1)^a) * norm (ω^b) * norm ((1 - ω)^c) * norm (product [ π_i^a_i | i <- [1..N]]) ==@ -- 3. @norm μ = (norm (-1))^a * (norm ω)^b * (norm (1 - ω))^c * product [ norm (π_i^a_i) | i <- [1..N]] ==@ -- 4. @norm μ = (norm (-1))^a * (norm ω)^b * (norm (1 - ω))^c * product [ (norm π_i)^a_i) | i <- [1..N]] ==@ -- 5. @norm μ = 1^a * 1^b * 3^c * product [ (norm π_i)^a_i) | i <- [1..N]] ==@ -- 6. @norm μ = 3^c * product [ (norm π_i)^a_i) | i <- [1..N]] ==@ -- -- where @a, b, c, a_i@ are nonnegative integers, and @N > 1@ is an integer. -- -- The remainder of the Eisenstein integer factorisation problem is about -- finding appropriate Eisenstein primes @[e_i | i <- [1..M]]@ such that -- @map norm [e_i | i <- [1..M]] == map norm [π_i | i <- [1..N]]@ -- where @ 1 < N <= M@ are integers and @==@ is equality on sets -- (i.e.duplicates do not matter). -- -- NB: The reason @M >= N@ is because the prime factors of an Eisenstein integer -- may include a prime factor and its conjugate (both have the same norm), -- meaning the number may have more Eisenstein prime factors than its norm has -- integer prime factors. factorise :: EisensteinInteger -> [(Prime EisensteinInteger, Word)] factorise g = concat $ snd $ mapAccumL go (abs g) (U.factorise $ norm g) where go :: EisensteinInteger -> (Prime Integer, Word) -> (EisensteinInteger, [(Prime EisensteinInteger, Word)]) go z (Prime 3, e) | e == n = (q, [(Prime (2 :+ 1), e)]) | otherwise = error $ "3 is a prime factor of the norm of z = " ++ show z ++ " with multiplicity " ++ show e ++ " but (1 - ω) only divides z " ++ show n ++ "times." where -- Remove all @1 :+ (-1)@ (which is associated to @2 :+ 1@) factors -- from the argument. (n, q) = divideByThree z go z (p, e) | unPrime p `mod` 3 == 2 = let e' = e `quot` 2 in (z `quotI` (unPrime p ^ e'), [(Prime (unPrime p :+ 0), e')]) -- The @`rem` 3 == 0@ case need not be verified because the -- only Eisenstein primes whose norm are a multiple of 3 -- are @1 - ω@ and its associates, which have already been -- removed by the above @go z (3, e)@ pattern match. -- This @otherwise@ is mandatorily @`mod` 3 == 1@. | otherwise = (z', filter ((> 0) . snd) [(gp, k), (gp', k')]) where gp = findPrime p x :+ y = unPrime gp -- @gp'@ is @gp@'s conjugate. gp' = Prime (x :+ (x - y)) (k, k', z') = divideByPrime gp gp' (unPrime p) e z quotI (a :+ b) n = a `quot` n :+ b `quot` n -- | Remove @p@ and @conjugate p@ factors from the argument, where -- @p@ is an Eisenstein prime. divideByPrime :: Prime EisensteinInteger -- ^ Eisenstein prime @p@ -> Prime EisensteinInteger -- ^ Conjugate of @p@ -> Integer -- ^ Precomputed norm of @p@, of form @4k + 1@ -> Word -- ^ Expected number of factors (either @p@ or @conjugate p@) -- in Eisenstein integer @z@ -> EisensteinInteger -- ^ Eisenstein integer @z@ -> ( Word -- Multiplicity of factor @p@ in @z@ , Word -- Multiplicity of factor @conjigate p@ in @z@ , EisensteinInteger -- Remaining Eisenstein integer ) divideByPrime p p' np k = go k 0 where go :: Word -> Word -> EisensteinInteger -> (Word, Word, EisensteinInteger) go 0 d z = (d, d, z) go c d z | c >= 2, Just z' <- z `quotEvenI` np = go (c - 2) (d + 1) z' go c d z = (d + d1, d + d2, z'') where (d1, z') = go1 c 0 z d2 = c - d1 z'' = iterate (\g -> fromMaybe err $ (g * unPrime p) `quotEvenI` np) z' !! max 0 (wordToInt d2) go1 :: Word -> Word -> EisensteinInteger -> (Word, EisensteinInteger) go1 0 d z = (d, z) go1 c d z | Just z' <- (z * unPrime p') `quotEvenI` np = go1 (c - 1) (d + 1) z' | otherwise = (d, z) err = error $ "divideByPrime: malformed arguments" ++ show (p, np, k) -- | Divide an Eisenstein integer by an even integer. quotEvenI :: EisensteinInteger -> Integer -> Maybe EisensteinInteger quotEvenI (x :+ y) n | xr == 0 , yr == 0 = Just (xq :+ yq) | otherwise = Nothing where (xq, xr) = x `quotRem` n (yq, yr) = y `quotRem` n ------------------------------------------------------------------------------- -- | See the source code and Haddock comments for the @factorise@ and @isPrime@ -- functions in this module (they are not exported) for implementation -- details. instance U.UniqueFactorisation EisensteinInteger where factorise 0 = [] factorise e = coerce $ factorise e isPrime e = if isPrime e then Just (Prime e) else Nothing
cartazio/arithmoi
Math/NumberTheory/Quadratic/EisensteinIntegers.hs
mit
13,281
0
17
3,674
3,218
1,786
1,432
174
4
{-# OPTIONS_GHC -Wall #-} module Main where import Log as L -- Skip 'n' words and interpret the next one as a number. wordsToNum :: String -> Int -> Int wordsToNum s n = read ((words s) !! n) -- Return the tail of a string. dropWords :: String -> Int -> String dropWords s n = unwords ( drop n (words s)) -- Convert a line from the sample log into an object of type L.LogMessage. parseMessage :: String -> L.LogMessage parseMessage [] = L.Unknown "" parseMessage p@(x:_) = case x of 'E' -> L.LogMessage (L.Error (wordsToNum p 1)) (wordsToNum p 2) (dropWords p 3) 'W' -> L.LogMessage L.Warning (wordsToNum p 1) (dropWords p 2) 'I' -> L.LogMessage L.Info (wordsToNum p 1) (dropWords p 2) _ -> L.Unknown p -- Parse a whole logfile. parse :: String -> [LogMessage] parse s = map parseMessage (lines s) -- Insert a L.LogMessage into a sorted L.MessageTree. insert :: L.LogMessage -> L.MessageTree -> L.MessageTree insert (L.Unknown _) t = t insert m (L.Leaf) = L.Node Leaf m Leaf insert m@(L.LogMessage _ ts1 _) (L.Node lhs (L.LogMessage _ ts2 _) rhs) = case ts1 > ts2 of True -> insert m rhs _ -> insert m lhs insert _ _ = L.Leaf -- error, what do we do now? -- Construct tree sorted by timestamp. build :: [L.LogMessage] -> L.MessageTree build [] = L.Leaf build (m:l) = insert m (build l) -- Flatten the tree into a sorted list. inOrder :: L.MessageTree -> [L.LogMessage] inOrder (L.Leaf) = [] inOrder (L.Node lhs m rhs) = inOrder lhs ++ [m] ++ inOrder rhs -- Sort by increasing timestamp. sort :: [L.LogMessage] -> [L.LogMessage] sort l = inOrder (build l) -- Remove massages, that are not error with severity >= 50. filterList :: [L.LogMessage] -> [L.LogMessage] filterList [] = [] filterList (m@(L.LogMessage (Error e) _ _):l) = case e >= 50 of True -> [m] ++ filterList l _ -> filterList l filterList (_:l) = filterList l toString :: [L.LogMessage] -> [String] toString [] = [] toString (m:l) = [show m] ++ toString l -- Extracts Error messages with severity >= 50 from an _unsorted_ list. whatWentWrong :: [L.LogMessage] -> [String] whatWentWrong [] = [] whatWentWrong l = toString (filterList (sort l)) main :: IO() main = do print (parseMessage "E 2 562 help help") print (parseMessage "I 29 la la la") print (parseMessage "This is not in the right format") _ <- L.testParse parse 10 "./sample.log" a <- L.testWhatWentWrong parse whatWentWrong "./sample.log" print (unlines a)
MiroslavVitkov/voiceid
misc/hw2.hs
mit
2,741
0
12
780
935
478
457
53
4
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Exception (catch) import Control.Monad (when) import Data.ByteString.Char8 (unpack) import System.Environment (getArgs, getProgName) import System.Exit (exitFailure, exitSuccess) import Network.HTTP.Client (HttpException (..), httpLbs, newManager, parseRequest, responseStatus) import Network.HTTP.Client.TLS (mkManagerSettings) import Network.HTTP.Types.Status (statusCode, statusMessage) import Data.X509.CertificateStore (CertificateStore, readCertificateStore) import System.X509 (getSystemCertificateStore) import Network.Connection (TLSSettings (..)) import Network.TLS (ClientParams, clientShared, clientSupported, defaultParamsClient, sharedCAStore, supportedCiphers) import Network.TLS.Extra.Cipher (ciphersuite_all) main :: IO () main = do args <- getArgs let argc = length args when (argc < 2 || argc > 3) $ do prog <- getProgName putStrLn $ prog ++ " <host> <port> [ca-bundle]" exitFailure let host = args !! 0 port = args !! 1 url = "https://" ++ host ++ ":" ++ port caBundle <- if argc == 3 then do cas <- readCertificateStore (args !! 2) case cas of (Just _) -> return cas _ -> do putStrLn $ "Error: Invalid ca-bundle in " ++ args !! 2 exitFailure else fmap Just getSystemCertificateStore let params = injectCiphers . injectCA caBundle $ defaultParamsClient host "" manager <- newManager $ mkManagerSettings (TLSSettings params) Nothing request <- parseRequest url _ <- catch (doGet request manager) (\exp' -> case exp' of TlsExceptionHostPort e _ _ -> do print e putStrLn "REJECT" exitSuccess e -> do print e exitFailure ) return () where doGet request manager = do r <- httpLbs request manager let status = responseStatus r code = statusCode status msg = statusMessage status putStrLn (show code ++" "++ unpack msg) putStrLn "ACCEPT" exitSuccess injectCA :: Maybe CertificateStore -> ClientParams -> ClientParams injectCA caBundle p = case caBundle of Nothing -> p Just ca -> p { clientShared = shared { sharedCAStore = ca } } where shared = clientShared p injectCiphers :: ClientParams -> ClientParams injectCiphers p = p { clientSupported = supported { supportedCiphers = ciphersuite_all } } where supported = clientSupported p
ouspg/trytls
stubs/haskell-http-client-tls/src/Main.hs
mit
3,157
0
18
1,250
735
380
355
71
4
{-# LANGUAGE JavaScriptFFI, OverloadedStrings #-} import GHCJS.Marshal import GHCJS.Foreign import GHCJS.Types import Control.Concurrent (threadDelay) import Data.Text (pack, unpack) import Data.Default import JavaScript.JQuery (click, select) import Protocol (Request (..), Response (..)) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (newTVarIO, writeTVar, readTVar, readTVarIO) import Data.List (isPrefixOf) import Safe (readMay) foreign import javascript interruptible "jQuery.ajax('/command', {type: 'POST', contentType: 'text/plain; charset=UTF-8', data: $1}).always(function (data) { $c(data) });" sendAjax :: JSString -> IO JSString foreign import javascript safe "jQuery('#add-player-submit').click(function () { h$run(h$addPlayer($('#add-player-input').val())) })" addPlayerCallback :: IO () foreign import javascript unsafe "jQuery($1).val()" getValue :: JSString -> IO JSString foreign import javascript unsafe "jQuery($1).val('')" clearValue :: JSString -> IO JSString foreign import javascript unsafe "jQuery($1).html($2)" setHtml :: JSString -> JSString -> IO () foreign import javascript unsafe "jQuery($1).hide()" hideElement :: JSString -> IO () foreign import javascript unsafe "jQuery($1).show()" showElement :: JSString -> IO () main = do playerName <- newTVarIO "" messages <- newTVarIO [] setup playerName loop playerName messages loop playerName messages = do updatePlayerList updateChat playerName messages threadDelay 1000000 loop playerName messages updateChat playerName messages = do name <- readTVarIO playerName if null name then return () else do result <- sendCommand $ ChatUpdatesRequest name case result of ChatUpdatesResponse newMessages -> do messages <- atomically $ do existingMessages <- readTVar messages let finalMessages = take 10 $ existingMessages ++ newMessages writeTVar messages finalMessages return finalMessages setHtml "#chat-messages" $ toJSString $ concatMap (wrapLi) messages _ -> return () setup playerName = do playerSubmitButton <- select "#add-player-submit" click (addPlayer playerName) def playerSubmitButton commandSubmitButton <- select "#command-submit" click (submitCommand playerName) def commandSubmitButton return () addPlayer playerName _ = do hideElement "#add-player" name <- getValue "#add-player-input" atomically $ writeTVar playerName (fromJSString name) showElement "#command" sendCommand $ AddPlayerRequest $ fromJSString name return () submitCommand playerName _ = do currentCommand <- getValue "#command-input" clearValue "#command-input" processCommand playerName $ fromJSString currentCommand return () processCommand playerName commandString | isPrefixOf "say " commandString = say playerName commandString | otherwise = return () say playerName commandString = do name <- readTVarIO playerName sendCommand $ ChatMessageRequest name $ dropWhile (== ' ') $ drop 3 commandString return () sendCommand :: Request -> IO Response sendCommand command = do result <- sendAjax $ toJSString $ show command let responseText = fromJSString result case readMay responseText of Just a -> return a Nothing -> print ("Error response " ++ responseText ++ " for command " ++ show command) >> return (ErrorResponse responseText) updatePlayerList = do result <- sendCommand PlayerListRequest case result of (PlayerListResponse names) -> do setHtml "#current-players" $ toJSString $ concatMap (wrapLi) names return () _ -> putStrLn $ "Got an invalid response of " ++ show result ++ " to command PlayerListRequest" wrapLi x = "<li>" ++ x ++ "</li>"
MichaelBaker/sartorial-client
src/Main.hs
mit
3,924
16
25
827
1,020
480
540
-1
-1
module Geometry ( sphereVolume , sphereArea , cubeVolume , cubeArea , cuboidArea , cuboidVolume ) where sphereVolume :: Float -> Float sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3) sphereArea :: Float -> Float sphereArea radius = 4 * pi * (radius ^ 2) cubeVolume :: Float -> Float cubeVolume side = cuboidVolume side side side cubeArea :: Float -> Float cubeArea side = cuboidArea side side side cuboidVolume :: Float -> Float -> Float -> Float cuboidVolume a b c = rectArea a b * c cuboidArea :: Float -> Float -> Float -> Float cuboidArea a b c = rectArea a b * 2 + rectArea a c * 2 + rectArea c b * 2 rectArea :: Float -> Float -> Float rectArea a b = a * b
rglew/lyah
Geometry.hs
mit
684
0
10
151
272
142
130
21
1
module Storyteller.Parser ( eol , escaping , stringWithout ) where import Control.Applicative import Storyteller.Symbols ( esc ) import Text.ParserCombinators.Parsec hiding ( (<|>), many, optional ) eol :: GenParser Char st () eol = try (newline *> pure ()) <|> eof -- Parses a character not present in `chars`, unless escaped with a backslash. -- If escaped, unescapes the character in the parsed string. escaping :: String -> GenParser Char st Char escaping chars = try (char esc *> char esc) <|> try (char esc *> oneOf chars) <|> noneOf chars <?> "None of " ++ show chars ++ " (unless escaped)" stringWithout :: String -> GenParser Char st String stringWithout = many1 . escaping
Soares/Storyteller.hs
src/Storyteller/Parser.hs
mit
741
0
13
172
199
106
93
16
1
module Feature.CorsSpec where -- {{{ Imports import Test.Hspec import Test.Hspec.Wai import Network.Wai.Test (SResponse(simpleHeaders, simpleBody)) import qualified Data.ByteString.Lazy as BL import SpecHelper import Network.HTTP.Types import Network.Wai (Application) import Protolude -- }}} spec :: SpecWith Application spec = describe "CORS" $ do let preflightHeaders = [ ("Accept", "*/*"), ("Origin", "http://example.com"), ("Access-Control-Request-Method", "POST"), ("Access-Control-Request-Headers", "Foo,Bar") ] let normalCors = [ ("Host", "localhost:3000"), ("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0"), ("Origin", "http://localhost:8000"), ("Accept", "text/csv, */*; q=0.01"), ("Accept-Language", "en-US,en;q=0.5"), ("Accept-Encoding", "gzip, deflate"), ("Referer", "http://localhost:8000/"), ("Connection", "keep-alive") ] describe "preflight request" $ do it "replies naively and permissively to preflight request" $ do r <- request methodOptions "/items" preflightHeaders "" liftIO $ do let respHeaders = simpleHeaders r respHeaders `shouldSatisfy` matchHeader "Access-Control-Allow-Origin" "http://example.com" respHeaders `shouldSatisfy` matchHeader "Access-Control-Allow-Credentials" "true" respHeaders `shouldSatisfy` matchHeader "Access-Control-Allow-Methods" "GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD" respHeaders `shouldSatisfy` matchHeader "Access-Control-Allow-Headers" "Authentication, Foo, Bar, Accept, Accept-Language, Content-Language" respHeaders `shouldSatisfy` matchHeader "Access-Control-Max-Age" "86400" it "suppresses body in response" $ do r <- request methodOptions "/" preflightHeaders "" liftIO $ simpleBody r `shouldBe` "" describe "regular request" $ it "exposes necesssary response headers" $ do r <- request methodGet "/items" [("Origin", "http://example.com")] "" liftIO $ simpleHeaders r `shouldSatisfy` matchHeader "Access-Control-Expose-Headers" "Content-Encoding, Content-Location, Content-Range, Content-Type, \ \Date, Location, Server, Transfer-Encoding, Range-Unit" describe "postflight request" $ it "allows INFO body through even with CORS request headers present" $ do r <- request methodOptions "/items" normalCors "" liftIO $ do simpleHeaders r `shouldSatisfy` matchHeader "Access-Control-Allow-Origin" "\\*" simpleBody r `shouldSatisfy` BL.null
begriffs/postgrest
test/Feature/CorsSpec.hs
mit
2,840
0
20
728
514
275
239
62
1
{-# LANGUAGE QuasiQuotes #-} {-| Module : BreadU.Pages.JS.Own Description : Own JavaScript. Stability : experimental Portability : POSIX Owr own JavaScript. The core idea is to keep our JavaScript as simple as possible. For example, we don't build DOM here, but in Haskell side only, because of compilation guarantees. I prefer AJAX-requests because of simplicity and efficiency. -} module BreadU.Pages.JS.Own ( ownJS , removeDOMItemBy , ajaxPOST ) where import Text.Jasmine ( minify ) import Data.Text ( Text ) import Data.Text.Encoding ( encodeUtf8, decodeUtf8 ) import Data.ByteString.Lazy ( toStrict, fromStrict ) import Data.String.QQ import Data.Monoid ( (<>) ) -- | Our own JavaScript as a 'Text'. ownJS :: Text ownJS = minifyJS [s| // Submits food form via AJAX POST-request. function submitFoodForm( langCode ) { var foodFormId = "#FoodFormId" + langCode; $( foodFormId ).submit(function( event ) { event.preventDefault(); // Stop form from submitting normally. // Send main food form via AJAX POST-request. $.post( langCode + "/calculate", $( foodFormId ).serialize(), function( result ) { // Shows calculated results if they're here. if ( result.results.length > 0 ) { // We know that total BU value is always first element. var totalBUArr = jQuery.makeArray( result.results[0] ); var totalBUId = "#" + totalBUArr[0]; var totalBUValue = totalBUArr[1]; $( totalBUId ).delay( 200 ).text( totalBUValue ); // Slice to miss the first element because it's already handled. $.each( result.results.slice(1), function( i, idAndValue ) { var arr = jQuery.makeArray( idAndValue ); var inputId = "#" + arr[0]; var value = arr[1]; // Delay 200 ms is for Bootstrap dynamic label movement. $( inputId ).focus().delay( 200 ).val( value ); }); } // Shows errors if they're here. $.each( result.badInputs, function( i, idAndMessage ) { var arr = jQuery.makeArray( idAndMessage ); var inputId = "#" + arr[0]; var errorTitle = arr[1]; var errorMessage = arr[2]; $( inputId ).popover({ 'placement': 'top', 'title': errorTitle, 'content': errorMessage }); $( inputId ).popover( 'toggle' ); // Hide popover after user click to this input to correct an invalid value. $( inputId ).click(function(e) { $( inputId ).popover( 'dispose' ); }); $( inputId ).change(function(e) { $( inputId ).popover( 'dispose' ); }); }); }); }); } $(document).ready( function() { submitFoodForm("en"); // Submits food form, with English-localized results. submitFoodForm("de"); // Submits food form, with German-localized results. submitFoodForm("ru"); // Submits food form, with Russian-localized results. // User began type food name. Send AJAX POST-request for autocomplete suggestions. $('body').on('keyup', 'input.FoodInputClass', function() { var idOfThisInput = "#" + this.id; var datalistForThisInput = idOfThisInput + "datalist"; var valueOfInput = $( this ).val(); // If the input's value is empty - just skip it. if ( !valueOfInput ) { $( datalistForThisInput ).find('option').remove().end(); // Remove all previous suggestions. return; } var inputedFoodInfo = { foodNamePart : valueOfInput, currentURL : $( location ).attr('href') }; $.post({ url: "autocomplete", data: JSON.stringify( inputedFoodInfo ), success: function( result ) { // Find id of corresponding food input. $( datalistForThisInput ).find('option').remove().end(); // Remove all previous suggestions. $( datalistForThisInput ).append( result.suggestionsHTML ); // Add current suggestions. }, dataType: "json", contentType: "application/json; charset=UTF-8" }); }); }); |] -- | Minify JS. minifyJS :: Text -> Text minifyJS = decodeUtf8 . toStrict . minify . fromStrict . encodeUtf8 -- | Remove DOM item by its id, via jQuery remove() method. removeDOMItemBy :: Text -> Text removeDOMItemBy anId = "$( \"#" <> anId <> "\" ).remove()" -- | AJAX POST-request, via jQuery post() method. -- Callback if OK uses response argument. ajaxPOST :: Text -> Text -> Text ajaxPOST url callbackIfOK = "$.post({ url: '" <> url <> "', success: function(response) { " <> callbackIfOK <> " } })"
denisshevchenko/breadu.info
src/lib/BreadU/Pages/JS/Own.hs
mit
4,974
0
8
1,538
203
122
81
20
1
{-| Module : BreadU.Tools.Validators Description : Validators for food values. Stability : experimental Portability : POSIX Validators for all food values submitted by user. -} module BreadU.Tools.Validators ( valueOfCarbsIsValid , minCarbs , maxCarbs , validate ) where import BreadU.Types ( CarbPer100g , BU, Grams , BadInput , Food , FoodInfo(..) , FoodItem(..) , LangCode(..) ) import qualified BreadU.Pages.Content.Errors.Messages as M import Control.Monad.Trans.State.Strict ( State, execState, modify ) import Data.HashMap.Strict ( member ) import Data.Maybe ( isNothing , fromMaybe , mapMaybe , catMaybes ) import Data.Text.Read ( double ) import Data.Text ( Text ) import qualified Data.Text as T {-| "Log" for validation results: each validator stores its output in the bad inputs list. As you can see, we use pure State monad transformer (based on 'Identity' monad). -} type ValidationLog = State (FoodInfo, LangCode, [BadInput]) () {-| Validate food info submitted by user. The idea is very simple: we check actual info from each input and if it's bad, we form BadInput: info about the problem with localized message. This message will be shown near corresponding input as a popover. -} validate :: FoodInfo -> Food -> LangCode -> [BadInput] validate foodInfo commonFood langCode = badInputs where (_, _, badInputs) = doValidation initialState initialState = (foodInfo, langCode, []) doValidation = execState $ checkMissedValues >> checkIncorrectNumbers >> checkUnknownFood commonFood -- Run State-transformer via execState, so all checkers work within the same -- State-context they extract food info and langCode from. Checkers will store -- in this State information about the problems they found. -- | Check missed values. User must enter food (via name or carbPer100g) and quantity (in grams or in BU). checkMissedValues :: ValidationLog checkMissedValues = -- Modify values in the State-context. It's very convenient: -- we obtain current badInputs and append to it info about problems we found. modify $ \(foodInfo@FoodInfo{..}, langCode, badInputs) -> (foodInfo, langCode, badInputs ++ concatMap (inputsWithMissedValues langCode) items) where inputsWithMissedValues :: LangCode -> FoodItem -> [BadInput] inputsWithMissedValues langCode FoodItem{..} = catMaybes [badFood, badQuantity] where (foodInputId, maybeFood) = foodName (_, maybeCarbs) = carbPer100g (buInputId, maybeBU) = bu (_, maybeGrams) = grams foodIsMissed = isNothing maybeFood && isNothing maybeCarbs quantityIsMissed = isNothing maybeBU && isNothing maybeGrams badFood = if foodIsMissed then Just missedFoodMessage else Nothing badQuantity = if quantityIsMissed then Just missedQuantityMessage else Nothing -- Here's an example: -- * 'foodInputId' - an id of the input where's incorrect value. -- * 'missedFoodErrorTitle' - localized title for error message. -- * 'missedFoodErrorMessage' - localized error message. missedFoodMessage = ( foodInputId , M.missedFoodErrorTitle langCode , M.missedFoodErrorMessage langCode ) missedQuantityMessage = ( buInputId , M.missedQuantityErrorTitle langCode , M.missedQuantityErrorMessage langCode ) -- | Check incorrect numbers (negative ones or out-of-range). checkIncorrectNumbers :: ValidationLog checkIncorrectNumbers = modify $ \(foodInfo@FoodInfo{..}, langCode, badInputs) -> (foodInfo, langCode, badInputs ++ concatMap (inputsWithIncorrectNumbers langCode) items) where inputsWithIncorrectNumbers :: LangCode -> FoodItem -> [BadInput] inputsWithIncorrectNumbers langCode FoodItem{..} = catMaybes [badCarbs, badBU, badGrams] where (carbInputId, maybeCarbs) = carbPer100g (buInputId, maybeBU) = bu (gramsInputId, maybeGrams) = grams badCarbs = onlyBad valueOfCarbsIsValid carbIncorrectNumber $ fromMaybe "" maybeCarbs badBU = onlyBad valueOfBUIsValid buIncorrectNumber $ fromMaybe "" maybeBU badGrams = onlyBad valueOfGramsIsValid gramsIncorrectNumber $ fromMaybe "" maybeGrams onlyBad :: (Double -> Bool) -> BadInput -> Text -> Maybe BadInput onlyBad predicate badInput rawValue = case double (anyDecimalSeparator rawValue) of Right (number, remainingTrash) -> if | notEmpty remainingTrash -> Just badInput | not $ predicate number -> Just badInput | otherwise -> Nothing Left _ -> if | notEmpty rawValue -> Just badInput | otherwise -> Nothing anyDecimalSeparator = T.replace "," "." notEmpty = not . T.null carbIncorrectNumber = ( carbInputId , M.carbIncorrectNumberErrorTitle langCode , M.carbIncorrectNumberErrorMessage langCode minCarbs maxCarbs ) buIncorrectNumber = ( buInputId , M.buIncorrectNumberErrorTitle langCode , M.buIncorrectNumberErrorMessage langCode ) gramsIncorrectNumber = ( gramsInputId , M.gramsIncorrectNumberErrorTitle langCode , M.gramsIncorrectNumberErrorMessage langCode ) -- | Check if user inserted unknown food name(s). checkUnknownFood :: Food -> ValidationLog checkUnknownFood commonFood = modify $ \(foodInfo@FoodInfo{..}, langCode, badInputs) -> (foodInfo, langCode, badInputs ++ mapMaybe (inputsWithUnknownFood langCode) items) where inputsWithUnknownFood :: LangCode -> FoodItem -> Maybe BadInput inputsWithUnknownFood langCode FoodItem{..} = case maybeFood of Just food -> if not $ member food commonFood then Just foodUnknownName else Nothing Nothing -> Nothing where (foodInputId, maybeFood) = foodName foodUnknownName = ( foodInputId , M.foodUnknownNameErrorTitle langCode , M.foodUnknownNameErrorMessage langCode ) -- | BU value must be positive integer or decimal number. valueOfBUIsValid :: BU -> Bool valueOfBUIsValid breadUnits = breadUnits > 0.0 -- | Grams value must be positive integer or decimal number. valueOfGramsIsValid :: Grams -> Bool valueOfGramsIsValid grams = grams > 0.0 -- | Carbs value must be integer or decimal number between min and max. -- Assumed that carbs value cannot be precisely equal to 0.0 nor 100.0. -- Even white sugar has 99.98 carbs value, but not 100.0. valueOfCarbsIsValid :: CarbPer100g -> Bool valueOfCarbsIsValid carbPer100g = carbPer100g > minCarbs && carbPer100g < maxCarbs minCarbs, maxCarbs :: CarbPer100g minCarbs = 0.0 maxCarbs = 100.0
denisshevchenko/breadu.info
src/lib/BreadU/Tools/Validators.hs
mit
8,026
0
17
2,778
1,261
702
559
-1
-1
import Crypto.Cipher import Crypto.Cipher.AES import Crypto.Cipher.Types import qualified Data.ByteString as ByteString import qualified Data.ByteString.Char8 as Char8 import Data.ByteString.Base64 import Data.List.Split stringToKey string = result where keyBytes = Char8.pack string Right key = makeKey keyBytes :: Either KeyError (Key AES128) result = key realMain byteString = putStrLn result where bytes = ByteString.unpack byteString blocks = map ByteString.pack (chunksOf 16 bytes) key = stringToKey "YELLOW SUBMARINE" aes = cipherInit key plaintextBlocks = map (\ block -> ecbDecrypt aes block) blocks stringBlocks = map Char8.unpack plaintextBlocks result = concat stringBlocks main :: IO() main = do lines <- ByteString.readFile "7.txt" let base64 = Char8.filter (\ c -> not (c == '\n')) lines let bytes = decode base64 (either putStrLn realMain bytes)
mozkeeler/cryptopals
set1/challenge7/aes.hs
mit
939
0
15
195
286
149
137
24
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-apistage.html module Stratosphere.ResourceProperties.ApiGatewayUsagePlanApiStage where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.ApiGatewayUsagePlanThrottleSettings -- | Full data type definition for ApiGatewayUsagePlanApiStage. See -- 'apiGatewayUsagePlanApiStage' for a more convenient constructor. data ApiGatewayUsagePlanApiStage = ApiGatewayUsagePlanApiStage { _apiGatewayUsagePlanApiStageApiId :: Maybe (Val Text) , _apiGatewayUsagePlanApiStageStage :: Maybe (Val Text) , _apiGatewayUsagePlanApiStageThrottle :: Maybe (Map Text ApiGatewayUsagePlanThrottleSettings) } deriving (Show, Eq) instance ToJSON ApiGatewayUsagePlanApiStage where toJSON ApiGatewayUsagePlanApiStage{..} = object $ catMaybes [ fmap (("ApiId",) . toJSON) _apiGatewayUsagePlanApiStageApiId , fmap (("Stage",) . toJSON) _apiGatewayUsagePlanApiStageStage , fmap (("Throttle",) . toJSON) _apiGatewayUsagePlanApiStageThrottle ] -- | Constructor for 'ApiGatewayUsagePlanApiStage' containing required fields -- as arguments. apiGatewayUsagePlanApiStage :: ApiGatewayUsagePlanApiStage apiGatewayUsagePlanApiStage = ApiGatewayUsagePlanApiStage { _apiGatewayUsagePlanApiStageApiId = Nothing , _apiGatewayUsagePlanApiStageStage = Nothing , _apiGatewayUsagePlanApiStageThrottle = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-apistage.html#cfn-apigateway-usageplan-apistage-apiid agupasApiId :: Lens' ApiGatewayUsagePlanApiStage (Maybe (Val Text)) agupasApiId = lens _apiGatewayUsagePlanApiStageApiId (\s a -> s { _apiGatewayUsagePlanApiStageApiId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-apistage.html#cfn-apigateway-usageplan-apistage-stage agupasStage :: Lens' ApiGatewayUsagePlanApiStage (Maybe (Val Text)) agupasStage = lens _apiGatewayUsagePlanApiStageStage (\s a -> s { _apiGatewayUsagePlanApiStageStage = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-apistage.html#cfn-apigateway-usageplan-apistage-throttle agupasThrottle :: Lens' ApiGatewayUsagePlanApiStage (Maybe (Map Text ApiGatewayUsagePlanThrottleSettings)) agupasThrottle = lens _apiGatewayUsagePlanApiStageThrottle (\s a -> s { _apiGatewayUsagePlanApiStageThrottle = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/ApiGatewayUsagePlanApiStage.hs
mit
2,623
0
12
256
365
208
157
33
1
import Utils.IntegerOps import Utils.ListOps import Data.Set (Set, toList, fromList, empty, insert, (\\)) main = print problem23Value problem23Value :: Integer problem23Value = sum $ toList resultSet -- to compute the result set of numbers (every positive integer which is NOT a sum of 2 abundant numbers), we take all positive integers <28123 and subtract the numbers that ARE a sum of 2 abundant numbers resultSet :: (Set Integer) resultSet = (positiveIntegers 28123) \\ numbersThatAreSumOfTwoAbundantNumbers positiveIntegers :: Integer -> (Set Integer) positiveIntegers max = fromList [1..max] -- we want to add together each pair of numbers from both lists, so long as the sum would be <= 28123 -- but we don't want duplicates, so that means that as we increment the left list, we don't care about items in the right list that are less than or equal to that number, because they've already been used -- so that means that for every i of the left list, we want every j such that i<=j<=(28123-i), or dropWhile (<i) $ takeUntil (>28123-i) $ js numbersThatAreSumOfTwoAbundantNumbers :: (Set Integer) numbersThatAreSumOfTwoAbundantNumbers = addEmUp consideredNumbers consideredNumbers where addEmUp (i:[]) [] = empty addEmUp (i:i':is) [] = addEmUp (i':is) $ takeUntil (>(28123-i')) $ dropWhile (<i') consideredNumbers addEmUp (i:is) (j:js) = insert (i+j) (addEmUp (i:is) js) consideredNumbers = takeWhile (<28123) abundantNumbers abundantNumbers :: [Integer] abundantNumbers = abundantNumbers' [1..] where abundantNumbers' (i:rem) | sumDiv > i = i:(abundantNumbers' rem) | otherwise = abundantNumbers' rem where sumDiv = sum $ properDivisors i
jchitel/ProjectEuler.hs
Problems/Problem0023.hs
mit
1,723
0
12
323
379
204
175
22
3
#!/usr/bin/env runhaskell -- Run this script from the root of the exercism checkout! module Main where import System.Exit (ExitCode(..), exitFailure) import System.Posix.Temp (mkdtemp) import System.Environment (getArgs) import System.Directory ( removeDirectoryRecursive, getTemporaryDirectory , getCurrentDirectory, setCurrentDirectory, copyFile , getDirectoryContents, removeFile ) import System.Posix.Files ( isDirectory, getFileStatus ) import Control.Exception (bracket, finally) import System.FilePath ((</>)) import System.Process (rawSystem) import Data.List (isPrefixOf, intercalate) import Data.Maybe (catMaybes) import Control.Monad (filterM) import Control.Applicative withTemporaryDirectory_ :: FilePath -> IO a -> IO a withTemporaryDirectory_ fp f = do sysTmpDir <- getTemporaryDirectory curDir <- getCurrentDirectory bracket (mkdtemp (sysTmpDir </> fp)) (\path -> setCurrentDirectory curDir >> removeDirectoryRecursive path) (\path -> setCurrentDirectory path >> f) assignmentsDir :: FilePath assignmentsDir = "." parseModule :: [String] -> String parseModule = (!!1) . words . head . filter (isPrefixOf "module ") testAssignment :: FilePath -> FilePath -> IO (Maybe String) testAssignment dir fn = do let d = dir </> fn example = d </> "example.hs" testFile = d </> (fn ++ "_test.hs") opts = ["-Wall", "-Werror", testFile] putStrLn $ "-- " ++ fn modFile <- (++ ".hs") . parseModule . lines <$> readFile example copyFile example modFile exitCode <- finally (rawSystem "runhaskell" opts) (removeFile modFile) return $ case exitCode of ExitSuccess -> Nothing _ -> Just fn getAssignments :: FilePath -> [FilePath] -> IO [FilePath] getAssignments dir = filterM isAssignmentDir where isAssignmentDir path = case path of '.':_ -> return False '_':_ -> return False "bin" -> return False _ -> isDirectory <$> getFileStatus (dir </> path) main :: IO () main = do dir <- (</> assignmentsDir) <$> getCurrentDirectory dirs <- getArgs >>= \args -> case args of [] -> getDirectoryContents dir _ -> return args withTemporaryDirectory_ "exercism-haskell" $ do failures <- catMaybes <$> (getAssignments dir dirs >>= mapM (testAssignment dir)) case failures of [] -> putStrLn "SUCCESS!" xs -> putStrLn ("Failures: " ++ intercalate ", " xs) >> exitFailure
pminten/xhaskell
_test/check-exercises.hs
mit
2,468
0
17
523
748
392
356
60
4
{- dfsbuild: CD image builder Copyright (c) 2006 John Goerzen Please see COPYRIGHT for more details -} module Bootloader.Yaboot where import Utils import System.Cmd.Utils import System.Path import System.Posix.Files import System.Posix.Directory import System.Path.Glob import Data.ConfigFile import System.FilePath yaboot env = do safeSystem "cp" ["/usr/lib/yaboot/yaboot", targetdir env ++ "/boot/"] writeFile (wdir env ++ "/hfs.map") hfsmap writeFile (targetdir env ++ "/boot/ofboot.b") ofboot newkerns <- glob $ targetdir env ++ "/boot/vmlinu*" rdparam <- getrdparam env rdsize <- getrdsize_kb env writeFile (targetdir env ++ "/boot/yaboot.conf") (yabootconf newkerns rdsize rdparam) return (["--netatalk", "-hfs", "-probe", "-hfs-unlock", "-part", "-no-desktop", "-map", wdir env ++ "/hfs.map", "-hfs-bless", targetdir env ++ "/boot", "-hfs-volid", "DFS/PPC"], postbuild) where postbuild isoname = do safeSystem "hmount" [isoname] safeSystem "hattrib" ["-b", ":boot"] safeSystem "humount" [] yabootconf klist rdsize rdparam = "## This yaboot.conf is for CD booting only. Do not use as reference.\n" ++ "debice=cd:\n" ++ concat (map (yabootitem rdsize rdparam . fst . splitFileName) klist) yabootitem rdsize rdparam kern = "image=/boot/" ++ kern ++ "\n" ++ " label=" ++ kern ++ "\n" ++ " initrd=/boot/initrd.dfs\n" ++ " initrd-size=" ++ show rdsize ++ "\n" ++ " append=\"initrd=/boot/initrd.dfs root=/dev/ram0 " ++ rdparam ++ "\"\n" ++ " read-only\n\n" ++ "# wonky fb\nimage=/boot/" ++ kern ++ "\n" ++ " label=" ++ kern ++ "-safe\n" ++ " initrd=/boot/initrd.dfs\n" ++ " initrd-size=" ++ show rdsize ++ "\n" ++ " append=\"video=ofonly initrd=/boot/initrd.dfs root=/dev/ram0 " ++ rdparam ++ "\"\n" ++ " read-only\n\n" hfsmap = "# ext. xlate creator type comment\n\ \.b Raw 'UNIX' 'tbxi' \"bootstrap\"\n\ \yaboot Raw 'UNIX' 'boot' \"bootstrap\"\n\ \.conf Raw 'UNIX' 'conf' \"bootstrap\"\n\ \* Ascii '????' '????' \"Text file\"\n"; ofboot = "<CHRP-BOOT>\n\ \<COMPATIBLE>\n\ \MacRISC MacRISC3 MacRISC4\n\ \</COMPATIBLE>\n\ \<DESCRIPTION>\n\ \GNU/Linux PPC bootloader\n\ \</DESCRIPTION>\n\ \<BOOT-SCRIPT>\n\ \\" screen\" output\n\ \load-base release-load-area\n\ \boot cd:,\\boot\\yaboot\n\ \</BOOT-SCRIPT>\n\ \<OS-BADGE-ICONS>\n\ \1010\n\ \000000000000F8FEACF6000000000000\n\ \0000000000F5FFFFFEFEF50000000000\n\ \00000000002BFAFEFAFCF70000000000\n\ \0000000000F65D5857812B0000000000\n\ \0000000000F5350B2F88560000000000\n\ \0000000000F6335708F8FE0000000000\n\ \00000000005600F600F5FD8100000000\n\ \00000000F9F8000000F5FAFFF8000000\n\ \000000008100F5F50000F6FEFE000000\n\ \000000F8F700F500F50000FCFFF70000\n\ \00000088F70000F50000F5FCFF2B0000\n\ \0000002F582A00F5000008ADE02C0000\n\ \00090B0A35A62B0000002D3B350A0000\n\ \000A0A0B0B3BF60000505E0B0A0B0A00\n\ \002E350B0B2F87FAFCF45F0B2E090000\n\ \00000007335FF82BF72B575907000000\n\ \000000000000ACFFFF81000000000000\n\ \000000000081FFFFFFFF810000000000\n\ \0000000000FBFFFFFFFFAC0000000000\n\ \000000000081DFDFDFFFFB0000000000\n\ \000000000081DD5F83FFFD0000000000\n\ \000000000081DDDF5EACFF0000000000\n\ \0000000000FDF981F981FFFF00000000\n\ \00000000FFACF9F9F981FFFFAC000000\n\ \00000000FFF98181F9F981FFFF000000\n\ \000000ACACF981F981F9F9FFFFAC0000\n\ \000000FFACF9F981F9F981FFFFFB0000\n\ \00000083DFFBF981F9F95EFFFFFC0000\n\ \005F5F5FDDFFFBF9F9F983DDDD5F0000\n\ \005F5F5F5FDD81F9F9E7DF5F5F5F5F00\n\ \0083DD5F5F83FFFFFFFFDF5F835F0000\n\ \000000FBDDDFACFBACFBDFDFFB000000\n\ \000000000000FFFFFFFF000000000000\n\ \0000000000FFFFFFFFFFFF0000000000\n\ \0000000000FFFFFFFFFFFF0000000000\n\ \0000000000FFFFFFFFFFFF0000000000\n\ \0000000000FFFFFFFFFFFF0000000000\n\ \0000000000FFFFFFFFFFFF0000000000\n\ \0000000000FFFFFFFFFFFFFF00000000\n\ \00000000FFFFFFFFFFFFFFFFFF000000\n\ \00000000FFFFFFFFFFFFFFFFFF000000\n\ \000000FFFFFFFFFFFFFFFFFFFFFF0000\n\ \000000FFFFFFFFFFFFFFFFFFFFFF0000\n\ \000000FFFFFFFFFFFFFFFFFFFFFF0000\n\ \00FFFFFFFFFFFFFFFFFFFFFFFFFF0000\n\ \00FFFFFFFFFFFFFFFFFFFFFFFFFFFF00\n\ \00FFFFFFFFFFFFFFFFFFFFFFFFFF0000\n\ \000000FFFFFFFFFFFFFFFFFFFF000000\n\ \</OS-BADGE-ICONS>\n\ \</CHRP-BOOT>\n"
jgoerzen/dfsbuild
Bootloader/Yaboot.hs
gpl-2.0
4,517
0
33
796
471
240
231
45
1
module Fun.State where import Fun.Type import Fun.Cache import Autolib.Reader import Autolib.ToDoc hiding ( empty ) import Machine.History import Data.Typeable data State = State { schritt :: Int , todo :: [ Exp ] , stack :: [ Integer ] -- die werden nicht angezeigt , past :: [ State ] , cache :: Cache Exp Integer } deriving Typeable instance History State where history = past essence s = ( todo s, stack s ) instance Eq State where x == y = essence x == essence y instance Ord State where x `compare` y = essence x `compare` essence y instance ToDoc State where toDocPrec d (State aa ab ac ad ae) = docParen (d >= 10) (named_dutch_record (text "State") [ text "schritt" <+.> equals <+.> toDocPrec 0 aa , text "todo" <+.> equals <+.> toDocPrec 0 ab , text "stack" <+.> equals <+.> toDocPrec 0 ac -- text "past" <+.> equals <+.> toDocPrec 0 ad, -- text "cache" <+.> equals <+.> toDocPrec 0 ae ]) instance Show State where show = render . toDoc
marcellussiegburg/autotool
collection/src/Fun/State.hs
gpl-2.0
1,053
23
8
283
330
182
148
27
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: $HEADER$ -- Description: Low level FFI. -- Copyright: -- License: GPL-2 -- -- Maintainer: Jan Sipr <[email protected]> -- Stability: experimental -- Portability: GHC specific language extensions. module Phone.Config ( Config(..) , Handlers(..) , Logging(..) ) where import Data.Bool (Bool) import Data.Int (Int) import Data.Maybe (Maybe) import Data.String (String) import Data.Word (Word) import GHC.Generics (Generic) import Text.Show (Show) import Data.Default (Default) import Phone.Internal.Event (Event) import Phone.Internal.FFI.Account (AccountId) import Phone.Internal.FFI.Common (CallId, PjIO) data Config = Config { handlers :: Handlers , logging :: Logging } deriving (Generic) instance Default Config data Handlers = Handlers { onCallStateChange :: Maybe (CallId -> Event -> PjIO ()) , onCallTransactionStateChange :: Maybe (CallId -> Event -> PjIO ()) , onIncomingCall :: Maybe (AccountId -> CallId -> PjIO ()) , onMediaStateChange :: Maybe (CallId -> PjIO ()) , onRegistrationStarted :: Maybe (AccountId -> Int -> PjIO ()) , onRegistrationStateChange :: Maybe (AccountId -> PjIO ()) } deriving (Generic) instance Default Handlers data Logging = Logging { logLevel :: Maybe Word , logConsoleLevel :: Maybe Word , logMsgLogging :: Maybe Bool , logFilename :: Maybe String } deriving (Show, Generic) instance Default Logging
IxpertaSolutions/hsua
src/Phone/Config.hs
gpl-2.0
1,536
0
14
311
421
244
177
38
0
{- Chapter 14.5 Exercises -} import Data.Monoid import Data.Foldable {- 1. Commented out for 'Duplicate instance declarations' instance (Monoid a, Monoid b) => Monoid (a,b) where -- mempty :: (a,b) mempty = (mempty, mempty) -- mappend :: (a,b) -> (a,b) -> (a,b) (x1,y1) `mappend` (x2,y2) = (x1 `mappend` x2, y1 `mappend` y2) -} {- 2. instance Monoid b => Monoid (a -> b) where -- mempty :: (a,b) mempty = |_ -> mempty -- mappend :: (a,b) -> (a,b) -> (a,b) f `mappend` g = x -> f x `mappend` g x -} {- 3. Not sure if this is correct: instance Foldable Maybe where -- fold :: Monoid a => Maybe a -> a fold = foldMap id -- foldMap :: Monoid b => (a -> b) -> Maybe a -> b foldMap = maybe mempty -- foldr :: (a -> b -> b) -> b -> Maybe a -> b foldr _ v Nothing = v foldr f v (Just x) = f x v -- foldl :: (b -> a -> b) -> b -> Maybe a -> b foldl _ v Nothing = v foldl f v (Just x) = f v x instance Traversable Maybe where -- traverse :: Applicative f => (a -> f b) -> Maybe a -> f (Maybe b) traverse _ Nothing = pure Nothing traverse f (Just x) = Just <$> f x -} {- 4. -} data Tree' a = Leaf' | Node' (Tree' a) a (Tree' a) deriving Show {- > (Node' (Leaf' ) (Just 5) (Leaf')) Node' Leaf' (Just 5) Leaf' > Node' (Node' Leaf' (Just 10) Leaf') (Just 15) (Node' Leaf' (Just 20) Leaf') Node' (Node' Leaf' (Just 10) Leaf') (Just 15) (Node' Leaf' (Just 20) Leaf') -} instance Foldable Tree' where -- fold :: Monoid a => Tree a -> a fold (Leaf') = mempty fold (Node' l a r) = fold l `mappend` fold r -- foldMap :: Monoid b => (a -> b) -> Tree' a -> b foldMap f (Leaf') = mempty foldMap f (Node' l a r) = foldMap f l `mappend` (f a) `mappend` foldMap f r -- foldr :: (a -> b -> b) -> b -> Tree' a -> b foldr f v (Leaf') = v foldr f v (Node' l a r) = foldr f (f a (foldr f v r)) l -- foldl :: (a -> b -> a) -> a -> Tree' b -> a foldl f v (Leaf') = v foldl f v (Node' l a r) = foldl f (f (foldl f v l) a) r instance Functor Tree' where -- fmap :: (a -> b) -> Tree' a -> Tree' b fmap g (Leaf') = Leaf' fmap g (Node' l a r) = Node' (fmap g l) (g a) (fmap g r) instance Traversable Tree' where -- traverse :: Applicative f => (a -> f b) -> Tree' a -> f (Tree' b) traverse g (Leaf') = pure Leaf' traverse g (Node' l a r) = pure Node' <*> traverse g l <*> g a <*> traverse g r {- > filterF (> Just 10) (Node' (Node' Leaf' (Just 10) Leaf') (Just 15) (Node' Leaf' (Just 20) Leaf')) [Just 15,Just 20] -} {- 5. -} data Tree a = Leaf a | Node (Tree a) (Tree a) deriving Show instance Foldable Tree where -- fold :: Monoid a => Tree a -> a fold (Leaf x) = x fold (Node l r) = fold l `mappend` fold r -- foldMap :: Monoid b => (a -> b) -> Tree a -> b foldMap f (Leaf x) = f x foldMap f (Node l r) = foldMap f l `mappend` foldMap f r -- foldr :: (a -> b -> b) -> b -> Tree a -> b foldr f v (Leaf x) = f x v foldr f v (Node l r) = foldr f (foldr f v r) l -- foldl :: (a -> b -> a) -> a -> Tree b -> a foldl f v (Leaf x) = f v x foldl f v (Node l r) = foldl f (foldl f v l) r instance Functor Tree where -- fmap :: (a -> b) -> Tree a -> Tree b fmap g (Leaf x) = Leaf (g x) fmap g (Node l r) = Node (fmap g l) (fmap g r) instance Traversable Tree where -- traverse :: Applicative f => (a -> f b) -> Tree a -> f (Tree b) traverse g (Leaf x) = pure Leaf <*> g x traverse g (Node l r) = pure Node <*> traverse g l <*> traverse g r filterF :: Foldable t => (a -> Bool) -> t a -> [a] filterF f = filter f . toList {- > filterF (> 10) [1..20] [11,12,13,14,15,16,17,18,19,20] > filterF (< Just 20) (Node (Node (Leaf (Just 10)) (Leaf (Just 15))) (Leaf (Just 20))) [Just 10,Just 15] > filterF (/= Just 2) (Node (Node (Leaf (Just 1)) (Leaf (Just 2))) (Leaf (Just 1))) [Just 1,Just 1] -}
rad1al/hutton_exercises
ch14.hs
gpl-2.0
3,974
0
10
1,176
888
453
435
38
1