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
{-# LANGUAGE OverloadedStrings #-} module MattermostBot.Data.Config where import Data.Default (Default, def) import Data.Maybe (fromJust) import Data.Text as T import qualified Data.Yaml as Y import Data.Yaml (FromJSON(..), (.:)) import Network.URL (URL, importURL) import MattermostBot.Data.Slack type GitlabApiPrivateToken = Text type GitlabSystemHookSecret= Text data BotConfig = BotConfig { _botConfigChannel :: SlackChannel , _botConfigUsername :: SlackUsername , _botConfigIconEmoij :: SlackIconEmoji , _botConfigMattermostIncoming :: URL -- | base url e.g. https://gitlab.example.com , _botConfigGitlabApiUrl :: URL , _botConfigGitlabApiPrivateToken :: GitlabApiPrivateToken , _botConfigGitlabSHSecret :: GitlabSystemHookSecret } deriving Show instance FromJSON BotConfig where parseJSON (Y.Object v) = BotConfig <$> v .: "channel" <*> v .: "username" <*> v .: "iconEmoij" <*> ((fromJust . importURL) <$> v .: "mattermostIncoming") <*> ((fromJust . importURL) <$> v .: "gitlabApiUrl") <*> v .: "gitlabApiPrivateToken" <*> v .: "gitlabSystemHookSecret" parseJSON _ = fail "Expected Object for Config value" instance Default BotConfig where def = BotConfig "TownsSquare" "λmatterbot" ":ghost:" matterMostUrl gitlabUrl "tkn" "secret" where matterMostUrl = fromJust $ importURL "mattermostIncoming" gitlabUrl = fromJust $ importURL "https://gitlab.example.com"
marcelbuesing/mattermost-bot
src/MattermostBot/Data/Config.hs
mit
1,567
0
17
364
324
188
136
35
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.MediaQueryListListener (newMediaQueryListListener, newMediaQueryListListenerSync, newMediaQueryListListenerAsync, MediaQueryListListener) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryListListener Mozilla MediaQueryListListener documentation> newMediaQueryListListener :: (MonadIO m) => (Maybe MediaQueryList -> IO ()) -> m MediaQueryListListener newMediaQueryListListener callback = liftIO (syncCallback1 ThrowWouldBlock (\ list -> fromJSRefUnchecked list >>= \ list' -> callback list')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryListListener Mozilla MediaQueryListListener documentation> newMediaQueryListListenerSync :: (MonadIO m) => (Maybe MediaQueryList -> IO ()) -> m MediaQueryListListener newMediaQueryListListenerSync callback = liftIO (syncCallback1 ContinueAsync (\ list -> fromJSRefUnchecked list >>= \ list' -> callback list')) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryListListener Mozilla MediaQueryListListener documentation> newMediaQueryListListenerAsync :: (MonadIO m) => (Maybe MediaQueryList -> IO ()) -> m MediaQueryListListener newMediaQueryListListenerAsync callback = liftIO (asyncCallback1 (\ list -> fromJSRefUnchecked list >>= \ list' -> callback list'))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/MediaQueryListListener.hs
mit
2,361
0
12
447
521
310
211
39
1
{-# LANGUAGE TemplateHaskell #-} module Text.Shakespeare.BaseSpec (spec) where import Test.Hspec import Text.Shakespeare import Text.ParserCombinators.Parsec ((<|>), ParseError, parse, runParser) import Text.Shakespeare.Base (Deref(..), Ident(..), parseDeref, parseVarString, parseUrlString, parseIntString) import Language.Haskell.TH.Syntax (Exp (VarE)) import Data.Text.Lazy.Builder (toLazyText, fromLazyText) import Data.Text.Lazy (pack) -- run :: Text.Parsec.Prim.Parsec Text.Parsec.Pos.SourceName () c -> Text.Parsec.Pos.SourceName -> c spec :: Spec spec = do let preFilterN = preFilter Nothing {- it "parseStrings" $ do run varString "%{var}" `shouldBe` Right "%{var}" run urlString "@{url}" `shouldBe` Right "@{url}" run intString "^{int}" `shouldBe` Right "^{int}" run (varString <|> urlString <|> intString) "@{url} #{var}" `shouldBe` Right "@{url}" -} it "parseDeref parse expressions with infix operator and trailing spaces" $ do runParser parseDeref () "" " a + b \t " `shouldBe` (Right (DerefBranch (DerefBranch (DerefIdent (Ident "+")) (DerefIdent (Ident "a"))) (DerefIdent (Ident "b")))) it "preFilter off" $ do preFilterN defaultShakespeareSettings template `shouldReturn` template it "preFilter on" $ do preFilterN preConversionSettings template `shouldReturn` "(function(shakespeare_var_var, shakespeare_var_url, shakespeare_var_int){unchanged shakespeare_var_var shakespeare_var_url shakespeare_var_int})(#{var}, @{url}, ^{int});\n" it "preFilter ignore quotes" $ do preFilterN preConversionSettings templateQuote `shouldReturn` "(function(shakespeare_var_url){unchanged '#{var}' shakespeare_var_url '^{int}'})(@{url});\n" it "preFilter ignore comments" $ do preFilterN preConversionSettings templateCommented `shouldReturn` "unchanged & '#{var}' @{url} '^{int}'" it "reload" $ do let helper input = $(do shakespeareFileReload defaultShakespeareSettings { toBuilder = VarE 'pack , wrap = VarE 'toLazyText , unwrap = VarE 'fromLazyText } "test/reload.txt") undefined helper "here1" `shouldBe` pack "here1\n" helper "here2" `shouldBe` pack "here2\n" where varString = parseVarString '%' urlString = parseUrlString '@' '?' intString = parseIntString '^' preConversionSettings = defaultShakespeareSettings { preConversion = Just PreConvert { preConvert = Id , preEscapeIgnoreBalanced = "'\"" , preEscapeIgnoreLine = "&" , wrapInsertion = Just WrapInsertion { wrapInsertionIndent = Nothing , wrapInsertionStartBegin = "function(" , wrapInsertionSeparator = ", " , wrapInsertionStartClose = "){" , wrapInsertionEnd = "}" , wrapInsertionAddParens = True } } } template = "unchanged #{var} @{url} ^{int}" templateQuote = "unchanged '#{var}' @{url} '^{int}'" templateCommented = "unchanged & '#{var}' @{url} '^{int}'" run parser str = eShowErrors $ parse parser str str eShowErrors :: Either ParseError c -> c eShowErrors = either (error . show) id
yesodweb/shakespeare
test/Text/Shakespeare/BaseSpec.hs
mit
3,271
0
21
746
606
330
276
63
1
module AyaScript.Parser where import AyaScript.GenES import AyaScript.Types import Text.ParserCombinators.Parsec import Text.ParserCombinators.Parsec.Expr import Text.ParserCombinators.Parsec.Language import qualified Text.ParserCombinators.Parsec.Token as P lexer :: P.TokenParser () lexer = P.makeTokenParser (haskellDef { reservedOpNames = [] }) natural = P.natural lexer parens = P.parens lexer identifier = P.identifier lexer lexeme = P.lexeme lexer compile :: String -> Either ParseError String compile x = genES <$> ayaScriptParser x ayaScriptParser :: String -> Either ParseError Program ayaScriptParser = parse program "" program :: Parser Program program = stmts <* eof stmts :: Parser [Stmt] stmts = sepBy stmt (char '\n') stmt :: Parser Stmt stmt = try declS <|> try assignS <|> exprS declS :: Parser Stmt declS = Decl <$> expr <*> (lexeme (char '=') *> expr) assignS :: Parser Stmt assignS = Assign <$> expr <*> (lexeme (string "#=") *> expr) exprS :: Parser Stmt exprS = Expr <$> expr expr :: Parser Expr expr = pipeOp exprs :: Parser [Expr] exprs = sepBy expr (lexeme (char ',')) pipeOp, mapOp, addOp, mulOp, expOp, logicOp, eqOp, compareOp, appOp, memberOp :: Parser Expr pipeOp = binOp AssocLeft ["|>"] mapOp mapOp = binOp AssocLeft ["<$>"] addOp addOp = binOp AssocLeft ["+", "-"] mulOp mulOp = binOp AssocLeft ["*", "/"] expOp expOp = binOp AssocRight ["**"] logicOp logicOp = binOp AssocLeft ["&&", "||"] eqOp eqOp = binOp AssocLeft ["==", "/="] compareOp compareOp = binOp AssocLeft ["<=", ">=", "<", ">"] appOp appOp = binOp AssocLeft [""] memberOp memberOp = binOp AssocLeft ["."] value value :: Parser Expr value = try ifE <|> try negateOp <|> try multiParamFunE <|> funE <|> listE <|> try (parens expr) <|> tupleE <|> var <|> numL <|> strL negateOp :: Parser Expr negateOp = unaryOp ["-"] memberOp ifE :: Parser Expr ifE = If <$> (lexeme (string "if") *> expr) <*> (lexeme (string "then") *> expr) <*> (lexeme (string "else") *> expr) multiParamFunE :: Parser Expr multiParamFunE = flip (foldr Fun) <$> (lexeme (char '\\') *> many1 identifier) <*> (lexeme (string "->") *> expr) funE :: Parser Expr funE = Fun <$> (lexeme (char '\\') *> identifier) <*> (lexeme (string "->") *> expr) listE :: Parser Expr listE = List <$> (lexeme (char '[') *> exprs <* lexeme (char ']')) tupleE :: Parser Expr tupleE = Tuple <$> parens exprs var :: Parser Expr var = Var <$> identifier numL :: Parser Expr numL = Natural <$> natural strL :: Parser Expr strL = Str <$> (lexeme (char '"') *> many (noneOf "\"") <* lexeme (char '"')) binOp :: Assoc -> [String] -> Parser Expr -> Parser Expr binOp AssocLeft ops prev = do e1 <- prev es <- many $ try $ do op <- lexeme $ foldl1 (<|>) (try . string <$> ops) e2 <- prev return (op, e2) return $ foldl (\acc (op, e2) -> BinOp op acc e2) e1 es binOp AssocRight ops prev = do es <- many $ try $ do e2 <- prev op <- lexeme $ foldl1 (<|>) (try . string <$> ops) return (e2, op) e1 <- prev return $ foldr (\(e2, op) acc -> BinOp op e2 acc) e1 es unaryOp :: [String] -> Parser Expr -> Parser Expr unaryOp ops prev = UnaryOp <$> foldl1 (<|>) (try . string <$> ops) <*> try prev
AyaMorisawa/aya-script
src/AyaScript/Parser.hs
mit
3,403
0
16
820
1,338
699
639
99
1
module Opponent (randomMove) where import Game (Game, Unfinished, Position, move, openPositions) import System.Random (getStdRandom, randomR) randomMove :: Unfinished -> IO Game randomMove u = move <$> randomPosition u <*> pure u randomPosition :: Unfinished -> IO Position randomPosition = pick . openPositions pick :: [a] -> IO a pick [] = error "cannot pick from empty list" pick xs = (xs !!) <$> (getStdRandom . randomR) (0, pred $ length xs)
amar47shah/NICTA-TicTacToe
src/Opponent.hs
mit
452
0
9
76
164
89
75
10
1
module KeymapTree ( Keymap, size, depth, get, set, toList, fromList ) where -- Modules for testing import Test.QuickCheck import Control.Monad import Data.List -- The data type data Keymap k a = Leaf | Node k a (Keymap k a) (Keymap k a) -- A test tree testTree :: Keymap Int Int testTree = Node 2 20 (Node 1 10 Leaf Leaf) (Node 3 30 Leaf (Node 4 40 Leaf (Node 5 50 Leaf Leaf))) -- Exercise 6 size :: Ord k => Keymap k a -> Int size Leaf = 0 size (Node _ _ left right) = 1 + size left + size right depth :: Ord k => Keymap k a -> Int depth Leaf = 0 depth (Node _ _ left right) = 1 + max (depth left) (depth right) -- Exercise 7 toList :: Ord k => Keymap k a -> [(k,a)] toList Leaf = [] toList (Node x y left right) = toList left ++ [(x, y)] ++ toList right -- Exercise 8 set :: Ord k => k -> a -> Keymap k a -> Keymap k a set key value = f where f Leaf = Node key value Leaf Leaf f (Node k v left right) | key == k = Node k value left right | key < k = f left | otherwise = f right -- Exercise 9 get :: Ord k => k -> Keymap k a -> Maybe a get k Leaf = Nothing get k (Node x y left right) | k == x = Just y | k < x = get k left | otherwise = get k right prop_set_get :: Int -> Int -> Bool prop_set_get k v = get k (set k v testTree) == Just v -- Exercise 10 fromList :: Ord k => [(k,a)] -> Keymap k a fromList [] = Leaf fromList ((k, v) : xs) = set k v (fromList xs) prop_toList_fromList :: [Int] -> [Int] -> Bool prop_toList_fromList xs ys = sort (toList (fromList zs)) == sort zs where zs = zip (nub xs) ys prop_toList_fromList_sorted :: [Int] -> [Int] -> Bool prop_toList_fromList_sorted xs ys = toList (fromList zs) == sort zs where zs = zip (nub xs) ys -- Instances for QuickCheck ----------------------------- instance (Ord k, Show k, Show a) => Show (Keymap k a) where show = show . toList instance (Ord k, Arbitrary k, Arbitrary a) => Arbitrary (Keymap k a) where arbitrary = liftM fromList $ liftM2 zip (liftM nub arbitrary) arbitrary
PavelClaudiuStefan/FMI
An_3_Semestru_1/ProgramareDeclarativa/Laboratoare/Laborator8/KeymapTree.hs
cc0-1.0
2,365
0
11
842
971
491
480
50
2
{-# LANGUAGE TemplateHaskell #-} module Ohua.Types.Environment where import Universum import Control.Lens.TH import Data.Default.Class import qualified Data.HashSet as HS import qualified Data.Vector as V import Ohua.Types.Make import Ohua.Types.Reference import Ohua.Types.Stage declareLenses [d| data Options = Options { callEnvExpr :: !(Maybe QualifiedBinding) , callLocalFunction :: !(Maybe QualifiedBinding) , transformRecursiveFunctions :: Bool , stageHandling :: StageHandling , skipCtrlTransformation :: Bool , higherOrderFunctions :: HS.HashSet QualifiedBinding } |] -- | Stateful name generator declareLenses [d| data NameGenerator = NameGenerator { takenNames :: !(HS.HashSet Binding) , simpleNameList :: [Binding] } |] -- | The read only compiler environment declareLenses [d| newtype Environment = Environment { options :: Options } |] -- | State of the ohua compiler monad. declareLenses [d| data OhuaState envExpr = OhuaState { nameGenerator :: !NameGenerator , idCounter :: !FnId , envExpressions :: !(V.Vector envExpr) } |] type instance SourceType NameGenerator = (HS.HashSet Binding, [Binding]) type instance SourceType (OhuaState envExpr) = (NameGenerator, FnId, V.Vector envExpr) instance UnsafeMake NameGenerator where unsafeMake = uncurry NameGenerator instance Make NameGenerator where make = pure . unsafeMake instance Make (OhuaState envExpr) where make (ng, fnid, exprs) = pure $ OhuaState ng fnid exprs instance Default Options where def = Options Nothing Nothing False -- for no we always disable this option (const (Don'tDump, False)) False HS.empty instance Default Environment where def = Environment def
ohua-dev/ohua-core
core/src/Ohua/Types/Environment.hs
epl-1.0
1,896
0
9
476
286
167
119
-1
-1
{- | Module : ./Proofs/NormalForm.hs Description : compute the normal forms of all nodes in development graphs Copyright : (c) Christian Maeder, DFKI GmbH 2009 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : non-portable(Logic) compute normal forms -} module Proofs.NormalForm ( normalFormLibEnv , normalForm , normalFormRule ) where import Logic.Logic import Logic.Grothendieck import Static.ComputeTheory import Static.GTheory import Static.DgUtils import Static.DevGraph import Static.History import Static.WACocone import Proofs.ComputeColimit import Common.Consistency import Common.Id import Common.LibName import Common.Result import Common.Lib.Graph import Common.Utils (nubOrd) import Data.Graph.Inductive.Graph as Graph import qualified Data.Map as Map import Control.Monad normalFormRule :: DGRule normalFormRule = DGRule "NormalForm" -- | compute normal form for a library and imported libs normalForm :: LibName -> LibEnv -> Result LibEnv normalForm ln le = normalFormLNS (dependentLibs ln le) le -- | compute norm form for all libraries normalFormLibEnv :: LibEnv -> Result LibEnv normalFormLibEnv le = normalFormLNS (getTopsortedLibs le) le normalFormLNS :: [LibName] -> LibEnv -> Result LibEnv normalFormLNS lns libEnv = foldM (\ le ln -> do let dg = lookupDGraph ln le newDg <- normalFormDG le dg return $ Map.insert ln (groupHistory dg normalFormRule newDg) le) libEnv lns normalFormDG :: LibEnv -> DGraph -> Result DGraph normalFormDG libEnv dgraph = foldM (\ dg (node, nodelab) -> if labelHasHiding nodelab then case dgn_nf nodelab of Just _ -> return dg -- already computed Nothing -> if isDGRef nodelab then do {- the normal form of the node is a reference to the normal form of the node it references careful: here not refNf, but a new Node which references refN -} let refLib = dgn_libname nodelab refNode = dgn_node nodelab refGraph' = lookupDGraph refLib libEnv refLabel = labDG refGraph' refNode case dgn_nf refLabel of Nothing -> warning dg (getDGNodeName refLabel ++ " (node " ++ show refNode ++ ") from '" ++ show (getLibId refLib) ++ "' without normal form") nullRange Just refNf -> do let refNodelab = labDG refGraph' refNf -- the label of the normal form ^ nfNode = getNewNodeDG dg -- the new reference node in the old graph ^ refLab = refNodelab { dgn_name = extName "NormalForm" $ dgn_name nodelab , dgn_nf = Just nfNode , dgn_sigma = Just $ ide $ dgn_sign refNodelab , nodeInfo = newRefInfo refLib refNf , dgn_lock = Nothing } newLab = nodelab { dgn_nf = Just nfNode, dgn_sigma = dgn_sigma refLabel } chLab = SetNodeLab nodelab (node, newLab) changes = [InsertNode (nfNode, refLab), chLab] newGraph = changesDGH dgraph changes return newGraph else do let gd = insNode (node, dgn_theory nodelab) empty g0 = Map.fromList [(node, node)] (diagram, g) = computeDiagram dg [node] (gd, g0) fsub = finalSubcateg diagram Result ds res = gWeaklyAmalgamableCocone fsub es = map (\ d -> if isErrorDiag d then d { diagKind = Warning } else d) ds appendDiags es case res of Nothing -> warning dg ("cocone failure for " ++ getDGNodeName nodelab ++ " (node " ++ shows node ")") nullRange Just (sign, mmap) -> do {- we don't know that node is in fsub if it's not, we have to find a tip accessible from node and dgn_sigma = edgeLabel(node, tip); mmap (g Map.! tip) -} morNode <- if node `elem` nodes fsub then let gn = Map.findWithDefault (error "gn") node g phi = Map.findWithDefault (error "mor") gn mmap in return phi else let leaves = filter (\ x -> outdeg fsub x == 0) $ nodes fsub paths = map (\ x -> (x, propagateErrors "normalFormDG" $ dijkstra diagram node x)) $ filter (\ x -> node `elem` predecs diagram x) leaves in case paths of [] -> fail "node should reach a tip" (xn, xf) : _ -> comp xf $ mmap Map.! xn let nfNode = getNewNodeDG dg -- new node for normal form info = nodeInfo nodelab ConsStatus c cp pr = node_cons_status info nfLabel = newInfoNodeLab (extName "NormalForm" $ dgn_name nodelab) info { node_origin = DGNormalForm node , node_cons_status = mkConsStatus c } sign newLab = nodelab -- the new label for node { dgn_nf = Just nfNode , dgn_sigma = Just morNode , nodeInfo = info { node_cons_status = ConsStatus None cp pr } } -- add the nf to the label of node chLab = SetNodeLab nodelab (node, newLab) -- insert the new node and add edges from the predecessors insNNF = InsertNode (nfNode, nfLabel) makeEdge src tgt m = (src, tgt, globDefLink m DGLinkProof) insStrMor = map (\ (x, f) -> InsertEdge $ makeEdge x nfNode f) $ nubOrd $ map (\ (x, y) -> (g Map.! x, y)) $ (node, morNode) : Map.toList mmap allChanges = insNNF : chLab : insStrMor newDG = changesDGH dg allChanges return $ changeDGH newDG $ SetNodeLab nfLabel (nfNode, nfLabel { globalTheory = computeLabelTheory libEnv newDG (nfNode, nfLabel) }) else return dg) dgraph $ topsortedNodes dgraph -- only change relevant nodes {- | computes the diagram associated to a node N in a development graph, adding common origins for multiple occurences of nodes, whenever needed -} computeDiagram :: DGraph -> [Node] -> (GDiagram, Map.Map Node Node) -> (GDiagram, Map.Map Node Node) -- as described in the paper for now computeDiagram dgraph nodeList (gd, g) = case nodeList of [] -> (gd, g) _ -> let -- defInEdges is list of pairs (n, edges of target g(n)) defInEdges = map (\ n -> (n, filter (\ e@(s, t, _) -> s /= t && liftE (liftOr isGlobalDef isHidingDef) e) $ innDG dgraph $ g Map.! n)) nodeList {- TO DO: no local links, and why edges with s=t are removed add normal form nodes sources of each edge must be added as new nodes -} nodeIds = zip (newNodes (length $ concatMap snd defInEdges) gd) $ concatMap (\ (n, l) -> map (\ x -> (n, x)) l ) defInEdges newLNodes = zip (map fst nodeIds) $ map (\ (s, _, _) -> dgn_theory $ labDG dgraph s) $ concatMap snd defInEdges g0 = Map.fromList $ map (\ (newS, (_newT, (s, _t, _))) -> (newS, s)) nodeIds morphEdge (n1, (n2, (_, _, el))) = if isHidingDef $ dgl_type el then (n2, n1, (x, dgl_morphism el)) else (n1, n2, (x, dgl_morphism el)) where EdgeId x = dgl_id el newLEdges = map morphEdge nodeIds gd' = insEdges newLEdges $ insNodes newLNodes gd g' = Map.union g g0 in computeDiagram dgraph (map fst nodeIds) (gd', g') finalSubcateg :: GDiagram -> GDiagram finalSubcateg graph = let leaves = filter (\ (n, _) -> outdeg graph n == 0) $ labNodes graph in buildGraph graph (map fst leaves) leaves [] $ nodes graph predecs :: Gr a b -> Node -> [Node] predecs graph node = let descs nList descList = case nList of [] -> descList _ -> let newDescs = concatMap (pre graph) nList nList' = filter (`notElem` nList) newDescs descList' = nubOrd $ descList ++ newDescs in descs nList' descList' in descs [node] [] buildGraph :: GDiagram -> [Node] -> [LNode G_theory] -> [LEdge (Int, GMorphism)] -> [Node] -> GDiagram buildGraph oGraph leaves nList eList nodeList = case nodeList of [] -> mkGraph nList eList n : nodeList' -> case outdeg oGraph n of 1 -> buildGraph oGraph leaves nList eList nodeList' -- the node is simply removed 0 -> buildGraph oGraph leaves nList eList nodeList' -- the leaves have already been added to nList _ -> let Just l = lab oGraph n nList' = (n, l) : nList accesLeaves = filter (\ x -> n `elem` predecs oGraph x) leaves eList' = map (\ x -> (n, x, (1 :: Int, propagateErrors "buildGraph" $ dijkstra oGraph n x))) accesLeaves in buildGraph oGraph leaves nList' (eList ++ eList') nodeList' -- branch, must add n to the nList and edges in eList
gnn/Hets
Proofs/NormalForm.hs
gpl-2.0
9,648
0
33
3,462
2,456
1,294
1,162
180
9
module Net.DHCP_Client where import Control.Monad(unless) import Data.Maybe(fromMaybe,listToMaybe) import Data.Bits(xor) import Monad.Util(whileM) import Net.DHCP import qualified Net.IPv4 as IP import qualified Net.Ethernet as Eth import qualified Net.UDP as UDP import Net.PacketParsing(doParse,doUnparse) import Net.Concurrent(fork,delay,newRef,readRef,writeRef) import Net.Utils({-emap,-}contents) --import System.Random(randomIO) -- Missing in hOp --import Kernel.Timer(readTimer) --import H.Monad(runH) init putStrLn eth = do --xid <- fmap (xor 0x7f23ae64 . fromIntegral) ({-runH-} readTimer) let xid = 0x7f23ae64 -- xid should be chosen randomly!!! let d = dhcpDiscover xid (offer,serverMAC) <- let req = do debug $ "Discover " -- ++show d tx d in solicit req (rx (isOffer xid)) debug $ "Offer " -- ++show offer let myIP = yiaddr offer Options os = options offer serverIP = head [sIP|ServerIdentifier sIP<-os] request = dhcpRequest xid serverIP serverMAC myIP (ack,_) <- let req = do debug $ "Request " -- ++show request tx request in solicit req (rx (isAck xid serverMAC)) debug $ "Ack " -- ++show ack let ip = yiaddr ack Options os = options ack router = listToMaybe [r|Routers rs<-os,r<-rs] dm = IP.defaultNetmask ip netmask = fromMaybe dm $ listToMaybe [m|SubnetMask m<-os] net = (ip,router,netmask) --debug $ show net return net where debug = putStrLn . ("DHCP init: "++) mac = Eth.myMAC eth tx p = Eth.tx eth (fmap doUnparse p) rx expected = do ep <- Eth.rx eth if Eth.packType ep/=Eth.IPv4 then again "" --"Eth type IPv4" else try "IP" ep $ \ ip -> if IP.protocol ip/=IP.UDP then again "protocol UDP" else try "UDP" ip $ \ udp -> if UDP.sourcePort udp/=serverPort || UDP.destPort udp/=clientPort then again "DHCP ports" else try "DHCP" udp $ \ dhcp -> cont dhcp (Eth.source ep) where try msg = flip (maybe (again msg)) . doParse . contents again msg = do unless (null msg) $ debug $ "not "++msg rx expected cont p sMAC = if expected sMAC p then return (p,sMAC) else do debug "unexpected DHCP packet" rx expected isAck uid sMac sMac' p = opcode p==BootReply && ack && sMac'==sMac && xid p == uid where Options os = options p ack = not $ null [()|MessageType Ack<-os] isOffer uid _ p = opcode p==BootReply && offer && xid p == uid where Options os = options p offer = not $ null [()|MessageType Offer<-os] --c3 = contents . contents . contents --c3 = id dhcpDiscover uid = bcastIP (dhcpUDP discover) where discover = (template mac){xid=uid, options=Options [MessageType Discover]} dhcpRequest uid sIP sMAC myIP = ucastIP myIP sIP sMAC (dhcpUDP request) where request = (template mac){xid=uid, options=Options [MessageType Request, ServerIdentifier sIP, RequestedIPAddress myIP]} dhcpUDP p = UDP.template clientPort serverPort p bcastIP p = bcastEth (IP.template IP.UDP z bcast p) where z = IP.Addr 0 0 0 0 bcast = IP.Addr 255 255 255 255 bcastEth p = Eth.Packet Eth.broadcastAddr mac Eth.IPv4 p ucastIP srcIP dstIP dstMAC p = ucastEth dstMAC (IP.template IP.UDP srcIP dstIP p) ucastEth dst p = Eth.Packet dst mac Eth.IPv4 p -- Nice enough to move to Net.Utils? solicit req = solicit' 3000000 req -- microseconds solicit' timeout request response = do waiting <- newRef True fork $ whileM (readRef waiting) $ do request delay timeout r <- response writeRef waiting False return r
nh2/network-house
Net/DHCP_Client.hs
gpl-2.0
3,772
95
18
1,005
1,251
663
588
92
5
module Main( main ) where import Graphics.UI.Gtk( initGUI, mainGUI, mainQuit, on, timeoutAdd ) import Graphics.UI.Gtk.Gdk.Events( TimeStamp ) import Graphics.UI.Gtk.General.Enums( MouseButton ) import Graphics.UI.Gtk.Display.StatusIcon ( StatusIcon, statusIconNewFromStock, statusIconActivate, statusIconPopupMenu , statusIconSetTooltip, statusIconSetVisible, statusIconSetBlinking ) import Graphics.UI.Gtk.ActionMenuToolbar.Action( actionNew, actionActivated ) import Graphics.UI.Gtk.ActionMenuToolbar.ActionGroup ( ActionGroup, actionGroupNew, actionGroupAddAction ) import Graphics.UI.Gtk.ActionMenuToolbar.UIManager ( uiManagerNew, uiManagerAddUiFromString, uiManagerGetWidget , uiManagerInsertActionGroup ) import Graphics.UI.Gtk.MenuComboToolbar.Menu( Menu, castToMenu, menuPopup, menuPopdown ) import Data.Maybe( fromJust ) import System.Cmd( system ) import Control.Monad( void, liftM ) import Graphics.UI.Gtk.General.StockItems ( stockApply ) import System.Exit ( ExitCode ) import Control.Exception( catch ) import DotaWHcheck( isAvailable ) import PlaySound( playFile ) data MenuItem = MenuItem { menuId :: String , menuText :: String , menuAction :: IO () } menuXml :: String menuXml = "<popup>\ \ <menuitem action=\"ACONF\" />\ \ <menuitem action=\"AOPEN\" />\ \ <menuitem action=\"ATEST\" />\ \ <menuitem action=\"AEXIT\" />\ \ </popup>" menuItems :: [MenuItem] menuItems = [ MenuItem "ACONF" "Open configuration" openConfig , MenuItem "AOPEN" "Show all items" showItems , MenuItem "ATEST" "Test notification sound" playNotification , MenuItem "AEXIT" "Exit" mainQuit ] main :: IO() main = do _ <- initGUI icon <- statusIconNewFromStock stockApply statusIconSetTooltip icon "Ikona jaxviň" group <- actionGroupNew "AGRP" mapM_ (createMenuItem group) menuItems uiman <- uiManagerNew _ <- uiManagerAddUiFromString uiman menuXml _ <- uiManagerInsertActionGroup uiman group 0 pop <- fmap (castToMenu . fromJust) $ uiManagerGetWidget uiman "/popup" --_ <- on icon statusIconActivate $ menuActivate pop _ <- on icon statusIconPopupMenu $ menuPopUp pop chackHandler <- timeoutAdd (update icon) 15000 mainGUI statusIconSetVisible icon False update :: StatusIcon -> IO Bool update icon = undefined createMenuItem :: ActionGroup -> MenuItem -> IO () createMenuItem group item = do action <- actionNew (menuId item) (menuText item) Nothing Nothing _ <- on action actionActivated (menuAction item) actionGroupAddAction group action menuPopUp :: Menu -> Maybe MouseButton -> TimeStamp -> IO () menuPopUp menu _ _ = do _ <- timeoutAdd (menuPopdown menu >> return False) 6000 menuPopup menu Nothing menuActivate :: Menu -> IO () menuActivate menu = menuPopup menu Nothing loadConfig :: IO [String] loadConfig = liftM (filter ((/= '#') . head) . filter (not . null) . lines) (readFile "items.txt") openSystem :: String -> IO ExitCode openSystem = system . ("start \"\" "++) openConfig :: IO () openConfig = void $ openSystem "items.txt" showItems :: IO () showItems = mapM_ (openSystem) =<< loadConfig playNotification :: IO () playNotification = playFile "available.wav" playInvalidFile :: IO () playInvalidFile = playFile "invalidFile.wav"
ThranMaru/DotaWHcheck
Main.hs
gpl-2.0
3,356
0
12
613
888
476
412
72
1
-- -- Copyright (c) 2012 Citrix Systems, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- module XenMgr.Connect.NetworkDaemon ( NetworkInfo(..) , listNetworks , statNetwork , joinNetwork , anyNetworksActive , onNetworkAdded, onNetworkRemoved, onNetworkStateChanged, onNetworkStateChangedRemove , getNetworkBackend' , vifConnected , netbackToUuid ) where import Data.Time import Data.String import Data.Maybe import qualified Data.Map as Map import Control.Applicative import Control.Monad import Control.Monad.Error (catchError) import Control.Monad.Trans import Control.Concurrent import Vm.Types import Vm.DmTypes import Vm.Uuid import qualified Data.Text.Lazy as TL import Text.Printf import Tools.Misc import Tools.Log import Tools.Text import Rpc.Autogen.NetworkDaemonClient import Rpc.Autogen.NetworkClient import XenMgr.Rpc import XenMgr.Errors service = "com.citrix.xenclient.networkdaemon" rootS = "/" vifS :: DomainID -> XbDeviceID -> String vifS domid (XbDeviceID di) = printf "vif%d.%d" domid di npathS :: Network -> String npathS = TL.unpack . strObjectPath . networkObjectPath ready :: Rpc Bool ready = comCitrixXenclientNetworkdaemonIsInitialized service rootS vifConnected :: DomainID -> NicID -> DomainID -> Rpc Bool vifConnected frontdomid nicid backdomid = comCitrixXenclientNetworkdaemonVifConnected service rootS (vifS frontdomid nicid) backdomid repeatUntil :: (MonadIO m) => m Bool -> Float -> Float -> m Bool repeatUntil pred delay to = do t0 <- liftIO getCurrentTime let test = do p <- pred t1 <- liftIO getCurrentTime let dt = realToFrac $ diffUTCTime t1 t0 case () of _ | p -> return True | t1 < t0 -> return False | dt > to -> return False | otherwise -> liftIO (threadDelay (round $ 10^6 * to)) >> test test listNetworks :: Rpc [Network] listNetworks = catMaybes . map from_map <$> comCitrixXenclientNetworkdaemonList service rootS where from_map m = do o <- fromString <$> Map.lookup "object" m return $ networkFromStr o -- expects that a) daemon is initialised b) network object is exported -- if not true, waits a bit before retrying and failing statNetwork :: Network -> Rpc (Maybe NetworkInfo) statNetwork n = stat =<< repeatUntil ready 1 30 where stat False = failTimeoutWaitingForNetworkDaemon stat True = (rpcRetryOnError 10 250 retryCheck $ (Just <$> statNetwork' n)) `catchError` onErr onErr ex = warn ("cannot stat " ++ show n ++ ": " ++ show ex) >> return Nothing retryCheck e = case toRemoteErr e of Nothing -> False Just (RemoteErr name _) -> name == fromString "org.freedesktop.DBus.Error.UnknownObject" statNetwork' :: Network -> Rpc NetworkInfo statNetwork' n = NetworkInfo n <$> getNetworkName n <*> getNetworkBridgeName n <*> (fromString <$> getNetworkBackend n) <*> (getNetworkType n >>= \t -> return (t == eNETWORK_TYPE_WIFI || t == eNETWORK_TYPE_MODEM)) <*> (getNetworkConnection n >>= \t -> return (t == eCONNECTION_TYPE_SHARED)) <*> (getNetworkType n >>= \t -> return (t == eNETWORK_TYPE_INTERNAL)) <*> isNetworkConfigured n <*> getNetworkCarrier n getNetworkName = comCitrixXenclientNetworkConfigGetName service . npathS getNetworkBridgeName = comCitrixXenclientNetworkConfigGetBridge service . npathS getNetworkBackend = comCitrixXenclientNetworkConfigGetBackendUuid service . npathS getNetworkBackend' :: Network -> Rpc (Maybe Uuid) getNetworkBackend' n = make <$> comCitrixXenclientNetworkdaemonGetNetworkBackend service rootS (npathS n) where make "" = Nothing make s = Just (fromString s) getNetworkType = comCitrixXenclientNetworkConfigGetType service . npathS getNetworkConnection = comCitrixXenclientNetworkConfigGetConnection service . npathS isNetworkConfigured = comCitrixXenclientNetworkIsConfigured service . npathS getNetworkCarrier = comCitrixXenclientNetworkConfigGetActive service . npathS anyNetworksActive :: Rpc Bool anyNetworksActive = comCitrixXenclientNetworkdaemonIsNetworkingActive service rootS joinNetwork :: Network -> DomainID -> NicID -> Rpc () joinNetwork n domid devid = comCitrixXenclientNetworkdaemonMoveToNetwork service rootS (vifS domid devid) (npathS n) onNetworkAdded, onNetworkRemoved :: (Network -> Rpc ()) -> Rpc () onNetworkAdded f = rpcOnSignal rule handle where rule = matchSignal "com.citrix.xenclient.networkdaemon.notify" "network_added" handle _ s = let (networkV:_) = signalArgs s in case fromVariant networkV of Just name -> f $ networkFromStr name _ -> return () onNetworkRemoved f = rpcOnSignal rule handle where rule = matchSignal "com.citrix.xenclient.networkdaemon.notify" "network_removed" handle _ s = let (networkV:_) = signalArgs s in case fromVariant networkV of Just name -> f $ networkFromStr name _ -> return () onNetworkStateChanged :: (Int -> String -> Rpc ()) -> Rpc () onNetworkStateChanged f = rpcOnSignal rule handle where rule = matchSignal "com.citrix.xenclient.networkdaemon.notify" "network_state_changed" handle _ s = let (networkV:stateV:backendV:_) = signalArgs s in case (fromVariant stateV, fromVariant backendV) of (Just state, Just backend) -> f (networkStateFromStr state) backend (_, _) -> return () onNetworkStateChangedRemove :: (Int -> String -> Rpc ()) -> Rpc () onNetworkStateChangedRemove f = rpcOnSignalRemove rule handle where rule = matchSignal "com.citrix.xenclient.networkdaemon.notify" "network_state_changed" handle _ s = let (networkV:stateV:backendV:_) = signalArgs s in case (fromVariant stateV, fromVariant backendV) of (Just state, Just backend) -> f (networkStateFromStr state) backend (_, _) -> return () -- "/ndvm/000000000_0000_0000_00000001" netbackToUuid :: String -> Uuid netbackToUuid backend = fromString $ replace "_" "-" $ last $ split '/' backend
OpenXT/manager
xenmgr/XenMgr/Connect/NetworkDaemon.hs
gpl-2.0
6,963
3
25
1,532
1,713
867
846
133
3
module Math.REPL.Evaluator.Statement (evalStat) where -------------------------------------------------------------------------------- import Math.REPL.Evaluator.Cmd (evalCmd) import Math.REPL.Evaluator.Expr (evalExpr) import Math.REPL.Prim.Bindings (Bindings) import Math.REPL.Prim.Expr (Expr (Message, Constant)) import Math.REPL.Prim.Result (Result (..)) import Math.REPL.Prim.Statement (Statement (..)) -------------------------------------------------------------------------------- evalStat :: Bindings -> Statement -> Result evalStat b stat = case stat of Expression e -> case evalExpr b e of Constant c -> Value c Message t -> Error . unlines $ t _ -> Error "Internal error: evalStat" Command c -> evalCmd b c --------------------------------------------------------------------------------
sumitsahrawat/calculator
src/Math/REPL/Evaluator/Statement.hs
gpl-2.0
975
0
12
252
199
116
83
15
4
{- Copyright 2013 Matthew Gordon. This file is part of Gramophone. Gramophone is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gramophone is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Gramophone. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE QuasiQuotes, OverloadedStrings #-} module Gramophone.GUI.ListAlbums ( getListAlbumsR ) where import Gramophone.GUI.Foundation import Yesod (Html, defaultLayout, whamlet) import Gramophone.GUI.DBTableWidgets import Control.Applicative ((<$>)) import Data.Maybe (catMaybes) getListAlbumsR :: Handler Html getListAlbumsR = defaultLayout $ do recordings <- withDatabase $ do ids <- getAllAlbums catMaybes <$> mapM getAlbum ids dbTableWidget [albumTitleColumn, albumArtistNameColumn, albumTrackCountColumn] recordings [whamlet|<div><a href=@{TestR}>Back to testing functions</a>|]
matthewscottgordon/gramophone
src/Gramophone/GUI/ListAlbums.hs
gpl-3.0
1,389
0
13
294
133
77
56
18
1
module TrainedPlayer where import Games import MCTSPlayer import Data.Maybe import System.IO import System.Random import Control.Monad.Random import Control.Concurrent.ParallelIO distribute :: Int -> [a] -> [[a]] distribute n elems = distributeHelp 0 elems where distributeHelp i [] = replicate n [] distributeHelp i (h:t) | i < n = let (x, l : y) = splitAt i $ distributeHelp (i + 1) t in x ++ (h : l) : y | otherwise = distributeHelp 0 (h:t) buildData :: Game b m => FilePath -> GameState b m -> Int -> Integer -> Int -> IO () buildData fileName initial numParallel numTrials numData = do file <- openFile fileName AppendMode statesGen <- newStdGen playoutGens <- sequence (replicate numParallel newStdGen) parallel $ [sequence [hPutStrLn file $ show $ evalRand (getPlayout game) gen | game <- games] | (gen, games) <- zip (concat $ repeat playoutGens) $ distribute numParallel (take numData $ trainingStates statesGen)] hClose file return () where trainingStates gen = states ++ trainingStates newGen where playoutStates game | isJust $ winner game = return [] | isDraw game = return [] | null $ gameMoves game = error "No moves and not a win or draw" | otherwise = do move <- randSample $ gameMoves game states <- playoutStates (makeMove game move) return $ game : states (states, newGen) = runRand (playoutStates initial) gen getPlayout game = do tree <- trials numTrials $ initTree game return (getWins tree, features $ board game)
krame505/board_games
haskell/TrainedPlayer.hs
gpl-3.0
1,712
0
15
514
608
292
316
43
2
-- The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. -- The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... -- What is the value of the first triangle number to have over five hundred divisors? import Data.List primes :: [Int] primes = 2 : filter (null . tail . primeFactors) [3,5..] primeFactors :: Int -> [Int] primeFactors n = factor n primes where factor n (p:ps) | p*p > n = [n] | n `mod` p == 0 = p : factor (n `div` p) (p:ps) | otherwise = factor n ps solution :: Int solution = head $ filter ((> 500) . nDivisors) triangleNumbers where nDivisors n = product $ map ((+1) . length) (group (primeFactors n)) triangleNumbers = scanl1 (+) [1..] main :: IO () main = (putStrLn . show ) solution
peri4n/projecteuler
haskell/problem12.hs
gpl-3.0
874
3
10
231
300
154
146
15
1
{-# LANGUAGE TypeSynonymInstances #-} module Elves.Value where import Elves.Exp import Data.Map -- simple direct valuation of the AST -- we only value FloatE!!!!! valueE :: Map Id Float -> FloatE -> Float valueE ctx (E a) = valueFloat ctx a valueBool _ (LitBool a) = a valueBool ctx (If c a b) = if (valueBool ctx c) then (valueBool ctx a) else (valueBool ctx b) valueBool ctx (And a b) = (valueBool ctx a) && (valueBool ctx b) valueBool ctx (Not a) = not (valueBool ctx a) valueBool ctx (Positive a) = (valueFloat ctx a) > 0.0 valueInt _ (LitInt a) = a valueInt ctx (CastInt a) = truncate (valueFloat ctx a) valueInt ctx (Var a Int) = let v = Data.Map.lookup a ctx in case v of Nothing -> error ("Missing " ++ a) Just val -> truncate val valueFloat _ (LitFloat a) = a valueFloat ctx (CastFloat a) = intToFloat (valueInt ctx a) valueFloat ctx (Var a Float) = let v = Data.Map.lookup a ctx in case v of Nothing -> error ("Missing " ++ a) Just val -> val valueFloat ctx (If c a b) = if (valueBool ctx c) then (valueFloat ctx a) else (valueFloat ctx b) valueFloat ctx (Add a b) = (valueFloat ctx a) + (valueFloat ctx b) valueFloat ctx (Mul a b) = (valueFloat ctx a) * (valueFloat ctx b) valueFloat ctx (Rec a) = 1 / (valueFloat ctx a) valueFloat ctx (Negate a) = 0 - (valueFloat ctx a) valueFloat ctx (Exponential a) = exp (valueFloat ctx a) valueFloat ctx (Logarithm a) = log (valueFloat ctx a) valueFloat ctx (Sin a) = sin (valueFloat ctx a) valueFloat ctx (Cos a) = cos (valueFloat ctx a) valueFloat ctx (ReadArr arr pos) = let a = valueArray ctx arr p = valueInt ctx pos in a !! p valueArray ctx (MkArray id s e) = let size = valueInt ctx s newCtx x = Data.Map.insert id x ctx arr = Prelude.map (\x -> valueFloat (newCtx (intToFloat x)) e) [0 .. size - 1] in arr
audetto/andsoft
haskell/Elves/Value.hs
gpl-3.0
2,348
0
16
925
881
439
442
37
3
-------------------------------------------------------------------------------- -- | -- Module : Dhek.Engine -- -- -------------------------------------------------------------------------------- module Dhek.Engine ( DrawEnv(..) , DhekMode(..) , EngineState , RuntimeEnv , Pos , engineDrawingArea , engineCurrentPage , engineCurrentState , engineModeMove , engineModePress , engineModeRelease , engineModeDraw , engineModeKeyPress , engineModeKeyRelease , engineModeEnter , engineModeLeave , engineSetMode , engineHasEvents -- Draw lenses , drawFreshId , drawOverRect , drawSelected -- Engine lenses , engineBoards , engineDrawState -- , engineRatio , getRects , loadPdfFileDoc , loadPdfInlinedDoc , loadViewer , makeRuntimeEnv , makeViewer , runProgram ) where -------------------------------------------------------------------------------- import Dhek.Engine.Runtime import Dhek.Engine.Type
cchantep/dhek
Dhek/Engine.hs
gpl-3.0
1,042
0
5
235
131
91
40
34
0
module Brainfuck ( Program, Machine, Op(..), makeMachine, makeProgram, compileProgram, runMachine ) where import Control.Monad.State (StateT(..), liftIO) import Control.Monad (unless) import Data.Array (Array, (//), (!), bounds, array, listArray) import Data.Char (chr, ord) data Op = PtInc | PtDec | ValInc | ValDec | PutC | GetC | LoopStart Int | LoopEnd Int deriving Show type Program = Array Int Op type Mem = Array Int Int data Machine = Machine (Program, Int) (Mem, Int) deriving Show execOpI :: Op -> Machine -> IO ((), Machine) execOpI PtInc (Machine (prg, pc) (mem, idx)) = return ((), Machine (prg, pc + 1) (mem, idx + 1)) execOpI PtDec (Machine (prg, pc) (mem, idx)) = return ((), Machine (prg, pc + 1) (mem, idx - 1)) execOpI ValInc (Machine (prg, pc) (mem, idx)) = return ((), Machine (prg, pc + 1) (mem // [(idx, (mem ! idx) + 1)], idx)) execOpI ValDec (Machine (prg, pc) (mem, idx)) = return ((), Machine (prg, pc + 1) (mem // [(idx, (mem ! idx) - 1)], idx)) execOpI (LoopStart x) (Machine (prg, pc) (mem, idx)) = return ((), Machine (prg, if (mem ! idx) == 0 then x else pc + 1) (mem , idx)) execOpI (LoopEnd x) (Machine (prg, pc) (mem, idx)) = return ((), Machine (prg, if (mem ! idx) /= 0 then x else pc + 1) (mem , idx)) execOpI PutC (Machine (prg, pc) (mem, idx)) = do putChar (chr (mem ! idx)) return ((), Machine (prg, pc + 1) (mem , idx)) execOpI GetC (Machine (prg, pc) (mem, idx)) = do c <- getChar return ((), Machine (prg, pc + 1) (mem // [(idx, ord c)], idx)) execOp :: Op -> StateT Machine IO () execOp op = StateT $ \t -> execOpI op t fetchPC :: Machine -> Op fetchPC (Machine (prg, pc) _) = prg ! pc fetchPC' :: Machine -> IO (Op, Machine) fetchPC' m = return (fetchPC m, m) fetchPC'' :: StateT Machine IO Op fetchPC'' = StateT $ \t -> liftIO $ fetchPC' t runStep :: StateT Machine IO () runStep = do op <- fetchPC'' execOp op isExit :: Machine -> Bool isExit (Machine (prg, pc) _) = let (start, end) = bounds prg in (start <= pc && pc <= end) updateLoop :: [Op] -> Int -> Int -> [Op] updateLoop op idx count = let len = length op (after, before) = splitAt (len-idx-1) op in after ++ LoopStart (count+1) : tail before compileProgram :: String -> [Op] compileProgram s = compileProgram' s [] [] 0 compileProgram' :: String -> [Op] -> [Int] -> Int -> [Op] compileProgram' ('>':xs) acc idxs cnt = compileProgram' xs (PtInc:acc) idxs (cnt+1) compileProgram' ('<':xs) acc idxs cnt = compileProgram' xs (PtDec:acc) idxs (cnt+1) compileProgram' ('+':xs) acc idxs cnt = compileProgram' xs (ValInc:acc) idxs (cnt+1) compileProgram' ('-':xs) acc idxs cnt = compileProgram' xs (ValDec:acc) idxs (cnt+1) compileProgram' ('.':xs) acc idxs cnt = compileProgram' xs (PutC:acc) idxs (cnt+1) compileProgram' (',':xs) acc idxs cnt = compileProgram' xs (GetC:acc) idxs (cnt+1) compileProgram' ('[':xs) acc idxs cnt = compileProgram' xs (LoopStart (-1):acc) (cnt:idxs) (cnt+1) compileProgram' (']':xs) acc idxs cnt = compileProgram' xs (LoopEnd (1 + head idxs) : updateLoop acc (head idxs) cnt) (tail idxs) (cnt+1) compileProgram' (_:xs) acc idxs cnt = compileProgram' xs acc idxs cnt compileProgram' [] acc _ _ = reverse acc -- Op‚ÌƒŠƒXƒg‚©‚çƒvƒƒOƒ‰ƒ€‚ðì‚é makeProgram :: [Op] -> Program makeProgram lst = listArray (0, length lst - 1) lst -- ƒvƒƒOƒ‰ƒ€‚ðƒ[ƒh‚µ‚½ƒ}ƒVƒ“‚ðì‚é makeMachine :: Program -> Machine makeMachine prog = Machine (prog, 0) (array (0, 30000) (zip [0..30000] (repeat 0)), 0) -- ƒvƒƒOƒ‰ƒ€‚ðŽÀs‚µ‚½ó‘Ԃ‚«ŒvŽZ‚ð‘g‚Ý—§‚Ä‚é runProgram :: StateT Machine IO () runProgram = do end <- StateT $ \t -> return (isExit t, t) unless (not end) $ do runStep runProgram -- ƒvƒƒOƒ‰ƒ€‚ðŽÀs‚·‚éIOƒAƒNƒVƒ‡ƒ“‚ð‘g‚Ý—§‚Ä‚éB–ß‚è’l‚ÍŽÀs‚µ‚½‹@ŠB‚»‚Ì‚à‚Ì runMachine :: Machine -> IO Machine runMachine st = do (_, m) <- runStateT runProgram st return m
ledyba/Brainfucks
haskell/src/Brainfuck.hs
gpl-3.0
4,086
2
14
952
1,933
1,048
885
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Instances.GetEffectiveFirewalls -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns effective firewalls applied to an interface of the instance. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instances.getEffectiveFirewalls@. module Network.Google.Resource.Compute.Instances.GetEffectiveFirewalls ( -- * REST Resource InstancesGetEffectiveFirewallsResource -- * Creating a Request , instancesGetEffectiveFirewalls , InstancesGetEffectiveFirewalls -- * Request Lenses , igefProject , igefNetworkInterface , igefZone , igefInstance ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.instances.getEffectiveFirewalls@ method which the -- 'InstancesGetEffectiveFirewalls' request conforms to. type InstancesGetEffectiveFirewallsResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "zones" :> Capture "zone" Text :> "instances" :> Capture "instance" Text :> "getEffectiveFirewalls" :> QueryParam "networkInterface" Text :> QueryParam "alt" AltJSON :> Get '[JSON] InstancesGetEffectiveFirewallsResponse -- | Returns effective firewalls applied to an interface of the instance. -- -- /See:/ 'instancesGetEffectiveFirewalls' smart constructor. data InstancesGetEffectiveFirewalls = InstancesGetEffectiveFirewalls' { _igefProject :: !Text , _igefNetworkInterface :: !Text , _igefZone :: !Text , _igefInstance :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InstancesGetEffectiveFirewalls' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'igefProject' -- -- * 'igefNetworkInterface' -- -- * 'igefZone' -- -- * 'igefInstance' instancesGetEffectiveFirewalls :: Text -- ^ 'igefProject' -> Text -- ^ 'igefNetworkInterface' -> Text -- ^ 'igefZone' -> Text -- ^ 'igefInstance' -> InstancesGetEffectiveFirewalls instancesGetEffectiveFirewalls pIgefProject_ pIgefNetworkInterface_ pIgefZone_ pIgefInstance_ = InstancesGetEffectiveFirewalls' { _igefProject = pIgefProject_ , _igefNetworkInterface = pIgefNetworkInterface_ , _igefZone = pIgefZone_ , _igefInstance = pIgefInstance_ } -- | Project ID for this request. igefProject :: Lens' InstancesGetEffectiveFirewalls Text igefProject = lens _igefProject (\ s a -> s{_igefProject = a}) -- | The name of the network interface to get the effective firewalls. igefNetworkInterface :: Lens' InstancesGetEffectiveFirewalls Text igefNetworkInterface = lens _igefNetworkInterface (\ s a -> s{_igefNetworkInterface = a}) -- | The name of the zone for this request. igefZone :: Lens' InstancesGetEffectiveFirewalls Text igefZone = lens _igefZone (\ s a -> s{_igefZone = a}) -- | Name of the instance scoping this request. igefInstance :: Lens' InstancesGetEffectiveFirewalls Text igefInstance = lens _igefInstance (\ s a -> s{_igefInstance = a}) instance GoogleRequest InstancesGetEffectiveFirewalls where type Rs InstancesGetEffectiveFirewalls = InstancesGetEffectiveFirewallsResponse type Scopes InstancesGetEffectiveFirewalls = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient InstancesGetEffectiveFirewalls'{..} = go _igefProject _igefZone _igefInstance (Just _igefNetworkInterface) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy InstancesGetEffectiveFirewallsResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Instances/GetEffectiveFirewalls.hs
mpl-2.0
4,785
0
18
1,099
551
326
225
92
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.Books.Volumes.Mybooks.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Return a list of books in My Library. -- -- /See:/ <https://code.google.com/apis/books/docs/v1/getting_started.html Books API Reference> for @books.volumes.mybooks.list@. module Network.Google.Resource.Books.Volumes.Mybooks.List ( -- * REST Resource VolumesMybooksListResource -- * Creating a Request , volumesMybooksList , VolumesMybooksList -- * Request Lenses , vmlProcessingState , vmlXgafv , vmlAcquireMethod , vmlUploadProtocol , vmlCountry , vmlLocale , vmlAccessToken , vmlUploadType , vmlSource , vmlStartIndex , vmlMaxResults , vmlCallback ) where import Network.Google.Books.Types import Network.Google.Prelude -- | A resource alias for @books.volumes.mybooks.list@ method which the -- 'VolumesMybooksList' request conforms to. type VolumesMybooksListResource = "books" :> "v1" :> "volumes" :> "mybooks" :> QueryParams "processingState" VolumesMybooksListProcessingState :> QueryParam "$.xgafv" Xgafv :> QueryParams "acquireMethod" VolumesMybooksListAcquireMethod :> QueryParam "upload_protocol" Text :> QueryParam "country" Text :> QueryParam "locale" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "source" Text :> QueryParam "startIndex" (Textual Word32) :> QueryParam "maxResults" (Textual Word32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Volumes -- | Return a list of books in My Library. -- -- /See:/ 'volumesMybooksList' smart constructor. data VolumesMybooksList = VolumesMybooksList' { _vmlProcessingState :: !(Maybe [VolumesMybooksListProcessingState]) , _vmlXgafv :: !(Maybe Xgafv) , _vmlAcquireMethod :: !(Maybe [VolumesMybooksListAcquireMethod]) , _vmlUploadProtocol :: !(Maybe Text) , _vmlCountry :: !(Maybe Text) , _vmlLocale :: !(Maybe Text) , _vmlAccessToken :: !(Maybe Text) , _vmlUploadType :: !(Maybe Text) , _vmlSource :: !(Maybe Text) , _vmlStartIndex :: !(Maybe (Textual Word32)) , _vmlMaxResults :: !(Maybe (Textual Word32)) , _vmlCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'VolumesMybooksList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vmlProcessingState' -- -- * 'vmlXgafv' -- -- * 'vmlAcquireMethod' -- -- * 'vmlUploadProtocol' -- -- * 'vmlCountry' -- -- * 'vmlLocale' -- -- * 'vmlAccessToken' -- -- * 'vmlUploadType' -- -- * 'vmlSource' -- -- * 'vmlStartIndex' -- -- * 'vmlMaxResults' -- -- * 'vmlCallback' volumesMybooksList :: VolumesMybooksList volumesMybooksList = VolumesMybooksList' { _vmlProcessingState = Nothing , _vmlXgafv = Nothing , _vmlAcquireMethod = Nothing , _vmlUploadProtocol = Nothing , _vmlCountry = Nothing , _vmlLocale = Nothing , _vmlAccessToken = Nothing , _vmlUploadType = Nothing , _vmlSource = Nothing , _vmlStartIndex = Nothing , _vmlMaxResults = Nothing , _vmlCallback = Nothing } -- | The processing state of the user uploaded volumes to be returned. -- Applicable only if the UPLOADED is specified in the acquireMethod. vmlProcessingState :: Lens' VolumesMybooksList [VolumesMybooksListProcessingState] vmlProcessingState = lens _vmlProcessingState (\ s a -> s{_vmlProcessingState = a}) . _Default . _Coerce -- | V1 error format. vmlXgafv :: Lens' VolumesMybooksList (Maybe Xgafv) vmlXgafv = lens _vmlXgafv (\ s a -> s{_vmlXgafv = a}) -- | How the book was acquired vmlAcquireMethod :: Lens' VolumesMybooksList [VolumesMybooksListAcquireMethod] vmlAcquireMethod = lens _vmlAcquireMethod (\ s a -> s{_vmlAcquireMethod = a}) . _Default . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). vmlUploadProtocol :: Lens' VolumesMybooksList (Maybe Text) vmlUploadProtocol = lens _vmlUploadProtocol (\ s a -> s{_vmlUploadProtocol = a}) -- | ISO-3166-1 code to override the IP-based location. vmlCountry :: Lens' VolumesMybooksList (Maybe Text) vmlCountry = lens _vmlCountry (\ s a -> s{_vmlCountry = a}) -- | ISO-639-1 language and ISO-3166-1 country code. Ex:\'en_US\'. Used for -- generating recommendations. vmlLocale :: Lens' VolumesMybooksList (Maybe Text) vmlLocale = lens _vmlLocale (\ s a -> s{_vmlLocale = a}) -- | OAuth access token. vmlAccessToken :: Lens' VolumesMybooksList (Maybe Text) vmlAccessToken = lens _vmlAccessToken (\ s a -> s{_vmlAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). vmlUploadType :: Lens' VolumesMybooksList (Maybe Text) vmlUploadType = lens _vmlUploadType (\ s a -> s{_vmlUploadType = a}) -- | String to identify the originator of this request. vmlSource :: Lens' VolumesMybooksList (Maybe Text) vmlSource = lens _vmlSource (\ s a -> s{_vmlSource = a}) -- | Index of the first result to return (starts at 0) vmlStartIndex :: Lens' VolumesMybooksList (Maybe Word32) vmlStartIndex = lens _vmlStartIndex (\ s a -> s{_vmlStartIndex = a}) . mapping _Coerce -- | Maximum number of results to return. vmlMaxResults :: Lens' VolumesMybooksList (Maybe Word32) vmlMaxResults = lens _vmlMaxResults (\ s a -> s{_vmlMaxResults = a}) . mapping _Coerce -- | JSONP vmlCallback :: Lens' VolumesMybooksList (Maybe Text) vmlCallback = lens _vmlCallback (\ s a -> s{_vmlCallback = a}) instance GoogleRequest VolumesMybooksList where type Rs VolumesMybooksList = Volumes type Scopes VolumesMybooksList = '["https://www.googleapis.com/auth/books"] requestClient VolumesMybooksList'{..} = go (_vmlProcessingState ^. _Default) _vmlXgafv (_vmlAcquireMethod ^. _Default) _vmlUploadProtocol _vmlCountry _vmlLocale _vmlAccessToken _vmlUploadType _vmlSource _vmlStartIndex _vmlMaxResults _vmlCallback (Just AltJSON) booksService where go = buildClient (Proxy :: Proxy VolumesMybooksListResource) mempty
brendanhay/gogol
gogol-books/gen/Network/Google/Resource/Books/Volumes/Mybooks/List.hs
mpl-2.0
7,491
0
24
1,961
1,261
722
539
179
1
module Game.Toliman.Graphical.Rendering.OpenGL ( module Types, module Core) where import Game.Toliman.Graphical.Rendering.OpenGL.Types as Types import Game.Toliman.Graphical.Rendering.OpenGL.Core as Core
duncanburke/toliman-graphical
src-lib/Game/Toliman/Graphical/Rendering/OpenGL.hs
mpl-2.0
210
0
4
22
41
32
9
5
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Classroom.Courses.CourseWork.StudentSubmissions.Patch -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates one or more fields of a student submission. See -- google.classroom.v1.StudentSubmission for details of which fields may be -- updated and who may change them. This request must be made by the -- Developer Console project of the [OAuth client -- ID](https:\/\/support.google.com\/cloud\/answer\/6158849) used to create -- the corresponding course work item. This method returns the following -- error codes: * \`PERMISSION_DENIED\` if the requesting developer project -- did not create the corresponding course work, if the user is not -- permitted to make the requested modification to the student submission, -- or for access errors. * \`INVALID_ARGUMENT\` if the request is -- malformed. * \`NOT_FOUND\` if the requested course, course work, or -- student submission does not exist. -- -- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.courses.courseWork.studentSubmissions.patch@. module Network.Google.Resource.Classroom.Courses.CourseWork.StudentSubmissions.Patch ( -- * REST Resource CoursesCourseWorkStudentSubmissionsPatchResource -- * Creating a Request , coursesCourseWorkStudentSubmissionsPatch , CoursesCourseWorkStudentSubmissionsPatch -- * Request Lenses , ccwsspXgafv , ccwsspUploadProtocol , ccwsspUpdateMask , ccwsspPp , ccwsspCourseId , ccwsspAccessToken , ccwsspUploadType , ccwsspPayload , ccwsspBearerToken , ccwsspId , ccwsspCallback , ccwsspCourseWorkId ) where import Network.Google.Classroom.Types import Network.Google.Prelude -- | A resource alias for @classroom.courses.courseWork.studentSubmissions.patch@ method which the -- 'CoursesCourseWorkStudentSubmissionsPatch' request conforms to. type CoursesCourseWorkStudentSubmissionsPatchResource = "v1" :> "courses" :> Capture "courseId" Text :> "courseWork" :> Capture "courseWorkId" Text :> "studentSubmissions" :> Capture "id" Text :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] StudentSubmission :> Patch '[JSON] StudentSubmission -- | Updates one or more fields of a student submission. See -- google.classroom.v1.StudentSubmission for details of which fields may be -- updated and who may change them. This request must be made by the -- Developer Console project of the [OAuth client -- ID](https:\/\/support.google.com\/cloud\/answer\/6158849) used to create -- the corresponding course work item. This method returns the following -- error codes: * \`PERMISSION_DENIED\` if the requesting developer project -- did not create the corresponding course work, if the user is not -- permitted to make the requested modification to the student submission, -- or for access errors. * \`INVALID_ARGUMENT\` if the request is -- malformed. * \`NOT_FOUND\` if the requested course, course work, or -- student submission does not exist. -- -- /See:/ 'coursesCourseWorkStudentSubmissionsPatch' smart constructor. data CoursesCourseWorkStudentSubmissionsPatch = CoursesCourseWorkStudentSubmissionsPatch' { _ccwsspXgafv :: !(Maybe Text) , _ccwsspUploadProtocol :: !(Maybe Text) , _ccwsspUpdateMask :: !(Maybe Text) , _ccwsspPp :: !Bool , _ccwsspCourseId :: !Text , _ccwsspAccessToken :: !(Maybe Text) , _ccwsspUploadType :: !(Maybe Text) , _ccwsspPayload :: !StudentSubmission , _ccwsspBearerToken :: !(Maybe Text) , _ccwsspId :: !Text , _ccwsspCallback :: !(Maybe Text) , _ccwsspCourseWorkId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CoursesCourseWorkStudentSubmissionsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccwsspXgafv' -- -- * 'ccwsspUploadProtocol' -- -- * 'ccwsspUpdateMask' -- -- * 'ccwsspPp' -- -- * 'ccwsspCourseId' -- -- * 'ccwsspAccessToken' -- -- * 'ccwsspUploadType' -- -- * 'ccwsspPayload' -- -- * 'ccwsspBearerToken' -- -- * 'ccwsspId' -- -- * 'ccwsspCallback' -- -- * 'ccwsspCourseWorkId' coursesCourseWorkStudentSubmissionsPatch :: Text -- ^ 'ccwsspCourseId' -> StudentSubmission -- ^ 'ccwsspPayload' -> Text -- ^ 'ccwsspId' -> Text -- ^ 'ccwsspCourseWorkId' -> CoursesCourseWorkStudentSubmissionsPatch coursesCourseWorkStudentSubmissionsPatch pCcwsspCourseId_ pCcwsspPayload_ pCcwsspId_ pCcwsspCourseWorkId_ = CoursesCourseWorkStudentSubmissionsPatch' { _ccwsspXgafv = Nothing , _ccwsspUploadProtocol = Nothing , _ccwsspUpdateMask = Nothing , _ccwsspPp = True , _ccwsspCourseId = pCcwsspCourseId_ , _ccwsspAccessToken = Nothing , _ccwsspUploadType = Nothing , _ccwsspPayload = pCcwsspPayload_ , _ccwsspBearerToken = Nothing , _ccwsspId = pCcwsspId_ , _ccwsspCallback = Nothing , _ccwsspCourseWorkId = pCcwsspCourseWorkId_ } -- | V1 error format. ccwsspXgafv :: Lens' CoursesCourseWorkStudentSubmissionsPatch (Maybe Text) ccwsspXgafv = lens _ccwsspXgafv (\ s a -> s{_ccwsspXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ccwsspUploadProtocol :: Lens' CoursesCourseWorkStudentSubmissionsPatch (Maybe Text) ccwsspUploadProtocol = lens _ccwsspUploadProtocol (\ s a -> s{_ccwsspUploadProtocol = a}) -- | Mask that identifies which fields on the student submission to update. -- This field is required to do an update. The update fails if invalid -- fields are specified. The following fields may be specified by teachers: -- * \`draft_grade\` * \`assigned_grade\` ccwsspUpdateMask :: Lens' CoursesCourseWorkStudentSubmissionsPatch (Maybe Text) ccwsspUpdateMask = lens _ccwsspUpdateMask (\ s a -> s{_ccwsspUpdateMask = a}) -- | Pretty-print response. ccwsspPp :: Lens' CoursesCourseWorkStudentSubmissionsPatch Bool ccwsspPp = lens _ccwsspPp (\ s a -> s{_ccwsspPp = a}) -- | Identifier of the course. This identifier can be either the -- Classroom-assigned identifier or an alias. ccwsspCourseId :: Lens' CoursesCourseWorkStudentSubmissionsPatch Text ccwsspCourseId = lens _ccwsspCourseId (\ s a -> s{_ccwsspCourseId = a}) -- | OAuth access token. ccwsspAccessToken :: Lens' CoursesCourseWorkStudentSubmissionsPatch (Maybe Text) ccwsspAccessToken = lens _ccwsspAccessToken (\ s a -> s{_ccwsspAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ccwsspUploadType :: Lens' CoursesCourseWorkStudentSubmissionsPatch (Maybe Text) ccwsspUploadType = lens _ccwsspUploadType (\ s a -> s{_ccwsspUploadType = a}) -- | Multipart request metadata. ccwsspPayload :: Lens' CoursesCourseWorkStudentSubmissionsPatch StudentSubmission ccwsspPayload = lens _ccwsspPayload (\ s a -> s{_ccwsspPayload = a}) -- | OAuth bearer token. ccwsspBearerToken :: Lens' CoursesCourseWorkStudentSubmissionsPatch (Maybe Text) ccwsspBearerToken = lens _ccwsspBearerToken (\ s a -> s{_ccwsspBearerToken = a}) -- | Identifier of the student submission. ccwsspId :: Lens' CoursesCourseWorkStudentSubmissionsPatch Text ccwsspId = lens _ccwsspId (\ s a -> s{_ccwsspId = a}) -- | JSONP ccwsspCallback :: Lens' CoursesCourseWorkStudentSubmissionsPatch (Maybe Text) ccwsspCallback = lens _ccwsspCallback (\ s a -> s{_ccwsspCallback = a}) -- | Identifier of the course work. ccwsspCourseWorkId :: Lens' CoursesCourseWorkStudentSubmissionsPatch Text ccwsspCourseWorkId = lens _ccwsspCourseWorkId (\ s a -> s{_ccwsspCourseWorkId = a}) instance GoogleRequest CoursesCourseWorkStudentSubmissionsPatch where type Rs CoursesCourseWorkStudentSubmissionsPatch = StudentSubmission type Scopes CoursesCourseWorkStudentSubmissionsPatch = '["https://www.googleapis.com/auth/classroom.coursework.me", "https://www.googleapis.com/auth/classroom.coursework.students"] requestClient CoursesCourseWorkStudentSubmissionsPatch'{..} = go _ccwsspCourseId _ccwsspCourseWorkId _ccwsspId _ccwsspXgafv _ccwsspUploadProtocol _ccwsspUpdateMask (Just _ccwsspPp) _ccwsspAccessToken _ccwsspUploadType _ccwsspBearerToken _ccwsspCallback (Just AltJSON) _ccwsspPayload classroomService where go = buildClient (Proxy :: Proxy CoursesCourseWorkStudentSubmissionsPatchResource) mempty
rueshyna/gogol
gogol-classroom/gen/Network/Google/Resource/Classroom/Courses/CourseWork/StudentSubmissions/Patch.hs
mpl-2.0
10,075
0
24
2,291
1,201
705
496
178
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.AndroidPublisher.Edits.Testers.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- /See:/ <https://developers.google.com/android-publisher Google Play Developer API Reference> for @androidpublisher.edits.testers.get@. module Network.Google.Resource.AndroidPublisher.Edits.Testers.Get ( -- * REST Resource EditsTestersGetResource -- * Creating a Request , editsTestersGet , EditsTestersGet -- * Request Lenses , etgTrack , etgPackageName , etgEditId ) where import Network.Google.AndroidPublisher.Types import Network.Google.Prelude -- | A resource alias for @androidpublisher.edits.testers.get@ method which the -- 'EditsTestersGet' request conforms to. type EditsTestersGetResource = "androidpublisher" :> "v2" :> "applications" :> Capture "packageName" Text :> "edits" :> Capture "editId" Text :> "testers" :> Capture "track" EditsTestersGetTrack :> QueryParam "alt" AltJSON :> Get '[JSON] Testers -- -- /See:/ 'editsTestersGet' smart constructor. data EditsTestersGet = EditsTestersGet' { _etgTrack :: !EditsTestersGetTrack , _etgPackageName :: !Text , _etgEditId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'EditsTestersGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'etgTrack' -- -- * 'etgPackageName' -- -- * 'etgEditId' editsTestersGet :: EditsTestersGetTrack -- ^ 'etgTrack' -> Text -- ^ 'etgPackageName' -> Text -- ^ 'etgEditId' -> EditsTestersGet editsTestersGet pEtgTrack_ pEtgPackageName_ pEtgEditId_ = EditsTestersGet' { _etgTrack = pEtgTrack_ , _etgPackageName = pEtgPackageName_ , _etgEditId = pEtgEditId_ } etgTrack :: Lens' EditsTestersGet EditsTestersGetTrack etgTrack = lens _etgTrack (\ s a -> s{_etgTrack = a}) -- | Unique identifier for the Android app that is being updated; for -- example, \"com.spiffygame\". etgPackageName :: Lens' EditsTestersGet Text etgPackageName = lens _etgPackageName (\ s a -> s{_etgPackageName = a}) -- | Unique identifier for this edit. etgEditId :: Lens' EditsTestersGet Text etgEditId = lens _etgEditId (\ s a -> s{_etgEditId = a}) instance GoogleRequest EditsTestersGet where type Rs EditsTestersGet = Testers type Scopes EditsTestersGet = '["https://www.googleapis.com/auth/androidpublisher"] requestClient EditsTestersGet'{..} = go _etgPackageName _etgEditId _etgTrack (Just AltJSON) androidPublisherService where go = buildClient (Proxy :: Proxy EditsTestersGetResource) mempty
rueshyna/gogol
gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/Edits/Testers/Get.hs
mpl-2.0
3,572
0
16
852
458
272
186
74
1
module Jammin where import Data.List data Fruit = Peach | Plum | Apple | Blackberry deriving (Eq, Show, Ord) data JamJars = Jam { fruit :: Fruit, quantity :: Int } deriving (Eq, Show, Ord) -- cardinality: Card(Int) * Card(Fruit) = 18446744073709551616 * 4 -- = 73786976294838206464 row1 = Jam Peach 5 row2 = Jam Plum 10 row3 = Jam Apple 6 row4 = Jam Blackberry 100 row5 = Jam Plum 100 row6 = Jam Apple 20 allJam = [row1, row2, row3, row4, row5, row6] totalJars :: [JamJars] -> Int totalJars = foldr (\x acc -> acc + (quantity x)) 0 mostRow :: [JamJars] -> JamJars mostRow = foldr1 (\x acc -> if (quantity x) > (quantity acc) then x else acc) compareKind :: JamJars -> JamJars -> Ordering compareKind (Jam k _) (Jam k' _) = compare k k' sameFruit :: JamJars -> JamJars -> Bool sameFruit (Jam k _) (Jam k' _) = case compare k k' of EQ -> True _ -> False sortJam :: [JamJars] -> [JamJars] sortJam = sortBy compareKind groupJam :: [JamJars] -> [[JamJars]] groupJam = groupBy sameFruit . sortJam
thewoolleyman/haskellbook
11/09/maor/jammin.hs
unlicense
1,042
0
11
237
414
227
187
35
2
-- run `cabal update` -- run `cabal install random` import System.Random roll100 :: IO Int roll100 = getStdRandom (randomR (1,100)) guess :: Int -> IO () guess x = do putStrLn "猜猜看1~100" l <- getLine if (read l :: Int) < x then do putStrLn "猜得太小了" guess x else if (read l :: Int) > x then do putStrLn "猜得太大了" guess x else do putStrLn "猜中了!你好棒!" return () main :: IO() main = do x <- roll100 guess x
bestian/haskell-sandbox
guessNumber.hs
unlicense
654
1
12
292
194
89
105
17
3
module TypeKwonDo where -- 1 f :: Int -> String f = undefined g :: String -> Char g = undefined h :: Int -> Char h x = (g . f) x -- 2 data A data B data C q :: A -> B q = undefined w :: B -> C w = undefined e :: A -> C e x = (w . q) x --3 data X data Y data Z xz :: X -> Z xz = undefined yz :: Y -> Z yz = undefined xform :: (X, Y) -> (Z, Z) xform (x, y) = ((xz x), (yz y)) --4 munge :: (x -> y) -> (y -> (w, z)) -> x -> w munge xToY yToWZ x = (fst . yToWZ . xToY) x
dmp1ce/Haskell-Programming-Exercises
Chapter 5/typeKwonDo.hs
unlicense
497
0
9
163
280
160
120
-1
-1
-- in this example, we shall check the performance of prepend and append import Control.Monad.Writer -- finalCountDown' use normal append finalCountDown' :: Int -> Writer [String] () finalCountDown' 0 = tell ["0"] finalCountDown' x = do finalCountDown' (x-1) tell [show x] -- final CountDown uses DiffList (prepend) newtype DiffList a = DiffList {getDiffList :: [a] -> [a]} toDiffList :: [a] -> DiffList a toDiffList xs = DiffList (xs++) fromDiffList :: DiffList a -> [a] fromDiffList (DiffList f) = f [] instance Monoid (DiffList a) where mempty = DiffList (\xs -> [] ++ xs) (DiffList f) `mappend` (DiffList g) = DiffList (f.g) finalCountDown :: Int -> Writer (DiffList String) () finalCountDown 0 = tell (toDiffList ["0"]) finalCountDown x = do finalCountDown (x-1) tell (toDiffList [show x])
Oscarzhao/haskell
learnyouahaskell/monad_more/performance.hs
apache-2.0
826
0
11
156
317
164
153
19
1
module Main where main :: IO () main = do print (1 + 2) putStrLn "10" print (negate (-1)) print ((+) 0 blah) where blah = negate 1
OCExercise/haskellbook-solutions
chapters/chapter05/exercises/arith3broken.hs
bsd-2-clause
156
0
11
53
81
40
41
8
1
import Criterion.Main import Control.DeepSeq import Data.Time (UTCTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Data.Text.Time (parseISODateTime) import qualified Data.TimeSeries as TS instance NFData a => NFData (TS.Series a) where rnf xs = rnf (TS.toList xs) seriesSize :: Integer seriesSize = 10^6 index :: Integer -> UTCTime index n = posixSecondsToUTCTime (fromIntegral n) lastIndex :: UTCTime lastIndex = index (seriesSize - 1) bigSeries :: TS.Series Double bigSeries = TS.tsSeries [1..seriesSize] [1..] smallSeries :: TS.Series Double smallSeries = TS.tsSeries [1..10^4] [1..] startTime :: UTCTime startTime = posixSecondsToUTCTime 1 main :: IO () main = defaultMain [ bgroup "Basic operations" [ bench "size" $ nf TS.size bigSeries , bench "valueAt" $ nf (TS.valueAt lastIndex) bigSeries , bench "slice" $ nf (TS.valueAt (index 1) . TS.slice (index 2) lastIndex) bigSeries , bench "max" $ nf maximum bigSeries , bench "fmap" $ nf (fmap (+ 2)) bigSeries ] , bgroup "Group operation" [ bench "rolling" $ nf (TS.rolling (TS.seconds 20) sum) smallSeries , bench "resampling" $ nf (TS.resample startTime (TS.seconds 20)) smallSeries ] , bgroup "IO" [ bench "load CSV" $ nfIO (TS.loadCSV TS.NoHeader parseISODateTime "test-100K.csv") ] ]
klangner/timeseries
benchmark/Benchmarks.hs
bsd-2-clause
1,377
2
15
297
527
258
269
33
1
-- | This module handles all display of output to the console when -- propellor is ensuring Properties. -- -- When two threads both try to display a message concurrently, -- the messages will be displayed sequentially. module Propellor.Message ( getMessageHandle, isConsole, forceConsole, actionMessage, actionMessageOn, warningMessage, infoMessage, errorMessage, stopPropellorMessage, processChainOutput, messagesDone, createProcessConcurrent, withConcurrentOutput, ) where import System.Console.ANSI import System.IO import Control.Monad.IO.Class (liftIO, MonadIO) import System.IO.Unsafe (unsafePerformIO) import Control.Concurrent import System.Console.Concurrent import Control.Applicative import Prelude import Propellor.Types import Propellor.Types.Exception import Utility.PartialPrelude import Utility.Monad import Utility.Exception data MessageHandle = MessageHandle { isConsole :: Bool } -- | A shared global variable for the MessageHandle. {-# NOINLINE globalMessageHandle #-} globalMessageHandle :: MVar MessageHandle globalMessageHandle = unsafePerformIO $ newMVar =<< MessageHandle <$> catchDefaultIO False (hIsTerminalDevice stdout) -- | Gets the global MessageHandle. getMessageHandle :: IO MessageHandle getMessageHandle = readMVar globalMessageHandle -- | Force console output. This can be used when stdout is not directly -- connected to a console, but is eventually going to be displayed at a -- console. forceConsole :: IO () forceConsole = modifyMVar_ globalMessageHandle $ \mh -> pure (mh { isConsole = True }) whenConsole :: String -> IO String whenConsole s = ifM (isConsole <$> getMessageHandle) ( pure s , pure "" ) -- | Shows a message while performing an action, with a colored status -- display. actionMessage :: (MonadIO m, MonadMask m, ActionResult r) => Desc -> m r -> m r actionMessage = actionMessage' Nothing -- | Shows a message while performing an action on a specified host, -- with a colored status display. actionMessageOn :: (MonadIO m, MonadMask m, ActionResult r) => HostName -> Desc -> m r -> m r actionMessageOn = actionMessage' . Just actionMessage' :: (MonadIO m, ActionResult r) => Maybe HostName -> Desc -> m r -> m r actionMessage' mhn desc a = do liftIO $ outputConcurrent =<< whenConsole (setTitleCode $ "propellor: " ++ desc) r <- a liftIO $ outputConcurrent . concat =<< sequence [ whenConsole $ setTitleCode "propellor: running" , showhn mhn , pure $ desc ++ " ... " , let (msg, intensity, color) = getActionResult r in colorLine intensity color msg ] return r where showhn Nothing = return "" showhn (Just hn) = concat <$> sequence [ whenConsole $ setSGRCode [SetColor Foreground Dull Cyan] , pure (hn ++ " ") , whenConsole $ setSGRCode [] ] warningMessage :: MonadIO m => String -> m () warningMessage s = liftIO $ outputConcurrent =<< colorLine Vivid Magenta ("** warning: " ++ s) infoMessage :: MonadIO m => [String] -> m () infoMessage ls = liftIO $ outputConcurrent $ concatMap (++ "\n") ls -- | Displays the error message in red, and throws an exception. -- -- When used inside a property, the exception will make the current -- property fail. Propellor will continue to the next property. errorMessage :: MonadIO m => String -> m a errorMessage s = liftIO $ do outputConcurrent =<< colorLine Vivid Red ("** error: " ++ s) -- Normally this exception gets caught and is not displayed, -- and propellor continues. So it's only displayed if not -- caught, and so we say, cannot continue. error "Cannot continue!" -- | Like `errorMessage`, but throws a `StopPropellorException`, -- preventing propellor from continuing to the next property. -- -- Think twice before using this. Is the problem so bad that propellor -- cannot try to ensure other properties? If not, use `errorMessage` -- instead. stopPropellorMessage :: MonadIO m => String -> m a stopPropellorMessage s = liftIO $ do outputConcurrent =<< colorLine Vivid Red ("** fatal error: " ++ s) throwM $ StopPropellorException "Cannot continue!" colorLine :: ColorIntensity -> Color -> String -> IO String colorLine intensity color msg = concat <$> sequence [ whenConsole $ setSGRCode [SetColor Foreground intensity color] , pure msg , whenConsole $ setSGRCode [] -- Note this comes after the color is reset, so that -- the color set and reset happen in the same line. , pure "\n" ] -- | Reads and displays each line from the Handle, except for the last line -- which is a Result. processChainOutput :: Handle -> IO Result processChainOutput h = go Nothing where go lastline = do v <- catchMaybeIO (hGetLine h) case v of Nothing -> case lastline of Nothing -> do return FailedChange Just l -> case readish l of Just r -> pure r Nothing -> do outputConcurrent (l ++ "\n") return FailedChange Just s -> do outputConcurrent $ maybe "" (\l -> if null l then "" else l ++ "\n") lastline go (Just s) -- | Called when all messages about properties have been printed. messagesDone :: IO () messagesDone = outputConcurrent =<< whenConsole (setTitleCode "propellor: done")
ArchiveTeam/glowing-computing-machine
src/Propellor/Message.hs
bsd-2-clause
5,147
64
22
950
1,249
648
601
108
5
module Data.Bool.Predicate ( (.&&.) , (.||.) ) where (.&&.) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool) (.&&.) f g v = f v && g v (.||.) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool) (.||.) f g v = f v || g v
sethfowler/pygmalion
src/Data/Bool/Predicate.hs
bsd-3-clause
211
0
8
56
139
80
59
7
1
module Language.Iso.Target.JavaScript where import Language.Iso.App import Language.Iso.Fls import Language.Iso.Ite import Language.Iso.Lam import Language.Iso.Tru import Language.Iso.Var newtype JavaScript = JavaScript { runJavaScript :: String } instance Show JavaScript where show (JavaScript js) = js instance Var JavaScript where var x = JavaScript x instance Lam JavaScript where lam v b = JavaScript $ "function (" ++ v ++ ") { return " ++ runJavaScript b ++ "; }" instance App JavaScript where app f x = JavaScript $ "(" ++ runJavaScript f ++ ")(" ++ runJavaScript x ++ ")" instance Fls JavaScript where fls = JavaScript $ "false" instance Tru JavaScript where tru = JavaScript $ "true" instance Ite JavaScript where ite b t f = JavaScript $ runJavaScript b ++ " ? " ++ runJavaScript t ++ " : " ++ runJavaScript f
joneshf/iso
src/Language/Iso/Target/JavaScript.hs
bsd-3-clause
905
0
11
216
266
141
125
25
0
{-| Module : Worker Description : Map Reduce only logic This module provides an entry point to compute MapReduce task. -} module Worker( run_worker -- :: Job k1 v1 k2 v2 v3 m p -> IO () ) where import Protocol import Reader import Data.List import System.Directory import System.IO import Control.Exception (handle, fromException, IOException) import Control.Monad import Control.Monad.Trans (lift) import Control.Monad.Trans.Maybe import Task import Control.Concurrent (threadDelay) ---------------------------------------------------------------- --TODO tests, improvements --Started multiple replica location handling -- --TODO it would be nice not to block --input_status :: Input -> MaybeT IO Input --input_status inpt = -- case status inpt of -- Ok -> return inpt -- Busy -> poll_input inpt -- Failed -> return inpt --TODO just ignore it? -- --poll_input :: Input -> MaybeT IO Input --poll_input inpt = do -- M_task_input t_input <- exchange_msg $ W_input $ Include [input_id inpt] -- TODO more, done -- return $ (head . inputs) t_input --[Input] ?? I ask for just one input_id, but can for a list -- ----tries to read replicas in order --read_replicas :: Task -> [Replica] -> [Replica] -> IO (Either [Replica] [String]) --read_replicas _ [] broken = return $ Left broken --read_replicas task (r:rs) broken = do -- read_repl <- read_dir_rest (replica_location r) task -- case read_repl of -- Just s -> return $ Right s -- Nothing -> read_replicas task rs (r:broken) -- ---- TODO after this function returns Nothing -> send Error msg to disco! --handle_mult_repl :: Task -> Input -> IO (Maybe [String]) --handle_mult_repl task inpt = do -- let repl_list = replicas inpt -- read_repl <- read_replicas task repl_list [] -- case read_repl of -- Right s -> return $ Just s -- --Left broken -> input_err inpt broken --TODO what with Nothing? -- Left broken -> handle_again task inpt broken --TODO what with Nothing? -- ----TODO change that silly function, abstract replica processing? --handle_again :: Task -> Input -> [Replica] -> IO (Maybe [String]) --handle_again task inpt broken = do -- new_in <- input_err inpt broken -- case new_in of -- Nothing -> return Nothing -- Just new_inpt -> do -- let repl_list = replicas new_inpt -- read_repl <- read_replicas task repl_list [] -- case read_repl of -- Right s -> return $ Just s -- Left broken -> return Nothing -- -- --input_err :: Input -> [Replica] -> IO (Maybe Input) --input_err inpt broken = do -- let r_ids = map replica_id broken -- msg <- runMaybeT $ exchange_msg $ W_input_err $ Input_err (input_id inpt) r_ids -- case msg of -- Just (M_retry new_replicas) -> return $ Just inpt {replicas = new_replicas} -- Just (M_wait how_long) -> (threadDelay $ how_long * 10^6) >> (runMaybeT $ poll_input inpt) --TODO what if wait repeats? -- Just (M_fail) -> return Nothing -- otherwise -> return Nothing ---------------------------------------------------------------- -- | Gives replicas' locations for a running task (now, for every input only one replica location is taken) get_locations :: [Input] -> [String] get_locations inpts = map replica_location $ map (head . replicas) inpts --TODO takes just first replica location -- | This function prepares the environment for running a task's process function: -- creates file for output, runs the task function, prepares output message run_process_function :: Process p -> FilePath -> String -> [String] -> Task -> Job k1 v1 k2 v2 v3 m p -> IO [Maybe Output] run_process_function process_fun pwd file_templ inpt_list task job = do (tempFilePath, tempHandle) <- openTempFile pwd file_templ process_fun inpt_list tempHandle $ params job let out_path = disco_output_path tempFilePath task out_size <- hFileSize tempHandle hClose tempHandle return $ [Just (Output (Label 0) out_path out_size)] --TODO labels? -- | Runs stage, gets inputs' locations run_stage :: FilePath -> String -> Task -> [Input] -> Process p -> Job k1 v1 k2 v2 v3 m p -> IO [Maybe Output] run_stage pwd file_templ task inpts process_fun job = do let locs = get_locations inpts read_inpts <- read_inputs task locs --TODO try -- TODO call init function run_process_function process_fun pwd file_templ read_inpts task job--check combine, sort flags + input_hook fun -- TODO call done function -- | Shuffling stage shuffle_out :: [Input] -> IO [Maybe Output] shuffle_out inpts = return $ map (\(Input _ _ lab repls) -> Just (Output lab (loc repls) 0)) inpts where loc = \xs -> replica_location (head xs) --TODO just first replica location -- | Iterates over the list of outputs and passes them to protocol handling part -- responsible for sending output message to Disco send_outputs :: (Maybe Output) -> MaybeT IO Master_msg send_outputs output = do case output of Just out -> do exchange_msg $ W_output out Nothing -> mzero --TODO -- | Polling for inputs, until done flag is met get_inputs :: [Int] -> MaybeT IO [Input] get_inputs exclude = do M_task_input t_input <- exchange_msg $ W_input $ Exclude exclude let inpts = inputs t_input let excl = exclude ++ (inpt_ids t_input) case (input_flag t_input) of Done -> return inpts More -> liftM (inpts ++) $ get_inputs excl inpt_ids :: Task_input -> [Int] inpt_ids t_inpt = map input_id (inputs t_inpt) -- | Helper function, returns prefix for output file and stage process function get_stage_tmp :: Task -> Job k1 v1 k2 v2 v3 m p -> (String, Process p) get_stage_tmp task job = case stage task of "map" -> ("map_out_", map_reader job) "reduce" -> ("reduce_out_", reduce_reader job) -- | Expect OK message from Disco expect_ok :: MaybeT IO Master_msg expect_ok = recive >>= (\msg -> case msg of M_ok -> return M_ok _ -> mzero) -- | Initializes a worker, sends messages in order and runs stage run :: Job k1 v1 k2 v2 v3 m p -> MaybeT IO () run job = do pwd <- lift getCurrentDirectory lift send_worker expect_ok M_task task <- exchange_msg W_task let (file_templ, process_fun) = get_stage_tmp task job inputs_list <- get_inputs [] outputs <- case stage task of "map_shuffle" -> lift $ shuffle_out inputs_list _ -> do lift $ run_stage pwd file_templ task inputs_list process_fun job mapM send_outputs outputs exchange_msg W_done return () --TODO errors and maybe -- | Entry point to whole worker logic run_worker :: Job k1 v1 k2 v2 v3 m p -> IO () run_worker job = do result <- runMaybeT $ run job --TODO Nothing + wrap it case result of Nothing -> (runMaybeT $ exchange_msg $ W_fatal "Protocol error") >> return () Just _ -> return ()
zuzia/haskell_worker
src/Worker.hs
bsd-3-clause
6,975
0
14
1,581
1,215
636
579
79
2
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Web.RTBBidder.Protocol.Adx.BidRequest.UserDataTreatment (UserDataTreatment(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified GHC.Generics as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data UserDataTreatment = TAG_FOR_CHILD_DIRECTED_TREATMENT deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable UserDataTreatment instance Prelude'.Bounded UserDataTreatment where minBound = TAG_FOR_CHILD_DIRECTED_TREATMENT maxBound = TAG_FOR_CHILD_DIRECTED_TREATMENT instance P'.Default UserDataTreatment where defaultValue = TAG_FOR_CHILD_DIRECTED_TREATMENT toMaybe'Enum :: Prelude'.Int -> P'.Maybe UserDataTreatment toMaybe'Enum 0 = Prelude'.Just TAG_FOR_CHILD_DIRECTED_TREATMENT toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum UserDataTreatment where fromEnum TAG_FOR_CHILD_DIRECTED_TREATMENT = 0 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Web.RTBBidder.Protocol.Adx.BidRequest.UserDataTreatment") . toMaybe'Enum succ _ = Prelude'.error "hprotoc generated code: succ failure for type Web.RTBBidder.Protocol.Adx.BidRequest.UserDataTreatment" pred _ = Prelude'.error "hprotoc generated code: pred failure for type Web.RTBBidder.Protocol.Adx.BidRequest.UserDataTreatment" instance P'.Wire UserDataTreatment where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB UserDataTreatment instance P'.MessageAPI msg' (msg' -> UserDataTreatment) UserDataTreatment where getVal m' f' = f' m' instance P'.ReflectEnum UserDataTreatment where reflectEnum = [(0, "TAG_FOR_CHILD_DIRECTED_TREATMENT", TAG_FOR_CHILD_DIRECTED_TREATMENT)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".Adx.BidRequest.UserDataTreatment") ["Web", "RTBBidder", "Protocol"] ["Adx", "BidRequest"] "UserDataTreatment") ["Web", "RTBBidder", "Protocol", "Adx", "BidRequest", "UserDataTreatment.hs"] [(0, "TAG_FOR_CHILD_DIRECTED_TREATMENT")] instance P'.TextType UserDataTreatment where tellT = P'.tellShow getT = P'.getRead
hiratara/hs-rtb-bidder
src/Web/RTBBidder/Protocol/Adx/BidRequest/UserDataTreatment.hs
bsd-3-clause
2,715
0
11
383
568
312
256
50
1
-------------------------------------------------------------------------------- -- | The LLVM Type System. -- module Llvm.Types where #include "HsVersions.h" import Data.Char import Data.Int import Data.List (intercalate) import Numeric import Constants import FastString import Unique -- from NCG import PprBase -- ----------------------------------------------------------------------------- -- * LLVM Basic Types and Variables -- -- | A global mutable variable. Maybe defined or external type LMGlobal = (LlvmVar, Maybe LlvmStatic) -- | A String in LLVM type LMString = FastString -- | A type alias type LlvmAlias = (LMString, LlvmType) -- | Llvm Types data LlvmType = LMInt Int -- ^ An integer with a given width in bits. | LMFloat -- ^ 32 bit floating point | LMDouble -- ^ 64 bit floating point | LMFloat80 -- ^ 80 bit (x86 only) floating point | LMFloat128 -- ^ 128 bit floating point | LMPointer LlvmType -- ^ A pointer to a 'LlvmType' | LMArray Int LlvmType -- ^ An array of 'LlvmType' | LMLabel -- ^ A 'LlvmVar' can represent a label (address) | LMVoid -- ^ Void type | LMStruct [LlvmType] -- ^ Structure type | LMAlias LlvmAlias -- ^ A type alias -- | Function type, used to create pointers to functions | LMFunction LlvmFunctionDecl deriving (Eq) instance Show LlvmType where show (LMInt size ) = "i" ++ show size show (LMFloat ) = "float" show (LMDouble ) = "double" show (LMFloat80 ) = "x86_fp80" show (LMFloat128 ) = "fp128" show (LMPointer x ) = show x ++ "*" show (LMArray nr tp ) = "[" ++ show nr ++ " x " ++ show tp ++ "]" show (LMLabel ) = "label" show (LMVoid ) = "void" show (LMStruct tys ) = "<{" ++ (commaCat tys) ++ "}>" show (LMFunction (LlvmFunctionDecl _ _ _ r varg p _)) = let varg' = case varg of VarArgs | null args -> "..." | otherwise -> ", ..." _otherwise -> "" -- by default we don't print param attributes args = intercalate ", " $ map (show . fst) p in show r ++ " (" ++ args ++ varg' ++ ")" show (LMAlias (s,_)) = "%" ++ unpackFS s -- | LLVM metadata values. Used for representing debug and optimization -- information. data LlvmMetaVal -- | Metadata string = MetaStr LMString -- | Metadata node | MetaNode LlvmMetaUnamed -- | Normal value type as metadata | MetaVar LlvmVar deriving (Eq) -- | LLVM metadata nodes. data LlvmMeta -- | Unamed metadata = MetaUnamed LlvmMetaUnamed [LlvmMetaVal] -- | Named metadata | MetaNamed LMString [LlvmMetaUnamed] deriving (Eq) -- | Unamed metadata variable. newtype LlvmMetaUnamed = LMMetaUnamed Int instance Eq LlvmMetaUnamed where (==) (LMMetaUnamed n) (LMMetaUnamed m) = n == m instance Show LlvmMetaVal where show (MetaStr s) = "metadata !\"" ++ unpackFS s ++ "\"" show (MetaNode n) = "metadata " ++ show n show (MetaVar v) = show v instance Show LlvmMetaUnamed where show (LMMetaUnamed u) = "!" ++ show u instance Show LlvmMeta where show (MetaUnamed m _) = show m show (MetaNamed m _) = "!" ++ unpackFS m -- | An LLVM section definition. If Nothing then let LLVM decide the section type LMSection = Maybe LMString type LMAlign = Maybe Int type LMConst = Bool -- ^ is a variable constant or not -- | LLVM Variables data LlvmVar -- | Variables with a global scope. = LMGlobalVar LMString LlvmType LlvmLinkageType LMSection LMAlign LMConst -- | Variables local to a function or parameters. | LMLocalVar Unique LlvmType -- | Named local variables. Sometimes we need to be able to explicitly name -- variables (e.g for function arguments). | LMNLocalVar LMString LlvmType -- | A constant variable | LMLitVar LlvmLit deriving (Eq) instance Show LlvmVar where show (LMLitVar x) = show x show (x ) = show (getVarType x) ++ " " ++ getName x -- | Llvm Literal Data. -- -- These can be used inline in expressions. data LlvmLit -- | Refers to an integer constant (i64 42). = LMIntLit Integer LlvmType -- | Floating point literal | LMFloatLit Double LlvmType -- | Literal NULL, only applicable to pointer types | LMNullLit LlvmType -- | Undefined value, random bit pattern. Useful for optimisations. | LMUndefLit LlvmType deriving (Eq) instance Show LlvmLit where show l = show (getLitType l) ++ " " ++ getLit l -- | Llvm Static Data. -- -- These represent the possible global level variables and constants. data LlvmStatic = LMComment LMString -- ^ A comment in a static section | LMStaticLit LlvmLit -- ^ A static variant of a literal value | LMUninitType LlvmType -- ^ For uninitialised data | LMStaticStr LMString LlvmType -- ^ Defines a static 'LMString' | LMStaticArray [LlvmStatic] LlvmType -- ^ A static array | LMStaticStruc [LlvmStatic] LlvmType -- ^ A static structure type | LMStaticPointer LlvmVar -- ^ A pointer to other data -- static expressions, could split out but leave -- for moment for ease of use. Not many of them. | LMBitc LlvmStatic LlvmType -- ^ Pointer to Pointer conversion | LMPtoI LlvmStatic LlvmType -- ^ Pointer to Integer conversion | LMAdd LlvmStatic LlvmStatic -- ^ Constant addition operation | LMSub LlvmStatic LlvmStatic -- ^ Constant subtraction operation instance Show LlvmStatic where show (LMComment s) = "; " ++ unpackFS s show (LMStaticLit l ) = show l show (LMUninitType t) = show t ++ " undef" show (LMStaticStr s t) = show t ++ " c\"" ++ unpackFS s ++ "\\00\"" show (LMStaticArray d t) = show t ++ " [" ++ commaCat d ++ "]" show (LMStaticStruc d t) = show t ++ "<{" ++ commaCat d ++ "}>" show (LMStaticPointer v) = show v show (LMBitc v t) = show t ++ " bitcast (" ++ show v ++ " to " ++ show t ++ ")" show (LMPtoI v t) = show t ++ " ptrtoint (" ++ show v ++ " to " ++ show t ++ ")" show (LMAdd s1 s2) = let ty1 = getStatType s1 op = if isFloat ty1 then " fadd (" else " add (" in if ty1 == getStatType s2 then show ty1 ++ op ++ show s1 ++ "," ++ show s2 ++ ")" else error $ "LMAdd with different types! s1: " ++ show s1 ++ ", s2: " ++ show s2 show (LMSub s1 s2) = let ty1 = getStatType s1 op = if isFloat ty1 then " fsub (" else " sub (" in if ty1 == getStatType s2 then show ty1 ++ op ++ show s1 ++ "," ++ show s2 ++ ")" else error $ "LMSub with different types! s1: " ++ show s1 ++ ", s2: " ++ show s2 -- | Concatenate an array together, separated by commas commaCat :: Show a => [a] -> String commaCat xs = intercalate ", " $ map show xs -- ----------------------------------------------------------------------------- -- ** Operations on LLVM Basic Types and Variables -- -- | Return the variable name or value of the 'LlvmVar' -- in Llvm IR textual representation (e.g. @\@x@, @%y@ or @42@). getName :: LlvmVar -> String getName v@(LMGlobalVar _ _ _ _ _ _) = "@" ++ getPlainName v getName v@(LMLocalVar _ _ ) = "%" ++ getPlainName v getName v@(LMNLocalVar _ _ ) = "%" ++ getPlainName v getName v@(LMLitVar _ ) = getPlainName v -- | Return the variable name or value of the 'LlvmVar' -- in a plain textual representation (e.g. @x@, @y@ or @42@). getPlainName :: LlvmVar -> String getPlainName (LMGlobalVar x _ _ _ _ _) = unpackFS x getPlainName (LMLocalVar x LMLabel ) = show x getPlainName (LMLocalVar x _ ) = "l" ++ show x getPlainName (LMNLocalVar x _ ) = unpackFS x getPlainName (LMLitVar x ) = getLit x -- | Print a literal value. No type. getLit :: LlvmLit -> String getLit (LMIntLit i (LMInt 32)) = show (fromInteger i :: Int32) getLit (LMIntLit i (LMInt 64)) = show (fromInteger i :: Int64) getLit (LMIntLit i _ ) = show (fromInteger i :: Int) getLit (LMFloatLit r LMFloat ) = fToStr $ realToFrac r getLit (LMFloatLit r LMDouble) = dToStr r getLit f@(LMFloatLit _ _) = error $ "Can't print this float literal!" ++ show f getLit (LMNullLit _ ) = "null" getLit (LMUndefLit _ ) = "undef" -- | Return the 'LlvmType' of the 'LlvmVar' getVarType :: LlvmVar -> LlvmType getVarType (LMGlobalVar _ y _ _ _ _) = y getVarType (LMLocalVar _ y ) = y getVarType (LMNLocalVar _ y ) = y getVarType (LMLitVar l ) = getLitType l -- | Return the 'LlvmType' of a 'LlvmLit' getLitType :: LlvmLit -> LlvmType getLitType (LMIntLit _ t) = t getLitType (LMFloatLit _ t) = t getLitType (LMNullLit t) = t getLitType (LMUndefLit t) = t -- | Return the 'LlvmType' of the 'LlvmStatic' getStatType :: LlvmStatic -> LlvmType getStatType (LMStaticLit l ) = getLitType l getStatType (LMUninitType t) = t getStatType (LMStaticStr _ t) = t getStatType (LMStaticArray _ t) = t getStatType (LMStaticStruc _ t) = t getStatType (LMStaticPointer v) = getVarType v getStatType (LMBitc _ t) = t getStatType (LMPtoI _ t) = t getStatType (LMAdd t _) = getStatType t getStatType (LMSub t _) = getStatType t getStatType (LMComment _) = error "Can't call getStatType on LMComment!" -- | Return the 'LlvmType' of the 'LMGlobal' getGlobalType :: LMGlobal -> LlvmType getGlobalType (v, _) = getVarType v -- | Return the 'LlvmVar' part of a 'LMGlobal' getGlobalVar :: LMGlobal -> LlvmVar getGlobalVar (v, _) = v -- | Return the 'LlvmLinkageType' for a 'LlvmVar' getLink :: LlvmVar -> LlvmLinkageType getLink (LMGlobalVar _ _ l _ _ _) = l getLink _ = Internal -- | Add a pointer indirection to the supplied type. 'LMLabel' and 'LMVoid' -- cannot be lifted. pLift :: LlvmType -> LlvmType pLift (LMLabel) = error "Labels are unliftable" pLift (LMVoid) = error "Voids are unliftable" pLift x = LMPointer x -- | Lower a variable of 'LMPointer' type. pVarLift :: LlvmVar -> LlvmVar pVarLift (LMGlobalVar s t l x a c) = LMGlobalVar s (pLift t) l x a c pVarLift (LMLocalVar s t ) = LMLocalVar s (pLift t) pVarLift (LMNLocalVar s t ) = LMNLocalVar s (pLift t) pVarLift (LMLitVar _ ) = error $ "Can't lower a literal type!" -- | Remove the pointer indirection of the supplied type. Only 'LMPointer' -- constructors can be lowered. pLower :: LlvmType -> LlvmType pLower (LMPointer x) = x pLower x = error $ show x ++ " is a unlowerable type, need a pointer" -- | Lower a variable of 'LMPointer' type. pVarLower :: LlvmVar -> LlvmVar pVarLower (LMGlobalVar s t l x a c) = LMGlobalVar s (pLower t) l x a c pVarLower (LMLocalVar s t ) = LMLocalVar s (pLower t) pVarLower (LMNLocalVar s t ) = LMNLocalVar s (pLower t) pVarLower (LMLitVar _ ) = error $ "Can't lower a literal type!" -- | Test if the given 'LlvmType' is an integer isInt :: LlvmType -> Bool isInt (LMInt _) = True isInt _ = False -- | Test if the given 'LlvmType' is a floating point type isFloat :: LlvmType -> Bool isFloat LMFloat = True isFloat LMDouble = True isFloat LMFloat80 = True isFloat LMFloat128 = True isFloat _ = False -- | Test if the given 'LlvmType' is an 'LMPointer' construct isPointer :: LlvmType -> Bool isPointer (LMPointer _) = True isPointer _ = False -- | Test if a 'LlvmVar' is global. isGlobal :: LlvmVar -> Bool isGlobal (LMGlobalVar _ _ _ _ _ _) = True isGlobal _ = False -- | Width in bits of an 'LlvmType', returns 0 if not applicable llvmWidthInBits :: LlvmType -> Int llvmWidthInBits (LMInt n) = n llvmWidthInBits (LMFloat) = 32 llvmWidthInBits (LMDouble) = 64 llvmWidthInBits (LMFloat80) = 80 llvmWidthInBits (LMFloat128) = 128 -- Could return either a pointer width here or the width of what -- it points to. We will go with the former for now. llvmWidthInBits (LMPointer _) = llvmWidthInBits llvmWord llvmWidthInBits (LMArray _ _) = llvmWidthInBits llvmWord llvmWidthInBits LMLabel = 0 llvmWidthInBits LMVoid = 0 llvmWidthInBits (LMStruct tys) = sum $ map llvmWidthInBits tys llvmWidthInBits (LMFunction _) = 0 llvmWidthInBits (LMAlias (_,t)) = llvmWidthInBits t -- ----------------------------------------------------------------------------- -- ** Shortcut for Common Types -- i128, i64, i32, i16, i8, i1, i8Ptr :: LlvmType i128 = LMInt 128 i64 = LMInt 64 i32 = LMInt 32 i16 = LMInt 16 i8 = LMInt 8 i1 = LMInt 1 i8Ptr = pLift i8 -- | The target architectures word size llvmWord, llvmWordPtr :: LlvmType llvmWord = LMInt (wORD_SIZE * 8) llvmWordPtr = pLift llvmWord -- ----------------------------------------------------------------------------- -- * LLVM Function Types -- -- | An LLVM Function data LlvmFunctionDecl = LlvmFunctionDecl { -- | Unique identifier of the function decName :: LMString, -- | LinkageType of the function funcLinkage :: LlvmLinkageType, -- | The calling convention of the function funcCc :: LlvmCallConvention, -- | Type of the returned value decReturnType :: LlvmType, -- | Indicates if this function uses varargs decVarargs :: LlvmParameterListType, -- | Parameter types and attributes decParams :: [LlvmParameter], -- | Function align value, must be power of 2 funcAlign :: LMAlign } deriving (Eq) instance Show LlvmFunctionDecl where show (LlvmFunctionDecl n l c r varg p a) = let varg' = case varg of VarArgs | null args -> "..." | otherwise -> ", ..." _otherwise -> "" align = case a of Just a' -> " align " ++ show a' Nothing -> "" -- by default we don't print param attributes args = intercalate ", " $ map (show . fst) p in show l ++ " " ++ show c ++ " " ++ show r ++ " @" ++ unpackFS n ++ "(" ++ args ++ varg' ++ ")" ++ align type LlvmFunctionDecls = [LlvmFunctionDecl] type LlvmParameter = (LlvmType, [LlvmParamAttr]) -- | LLVM Parameter Attributes. -- -- Parameter attributes are used to communicate additional information about -- the result or parameters of a function data LlvmParamAttr -- | This indicates to the code generator that the parameter or return value -- should be zero-extended to a 32-bit value by the caller (for a parameter) -- or the callee (for a return value). = ZeroExt -- | This indicates to the code generator that the parameter or return value -- should be sign-extended to a 32-bit value by the caller (for a parameter) -- or the callee (for a return value). | SignExt -- | This indicates that this parameter or return value should be treated in -- a special target-dependent fashion during while emitting code for a -- function call or return (usually, by putting it in a register as opposed -- to memory). | InReg -- | This indicates that the pointer parameter should really be passed by -- value to the function. | ByVal -- | This indicates that the pointer parameter specifies the address of a -- structure that is the return value of the function in the source program. | SRet -- | This indicates that the pointer does not alias any global or any other -- parameter. | NoAlias -- | This indicates that the callee does not make any copies of the pointer -- that outlive the callee itself | NoCapture -- | This indicates that the pointer parameter can be excised using the -- trampoline intrinsics. | Nest deriving (Eq) instance Show LlvmParamAttr where show ZeroExt = "zeroext" show SignExt = "signext" show InReg = "inreg" show ByVal = "byval" show SRet = "sret" show NoAlias = "noalias" show NoCapture = "nocapture" show Nest = "nest" -- | Llvm Function Attributes. -- -- Function attributes are set to communicate additional information about a -- function. Function attributes are considered to be part of the function, -- not of the function type, so functions with different parameter attributes -- can have the same function type. Functions can have multiple attributes. -- -- Descriptions taken from <http://llvm.org/docs/LangRef.html#fnattrs> data LlvmFuncAttr -- | This attribute indicates that the inliner should attempt to inline this -- function into callers whenever possible, ignoring any active inlining -- size threshold for this caller. = AlwaysInline -- | This attribute indicates that the source code contained a hint that -- inlining this function is desirable (such as the \"inline\" keyword in -- C/C++). It is just a hint; it imposes no requirements on the inliner. | InlineHint -- | This attribute indicates that the inliner should never inline this -- function in any situation. This attribute may not be used together -- with the alwaysinline attribute. | NoInline -- | This attribute suggests that optimization passes and code generator -- passes make choices that keep the code size of this function low, and -- otherwise do optimizations specifically to reduce code size. | OptSize -- | This function attribute indicates that the function never returns -- normally. This produces undefined behavior at runtime if the function -- ever does dynamically return. | NoReturn -- | This function attribute indicates that the function never returns with -- an unwind or exceptional control flow. If the function does unwind, its -- runtime behavior is undefined. | NoUnwind -- | This attribute indicates that the function computes its result (or -- decides to unwind an exception) based strictly on its arguments, without -- dereferencing any pointer arguments or otherwise accessing any mutable -- state (e.g. memory, control registers, etc) visible to caller functions. -- It does not write through any pointer arguments (including byval -- arguments) and never changes any state visible to callers. This means -- that it cannot unwind exceptions by calling the C++ exception throwing -- methods, but could use the unwind instruction. | ReadNone -- | This attribute indicates that the function does not write through any -- pointer arguments (including byval arguments) or otherwise modify any -- state (e.g. memory, control registers, etc) visible to caller functions. -- It may dereference pointer arguments and read state that may be set in -- the caller. A readonly function always returns the same value (or unwinds -- an exception identically) when called with the same set of arguments and -- global state. It cannot unwind an exception by calling the C++ exception -- throwing methods, but may use the unwind instruction. | ReadOnly -- | This attribute indicates that the function should emit a stack smashing -- protector. It is in the form of a \"canary\"—a random value placed on the -- stack before the local variables that's checked upon return from the -- function to see if it has been overwritten. A heuristic is used to -- determine if a function needs stack protectors or not. -- -- If a function that has an ssp attribute is inlined into a function that -- doesn't have an ssp attribute, then the resulting function will have an -- ssp attribute. | Ssp -- | This attribute indicates that the function should always emit a stack -- smashing protector. This overrides the ssp function attribute. -- -- If a function that has an sspreq attribute is inlined into a function -- that doesn't have an sspreq attribute or which has an ssp attribute, -- then the resulting function will have an sspreq attribute. | SspReq -- | This attribute indicates that the code generator should not use a red -- zone, even if the target-specific ABI normally permits it. | NoRedZone -- | This attributes disables implicit floating point instructions. | NoImplicitFloat -- | This attribute disables prologue / epilogue emission for the function. -- This can have very system-specific consequences. | Naked deriving (Eq) instance Show LlvmFuncAttr where show AlwaysInline = "alwaysinline" show InlineHint = "inlinehint" show NoInline = "noinline" show OptSize = "optsize" show NoReturn = "noreturn" show NoUnwind = "nounwind" show ReadNone = "readnon" show ReadOnly = "readonly" show Ssp = "ssp" show SspReq = "ssqreq" show NoRedZone = "noredzone" show NoImplicitFloat = "noimplicitfloat" show Naked = "naked" -- | Different types to call a function. data LlvmCallType -- | Normal call, allocate a new stack frame. = StdCall -- | Tail call, perform the call in the current stack frame. | TailCall deriving (Eq,Show) -- | Different calling conventions a function can use. data LlvmCallConvention -- | The C calling convention. -- This calling convention (the default if no other calling convention is -- specified) matches the target C calling conventions. This calling -- convention supports varargs function calls and tolerates some mismatch in -- the declared prototype and implemented declaration of the function (as -- does normal C). = CC_Ccc -- | This calling convention attempts to make calls as fast as possible -- (e.g. by passing things in registers). This calling convention allows -- the target to use whatever tricks it wants to produce fast code for the -- target, without having to conform to an externally specified ABI -- (Application Binary Interface). Implementations of this convention should -- allow arbitrary tail call optimization to be supported. This calling -- convention does not support varargs and requires the prototype of al -- callees to exactly match the prototype of the function definition. | CC_Fastcc -- | This calling convention attempts to make code in the caller as efficient -- as possible under the assumption that the call is not commonly executed. -- As such, these calls often preserve all registers so that the call does -- not break any live ranges in the caller side. This calling convention -- does not support varargs and requires the prototype of all callees to -- exactly match the prototype of the function definition. | CC_Coldcc -- | Any calling convention may be specified by number, allowing -- target-specific calling conventions to be used. Target specific calling -- conventions start at 64. | CC_Ncc Int -- | X86 Specific 'StdCall' convention. LLVM includes a specific alias for it -- rather than just using CC_Ncc. | CC_X86_Stdcc deriving (Eq) instance Show LlvmCallConvention where show CC_Ccc = "ccc" show CC_Fastcc = "fastcc" show CC_Coldcc = "coldcc" show (CC_Ncc i) = "cc " ++ show i show CC_X86_Stdcc = "x86_stdcallcc" -- | Functions can have a fixed amount of parameters, or a variable amount. data LlvmParameterListType -- Fixed amount of arguments. = FixedArgs -- Variable amount of arguments. | VarArgs deriving (Eq,Show) -- | Linkage type of a symbol. -- -- The description of the constructors is copied from the Llvm Assembly Language -- Reference Manual <http://www.llvm.org/docs/LangRef.html#linkage>, because -- they correspond to the Llvm linkage types. data LlvmLinkageType -- | Global values with internal linkage are only directly accessible by -- objects in the current module. In particular, linking code into a module -- with an internal global value may cause the internal to be renamed as -- necessary to avoid collisions. Because the symbol is internal to the -- module, all references can be updated. This corresponds to the notion -- of the @static@ keyword in C. = Internal -- | Globals with @linkonce@ linkage are merged with other globals of the -- same name when linkage occurs. This is typically used to implement -- inline functions, templates, or other code which must be generated -- in each translation unit that uses it. Unreferenced linkonce globals are -- allowed to be discarded. | LinkOnce -- | @weak@ linkage is exactly the same as linkonce linkage, except that -- unreferenced weak globals may not be discarded. This is used for globals -- that may be emitted in multiple translation units, but that are not -- guaranteed to be emitted into every translation unit that uses them. One -- example of this are common globals in C, such as @int X;@ at global -- scope. | Weak -- | @appending@ linkage may only be applied to global variables of pointer -- to array type. When two global variables with appending linkage are -- linked together, the two global arrays are appended together. This is -- the Llvm, typesafe, equivalent of having the system linker append -- together @sections@ with identical names when .o files are linked. | Appending -- | The semantics of this linkage follow the ELF model: the symbol is weak -- until linked, if not linked, the symbol becomes null instead of being an -- undefined reference. | ExternWeak -- | The symbol participates in linkage and can be used to resolve external -- symbol references. | ExternallyVisible -- | Alias for 'ExternallyVisible' but with explicit textual form in LLVM -- assembly. | External deriving (Eq) instance Show LlvmLinkageType where show Internal = "internal" show LinkOnce = "linkonce" show Weak = "weak" show Appending = "appending" show ExternWeak = "extern_weak" -- ExternallyVisible does not have a textual representation, it is -- the linkage type a function resolves to if no other is specified -- in Llvm. show ExternallyVisible = "" show External = "external" -- ----------------------------------------------------------------------------- -- * LLVM Operations -- -- | Llvm binary operators machine operations. data LlvmMachOp = LM_MO_Add -- ^ add two integer, floating point or vector values. | LM_MO_Sub -- ^ subtract two ... | LM_MO_Mul -- ^ multiply .. | LM_MO_UDiv -- ^ unsigned integer or vector division. | LM_MO_SDiv -- ^ signed integer .. | LM_MO_URem -- ^ unsigned integer or vector remainder (mod) | LM_MO_SRem -- ^ signed ... | LM_MO_FAdd -- ^ add two floating point or vector values. | LM_MO_FSub -- ^ subtract two ... | LM_MO_FMul -- ^ multiply ... | LM_MO_FDiv -- ^ divide ... | LM_MO_FRem -- ^ remainder ... -- | Left shift | LM_MO_Shl -- | Logical shift right -- Shift right, filling with zero | LM_MO_LShr -- | Arithmetic shift right -- The most significant bits of the result will be equal to the sign bit of -- the left operand. | LM_MO_AShr | LM_MO_And -- ^ AND bitwise logical operation. | LM_MO_Or -- ^ OR bitwise logical operation. | LM_MO_Xor -- ^ XOR bitwise logical operation. deriving (Eq) instance Show LlvmMachOp where show LM_MO_Add = "add" show LM_MO_Sub = "sub" show LM_MO_Mul = "mul" show LM_MO_UDiv = "udiv" show LM_MO_SDiv = "sdiv" show LM_MO_URem = "urem" show LM_MO_SRem = "srem" show LM_MO_FAdd = "fadd" show LM_MO_FSub = "fsub" show LM_MO_FMul = "fmul" show LM_MO_FDiv = "fdiv" show LM_MO_FRem = "frem" show LM_MO_Shl = "shl" show LM_MO_LShr = "lshr" show LM_MO_AShr = "ashr" show LM_MO_And = "and" show LM_MO_Or = "or" show LM_MO_Xor = "xor" -- | Llvm compare operations. data LlvmCmpOp = LM_CMP_Eq -- ^ Equal (Signed and Unsigned) | LM_CMP_Ne -- ^ Not equal (Signed and Unsigned) | LM_CMP_Ugt -- ^ Unsigned greater than | LM_CMP_Uge -- ^ Unsigned greater than or equal | LM_CMP_Ult -- ^ Unsigned less than | LM_CMP_Ule -- ^ Unsigned less than or equal | LM_CMP_Sgt -- ^ Signed greater than | LM_CMP_Sge -- ^ Signed greater than or equal | LM_CMP_Slt -- ^ Signed less than | LM_CMP_Sle -- ^ Signed less than or equal -- Float comparisons. GHC uses a mix of ordered and unordered float -- comparisons. | LM_CMP_Feq -- ^ Float equal | LM_CMP_Fne -- ^ Float not equal | LM_CMP_Fgt -- ^ Float greater than | LM_CMP_Fge -- ^ Float greater than or equal | LM_CMP_Flt -- ^ Float less than | LM_CMP_Fle -- ^ Float less than or equal deriving (Eq) instance Show LlvmCmpOp where show LM_CMP_Eq = "eq" show LM_CMP_Ne = "ne" show LM_CMP_Ugt = "ugt" show LM_CMP_Uge = "uge" show LM_CMP_Ult = "ult" show LM_CMP_Ule = "ule" show LM_CMP_Sgt = "sgt" show LM_CMP_Sge = "sge" show LM_CMP_Slt = "slt" show LM_CMP_Sle = "sle" show LM_CMP_Feq = "oeq" show LM_CMP_Fne = "une" show LM_CMP_Fgt = "ogt" show LM_CMP_Fge = "oge" show LM_CMP_Flt = "olt" show LM_CMP_Fle = "ole" -- | Llvm cast operations. data LlvmCastOp = LM_Trunc -- ^ Integer truncate | LM_Zext -- ^ Integer extend (zero fill) | LM_Sext -- ^ Integer extend (sign fill) | LM_Fptrunc -- ^ Float truncate | LM_Fpext -- ^ Float extend | LM_Fptoui -- ^ Float to unsigned Integer | LM_Fptosi -- ^ Float to signed Integer | LM_Uitofp -- ^ Unsigned Integer to Float | LM_Sitofp -- ^ Signed Int to Float | LM_Ptrtoint -- ^ Pointer to Integer | LM_Inttoptr -- ^ Integer to Pointer | LM_Bitcast -- ^ Cast between types where no bit manipulation is needed deriving (Eq) instance Show LlvmCastOp where show LM_Trunc = "trunc" show LM_Zext = "zext" show LM_Sext = "sext" show LM_Fptrunc = "fptrunc" show LM_Fpext = "fpext" show LM_Fptoui = "fptoui" show LM_Fptosi = "fptosi" show LM_Uitofp = "uitofp" show LM_Sitofp = "sitofp" show LM_Ptrtoint = "ptrtoint" show LM_Inttoptr = "inttoptr" show LM_Bitcast = "bitcast" -- ----------------------------------------------------------------------------- -- * Floating point conversion -- -- | Convert a Haskell Double to an LLVM hex encoded floating point form. In -- Llvm float literals can be printed in a big-endian hexadecimal format, -- regardless of underlying architecture. dToStr :: Double -> String dToStr d = let bs = doubleToBytes d hex d' = case showHex d' "" of [] -> error "dToStr: too few hex digits for float" [x] -> ['0',x] [x,y] -> [x,y] _ -> error "dToStr: too many hex digits for float" str = map toUpper $ concat . fixEndian . (map hex) $ bs in "0x" ++ str -- | Convert a Haskell Float to an LLVM hex encoded floating point form. -- LLVM uses the same encoding for both floats and doubles (16 digit hex -- string) but floats must have the last half all zeroes so it can fit into -- a float size type. {-# NOINLINE fToStr #-} fToStr :: Float -> String fToStr = (dToStr . realToFrac) -- | Reverse or leave byte data alone to fix endianness on this target. fixEndian :: [a] -> [a] #ifdef WORDS_BIGENDIAN fixEndian = id #else fixEndian = reverse #endif
nomeata/ghc
compiler/llvmGen/Llvm/Types.hs
bsd-3-clause
31,173
0
19
7,511
5,017
2,762
2,255
456
4
module Main where import Gli.Cli main :: IO () main = runParser
goromlagche/gli
app/Main.hs
bsd-3-clause
76
0
6
24
24
14
10
4
1
import Control.Applicative import Control.Monad import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C8 import Data.List import Data.Maybe consumable :: [Int] consumable = scanl (+) 1 [6, 10..] mostConsumable :: Int -> (Int, Int) mostConsumable 0 = (0, -1) mostConsumable num = let (l, r) = span (<= num) consumable in (last l, length l - 1) printHourGlass :: Int -> Char -> IO () printHourGlass iterCnt c = do forM_ [iterCnt,iterCnt-1..1] $ \i -> printHGLine i iterCnt c forM_ [0..iterCnt] $ \i -> printHGLine i iterCnt c where printHGLine n maxN c = do putStr $ replicate (maxN-n) ' ' putStrLn $ replicate ((n*2)+1) c main = do numS:cS:_ <- C8.words <$> BS.getLine let num = fst $ fromJust $ C8.readInt numS c = C8.head cS (mc, iterCnt) = mostConsumable num printHourGlass iterCnt c print $ num - mc
y-usuzumi/survive-the-course
www.icourse163.org/ZJU-93001/起步能力自测题/1.hs
bsd-3-clause
928
1
12
238
400
205
195
27
1
module Main where import Lib import HLiquid.Parser import System.Environment import Data.Either main :: IO () main = do files <- getArgs results <- mapM (\file -> parseFile fullFile file) files let success = length (rights results) mapM_ (putStrLn) (lefts results) putStrLn $ "Parsed " ++ (show success) ++ " / " ++ (show $ length results) ++ " successfully."
xldenis/hliquid
app/Main.hs
bsd-3-clause
374
0
12
73
143
72
71
12
1
{-# language TemplateHaskell #-} module Phil.Typecheck.TypeError where import Control.Lens import Data.List import Data.List.NonEmpty (NonEmpty) import Data.Set (Set) import Data.Text (unpack) import Text.PrettyPrint.ANSI.Leijen hiding ((<$>)) import qualified Data.Set as S import Phil.Core.AST.Identifier import Phil.Core.AST.Types import Phil.ErrorMsg import Phil.Typecheck.Unification data TypeError = VarNotInScope Ident | CtorNotInScope Ctor | VarAlreadyDefined Ident | CtorAlreadyDefined Ctor | PatternArgMismatch Ctor Int Int | DuplicateTypeSignatures Ident | CouldNotDeduce [Type] [Type] | NoSuchClass Ctor | NoSuchInstance Ctor (NonEmpty Type) | NonClassFunction Ctor Ident | MissingClassFunctions Ctor (NonEmpty (Ctor, [Ident])) (Set Ident) | MissingSuperclassInst (Ctor, NonEmpty (Ctor, [Ident])) (Ctor, NonEmpty (Ctor, [Ident])) | TypeMismatch TypeScheme TypeScheme | TUnificationError (UnificationError Type) deriving (Eq, Show) makeClassyPrisms ''TypeError -- typeErrorMsg :: AsTypeError e => e -> Maybe Doc -- typeErrorMsg = previews _TypeError toMessage typeErrorMsg = toMessage where toMessage (VarNotInScope var) = errorMsg "Variable not in scope" $ hsep [ text "Variable" , squotes . text . unpack $ getIdent var , text "not in scope" ] toMessage (CtorNotInScope ctor) = errorMsg "Constructor not in scope" $ hsep [ text "Constructor" , squotes . text . unpack $ getCtor ctor , text "not in scope" ] toMessage (PatternArgMismatch constructor actual expected) = errorMsg "Pattern arguments mismatch" $ hsep [ squotes . text . unpack $ getCtor constructor , text "was given" , text $ show actual , text "arguments, but requires" , text $ show expected ] toMessage (VarAlreadyDefined name) = errorMsg "Name already defined" $ hsep [ squotes . text . unpack $ getIdent name , text "is already defined" ] toMessage (CtorAlreadyDefined name) = errorMsg "Constructor already defined" $ hsep [ squotes . text . unpack $ getCtor name , text "is already defined" ] toMessage (DuplicateTypeSignatures function) = errorMsg "Duplicate type signatures" $ hsep [ text "Type signature for" , squotes . text . unpack $ getIdent function , text "is defined multiple times" ] toMessage (CouldNotDeduce targets given) = errorMsg "Constraint error" $ hsep [ text "Could not deduce" , renderConstraints targets , text "from" , renderConstraints given ] toMessage (NoSuchClass className) = errorMsg "Class not found" $ hsep [ text "Class" , squotes . text . unpack $ getCtor className , text "cannot be found" ] toMessage (NoSuchInstance className args) = errorMsg "Instance not found" $ hsep [ text "Could not find instance" , squotes . renderType $ toType (className, args) , text "for class" , squotes . text . unpack $ getCtor className ] toMessage (NonClassFunction className function) = errorMsg "Invalid instance definition" $ hsep [ squotes . text . unpack $ getIdent function , text "is not a member of the" , squotes . text . unpack $ getCtor className , text "class" ] toMessage (MissingClassFunctions className args notImplemented) = errorMsg "Invalid instance definition" $ hsep [ text "Instance" , squotes . renderType $ toType (className, toTypeTyVars <$> args) , text "does not implement required functions:" , hcat . intersperse (comma <> space) . fmap (text . unpack . getIdent) . S.toList $ notImplemented ] toMessage (MissingSuperclassInst target required) = errorMsg "Invalid instance definition" $ hsep [ text "Could not find instance" , squotes (renderType . toType $ over (_2.mapped) toTypeTyVars required) <> text "." , brackets $ hsep [ text "Required by" , squotes . renderType . toType $ over (_2.mapped) toTypeTyVars target ] ] toMessage (TypeMismatch actual expected) = errorMsg "Type mismatch" $ vcat [ hsep [ text "Expected:" , renderTypeScheme expected ] , hsep [ text "Actual:" , renderTypeScheme actual ] ] toMessage (TUnificationError (CannotUnify ty ty')) = errorMsg "Type error" $ vcat [ text "Cannot unify" , text "" , renderType ty , text "with" , hsep [renderType ty'] ] toMessage (TUnificationError (Occurs var ty)) = errorMsg "Type error" $ hsep [ text "Cannot constuct infinite type" , squotes $ hsep [text . unpack $ getIdent var, text "=", renderType ty] ]
LightAndLight/hindley-milner
src/Phil/Typecheck/TypeError.hs
bsd-3-clause
5,350
0
16
1,781
1,306
672
634
137
15
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {- | Module : Language.ObjC.Runtime Description : High-level bindings allowing developers to interface with Objective-C License : BSD3 Maintainer : ian@iankduncan.com Stability : experimental Portability : macOS only Overview The Objective-C runtime is a runtime library that provides support for the dynamic properties of the Objective-C language, and as such is linked to by all Objective-C apps. Objective-C runtime library support functions are implemented in the shared library found at /usr/lib/libobjc.A.dylib. You typically don't need to use the Objective-C runtime library directly when programming in Objective-C. This API is useful primarily for developing bridge layers between Objective-C and other languages, or for low-level debugging. The macOS implementation of the Objective-C runtime library is unique to the Mac. For other platforms, the GNU Compiler Collection provides a different implementation with a similar API. This document covers only the macOS implementation. The low-level Objective-C runtime API is significantly updated in OS X version 10.5. Many functions and all existing data structures are replaced with new functions. The old functions and structures are deprecated in 32-bit and absent in 64-bit mode. The API constrains several values to 32-bit ints even in 64-bit mode—class count, protocol count, methods per class, ivars per class, arguments per method, sizeof(all arguments) per method, and class version number. In addition, the new Objective-C ABI (not described here) further constrains sizeof(anInstance) to 32 bits, and three other values to 24 bits—methods per class, ivars per class, and sizeof(a single ivar). Finally, the obsolete NXHashTable and NXMapTable are limited to 4 billion items. String encoding All char * in the runtime API should be considered to have UTF-8 encoding. -} module Language.ObjC.Runtime ( -- * Constants yes , no , bool , nil , AssociativeObjectBehavior(..) -- * Data types , Class(..) , IVar(..) , Id(..) , ToId(..) , Method(..) , Selector(..) , Property(..) , Protocol(..) , Imp , Attribute(..) , IvarLayout(..) -- * Working with Classes , className , classSuperclass , classIsMetaClass , classInstanceSize , classInstanceVariable , classClassVariable , classAddIvar , classIvarList , classGetIvarLayout , classSetIvarLayout , classGetWeakIvarLayout , classSetWeakIvarLayout , classGetProperty , classPropertyList , classAddMethod , classGetInstanceMethod , classGetClassMethod , classMethodList , classReplaceMethod , classGetMethodImplementation , classGetMethodImplementationStret , respondsToSelector , classAddProtocol , classAddProperty , classReplaceProperty , classConformsToProtocol , classProtocolList , classGetVersion , classSetVersion -- * Adding Classs , allocateClassPair , disposeClassPair , registerClassPair -- * Instantiating Classes , createInstance , constructInstance , destructInstance -- * Working with Instances , copy , dispose , objectSetInstanceVariable , objectGetInstanceVariable , objectGetIndexedIvars , objectGetIVar , objectSetIVar , objectGetClassName , objectGetClass , objectSetClass -- * Obtaining Class Definitions -- , getClassList , classList , lookupClass , getClass , requireClass , getMetaClass -- * Working with Instance Variables , ivarName , ivarTypeEncoding , ivarOffset -- * Associative References , setAssociatedObject , getAssociatedObject , removeAssociatedObjects -- * Sending Messages , msgSend -- * Working with Methods -- methodInvoke -- methodInvokeStret , methodName , methodGetImplementation , methodTypeEncoding , methodReturnType -- , methodGetReturnType , methodNumberOfArguments , methodArgumentType , methodGetDescription , methodSetImplementation , methodExchangeImplementations -- * Working with Libraries , imageNames , classImageName , classNamesForImage -- * Working with Selectors , selectorName , selector -- * Working with Protocols , getProtocol , protocolList , allocateProtocol , registerProtocol , protocolAddMethodDescription , protocolAddProtocol , protocolAddProperty , protocolGetName , protocolMethodDescriptionList -- , protocolGetMethodDescription , protocolPropertyList , protocolProperty , protocolConformsToProtocol -- * Working with Properties , propertyName , propertyAttributes , propertyAttributeValue , propertyAttributeList -- * Using Objective-C Language Features , enumerationMutation , setEnumerationMutationHandler {- -- * Primitive API -- ** Working with Classes , class_getName , class_getSuperclass , class_isMetaClass , class_getInstanceSize , class_getInstanceVariable , class_getClassVariable , class_addIvar , class_copyIvarList , class_getIvarLayout , class_setIvarLayout , class_getWeakIvarLayout , class_setWeakIvarLayout , class_getProperty , class_copyPropertyList , class_addMethod , class_getInstanceMethod , class_getClassMethod , class_copyMethodList , class_replaceMethod , class_getMethodImplementation , class_getMethodImplementation_stret , class_respondsToSelector , class_addProtocol , class_addProperty , class_replaceProperty , class_conformsToProtocol , class_copyProtocolList , class_getVersion , class_setVersion -- ** Adding Classes , objc_allocateClassPair , objc_disposeClassPair , objc_registerClassPair -- ** Instantiating Classes , class_createInstance , objc_constructInstance , objc_destructInstance -- ** Working with Instances , object_copy , object_dispose , object_setInstanceVariable , object_getInstanceVariable , object_getIndexedIvars , object_getIvar , object_setIvar , object_getClassName , object_getClass , object_setClass -- ** Obtaining Class Definitions , objc_getClassList , objc_copyClassList , objc_lookUpClass , objc_getClass , objc_getRequiredClass , objc_getMetaClass -- ** Working with Instance Variables , ivar_getName , ivar_getTypeEncoding , ivar_getOffset -- ** Associative References , objc_setAssociatedObject , objc_getAssociatedObject , objc_removeAssociatedObjects -- ** Sending Messages , p_objc_msgSend , p_objc_msgSend_fpret , p_objc_msgSend_stret , p_objc_msgSendSuper , p_objc_msgSendSuper_stret -- ** Working with Methods , method_invoke , method_invoke_stret , method_getName , method_getImplementation , method_getTypeEncoding , method_copyReturnType , method_getReturnType , method_getNumberOfArguments , method_getArgumentType -- , method_getDescription , method_setImplementation , method_exchangeImplementations -- ** Working with Libraries , objc_copyImageNames , class_getImageName , objc_copyClassNamesForImage -- ** Working with Selectors , sel_getName , sel_registerName , sel_isEqual -- ** Working with Protocols , objc_getProtocol , objc_copyProtocolList , objc_allocateProtocol , objc_registerProtocol , protocol_addMethodDescription , protocol_addProtocol , protocol_addProperty , protocol_getName , protocol_isEqual , protocol_copyMethodDescriptionList , protocol_getMethodDescription , protocol_copyPropertyList , protocol_getProperty , protocol_conformsToProtocol -- ** Working with Properties , property_getName , property_getAttributes , property_copyAttributeValue , property_copyAttributeList -- ** Using Objective-C Language Features , objc_enumerationMutation , objc_setEnumerationMutationHandler , imp_implementationWithBlock , imp_getBlock , imp_removeBlock , objc_loadWeak , objc_storeWeak -- ** Associative References -} ) where import Control.Monad import Control.Monad.Trans import Data.Char import qualified Data.Vector as V import qualified Data.Vector.Algorithms.Intro as VS import qualified Data.Vector.Generic as G import qualified Data.Vector.Storable as VS import Control.Monad.Managed import Data.Coerce import Data.Maybe (fromMaybe) import Data.StateVar import Data.Word import Foreign.C.String import Foreign.C.Types import Foreign.ForeignPtr import Foreign.LibFFI import Foreign.Marshal hiding (with, toBool) import Foreign.Ptr import Foreign.Storable import System.IO.Unsafe -- | Objective-C equivalents to @True@ and @False@ yes, no :: CUInt yes = 1 no = 0 -- | Convert Haskell Boolean values to Objective-C equivalent bool :: Bool -> CUInt bool b = if b then yes else no toBool :: CUInt -> Bool toBool b = b == yes -- | Subsumes Objective-C's @nil@ and @Nil@ constants nil :: (Coercible a Id, ToId a) => a nil = coerce nullPtr nullCheck :: (Coercible a (Ptr b)) => a -> Maybe a nullCheck x = if coerce x == nullPtr then Nothing else Just x listCopier :: Storable a => (Ptr CUInt -> IO (Ptr a)) -> IO (VS.Vector a) listCopier f = alloca $ \len -> do p <- f len fp <- newForeignPtr finalizerFree p l <- peek len return $ VS.unsafeFromForeignPtr0 fp (fromIntegral l) -- | A class describes the behavior and properties common to any particular type of object. For a string object (in Objective-C, this is an instance of the class NSString), the class offers various ways to examine and convert the internal characters that it represents. Similarly, the class used to describe a number object (NSNumber) offers functionality around an internal numeric value, such as converting that value to a different numeric type. -- -- In the same way that multiple buildings constructed from the same blueprint are identical in structure, every instance of a class shares the same properties and behavior as all other instances of that class. Every NSString instance behaves in the same way, regardless of the internal string of characters it holds. -- -- Any particular object is designed to be used in specific ways. You might know that a string object represents some string of characters, but you don’t need to know the exact internal mechanisms used to store those characters. You don’t know anything about the internal behavior used by the object itself to work directly with its characters, but you do need to know how you are expected to interact with the object, perhaps to ask it for specific characters or request a new object in which all the original characters are converted to uppercase. -- -- In Objective-C, the class interface specifies exactly how a given type of object is intended to be used by other objects. In other words, it defines the public interface between instances of the class and the outside world. newtype Class = Class (Ptr CSize) deriving (Eq, Ord, Storable) instance Show Class where show = className newtype IVar = IVar (Ptr IVar) deriving (Show, Eq, Ord, Storable) -- | A pointer to an instance of a class. newtype Id = Id (Ptr Id) deriving (Show, Eq, Ord, Storable) -- | An opaque type that represents a method in a class definition. newtype Method = Method (Ptr Method) deriving (Eq, Ord, Storable) -- | An opaque type that represents a method selector. newtype Selector = Selector (Ptr Selector) deriving (Ord, Storable) -- | An opaque type that represents an Objective-C declared property. newtype Property = Property (Ptr Property) deriving (Storable) newtype Protocol = Protocol (Ptr Protocol) deriving (Ord, Storable) instance ToId Protocol where toId = coerce type Imp p = FunPtr (Id -> Selector -> p) data Attribute = Attribute { attributeName :: String , attributeValue :: String } deriving (Show, Eq) data RawAttribute = RawAttribute { rawAttributeName :: !CString , rawAttributeValue :: !CString } rawAttribute :: Attribute -> Managed RawAttribute rawAttribute (Attribute k v) = RawAttribute <$> managed (withCString k) <*> managed (withCString v) readAttribute :: RawAttribute -> IO Attribute readAttribute (RawAttribute k v) = Attribute <$> peekCString k <*> peekCString v instance Storable RawAttribute where sizeOf _ = 2 * sizeOf nullPtr alignment _ = 2 * alignment nullPtr {- peek p = do n <- peekCString (castPtr p) v <- peekCString $ plusPtr (castPtr p) (sizeOf nullPtr) return $ RawAttribute n v -} peek p = return $ RawAttribute (castPtr p) (plusPtr (castPtr p) (sizeOf nullPtr)) -- Note that allocated strings need to be freed when @Ptr Attribute@ is out of use poke p (RawAttribute pn pv) = do poke (castPtr p) pn poke (plusPtr (castPtr p) (sizeOf nullPtr)) pv data RawMethodDescription = RawMethodDescription { rawMethodDescriptionName :: Selector , rawMethodDescriptionTypes :: CString } deriving (Show, Eq) instance Storable RawMethodDescription where sizeOf _ = 2 * sizeOf nullPtr alignment _ = 2 * alignment nullPtr peek p = do n <- peek (castPtr p) t <- peek (castPtr p `plusPtr` sizeOf (Selector nullPtr)) return $ RawMethodDescription n t poke p (RawMethodDescription n t) = do poke (castPtr p) n poke (castPtr p `plusPtr` sizeOf (Selector nullPtr)) t data MethodDescription = MethodDescription { methodDescriptionName :: Selector , methodDescriptionTypes :: String } deriving (Show, Eq) peekMethodDescription :: RawMethodDescription -> IO MethodDescription peekMethodDescription (RawMethodDescription s ts) = do tstr <- peekCString ts return $ MethodDescription s tstr -- | Type class for representing any value that has an underlying pointer -- that points to an Objective-C class. class ToId a where toId :: a -> Id instance ToId Id where toId = id instance ToId Class where toId (Class c) = Id (castPtr c) -- * Working with classes foreign import ccall "class_getName" class_getName :: Class -> CString -- | Returns the name of a class. className :: Class -> String className = unsafePerformIO . peekCString . class_getName foreign import ccall "class_getSuperclass" class_getSuperclass :: Class -> Class -- | Returns the superclass of a class. classSuperclass :: Class -> Maybe Class classSuperclass c = let s = class_getSuperclass c in if s == nil then Nothing else Just s foreign import ccall "class_isMetaClass" class_isMetaClass :: Class -> CUInt -- | Returns a Boolean value that indicates whether a class object is a metaclass. classIsMetaClass :: Class -> Bool classIsMetaClass = toBool . class_isMetaClass foreign import ccall "class_getInstanceSize" class_getInstanceSize :: Class -> CSize -- | Returns the size of instances of a class. classInstanceSize :: Class -> CSize classInstanceSize = class_getInstanceSize foreign import ccall "class_getInstanceVariable" class_getInstanceVariable :: Class -> CString -> IO IVar -- | Returns the Ivar for a specified instance variable of a given class. classInstanceVariable :: MonadIO m => Class -- ^ The class whose instance variable you wish to obtain. -> String -- ^ The name of the instance variable definition to obtain. -> m IVar classInstanceVariable c str = liftIO $ withCString str (class_getInstanceVariable c) foreign import ccall "class_getClassVariable" class_getClassVariable :: Class -> CString -> IO IVar -- | Returns the Ivar for a specified class variable of a given class. classClassVariable :: MonadIO m => Class -- ^ The class definition whose class variable you wish to obtain. -> String -- ^ The name of the class variable definition to obtain. -> m IVar -- ^ A pointer to an Ivar data structure containing information about the class variable specified by nam. classClassVariable c str = liftIO $ withCString str (class_getClassVariable c) foreign import ccall "class_addIvar" class_addIvar :: Class -> CString -> CSize -> Word8 -> CString -> IO CUInt -- | Adds a new instance variable to a class. -- -- This function may only be called after objc_allocateClassPair and before objc_registerClassPair. Adding an instance variable to an existing class is not supported. -- -- The class must not be a metaclass. Adding an instance variable to a metaclass is not supported. -- -- The instance variable's minimum alignment in bytes is 1<<align. The minimum alignment of an instance variable depends on the ivar's type and the machine architecture. For variables of any pointer type, pass log2(sizeof(pointer_type)). classAddIvar :: MonadIO m => Class -> String -- ^ Instance variable name -> Int -- ^ Value size -> Word8 -- ^ Alignment -> String -- ^ Types -> m Bool -- ^ @True@ if the instance variable was added successfully, otherwise @False@ (for example, the class already contains an instance variable with that name). classAddIvar c str size align enc = liftIO $ withCString str $ \strp -> withCString enc $ \encp -> fmap (== 1) $ class_addIvar c strp (fromIntegral size) align encp foreign import ccall "class_copyIvarList" class_copyIvarList :: Class -> Ptr CUInt -> IO (Ptr IVar) -- | Describes the instance variables declared by a class. -- -- Any instance variables declared by superclasses are not included. classIvarList :: MonadIO m => Class -> m (VS.Vector IVar) classIvarList = liftIO . listCopier . class_copyIvarList newtype IvarLayout = IvarLayout (Ptr Word8) deriving (Show, Eq) foreign import ccall "class_getIvarLayout" class_getIvarLayout :: Class -> IO IvarLayout -- | Returns a description of the Ivar layout for a given class. classGetIvarLayout :: MonadIO m => Class -> m IvarLayout classGetIvarLayout = liftIO . class_getIvarLayout foreign import ccall "class_setIvarLayout" class_setIvarLayout :: Class -> IvarLayout -> IO () -- | Sets the Ivar layout for a given class. classSetIvarLayout :: MonadIO m => Class -> IvarLayout -> m () classSetIvarLayout c = liftIO . class_setIvarLayout c foreign import ccall "class_getWeakIvarLayout" class_getWeakIvarLayout :: Class -> IO IvarLayout -- | Returns a description of the layout of weak Ivars for a given class. classGetWeakIvarLayout :: MonadIO m => Class -> m IvarLayout classGetWeakIvarLayout = liftIO . class_getWeakIvarLayout foreign import ccall "class_setWeakIvarLayout" class_setWeakIvarLayout :: Class -> IvarLayout -> IO () -- | Sets the layout for weak Ivars for a given class. classSetWeakIvarLayout :: MonadIO m => Class -> IvarLayout -> m () classSetWeakIvarLayout c = liftIO . class_setWeakIvarLayout c foreign import ccall "class_getProperty" class_getProperty :: Class -> CString -> IO Property -- | Returns a property with a given name of a given class. classGetProperty :: MonadIO m => Class -> String -> m (Maybe Property) classGetProperty c s = liftIO (nullCheck <$> (withCString s $ class_getProperty c)) foreign import ccall "class_copyPropertyList" class_copyPropertyList :: Class -> Ptr CUInt -> IO (Ptr Property) -- | Describes the properties declared by a class. -- -- Any properties declared by superclasses are not included. classPropertyList :: MonadIO m => Class -> m (VS.Vector Property) classPropertyList = liftIO . listCopier . class_copyPropertyList foreign import ccall "class_addMethod" class_addMethod :: Class -> Selector -> Imp p -> CString -> IO CUInt -- | Adds a new method to a class with a given name and implementation. -- -- @classAddMethod@ will add an override of a superclass's implementation, but will not replace an existing implementation in this class. To change an existing implementation, use @methodSetImplementation@. classAddMethod :: MonadIO m => Class -- ^ The class to which to add a method. -> Selector -- ^ A selector that specifies the name of the method being added. -> Imp p -- ^ A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd. -> String -- ^ An array of characters that describe the types of the arguments to the method. For possible values, see Objective-C Runtime Programming Guide > Type Encodings. Since the function must take at least two arguments—self and _cmd, the second and third characters must be “@:” (the first character is the return type). -> m Bool -- ^ @True@ if the method was added successfully, otherwise @False@ (for example, the class already contains a method implementation with that name). classAddMethod c s i n = liftIO (toBool <$> withCString n (class_addMethod c s i)) foreign import ccall "class_getInstanceMethod" class_getInstanceMethod :: Class -> Selector -> IO Method -- | Returns a specified instance method for a given class. -- -- The method that corresponds to the implementation of the selector specified for the given class, or @Nothing@ if the specified class or its superclasses do not contain an instance method with the specified selector. -- -- Note that this function searches superclasses for implementations, whereas classMethodList does not. classGetInstanceMethod :: MonadIO m => Class -> Selector -> m (Maybe Method) classGetInstanceMethod c s = liftIO (nullCheck <$> class_getInstanceMethod c s) foreign import ccall "class_getClassMethod" class_getClassMethod :: Class -> Selector -> IO Method -- | Returns a pointer to the data structure describing a given class method for a given class. -- -- Note that this function searches superclasses for implementations, whereas classMethodList does not. classGetClassMethod :: MonadIO m => Class -> Selector -> m (Maybe Method) classGetClassMethod c s = liftIO (nullCheck <$> class_getClassMethod c s) foreign import ccall "class_copyMethodList" class_copyMethodList :: Class -> Ptr CUInt -> IO (Ptr Method) -- | Describes the instance methods implemented by a class. -- -- To get the class methods of a class, use @(objectGetClass classVal >>= classMethodList)@ classMethodList :: MonadIO m => Class -> m (VS.Vector Method) classMethodList = liftIO . listCopier . class_copyMethodList foreign import ccall "class_replaceMethod" class_replaceMethod :: Class -> Selector -> Imp a -> CString -> IO (Imp b) -- | Replaces the implementation of a method for a given class. classReplaceMethod :: MonadIO m => Class -- ^ The class you want to modify. -> Selector -- ^ A selector that identifies the method whose implementation you want to replace. -> Imp a -- ^ The new implementation for the method identified by name for the class identified by cls. -> String -- ^ An array of characters that describe the types of the arguments to the method. For possible values, see Objective-C Runtime Programming Guide > Type Encodings. Since the function must take at least two arguments—self and _cmd, the second and third characters must be “@:” (the first character is the return type). -> m (Imp b) -- ^ The previous implementation of the method identified by name for the class identified by cls. classReplaceMethod c s imp str = liftIO $ withCString str $ \strp -> class_replaceMethod c s imp strp foreign import ccall "class_getMethodImplementation" class_getMethodImplementation :: Class -> Selector -> IO (Imp a) -- | Returns the function pointer that would be called if a particular message were sent to an instance of a class. -- -- class_getMethodImplementation may be faster than method_getImplementation(class_getInstanceMethod(cls, name)). -- -- The function pointer returned may be a function internal to the runtime instead of an actual method implementation. For example, if instances of the class do not respond to the selector, the function pointer returned will be part of the runtime's message forwarding machinery. classGetMethodImplementation :: MonadIO m => Class -> Selector -> m (Imp a) classGetMethodImplementation c = liftIO . class_getMethodImplementation c foreign import ccall "class_getMethodImplementation_stret" class_getMethodImplementation_stret :: Class -> Selector -> IO (Imp a) -- | Returns the function pointer that would be called if a particular message were sent to an instance of a class. Similar to @classGetMethodImplementation@, but intended for functions which return a C struct. This means that the FunPtr returned to Haskell is probably of questionable utility since there's no way for the Haskell FFI to handle returned structs. However, this may still have its uses in the event that a package like @inline-c@ is used in conjunction with this package classGetMethodImplementationStret :: MonadIO m => Class -> Selector -> m (Imp a) classGetMethodImplementationStret c = liftIO . class_getMethodImplementation_stret c foreign import ccall "class_respondsToSelector" class_respondsToSelector :: Class -> Selector -> IO CUInt -- | Returns a Boolean value that indicates whether instances of a class respond to a particular selector. respondsToSelector :: MonadIO m => Class -> Selector -> m Bool respondsToSelector c = liftIO . fmap toBool . class_respondsToSelector c foreign import ccall "class_addProtocol" class_addProtocol :: Class -> Protocol -> IO CUInt -- | Adds a protocol to a class. classAddProtocol :: MonadIO m => Class -> Protocol -> m Bool -- ^ @True@ if the protocol was added successfully, otherwise @False@ (for example, the class already conforms to that protocol). classAddProtocol c = liftIO . fmap toBool . class_addProtocol c foreign import ccall "class_addProperty" class_addProperty :: Class -> CString -> Ptr RawAttribute -> CUInt -> IO CUInt -- | Adds a property to a class. classAddProperty :: MonadIO m => Class -- ^ The class to modify. -> String -- ^ The name of the property. -> [Attribute] -- ^ An array of property attributes. -> m Bool -- ^ @True@ if the property was added successfully; otherwise @False@ (for example, this function returns @False@ if the class already has that property). classAddProperty c s as = liftIO $ fmap toBool $ with (mapM rawAttribute as) $ \ras -> withArrayLen ras $ \l rasp -> withCString s $ \sp -> class_addProperty c sp rasp (fromIntegral l) foreign import ccall "class_replaceProperty" class_replaceProperty :: Class -> CString -> Ptr RawAttribute -> CUInt -> IO () -- | Replace a property of a class. classReplaceProperty :: MonadIO m => Class -- ^ The class to modify. -> String -- ^ The name of the property. -> [Attribute] -- ^ An array of property attributes. -> m () classReplaceProperty c s as = liftIO $ with (mapM rawAttribute as) $ \ras -> withArrayLen ras $ \l rasp -> withCString s $ \sp -> class_replaceProperty c sp rasp (fromIntegral l) foreign import ccall "class_conformsToProtocol" class_conformsToProtocol :: Class -> Protocol -> IO CUInt -- | Returns a Boolean value that indicates whether a class conforms to a given protocol. classConformsToProtocol :: MonadIO m => Class -> Protocol -> m Bool classConformsToProtocol c p = liftIO (toBool <$> class_conformsToProtocol c p) foreign import ccall "class_copyProtocolList" class_copyProtocolList :: Class -> Ptr CUInt -> IO (Ptr Protocol) -- | Describes the protocols adopted by a class. -- -- Any protocols adopted by superclasses or other protocols are not included. classProtocolList :: MonadIO m => Class -> m (VS.Vector Protocol) classProtocolList = liftIO . listCopier . class_copyProtocolList foreign import ccall "class_getVersion" class_getVersion :: Class -> IO CInt -- | Returns the version number of a class definition. -- -- You can use the version number of the class definition to provide versioning of the interface that your class represents to other classes. This is especially useful for object serialization (that is, archiving of the object in a flattened form), where it is important to recognize changes to the layout of the instance variables in different class-definition versions. -- -- Classes derived from the Foundation framework NSObject class can obtain the class-definition version number using the getVersion class method, which is implemented using the class_getVersion function. classGetVersion :: MonadIO m => Class -- ^ A pointer to an Class data structure. Pass the class definition for which you wish to obtain the version. -> m Int -- ^ An integer indicating the version number of the class definition. classGetVersion = liftIO . fmap fromIntegral . class_getVersion foreign import ccall "class_setVersion" class_setVersion :: Class -> CInt -> IO () -- | Sets the version number of a class definition. -- -- You can use the version number of the class definition to provide versioning of the interface that your class represents to other classes. This is especially useful for object serialization (that is, archiving of the object in a flattened form), where it is important to recognize changes to the layout of the instance variables in different class-definition versions. -- -- Classes derived from the Foundation framework NSObject class can set the class-definition version number using the setVersion: class method, which is implemented using the class_setVersion function. classSetVersion :: MonadIO m => Class -> Int -> m () classSetVersion c = liftIO . class_setVersion c . fromIntegral -- classInstanceVariable :: Class -> CString -> IVar -- classInstanceVariable = class_getInstanceVariable -- * Adding classes foreign import ccall "objc_allocateClassPair" objc_allocateClassPair :: Class -> CString -> CSize -> IO Class -- | Creates a new class and metaclass. allocateClassPair :: MonadIO m => Maybe Class -- ^ The class to use as the new class's superclass, or Nothing to create a new root class. -> String -- ^ The string to use as the new class's name. -> Int -- ^ The number of bytes to allocate for indexed ivars at the end of the class and metaclass objects. This should usually be 0. -> m (Maybe Class) -- ^ The new class, or Nothing if the class could not be created (for example, the desired name is already in use). allocateClassPair c str extraBytes = liftIO $ fmap nullCheck $ withCString str $ \cstr -> objc_allocateClassPair (fromMaybe nil c) cstr (fromIntegral extraBytes) foreign import ccall "objc_disposeClassPair" objc_disposeClassPair :: Class -> IO () -- | Destroys a class and its associated metaclass. -- -- Do not call this function if instances of the class or any subclass exist. disposeClassPair :: MonadIO m => Class -> m () disposeClassPair = liftIO . objc_disposeClassPair foreign import ccall "objc_registerClassPair" objc_registerClassPair :: Class -> IO () -- | Registers a class that was allocated using allocateClassPair. registerClassPair :: MonadIO m => Class -> m () registerClassPair = liftIO . objc_registerClassPair -- * Instantiating classes foreign import ccall "class_createInstance" class_createInstance :: Class -> CSize -> IO Id -- | Creates an instance of a class, allocating memory for the class in the default malloc memory zone. createInstance :: MonadIO m => Class -- ^ The class that you want to allocate an instance of. -> Int -- ^ An integer indicating the number of extra bytes to allocate. The additional bytes can be used to store additional instance variables beyond those defined in the class definition. -> m Id -- ^ An instance of the class cls. createInstance c s = liftIO $ class_createInstance c (fromIntegral s) foreign import ccall "objc_constructInstance" objc_constructInstance :: Class -> Ptr a -- ^ The location at which to allocate an instance of the cls class. bytes must point to at least class_getInstanceSize(cls) bytes of well-aligned, zero-filled memory. -> IO Id -- | Creates an instance of a class at the specified location. constructInstance :: MonadIO m => Class -- ^ The class that you want to allocate an instance of. -> Ptr a -- ^ The location at which to allocate an instance of the cls class. bytes myst point to at least class_getInstanceSize(cls) bytes of well-aligned, zero-filled memory. -> m (Maybe Id) -- ^ An instance of the class cls at bytes, if successful; otherwise @Nothing@ (for example, if the class or bytes are themselves null). constructInstance c = liftIO . fmap nullCheck . objc_constructInstance c foreign import ccall "objc_destructInstance" objc_destructInstance :: Id -> IO (Ptr a) -- | Destroys an instance of a class without freeing memory and removes any of its associated references. -- -- This method does nothing if obj is nil. -- -- Important -- -- The Objective-C garbage collector does not call this function. As a result, if you edit this function, you should also edit finalize. That said, Core Foundation and other clients do call this function under garbage collection. destructInstance :: (MonadIO m, ToId id) => id -> m (Ptr a) destructInstance = liftIO . objc_destructInstance . toId -- * Working with instances foreign import ccall "object_copy" object_copy :: Id -> CSize -> IO Id -- | Returns a copy of a given object. copy :: (MonadIO m, Coercible id Id, ToId id) => id -- ^ An Objective-C object. -> Int -- ^ The size of the object -> m id -- ^ A copy of the supplied object. copy i s = liftIO $ coerce $ object_copy (toId i) (fromIntegral s) foreign import ccall "object_dispose" object_dispose :: Id -> IO Id -- | Frees the memory occupied by a given object. dispose :: (MonadIO m, ToId id) => id -- ^ An Objective-C object. -> m () dispose = liftIO . Control.Monad.void . object_dispose . toId foreign import ccall "object_setInstanceVariable" object_setInstanceVariable :: Id -> CString -> Ptr a -> IO IVar -- | Changes the value of an instance variable of a class instance. objectSetInstanceVariable :: (MonadIO m, ToId id) => id -- ^ A pointer to an instance of a class. Pass the object containing the instance variable whose value you wish to modify. -> String -- ^ Pass the name of the instance variable whose value you wish to modify. -> Ptr a -- ^ The new value for the instance variable. -> m IVar -- ^ A pointer to the Ivar data structure that defines the type and name of the instance variable specified by the name string. objectSetInstanceVariable i str p = liftIO $ withCString str $ \cstr -> object_setInstanceVariable (toId i) cstr p foreign import ccall "object_getInstanceVariable" object_getInstanceVariable :: Id -> CString -> Ptr (Ptr a) -> IO IVar -- | Obtains the value of an instance variable of a class instance. objectGetInstanceVariable :: (MonadIO m, ToId id) => id -- ^ A pointer to an instance of a class. Pass the object containing the instance variable whose value you wish to obtain. -> String -- ^ A C string. Pass the name of the instance variable whose value you wish to obtain. -> m (Ptr a, IVar) -- ^ Pointer to the value of the instance variable, and a pointer to the Ivar data structure that defines the type and name of the instance variable specified by name. objectGetInstanceVariable i str = liftIO $ withCString str $ \cstr -> alloca $ \pp -> do i <- object_getInstanceVariable (toId i) cstr pp p <- peek pp return (p, i) -- instanceVariable :: ToId id => id -> String -> StateVar () foreign import ccall "object_getIndexedIvars" object_getIndexedIvars :: Id -> IO (Ptr a) -- | Returns a pointer to any extra bytes allocated with a instance given object. objectGetIndexedIvars :: (MonadIO m, ToId id) => id -- ^ An Objective-C object. -> m (Ptr a) -- ^ A pointer to any extra bytes allocated for the given object. If the object was not allocated with any extra bytes, then dereferencing the returned pointer is undefined. objectGetIndexedIvars = liftIO . object_getIndexedIvars . toId foreign import ccall "object_getIvar" object_getIvar :: Id -> IVar -> IO Id -- | Reads the value of an instance variable in an object. objectGetIVar :: (MonadIO m, ToId id) => id -> IVar -> m (Maybe Id) objectGetIVar i v = liftIO $ do r <- object_getIvar (toId i) v return $! if r == nil then Nothing else Just r foreign import ccall "object_setIvar" object_setIvar :: Id -> IVar -> Id -> IO () -- | Sets the value of an instance variable in an object. objectSetIVar :: (MonadIO m, ToId id, ToId a) => id -> IVar -> a -> m () objectSetIVar o iv x = liftIO $ object_setIvar (toId o) iv (toId x) -- ivar :: (ToId id, ToId a) => id -> IVar -> StateVar a -- ivar o v = makeStateVar (objectGetIVar o v) (objectSetIVar o v) foreign import ccall "object_getClassName" object_getClassName :: Id -> IO CString -- | Returns the class name of a given object. objectGetClassName :: (MonadIO m, ToId id) => id -> m String objectGetClassName i = liftIO (object_getClassName (toId i) >>= peekCString) foreign import ccall "object_getClass" object_getClass :: Id -> IO Class -- | Returns the class of an object. -- -- The class object of which object is an instance, or @Nothing@ if object is nil. objectGetClass :: (MonadIO m, ToId id) => id -> m (Maybe Class) objectGetClass = liftIO . fmap nullCheck . object_getClass . toId foreign import ccall "object_setClass" object_setClass :: Id -> Class -> IO Class -- | Sets the class of an object. objectSetClass :: (MonadIO m, ToId id) => id -> Class -> m (Maybe Class) -- ^ The previous value of object‘s class, or @Nothing@ if object is nil. objectSetClass o = liftIO . fmap nullCheck . object_setClass (toId o) -- * Obtaining class definitions foreign import ccall "objc_getClassList" objc_getClassList :: Ptr Class -> Int -> IO Int foreign import ccall "objc_copyClassList" objc_copyClassList :: Ptr CUInt -> IO (Ptr Class) -- | Obtains the list of registered class definitions. classList :: MonadIO m => m (VS.Vector Class) classList = liftIO $ listCopier objc_copyClassList foreign import ccall "objc_lookUpClass" objc_lookUpClass :: CString -> IO Class -- | Returns the class definition of a specified class. lookupClass :: MonadIO m => String -- ^ The name of the class to look up. -> m (Maybe Class) -- ^ The Class object for the named class, or @Nothing@ if the class is not registered with the Objective-C runtime. lookupClass str = liftIO $ withCString str $ \cstr -> do c <- objc_lookUpClass cstr return $! if c == nil then Nothing else Just c foreign import ccall "objc_getClass" objc_getClass :: CString -> IO Class -- | Returns the class definition of a specified class. -- -- getClass is different from lookupClass in that if the class is not registered, getClass calls the class handler callback and then checks a second time to see whether the class is registered. lookupClass does not call the class handler callback. getClass :: MonadIO m => String -- ^ The name of the class to look up. -> m (Maybe Class) -- ^ The Class object for the named class, or @Nothing@ if the class is not registered with the Objective-C runtime. getClass str = liftIO $ withCString str $ \cstr -> do c <- objc_getClass cstr return $! if c == nil then Nothing else Just c foreign import ccall "objc_getRequiredClass" objc_getRequiredClass :: CString -> IO Class -- | This function is the same as @getClass@, but kills the process if the class is not found. requireClass :: MonadIO m => String -> m Class requireClass str = liftIO $ withCString str objc_getRequiredClass foreign import ccall "objc_getMetaClass" objc_getMetaClass :: CString -> IO Class -- | Returns the metaclass definition of a specified class. getMetaClass :: MonadIO m => String -- ^ The name of the class to look up. -> m (Maybe Class) -- ^ The Class object for the metaclass of the named class, or nil if the class is not registered with the Objective-C runtime. getMetaClass str = liftIO $ withCString str $ \cstr -> do c <- objc_getMetaClass cstr return $! if c == nil then Nothing else Just c -- * Working with instance variables foreign import ccall "ivar_getName" ivar_getName :: IVar -> CString -- | Returns the name of an instance variable. ivarName :: IVar -> String ivarName = unsafePerformIO . peekCString . ivar_getName foreign import ccall "ivar_getTypeEncoding" ivar_getTypeEncoding :: IVar -> IO CString -- | Returns the type string of an instance variable. -- -- For possible values, see Objective-C Runtime Programming Guide > Type Encodings. ivarTypeEncoding :: IVar -> String ivarTypeEncoding i = unsafePerformIO $ do cstr <- ivar_getTypeEncoding i peekCString cstr foreign import ccall "ivar_getOffset" ivar_getOffset :: IVar -> CPtrdiff -- | Returns the offset of an instance variable. -- -- For instance variables of type id or other object types, call object_getIvar and object_setIvar instead of using this offset to access the instance variable data directly. ivarOffset :: IVar -> Int ivarOffset = fromIntegral . ivar_getOffset -- * Associative references foreign import ccall "objc_setAssociatedObject" objc_setAssociatedObject :: Id -> Ptr a -> Id -> CInt -> IO () -- | Sets an associated value for a given object using a given key and association policy. setAssociatedObject :: (MonadIO m, ToId id) => id -- ^ The source object for the association. -> Ptr a -- ^ The key for the association. -> Id -- ^ The value to associate with the key key for object. Pass nil to clear an existing association. -> AssociativeObjectBehavior -- ^ The policy for the association. For possible values, see Associative Object Behaviors. -> m () setAssociatedObject o k v pol = liftIO $ objc_setAssociatedObject (toId o) k v (fromIntegral $ fromEnum pol) foreign import ccall "objc_getAssociatedObject" objc_getAssociatedObject :: Id -> Ptr a -> IO Id -- | Returns the value associated with a given object for a given key. getAssociatedObject :: (MonadIO m, ToId id) => id -- ^ The source object for the association. -> Ptr a -- ^ The key for the association. -> m Id -- ^ The value associated with the key key for object. getAssociatedObject i = liftIO . objc_getAssociatedObject (toId i) foreign import ccall "objc_removeAssociatedObjects" objc_removeAssociatedObjects :: Id -> IO () -- | Removes all associations for a given object. -- -- The main purpose of this function is to make it easy to return an object to a "pristine state”. You should not use this function for general removal of associations from objects, since it also removes associations that other clients may have added to the object. Typically you should use objc_setAssociatedObject with a nil value to clear an association. removeAssociatedObjects :: (MonadIO m, ToId id) => id -- ^ An object that maintains associated objects. -> m () removeAssociatedObjects = liftIO . objc_removeAssociatedObjects . toId -- * Sending messages -- TODO quasiquoter -- send :: QuasiQuoter -- send = undefined foreign import ccall "&objc_msgSend" p_objc_msgSend :: FunPtr (Id -> Selector -> IO Id) -- | Sends a message with a simple return value to an instance of a class. msgSend :: (MonadIO m, ToId a) => a -> Selector -> [Arg] -> m Id msgSend x (Selector s) as = liftIO ((Id . castPtr) <$> callFFI p_objc_msgSend (retPtr retVoid) (argPtr i : argPtr s : as)) where (Id i) = toId x foreign import ccall "&objc_msgSend_stret" p_objc_msgSend_stret :: FunPtr (Id -> Selector -> IO (Ptr ())) foreign import ccall "&objc_msgSendSuper" p_objc_msgSendSuper :: FunPtr (Id -> Selector -> IO Id) foreign import ccall "&objc_msgSendSuper_stret" p_objc_msgSendSuper_stret :: FunPtr (Id -> Selector -> IO (Ptr ())) foreign import ccall "&method_invoke" method_invoke :: FunPtr (Id -> Method -> IO Id) foreign import ccall "&method_invoke_stret" method_invoke_stret :: FunPtr (Id -> Method -> IO (Ptr ())) foreign import ccall "method_getName" method_getName :: Method -> Selector -- | Returns the name of a method. -- -- To get the method name as a string, call selectorName(methodName(method)). methodName :: Method -> Selector methodName = method_getName foreign import ccall "method_getImplementation" method_getImplementation :: Method -> IO (Imp a) -- | Returns the implementation of a method. methodGetImplementation :: MonadIO m => Method -> m (Imp a) methodGetImplementation = liftIO . method_getImplementation foreign import ccall "method_getTypeEncoding" method_getTypeEncoding :: Method -> IO CString -- | Returns a string describing a method's parameter and return types. methodTypeEncoding :: MonadIO m => Method -> m (Maybe String) methodTypeEncoding m = liftIO $ do e <- method_getTypeEncoding m if e /= nullPtr then Just <$> peekCString e else pure Nothing foreign import ccall "method_copyReturnType" method_copyReturnType :: Method -> IO CString -- | Returns a string describing a method's return type. methodReturnType :: MonadIO m => Method -> m String methodReturnType m = liftIO $ do t <- method_copyReturnType m s <- peekCString t free t return s foreign import ccall "method_copyArgumentType" method_copyArgumentType :: Method -> CUInt -> IO CString -- | Returns a string describing a single parameter type of a method, -- or @Nothing@ if method has no parameter at the given index. methodArgumentType :: MonadIO m => Method -> Int -- ^ The index of the parameter to inspect. -> m (Maybe String) methodArgumentType m i = liftIO $ do t <- method_copyArgumentType m (fromIntegral i) if t /= nullPtr then do s <- peekCString t free t return $ Just s else return Nothing foreign import ccall "method_getReturnType" method_getReturnType :: Method -> CString -> CSize -> IO () foreign import ccall "method_getNumberOfArguments" method_getNumberOfArguments :: Method -> IO CUInt -- | Returns the number of arguments accepted by a method. methodNumberOfArguments :: Method -> Int methodNumberOfArguments = fromIntegral . unsafePerformIO . method_getNumberOfArguments foreign import ccall "method_getArgumentType" method_getArgumentType :: Method -> CUInt -> CString -> CSize -> IO () foreign import ccall "method_getDescription" method_getDescription :: Method -> IO (Ptr RawMethodDescription) -- | Returns a method description structure for a specified method. methodGetDescription :: MonadIO m => Method -> m MethodDescription methodGetDescription m = liftIO $ do p <- method_getDescription m raw <- peek p str <- peekCString $ rawMethodDescriptionTypes raw return $ MethodDescription (rawMethodDescriptionName raw) str foreign import ccall "method_setImplementation" method_setImplementation :: Method -> Imp a -> IO (Imp b) -- | Sets the implementation of a method. methodSetImplementation :: MonadIO m => Method -> Imp a -> m (Imp b) -- ^ The previous implementation of the method. methodSetImplementation m = liftIO . method_setImplementation m foreign import ccall "method_exchangeImplementations" method_exchangeImplementations :: Method -> Method -> IO () -- | Exchanges the implementations of two methods. -- -- This is an atomic version of the following: -- -- > IMP imp1 = method_getImplementation(m1); -- > IMP imp2 = method_getImplementation(m2); -- > method_setImplementation(m1, imp2); -- > method_setImplementation(m2, imp1); methodExchangeImplementations :: MonadIO m => Method -> Method -> m () methodExchangeImplementations m = liftIO . method_exchangeImplementations m foreign import ccall "objc_copyImageNames" objc_copyImageNames :: Ptr CUInt -> IO (Ptr CString) -- | Returns the names of all the loaded Objective-C frameworks and dynamic libraries. imageNames :: MonadIO m => m [String] -- ^ An array of C strings representing the names of all the loaded Objective-C frameworks and dynamic libraries. imageNames = liftIO $ alloca $ \len -> do strs <- objc_copyImageNames len l <- peek len arr <- peekArray (fromIntegral l) strs mapM peekCString arr foreign import ccall "class_getImageName" class_getImageName :: Class -> IO CString -- | Returns the name of the dynamic library a class originated from. classImageName :: MonadIO m => Class -- ^ The class you are inquiring about. -> m (Maybe String) -- ^ A C string representing the name of the library containing the provided class. classImageName c = liftIO $ do n <- class_getImageName c if n == nullPtr then pure Nothing else Just <$> peekCString n foreign import ccall "objc_copyClassNamesForImage" objc_copyClassNamesForImage :: CString -> Ptr CUInt -> IO (Ptr CString) -- | Returns the names of all the classes within a specified library or framework. classNamesForImage :: MonadIO m => String -- ^ The library or framework you are inquiring about. -> m [String] -- ^ An array of C strings representing all of the class names within the specified library or framework. classNamesForImage i = liftIO $ alloca $ \len -> withCString i $ \ip -> do nsp <- objc_copyClassNamesForImage ip len l <- peek len arr <- peekArray (fromIntegral l) nsp mapM peekCString arr foreign import ccall "sel_getName" sel_getName :: Selector -> CString -- | Returns the name of the method specified by a given selector. selectorName :: Selector -> String selectorName = unsafePerformIO . peekCString . sel_getName foreign import ccall "sel_registerName" sel_registerName :: CString -> IO Selector -- | Registers a method with the Objective-C runtime system, maps the method name to a selector, and returns the selector value. selector :: String -> Selector selector str = unsafeDupablePerformIO $ withCString str sel_registerName foreign import ccall "sel_isEqual" sel_isEqual :: Selector -> Selector -> CUInt instance Eq Selector where (==) s1 s2 = toBool (sel_isEqual s1 s2) instance Show Selector where show = selectorName foreign import ccall "objc_getProtocol" objc_getProtocol :: CString -> IO Protocol -- | Returns a specified protocol. -- -- This function acquires the Objective-C runtime lock. getProtocol :: MonadIO m => String -- ^ The name of a protocol. -> m (Maybe Protocol) -- ^ The protocol named name, or @Nothing@ if no protocol named name could be found. getProtocol str = liftIO $ withCString str $ \cstr -> do p <- objc_getProtocol cstr return $ if p == Protocol nullPtr then Nothing else Just p foreign import ccall "objc_copyProtocolList" objc_copyProtocolList :: Ptr CUInt -> IO (Ptr Protocol) -- | Returns an array of all the protocols known to the runtime. protocolList :: MonadIO m => m (VS.Vector Protocol) protocolList = liftIO $ listCopier objc_copyProtocolList foreign import ccall "objc_allocateProtocol" objc_allocateProtocol :: CString -> IO Protocol -- | Creates a new protocol instance. -- -- You must register the returned protocol instance with the registerProtocol function before you can use it. -- -- There is no dispose method associated with this function. allocateProtocol :: MonadIO m => String -- ^ The name of the protocol you want to create. -> m (Maybe Protocol) -- ^ A new protocol instance or @Nothing@ if a protocol with the same name as name already exists. allocateProtocol str = liftIO $ do r <- withCString str objc_allocateProtocol return $! if r == nil then Nothing else Just r foreign import ccall "objc_registerProtocol" objc_registerProtocol :: Protocol -> IO () -- | Registers a newly created protocol with the Objective-C runtime. -- -- When you create a new protocol using allocateProtocol, you then register it with the Objective-C runtime by calling this function. After a protocol is successfully registered, it is immutable and ready to use. registerProtocol :: MonadIO m => Protocol -- ^ The protocol you want to register with the Objective-C runtime. -> m () registerProtocol = liftIO . objc_registerProtocol foreign import ccall "protocol_addMethodDescription" protocol_addMethodDescription :: Protocol -> Selector -> CString -> CUInt -> CUInt -> IO () -- | Adds a method to a protocol. -- -- To add a method to a protocol using this function, the protocol must be under construction. That is, you must add any methods to proto before you register it with the Objective-C runtime (via the objc_registerProtocol function). protocolAddMethodDescription :: MonadIO m => Protocol -- ^ The protocol you want to add a method to. -> Selector -- ^ The name of the method you want to add. -> String -- ^ A string representing the signature of the method you want to add. -> Bool -- ^ A Boolean indicating whether the method is a required method of throto protocol. If @True@, the method is a required method; if @False@, the method is an optional method. -> Bool -- ^ A Boolean indicating whether the method is an instance method. If @True@, the method is an instance method; if @False@, the method is a class method. -> m () protocolAddMethodDescription p s str req inst = liftIO $ withCString str $ \cstr -> protocol_addMethodDescription p s cstr (if req then yes else no) (if inst then yes else no) foreign import ccall "protocol_addProtocol" protocol_addProtocol :: Protocol -> Protocol -> IO () -- | Adds a registered protocol to another protocol that is under construction. -- -- The protocol you want to add to must be under construction— allocated but not yet registered with the Objective-C runtime. The protocol you want to add must be registered already. protocolAddProtocol :: MonadIO m => Protocol -- ^ The protocol you want to add the registered protocol to. -> Protocol -- ^ The registered protocol you want to add -> m () protocolAddProtocol p = liftIO . protocol_addProtocol p foreign import ccall "protocol_addProperty" protocol_addProperty :: Protocol -> CString -> Ptr RawAttribute -> CUInt -> CUInt -> CUInt -> IO () -- | Adds a property to a protocol that is under construction. protocolAddProperty :: MonadIO m => Protocol -> String -- ^ The name of the property you want to add. -> [Attribute] -- ^ An array of property attributes. -> Bool -- ^ A Boolean indicating whether the property’s accessor methods are required methods of the protocol. If @True@, the property’s accessor methods are required methods; if @False@, the property’s accessor methods are optional methods. -> m () protocolAddProperty p n as req = liftIO $ withCString n $ \np -> with (mapM rawAttribute as) $ \ras -> withArrayLen ras $ \asl asp -> protocol_addProperty p np asp (fromIntegral asl) (if req then yes else no) yes foreign import ccall "protocol_getName" protocol_getName :: Protocol -> IO CString -- | Returns a the name of a protocol. protocolGetName :: Protocol -> String protocolGetName p = unsafePerformIO $ do s <- protocol_getName p peekCString s instance Show Protocol where show = protocolGetName foreign import ccall "protocol_isEqual" protocol_isEqual :: Protocol -> Protocol -> CUInt instance Eq Protocol where (==) a b = toBool $ protocol_isEqual a b foreign import ccall "protocol_copyMethodDescriptionList" protocol_copyMethodDescriptionList :: Protocol -> CUInt -> CUInt -> Ptr CUInt -> IO (Ptr RawMethodDescription) -- | Returns an array of method descriptions of methods meeting a given specification for a given protocol. protocolMethodDescriptionList :: MonadIO m => Protocol -> Bool -- ^ A Boolean value that indicates whether returned methods should be required methods (pass @True@ to specify required methods). -> Bool -- ^ A Boolean value that indicates whether returned methods should be instance methods (pass @True@ to specify instance methods). -> m (V.Vector MethodDescription) protocolMethodDescriptionList p req inst = liftIO $ do l <- listCopier (protocol_copyMethodDescriptionList p (if req then yes else no) (if inst then yes else no)) mapM peekMethodDescription $ G.convert l -- | TODO this returns a struct directly, needs a wrapper. Don't use this foreign import ccall "protocol_getMethodDescription" protocol_getMethodDescription :: Protocol -> Selector -> CUInt -> CUInt -> IO (Ptr RawMethodDescription) foreign import ccall "protocol_copyPropertyList" protocol_copyPropertyList :: Protocol -> Ptr CUInt -> IO (Ptr Property) -- | Returns an array of the properties declared by a protocol. protocolPropertyList :: MonadIO m => Protocol -> m (VS.Vector Property) protocolPropertyList = liftIO . listCopier . protocol_copyPropertyList foreign import ccall "protocol_getProperty" protocol_getProperty :: Protocol-> CString -> CUInt -> CUInt -> IO Property -- | Returns the specified property of a given protocol. protocolProperty :: MonadIO m => Protocol -> String -- ^ The name of a property. -> Bool -- ^ A Boolean value that indicates whether name is a required property. -> Bool -- ^ A Boolean value that indicates whether name is an instance property. -> m (Maybe Property) -- ^ The property specified by name, isRequiredProperty, and isInstanceProperty for proto, or @Nothing@ if none of proto’s properties meets the specification. protocolProperty p s req inst = liftIO $ withCString s $ \cstr -> do pr@(Property prp) <- protocol_getProperty p cstr (if req then yes else no) (if inst then yes else no) return $! if prp == nullPtr then Nothing else Just pr foreign import ccall "protocol_conformsToProtocol" protocol_conformsToProtocol :: Protocol -> Protocol -> IO CUInt -- | Returns a Boolean value that indicates whether one protocol conforms to another protocol. protocolConformsToProtocol :: MonadIO m => Protocol -> Protocol -> m Bool protocolConformsToProtocol p1 p2 = liftIO $ fmap toBool $ protocol_conformsToProtocol p1 p2 foreign import ccall "property_getName" property_getName :: Property -> CString -- | Returns the name of a property. propertyName :: Property -> String propertyName = unsafePerformIO . peekCString . property_getName instance Show Property where show = propertyName foreign import ccall "property_getAttributes" property_getAttributes :: Property -> CString -- | Returns the attribute string of a property. -- -- The format of the attribute string is described in Declared Properties in Objective-C Runtime Programming Guide. propertyAttributes :: Property -> String propertyAttributes = unsafePerformIO . peekCString . property_getAttributes foreign import ccall "property_copyAttributeValue" property_copyAttributeValue :: Property -> CString -> IO CString -- | Returns the value of a property attribute given the attribute name. propertyAttributeValue :: MonadIO m => Property -- ^ The property whose value you are interested in. -> String -- ^ A C string representing the name of the attribute. -> m (Maybe String) -- ^ The value string of the attributeName attribute, if one exists in property; otherwise, @Nothing@ propertyAttributeValue p str = liftIO $ withCString str $ \cstr -> do r <- property_copyAttributeValue p cstr if r /= nullPtr then do val <- peekCString r free r return $ Just val else pure Nothing foreign import ccall "property_copyAttributeList" property_copyAttributeList :: Property -> Ptr CUInt -> IO (Ptr RawAttribute) -- | Returns an array of property attributes for a given property. propertyAttributeList :: MonadIO m => Property -- ^ The property whose attributes you want to list. -> m (V.Vector Attribute) propertyAttributeList p = liftIO $ do l <- listCopier (property_copyAttributeList p) mapM readAttribute $ G.convert l foreign import ccall "objc_enumerationMutation" objc_enumerationMutation :: Id -> IO () -- | The Objective-C compiler inserts this function when it detects that an object is mutated during a foreach iteration. The function is called when a mutation occurs, and the enumeration mutation handler is enacted if it is set up (via the objc_setEnumerationMutationHandler function). If the handler is not set up, a fatal error occurs. enumerationMutation :: MonadIO m => Id -- ^ The object being mutated. -> m () enumerationMutation = liftIO . objc_enumerationMutation foreign import ccall "objc_setEnumerationMutationHandler" objc_setEnumerationMutationHandler :: FunPtr (Id -> IO ()) -> IO () foreign import ccall "wrapper" enumerationMutationCallback :: (Id -> IO ()) -> IO (FunPtr (Id -> IO ())) -- | Sets the current mutation handler. setEnumerationMutationHandler :: MonadIO m => (Id -> IO ()) -- ^ A function pointer to the new mutation handler. -> m (IO ()) -- ^ Returns a cleanup function that frees the exported callback setEnumerationMutationHandler f = liftIO $ do cb <- enumerationMutationCallback f objc_setEnumerationMutationHandler cb return (freeHaskellFunPtr cb) foreign import ccall "imp_implementationWithBlock" imp_implementationWithBlock :: Id -> IO (Imp a) foreign import ccall "imp_getBlock" imp_getBlock :: Imp a -> IO Id foreign import ccall "imp_removeBlock" imp_removeBlock :: Imp a -> IO CUInt foreign import ccall "objc_loadWeak" objc_loadWeak :: Ptr Id -> IO Id foreign import ccall "objc_storeWeak" objc_storeWeak :: Ptr Id -> Id -> IO Id -- | Policies related to associative references. data AssociativeObjectBehavior = Assign -- ^ Specifies a weak reference to the associated object. | RetainNonatomic -- ^ Specifies a strong reference to the associated object, and that the association is not made atomically. | CopyNonatomic -- ^ Specifies that the associated object is copied, and that the association is not made atomically. | Retain -- ^ Specifies a strong reference to the associated object, and that the association is made atomically. | Copy -- ^ Specifies that the associated object is copied, and that the association is made atomically. instance Enum AssociativeObjectBehavior where toEnum x = case x of 0 -> Assign 1 -> RetainNonatomic 3 -> CopyNonatomic 01401 -> Retain 01403 -> Copy fromEnum x = case x of Assign -> 0 RetainNonatomic -> 1 CopyNonatomic -> 3 Retain -> 01401 Copy -> 01403 -- TESTBED makeNSObj :: IO Id makeNSObj = do (Just c) <- lookupClass "NSObject" r <- msgSend c (selector "new") [] cn <- objectGetClassName r print cn return r printClassHierarchy :: IO () printClassHierarchy = do cs <- classList mcs <- VS.thaw cs VS.sortBy (\a b -> compare (className a) (className b)) mcs css <- VS.unsafeFreeze mcs G.forM_ (G.filter ((/= '_') . head . className) css) $ \c -> do print $ classChain c putStrLn "Properties" print =<< classPropertyList c objectClass <- objectGetClass c forM_ objectClass $ \oc -> do putStrLn "Class properties" print =<< classPropertyList oc putStrLn "Class methods" print =<< (V.mapM methodTypeEncoding) =<< (G.convert <$> classMethodList oc) putStrLn "Instance methods" print =<< fmap (V.filter ((/= '_') . head . selectorName) . V.map methodName) (G.convert <$> classMethodList c) putStrLn "" where classChain c = c : case classSuperclass c of Nothing -> [] Just s -> classChain s foreign import ccall "wrapper" printyExport :: (Id -> Selector -> CString -> IO ()) -> IO (FunPtr (Id -> Selector -> CString -> IO ())) mkPrinter :: IO Class mkPrinter = do expp <- printyExport $ \_ sel cstr -> do print sel peekCString cstr >>= putStrLn parent <- lookupClass "NSObject" (Just cls) <- allocateClassPair parent "Printy" 0 print =<< classAddMethod cls (selector "print:") expp "v@:" print =<< classAddProperty cls "woot" [] registerClassPair cls return cls tryPrinting = do (Just c) <- lookupClass "Printy" r <- msgSend c (selector "new") [] cn <- objectGetClassName r print cn withCString "yo" $ \cstr -> msgSend r (selector "print:") [argPtr cstr] return () data TypeEncoding = Char | Int | Short | Long -- ^ Treated as a 32-bit quantity on 64-bit programs | LongLong | UnsignedChar | UnsignedInt | UnsignedShort | UnsignedLong | UnsignedLongLong | Float | Double | Bool | Void | CharString | Object | RTClass | RTSelector | Array Int TypeEncoding | Structure String [TypeEncoding] | Union String [TypeEncoding] | Bits Int | Pointer TypeEncoding | Unknown | ConstModifier TypeEncoding | InModifier TypeEncoding | InOutModifier TypeEncoding | OutModifier TypeEncoding | ByCopyModifier TypeEncoding | ByRefModifier TypeEncoding | OneWayModifier TypeEncoding deriving (Show) readTypeEncoding :: String -> Either String (TypeEncoding, String) readTypeEncoding [] = Left [] readTypeEncoding (c:cs) = case c of 'c' -> pure (Char, dropWhile isDigit cs) 'i' -> pure (Int, dropWhile isDigit cs) 's' -> pure (Short, dropWhile isDigit cs) 'l' -> pure (Long, dropWhile isDigit cs) 'q' -> pure (LongLong, dropWhile isDigit cs) 'C' -> pure (UnsignedChar, dropWhile isDigit cs) 'I' -> pure (UnsignedInt, dropWhile isDigit cs) 'S' -> pure (UnsignedShort, dropWhile isDigit cs) 'L' -> pure (UnsignedLong, dropWhile isDigit cs) 'Q' -> pure (UnsignedLongLong, dropWhile isDigit cs) 'f' -> pure (Float, dropWhile isDigit cs) 'd' -> pure (Double, dropWhile isDigit cs) 'B' -> pure (Bool, dropWhile isDigit cs) 'v' -> pure (Void, dropWhile isDigit cs) '*' -> pure (CharString, dropWhile isDigit cs) '@' -> pure (Object, dropWhile isDigit cs) '#' -> pure (RTClass, dropWhile isDigit cs) ':' -> pure (RTSelector, dropWhile isDigit cs) {- '[' -> case span isDigit cs of (n, rest) -> case readTypeEncoding rest of Nothing -> error "Barf" Just (enc, rest') -> pure (Array (read n) enc, tail rest') '{' -> case span (\c -> c /= '=' && c /= '}') cs of (n, rest) -> case rest of [] -> pure (Structure n [], ) ('=':rest') -> case span (/= '}') rest' of (inStruct, outStruct) -> pure (Structure n (readEncodingArray inStruct), tail outStruct) '(' -> case span (/= '=') cs of (n, rest) -> case span (/= ')') (tail rest) of (inUnion, outUnion) -> pure (Union n (readEncodingArray inUnion), tail outUnion) -} 'b' -> case span isDigit cs of (n, rest) -> pure (Bits (read n), rest) '^' -> do (val, rest) <- readTypeEncoding cs pure (Pointer val, rest) '?' -> pure (Unknown, dropWhile isDigit cs) 'r' -> do (val, rest) <- readTypeEncoding cs pure (ConstModifier val, rest) 'n' -> do (val, rest) <- readTypeEncoding cs pure (InModifier val, rest) 'N' -> do (val, rest) <- readTypeEncoding cs pure (InOutModifier val, rest) 'o' -> do (val, rest) <- readTypeEncoding cs pure (OutModifier val, rest) 'O' -> do (val, rest) <- readTypeEncoding cs pure (ByCopyModifier val, rest) 'R' -> do (val, rest) <- readTypeEncoding cs pure (ByRefModifier val, rest) 'V' -> do (val, rest) <- readTypeEncoding cs pure (OneWayModifier val, rest) _ -> Left (c : cs) readEncodingArray :: String -> [TypeEncoding] readEncodingArray [] = [] readEncodingArray str = case readTypeEncoding str of Left str -> [] Right (enc, rest) -> enc : readEncodingArray rest
iand675/hobjc
src/Language/ObjC/Runtime.hs
bsd-3-clause
66,899
0
19
12,431
11,760
6,125
5,635
949
29
module Main where import Graphics.Gloss main = display disp color pic where disp = (InWindow "Nice Window" (200, 200) (10, 10)) color = white pic = pictures [Circle 80, Circle 40]
weiningl/tic-tac-toe
test.hs
bsd-3-clause
200
0
9
51
75
42
33
6
1
{-# LANGUAGE ScopedTypeVariables #-} import Control.Monad import Control.Concurrent import System.Environment import Foreign import System.LibVirt uri = "qemu:///system" main :: IO () main = do args <- getArgs case args of ["test"] -> initialize >> withConnection uri doTest ["list-nets"] -> initialize >> withConnection uri listNets ["start", domain] -> initialize >> withConnection uri (start domain) ["stop", domain] -> initialize >> withConnection uri (stop domain) ["destroy", domain] -> initialize >> withConnection uri (destroy domain) ["callback", domain] -> initialize >> eventRegisterDefaultImpl >> withConnection uri (doTest1 domain) ["capabilities"] -> initialize >> withConnection uri (\c -> connectGetCapabilities c >>= putStrLn) other -> putStrLn "Usage: Test <test | list-nets | start DOMAIN | stop DOMAIN | destroy DOMAIN | callback DOMAIN | capabilities>" start :: String -> Connection -> IO () start domain conn = do putStrLn $ "Running " ++ domain ++ "..." dom <- lookupDomainName conn domain createDomain dom `catchVirtError` (\e -> do putStrLn "Error:" print e) return () stop :: String -> Connection -> IO () stop domain conn = do putStrLn $ "Shutting down " ++ domain ++ "..." dom <- lookupDomainName conn domain shutdownDomain dom `catchVirtError` (\e -> do putStrLn "Error:" print e) return () destroy:: String -> Connection -> IO () destroy domain conn = do putStrLn $ "Destroing down " ++ domain ++ "..." dom <- lookupDomainName conn domain destroyDomain dom `catchVirtError` (\e -> do putStrLn "Error:" print e) return () doTest :: Connection -> IO () doTest conn = do putStrLn $ "Defined domains:" names <- definedDomainsNames conn forM_ names $ \name -> do putStrLn $ " Domain: " ++ name di <- getDomainInfo =<< lookupDomainName conn name putStrLn $ " Info: " ++ show di nr <- runningDomainsCount conn putStrLn $ "Number of running domains: " ++ show nr ni <- connectNumOfInterfaces conn putStrLn $ "Number of running interfaces: " ++ show ni ndi <- connectNumOfDefinedInterfaces conn putStrLn $ "Number of defined interfaces: " ++ show ndi ifs <- connectListAllInterfaces conn [ConnectListInterfacesInactive] putStrLn $ "Inactive interfaces: "++show ifs ifs' <- connectListAllInterfaces conn [ConnectListInterfacesActive] putStrLn $ "Active Interfaces: "++show ifs' ifs'' <- connectListAllInterfaces conn [ConnectListInterfacesActive, ConnectListInterfacesInactive] putStrLn $ "All Interfaces: "++show ifs'' forM_ ifs' $ \t -> do mc <- interfaceGetMACString t nc <- interfaceGetName t xc <- interfaceGetXMLDesc t 0 putStrLn . unwords $ ["interface", show t, "MAC is:", show mc, "Name is:", nc, xc] listNets :: Connection -> IO () listNets conn = do putStrLn $ "Defined networks:" names <- definedNetworksNames conn forM_ names putStrLn putStrLn "" nr <- runningNetworksCount conn putStrLn $ "Number of running networks: " ++ show nr putStrLn "Running networks:" names <- runningNetworksNames conn forM_ names putStrLn doTest1 domain conn = do doTest conn dom <- lookupDomainName conn domain callback <- mkConnectDomainEventCallback $ \conn dom event detail _o -> do print =<< getDomainInfo dom let ev = toEnum event print ev case ev of DomainEventDefined -> print (toEnum detail ::DomainEventDefinedDetailType) DomainEventUndefined -> print (toEnum detail ::DomainEventUndefinedDetailType) DomainEventStarted -> print (toEnum detail :: DomainEventStartedDetailType) DomainEventSuspended -> print (toEnum detail :: DomainEventSuspendedDetailType) DomainEventResumed -> print (toEnum detail :: DomainEventResumedDetailType) DomainEventStopped -> print (toEnum detail :: DomainEventStoppedDetailType) DomainEventShutdown -> print (toEnum detail :: DomainEventShutdownDetailType) print "callback" callbackFree <- mkFreeCallback $ \a -> print "free" --start domain conn --threadDelay (10*1000000) print =<< getDomainInfo dom connectDomainEventRegisterAny conn (dom) DomainEventIdLifecycle (callback) -- callback (nullPtr :: Ptr Int) (callbackFree) -- callbackFree forkIO . forever $ eventRunDefaultImpl getLine freeHaskellFunPtr callback freeHaskellFunPtr callbackFree
qnikst/libvirt-hs
Test.hs
bsd-3-clause
4,872
1
17
1,337
1,318
612
706
105
8
{-| Module : DeepControl.Monad.Trans Description : Deepened the usual Control.Monad.Trans module. Copyright : (c) Andy Gill 2001, (c) Oregon Graduate Institute of Science and Technology, 2001, (c) 2015 KONISHI Yohsuke License : BSD-style (see the file LICENSE) Maintainer : ocean0yohsuke@gmail.com Stability : experimental Portability : --- This module enables you to program in Monad-Transformer style for more __deeper__ level than the usual @Control.Monad.Trans@ module expresses. You would realize exactly what __/much deeper level/__ means by reading the example codes, which are attached on the page bottom. -} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} module DeepControl.Monad.Trans ( module Control.Monad.Trans, -- * MonadTrans MonadTrans_(..), -- * Level-2 -- ** trans-roll transfold2, untransfold2, -- * Level-3 -- ** trans-roll transfold3, untransfold3, -- * Level-4 -- ** trans-roll transfold4, untransfold4, -- * Level-5 -- ** trans-roll transfold5, untransfold5, -- * Level-2 example -- $Example_Level2 ) where import DeepControl.Applicative import DeepControl.Monad import Control.Monad.Trans import Control.Monad.Identity (Identity(..)) import Control.Monad.Trans.Identity (IdentityT(..)) import Control.Monad.Trans.List (ListT(..)) import Control.Monad.Trans.Maybe (MaybeT(..)) import Control.Monad.Except (Except, ExceptT(..), runExcept, runExceptT) import Control.Monad.Writer (Writer, WriterT(..), runWriter) import Data.Monoid -- import Control.Monad.Reader (Reader, ReaderT(..), runReader) -- $setup -- >>> import Control.Monad.Trans.Maybe -- >>> import Control.Monad.List -- >>> import Control.Monad.Except -- >>> import Control.Monad.Writer ---------------------------------------------------------------------- -- Level-1 -- | Required only for transfold class (Monad m, MonadTrans t) => MonadTrans_ m t | m -> t, t -> m where trans :: (Monad n) => n (m a) -> t n a untrans :: (Monad n) => t n a -> n (m a) instance MonadTrans_ Identity IdentityT where trans = IdentityT . (runIdentity|$>) untrans = (Identity|$>) . runIdentityT instance MonadTrans_ [] ListT where trans = ListT untrans = runListT instance MonadTrans_ Maybe MaybeT where trans = MaybeT untrans = runMaybeT instance MonadTrans_ (Except e) (ExceptT e) where trans x = ExceptT ((runIdentity . runExceptT) |$> x) untrans x = (ExceptT . Identity) |$> runExceptT x instance (Monoid w) => MonadTrans_ (Writer w) (WriterT w) where trans x = WriterT ((runIdentity . runWriterT) |$> x) untrans x = (WriterT . Identity) |$> runWriterT x {- instance MonadTrans_ (Reader r) (ReaderT r) where trans x = ReaderT . sink $ (((runIdentity|$>) . runReaderT) |$> x) untrans x = (ReaderT . (Identity|$>)) |$> (sink . runReaderT) x -- error: Could not deduce (Traversable ((->) r)) -} ---------------------------------------------------------------------- -- Level-2 -- | -- -- >>> transfold2 $ [Just 1] -- MaybeT [Just 1] -- -- >>> transfold2 $ Just [1] -- ListT (Just [1]) -- transfold2 :: (Monad m1, MonadTrans_ m2 t2) => m1 (m2 a) -> (t2 m1) a transfold2 = trans -- | -- -- >>> untransfold2 $ MaybeT [Just 1] -- [Just 1] -- -- >>> untransfold2 $ ListT (Just [1]) -- Just [1] -- untransfold2 :: (Monad m1, MonadTrans_ m2 t2) => (t2 m1) a -> m1 (m2 a) untransfold2 = untrans ---------------------------------------------------------------------- -- Level-3 -- | -- -- >>> transfold3 $ ExceptT (Identity (Right [Just 1])) -- MaybeT (ListT (ExceptT (Identity (Right [Just 1])))) -- transfold3 :: (Monad m1, Monad (t2 m1), MonadTrans_ m2 t2, MonadTrans_ m3 t3) => m1 (m2 (m3 a)) -> t3 (t2 m1) a transfold3 = trans . trans -- | -- -- >>> untransfold3 $ MaybeT (ListT (ExceptT (Identity (Right [Just 1])))) -- ExceptT (Identity (Right [Just 1])) -- untransfold3 :: (Monad m1, Monad (t2 m1), MonadTrans_ m2 t2, MonadTrans_ m3 t3) => t3 (t2 m1) a -> m1 (m2 (m3 a)) untransfold3 = untrans . untrans ---------------------------------------------------------------------- -- Level-4 transfold4 :: (Monad m1, Monad (t2 m1), Monad (t3 (t2 m1)), MonadTrans_ m2 t2, MonadTrans_ m3 t3, MonadTrans_ m4 t4) => m1 (m2 (m3 (m4 a))) -> t4 (t3 (t2 m1)) a transfold4 = trans . trans . trans untransfold4 :: (Monad m1, Monad (t2 m1), Monad (t3 (t2 m1)), MonadTrans_ m2 t2, MonadTrans_ m3 t3, MonadTrans_ m4 t4) => t4 (t3 (t2 m1)) a -> m1 (m2 (m3 (m4 a))) untransfold4 = untrans . untrans . untrans ---------------------------------------------------------------------- -- Level-4 transfold5 :: (Monad m1, Monad (t2 m1), Monad (t3 (t2 m1)), Monad (t4 (t3 (t2 m1))), MonadTrans_ m2 t2, MonadTrans_ m3 t3, MonadTrans_ m4 t4, MonadTrans_ m5 t5) => m1 (m2 (m3 (m4 (m5 a)))) -> t5 (t4 (t3 (t2 m1))) a transfold5 = trans . trans . trans . trans untransfold5 :: (Monad m1, Monad (t2 m1), Monad (t3 (t2 m1)), Monad (t4 (t3 (t2 m1))), MonadTrans_ m2 t2, MonadTrans_ m3 t3, MonadTrans_ m4 t4, MonadTrans_ m5 t5) => t5 (t4 (t3 (t2 m1))) a -> m1 (m2 (m3 (m4 (m5 a)))) untransfold5 = untrans . untrans . untrans . untrans ---------------------------------------------------------------------- -- Examples {- $Example_Level2 Here is a monad transformer example how to implement Ackermann function improved to stop within a certain limit of time, with ReaderT-IdentityT2-IO-Maybe monad, a level-2 monad-transformation. >import DeepControl.Applicative >import DeepControl.Traversable (sink) >import DeepControl.Monad ((>-)) >import DeepControl.Monad.Morph ((|*|), (|>|)) >import DeepControl.Monad.Trans (transfold2, untransfold2) >import DeepControl.Monad.Trans.Identity (Identity(..), IdentityT(..), IdentityT2(..)) >import Control.Monad.Reader >import Control.Monad.Trans.Maybe > >import System.Timeout (timeout) > >type TimeLimit = Int > >ackermannTimeLimit :: TimeLimit -> Int -> Int -> > IO (Maybe Int) -- IO-Maybe Monad >ackermannTimeLimit timelimit x y = timeout timelimit (ackermannIO x y) > where > ackermannIO :: Int -> Int -> IO Int > ackermannIO 0 n = (.*) $ n + 1 > ackermannIO m n | m > 0 && n == 0 = ackermannIO (m-1) 1 > | m > 0 && n > 0 = ackermannIO m (n-1) >>= ackermannIO (m-1) > >ackermann :: Int -> Int -> > ReaderT TimeLimit (IdentityT2 IO Maybe) Int -- ReaderT-IdentityT2-IO-Maybe monad >ackermann x y = do > timelimit <- ask > (|*|) . IdentityT2 $ ackermannTimeLimit timelimit x y -- lift IO-Maybe function to ReaderT-IdentityT2-IO-Maybe function > >calc_ackermann :: TimeLimit -> Int -> Int -> IO (Maybe Int) >calc_ackermann timelimit x y = ackermann x y >- \r -> runReaderT r timelimit > >- runIdentityT2 > >-- λ> sink $ calc_ackermann 1000 |$> [0..4] |* 4 >-- [Just 5,Just 6,Just 11,Just 125,Nothing] > >ackermann' :: Int -> Int -> > ReaderT TimeLimit (MaybeT IO) Int -- ReaderT-MaybeT-IO monad >ackermann' x y = (transfold2 . runIdentityT2) |>| ackermann x y -- You can make usual ReaderT-MaybeT-IO function from ReaderT-IdentityT2-IO-Maybe function > >ackermann'' :: Int -> Int -> > ReaderT TimeLimit (IdentityT2 IO Maybe) Int -- ReaderT-IdentityT2-IO-Maybe monad >ackermann'' x y = (IdentityT2 . untransfold2) |>| ackermann' x y -- You can make ReaderT-IdentityT2-IO-Maybe function from usual ReaderT-MaybeT-IO function -}
ocean0yohsuke/deepcontrol
DeepControl/Monad/Trans.hs
bsd-3-clause
7,636
0
15
1,510
1,414
782
632
57
1
{-# OPTIONS_GHC -Wno-missing-signatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} module Cm.ORSet where import Control.Monad.State.Strict (evalStateT) import qualified Data.MultiMap as MultiMap import Test.QuickCheck (counterexample, (.&&.), (===), (==>)) import CRDT.Cm (initial, makeAndApplyOp, query) import CRDT.Cm.ORSet (Intent (Add, Remove), ORSet, Tag (Tag), elements) import CRDT.LamportClock.Simulation (runLamportClockSim, runProcessSim) import CRDT.Laws (cmrdtLaw) import Util (pattern (:-), expectRight) prop_Cm = cmrdtLaw @(ORSet Char) -- | Example from fig. 14 from "A comprehensive study of CRDTs" prop_fig14 α β a = expectRight . runLamportClockSim $ do op1 <- runProcessSim β . eval . makeAndApplyOp $ Add (a :: Char) (op2, op3) <- runProcessSim α . eval $ (,) <$> makeAndApplyOp (Add a) <*> makeAndApplyOp (Remove a) pure $ α < β ==> check "2" [op2] [a :- [Tag α 0]] .&&. check "23" [op2, op3] [] .&&. check "231" [op2, op3, op1] [a :- [Tag β 0]] .&&. check "1" [op1] [a :- [Tag β 0]] .&&. check "12" [op1, op2] [a :- [Tag α 0, Tag β 0]] .&&. check "123" [op1, op2, op3] [a :- [Tag β 0]] where check opsLabel ops result = counterexample ("ops = " ++ opsLabel) $ counterexample ("ops = " ++ show ops) $ query' ops === result eval = (`evalStateT` initial @(ORSet Char)) query' :: (Ord a, Foldable f) => f (ORSet a) -> [(a, [Tag])] query' = MultiMap.assocs . elements . query
cblp/crdt
crdt-test/test/Cm/ORSet.hs
bsd-3-clause
1,861
0
18
600
594
332
262
37
1
----------------------------------------------------------------------------- -- | -- Module : Language.VHDL.Ppr -- Copyright : (c) SAM Group, KTH/ICT/ECS 2007-2008 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : christiaan.baaij@gmail.com -- Stability : experimental -- Portability : non-portable (Template Haskell) -- -- ForSyDe pretty-printing class and auxiliar functions. -- ----------------------------------------------------------------------------- module Language.VHDL.Ppr where import Text.PrettyPrint.HughesPJ -- | Pretty printing class class Ppr a where ppr :: a -> Doc -- identity instantiation instance Ppr Doc where ppr = id -- | Pretty printing class with associated printing options class PprOps ops toPpr | toPpr -> ops where -- NOTE: Would it be better to use a State Monad? -- i.e. pprOps :: toPpr -> State ops Doc pprOps :: ops -> toPpr -> Doc -- dot dot :: Doc dot = char '.' -- One line vertical space vSpace :: Doc vSpace = text "" -- Multi-line vertical space multiVSpace :: Int -> Doc multiVSpace n = vcat (replicate n (text "")) -- Pretty-print a list supplying the document joining function ppr_list :: Ppr a => (Doc -> Doc -> Doc) -> [a] -> Doc ppr_list _ [] = empty ppr_list join (a1:rest) = go a1 rest where go a1 [] = ppr a1 go a1 (a2:rest) = ppr a1 `join` go a2 rest -- Pretty-print a list supplying the document joining function -- (PprOps version) pprOps_list :: PprOps ops toPpr => ops -> (Doc -> Doc -> Doc) -> [toPpr] -> Doc pprOps_list _ _ [] = empty pprOps_list ops join (a1:rest) = go a1 rest where go a1 [] = pprOps ops a1 go a1 (a2:rest) = pprOps ops a1 `join` go a2 rest -- | Join two documents vertically leaving n vertical spaces between them vNSpaces :: Int -> Doc -> Doc -> Doc vNSpaces n doc1 doc2 = doc1 $+$ multiVSpace n $+$ doc2 -- Join two documents vertically putting a semicolon in the middle vSemi :: Doc -> Doc -> Doc vSemi doc1 doc2 = doc1 <> semi $+$ doc2 -- Join two documents vertically putting a comma in the middle vComma :: Doc -> Doc -> Doc vComma doc1 doc2 = doc1 <> comma $+$ doc2 -- Join two documents horizontally putting a comma in the middle hComma :: Doc -> Doc -> Doc hComma doc1 doc2 = doc1 <> comma <+> doc2 -- | apply sep to a list of prettyprintable elements, -- previously interspersing commas commaSep :: Ppr a => [a] -> Doc commaSep = sep.(punctuate comma).(map ppr) -- | Only append if both of the documents are non-empty ($++$) :: Doc -> Doc -> Doc d1 $++$ d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 $+$ d2 -- | Only append if both of the documents are non-empty (<++>) :: Doc -> Doc -> Doc d1 <++> d2 | isEmpty d1 || isEmpty d2 = empty | otherwise = d1 <+> d2 -- | Enclose in parenthesis only if the document is non-empty parensNonEmpty :: Doc -> Doc parensNonEmpty doc | isEmpty doc = empty parensNonEmpty doc = parens doc -- | Enclose in parenthesis only if the predicate is True parensIf :: Bool -> Doc -> Doc parensIf p d = if p then parens d else d
christiaanb/vhdl
Language/VHDL/Ppr.hs
bsd-3-clause
3,107
2
10
681
771
409
362
-1
-1
{-| Module : Mandelbrot Description : Algorithm of Mandelbrot functions Module which get resolution of image and points and calculate correct color to point based on Mandelbrot algorithm -} module Mandelbrot (drawMandelbrot, runMandelbrotTests, runQuickCheckMandelbrot) where import Data.Complex import Graphics.GD import Plot import Test.HUnit import Test.QuickCheck -- |Max number of iteration to approximate set maxIteration = 150 -- |Main function, invoke draw Mandelbrot set drawMandelbrot :: Size -- ^ Resolution of generating image -> Bound -- ^ Four coordinates of funtion bound -> String -- ^ Name of generating file -> IO() -- ^ Result: Save file drawMandelbrot size bound fileName = drawPlot drawMandelbrot_ size bound fileName -- |Generating colors for points drawMandelbrot_ :: Coord -- ^ Point to draw -> Color -- ^ Color of the point calculated from mandelbrot formula drawMandelbrot_ (x,y) = rgb (floor $ f * 255) (floor $ f * 120) 0 where i = mandelbrot (x :+ y) f = fromIntegral i / fromIntegral maxIteration -- |Recursive formula for points mandelbrot :: Complex Double -- ^ Checking point -> Int -- ^ Number of iteration mandelbrot z = length $ takeWhile (\c -> magnitude c <= 2) $ take maxIteration $ iterate (\w -> w^2 + z) 0 test1 = TestCase (assertEqual "color1" 16742400 (drawMandelbrot_ (0,0))) test2 = TestCase (assertEqual "color2" 196864 (drawMandelbrot_ (1,1))) test3 = TestCase (assertEqual "color3" 65536 (drawMandelbrot_ (10,10))) test4 = TestCase (assertEqual "mandelbrot1" 2 (mandelbrot (1 :+1))) test5 = TestCase (assertEqual "mandelbrot2" 1 (mandelbrot (0 :+ 20))) test6 = TestCase (assertEqual "mandelbrot3" 1 (mandelbrot (123 :+ 0))) test7 = TestCase (assertEqual "mandelbrot3" 150 (mandelbrot (0 :+ 0))) tests = TestList [TestLabel "test1" test1, TestLabel "test2" test2, TestLabel "test3" test3, TestLabel "test4" test4, TestLabel "test5" test5, TestLabel "test6" test6, TestLabel "test7" test7] -- |Run tests runMandelbrotTests :: IO Counts runMandelbrotTests = do runTestTT tests max_Color :: Coord -> Bool max_Color (x,y) = drawMandelbrot_ (x,y) <= 16777216 min_Color :: Coord -> Bool min_Color (x,y) = drawMandelbrot_ (x,y) >= 0 -- |Run quick tests runQuickCheckMandelbrot = do quickCheck max_Color >> quickCheck min_Color
jsamol/fractal-painter
src/Mandelbrot.hs
bsd-3-clause
2,452
0
12
522
646
345
301
35
1
{-#LANGUAGE OverloadedStrings#-} {- Project name: Gtf2Table Min Zhang Date: March 1, 2016 Version: v0.1.0 README: Fix some genes have errors in annotation -} module Gtf2Table where import qualified Data.Text.Lazy as T import qualified Data.Text.Lazy.IO as TextIO import Control.Applicative import qualified Data.List as L import qualified Data.Set as Set import Control.Monad (fmap) import Data.Ord (comparing) import Data.Function (on) import qualified Safe as S import qualified Data.HashMap.Lazy as M import qualified Data.Maybe as Maybe import qualified Data.Foldable as F (all) import qualified System.IO as IO import System.Environment main = do intro args <- getArgs let inputpath = S.headNote "Please put two arguments. gtf2Tab inputpath outputpath." args let outputpath = S.lastNote "Please put two arguments. gtf2Tab inputpath outputpath." args input <- TextIO.readFile inputpath let output = (makeTable . shrinkLines . filter (\x->length x == 2) . map (map last . filter (\x->head x == "gene_id" || head x == "gene_name") . map (T.splitOn " ")) . map (T.splitOn "; ") . T.lines . replaceTab . stripQuotes) input TextIO.writeFile outputpath output inputpath = "/Users/minzhang/Downloads/sample.gtf" intro = TextIO.putStrLn "Gtf2Table: inputpath outputpath" stripQuotes t = T.replace "\"" "" t replaceTab = T.replace "\t" "; " shrinkLines = Set.toList . Set.fromList makeTable x = T.unlines $ map (T.intercalate " ") x
Min-/Ensembl2Symbol
src/Gtf2Table.hs
bsd-3-clause
1,569
0
27
345
409
224
185
37
1
module AERN2.Local.Poly ( variable , genericisePoly , LocalPoly ) where import MixedTypesNumPrelude import AERN2.Interval import AERN2.MP.Ball import AERN2.Poly.Cheb import AERN2.RealFun.Operations import AERN2.Local.Basics import AERN2.MP.Dyadic import AERN2.Poly.Power.RootsInt import AERN2.Poly.Power.SignedSubresultant import AERN2.Poly.Basics hiding (Terms) import AERN2.Poly.Conversion import Data.Ratio import qualified Data.Map as Map import AERN2.Local.Maximum type LocalPoly a = Local (ChPoly a) variable :: LocalPoly MPBall variable l r ac = setAccuracyGuide ac $ setPrecisionAtLeastAccuracy ac x where x :: ChPoly MPBall x = varFn (dom, ac) () dom = Interval l r debug_useSeparablePart :: Bool debug_useSeparablePart = True instance GenericMaximum (LocalPoly MPBall) where genericise f l r ac = [genericisePoly fI l r] where fI = f l r ac genericisePoly :: ChPoly MPBall -> Dyadic -> Dyadic -> (Dyadic, Dyadic, MPBall -> MPBall, Accuracy, Rational -> Rational, DyadicInterval, Terms) genericisePoly fI a b = (a, b, evalF, fAcc, evalDF, dom, bsI) where Interval l r = getDomain fI evalF = evalDf fI (2/!(r - l) * dfI) fAcc = getAccuracy fI evalDF = evalDirect dfRat :: Rational -> Rational ch2Power (e, p) = (e, cheb2Power p) dfI = (derivativeExact . centre) fI dfRat = makeRational dfI (eI, dfIPow) = (ch2Power . intify) dfI dom = chPoly_dom fI aI = fromDomToUnitInterval dom (rational a) bI = fromDomToUnitInterval dom (rational b) dfIPow' = if debug_useSeparablePart && dyadic eI == 0 && degree dfI < 50 then separablePart dfIPow else dfIPow bsI = initialBernsteinCoefs dfIPow' eI aI bI makeRational :: ChPoly MPBall -> ChPoly Rational makeRational (ChPoly dom (Poly ts) acG _) = ChPoly dom (Poly $ terms_map (rational . centre) ts) acG (error "makeRational does not define bounds") intify :: ChPoly MPBall -> (ErrorBound, Poly Integer) intify (ChPoly _ p _ _) = (err, pInt) where termsRational = terms_map (rational . ball_value) (poly_terms p) err = termsError * termsDenominator termsError = ball_error $ terms_lookupCoeff (poly_terms p) 0 termsDenominator = Map.foldl' lcm 1 $ terms_map denominator termsRational pInt = Poly $ terms_map (numerator . (* termsDenominator)) termsRational instance CanDiv (Local (ChPoly MPBall)) Integer where type DivType (Local (ChPoly MPBall)) Integer = Local (ChPoly MPBall) (f `divide` i) l r ac = (f l r ac) /! (mpBallP (prec $ fromAccuracy $ ac) i) type DivTypeNoCN (Local (ChPoly MPBall)) Integer = Local (ChPoly MPBall) (f `divideNoCN` i) l r ac = (f l r ac) /! (mpBallP (prec $ fromAccuracy $ ac) i)
michalkonecny/aern2
aern2-fun-univariate/src/AERN2/Local/Poly.hs
bsd-3-clause
2,692
4
13
523
974
525
449
-1
-1
data Formula = Atom Bool -- atomic formula | And Formula Formula -- f /\ f | Or Formula Formula -- f \/ f | Not Formula -- not(f) instance Show Formula where show (Atom a) = "Atom " ++ show a show (And a b) = "And (" ++ show a ++ ") (" ++ show b ++ ")" show (Or a b) = "Or (" ++ show a ++ ") (" ++ show b ++ ")" show (Not a) = "Not (" ++ show a ++ ")" collect_atoms (Atom x) = [Atom x] collect_atoms (And a b) = collect_atoms a ++ collect_atoms b collect_atoms (Or a b) = collect_atoms a ++ collect_atoms b collect_atoms (Not a) = collect_atoms a eval (Atom a) = a eval (And a b) = eval a && eval b eval (Or a b) = eval a || eval b eval (Not a) = not (eval a)
zseymour/latex-repo
CS 571/assignment3/code/formula.hs
mit
714
0
10
207
341
166
175
18
1
{- | Module : ./SoftFOL/ParseTPTP.hs Description : A parser for the TPTP Input Syntax Copyright : (c) C.Maeder, DFKI Lab Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable A parser for the TPTP Input Syntax v3.4.0.1 taken from <http://www.cs.miami.edu/~tptp/TPTP/SyntaxBNF.html> -} module SoftFOL.ParseTPTP ( tptp , singleQuoted , form , genList , genTerm , GenTerm (..) , GenData (..) , AWord (..) , prTPTPs , tptpModel , ppGenTerm ) where import Text.ParserCombinators.Parsec import SoftFOL.Sign import SoftFOL.PrintTPTP import qualified Common.Doc as Doc import Common.Id import Common.Lexer (getPos) import Common.Parsec import Control.Monad import Data.Char (ord, toLower, isAlphaNum) import Data.Maybe showRole :: Role -> String showRole = map toLower . show allRoles :: [Role] allRoles = [ Axiom , Hypothesis , Definition , Assumption , Lemma , Theorem , Conjecture , Negated_conjecture , Plain , Fi_domain , Fi_functors , Fi_predicates , Type , Unknown ] tptp :: Parser [TPTP] tptp = skip >> many (headerLine <|> include <|> formAnno <|> (newline >> skip >> return EmptyLine)) << eof blank :: Parser p -> Parser () blank = (>> skipMany1 whiteSpace) szsOutput :: Parser () szsOutput = blank (string "SZS") >> blank (string "output") iproverSzsEnd :: Parser () iproverSzsEnd = try $ char '%' >> skipMany whiteSpace >> szsOutput otherCommentLine :: Parser () otherCommentLine = (lookAhead iproverSzsEnd >> forget (char '%')) <|> forget commentLine skipAllButEnd :: Parser () skipAllButEnd = skipMany $ whiteSpace <|> commentBlock <|> otherCommentLine <|> forget newline tptpModel :: Parser [(String, SPTerm)] tptpModel = do _ <- manyTill anyChar (try (szsOutput >> blank (string "start")) <|> try (blank $ string "START OF MODEL")) _ <- manyTill anyChar newline skipAllButEnd ts <- many1 (formAnno << skipAllButEnd) (szsOutput >> blank (string "end")) <|> forget (string "END OF MODEL") return $ foldr (\ t l -> case t of FormAnno _ (Name n) _ e _ -> (n, e) : l _ -> l) [] ts printable :: Char -> Bool printable c = let i = ord c in i >= 32 && i <= 126 commentLine :: Parser String commentLine = (char '%' <|> char '#') >> manyTill (satisfy printable) newline headerLine :: Parser TPTP headerLine = fmap CommentLine $ commentLine << skip commentBlock :: Parser () commentBlock = forget $ plainBlock "/*" "*/" whiteSpace :: Parser () whiteSpace = forget $ oneOf "\r\t\v\f " skip :: Parser () skip = skipMany $ whiteSpace <|> commentBlock skipAll :: Parser () skipAll = skipMany $ whiteSpace <|> commentBlock <|> forget commentLine <|> forget newline lexeme :: Parser a -> Parser a lexeme = (<< skipAll) key :: Parser a -> Parser () key = (>> skipAll) keyChar :: Char -> Parser () keyChar = key . char comma :: Parser () comma = keyChar ',' oParen :: Parser () oParen = keyChar '(' cDotParen :: Parser () cDotParen = string ")." >> skip >> option () (newline >> skip) include :: Parser TPTP include = do key $ tryString "include" oParen a <- atomicWord m <- optionL $ do comma sepBy1 aname comma cDotParen return $ Include (FileName a) m -- | does not allow leading zeros natural :: Parser String natural = string "0" <|> many1 digit aname :: Parser Name aname = fmap Name (atomicWord <|> lexeme natural) atomicWord :: Parser String atomicWord = lexeme $ lowerWord <|> singleQuoted isUAlphaNum :: Char -> Bool isUAlphaNum c = isAlphaNum c || elem c "_$" luWord :: Parser Char -> Parser String luWord p = do c <- p r <- many $ satisfy isUAlphaNum return $ c : r lowerWord :: Parser String lowerWord = luWord lower upperWord :: Parser String upperWord = luWord upper singleQuoted :: Parser String singleQuoted = let quote = '\'' in fmap concat $ char quote >> many (tryString "\\'" <|> single (satisfy $ \ c -> printable c && c /= quote)) << char quote formKind :: Parser FormKind formKind = choice $ map (\ k -> key (tryString $ show k) >> return k) [FofKind, CnfKind, FotKind] role :: Parser Role role = choice $ map (\ r -> key (tryString $ showRole r) >> return r) allRoles formAnno :: Parser TPTP formAnno = do k <- formKind oParen n <- aname comma r <- role comma f <- form m <- optionMaybe $ do comma gt <- fmap Source genTerm i <- optionMaybe $ do comma fmap Info genList return $ Annos gt i cDotParen return $ FormAnno k n r f m colon :: Parser () colon = keyChar ':' genTerm :: Parser GenTerm genTerm = fmap GenTermList genList <|> do gd <- genData m <- optionMaybe $ do keyChar ':' genTerm return $ GenTerm gd m genData :: Parser GenData genData = formData <|> otherData <|> do a <- fmap AWord atomicWord l <- optionL $ parens $ sepBy1 genTerm comma return $ GenData a l otherData :: Parser GenData otherData = fmap OtherGenData $ (upperWord <|> real <|> distinct) << skipAll distinct :: Parser String distinct = let dquot = '"' in enclosedBy (flat $ many1 $ tryString "\\\"" <|> single (satisfy (/= dquot))) $ char dquot decimal :: Parser String decimal = optionL (single $ oneOf "-+") <++> natural real :: Parser String real = do d <- decimal f <- optionL $ char '.' <:> many1 digit e <- optionL $ oneOf "eE" <:> decimal return $ d ++ f ++ e formData :: Parser GenData formData = liftM GenFormData $ liftM2 FormData (char '$' >> formKind) $ parens form orOp :: Parser () orOp = keyChar '|' andOp :: Parser () andOp = keyChar '&' pToken :: Parser String -> Parser Token pToken = liftM2 (\ p s -> Token s (Range [p])) getPos . (<< skipAll) form :: Parser SPTerm form = do u <- unitary do orOp us <- sepBy1 unitary orOp return $ compTerm SPOr $ u : us <|> do andOp us <- sepBy1 unitary andOp return $ compTerm SPAnd $ u : us <|> do o <- choice $ map (pToken . tryString) ["<=>", "=>", "<=", "<~>", "~|", "~&"] u2 <- unitary let s = tokStr o a = [u, u2] return $ case lookup s $ zip ["<=>", "=>", "<="] [SPEquiv, SPImplies, SPImplied] of Just ks -> compTerm ks a Nothing -> case lookup s $ zip ["<~>", "~|", "~&"] [SPEquiv, SPOr, SPAnd] of Just ks -> compTerm SPNot [compTerm ks a] Nothing -> compTerm (SPCustomSymbol o) a <|> return u unitary :: Parser SPTerm unitary = parens form <|> quantForm <|> unaryForm <|> atomicForm quantForm :: Parser SPTerm quantForm = do q <- lexeme $ (char '!' >> return SPForall) <|> (char '?' >> return SPExists) vs <- brackets $ sepBy1 variable comma colon u <- unitary return SPQuantTerm { quantSym = q , variableList = vs , qFormula = u } unaryForm :: Parser SPTerm unaryForm = do keyChar '~' u <- unitary return $ compTerm SPNot [u] atomicForm :: Parser SPTerm atomicForm = do t <- term do key $ try $ char '=' << notFollowedBy (char '>' ) t2 <- term return $ mkEq t t2 <|> do key $ tryString "!=" t2 <- term return $ compTerm SPNot [mkEq t t2] <|> return t variable :: Parser SPTerm variable = fmap (simpTerm . SPCustomSymbol) $ pToken upperWord definedAtom :: Parser SPTerm definedAtom = fmap (simpTerm . SPCustomSymbol) $ pToken $ real <|> distinct functor :: Parser SPSymbol functor = fmap (\ t -> fromMaybe (SPCustomSymbol t) $ lookup (tokStr t) $ zip ["$true", "$false", "$equal"] [SPTrue, SPFalse, SPEqual]) $ pToken $ lowerWord <|> singleQuoted <|> dollarWord -- system and defined words dollarWord :: Parser String dollarWord = do d <- tryString "$$" <|> string "$" w <- lowerWord return $ d ++ w -- mixed plain, defined and system terms term :: Parser SPTerm term = variable <|> definedAtom <|> do f <- functor as <- optionL $ parens $ sepBy1 term comma return $ compTerm f as brackets :: Parser a -> Parser a brackets p = do keyChar '[' a <- p keyChar ']' return a parens :: Parser a -> Parser a parens p = do oParen a <- p keyChar ')' return a genList :: Parser [GenTerm] genList = brackets $ sepBy genTerm comma prTPTPs :: [TPTP] -> Doc.Doc prTPTPs = Doc.vcat . map prTPTP prTPTP :: TPTP -> Doc.Doc prTPTP p = case p of FormAnno k (Name n) r t m -> Doc.text (show k) Doc.<> Doc.parens (Doc.sepByCommas $ [ Doc.text n , Doc.text $ showRole r , printTPTP t] ++ maybe [] ppAnnos m) Doc.<> Doc.dot Include (FileName f) ns -> Doc.text "include" Doc.<> Doc.parens (Doc.sepByCommas $ ppName f : if null ns then [] else [Doc.brackets $ Doc.sepByCommas $ map ppAName ns]) Doc.<> Doc.dot CommentLine l -> Doc.text $ '%' : l EmptyLine -> Doc.text "" ppName :: String -> Doc.Doc ppName s = (if all isUAlphaNum s then id else Doc.quotes) $ Doc.text s ppAName :: Name -> Doc.Doc ppAName (Name n) = ppName n ppAnnos :: Annos -> [Doc.Doc] ppAnnos (Annos (Source gt) m) = ppGenTerm gt : maybe [] ppInfo m ppInfo :: Info -> [Doc.Doc] ppInfo (Info l) = [ppGenList l] ppList :: [GenTerm] -> Doc.Doc ppList = Doc.sepByCommas . map ppGenTerm ppGenList :: [GenTerm] -> Doc.Doc ppGenList = Doc.brackets . ppList ppGenTerm :: GenTerm -> Doc.Doc ppGenTerm gt = case gt of GenTerm gd m -> let d = ppGenData gd in case m of Just t -> Doc.fsep [d Doc.<> Doc.colon, ppGenTerm t] Nothing -> d GenTermList l -> ppGenList l ppGenData :: GenData -> Doc.Doc ppGenData gd = case gd of GenData (AWord aw) l -> ppName aw Doc.<> if null l then Doc.empty else Doc.parens $ ppList l OtherGenData s -> Doc.text s GenFormData (FormData k t) -> Doc.text ('$' : show k) Doc.<> Doc.parens (printTPTP t)
spechub/Hets
SoftFOL/ParseTPTP.hs
gpl-2.0
9,860
0
20
2,399
3,774
1,867
1,907
326
5
module Analysis.Interlevel.InterLevelCPSpec where import Data.Maybe (fromMaybe) import Test.Hspec import Abstract.Category import Abstract.Rewriting.DPO import Analysis.Interlevel.InterLevelCP import Category.TypedGraphRule () import Data.TypedGraph import Util.List import qualified XML.GGXReader as XML fileName = "tests/grammars/secondOrderMatchTest.ggx" dpoConf1, dpoConf2 :: Category morph => MorphismsConfig morph dpoConf1 = MorphismsConfig monic dpoConf2 = MorphismsConfig anyMorphism spec :: Spec spec = context "Inter-level Critical Pairs Test" dangextTest dangextTest :: Spec dangextTest = do it "dangling extension generates expected values" $ do (gg1,_,_) <- XML.readGrammar fileName False dpoConf1 checkDanglingExtension gg1 it "it finds inter-level conflicts in expected situations" $ do (gg1,gg2,_) <- XML.readGrammar fileName False dpoConf1 checkInterlevelConflict dpoConf1 dpoConf2 gg1 gg2 -- | Runs dangling extension to a specific rule and checks if there is -- the correct number of messages and data nodes, all nodes and all edges checkDanglingExtension gg1 = do let ruleC = getRule "ruleC" gg1 dangGraph = codomain (danglingExtension (leftMorphism ruleC)) [(_,typeOfMsg),(_,typeOfData)] = nodes (leftObject ruleC) msgsInDang = countElement typeOfMsg (map snd nods) dataInDang = countElement typeOfData (map snd nods) nods = nodes dangGraph edgs = edges dangGraph msgsInDang `shouldBe` 3 dataInDang `shouldBe` 3 length nods `shouldBe` 8 length edgs `shouldBe` 8 -- | Checks if the inter-level conflicts algorithm finds conflicts in -- expected situations. It does not check what is the conflict. checkInterlevelConflict mono arbitrary gg1 gg2 = do let sendMsg = ("sendMsg", getRule "sendMsg" gg1) getData = ("getData", getRule "getData" gg1) receiveMsg = ("receiveMsg", getRule "receiveMsg" gg1) deleteMsg = ("deleteMsg", getRule "deleteMsg" gg1) ruleB = ("ruleB", getRule "ruleB" gg1) ruleC = ("ruleC", getRule "ruleC" gg1) ruleD = ("ruleD", getRule "ruleD" gg1) a = ("a", getRule "a" gg2) b = ("b", getRule "b" gg2) c = ("c", getRule "c" gg2) d = ("d", getRule "d" gg2) length (interLevelCP arbitrary a sendMsg) `shouldBe` 1 length (interLevelCP arbitrary b sendMsg) `shouldBe` 0 length (interLevelCP arbitrary c sendMsg) `shouldBe` 0 length (interLevelCP arbitrary d sendMsg) `shouldBe` 0 length (interLevelCP arbitrary a getData) `shouldBe` 0 length (interLevelCP arbitrary b getData) `shouldBe` 0 length (interLevelCP arbitrary c getData) `shouldBe` 0 length (interLevelCP arbitrary d getData) `shouldBe` 0 length (interLevelCP arbitrary a receiveMsg) `shouldBe` 0 length (interLevelCP arbitrary b receiveMsg) `shouldBe` 0 length (interLevelCP arbitrary c receiveMsg) `shouldBe` 0 length (interLevelCP arbitrary d receiveMsg) `shouldBe` 0 length (interLevelCP arbitrary a deleteMsg) `shouldBe` 0 length (interLevelCP arbitrary b deleteMsg) `shouldBe` 0 length (interLevelCP arbitrary c deleteMsg) `shouldBe` 0 length (interLevelCP arbitrary d deleteMsg) `shouldBe` 0 length (interLevelCP arbitrary a ruleB) `shouldBe` 0 Prelude.null (interLevelCP mono b ruleB) `shouldBe` False length (interLevelCP arbitrary c ruleB) `shouldBe` 0 length (interLevelCP arbitrary d ruleB) `shouldBe` 0 length (interLevelCP arbitrary a ruleC) `shouldBe` 0 length (interLevelCP arbitrary b ruleC) `shouldBe` 0 Prelude.null (interLevelCP mono c ruleC) `shouldBe` False length (interLevelCP arbitrary d ruleC) `shouldBe` 0 length (interLevelCP arbitrary a ruleD) `shouldBe` 0 length (interLevelCP arbitrary b ruleD) `shouldBe` 0 length (interLevelCP arbitrary c ruleD) `shouldBe` 0 Prelude.null (interLevelCP mono d ruleD) `shouldBe` False getRule str gg = fromMaybe (error ("secondOrderTest: " ++ str ++ " is not in secondOrderMatchTest.ggx")) (lookup str (productions gg))
rodrigo-machado/verigraph
tests/Analysis/Interlevel/InterLevelCPSpec.hs
gpl-3.0
4,245
0
14
962
1,251
649
602
82
1
{-# LANGUAGE OverloadedStrings #-} -- Last updated 2008/11/04 11:11 -- http://www.imagemagick.org/discourse-server/viewtopic.php?f=10&t=10993 -- convert -size 640x480 xc:none -fill white -draw 'roundRectangle 15,15 624,464 15,15' logo: -compose SrcIn -composite mask_result.png -- import Graphics.ImageMagick.MagickWand main :: IO () main = withMagickWandGenesis $ do (_,mWand) <- magickWand (_,lWand) <- magickWand pWand <- pixelWand (_,dWand) <- drawingWand -- Create the initial 640x480 transparent canvas pWand `setColor` "none" newImage mWand 640 480 pWand pWand `setColor` "white" dWand `setFillColor` pWand drawRoundRectangle dWand 15 15 624 464 15 15 mWand `drawImage` dWand lWand `readImage` "logo:" -- Note that MagickSetImageCompose is usually only used for the MagickMontageImage -- function and isn't used or needed by MagickCompositeImage compositeImage mWand lWand srcInCompositeOp 0 0 -- Write the new image writeImages mWand "mask_result.png" True
flowbox-public/imagemagick
examples/round_mask.hs
apache-2.0
1,096
0
9
253
180
95
85
18
1
{-# LANGUAGE OverloadedStrings #-} {-| Implementation of the Ganeti maintenenace server. -} {- Copyright (C) 2015 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.MaintD.Server ( options , main , checkMain , prepMain ) where import Control.Applicative ((<|>)) import Control.Concurrent (forkIO) import Control.Exception.Lifted (bracket) import Control.Monad (forever, void, unless, when, liftM) import Control.Monad.IO.Class (liftIO) import Data.IORef (IORef, newIORef, readIORef) import qualified Data.Set as Set import Snap.Core (Snap, method, Method(GET), ifTop, dir, route) import Snap.Http.Server (httpServe) import Snap.Http.Server.Config (Config) import System.IO.Error (tryIOError) import System.Time (getClockTime) import qualified Text.JSON as J import Ganeti.BasicTypes ( GenericResult(..), ResultT, runResultT, mkResultT , mkResultTEither, withErrorT, isBad, isOk) import qualified Ganeti.Constants as C import Ganeti.Daemon ( OptType, CheckFn, PrepFn, MainFn, oDebug , oNoVoting, oYesDoIt, oPort, oBindAddress, oNoDaemonize) import Ganeti.Daemon.Utils (handleMasterVerificationOptions) import qualified Ganeti.HTools.Backend.Luxi as Luxi import Ganeti.HTools.Loader (ClusterData(..), mergeData, checkData) import Ganeti.Jobs (waitForJobs) import Ganeti.Logging.Lifted import qualified Ganeti.Luxi as L import Ganeti.MaintD.Autorepairs (harepTasks) import Ganeti.MaintD.Balance (balanceTask) import Ganeti.MaintD.CleanupIncidents (cleanupIncidents) import Ganeti.MaintD.CollectIncidents (collectIncidents) import Ganeti.MaintD.FailIncident (failIncident) import Ganeti.MaintD.HandleIncidents (handleIncidents) import Ganeti.MaintD.MemoryState import qualified Ganeti.Path as Path import Ganeti.Runtime (GanetiDaemon(GanetiMaintd)) import Ganeti.Types (JobId(..), JobStatus(..)) import Ganeti.Utils (threadDelaySeconds, partitionM) import Ganeti.Utils.Http (httpConfFromOpts, plainJSON, error404) import Ganeti.WConfd.Client ( runNewWConfdClient, maintenanceRoundDelay , maintenanceBalancing) -- | Options list and functions. options :: [OptType] options = [ oNoDaemonize , oDebug , oPort C.defaultMaintdPort , oBindAddress , oNoVoting , oYesDoIt ] -- | Type alias for checkMain results. type CheckResult = () -- | Type alias for prepMain results type PrepResult = Config Snap () -- | Load cluster data -- -- At the moment, only the static data is fetched via luxi; -- once we support load-based balancing in maintd as well, -- we also need to query the MonDs for the load data. loadClusterData :: ResultT String IO ClusterData loadClusterData = do now <- liftIO getClockTime socket <- liftIO Path.defaultQuerySocket either_inp <- liftIO . tryIOError $ Luxi.loadData False socket input_data <- mkResultT $ case either_inp of Left e -> do let msg = show e logNotice $ "Couldn't read data from luxid: " ++ msg return $ Bad msg Right r -> return r cdata <- mkResultT . return $ mergeData [] [] [] [] now input_data let (msgs, nl) = checkData (cdNodes cdata) (cdInstances cdata) unless (null msgs) . logDebug $ "Cluster data inconsistencies: " ++ show msgs return $ cdata { cdNodes = nl } -- | Perform one round of maintenance maintenance :: IORef MemoryState -> ResultT String IO () maintenance memstate = do delay <- withErrorT show $ runNewWConfdClient maintenanceRoundDelay liftIO $ threadDelaySeconds delay oldjobs <- getJobs memstate logDebug $ "Jobs submitted in the last round: " ++ show (map fromJobId oldjobs) luxiSocket <- liftIO Path.defaultQuerySocket -- Filter out any jobs in the maintenance list which can't be parsed by luxi -- anymore. This can happen if the job file is corrupted, missing or archived. -- We have to query one job at a time, as luxi returns a single error if any -- job in the query list can't be read/parsed. (okjobs, badjobs) <- bracket (mkResultTEither . tryIOError $ L.getLuxiClient luxiSocket) (liftIO . L.closeClient) $ mkResultT . liftM Ok . (\c -> partitionM (\j -> liftM isOk $ L.queryJobsStatus c [j]) oldjobs) unless (null badjobs) $ do logInfo . (++) "Unparsable jobs (marking as failed): " . show $ map fromJobId badjobs mapM_ (failIncident memstate) badjobs jobresults <- bracket (mkResultTEither . tryIOError $ L.getLuxiClient luxiSocket) (liftIO . L.closeClient) $ mkResultT . (waitForJobs okjobs) let failedjobs = map fst $ filter ((/=) JOB_STATUS_SUCCESS . snd) jobresults unless (null failedjobs) $ do logInfo . (++) "Failed jobs: " . show $ map fromJobId failedjobs mapM_ (failIncident memstate) failedjobs unless (null oldjobs) . liftIO $ clearJobs memstate logDebug "New round of maintenance started" cData <- loadClusterData let il = cdInstances cData nl = cdNodes cData gl = cdGroups cData cleanupIncidents memstate nl collectIncidents memstate nl nidxs <- handleIncidents memstate (gl, nl, il) (nidxs', jobs) <- harepTasks (nl, il) nidxs unless (null jobs) . liftIO $ appendJobs memstate jobs logDebug $ "Nodes unaffected by harep " ++ show (Set.toList nidxs') ++ ", jobs submitted " ++ show (map fromJobId jobs) (bal, thresh) <- withErrorT show $ runNewWConfdClient maintenanceBalancing when (bal && not (Set.null nidxs')) $ do logDebug $ "Will balance unaffected nodes, threshold " ++ show thresh jobs' <- balanceTask memstate (nl, il) nidxs thresh logDebug $ "Balancing jobs submitted: " ++ show (map fromJobId jobs') unless (null jobs') . liftIO $ appendJobs memstate jobs' -- | Expose a part of the memory state exposeState :: J.JSON a => (MemoryState -> a) -> IORef MemoryState -> Snap () exposeState selector ref = do state <- liftIO $ readIORef ref plainJSON $ selector state -- | The information to serve via HTTP httpInterface :: IORef MemoryState -> Snap () httpInterface memstate = ifTop (method GET $ plainJSON [1 :: Int]) <|> dir "1" (ifTop (plainJSON J.JSNull) <|> route [ ("jobs", exposeState msJobs memstate) , ("evacuated", exposeState msEvacuated memstate) , ("status", exposeState msIncidents memstate) ]) <|> error404 -- | Check function for luxid. checkMain :: CheckFn CheckResult checkMain = handleMasterVerificationOptions -- | Prepare function for luxid. prepMain :: PrepFn CheckResult PrepResult prepMain opts _ = httpConfFromOpts GanetiMaintd opts -- | Main function. main :: MainFn CheckResult PrepResult main _ _ httpConf = do memstate <- newIORef emptyMemoryState void . forkIO . forever $ do res <- runResultT $ maintenance memstate (if isBad res then logInfo else logDebug) $ "Maintenance round result is " ++ show res when (isBad res) $ do logDebug "Backing off after a round with internal errors" threadDelaySeconds C.maintdDefaultRoundDelay httpServe httpConf $ httpInterface memstate
onponomarev/ganeti
src/Ganeti/MaintD/Server.hs
bsd-2-clause
8,385
0
17
1,671
1,899
1,003
896
143
2
{- | The public face of Template Haskell For other documentation, refer to: <http://www.haskell.org/haskellwiki/Template_Haskell> -} module Language.Eta.Meta( -- * The monad and its operations Q, runQ, -- ** Administration: errors, locations and IO reportError, -- :: String -> Q () reportWarning, -- :: String -> Q () report, -- :: Bool -> String -> Q () recover, -- :: Q a -> Q a -> Q a location, -- :: Q Loc Loc(..), runIO, -- :: IO a -> Q a -- ** Querying the compiler -- *** Reify reify, -- :: Name -> Q Info reifyModule, thisModule, Info(..), ModuleInfo(..), InstanceDec, ParentName, Arity, Unlifted, -- *** Language extension lookup Extension(..), extsEnabled, isExtEnabled, -- *** Name lookup lookupTypeName, -- :: String -> Q (Maybe Name) lookupValueName, -- :: String -> Q (Maybe Name) -- *** Fixity lookup reifyFixity, -- *** Instance lookup reifyInstances, isInstance, -- *** Roles lookup reifyRoles, -- *** Annotation lookup reifyAnnotations, AnnLookup(..), -- *** Constructor strictness lookup reifyConStrictness, -- * Typed expressions TExp, unType, -- * Names Name, NameSpace, -- Abstract -- ** Constructing names mkName, -- :: String -> Name newName, -- :: String -> Q Name -- ** Deconstructing names nameBase, -- :: Name -> String nameModule, -- :: Name -> Maybe String namePackage, -- :: Name -> Maybe String nameSpace, -- :: Name -> Maybe NameSpace -- ** Built-in names tupleTypeName, tupleDataName, -- Int -> Name unboxedTupleTypeName, unboxedTupleDataName, -- :: Int -> Name -- * The algebraic data types -- | The lowercase versions (/syntax operators/) of these constructors are -- preferred to these constructors, since they compose better with -- quotations (@[| |]@) and splices (@$( ... )@) -- ** Declarations Dec(..), Con(..), Clause(..), SourceUnpackedness(..), SourceStrictness(..), DecidedStrictness(..), Bang(..), Strict, Foreign(..), Callconv(..), Safety(..), Pragma(..), Inline(..), RuleMatch(..), Phases(..), RuleBndr(..), AnnTarget(..), FunDep(..), FamFlavour(..), TySynEqn(..), TypeFamilyHead(..), Fixity(..), FixityDirection(..), defaultFixity, maxPrecedence, -- ** Expressions Exp(..), Match(..), Body(..), Guard(..), Stmt(..), Range(..), Lit(..), -- ** Patterns Pat(..), FieldExp, FieldPat, -- ** Types Type(..), TyVarBndr(..), TyLit(..), Kind, Cxt, Pred, Syntax1.Role(..), FamilyResultSig(..), Syntax1.InjectivityAnn(..), -- * Library functions -- ** Abbreviations InfoQ, ExpQ, DecQ, DecsQ, ConQ, TypeQ, TyLitQ, CxtQ, PredQ, MatchQ, ClauseQ, BodyQ, GuardQ, StmtQ, RangeQ, SourceStrictnessQ, SourceUnpackednessQ, BangTypeQ, VarBangTypeQ, StrictTypeQ, VarStrictTypeQ, PatQ, FieldPatQ, RuleBndrQ, TySynEqnQ, -- ** Constructors lifted to 'Q' -- *** Literals intPrimL, wordPrimL, floatPrimL, doublePrimL, integerL, rationalL, charL, stringL, stringPrimL, charPrimL, -- *** Patterns litP, varP, tupP, conP, uInfixP, parensP, infixP, tildeP, bangP, asP, wildP, recP, listP, sigP, viewP, fieldPat, -- *** Pattern Guards normalB, guardedB, normalG, normalGE, patG, patGE, match, clause, -- *** Expressions dyn, varE, conE, litE, appE, uInfixE, parensE, staticE, infixE, infixApp, sectionL, sectionR, lamE, lam1E, lamCaseE, tupE, condE, multiIfE, letE, caseE, appsE, listE, sigE, recConE, recUpdE, stringE, fieldExp, -- **** Ranges fromE, fromThenE, fromToE, fromThenToE, -- ***** Ranges with more indirection arithSeqE, fromR, fromThenR, fromToR, fromThenToR, -- **** Statements doE, compE, bindS, letS, noBindS, parS, -- *** Types forallT, varT, conT, appT, arrowT, infixT, uInfixT, parensT, equalityT, listT, tupleT, sigT, litT, promotedT, promotedTupleT, promotedNilT, promotedConsT, -- **** Type literals numTyLit, strTyLit, -- **** Strictness noSourceUnpackedness, sourceNoUnpack, sourceUnpack, noSourceStrictness, sourceLazy, sourceStrict, isStrict, notStrict, unpacked, bang, bangType, varBangType, strictType, varStrictType, -- **** Class Contexts cxt, classP, equalP, -- **** Constructors normalC, recC, infixC, forallC, gadtC, recGadtC, -- *** Kinds varK, conK, tupleK, arrowK, listK, appK, starK, constraintK, -- *** Roles nominalR, representationalR, phantomR, inferR, -- *** Top Level Declarations -- **** Data valD, funD, tySynD, dataD, newtypeD, -- **** Class classD, instanceD, instanceWithOverlapD, Overlap(..), sigD, standaloneDerivD, defaultSigD, -- **** Role annotations roleAnnotD, -- **** Type Family / Data Family dataFamilyD, openTypeFamilyD, closedTypeFamilyD, dataInstD, familyNoKindD, familyKindD, closedTypeFamilyNoKindD, closedTypeFamilyKindD, newtypeInstD, tySynInstD, typeFam, dataFam, tySynEqn, injectivityAnn, noSig, kindSig, tyVarSig, -- **** Foreign Function Interface (FFI) cCall, stdCall, cApi, prim, javaScript, unsafe, safe, forImpD, -- **** Pragmas ruleVar, typedRuleVar, pragInlD, pragSpecD, pragSpecInlD, pragSpecInstD, pragRuleD, pragAnnD, pragLineD, -- * Pretty-printer Ppr(..), pprint, pprExp, pprLit, pprPat, pprParendType ) where import Eta.Location import Language.Eta.Meta.Syntax as Syntax1 import Language.Eta.Meta.Lib import Language.Eta.Meta.Ppr
rahulmutt/ghcvm
libraries/eta-meta/Language/Eta/Meta.hs
bsd-3-clause
6,072
0
5
1,687
1,169
817
352
98
0
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcInstDecls: Typechecking instance declarations -} {-# LANGUAGE CPP #-} module Eta.TypeCheck.TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where import Eta.HsSyn.HsSyn import Eta.TypeCheck.TcBinds import Eta.TypeCheck.TcTyClsDecls import Eta.TypeCheck.TcClassDcl( tcClassDecl2, HsSigFun, lookupHsSig, mkHsSigFun, findMethodBind, instantiateMethod, tcInstanceMethodBody ) import Eta.TypeCheck.TcPat ( addInlinePrags ) import Eta.TypeCheck.TcRnMonad import Eta.TypeCheck.TcValidity import Eta.TypeCheck.TcMType import Eta.TypeCheck.TcType import Eta.Iface.BuildTyCl import Eta.TypeCheck.Inst import Eta.Types.InstEnv import Eta.TypeCheck.FamInst import Eta.Types.FamInstEnv import Eta.TypeCheck.TcDeriv import Eta.TypeCheck.TcEnv import Eta.TypeCheck.TcHsType import Eta.TypeCheck.TcUnify import Eta.Types.Coercion ( pprCoAxiom ) import Eta.Core.MkCore ( nO_METHOD_BINDING_ERROR_ID ) import Eta.Types.Type import Eta.TypeCheck.TcEvidence import Eta.Types.TyCon import Eta.Types.CoAxiom import Eta.BasicTypes.DataCon import Eta.Types.Class import Eta.BasicTypes.Var import qualified Eta.BasicTypes.Var as Var import Eta.BasicTypes.VarEnv import Eta.BasicTypes.VarSet import Eta.Prelude.PrelNames ( typeableClassName, genericClassNames ) import Eta.Utils.Bag import Eta.BasicTypes.BasicTypes import Eta.Main.DynFlags import Eta.Main.ErrUtils import Eta.Utils.FastString import Eta.Main.HscTypes ( isHsBootOrSig ) import Eta.BasicTypes.Id import Eta.BasicTypes.MkId import Eta.BasicTypes.Name import Eta.BasicTypes.NameSet import Eta.Utils.Outputable import qualified Eta.Utils.Outputable as Outputable import Eta.BasicTypes.SrcLoc import Eta.Utils.Util import Eta.Utils.BooleanFormula ( isUnsatisfied, pprBooleanFormulaNice ) import qualified Eta.LanguageExtensions as LangExt import Control.Monad import Eta.Utils.Maybes ( isNothing, isJust, whenIsJust ) import Data.List ( mapAccumL, partition ) #include "HsVersions.h" {- Typechecking instance declarations is done in two passes. The first pass, made by @tcInstDecls1@, collects information to be used in the second pass. This pre-processed info includes the as-yet-unprocessed bindings inside the instance declaration. These are type-checked in the second pass, when the class-instance envs and GVE contain all the info from all the instance and value decls. Indeed that's the reason we need two passes over the instance decls. Note [How instance declarations are translated] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is how we translation instance declarations into Core Running example: class C a where op1, op2 :: Ix b => a -> b -> b op2 = <dm-rhs> instance C a => C [a] {-# INLINE [2] op1 #-} op1 = <rhs> ===> -- Method selectors op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b op1 = ... op2 = ... -- Default methods get the 'self' dictionary as argument -- so they can call other methods at the same type -- Default methods get the same type as their method selector $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs> -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs> -- Note [Tricky type variable scoping] -- A top-level definition for each instance method -- Here op1_i, op2_i are the "instance method Ids" -- The INLINE pragma comes from the user pragma {-# INLINE [2] op1_i #-} -- From the instance decl bindings op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b op1_i = /\a. \(d:C a). let this :: C [a] this = df_i a d -- Note [Subtle interaction of recursion and overlap] local_op1 :: forall b. Ix b => [a] -> b -> b local_op1 = <rhs> -- Source code; run the type checker on this -- NB: Type variable 'a' (but not 'b') is in scope in <rhs> -- Note [Tricky type variable scoping] in local_op1 a d op2_i = /\a \d:C a. $dmop2 [a] (df_i a d) -- The dictionary function itself {-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions df_i :: forall a. C a -> C [a] df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d) -- But see Note [Default methods in instances] -- We can't apply the type checker to the default-method call -- Use a RULE to short-circuit applications of the class ops {-# RULE "op1@C[a]" forall a, d:C a. op1 [a] (df_i d) = op1_i a d #-} Note [Instances and loop breakers] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Note that df_i may be mutually recursive with both op1_i and op2_i. It's crucial that df_i is not chosen as the loop breaker, even though op1_i has a (user-specified) INLINE pragma. * Instead the idea is to inline df_i into op1_i, which may then select methods from the MkC record, and thereby break the recursion with df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at the same type, it won't mention df_i, so there won't be recursion in the first place.) * If op1_i is marked INLINE by the user there's a danger that we won't inline df_i in it, and that in turn means that (since it'll be a loop-breaker because df_i isn't), op1_i will ironically never be inlined. But this is OK: the recursion breaking happens by way of a RULE (the magic ClassOp rule above), and RULES work inside InlineRule unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils Note [ClassOp/DFun selection] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ One thing we see a lot is stuff like op2 (df d1 d2) where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both* 'op2' and 'df' to get case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of MkD _ op2 _ _ _ -> op2 And that will reduce to ($cop2 d1 d2) which is what we wanted. But it's tricky to make this work in practice, because it requires us to inline both 'op2' and 'df'. But neither is keen to inline without having seen the other's result; and it's very easy to get code bloat (from the big intermediate) if you inline a bit too much. Instead we use a cunning trick. * We arrange that 'df' and 'op2' NEVER inline. * We arrange that 'df' is ALWAYS defined in the sylised form df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ... * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..]) that lists its methods. * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return a suitable constructor application -- inlining df "on the fly" as it were. * ClassOp rules: We give the ClassOp 'op2' a BuiltinRule that extracts the right piece iff its argument satisfies exprIsConApp_maybe. This is done in MkId mkDictSelId * We make 'df' CONLIKE, so that shared uses still match; eg let d = df d1 d2 in ...(op2 d)...(op1 d)... Note [Single-method classes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the class has just one method (or, more accurately, just one element of {superclasses + methods}), then we use a different strategy. class C a where op :: a -> a instance C a => C [a] where op = <blah> We translate the class decl into a newtype, which just gives a top-level axiom. The "constructor" MkC expands to a cast, as does the class-op selector. axiom Co:C a :: C a ~ (a->a) op :: forall a. C a -> (a -> a) op a d = d |> (Co:C a) MkC :: forall a. (a->a) -> C a MkC = /\a.\op. op |> (sym Co:C a) The clever RULE stuff doesn't work now, because ($df a d) isn't a constructor application, so exprIsConApp_maybe won't return Just <blah>. Instead, we simply rely on the fact that casts are cheap: $df :: forall a. C a => C [a] {-# INLINE df #-} -- NB: INLINE this $df = /\a. \d. MkC [a] ($cop_list a d) = $cop_list |> forall a. C a -> (sym (Co:C [a])) $cop_list :: forall a. C a => [a] -> [a] $cop_list = <blah> So if we see (op ($df a d)) we'll inline 'op' and '$df', since both are simply casts, and good things happen. Why do we use this different strategy? Because otherwise we end up with non-inlined dictionaries that look like $df = $cop |> blah which adds an extra indirection to every use, which seems stupid. See Trac #4138 for an example (although the regression reported there wasn't due to the indirection). There is an awkward wrinkle though: we want to be very careful when we have instance C a => C [a] where {-# INLINE op #-} op = ... then we'll get an INLINE pragma on $cop_list but it's important that $cop_list only inlines when it's applied to *two* arguments (the dictionary and the list argument). So we must not eta-expand $df above. We ensure that this doesn't happen by putting an INLINE pragma on the dfun itself; after all, it ends up being just a cast. There is one more dark corner to the INLINE story, even more deeply buried. Consider this (Trac #3772): class DeepSeq a => C a where gen :: Int -> a instance C a => C [a] where gen n = ... class DeepSeq a where deepSeq :: a -> b -> b instance DeepSeq a => DeepSeq [a] where {-# INLINE deepSeq #-} deepSeq xs b = foldr deepSeq b xs That gives rise to these defns: $cdeepSeq :: DeepSeq a -> [a] -> b -> b -- User INLINE( 3 args )! $cdeepSeq a (d:DS a) b (x:[a]) (y:b) = ... $fDeepSeq[] :: DeepSeq a -> DeepSeq [a] -- DFun (with auto INLINE pragma) $fDeepSeq[] a d = $cdeepSeq a d |> blah $cp1 a d :: C a => DeepSep [a] -- We don't want to eta-expand this, lest -- $cdeepSeq gets inlined in it! $cp1 a d = $fDeepSep[] a (scsel a d) $fC[] :: C a => C [a] -- Ordinary DFun $fC[] a d = MkC ($cp1 a d) ($cgen a d) Here $cp1 is the code that generates the superclass for C [a]. The issue is this: we must not eta-expand $cp1 either, or else $fDeepSeq[] and then $cdeepSeq will inline there, which is definitely wrong. Like on the dfun, we solve this by adding an INLINE pragma to $cp1. Note [Subtle interaction of recursion and overlap] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this class C a where { op1,op2 :: a -> a } instance C a => C [a] where op1 x = op2 x ++ op2 x op2 x = ... instance C [Int] where ... When type-checking the C [a] instance, we need a C [a] dictionary (for the call of op2). If we look up in the instance environment, we find an overlap. And in *general* the right thing is to complain (see Note [Overlapping instances] in InstEnv). But in *this* case it's wrong to complain, because we just want to delegate to the op2 of this same instance. Why is this justified? Because we generate a (C [a]) constraint in a context in which 'a' cannot be instantiated to anything that matches other overlapping instances, or else we would not be executing this version of op1 in the first place. It might even be a bit disguised: nullFail :: C [a] => [a] -> [a] nullFail x = op2 x ++ op2 x instance C a => C [a] where op1 x = nullFail x Precisely this is used in package 'regex-base', module Context.hs. See the overlapping instances for RegexContext, and the fact that they call 'nullFail' just like the example above. The DoCon package also does the same thing; it shows up in module Fraction.hs. Conclusion: when typechecking the methods in a C [a] instance, we want to treat the 'a' as an *existential* type variable, in the sense described by Note [Binding when looking up instances]. That is why isOverlappableTyVar responds True to an InstSkol, which is the kind of skolem we use in tcInstDecl2. Note [Tricky type variable scoping] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In our example class C a where op1, op2 :: Ix b => a -> b -> b op2 = <dm-rhs> instance C a => C [a] {-# INLINE [2] op1 #-} op1 = <rhs> note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is in scope in <rhs>. In particular, we must make sure that 'b' is in scope when typechecking <dm-rhs>. This is achieved by subFunTys, which brings appropriate tyvars into scope. This happens for both <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have complained if 'b' is mentioned in <rhs>. ************************************************************************ * * \subsection{Extracting instance decls} * * ************************************************************************ Gather up the instance declarations from their various sources -} tcInstDecls1 -- Deal with both source-code and imported instance decls :: [LTyClDecl Name] -- For deriving stuff -> [LInstDecl Name] -- Source code instance decls -> [LDerivDecl Name] -- Source code stand-alone deriving decls -> TcM (TcGblEnv, -- The full inst env [InstInfo Name], -- Source-code instance decls to process; -- contains all dfuns for this module HsValBinds Name) -- Supporting bindings for derived instances tcInstDecls1 tycl_decls inst_decls deriv_decls = checkNoErrs $ do { -- Stop if addInstInfos etc discovers any errors -- (they recover, so that we get more than one error each -- round) -- Do class and family instance declarations ; stuff <- mapAndRecoverM tcLocalInstDecl inst_decls ; let (local_infos_s, fam_insts_s) = unzip stuff fam_insts = concat fam_insts_s local_infos' = concat local_infos_s -- Handwritten instances of the poly-kinded Typeable class are -- forbidden, so we handle those separately (typeable_instances, local_infos) = partition bad_typeable_instance local_infos' ; addClsInsts local_infos $ addFamInsts fam_insts $ do { -- Compute instances from "deriving" clauses; -- This stuff computes a context for the derived instance -- decl, so it needs to know about all the instances possible -- NB: class instance declarations can contain derivings as -- part of associated data type declarations failIfErrsM -- If the addInsts stuff gave any errors, don't -- try the deriving stuff, because that may give -- more errors still ; traceTc "tcDeriving" Outputable.empty ; th_stage <- getStage -- See Note [Deriving inside TH brackets ] ; (gbl_env, deriv_inst_info, deriv_binds) <- if isBrackStage th_stage then do { gbl_env <- getGblEnv ; return (gbl_env, emptyBag, emptyValBindsOut) } else tcDeriving tycl_decls inst_decls deriv_decls -- Fail if there are any handwritten instance of poly-kinded Typeable ; mapM_ typeable_err typeable_instances -- Check that if the module is compiled with -XSafe, there are no -- hand written instances of old Typeable as then unsafe casts could be -- performed. Derived instances are OK. ; dflags <- getDynFlags ; when (safeLanguageOn dflags) $ forM_ local_infos $ \x -> case x of _ | genInstCheck x -> addErrAt (getSrcSpan $ iSpec x) (genInstErr x) _ -> return () -- As above but for Safe Inference mode. ; when (safeInferOn dflags) $ forM_ local_infos $ \x -> case x of _ | genInstCheck x -> recordUnsafeInfer _ | overlapCheck x -> recordUnsafeInfer _ -> return () ; return ( gbl_env , bagToList deriv_inst_info ++ local_infos , deriv_binds) }} where -- Separate the Typeable instances from the rest bad_typeable_instance i = typeableClassName == is_cls_nm (iSpec i) overlapCheck ty = case overlapMode (is_flag $ iSpec ty) of NoOverlap _ -> False _ -> True genInstCheck ty = is_cls_nm (iSpec ty) `elem` genericClassNames genInstErr i = hang (ptext (sLit $ "Generic instances can only be " ++ "derived in Safe Haskell.") $+$ ptext (sLit "Replace the following instance:")) 2 (pprInstanceHdr (iSpec i)) -- Report an error or a warning for a `Typeable` instances. -- If we are workikng on an .hs-boot file, we just report a warning, -- and ignore the instance. We do this, to give users a chance to fix -- their code. typeable_err i = setSrcSpan (getSrcSpan (iSpec i)) $ do env <- getGblEnv if isHsBootOrSig (tcg_src env) then do warn <- woptM Opt_WarnDerivingTypeable when warn $ addWarnTc (Reason Opt_WarnDerivingTypeable) $ vcat [ ptext (sLit "`Typeable` instances in .hs-boot files are ignored.") , ptext (sLit "This warning will become an error in future versions of the compiler.") ] else addErrTc $ ptext (sLit "Class `Typeable` does not support user-specified instances.") addClsInsts :: [InstInfo Name] -> TcM a -> TcM a addClsInsts infos thing_inside = tcExtendLocalInstEnv (map iSpec infos) thing_inside addFamInsts :: [FamInst] -> TcM a -> TcM a -- Extend (a) the family instance envt -- (b) the type envt with stuff from data type decls addFamInsts fam_insts thing_inside = tcExtendLocalFamInstEnv fam_insts $ tcExtendGlobalEnv things $ do { traceTc "addFamInsts" (pprFamInsts fam_insts) ; tcg_env <- tcAddImplicits things ; setGblEnv tcg_env thing_inside } where axioms = map (toBranchedAxiom . famInstAxiom) fam_insts tycons = famInstsRepTyCons fam_insts things = map ATyCon tycons ++ map ACoAxiom axioms {- Note [Deriving inside TH brackets] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Given a declaration bracket [d| data T = A | B deriving( Show ) |] there is really no point in generating the derived code for deriving( Show) and then type-checking it. This will happen at the call site anyway, and the type check should never fail! Moreover (Trac #6005) the scoping of the generated code inside the bracket does not seem to work out. The easy solution is simply not to generate the derived instances at all. (A less brutal solution would be to generate them with no bindings.) This will become moot when we shift to the new TH plan, so the brutal solution will do. -} tcLocalInstDecl :: LInstDecl Name -> TcM ([InstInfo Name], [FamInst]) -- A source-file instance declaration -- Type-check all the stuff before the "where" -- -- We check for respectable instance type, and context tcLocalInstDecl (L loc (TyFamInstD { tfid_inst = decl })) = do { fam_inst <- tcTyFamInstDecl Nothing (L loc decl) ; return ([], [fam_inst]) } tcLocalInstDecl (L loc (DataFamInstD { dfid_inst = decl })) = do { fam_inst <- tcDataFamInstDecl Nothing (L loc decl) ; return ([], [fam_inst]) } tcLocalInstDecl (L loc (ClsInstD { cid_inst = decl })) = do { (insts, fam_insts) <- tcClsInstDecl (L loc decl) ; return (insts, fam_insts) } tcClsInstDecl :: LClsInstDecl Name -> TcM ([InstInfo Name], [FamInst]) tcClsInstDecl (L loc (ClsInstDecl { cid_poly_ty = poly_ty, cid_binds = binds , cid_sigs = uprags, cid_tyfam_insts = ats , cid_overlap_mode = overlap_mode , cid_datafam_insts = adts })) = setSrcSpan loc $ addErrCtxt (instDeclCtxt1 poly_ty) $ do { is_boot <- tcIsHsBootOrSig ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags)) badBootDeclErr ; (tyvars, theta, clas, inst_tys) <- tcHsInstHead InstDeclCtxt poly_ty ; let mini_env = mkVarEnv (classTyVars clas `zip` inst_tys) mini_subst = mkTvSubst (mkInScopeSet (mkVarSet tyvars)) mini_env mb_info = Just (clas, mini_env) -- Next, process any associated types. ; traceTc "tcLocalInstDecl" (ppr poly_ty) ; tyfam_insts0 <- tcExtendTyVarEnv tyvars $ mapAndRecoverM (tcTyFamInstDecl mb_info) ats ; datafam_insts <- tcExtendTyVarEnv tyvars $ mapAndRecoverM (tcDataFamInstDecl mb_info) adts -- Check for missing associated types and build them -- from their defaults (if available) ; let defined_ats = mkNameSet (map (tyFamInstDeclName . unLoc) ats) `unionNameSet` mkNameSet (map (unLoc . dfid_tycon . unLoc) adts) ; tyfam_insts1 <- mapM (tcATDefault mini_subst defined_ats) (classATItems clas) -- Finally, construct the Core representation of the instance. -- (This no longer includes the associated types.) ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty) -- Dfun location is that of instance *header* ; ispec <- newClsInst (fmap unLoc overlap_mode) dfun_name tyvars theta clas inst_tys ; let inst_info = InstInfo { iSpec = ispec , iBinds = InstBindings { ib_binds = binds , ib_tyvars = map Var.varName tyvars -- Scope over bindings , ib_pragmas = uprags , ib_extensions = [] , ib_derived = False } } ; return ( [inst_info], tyfam_insts0 ++ concat tyfam_insts1 ++ datafam_insts) } tcATDefault :: TvSubst -> NameSet -> ClassATItem -> TcM [FamInst] -- ^ Construct default instances for any associated types that -- aren't given a user definition -- Returns [] or singleton tcATDefault inst_subst defined_ats (ATI fam_tc defs) -- User supplied instances ==> everything is OK | tyConName fam_tc `elemNameSet` defined_ats = return [] -- No user instance, have defaults ==> instatiate them -- Example: class C a where { type F a b :: *; type F a b = () } -- instance C [x] -- Then we want to generate the decl: type F [x] b = () | Just (rhs_ty, _loc) <- defs = do { let (subst', pat_tys') = mapAccumL subst_tv inst_subst (tyConTyVars fam_tc) rhs' = substTy subst' rhs_ty tv_set' = tyVarsOfTypes pat_tys' tvs' = varSetElemsKvsFirst tv_set' ; rep_tc_name <- newFamInstTyConName (noLoc (tyConName fam_tc)) pat_tys' ; let axiom = mkSingleCoAxiom rep_tc_name tvs' fam_tc pat_tys' rhs' ; traceTc "mk_deflt_at_instance" (vcat [ ppr fam_tc, ppr rhs_ty , pprCoAxiom axiom ]) ; fam_inst <- ASSERT( tyVarsOfType rhs' `subVarSet` tv_set' ) newFamInst SynFamilyInst axiom ; return [fam_inst] } -- No defaults ==> generate a warning | otherwise -- defs = Nothing = do { warnMissingMethodOrAT "associated type" (tyConName fam_tc) ; return [] } where subst_tv subst tc_tv | Just ty <- lookupVarEnv (getTvSubstEnv subst) tc_tv = (subst, ty) | otherwise = (extendTvSubst subst tc_tv ty', ty') where ty' = mkTyVarTy (updateTyVarKind (substTy subst) tc_tv) {- ************************************************************************ * * Type checking family instances * * ************************************************************************ Family instances are somewhat of a hybrid. They are processed together with class instance heads, but can contain data constructors and hence they share a lot of kinding and type checking code with ordinary algebraic data types (and GADTs). -} tcFamInstDeclCombined :: Maybe (Class, VarEnv Type) -- the class & mini_env if applicable -> Located Name -> TcM TyCon tcFamInstDeclCombined mb_clsinfo fam_tc_lname = do { -- Type family instances require -XTypeFamilies -- and can't (currently) be in an hs-boot file ; traceTc "tcFamInstDecl" (ppr fam_tc_lname) ; type_families <- xoptM LangExt.TypeFamilies ; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file? ; checkTc type_families $ badFamInstDecl fam_tc_lname ; checkTc (not is_boot) $ badBootFamInstDeclErr -- Look up the family TyCon and check for validity including -- check that toplevel type instances are not for associated types. ; fam_tc <- tcLookupLocatedTyCon fam_tc_lname ; when (isNothing mb_clsinfo && -- Not in a class decl isTyConAssoc fam_tc) -- but an associated type (addErr $ assocInClassErr fam_tc_lname) ; return fam_tc } tcTyFamInstDecl :: Maybe (Class, VarEnv Type) -- the class & mini_env if applicable -> LTyFamInstDecl Name -> TcM FamInst -- "type instance" tcTyFamInstDecl mb_clsinfo (L loc decl@(TyFamInstDecl { tfid_eqn = eqn })) = setSrcSpan loc $ tcAddTyFamInstCtxt decl $ do { let fam_lname = tfe_tycon (unLoc eqn) ; fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_lname -- (0) Check it's an open type family ; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc) ; checkTc (isTypeFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc) ; checkTc (isOpenTypeFamilyTyCon fam_tc) (notOpenFamily fam_tc) -- (1) do the work of verifying the synonym group ; co_ax_branch <- tcTyFamInstEqn (famTyConShape fam_tc) eqn -- (2) check for validity ; checkValidTyFamInst mb_clsinfo fam_tc co_ax_branch -- (3) construct coercion axiom ; rep_tc_name <- newFamInstAxiomName loc (unLoc fam_lname) [co_ax_branch] ; let axiom = mkUnbranchedCoAxiom rep_tc_name fam_tc co_ax_branch ; newFamInst SynFamilyInst axiom } tcDataFamInstDecl :: Maybe (Class, VarEnv Type) -> LDataFamInstDecl Name -> TcM FamInst -- "newtype instance" and "data instance" tcDataFamInstDecl mb_clsinfo (L loc decl@(DataFamInstDecl { dfid_pats = pats , dfid_tycon = fam_tc_name , dfid_defn = defn@HsDataDefn { dd_ND = new_or_data, dd_metaData = (cType, _) , dd_ctxt = ctxt, dd_cons = cons } })) = setSrcSpan loc $ tcAddDataFamInstCtxt decl $ do { fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_tc_name -- Check that the family declaration is for the right kind ; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc) ; checkTc (isAlgTyCon fam_tc) (wrongKindOfFamily fam_tc) -- Kind check type patterns ; tcFamTyPats (famTyConShape fam_tc) pats (kcDataDefn defn) $ \tvs' pats' res_kind -> do { -- Check that left-hand side contains no type family applications -- (vanilla synonyms are fine, though, and we checked for -- foralls earlier) checkValidFamPats fam_tc tvs' pats' -- Check that type patterns match class instance head, if any ; checkConsistentFamInst mb_clsinfo fam_tc tvs' pats' -- Result kind must be '*' (otherwise, we have too few patterns) ; checkTc (isLiftedTypeKind res_kind) $ tooFewParmsErr (tyConArity fam_tc) ; stupid_theta <- tcHsContext ctxt ; gadt_syntax <- dataDeclChecks (tyConName fam_tc) new_or_data stupid_theta cons -- Construct representation tycon ; rep_tc_name <- newFamInstTyConName fam_tc_name pats' ; axiom_name <- newImplicitBinder rep_tc_name mkInstTyCoOcc ; let orig_res_ty = mkTyConApp fam_tc pats' ; (rep_tc, fam_inst) <- fixM $ \ ~(rec_rep_tc, _) -> do { data_cons <- tcConDecls new_or_data rec_rep_tc (tvs', orig_res_ty) cons ; tc_rhs <- case new_or_data of DataType -> return (mkDataTyConRhs data_cons) NewType -> ASSERT( not (null data_cons) ) mkNewTyConRhs rep_tc_name rec_rep_tc (head data_cons) -- freshen tyvars ; let (eta_tvs, eta_pats) = eta_reduce tvs' pats' axiom = mkSingleCoAxiom axiom_name eta_tvs fam_tc eta_pats (mkTyConApp rep_tc (mkTyVarTys eta_tvs)) parent = FamInstTyCon axiom fam_tc pats' roles = map (const Nominal) tvs' rep_tc = buildAlgTyCon rep_tc_name tvs' roles (fmap unLoc cType) stupid_theta tc_rhs Recursive False -- No promotable to the kind level gadt_syntax parent -- We always assume that indexed types are recursive. Why? -- (1) Due to their open nature, we can never be sure that a -- further instance might not introduce a new recursive -- dependency. (2) They are always valid loop breakers as -- they involve a coercion. ; fam_inst <- newFamInst (DataFamilyInst rep_tc) axiom ; return (rep_tc, fam_inst) } -- Remember to check validity; no recursion to worry about here ; checkValidTyCon rep_tc ; return fam_inst } } where -- See Note [Eta reduction for data family axioms] -- [a,b,c,d].T [a] c Int c d ==> [a,b,c]. T [a] c Int c eta_reduce tvs pats = go (reverse tvs) (reverse pats) go (tv:tvs) (pat:pats) | Just tv' <- getTyVar_maybe pat , tv == tv' , not (tv `elemVarSet` tyVarsOfTypes pats) = go tvs pats go tvs pats = (reverse tvs, reverse pats) {- Note [Eta reduction for data family axioms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this data family T a b :: * newtype instance T Int a = MkT (IO a) deriving( Monad ) We'd like this to work. From the 'newtype instance' you might think we'd get: newtype TInt a = MkT (IO a) axiom ax1 a :: T Int a ~ TInt a -- The type-instance part axiom ax2 a :: TInt a ~ IO a -- The newtype part But now what can we do? We have this problem Given: d :: Monad IO Wanted: d' :: Monad (T Int) = d |> ???? What coercion can we use for the ??? Solution: eta-reduce both axioms, thus: axiom ax1 :: T Int ~ TInt axiom ax2 :: TInt ~ IO Now d' = d |> Monad (sym (ax2 ; ax1)) This eta reduction happens both for data instances and newtype instances. See Note [Newtype eta] in TyCon. ************************************************************************ * * Type-checking instance declarations, pass 2 * * ************************************************************************ -} tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name] -> TcM (LHsBinds Id) -- (a) From each class declaration, -- generate any default-method bindings -- (b) From each instance decl -- generate the dfun binding tcInstDecls2 tycl_decls inst_decls = do { -- (a) Default methods from class decls let class_decls = filter (isClassDecl . unLoc) tycl_decls ; dm_binds_s <- mapM tcClassDecl2 class_decls ; let dm_binds = unionManyBags dm_binds_s -- (b) instance declarations ; let dm_ids = collectHsBindsBinders dm_binds -- Add the default method Ids (again) -- See Note [Default methods and instances] ; inst_binds_s <- tcExtendLetEnv TopLevel TopLevel dm_ids $ mapM tcInstDecl2 inst_decls -- Done ; return (dm_binds `unionBags` unionManyBags inst_binds_s) } {- See Note [Default methods and instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The default method Ids are already in the type environment (see Note [Default method Ids and Template Haskell] in TcTyClsDcls), BUT they don't have their InlinePragmas yet. Usually that would not matter, because the simplifier propagates information from binding site to use. But, unusually, when compiling instance decls we *copy* the INLINE pragma from the default method to the method for that particular operation (see Note [INLINE and default methods] below). So right here in tcInstDecls2 we must re-extend the type envt with the default method Ids replete with their INLINE pragmas. Urk. -} tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id) -- Returns a binding for the dfun tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds }) = recoverM (return emptyLHsBinds) $ setSrcSpan loc $ addErrCtxt (instDeclCtxt2 (idType dfun_id)) $ do { -- Instantiate the instance decl with skolem constants ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id) -- We instantiate the dfun_id with superSkolems. -- See Note [Subtle interaction of recursion and overlap] -- and Note [Binding when looking up instances] ; let (clas, inst_tys) = tcSplitDFunHead inst_head (class_tyvars, sc_theta, _, op_items) = classBigSig clas sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys) sc_theta ; dfun_ev_vars <- newEvVars dfun_theta ; sc_ev_vars <- tcSuperClasses dfun_id inst_tyvars dfun_ev_vars sc_theta' -- Deal with 'SPECIALISE instance' pragmas -- See Note [SPECIALISE instance pragmas] ; spec_inst_info@(spec_inst_prags,_) <- tcSpecInstPrags dfun_id ibinds -- Typecheck the methods ; (meth_ids, meth_binds) <- tcInstanceMethods dfun_id clas inst_tyvars dfun_ev_vars inst_tys spec_inst_info op_items ibinds -- Create the result bindings ; self_dict <- newDict clas inst_tys ; let class_tc = classTyCon clas [dict_constr] = tyConDataCons class_tc dict_bind = mkVarBind self_dict (L loc con_app_args) -- We don't produce a binding for the dict_constr; instead we -- rely on the simplifier to unfold this saturated application -- We do this rather than generate an HsCon directly, because -- it means that the special cases (e.g. dictionary with only one -- member) are dealt with by the common MkId.mkDataConWrapId -- code rather than needing to be repeated here. -- con_app_tys = MkD ty1 ty2 -- con_app_scs = MkD ty1 ty2 sc1 sc2 -- con_app_args = MkD ty1 ty2 sc1 sc2 op1 op2 con_app_tys = wrapId (mkWpTyApps inst_tys) (dataConWrapId dict_constr) con_app_scs = mkHsWrap (mkWpEvApps (map EvId sc_ev_vars)) con_app_tys con_app_args = foldl app_to_meth con_app_scs meth_ids app_to_meth :: HsExpr Id -> Id -> HsExpr Id app_to_meth fun meth_id = L loc fun `HsApp` L loc (wrapId arg_wrapper meth_id) inst_tv_tys = mkTyVarTys inst_tyvars arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps inst_tv_tys -- Do not inline the dfun; instead give it a magic DFunFunfolding dfun_spec_prags | isNewTyCon class_tc = SpecPrags [] -- Newtype dfuns just inline unconditionally, -- so don't attempt to specialise them | otherwise = SpecPrags spec_inst_prags export = ABE { abe_wrap = idHsWrapper, abe_poly = dfun_id , abe_mono = self_dict, abe_prags = dfun_spec_prags } -- NB: see Note [SPECIALISE instance pragmas] main_bind = AbsBinds { abs_tvs = inst_tyvars , abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = emptyTcEvBinds , abs_binds = unitBag dict_bind } ; return (unitBag (L loc main_bind) `unionBags` listToBag meth_binds) } where dfun_id = instanceDFunId ispec loc = getSrcSpan dfun_id ------------------------------ tcSuperClasses :: DFunId -> [TcTyVar] -> [EvVar] -> TcThetaType -> TcM [EvVar] -- See Note [Silent superclass arguments] tcSuperClasses dfun_id inst_tyvars dfun_ev_vars sc_theta | null inst_tyvars && null dfun_ev_vars = emitWanteds ScOrigin sc_theta | otherwise = do { -- Check that all superclasses can be deduced from -- the originally-specified dfun arguments ; _ <- checkConstraints InstSkol inst_tyvars orig_ev_vars $ emitWanteds ScOrigin sc_theta ; return (map (find dfun_ev_vars) sc_theta) } where n_silent = dfunNSilent dfun_id orig_ev_vars = drop n_silent dfun_ev_vars find [] pred = pprPanic "tcInstDecl2" (ppr dfun_id $$ ppr (idType dfun_id) $$ ppr pred) find (ev:evs) pred | pred `eqPred` evVarPred ev = ev | otherwise = find evs pred ---------------------- mkMethIds :: HsSigFun -> Class -> [TcTyVar] -> [EvVar] -> [TcType] -> Id -> TcM (TcId, TcSigInfo, HsWrapper) mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id = do { poly_meth_name <- newName (mkClassOpAuxOcc sel_occ) ; local_meth_name <- newName sel_occ -- Base the local_meth_name on the selector name, because -- type errors from tcInstanceMethodBody come from here ; let poly_meth_id = mkLocalId poly_meth_name poly_meth_ty local_meth_id = mkLocalId local_meth_name local_meth_ty ; case lookupHsSig sig_fn sel_name of Just lhs_ty -- There is a signature in the instance declaration -- See Note [Instance method signatures] -> setSrcSpan (getLoc lhs_ty) $ do { inst_sigs <- xoptM LangExt.InstanceSigs ; checkTc inst_sigs (misplacedInstSig sel_name lhs_ty) ; sig_ty <- tcHsSigType (FunSigCtxt sel_name) lhs_ty ; let poly_sig_ty = mkSigmaTy tyvars theta sig_ty ; tc_sig <- instTcTySig lhs_ty sig_ty Nothing [] local_meth_name ; hs_wrap <- addErrCtxtM (methSigCtxt sel_name poly_sig_ty poly_meth_ty) $ tcSubType (FunSigCtxt sel_name) poly_sig_ty poly_meth_ty ; return (poly_meth_id, tc_sig, hs_wrap) } Nothing -- No type signature -> do { tc_sig <- instTcTySigFromId local_meth_id ; return (poly_meth_id, tc_sig, idHsWrapper) } } -- Absent a type sig, there are no new scoped type variables here -- Only the ones from the instance decl itself, which are already -- in scope. Example: -- class C a where { op :: forall b. Eq b => ... } -- instance C [c] where { op = <rhs> } -- In <rhs>, 'c' is scope but 'b' is not! where sel_name = idName sel_id sel_occ = nameOccName sel_name local_meth_ty = instantiateMethod clas sel_id inst_tys poly_meth_ty = mkSigmaTy tyvars theta local_meth_ty theta = map idType dfun_ev_vars methSigCtxt :: Name -> TcType -> TcType -> TidyEnv -> TcM (TidyEnv, MsgDoc) methSigCtxt sel_name sig_ty meth_ty env0 = do { (env1, sig_ty) <- zonkTidyTcType env0 sig_ty ; (env2, meth_ty) <- zonkTidyTcType env1 meth_ty ; let msg = hang (ptext (sLit "When checking that instance signature for") <+> quotes (ppr sel_name)) 2 (vcat [ ptext (sLit "is more general than its signature in the class") , ptext (sLit "Instance sig:") <+> ppr sig_ty , ptext (sLit " Class sig:") <+> ppr meth_ty ]) ; return (env2, msg) } misplacedInstSig :: Name -> LHsType Name -> SDoc misplacedInstSig name hs_ty = vcat [ hang (ptext (sLit "Illegal type signature in instance declaration:")) 2 (hang (pprPrefixName name) 2 (dcolon <+> ppr hs_ty)) , ptext (sLit "(Use InstanceSigs to allow this)") ] ------------------------------ tcSpecInstPrags :: DFunId -> InstBindings Name -> TcM ([Located TcSpecPrag], PragFun) tcSpecInstPrags dfun_id (InstBindings { ib_binds = binds, ib_pragmas = uprags }) = do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $ filter isSpecInstLSig uprags -- The filter removes the pragmas for methods ; return (spec_inst_prags, mkPragFun uprags binds) } {- Note [Instance method signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With -XInstanceSigs we allow the user to supply a signature for the method in an instance declaration. Here is an artificial example: data Age = MkAge Int instance Ord Age where compare :: a -> a -> Bool compare = error "You can't compare Ages" We achieve this by building a TcSigInfo for the method, whether or not there is an instance method signature, and using that to typecheck the declaration (in tcInstanceMethodBody). That means, conveniently, that the type variables bound in the signature will scope over the body. What about the check that the instance method signature is more polymorphic than the instantiated class method type? We just do a tcSubType call in mkMethIds, and use the HsWrapper thus generated in the method AbsBind. It's very like the tcSubType impedence-matching call in mkExport. We have to pass the HsWrapper into tcInstanceMethodBody. Note [Silent superclass arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See Trac #3731, #4809, #5751, #5913, #6117, which all describe somewhat more complicated situations, but ones encountered in practice. THE PROBLEM The problem is that it is all too easy to create a class whose superclass is bottom when it should not be. Consider the following (extreme) situation: class C a => D a where ... instance D [a] => D [a] where ... (dfunD) instance C [a] => C [a] where ... (dfunC) Although this looks wrong (assume D [a] to prove D [a]), it is only a more extreme case of what happens with recursive dictionaries, and it can, just about, make sense because the methods do some work before recursing. To implement the dfunD we must generate code for the superclass C [a], which we had better not get by superclass selection from the supplied argument: dfunD :: forall a. D [a] -> D [a] dfunD = \d::D [a] -> MkD (scsel d) .. Otherwise if we later encounter a situation where we have a [Wanted] dw::D [a] we might solve it thus: dw := dfunD dw Which is all fine except that now ** the superclass C is bottom **! The instance we want is: dfunD :: forall a. D [a] -> D [a] dfunD = \d::D [a] -> MkD (dfunC (scsel d)) ... THE SOLUTION Our solution to this problem "silent superclass arguments". We pass to each dfun some ``silent superclass arguments’’, which are the immediate superclasses of the dictionary we are trying to construct. In our example: dfun :: forall a. C [a] -> D [a] -> D [a] dfun = \(dc::C [a]) (dd::D [a]) -> DOrd dc ... Notice the extra (dc :: C [a]) argument compared to the previous version. This gives us: ----------------------------------------------------------- DFun Superclass Invariant ~~~~~~~~~~~~~~~~~~~~~~~~ In the body of a DFun, every superclass argument to the returned dictionary is either * one of the arguments of the DFun, or * constant, bound at top level ----------------------------------------------------------- This net effect is that it is safe to treat a dfun application as wrapping a dictionary constructor around its arguments (in particular, a dfun never picks superclasses from the arguments under the dictionary constructor). No superclass is hidden inside a dfun application. The extra arguments required to satisfy the DFun Superclass Invariant always come first, and are called the "silent" arguments. You can find out how many silent arguments there are using Id.dfunNSilent; and then you can just drop that number of arguments to see the ones that were in the original instance declaration. DFun types are built (only) by MkId.mkDictFunId, so that is where we decide what silent arguments are to be added. In our example, if we had [Wanted] dw :: D [a] we would get via the instance: dw := dfun d1 d2 [Wanted] (d1 :: C [a]) [Wanted] (d2 :: D [a]) And now, though we *can* solve: d2 := dw That's fine; and we solve d1:C[a] separately. Test case SCLoop tests this fix. Note [SPECIALISE instance pragmas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider instance (Ix a, Ix b) => Ix (a,b) where {-# SPECIALISE instance Ix (Int,Int) #-} range (x,y) = ... We make a specialised version of the dictionary function, AND specialised versions of each *method*. Thus we should generate something like this: $dfIxPair :: (Ix a, Ix b) => Ix (a,b) {-# DFUN [$crangePair, ...] #-} {-# SPECIALISE $dfIxPair :: Ix (Int,Int) #-} $dfIxPair da db = Ix ($crangePair da db) (...other methods...) $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)] {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-} $crange da db = <blah> The SPECIALISE pragmas are acted upon by the desugarer, which generate dii :: Ix Int dii = ... $s$dfIxPair :: Ix ((Int,Int),(Int,Int)) {-# DFUN [$crangePair di di, ...] #-} $s$dfIxPair = Ix ($crangePair di di) (...) {-# RULE forall (d1,d2:Ix Int). $dfIxPair Int Int d1 d2 = $s$dfIxPair #-} $s$crangePair :: ((Int,Int),(Int,Int)) -> [(Int,Int)] $c$crangePair = ...specialised RHS of $crangePair... {-# RULE forall (d1,d2:Ix Int). $crangePair Int Int d1 d2 = $s$crangePair #-} Note that * The specialised dictionary $s$dfIxPair is very much needed, in case we call a function that takes a dictionary, but in a context where the specialised dictionary can be used. See Trac #7797. * The ClassOp rule for 'range' works equally well on $s$dfIxPair, because it still has a DFunUnfolding. See Note [ClassOp/DFun selection] * A call (range ($dfIxPair Int Int d1 d2)) might simplify two ways: --> {ClassOp rule for range} $crangePair Int Int d1 d2 --> {SPEC rule for $crangePair} $s$crangePair or thus: --> {SPEC rule for $dfIxPair} range $s$dfIxPair --> {ClassOpRule for range} $s$crangePair It doesn't matter which way. * We want to specialise the RHS of both $dfIxPair and $crangePair, but the SAME HsWrapper will do for both! We can call tcSpecPrag just once, and pass the result (in spec_inst_info) to tcInstanceMethods. -} tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag tcSpecInst dfun_id prag@(SpecInstSig _src hs_ty) = addErrCtxt (spec_ctxt prag) $ do { (tyvars, theta, clas, tys) <- tcHsInstHead SpecInstCtxt hs_ty ; let (_, spec_dfun_ty) = mkDictFunTy tyvars theta clas tys ; co_fn <- tcSubType SpecInstCtxt (idType dfun_id) spec_dfun_ty ; return (SpecPrag dfun_id co_fn defaultInlinePragma) } where spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag) tcSpecInst _ _ = panic "tcSpecInst" {- ************************************************************************ * * Type-checking an instance method * * ************************************************************************ tcInstanceMethod - Make the method bindings, as a [(NonRec, HsBinds)], one per method - Remembering to use fresh Name (the instance method Name) as the binder - Bring the instance method Ids into scope, for the benefit of tcInstSig - Use sig_fn mapping instance method Name -> instance tyvars - Ditto prag_fn - Use tcValBinds to do the checking -} tcInstanceMethods :: DFunId -> Class -> [TcTyVar] -> [EvVar] -> [TcType] -> ([Located TcSpecPrag], PragFun) -> [(Id, DefMeth)] -> InstBindings Name -> TcM ([Id], [LHsBind Id]) -- The returned inst_meth_ids all have types starting -- forall tvs. theta => ... tcInstanceMethods dfun_id clas tyvars dfun_ev_vars inst_tys (spec_inst_prags, prag_fn) op_items (InstBindings { ib_binds = binds , ib_tyvars = lexical_tvs , ib_pragmas = sigs , ib_extensions = exts , ib_derived = is_derived }) = tcExtendTyVarEnv2 (lexical_tvs `zip` tyvars) $ -- The lexical_tvs scope over the 'where' part do { traceTc "tcInstMeth" (ppr sigs $$ ppr binds) ; let hs_sig_fn = mkHsSigFun sigs ; checkMinimalDefinition ; set_exts exts $ mapAndUnzipM (tc_item hs_sig_fn) op_items } where set_exts :: [LangExt.Extension] -> TcM a -> TcM a set_exts es thing = foldr setXOptM thing es ---------------------- tc_item :: HsSigFun -> (Id, DefMeth) -> TcM (Id, LHsBind Id) tc_item sig_fn (sel_id, dm_info) = case findMethodBind (idName sel_id) binds of Just (user_bind, bndr_loc) -> tc_body sig_fn sel_id user_bind bndr_loc Nothing -> do { traceTc "tc_def" (ppr sel_id) ; tc_default sig_fn sel_id dm_info } ---------------------- tc_body :: HsSigFun -> Id -> LHsBind Name -> SrcSpan -> TcM (TcId, LHsBind Id) tc_body sig_fn sel_id rn_bind bndr_loc = add_meth_ctxt sel_id rn_bind $ do { traceTc "tc_item" (ppr sel_id <+> ppr (idType sel_id)) ; (meth_id, local_meth_sig, hs_wrap) <- setSrcSpan bndr_loc $ mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; let prags = prag_fn (idName sel_id) ; meth_id1 <- addInlinePrags meth_id prags ; spec_prags <- tcSpecPrags meth_id1 prags ; bind <- tcInstanceMethodBody InstSkol tyvars dfun_ev_vars meth_id1 local_meth_sig hs_wrap (mk_meth_spec_prags meth_id1 spec_prags) rn_bind ; return (meth_id1, bind) } ---------------------- tc_default :: HsSigFun -> Id -> DefMeth -> TcM (TcId, LHsBind Id) tc_default sig_fn sel_id (GenDefMeth dm_name) = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id dm_name ; tc_body sig_fn sel_id meth_bind inst_loc } tc_default sig_fn sel_id NoDefMeth -- No default method at all = do { traceTc "tc_def: warn" (ppr sel_id) ; (meth_id, _, _) <- mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; dflags <- getDynFlags ; return (meth_id, mkVarBind meth_id $ mkLHsWrap lam_wrapper (error_rhs dflags)) } where error_rhs dflags = L inst_loc $ HsApp error_fun (error_msg dflags) error_fun = L inst_loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID error_msg dflags = L inst_loc (HsLit (HsStringPrim "" (unsafeMkByteString (error_string dflags)))) meth_tau = funResultTy (applyTys (idType sel_id) inst_tys) error_string dflags = showSDoc dflags (hcat [ppr inst_loc, text "|", ppr sel_id ]) lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_ev_vars tc_default sig_fn sel_id (DefMeth dm_name) -- A polymorphic default method = do { -- Build the typechecked version directly, -- without calling typecheck_method; -- see Note [Default methods in instances] -- Generate /\as.\ds. let self = df as ds -- in $dm inst_tys self -- The 'let' is necessary only because HsSyn doesn't allow -- you to apply a function to a dictionary *expression*. ; self_dict <- newDict clas inst_tys ; let self_ev_bind = EvBind self_dict (EvDFunApp dfun_id (mkTyVarTys tyvars) (map EvId dfun_ev_vars)) ; (meth_id, local_meth_sig, hs_wrap) <- mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; dm_id <- tcLookupId dm_name ; let dm_inline_prag = idInlinePragma dm_id rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $ HsVar dm_id local_meth_id = sig_id local_meth_sig meth_bind = mkVarBind local_meth_id (L inst_loc rhs) meth_id1 = meth_id `setInlinePragma` dm_inline_prag -- Copy the inline pragma (if any) from the default -- method to this version. Note [INLINE and default methods] export = ABE { abe_wrap = hs_wrap, abe_poly = meth_id1 , abe_mono = local_meth_id , abe_prags = mk_meth_spec_prags meth_id1 [] } bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = EvBinds (unitBag self_ev_bind) , abs_binds = unitBag meth_bind } -- Default methods in an instance declaration can't have their own -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but -- currently they are rejected with -- "INLINE pragma lacks an accompanying binding" ; return (meth_id1, L inst_loc bind) } ---------------------- mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> TcSpecPrags -- Adapt the 'SPECIALISE instance' pragmas to work for this method Id -- There are two sources: -- * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-} -- * spec_prags_from_inst: derived from {-# SPECIALISE instance :: <blah> #-} -- These ones have the dfun inside, but [perhaps surprisingly] -- the correct wrapper. mk_meth_spec_prags meth_id spec_prags_for_me = SpecPrags (spec_prags_for_me ++ spec_prags_from_inst) where spec_prags_from_inst | isInlinePragma (idInlinePragma meth_id) = [] -- Do not inherit SPECIALISE from the instance if the -- method is marked INLINE, because then it'll be inlined -- and the specialisation would do nothing. (Indeed it'll provoke -- a warning from the desugarer | otherwise = [ L inst_loc (SpecPrag meth_id wrap inl) | L inst_loc (SpecPrag _ wrap inl) <- spec_inst_prags] inst_loc = getSrcSpan dfun_id -- For instance decls that come from deriving clauses -- we want to print out the full source code if there's an error -- because otherwise the user won't see the code at all add_meth_ctxt sel_id rn_bind thing | is_derived = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys rn_bind) thing | otherwise = thing ---------------------- -- check if one of the minimal complete definitions is satisfied checkMinimalDefinition = whenIsJust (isUnsatisfied methodExists (classMinimalDef clas)) $ warnUnsatisifiedMinimalDefinition where methodExists meth = isJust (findMethodBind meth binds) mkGenericDefMethBind :: Class -> [Type] -> Id -> Name -> TcM (LHsBind Name) mkGenericDefMethBind clas inst_tys sel_id dm_name = -- A generic default method -- If the method is defined generically, we only have to call the -- dm_name. do { dflags <- getDynFlags ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Filling in method body" (vcat [ppr clas <+> ppr inst_tys, nest 2 (ppr sel_id <+> equals <+> ppr rhs)])) ; return (noLoc $ mkTopFunBind Generated (noLoc (idName sel_id)) [mkSimpleMatch [] rhs]) } where rhs = nlHsVar dm_name ---------------------- wrapId :: HsWrapper -> id -> HsExpr id wrapId wrapper id = mkHsWrap wrapper (HsVar id) derivBindCtxt :: Id -> Class -> [Type ] -> LHsBind Name -> SDoc derivBindCtxt sel_id clas tys _bind = vcat [ ptext (sLit "When typechecking the code for ") <+> quotes (ppr sel_id) , nest 2 (ptext (sLit "in a derived instance for") <+> quotes (pprClassPred clas tys) <> colon) , nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ] warnMissingMethodOrAT :: String -> Name -> TcM () warnMissingMethodOrAT what name = do { warn <- woptM Opt_WarnMissingMethods ; traceTc "warn" (ppr name <+> ppr warn <+> ppr (not (startsWithUnderscore (getOccName name)))) ; warnTc (Reason Opt_WarnMissingMethods) (warn -- Warn only if -fwarn-missing-methods && not (startsWithUnderscore (getOccName name))) -- Don't warn about _foo methods (ptext (sLit "No explicit") <+> text what <+> ptext (sLit "or default declaration for") <+> quotes (ppr name)) } warnUnsatisifiedMinimalDefinition :: ClassMinimalDef -> TcM () warnUnsatisifiedMinimalDefinition mindef = do { warn <- woptM Opt_WarnMissingMethods ; warnTc (Reason Opt_WarnMissingMethods) warn message } where message = vcat [ptext (sLit "No explicit implementation for") ,nest 2 $ pprBooleanFormulaNice mindef ] {- Note [Export helper functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We arrange to export the "helper functions" of an instance declaration, so that they are not subject to preInlineUnconditionally, even if their RHS is trivial. Reason: they are mentioned in the DFunUnfolding of the dict fun as Ids, not as CoreExprs, so we can't substitute a non-variable for them. We could change this by making DFunUnfoldings have CoreExprs, but it seems a bit simpler this way. Note [Default methods in instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this class Baz v x where foo :: x -> x foo y = <blah> instance Baz Int Int From the class decl we get $dmfoo :: forall v x. Baz v x => x -> x $dmfoo y = <blah> Notice that the type is ambiguous. That's fine, though. The instance decl generates $dBazIntInt = MkBaz fooIntInt fooIntInt = $dmfoo Int Int $dBazIntInt BUT this does mean we must generate the dictionary translation of fooIntInt directly, rather than generating source-code and type-checking it. That was the bug in Trac #1061. In any case it's less work to generate the translated version! Note [INLINE and default methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Default methods need special case. They are supposed to behave rather like macros. For exmample class Foo a where op1, op2 :: Bool -> a -> a {-# INLINE op1 #-} op1 b x = op2 (not b) x instance Foo Int where -- op1 via default method op2 b x = <blah> The instance declaration should behave just as if 'op1' had been defined with the code, and INLINE pragma, from its original definition. That is, just as if you'd written instance Foo Int where op2 b x = <blah> {-# INLINE op1 #-} op1 b x = op2 (not b) x So for the above example we generate: {-# INLINE $dmop1 #-} -- $dmop1 has an InlineCompulsory unfolding $dmop1 d b x = op2 d (not b) x $fFooInt = MkD $cop1 $cop2 {-# INLINE $cop1 #-} $cop1 = $dmop1 $fFooInt $cop2 = <blah> Note carefully: * We *copy* any INLINE pragma from the default method $dmop1 to the instance $cop1. Otherwise we'll just inline the former in the latter and stop, which isn't what the user expected * Regardless of its pragma, we give the default method an unfolding with an InlineCompulsory source. That means that it'll be inlined at every use site, notably in each instance declaration, such as $cop1. This inlining must happen even though a) $dmop1 is not saturated in $cop1 b) $cop1 itself has an INLINE pragma It's vital that $dmop1 *is* inlined in this way, to allow the mutual recursion between $fooInt and $cop1 to be broken * To communicate the need for an InlineCompulsory to the desugarer (which makes the Unfoldings), we use the IsDefaultMethod constructor in TcSpecPrags. ************************************************************************ * * \subsection{Error messages} * * ************************************************************************ -} instDeclCtxt1 :: LHsType Name -> SDoc instDeclCtxt1 hs_inst_ty = inst_decl_ctxt (case unLoc hs_inst_ty of HsForAllTy _ _ _ _ (L _ ty') -> ppr ty' _ -> ppr hs_inst_ty) -- Don't expect this instDeclCtxt2 :: Type -> SDoc instDeclCtxt2 dfun_ty = inst_decl_ctxt (ppr (mkClassPred cls tys)) where (_,_,cls,tys) = tcSplitDFunTy dfun_ty inst_decl_ctxt :: SDoc -> SDoc inst_decl_ctxt doc = hang (ptext (sLit "In the instance declaration for")) 2 (quotes doc) badBootFamInstDeclErr :: SDoc badBootFamInstDeclErr = ptext (sLit "Illegal family instance in hs-boot file") notFamily :: TyCon -> SDoc notFamily tycon = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon) , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))] tooFewParmsErr :: Arity -> SDoc tooFewParmsErr arity = ptext (sLit "Family instance has too few parameters; expected") <+> ppr arity assocInClassErr :: Located Name -> SDoc assocInClassErr name = ptext (sLit "Associated type") <+> quotes (ppr name) <+> ptext (sLit "must be inside a class instance") badFamInstDecl :: Located Name -> SDoc badFamInstDecl tc_name = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tc_name) , nest 2 (parens $ ptext (sLit "Use TypeFamilies to allow indexed type families")) ] notOpenFamily :: TyCon -> SDoc notOpenFamily tc = ptext (sLit "Illegal instance for closed family") <+> quotes (ppr tc)
rahulmutt/ghcvm
compiler/Eta/TypeCheck/TcInstDcls.hs
bsd-3-clause
64,269
6
26
18,851
8,213
4,271
3,942
579
7
{-# LANGUAGE CPP #-} -- | This is where we define a mapping from Uniques to their associated -- known-key Names for things associated with tuples and sums. We use this -- mapping while deserializing known-key Names in interface file symbol tables, -- which are encoded as their Unique. See Note [Symbol table representation of -- names] for details. -- module Eta.Prelude.KnownUniques ( -- * Looking up known-key names knownUniqueName -- * Getting the 'Unique's of 'Name's -- ** Anonymous sums , mkSumTyConUnique , mkSumDataConUnique -- ** Tuples -- *** Vanilla , mkTupleTyConUnique , mkTupleDataConUnique -- *** Constraint , mkCTupleTyConUnique , mkCTupleDataConUnique ) where #include "HsVersions.h" import Eta.Prelude.TysWiredIn import Eta.Types.TyCon import Eta.BasicTypes.DataCon import Eta.BasicTypes.Id import Eta.BasicTypes.BasicTypes import Eta.Utils.Outputable import Eta.BasicTypes.Unique import Eta.BasicTypes.Name import Eta.Utils.Util import Data.Bits -- import Data.Maybe -- | Get the 'Name' associated with a known-key 'Unique'. knownUniqueName :: Unique -> Maybe Name knownUniqueName u = case tag of --'z' -> Just $ getUnboxedSumName n '4' -> Just $ getTupleTyConName BoxedTuple n '5' -> Just $ getTupleTyConName UnboxedTuple n '7' -> Just $ getTupleDataConName BoxedTuple n '8' -> Just $ getTupleDataConName UnboxedTuple n 'k' -> Just $ getTupleTyConName ConstraintTuple n 'm' -> Just $ getTupleDataConName ConstraintTuple n _ -> Nothing where (tag, n) = unpkUnique u -------------------------------------------------- -- Anonymous sums -- -- Sum arities start from 2. The encoding is a bit funny: we break up the -- integral part into bitfields for the arity, an alternative index (which is -- taken to be 0xff in the case of the TyCon), and, in the case of a datacon, a -- tag (used to identify the sum's TypeRep binding). -- -- This layout is chosen to remain compatible with the usual unique allocation -- for wired-in data constructors described in Unique.hs -- -- TyCon for sum of arity k: -- 00000000 kkkkkkkk 11111100 -- TypeRep of TyCon for sum of arity k: -- 00000000 kkkkkkkk 11111101 -- -- DataCon for sum of arity k and alternative n (zero-based): -- 00000000 kkkkkkkk nnnnnn00 -- -- TypeRep for sum DataCon of arity k and alternative n (zero-based): -- 00000000 kkkkkkkk nnnnnn10 mkSumTyConUnique :: Arity -> Unique mkSumTyConUnique arity = ASSERT(arity < 0x3f) -- 0x3f since we only have 6 bits to encode the -- alternative mkUnique 'z' (arity `shiftL` 8 .|. 0xfc) mkSumDataConUnique :: ConTagZ -> Arity -> Unique mkSumDataConUnique alt arity | alt >= arity = panic ("mkSumDataConUnique: " ++ show alt ++ " >= " ++ show arity) | otherwise = mkUnique 'z' (arity `shiftL` 8 + alt `shiftL` 2) {- skip the tycon -} -- getUnboxedSumName :: Int -> Name -- getUnboxedSumName n -- | n .&. 0xfc == 0xfc -- = case tag of -- 0x0 -> tyConName $ sumTyCon arity -- 0x1 -> getRep $ sumTyCon arity -- _ -> pprPanic "getUnboxedSumName: invalid tag" (ppr tag) -- | tag == 0x0 -- = dataConName $ sumDataCon (alt + 1) arity -- | tag == 0x1 -- = getName $ dataConWrapId $ sumDataCon (alt + 1) arity -- | tag == 0x2 -- = getRep $ promoteDataCon $ sumDataCon (alt + 1) arity -- | otherwise -- = pprPanic "getUnboxedSumName" (ppr n) -- where -- arity = n `shiftR` 8 -- alt = (n .&. 0xfc) `shiftR` 2 -- tag = 0x3 .&. n -- getRep tycon = -- fromMaybe (pprPanic "getUnboxedSumName(getRep)" (ppr tycon)) -- $ tyConRepName_maybe tycon -- Note [Uniques for tuple type and data constructors] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- Wired-in type constructor keys occupy *two* slots: -- * u: the TyCon itself -- * u+1: the TyConRepName of the TyCon -- -- Wired-in tuple data constructor keys occupy *three* slots: -- * u: the DataCon itself -- * u+1: its worker Id -- * u+2: the TyConRepName of the promoted TyCon -------------------------------------------------- -- Constraint tuples mkCTupleTyConUnique :: Arity -> Unique mkCTupleTyConUnique a = mkUnique 'k' (2*a) mkCTupleDataConUnique :: Arity -> Unique mkCTupleDataConUnique a = mkUnique 'm' (3*a) -- getCTupleTyConName :: Int -> Name -- getCTupleTyConName n = -- case n `divMod` 2 of -- (arity, 0) -> tyConName $ tupleTyCon boxity arity -- (arity, 1) -> mkPrelTyConRepName $ cTupleTyConName arity -- _ -> panic "getCTupleTyConName: impossible" -- -- getCTupleDataConUnique :: Int -> Name -- getCTupleDataConUnique n = -- case n `divMod` 3 of -- (arity, 0) -> cTupleDataConName arity -- (_arity, 1) -> panic "getCTupleDataConName: no worker" -- (arity, 2) -> mkPrelTyConRepName $ cTupleDataConName arity -- _ -> panic "getCTupleDataConName: impossible" -------------------------------------------------- -- Normal tuples mkTupleDataConUnique :: TupleSort -> Arity -> Unique mkTupleDataConUnique BoxedTuple a = mkUnique '7' (3*a) -- may be used in C labels mkTupleDataConUnique UnboxedTuple a = mkUnique '8' (3*a) mkTupleDataConUnique ConstraintTuple a = mkCTupleDataConUnique a mkTupleTyConUnique :: TupleSort -> Arity -> Unique mkTupleTyConUnique BoxedTuple a = mkUnique '4' (2*a) mkTupleTyConUnique UnboxedTuple a = mkUnique '5' (2*a) mkTupleTyConUnique ConstraintTuple a = mkCTupleTyConUnique a getTupleTyConName :: TupleSort -> Int -> Name getTupleTyConName sort n = case n `divMod` 2 of (arity, 0) -> tyConName $ tupleTyCon sort arity (_arity, 1) -> panic "getTupleTyConName not handled!" -- fromMaybe (panic "getTupleTyConName") -- $ tyConRepName_maybe $ tupleTyCon boxity arity _ -> panic "getTupleTyConName: impossible" getTupleDataConName :: TupleSort -> Int -> Name getTupleDataConName sort n = case n `divMod` 3 of (arity, 0) -> dataConName $ tupleCon sort arity (arity, 1) -> idName $ dataConWorkId $ tupleCon sort arity (_arity, 2) -> panic "getTupleDataConName not handled!" -- fromMaybe (panic "getTupleDataCon") -- $ tyConRepName_maybe $ promotedTupleDataCon boxity arity _ -> panic "getTupleDataConName: impossible"
rahulmutt/ghcvm
compiler/Eta/Prelude/KnownUniques.hs
bsd-3-clause
6,452
0
11
1,446
838
487
351
66
7
{-# LANGUAGE PatternGuards, ScopedTypeVariables #-} module Main where import Prelude hiding ( mod, id, mapM ) import GHC hiding (flags) --import Packages import HscTypes ( isBootSummary ) import Digraph ( flattenSCCs ) import DriverPhases ( isHaskellSrcFilename ) import HscTypes ( msHsFilePath ) import Name ( getOccString ) --import ErrUtils ( printBagOfErrors ) import Panic ( panic ) import DynFlags ( defaultLogAction ) import Bag import Exception import FastString import MonadUtils ( liftIO ) import SrcLoc -- Every GHC comes with Cabal anyways, so this is not a bad new dependency import Distribution.Simple.GHC ( ghcOptions ) import Distribution.Simple.Configure ( getPersistBuildConfig ) import Distribution.PackageDescription ( library, libBuildInfo ) import Distribution.Simple.LocalBuildInfo ( localPkgDescr, buildDir, libraryConfig ) import Control.Monad hiding (mapM) import System.Environment import System.Console.GetOpt import System.Exit import System.IO import Data.List as List hiding ( group ) import Data.Traversable (mapM) import Data.Map ( Map ) import qualified Data.Map as M --import UniqFM --import Debug.Trace -- search for definitions of things -- we do this by parsing the source and grabbing top-level definitions -- We generate both CTAGS and ETAGS format tags files -- The former is for use in most sensible editors, while EMACS uses ETAGS ---------------------------------- ---- CENTRAL DATA TYPES ---------- type FileName = String type ThingName = String -- name of a defined entity in a Haskell program -- A definition we have found (we know its containing module, name, and location) data FoundThing = FoundThing ModuleName ThingName RealSrcLoc -- Data we have obtained from a file (list of things we found) data FileData = FileData FileName [FoundThing] (Map Int String) --- invariant (not checked): every found thing has a source location in that file? ------------------------------ -------- MAIN PROGRAM -------- main :: IO () main = do progName <- getProgName let usageString = "Usage: " ++ progName ++ " [OPTION...] [-- GHC OPTION... --] [files...]" args <- getArgs let (ghcArgs', ourArgs, unbalanced) = splitArgs args let (flags, filenames, errs) = getOpt Permute options ourArgs let (hsfiles, otherfiles) = List.partition isHaskellSrcFilename filenames let ghc_topdir = case [ d | FlagTopDir d <- flags ] of [] -> "" (x:_) -> x mapM_ (\n -> putStr $ "Warning: ignoring non-Haskellish file " ++ n ++ "\n") otherfiles if unbalanced || errs /= [] || elem FlagHelp flags || hsfiles == [] then do putStr $ unlines errs putStr $ usageInfo usageString options exitWith (ExitFailure 1) else return () ghcArgs <- case [ d | FlagUseCabalConfig d <- flags ] of [distPref] -> do cabalOpts <- flagsFromCabal distPref return (cabalOpts ++ ghcArgs') [] -> return ghcArgs' _ -> error "Too many --use-cabal-config flags" print ghcArgs let modes = getMode flags let openFileMode = if elem FlagAppend flags then AppendMode else WriteMode ctags_hdl <- if CTags `elem` modes then Just `liftM` openFile "tags" openFileMode else return Nothing etags_hdl <- if ETags `elem` modes then Just `liftM` openFile "TAGS" openFileMode else return Nothing GHC.defaultErrorHandler defaultLogAction $ runGhc (Just ghc_topdir) $ do --liftIO $ print "starting up session" dflags <- getSessionDynFlags (pflags, unrec, warns) <- parseDynamicFlags dflags{ verbosity=1 } (map noLoc ghcArgs) unless (null unrec) $ liftIO $ putStrLn $ "Unrecognised options:\n" ++ show (map unLoc unrec) liftIO $ mapM_ putStrLn (map unLoc warns) let dflags2 = pflags { hscTarget = HscNothing } -- don't generate anything -- liftIO $ print ("pkgDB", case (pkgDatabase dflags2) of Nothing -> 0 -- Just m -> sizeUFM m) _ <- setSessionDynFlags dflags2 --liftIO $ print (length pkgs) GHC.defaultCleanupHandler dflags2 $ do targetsAtOneGo hsfiles (ctags_hdl,etags_hdl) mapM_ (mapM (liftIO . hClose)) [ctags_hdl, etags_hdl] ---------------------------------------------- ---------- ARGUMENT PROCESSING -------------- data Flag = FlagETags | FlagCTags | FlagBoth | FlagAppend | FlagHelp | FlagTopDir FilePath | FlagUseCabalConfig FilePath | FlagFilesFromCabal deriving (Ord, Eq, Show) -- ^Represents options passed to the program data Mode = ETags | CTags deriving Eq getMode :: [Flag] -> [Mode] getMode fs = go (concatMap modeLike fs) where go [] = [ETags,CTags] go [x] = [x] go more = nub more modeLike FlagETags = [ETags] modeLike FlagCTags = [CTags] modeLike FlagBoth = [ETags,CTags] modeLike _ = [] splitArgs :: [String] -> ([String], [String], Bool) -- ^Pull out arguments between -- for GHC splitArgs args0 = split [] [] False args0 where split ghc' tags' unbal ("--" : args) = split tags' ghc' (not unbal) args split ghc' tags' unbal (arg : args) = split ghc' (arg:tags') unbal args split ghc' tags' unbal [] = (reverse ghc', reverse tags', unbal) options :: [OptDescr Flag] -- supports getopt options = [ Option "" ["topdir"] (ReqArg FlagTopDir "DIR") "root of GHC installation (optional)" , Option "c" ["ctags"] (NoArg FlagCTags) "generate CTAGS file (ctags)" , Option "e" ["etags"] (NoArg FlagETags) "generate ETAGS file (etags)" , Option "b" ["both"] (NoArg FlagBoth) ("generate both CTAGS and ETAGS") , Option "a" ["append"] (NoArg FlagAppend) ("append to existing CTAGS and/or ETAGS file(s)") , Option "" ["use-cabal-config"] (ReqArg FlagUseCabalConfig "DIR") "use local cabal configuration from dist dir" , Option "" ["files-from-cabal"] (NoArg FlagFilesFromCabal) "use files from cabal" , Option "h" ["help"] (NoArg FlagHelp) "This help" ] flagsFromCabal :: FilePath -> IO [String] flagsFromCabal distPref = do lbi <- getPersistBuildConfig distPref let pd = localPkgDescr lbi case (library pd, libraryConfig lbi) of (Just lib, Just clbi) -> let bi = libBuildInfo lib odir = buildDir lbi opts = ghcOptions lbi bi clbi odir in return opts _ -> error "no library" ---------------------------------------------------------------- --- LOADING HASKELL SOURCE --- (these bits actually run the compiler and produce abstract syntax) safeLoad :: LoadHowMuch -> Ghc SuccessFlag -- like GHC.load, but does not stop process on exception safeLoad mode = do _dflags <- getSessionDynFlags ghandle (\(e :: SomeException) -> liftIO (print e) >> return Failed ) $ handleSourceError (\e -> printException e >> return Failed) $ load mode targetsAtOneGo :: [FileName] -> (Maybe Handle, Maybe Handle) -> Ghc () -- load a list of targets targetsAtOneGo hsfiles handles = do targets <- mapM (\f -> guessTarget f Nothing) hsfiles setTargets targets modgraph <- depanal [] False let mods = flattenSCCs $ topSortModuleGraph False modgraph Nothing graphData mods handles fileTarget :: FileName -> Target fileTarget filename = Target (TargetFile filename Nothing) True Nothing --------------------------------------------------------------- ----- CRAWLING ABSTRACT SYNTAX TO SNAFFLE THE DEFINITIONS ----- graphData :: ModuleGraph -> (Maybe Handle, Maybe Handle) -> Ghc () graphData graph handles = do mapM_ foundthings graph where foundthings ms = let filename = msHsFilePath ms modname = moduleName $ ms_mod ms in handleSourceError (\e -> do printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ putStrLn ("loading " ++ filename) mod <- loadModule =<< typecheckModule =<< parseModule ms case mod of _ | isBootSummary ms -> return () _ | Just s <- renamedSource mod -> liftIO (writeTagsData handles =<< fileData filename modname s) _otherwise -> liftIO $ exitWith (ExitFailure 1) fileData :: FileName -> ModuleName -> RenamedSource -> IO FileData fileData filename modname (group, _imports, _lie, _doc) = do -- lie is related to type checking and so is irrelevant -- imports contains import declarations and no definitions -- doc and haddock seem haddock-related; let's hope to ignore them ls <- lines `fmap` readFile filename let line_map = M.fromAscList $ zip [1..] ls line_map' <- evaluate line_map return $ FileData filename (boundValues modname group) line_map' boundValues :: ModuleName -> HsGroup Name -> [FoundThing] -- ^Finds all the top-level definitions in a module boundValues mod group = let vals = case hs_valds group of ValBindsOut nest _sigs -> [ x | (_rec, binds) <- nest , bind <- bagToList binds , x <- boundThings mod bind ] _other -> error "boundValues" tys = [ n | ns <- map hsTyClDeclBinders (concat (hs_tyclds group)) , n <- map found ns ] fors = concat $ map forBound (hs_fords group) where forBound lford = case unLoc lford of ForeignImport n _ _ _ -> [found n] ForeignExport { } -> [] in vals ++ tys ++ fors where found = foundOfLName mod startOfLocated :: Located a -> RealSrcLoc startOfLocated lHs = case getLoc lHs of RealSrcSpan l -> realSrcSpanStart l UnhelpfulSpan _ -> panic "startOfLocated UnhelpfulSpan" foundOfLName :: ModuleName -> Located Name -> FoundThing foundOfLName mod id = FoundThing mod (getOccString $ unLoc id) (startOfLocated id) boundThings :: ModuleName -> LHsBind Name -> [FoundThing] boundThings modname lbinding = case unLoc lbinding of FunBind { fun_id = id } -> [thing id] PatBind { pat_lhs = lhs } -> patThings lhs [] VarBind { var_id = id } -> [FoundThing modname (getOccString id) (startOfLocated lbinding)] AbsBinds { } -> [] -- nothing interesting in a type abstraction where thing = foundOfLName modname patThings lpat tl = let loc = startOfLocated lpat lid id = FoundThing modname (getOccString id) loc in case unLoc lpat of WildPat _ -> tl VarPat name -> lid name : tl LazyPat p -> patThings p tl AsPat id p -> patThings p (thing id : tl) ParPat p -> patThings p tl BangPat p -> patThings p tl ListPat ps _ -> foldr patThings tl ps TuplePat ps _ _ -> foldr patThings tl ps PArrPat ps _ -> foldr patThings tl ps ConPatIn _ conargs -> conArgs conargs tl ConPatOut _ _ _ _ conargs _ -> conArgs conargs tl LitPat _ -> tl NPat _ _ _ -> tl -- form of literal pattern? NPlusKPat id _ _ _ -> thing id : tl SigPatIn p _ -> patThings p tl SigPatOut p _ -> patThings p tl _ -> error "boundThings" conArgs (PrefixCon ps) tl = foldr patThings tl ps conArgs (RecCon (HsRecFields { rec_flds = flds })) tl = foldr (\f tl' -> patThings (hsRecFieldArg f) tl') tl flds conArgs (InfixCon p1 p2) tl = patThings p1 $ patThings p2 tl -- stuff for dealing with ctags output format writeTagsData :: (Maybe Handle, Maybe Handle) -> FileData -> IO () writeTagsData (mb_ctags_hdl, mb_etags_hdl) fd = do maybe (return ()) (\hdl -> writectagsfile hdl fd) mb_ctags_hdl maybe (return ()) (\hdl -> writeetagsfile hdl fd) mb_etags_hdl writectagsfile :: Handle -> FileData -> IO () writectagsfile ctagsfile filedata = do let things = getfoundthings filedata mapM_ (\x -> hPutStrLn ctagsfile $ dumpthing False x) things mapM_ (\x -> hPutStrLn ctagsfile $ dumpthing True x) things getfoundthings :: FileData -> [FoundThing] getfoundthings (FileData _filename things _src_lines) = things dumpthing :: Bool -> FoundThing -> String dumpthing showmod (FoundThing modname name loc) = fullname ++ "\t" ++ filename ++ "\t" ++ (show line) where line = srcLocLine loc filename = unpackFS $ srcLocFile loc fullname = if showmod then moduleNameString modname ++ "." ++ name else name -- stuff for dealing with etags output format writeetagsfile :: Handle -> FileData -> IO () writeetagsfile etagsfile = hPutStr etagsfile . e_dumpfiledata e_dumpfiledata :: FileData -> String e_dumpfiledata (FileData filename things line_map) = "\x0c\n" ++ filename ++ "," ++ (show thingslength) ++ "\n" ++ thingsdump where thingsdump = concat $ map (e_dumpthing line_map) things thingslength = length thingsdump e_dumpthing :: Map Int String -> FoundThing -> String e_dumpthing src_lines (FoundThing modname name loc) = tagline name ++ tagline (moduleNameString modname ++ "." ++ name) where tagline n = src_code ++ "\x7f" ++ n ++ "\x01" ++ (show line) ++ "," ++ (show $ column) ++ "\n" line = srcLocLine loc column = srcLocCol loc src_code = case M.lookup line src_lines of Just l -> take (column + length name) l Nothing -> --trace (show ("not found: ", moduleNameString modname, name, line, column)) name
mcmaniac/ghc
utils/ghctags/Main.hs
bsd-3-clause
14,240
0
19
4,139
3,794
1,920
1,874
266
22
{-# LANGUAGE FlexibleContexts #-} module LoadInterfaces where import Control.Monad.Except (MonadError, MonadIO, liftIO, throwError) import Control.Monad.Reader (MonadReader, ask) import qualified Data.Graph as Graph import qualified Data.List as List import qualified Data.Set as Set import Data.Map ((!)) import qualified Data.Map as Map import qualified Data.Maybe as Maybe import System.Directory (doesFileExist, getModificationTime) import qualified Elm.Compiler.Module as Module import qualified Path import qualified Utils.File as File import TheMasterPlan ( ModuleID(ModuleID), Location(..) , ProjectSummary(ProjectSummary), ProjectData(..) , BuildSummary(..), BuildData(..) ) prepForBuild :: (MonadIO m, MonadError String m, MonadReader FilePath m) => Set.Set ModuleID -> ProjectSummary Location -> m BuildSummary prepForBuild modulesToDocument (ProjectSummary projectData _projectNatives) = do enhancedData <- addInterfaces projectData filteredData <- filterStaleInterfaces modulesToDocument enhancedData return (toBuildSummary filteredData) --- LOAD INTERFACES -- what has already been compiled? addInterfaces :: (MonadIO m, MonadReader FilePath m, MonadError String m) => Map.Map ModuleID (ProjectData Location) -> m (Map.Map ModuleID (ProjectData (Location, Maybe Module.Interface))) addInterfaces projectData = do enhancedData <- mapM maybeLoadInterface (Map.toList projectData) return (Map.fromList enhancedData) -- TODO: if two modules in the same package have the same name, their interface -- files will be indistinguishable right now. The most common case of this is -- modules named Main. As a stopgap, we never load in the interface file for -- Main. The real fix may be to add a hash of the source code to the interface -- files. maybeLoadInterface :: (MonadIO m, MonadReader FilePath m, MonadError String m) => (ModuleID, ProjectData Location) -> m (ModuleID, ProjectData (Location, Maybe Module.Interface)) maybeLoadInterface (moduleID, (ProjectData location deps)) = do cacheRoot <- ask let interfacePath = Path.toInterface cacheRoot moduleID let sourcePath = Path.toSource location fresh <- liftIO (isFresh sourcePath interfacePath) maybeInterface <- case fresh && not (isMain moduleID) of False -> return Nothing True -> do interface <- File.readBinary interfacePath return (Just interface) return (moduleID, ProjectData (location, maybeInterface) deps) isFresh :: FilePath -> FilePath -> IO Bool isFresh sourcePath interfacePath = do exists <- doesFileExist interfacePath case exists of False -> return False True -> do sourceTime <- getModificationTime sourcePath interfaceTime <- getModificationTime interfacePath return (sourceTime <= interfaceTime) isMain :: ModuleID -> Bool isMain (ModuleID (Module.Name names) _) = case names of ["Main"] -> True _ -> False -- FILTER STALE INTERFACES -- have files become stale due to other changes? filterStaleInterfaces :: (MonadError String m) => Set.Set ModuleID -> Map.Map ModuleID (ProjectData (Location, Maybe Module.Interface)) -> m (Map.Map ModuleID (ProjectData (Either Location Module.Interface))) filterStaleInterfaces modulesToDocument summary = do sortedNames <- topologicalSort (Map.map projectDependencies summary) return (List.foldl' (filterIfStale summary modulesToDocument) Map.empty sortedNames) filterIfStale :: Map.Map ModuleID (ProjectData (Location, Maybe Module.Interface)) -> Set.Set ModuleID -> Map.Map ModuleID (ProjectData (Either Location Module.Interface)) -> ModuleID -> Map.Map ModuleID (ProjectData (Either Location Module.Interface)) filterIfStale enhancedSummary modulesToDocument filteredSummary moduleName = Map.insert moduleName (ProjectData trueLocation deps) filteredSummary where (ProjectData (filePath, maybeInterface) deps) = enhancedSummary ! moduleName depsAreDone = all (haveInterface filteredSummary) deps needsDocs = Set.member moduleName modulesToDocument trueLocation = case maybeInterface of Just interface | depsAreDone && not needsDocs -> Right interface _ -> Left filePath haveInterface :: Map.Map ModuleID (ProjectData (Either Location Module.Interface)) -> ModuleID -> Bool haveInterface enhancedSummary rawName = case filterNativeDeps rawName of Nothing -> True Just name -> case Map.lookup name enhancedSummary of Just (ProjectData (Right _) _) -> True _ -> False -- FILTER DEPENDENCIES -- which modules actually need to be compiled? toBuildSummary :: Map.Map ModuleID (ProjectData (Either Location Module.Interface)) -> BuildSummary toBuildSummary summary = BuildSummary { blockedModules = Map.map (toBuildData interfaces) locations , completedInterfaces = interfaces } where (locations, interfaces) = Map.mapEither divide summary divide (ProjectData either deps) = case either of Left location -> Left (ProjectData location deps) Right interface -> Right interface toBuildData :: Map.Map ModuleID Module.Interface -> ProjectData Location -> BuildData toBuildData interfaces (ProjectData location dependencies) = BuildData blocking location where blocking = Maybe.mapMaybe filterDeps dependencies filterDeps :: ModuleID -> Maybe ModuleID filterDeps deps = filterCachedDeps interfaces =<< filterNativeDeps deps filterCachedDeps :: Map.Map ModuleID Module.Interface -> ModuleID -> Maybe ModuleID filterCachedDeps interfaces name = case Map.lookup name interfaces of Just _interface -> Nothing Nothing -> Just name filterNativeDeps :: ModuleID -> Maybe ModuleID filterNativeDeps name = case name of ModuleID (Module.Name ("Native" : _)) _pkg -> Nothing _ -> Just name -- SORT GRAPHS / CHECK FOR CYCLES topologicalSort :: (MonadError String m) => Map.Map ModuleID [ModuleID] -> m [ModuleID] topologicalSort dependencies = mapM errorOnCycle components where components = Graph.stronglyConnComp (map toNode (Map.toList dependencies)) toNode (name, deps) = (name, name, deps) errorOnCycle scc = case scc of Graph.AcyclicSCC name -> return name Graph.CyclicSCC cycle@(first:_) -> throwError $ "Your dependencies form a cycle:\n\n" ++ showCycle first cycle ++ "\nYou may need to move some values to a new module to get rid of the cycle." showCycle :: ModuleID -> [ModuleID] -> String showCycle first cycle = case cycle of [] -> "" [last] -> " " ++ idToString last ++ " => " ++ idToString first ++ "\n" one:two:rest -> " " ++ idToString one ++ " => " ++ idToString two ++ "\n" ++ showCycle first (two:rest) where idToString (ModuleID moduleName _pkg) = Module.nameToString moduleName
mgold/elm-make
src/LoadInterfaces.hs
bsd-3-clause
7,297
0
15
1,724
1,908
971
937
170
3
module Stack.Options.DockerParser where import Data.Char import Data.List (intercalate) import Data.Monoid.Extra import qualified Data.Text as T import Distribution.Version (anyVersion) import Options.Applicative import Options.Applicative.Args import Options.Applicative.Builder.Extra import Stack.Constants import Stack.Docker import qualified Stack.Docker as Docker import Stack.Options.Utils import Stack.Types.Version import Stack.Types.Docker -- | Options parser configuration for Docker. dockerOptsParser :: Bool -> Parser DockerOptsMonoid dockerOptsParser hide0 = DockerOptsMonoid <$> pure (Any False) <*> firstBoolFlags dockerCmdName "using a Docker container. Implies 'system-ghc: true'" hide <*> fmap First ((Just . DockerMonoidRepo) <$> option str (long (dockerOptName dockerRepoArgName) <> hide <> metavar "NAME" <> help "Docker repository name") <|> (Just . DockerMonoidImage) <$> option str (long (dockerOptName dockerImageArgName) <> hide <> metavar "IMAGE" <> help "Exact Docker image ID (overrides docker-repo)") <|> pure Nothing) <*> firstBoolFlags (dockerOptName dockerRegistryLoginArgName) "registry requires login" hide <*> firstStrOption (long (dockerOptName dockerRegistryUsernameArgName) <> hide <> metavar "USERNAME" <> help "Docker registry username") <*> firstStrOption (long (dockerOptName dockerRegistryPasswordArgName) <> hide <> metavar "PASSWORD" <> help "Docker registry password") <*> firstBoolFlags (dockerOptName dockerAutoPullArgName) "automatic pulling latest version of image" hide <*> firstBoolFlags (dockerOptName dockerDetachArgName) "running a detached Docker container" hide <*> firstBoolFlags (dockerOptName dockerPersistArgName) "not deleting container after it exits" hide <*> firstStrOption (long (dockerOptName dockerContainerNameArgName) <> hide <> metavar "NAME" <> help "Docker container name") <*> argsOption (long (dockerOptName dockerRunArgsArgName) <> hide <> value [] <> metavar "'ARG1 [ARG2 ...]'" <> help "Additional options to pass to 'docker run'") <*> many (option auto (long (dockerOptName dockerMountArgName) <> hide <> metavar "(PATH | HOST-PATH:CONTAINER-PATH)" <> help ("Mount volumes from host in container " ++ "(may specify multiple times)"))) <*> many (option str (long (dockerOptName dockerEnvArgName) <> hide <> metavar "NAME=VALUE" <> help ("Set environment variable in container " ++ "(may specify multiple times)"))) <*> optionalFirst (absFileOption (long (dockerOptName dockerDatabasePathArgName) <> hide <> metavar "PATH" <> help "Location of image usage tracking database")) <*> optionalFirst (option (eitherReader' parseDockerStackExe) (long(dockerOptName dockerStackExeArgName) <> hide <> metavar (intercalate "|" [ dockerStackExeDownloadVal , dockerStackExeHostVal , dockerStackExeImageVal , "PATH" ]) <> help (concat [ "Location of " , stackProgName , " executable used in container" ]))) <*> firstBoolFlags (dockerOptName dockerSetUserArgName) "setting user in container to match host" hide <*> pure (IntersectingVersionRange anyVersion) where dockerOptName optName = dockerCmdName ++ "-" ++ T.unpack optName firstStrOption = optionalFirst . option str hide = hideMods hide0 -- | Parser for docker cleanup arguments. dockerCleanupOptsParser :: Parser Docker.CleanupOpts dockerCleanupOptsParser = Docker.CleanupOpts <$> (flag' Docker.CleanupInteractive (short 'i' <> long "interactive" <> help "Show cleanup plan in editor and allow changes (default)") <|> flag' Docker.CleanupImmediate (short 'y' <> long "immediate" <> help "Immediately execute cleanup plan") <|> flag' Docker.CleanupDryRun (short 'n' <> long "dry-run" <> help "Display cleanup plan but do not execute") <|> pure Docker.CleanupInteractive) <*> opt (Just 14) "known-images" "LAST-USED" <*> opt Nothing "unknown-images" "CREATED" <*> opt (Just 0) "dangling-images" "CREATED" <*> opt Nothing "stopped-containers" "CREATED" <*> opt Nothing "running-containers" "CREATED" where opt def' name mv = fmap Just (option auto (long name <> metavar (mv ++ "-DAYS-AGO") <> help ("Remove " ++ toDescr name ++ " " ++ map toLower (toDescr mv) ++ " N days ago" ++ case def' of Just n -> " (default " ++ show n ++ ")" Nothing -> ""))) <|> flag' Nothing (long ("no-" ++ name) <> help ("Do not remove " ++ toDescr name ++ case def' of Just _ -> "" Nothing -> " (default)")) <|> pure def' toDescr = map (\c -> if c == '-' then ' ' else c)
deech/stack
src/Stack/Options/DockerParser.hs
bsd-3-clause
6,673
0
33
2,870
1,199
593
606
137
4
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module RIO.Prelude ( mapLeft , withLazyFile , fromFirst , mapMaybeA , mapMaybeM , forMaybeA , forMaybeM , stripCR , RIO (..) , runRIO , module X ) where import Control.Applicative as X (Alternative, Applicative (..), liftA, liftA2, liftA3, many, optional, some, (<|>)) import Control.Arrow as X (first, second, (&&&), (***)) import Control.DeepSeq as X (NFData (..), force, ($!!)) import Control.Monad as X (Monad (..), MonadPlus (..), filterM, foldM, foldM_, forever, guard, join, liftM, liftM2, replicateM_, unless, when, zipWithM, zipWithM_, (<$!>), (<=<), (=<<), (>=>)) import Control.Monad.Catch as X (MonadThrow (..)) import Control.Monad.Reader as X (MonadReader, MonadTrans (..), ReaderT (..), ask, asks, local) import Data.Bool as X (Bool (..), not, otherwise, (&&), (||)) import Data.ByteString as X (ByteString) import Data.Char as X (Char) import Data.Conduit as X (ConduitM, runConduit, (.|)) import Data.Data as X (Data (..)) import Data.Either as X (Either (..), either, isLeft, isRight, lefts, partitionEithers, rights) import Data.Eq as X (Eq (..)) import Data.Foldable as X (Foldable, all, and, any, asum, concat, concatMap, elem, fold, foldMap, foldl', foldr, forM_, for_, length, mapM_, msum, notElem, null, or, product, sequenceA_, sequence_, sum, toList, traverse_) import Data.Function as X (const, fix, flip, id, on, ($), (&), (.)) import Data.Functor as X (Functor (..), void, ($>), (<$), (<$>)) import Data.Hashable as X (Hashable) import Data.HashMap.Strict as X (HashMap) import Data.HashSet as X (HashSet) import Data.Int as X import Data.IntMap.Strict as X (IntMap) import Data.IntSet as X (IntSet) import Data.List as X (break, drop, dropWhile, filter, lines, lookup, map, replicate, reverse, span, take, takeWhile, unlines, unwords, words, zip, (++)) import Data.Map.Strict as X (Map) import Data.Maybe as X (Maybe (..), catMaybes, fromMaybe, isJust, isNothing, listToMaybe, mapMaybe, maybe, maybeToList) import Data.Monoid as X (All (..), Any (..), Endo (..), First (..), Last (..), Monoid (..), Product (..), Sum (..), (<>)) import Data.Ord as X (Ord (..), Ordering (..), comparing) import Data.Set as X (Set) import Data.Store as X (Store) import Data.String as X (IsString (..)) import Data.Text as X (Text) import Data.Traversable as X (Traversable (..), for, forM) import Data.Vector as X (Vector) import Data.Void as X (Void, absurd) import Data.Word as X import GHC.Generics as X (Generic) import GHC.Stack as X (HasCallStack) import Lens.Micro as X (Getting, Lens', lens) import Lens.Micro.Mtl as X (view) import Prelude as X (Bounded (..), Double, Enum, FilePath, Float, Floating (..), Fractional (..), IO, Integer, Integral (..), Num (..), Rational, Real (..), RealFloat (..), RealFrac (..), Show, String, asTypeOf, curry, error, even, fromIntegral, fst, gcd, lcm, odd, realToFrac, seq, show, snd, subtract, uncurry, undefined, ($!), (^), (^^)) import System.Exit as X (ExitCode (..)) import Text.Read as X (Read, readMaybe) import UnliftIO as X import qualified Data.Text as T import qualified Data.ByteString.Lazy as BL mapLeft :: (a1 -> a2) -> Either a1 b -> Either a2 b mapLeft f (Left a1) = Left (f a1) mapLeft _ (Right b) = Right b fromFirst :: a -> First a -> a fromFirst x = fromMaybe x . getFirst -- | Applicative 'mapMaybe'. mapMaybeA :: Applicative f => (a -> f (Maybe b)) -> [a] -> f [b] mapMaybeA f = fmap catMaybes . traverse f -- | @'forMaybeA' '==' 'flip' 'mapMaybeA'@ forMaybeA :: Applicative f => [a] -> (a -> f (Maybe b)) -> f [b] forMaybeA = flip mapMaybeA -- | Monadic 'mapMaybe'. mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b] mapMaybeM f = liftM catMaybes . mapM f -- | @'forMaybeM' '==' 'flip' 'mapMaybeM'@ forMaybeM :: Monad m => [a] -> (a -> m (Maybe b)) -> m [b] forMaybeM = flip mapMaybeM -- | Strip trailing carriage return from Text stripCR :: T.Text -> T.Text stripCR t = fromMaybe t (T.stripSuffix "\r" t) -- | Lazily get the contents of a file. Unlike 'BL.readFile', this -- ensures that if an exception is thrown, the file handle is closed -- immediately. withLazyFile :: MonadUnliftIO m => FilePath -> (BL.ByteString -> m a) -> m a withLazyFile fp inner = withBinaryFile fp ReadMode $ inner <=< liftIO . BL.hGetContents -- | The Reader+IO monad. This is different from a 'ReaderT' because: -- -- * It's not a transformer, it hardcodes IO for simpler usage and -- error messages. -- -- * Instances of typeclasses like 'MonadLogger' are implemented using -- classes defined on the environment, instead of using an -- underlying monad. newtype RIO env a = RIO { unRIO :: ReaderT env IO a } deriving (Functor,Applicative,Monad,MonadIO,MonadReader env,MonadThrow) runRIO :: MonadIO m => env -> RIO env a -> m a runRIO env (RIO (ReaderT f)) = liftIO (f env) instance MonadUnliftIO (RIO env) where askUnliftIO = RIO $ ReaderT $ \r -> withUnliftIO $ \u -> return (UnliftIO (unliftIO u . flip runReaderT r . unRIO))
anton-dessiatov/stack
subs/rio/src/RIO/Prelude.hs
bsd-3-clause
7,400
0
16
3,185
1,858
1,174
684
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ja-JP"> <title>AMF Support</title> <maps> <homeID>amf</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/amf/src/main/javahelp/help_ja_JP/helpset_ja_JP.hs
apache-2.0
956
82
52
156
390
206
184
-1
-1
{- Progression-based benchmarks. Progression charts the difference between successive benchmark runs. -} import Criterion.Main hiding (defaultMain, defaultMainWith) import Progression.Main import System.Environment (withArgs) import qualified HledgerMain main = defaultMain $ bench "balance_100x100x10" $ nfIO $ withArgs ["balance", "-f", "100x100x10.ledger", ">/dev/null"] HledgerMain.main
adept/hledger
tools/progressionbench.hs
gpl-3.0
401
1
8
50
77
43
34
6
1
-- From the GHC users mailing list, 3/9/14 {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} module Sock where import Data.Proxy import Data.Kind data Message data SocketType = Dealer | Push | Pull data SocketOperation = Read | Write data SockOp :: SocketType -> SocketOperation -> Type where SRead :: Foo 'Read sock => SockOp sock 'Read SWrite :: Foo Write sock => SockOp sock Write data Socket :: SocketType -> Type where Socket :: proxy sock -> (forall op . Foo op sock => SockOp sock op -> Operation op) -> Socket sock type family Foo (op :: SocketOperation) (s :: SocketType) :: Constraint where Foo 'Read s = Readable s Foo Write s = Writable s type family Operation (op :: SocketOperation) :: Type where Operation 'Read = IO Message Operation Write = Message -> IO () type family Readable (t :: SocketType) :: Constraint where Readable Dealer = () Readable Pull = () type family Writable (t :: SocketType) :: Constraint where Writable Dealer = () Writable Push = () dealer :: Socket Dealer dealer = undefined push :: Socket Push push = undefined pull :: Socket Pull pull = undefined readSocket :: forall sock . Readable sock => Socket sock -> IO Message readSocket (Socket _ f) = f (SRead :: SockOp sock 'Read)
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/Sock.hs
bsd-3-clause
1,427
0
12
315
430
237
193
-1
-1
module TestImport ( module TestImport , module X ) where import Application (makeFoundation) import ClassyPrelude as X import Database.Persist as X hiding (get) import Database.Persist.Sql (SqlPersistM, runSqlPersistMPool) import Foundation as X import Model as X import Test.Hspec as X import Yesod.Default.Config2 (ignoreEnv, loadAppSettings) import Yesod.Test as X runDB :: SqlPersistM a -> YesodExample App a runDB query = do pool <- fmap appConnPool getTestYesod liftIO $ runSqlPersistMPool query pool withApp :: SpecWith App -> Spec withApp = before $ do settings <- loadAppSettings ["config/test-settings.yml", "config/settings.yml"] [] ignoreEnv makeFoundation settings
lubomir/dot-race
test/TestImport.hs
bsd-3-clause
806
0
10
217
190
110
80
23
1
-- !!! Re-exporting alias which maps to multiple mods; some qualified. module M where import Mod138_A x = zipWith5 y = isLatin1
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/module/mod138.hs
bsd-3-clause
134
0
4
28
18
12
6
4
1
-- | Compose drawable items into a scene graph. module Iris.SceneGraph ( module X ) where import Iris.SceneGraph.Clipper as X import Iris.SceneGraph.DrawGraph as X import Iris.SceneGraph.DynamicScene as X
jdreaver/iris
src/Iris/SceneGraph.hs
mit
221
0
4
44
37
27
10
5
0
-- | -- Module: Math.NumberTheory.Recurrencies.BilinearTests -- Copyright: (c) 2016 Andrew Lelechenko -- Licence: MIT -- Maintainer: Andrew Lelechenko <andrew.lelechenko@gmail.com> -- Stability: Provisional -- -- Tests for Math.NumberTheory.Recurrencies.Bilinear -- {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Math.NumberTheory.Recurrencies.BilinearTests ( testSuite ) where import Test.Tasty import Test.Tasty.HUnit import Data.Ratio import Math.NumberTheory.Recurrencies.Bilinear import Math.NumberTheory.TestUtils binomialProperty1 :: NonNegative Int -> Bool binomialProperty1 (NonNegative i) = length (binomial !! i) == i + 1 binomialProperty2 :: NonNegative Int -> Bool binomialProperty2 (NonNegative i) = binomial !! i !! 0 == 1 binomialProperty3 :: NonNegative Int -> Bool binomialProperty3 (NonNegative i) = binomial !! i !! i == 1 binomialProperty4 :: Positive Int -> Positive Int -> Bool binomialProperty4 (Positive i) (Positive j) = j >= i || binomial !! i !! j == binomial !! (i - 1) !! (j - 1) + binomial !! (i - 1) !! j stirling1Property1 :: NonNegative Int -> Bool stirling1Property1 (NonNegative i) = length (stirling1 !! i) == i + 1 stirling1Property2 :: NonNegative Int -> Bool stirling1Property2 (NonNegative i) = stirling1 !! i !! 0 == if i == 0 then 1 else 0 stirling1Property3 :: NonNegative Int -> Bool stirling1Property3 (NonNegative i) = stirling1 !! i !! i == 1 stirling1Property4 :: Positive Int -> Positive Int -> Bool stirling1Property4 (Positive i) (Positive j) = j >= i || stirling1 !! i !! j == stirling1 !! (i - 1) !! (j - 1) + (toInteger i - 1) * stirling1 !! (i - 1) !! j stirling2Property1 :: NonNegative Int -> Bool stirling2Property1 (NonNegative i) = length (stirling2 !! i) == i + 1 stirling2Property2 :: NonNegative Int -> Bool stirling2Property2 (NonNegative i) = stirling2 !! i !! 0 == if i == 0 then 1 else 0 stirling2Property3 :: NonNegative Int -> Bool stirling2Property3 (NonNegative i) = stirling2 !! i !! i == 1 stirling2Property4 :: Positive Int -> Positive Int -> Bool stirling2Property4 (Positive i) (Positive j) = j >= i || stirling2 !! i !! j == stirling2 !! (i - 1) !! (j - 1) + toInteger j * stirling2 !! (i - 1) !! j lahProperty1 :: NonNegative Int -> Bool lahProperty1 (NonNegative i) = length (lah !! i) == i + 1 lahProperty2 :: NonNegative Int -> Bool lahProperty2 (NonNegative i) = lah !! i !! 0 == product [1 .. i+1] lahProperty3 :: NonNegative Int -> Bool lahProperty3 (NonNegative i) = lah !! i !! i == 1 lahProperty4 :: Positive Int -> Positive Int -> Bool lahProperty4 (Positive i) (Positive j) = j >= i || lah !! i !! j == sum [ stirling1 !! (i + 1) !! k * stirling2 !! k !! (j + 1) | k <- [j + 1 .. i + 1] ] eulerian1Property1 :: NonNegative Int -> Bool eulerian1Property1 (NonNegative i) = length (eulerian1 !! i) == i eulerian1Property2 :: Positive Int -> Bool eulerian1Property2 (Positive i) = eulerian1 !! i !! 0 == 1 eulerian1Property3 :: Positive Int -> Bool eulerian1Property3 (Positive i) = eulerian1 !! i !! (i - 1) == 1 eulerian1Property4 :: Positive Int -> Positive Int -> Bool eulerian1Property4 (Positive i) (Positive j) = j >= i - 1 || eulerian1 !! i !! j == (toInteger $ i - j) * eulerian1 !! (i - 1) !! (j - 1) + (toInteger j + 1) * eulerian1 !! (i - 1) !! j eulerian2Property1 :: NonNegative Int -> Bool eulerian2Property1 (NonNegative i) = length (eulerian2 !! i) == i eulerian2Property2 :: Positive Int -> Bool eulerian2Property2 (Positive i) = eulerian2 !! i !! 0 == 1 eulerian2Property3 :: Positive Int -> Bool eulerian2Property3 (Positive i) = eulerian2 !! i !! (i - 1) == product [1 .. toInteger i] eulerian2Property4 :: Positive Int -> Positive Int -> Bool eulerian2Property4 (Positive i) (Positive j) = j >= i - 1 || eulerian2 !! i !! j == (toInteger $ 2 * i - j - 1) * eulerian2 !! (i - 1) !! (j - 1) + (toInteger j + 1) * eulerian2 !! (i - 1) !! j bernoulliSpecialCase1 :: Assertion bernoulliSpecialCase1 = assertEqual "B_0 = 1" (bernoulli !! 0) 1 bernoulliSpecialCase2 :: Assertion bernoulliSpecialCase2 = assertEqual "B_1 = -1/2" (bernoulli !! 1) (- 1 % 2) bernoulliProperty1 :: NonNegative Int -> Bool bernoulliProperty1 (NonNegative m) = case signum (bernoulli !! m) of 1 -> m == 0 || m `mod` 4 == 2 0 -> m /= 1 && odd m -1 -> m == 1 || (m /= 0 && m `mod` 4 == 0) _ -> False bernoulliProperty2 :: NonNegative Int -> Bool bernoulliProperty2 (NonNegative m) = bernoulli !! m == (if m == 0 then 1 else 0) - sum [ bernoulli !! k * (binomial !! m !! k % (toInteger $ m - k + 1)) | k <- [0 .. m - 1] ] testSuite :: TestTree testSuite = testGroup "Bilinear" [ testGroup "binomial" [ testSmallAndQuick "shape" binomialProperty1 , testSmallAndQuick "left side" binomialProperty2 , testSmallAndQuick "right side" binomialProperty3 , testSmallAndQuick "recurrency" binomialProperty4 ] , testGroup "stirling1" [ testSmallAndQuick "shape" stirling1Property1 , testSmallAndQuick "left side" stirling1Property2 , testSmallAndQuick "right side" stirling1Property3 , testSmallAndQuick "recurrency" stirling1Property4 ] , testGroup "stirling2" [ testSmallAndQuick "shape" stirling2Property1 , testSmallAndQuick "left side" stirling2Property2 , testSmallAndQuick "right side" stirling2Property3 , testSmallAndQuick "recurrency" stirling2Property4 ] , testGroup "lah" [ testSmallAndQuick "shape" lahProperty1 , testSmallAndQuick "left side" lahProperty2 , testSmallAndQuick "right side" lahProperty3 , testSmallAndQuick "zip stirlings" lahProperty4 ] , testGroup "eulerian1" [ testSmallAndQuick "shape" eulerian1Property1 , testSmallAndQuick "left side" eulerian1Property2 , testSmallAndQuick "right side" eulerian1Property3 , testSmallAndQuick "recurrency" eulerian1Property4 ] , testGroup "eulerian2" [ testSmallAndQuick "shape" eulerian2Property1 , testSmallAndQuick "left side" eulerian2Property2 , testSmallAndQuick "right side" eulerian2Property3 , testSmallAndQuick "recurrency" eulerian2Property4 ] , testGroup "bernoulli" [ testCase "B_0" bernoulliSpecialCase1 , testCase "B_1" bernoulliSpecialCase2 , testSmallAndQuick "sign" bernoulliProperty1 , testSmallAndQuick "recursive definition" bernoulliProperty2 ] ]
cfredric/arithmoi
test-suite/Math/NumberTheory/Recurrencies/BilinearTests.hs
mit
6,566
0
17
1,436
2,146
1,104
1,042
143
4
{-# OPTIONS_GHC -XFlexibleInstances #-} module SetADT ( Set , empty , sing , memSet , union, inter, diff , eqSet , subSet , makeSet , mapSet , filterSet , foldSet , showSet , card , symmDiff , powerSet , setUnion , setInter , flatten ) where import Data.List hiding (union) newtype Set a = Set [a] deriving (Show) instance Eq a => Eq (Set a) where (==) = eqSet instance Ord a => Ord (Set a) where (<=) = leqSet empty :: Set a empty = Set [] sing :: a -> Set a sing v = Set [v] memSet :: Ord a => a -> Set a -> Bool memSet _ (Set []) = False memSet v (Set (x : xs)) | v < x = memSet v (Set xs) | v == x = True | otherwise = False union :: Ord a => Set a -> Set a -> Set a union (Set lsa) (Set lsb) = Set (merge lsa lsb) merge :: Ord a => [a] -> [a] -> [a] merge (x : xs) (y : ys) | x < y = x : merge xs (y : ys) | x == y = x : merge xs ys | otherwise = y : merge (x : xs) ys merge [] ys = ys merge xs [] = xs inter :: Ord a => Set a -> Set a -> Set a inter (Set lsa) (Set lsb) = Set (lsit lsa lsb) lsit :: Ord a => [a] -> [a] -> [a] lsit (x : xs) (y : ys) | x < y = lsit xs (y : ys) | x == y = x : lsit xs ys | otherwise = lsit (x : xs) ys lsit _ _ = [] diff :: Ord a => Set a -> Set a -> Set a diff (Set lsa) (Set lsb) = Set (diffls lsa lsb) diffls :: Ord a => [a] -> [a] -> [a] diffls (x : xs) (y : ys) | x < y = x : diffls xs (y : ys) | x == y = diffls xs ys | otherwise = diffls (x : xs) ys diffls [] _ = [] diffls xs [] = xs eqSet :: Eq a => Set a -> Set a -> Bool eqSet (Set xs) (Set ys) = xs == ys leqSet :: Ord a => Set a -> Set a -> Bool leqSet (Set xs) (Set ys) = xs <= ys subSet :: Ord a => Set a -> Set a -> Bool subSet (Set xs) (Set ys) = subLs xs ys subLs :: Ord a => [a] -> [a] -> Bool subLs [] _ = True subLs _ [] = False subLs (x : xs) (y : ys) | x == y = subLs xs ys | x < y = False | otherwise = subLs (x : xs) ys makeSet :: Ord a => [a] -> Set a makeSet = Set . removeEqu . sort where removeEqu :: Ord a => [a] -> [a] removeEqu (x : y : rs) | x == y = removeEqu (x : rs) | otherwise = x : removeEqu (y : rs) removeEqu other = other mapSet :: Ord b => (a -> b) -> Set a -> Set b mapSet f (Set as) = (makeSet . map f) as filterSet :: (a -> Bool) -> Set a -> Set a filterSet f (Set as) = (Set . filter f) as foldSet :: (a -> b -> b) -> b -> Set a -> b foldSet f x (Set as) = foldr f x as showSet :: (a -> String) -> Set a -> String showSet f (Set xs) = (unlines . map f) xs card :: Set a -> Int card (Set xs) = length xs symmDiff :: Ord a => Set a -> Set a -> Set a symmDiff sa sb = diff sa sb `union` diff sb sa powerSet :: Ord a => Set a -> Set (Set a) powerSet (Set []) = Set [Set []] powerSet (Set (x : xs)) = powerSet (Set xs) `union` mapSet (union (Set [x])) (powerSet (Set xs)) setUnion :: Ord a => Set (Set a) -> Set a setUnion = foldSet union empty setInter :: Ord a => Set (Set a) -> Set a setInter = foldSet inter empty flatten :: Set a -> [a] flatten (Set xs ) = xs
tonyfloatersu/solution-haskell-craft-of-FP
SetADT.hs
mit
3,526
0
11
1,375
1,860
930
930
103
2
module HW01Spec where import Test.Hspec import HW01 spec :: Spec spec = do describe "lastDigit" $ it "should return the last digit" $ do lastDigit 123 `shouldBe` 3 lastDigit 0 `shouldBe` 0 lastDigit 123 `shouldBe` 3 lastDigit 1234 `shouldBe` 4 lastDigit 5 `shouldBe` 5 lastDigit 10 `shouldBe` 0 lastDigit 0 `shouldBe` 0 describe "dropLastDigit" $ it "should return the digits except last" $ do dropLastDigit 123 `shouldBe` 12 dropLastDigit 5 `shouldBe` 0 dropLastDigit 123 `shouldBe` 12 dropLastDigit 1234 `shouldBe` 123 dropLastDigit 5 `shouldBe` 0 dropLastDigit 10 `shouldBe` 1 dropLastDigit 0 `shouldBe` 0 describe "toRevDigits" $ it "should return the digits in reverse order" $ do toRevDigits 123 `shouldBe` [3, 2, 1] toRevDigits 5 `shouldBe` [5] toRevDigits 1234 `shouldBe` [4, 3, 2, 1] toRevDigits 10 `shouldBe` [0, 1] toRevDigits 0 `shouldBe` [] toRevDigits (-17) `shouldBe` [] describe "toDigits" $ it "should return the digits in the right order" $ do toDigits 123 `shouldBe` [1, 2, 3] toDigits 5 `shouldBe` [5] toDigits 1234 `shouldBe` [1, 2, 3, 4] toDigits 10 `shouldBe` [1, 0] toDigits 0 `shouldBe` [] toDigits (-17) `shouldBe` [] describe "doubleEveryOther" $ it "should double every other numbers, starting from the second number" $ do doubleEveryOther [4, 9, 5, 5] `shouldBe` [4, 18, 5, 10] doubleEveryOther [0, 0] `shouldBe` [0, 0] describe "sumDigits" $ it "should sum the digits in the provided list" $ sumDigits [10, 5, 18, 4] `shouldBe` 1 + 0 + 5 + 1 + 8 + 4 describe "luhn" $ it "should return whether a credit card number is valid" $ do luhn 5594589764218858 `shouldBe` True luhn 1234567898765432 `shouldBe` False describe "hanoi" $ it "should return a correct result for the puzzle" $ hanoi 2 "a" "b" "c" `shouldBe` [("a","c"), ("a","b"), ("c","b")] describe "hanoi4" $ it "should return a correct number of moves for a puzzle" $ length (hanoi4 15 "a" "b" "c" "d") `shouldBe` 129
mrordinaire/upenn-haskell
tests/HW01Spec.hs
mit
2,226
0
15
632
755
392
363
56
1
module Config ( Config(..) , Redmine(..) , readConfigFile ) where import Control.Applicative import Data.Aeson import qualified Data.ByteString.Lazy as BS import Data.Traversable (traverse) import System.Exit (exitFailure) import System.IO (hPutStrLn, stderr) data Config = Config { statusUrl :: String , karmaFile :: FilePath , channel :: String , pidDir :: Maybe FilePath , serv :: String , port :: Int , nick :: String , password :: Maybe String , redmine :: Maybe Redmine , mqttHost :: String , pizzaTopic :: String , alarmTopic :: String , soundTopic :: String } data Redmine = Redmine { rmURL :: String , rmProject :: String , rmInterval :: Int , rmUser :: Maybe String , rmPassword :: Maybe String } instance FromJSON Redmine where parseJSON (Object v) = Redmine <$> v .: "url" <*> v .: "project" <*> v .: "interval" <*> v .:? "user" <*> v .:? "password" parseJSON _ = empty instance FromJSON Config where parseJSON (Object v) = Config <$> v .: "statusUrl" <*> v .: "karmaFile" <*> v .: "channel" <*> v .:? "pidDir" <*> v .:? "server" .!= "chat.freenode.net" <*> v .:? "port" .!= 6667 <*> v .:? "nick" .!= "b4ckspace" <*> v .:? "password" <*> (v .:? "redmine" >>= traverse parseJSON) <*> v .: "mqttHost" <*> v .: "pizzaTopic" <*> v .: "alarmTopic" <*> v .: "soundTopic" parseJSON _ = empty readConfigFile :: FilePath -> IO Config readConfigFile path = do config <- BS.readFile path case eitherDecode config of Right cfg -> return cfg Left err -> do hPutStrLn stderr ("Error reading config file: " ++ err) exitFailure
k00mi/bckspc-bot
src/Config.hs
mit
2,518
0
33
1,254
523
285
238
62
2
{-# LANGUAGE QuasiQuotes #-} module AoC201604 ( runDay, ) where import Caesar (caesar) import Data.List (isInfixOf, sortBy) import Data.Map (toList, fromListWith) import Frequency import Language.Haskell.TH import Language.Haskell.TH.Quote import Str import Text.Parsec import Text.Parsec.String runDay :: IO () runDay = do let part1 = executePart1 fullInput let part2 = executePart2 fullInput putStrLn $ "4) The sum of valid rooms is " ++ (show part1) ++ "." putStrLn $ "4) The sector ID of the room where the North Pole objects are is " ++ (show part2) ++ "." type Checksum = String type SectorId = Int data Room = Room { letters :: String, sectorId :: SectorId, checksum :: Checksum } deriving Show -- Part 2 -- Step 1 - steal caesar cipher from http://www.rosettacode.org/wiki/Caesar_cipher#Haskell -- Then... executePart2 :: String -> String executePart2 xs = case parsedRooms xs of Prelude.Left msg -> show msg Prelude.Right rooms -> show $ sectorId $ head $ filterRoomName "northpoleobjectstorage" $ map decryptRoomName $ validRooms rooms filterRoomName :: String -> [Room] -> [Room] filterRoomName s r = filter (\x -> isInfixOf s $ letters x) r decryptRoomName :: Room -> Room decryptRoomName r = let decryptedName = caesar (sectorId r) $ letters r in Room decryptedName (sectorId r) (checksum r) roomNames :: [Room] -> [String] roomNames xs = map letters xs -- Part 1 executePart1 :: String -> String executePart1 xs = case parsedRooms xs of Prelude.Left msg -> show msg Prelude.Right rooms -> show $ sectorSums $ validRooms rooms sectorSums :: [Room] -> Int sectorSums xs = sum $ map sectorId xs validRooms :: [Room] -> [Room] validRooms xs = filter isRoomValid xs isRoomValid :: Room -> Bool isRoomValid r = expectedChecksum r == checksum r expectedChecksum :: Room -> Checksum expectedChecksum r = map (\x -> fst x) $ take 5 $ frequencySort $ letterFrequency $ letters r -- Parsers parsedRooms :: String -> Either ParseError [Room] parsedRooms xs = parse roomsParser "test" xs roomsParser :: Parser [Room] roomsParser = do r <- many1 roomParser return r roomParser :: Parser Room roomParser = do optional spaces l <- many1 lettersParser s <- many1 digit char '[' c <- many1 letter char ']' optional endOfLine return $ Room (concat l) (read s :: Int) c lettersParser :: Parser String lettersParser = do s <- many1 letter optional $ char '-' return s -- Input data cipherTestInput :: String cipherTestInput = [str|qzmt-zixmtkozy-ivhz-343[whatever]|] smallInput :: String smallInput = [str|aaaaa-bbb-z-y-x-123[abxyz] a-b-c-d-e-f-g-h-987[abcde] not-a-real-room-404[oarel] totally-real-room-200[decoy]|] fullInput :: String fullInput = [str|gbc-frperg-pubpbyngr-znantrzrag-377[rgbnp] nij-mywlyn-wlsiayhcw-jfumncw-alumm-mbcjjcha-422[mcjwa] pualyuhapvuhs-ibuuf-zhslz-227[uhalp] xlrypetn-prr-lylwjdtd-665[dzoya] zilqwikbqdm-rmttgjmiv-mvoqvmmzqvo-278[mqvio] rgllk-bxmefuo-sdmee-geqd-fqefuzs-274[efdgl] ugfkmewj-yjsvw-wyy-lwuzfgdgyq-814[wygfj] lnkfaypeha-xwogap-bejwjyejc-524[uqzms] laffe-sorozgxe-mxgjk-jek-xkykgxin-254[kxegf] ytu-xjhwjy-hfsid-htfynsl-qtlnxynhx-411[hyntx] vetllbybxw-xzz-mktbgbgz-709[kblty] ixeumktoi-kmm-giwaoyozout-176[oimkt] frqvxphu-judgh-udpsdjlqj-udeelw-uhvhdufk-647[ntbsq] ixccb-hjj-uhvhdufk-725[hcjub] sehheiylu-isqludwuh-xkdj-qsgkyiyjyed-634[ydehi] yhwooebeaz-acc-ajcejaanejc-316[acejo] qyujihctyx-vumeyn-zchuhwcha-318[hcuya] xtwtelcj-rclop-clmmte-nzyeltyxpye-171[eltcy] pinovwgz-mvwwdo-yzkgjthzio-941[owzgi] htwwtxnaj-xhfajsljw-mzsy-hzxytrjw-xjwanhj-229[jwhxa] amlqskcp-epybc-cee-pcyaosgqgrgml-652[cegpa] fab-eqodqf-omzpk-emxqe-560[eqfmo] bnmrtldq-fqzcd-idkkxadzm-qdrdzqbg-365[dqzbk] ovbunmneqbhf-wryylorna-qrirybczrag-559[rbnya] ynukcajey-xwogap-iwjwcaiajp-966[jydme] dkqjcbctfqwu-uecxgpigt-jwpv-fgrctvogpv-128[cgptv] ugfkmewj-yjsvw-tmffq-vwhdgqewfl-606[zfmlc] htqtwkzq-idj-ijxnls-723[rwmzt] kgjgrypw-epybc-aylbw-amyrgle-amlryglkclr-184[lygra] jxdkbqfz-yrkkv-bkdfkbbofkd-705[csxut] ujqgywfau-uzgugdslw-sfsdqkak-684[duboh] rwcnawjcrxwju-mhn-nwprwnnarwp-823[wnrac] eqttqukxg-rncuvke-itcuu-ujkrrkpi-102[ukrtc] jvuzbtly-nyhkl-ibuuf-dvyrzovw-201[uvybl] tvsnigxmpi-fewoix-wxsveki-750[ixesv] rtqlgevkng-ejqeqncvg-ncdqtcvqta-336[prlxq] wfummczcyx-luvvcn-nywbhifias-864[cfimn] irdgrxzex-vxx-nfibjyfg-763[xfgir] buzahisl-ipvohghykvbz-qlssfilhu-klclsvwtlua-591[moyzp] dpotvnfs-hsbef-sbnqbhjoh-fhh-nbobhfnfou-831[vbmns] owshgfarwv-lgh-kwujwl-usfvq-ghwjslagfk-164[wgfhl] yuxufmdk-sdmpq-bxmefuo-sdmee-dqeqmdot-222[dmequ] clotzlnetgp-clmmte-opawzjxpye-873[elptc] mfklstdw-usfvq-kwjnauwk-268[kwfsu] vhglnfxk-zktwx-unggr-xgzbgxxkbgz-839[gxkzb] yrwxefpi-tpewxmg-kveww-ywiv-xiwxmrk-932[pxhgu] shmml-cynfgvp-tenff-qrfvta-143[fmntv] zhdsrqlchg-sodvwlf-judvv-uhdftxlvlwlrq-855[ldvhf] kfg-jvtivk-sleep-uvjzxe-711[evjkf] molgbzqfib-yxphbq-obpbxoze-757[bopqx] qfmcusbwq-qobrm-qcohwbu-fsoqeiwgwhwcb-168[qwbco] sbejpbdujwf-gmpxfs-tupsbhf-623[bfpsj] jsehsyafy-hdsklau-yjskk-ksdwk-242[ksyad] rwcnawjcrxwju-ljwmh-bcxajpn-823[jwcan] excdklvo-oqq-oxqsxoobsxq-874[oqxsb] buzahisl-jhukf-jvhapun-klwsvftlua-565[uahlf] gpbepvxcv-snt-steadnbtci-453[tbcen] wyvqljapsl-ihzrla-zlycpjlz-149[lzajp] amlqskcp-epybc-cee-kylyeckclr-938[cekly] jchipqat-qphzti-advxhixrh-895[hiapq] tinnm-qvcqczohs-qighcasf-gsfjwqs-818[jfuek] qyujihctyx-mwupyhayl-bohn-wihnuchgyhn-890[hynuc] wlqqp-nvrgfezqvu-irsszk-ivjvrity-607[viqrs] molgbzqfib-avb-cfkxkzfkd-315[bfkza] luxciuwncpy-wuhxs-womnigyl-mylpcwy-266[ylhtr] ugdgjxmd-bwddqtwsf-ugflsafewfl-762[qdtes] fmsledevhsyw-nippcfier-eguymwmxmsr-438[vmsip] xekdwvwnzkqo-xwogap-ajcejaanejc-706[aejwc] wfummczcyx-yaa-fiacmncwm-136[bxsio] rdadguja-tvv-ldgzhwde-375[dagve] wsvsdkbi-qbkno-oqq-domrxyvyqi-718[qobdi] oaxadrgx-qss-oazfmuzyqzf-300[mfedb] hqfxxnknji-uqfxynh-lwfxx-xfqjx-125[zkwtx] gpbepvxcv-qphzti-rdcipxcbtci-947[cpibt] etyyx-bzmcx-bnzshmf-qdrdzqbg-443[btyez] htqtwkzq-gzssd-qfgtwfytwd-541[ogntm] uiovmbqk-kpwkwtibm-mvoqvmmzqvo-798[awevt] zotts-vumeyn-xypyfijgyhn-448[qasni] zovldbkfz-pzxsbkdbo-erkq-xznrfpfqflk-367[eunpo] htwwtxnaj-gntmfefwitzx-hfsid-htfynsl-zxjw-yjxynsl-255[tfnwx] vhglnfxk-zktwx-vahvhetmx-labiibgz-839[hvxab] htqtwkzq-idj-wjhjnansl-983[rmtzn] irgyyolokj-vrgyzoi-mxgyy-aykx-zkyzotm-358[yogkz] ktfitzbgz-lvtoxgzxk-angm-wxitkmfxgm-943[vxmua] uwtojhynqj-hmthtqfyj-jslnsjjwnsl-879[jhnst] mrxivrexmsrep-gerhc-gsexmrk-hiwmkr-100[yzpuo] hdgdovmt-bmvyz-ezggtwzvi-adivixdib-707[divgz] lqwhuqdwlrqdo-iorzhu-ghvljq-959[qhldo] vhkkhlbox-wrx-inkvatlbgz-397[kbhlv] tyepcyletzylw-awldetn-rcldd-dezclrp-795[ldect] sedikcuh-whqtu-uww-tufqhjcudj-946[uhwcd] lsyrkjkbnyec-zvkcdsm-qbkcc-myxdksxwoxd-848[kcdsx] fnjyxwrinm-lqxlxujcn-mnyjacvnwc-355[ncjxl] gpbepvxcv-tvv-rdcipxcbtci-141[cvpbi] xgsvgmotm-hgyqkz-ykxboiky-124[gkymo] udskkaxawv-usfvq-esjcwlafy-814[uidxk] fydelmwp-nlyoj-opalcexpye-899[elpyo] aczupnetwp-qwzhpc-afcnsldtyr-717[cpant] bknsykmdsfo-nio-yzobkdsyxc-926[kosyb] xjmmjndqz-xcjxjgvoz-mzvxlpdndodji-343[fqvmn] amjmpdsj-qaytclecp-fslr-bcqgel-782[claej] fnjyxwrinm-ouxfna-anjlzdrbrcrxw-719[nrxaf] qcbgiasf-ufors-pogysh-zcuwghwqg-168[gscfh] kmjezxodgz-wpiit-mzxzdqdib-109[aypcu] ckgvutofkj-xghhoz-uvkxgzouty-696[ajsic] lsyrkjkbnyec-mkxni-cdybkqo-510[kybcn] tipfxvezt-gcrjkzt-xirjj-jvimztvj-919[pofxi] pbybeshy-cynfgvp-tenff-svanapvat-403[afnpv] cjpibabsepvt-cvooz-usbjojoh-155[objcp] jvyyvzpcl-lnn-ayhpupun-929[npylu] wsvsdkbi-qbkno-zvkcdsm-qbkcc-oxqsxoobsxq-276[sbkoq] ugdgjxmd-usfvq-ugslafy-ugflsafewfl-918[xbmpo] nwlddtqtpo-ojp-xlcvpetyr-639[ptdlo] nzcczdtgp-prr-opdtry-587[wsiym] ynssr-yehpxk-wxlbzg-111[plhnx] xjmmjndqz-xcjxjgvoz-xjiovdihzio-967[jxioz] enqvbnpgvir-pubpbyngr-znexrgvat-585[qtsjn] gvcskirmg-qekrixmg-ikk-xvemrmrk-126[kmrgi] gpbepvxcv-uadltg-ejgrwphxcv-921[gpvce] kmjezxodgz-nxvqzibzm-cpio-adivixdib-941[izdxb] hcd-gsqfsh-xszzmpsob-sbuwbssfwbu-428[sbfhu] nwlddtqtpo-upwwjmply-dpcgtnpd-119[pdtwl] mbggf-msvdly-zlycpjlz-929[aonev] lhkhszqx-fqzcd-qzaahs-btrsnldq-rdquhbd-443[qdhsz] luxciuwncpy-xsy-uwkocmcncih-500[cuinw] qvbmzvibqwvit-kpwkwtibm-zmkmqdqvo-564[mqvbi] tvsnigxmpi-jpsaiv-irkmriivmrk-568[yileu] vxupkizork-kmm-lotgtiotm-748[xymrs] gpewwmjmih-gerhc-hiwmkr-152[lostk] ibghopzs-gqojsbusf-vibh-rsgwub-818[bsghi] guahyncw-luvvcn-wihnuchgyhn-552[hncug] iruzfrtkzmv-treup-tfrkzex-ivjvrity-373[rtivz] dsxxw-cee-ylyjwqgq-704[eqwxy] lhkhszqx-fqzcd-eknvdq-lzmzfdldms-911[dzlqf] oxmeeuruqp-omzpk-oamfuzs-emxqe-248[emoup] dyz-combod-mkxni-mykdsxq-vklybkdybi-848[dkybm] bpvctixr-qphzti-ldgzhwde-999[abmop] kwvacumz-ozilm-jiasmb-mvoqvmmzqvo-824[tnqvi] njmjubsz-hsbef-kfmmzcfbo-nbobhfnfou-389[luxhg] hwbba-fag-tgceswkukvkqp-622[kabgw] nchhg-jiasmb-lmxizbumvb-382[bmhia] ymszqfuo-dmnnuf-emxqe-170[syxpj] ymszqfuo-qss-abqdmfuaze-144[qsafm] tcfkqcevkxg-hwbba-hnqygt-vtckpkpi-440[kctbg] zloolpfsb-gbiivybxk-rpbo-qbpqfkd-705[bopfi] slqryzjc-pyzzgr-rpyglgle-288[uanmz] iutyaskx-mxgjk-inuiurgzk-rumoyzoiy-696[klmzy] dpssptjwf-cvooz-efqmpznfou-311[fopsz] dsxxw-cee-dglylagle-756[eldgx] nwlddtqtpo-upwwjmply-xlcvpetyr-223[pltwd] jvuzbtly-nyhkl-lnn-lunpullypun-201[tqlba] uiovmbqk-kivlg-bmkpvwtwog-720[kpvsu] nchhg-xtiabqk-oziaa-zmamizkp-850[aizhk] molgbzqfib-zixppfcfba-gbiivybxk-pqloxdb-237[igmjz] jyfvnlupj-jhukf-jvhapun-yljlpcpun-539[dmnws] hqtyeqsjylu-sqdto-tufqhjcudj-712[cnysz] gsvvswmzi-gerhc-gsrxemrqirx-100[dlypm] ktwbhtvmbox-xzz-vhgmtbgfxgm-709[bgmtx] hjgbwuladw-uzgugdslw-vwhsjlewfl-580[wlgud] njmjubsz-hsbef-kfmmzcfbo-efqmpznfou-181[subnv] bnknqetk-bzmcx-zbpthrhshnm-417[bhnkm] gspsvjyp-fyrrc-jmrergmrk-126[rgjmp] bjfutsneji-gntmfefwitzx-kqtbjw-fhvznxnynts-307[ntfjb] sedikcuh-whqtu-rqiauj-tuiywd-270[gipnv] hjgbwuladw-bwddqtwsf-jwsuimakalagf-294[wadbf] encuukhkgf-uecxgpigt-jwpv-rwtejcukpi-986[ucegk] nzydfxpc-rclop-nlyoj-nzletyr-zapcletzyd-847[lyzcn] eqpuwogt-itcfg-lgnnadgcp-tgceswkukvkqp-518[gckpt] nzwzcqfw-mldvpe-afcnsldtyr-171[cdfln] ide-htrgti-snt-advxhixrh-401[hitdr] fmsledevhsyw-gerhc-gsexmrk-erepcwmw-776[emrsw] jvyyvzpcl-yhiipa-aljouvsvnf-201[vyaij] chnylhuncihuf-zfiqyl-mniluay-656[hilnu] udskkaxawv-xdgowj-klgjsyw-346[eruiv] pbeebfvir-sybjre-qrcnegzrag-585[erbga] aoubshwq-qobrm-obozmgwg-948[obgmq] jvsvymbs-ibuuf-huhsfzpz-747[subfh] qvbmzvibqwvit-jiasmb-ikycqaqbqwv-928[qbiva] zuv-ykixkz-kmm-jkyomt-748[kmyzi] slqryzjc-zsllw-amlryglkclr-808[lrcsy] enzcntvat-enoovg-ybtvfgvpf-273[vntef] iqmbazulqp-dmnnuf-oazfmuzyqzf-664[zfmqu] yaxsnlcrun-ouxfna-uxprbcrlb-537[nruxa] ovbunmneqbhf-cynfgvp-tenff-ratvarrevat-351[uakpm] qzchnzbshud-idkkxadzm-rghoohmf-885[hdzkm] fodvvlilhg-sodvwlf-judvv-fxvwrphu-vhuylfh-101[vfhld] qvbmzvibqwvit-kpwkwtibm-apqxxqvo-798[qvbiw] aoubshwq-pwcvonofrcig-rms-aofyshwbu-688[oswab] hwbba-gii-fgrnqaogpv-882[gabif] pkl-oaynap-acc-pnwejejc-186[acpej] ltpedcxots-qphzti-ejgrwphxcv-323[ptceh] mybbycsfo-nio-nofovyzwoxd-250[stdkc] bgmxkgtmbhgte-ietlmbv-zktll-inkvatlbgz-397[ptrnf] dpotvnfs-hsbef-dipdpmbuf-qvsdibtjoh-545[dbfps] fmsledevhsyw-veqtekmrk-tpewxmg-kveww-hitevxqirx-568[evwkm] ykjoqian-cnwza-ywjzu-ykwpejc-wymqeoepekj-628[hmfzu] wihmogyl-aluxy-vumeyn-jolwbumcha-240[lmuya] yuxufmdk-sdmpq-eomhqzsqd-tgzf-emxqe-664[mqdef] wifilzof-vumeyn-guhuaygyhn-864[uyfgh] hplazytkpo-nlyoj-cpdplcns-457[plcno] vhglnfxk-zktwx-utldxm-hixktmbhgl-917[tursp] jxdkbqfz-zxkav-zlxqfkd-pxibp-133[xkzbd] mfklstdw-xdgowj-jwuwanafy-554[wadfj] eqttqukxg-tcddkv-vtckpkpi-596[ampxv] tpspahyf-nyhkl-jovjvshal-mpuhujpun-591[fkeyj] vqr-ugetgv-ecpfa-eqcvkpi-ujkrrkpi-414[ekprv] mvkccspson-bkllsd-nozvyiwoxd-952[oscdk] ugjjgkanw-ugfkmewj-yjsvw-bwddqtwsf-kwjnauwk-528[nkliy] wkqxodsm-lexxi-myxdksxwoxd-848[xdkmo] tfiifjzmv-tyftfcrkv-jyzggzex-841[unmyd] wdjcvuvmyjpn-rzvkjiduzy-mvwwdo-adivixdib-421[dvijw] xzwrmkbqtm-jcvvg-amzdqkma-226[uonyt] tvsnigxmpi-mrxivrexmsrep-veffmx-xvemrmrk-308[mrxev] iehepwnu-cnwza-nwxxep-owhao-420[wenah] fubrjhqlf-edvnhw-wudlqlqj-725[lqdfh] wfummczcyx-wuhxs-mniluay-370[cbijt] jchipqat-eaphixr-vgphh-sthxvc-895[hpaci] pelbtravp-ohaal-hfre-grfgvat-169[arefg] jshzzpmplk-jhukf-aljouvsvnf-279[jfhkl] hwbba-ejqeqncvg-ocpcigogpv-128[cgbeo] fnjyxwrinm-ajkkrc-cajrwrwp-745[rjwac] mhi-lxvkxm-utldxm-tgterlbl-267[lmtxb] jxdkbqfz-bdd-pqloxdb-237[dbqxf] qfkkj-nzydfxpc-rclop-clmmte-xlylrpxpye-197[vzyuc] bxaxipgn-vgpst-qxdwpopgsdjh-ytaanqtpc-hwxeexcv-687[csdop] rdggdhxkt-eaphixr-vgphh-itrwcdadvn-245[dhgra] qlm-pbzobq-zxkav-zlxqfkd-obzbfsfkd-471[bzfkq] ajyqqgdgcb-qaytclecp-fslr-sqcp-rcqrgle-106[cqglr] zgmfyxypbmsq-aylbw-amyrgle-qfgnngle-704[jmbna] pkl-oaynap-acc-zalhkuiajp-654[apckl] bqxnfdmhb-okzrshb-fqzrr-btrsnldq-rdquhbd-599[nszgr] mybbycsfo-mkxni-mykdsxq-cobfsmoc-302[mbcos] ujoon-eaphixr-vgphh-ldgzhwde-141[hdego] iuxxuyobk-hatte-lotgtiotm-852[toiux] muqfedyput-rkddo-huqsgkyiyjyed-608[dyuek] mrxivrexmsrep-ikk-irkmriivmrk-230[rikme] htqtwkzq-wfggny-ywfnsnsl-749[nwfgq] sno-rdbqds-idkkxadzm-trdq-sdrshmf-599[dsrkm] apuut-wpiit-gvwjmvojmt-369[tijmp] molgbzqfib-yxphbq-tlohpelm-133[blhmo] ugdgjxmd-wyy-hmjuzskafy-866[ydgjm] slqryzjc-hcjjwzcyl-dglylagle-860[lcjyg] ktwbhtvmbox-wrx-etuhktmhkr-241[psbxd] oaddaeuhq-otaoaxmfq-ruzmzouzs-950[aouzd] ugfkmewj-yjsvw-tmffq-klgjsyw-528[sqogh] vrurcjah-pajmn-ajvyjprwp-ljwmh-anlnrerwp-433[jkstx] fab-eqodqf-vqxxknqmz-ymdwqfuzs-586[qfdmx] tpspahyf-nyhkl-kfl-klwhyatlua-123[lahky] zntargvp-enoovg-znexrgvat-195[gnvae] dkqjcbctfqwu-uecxgpigt-jwpv-ugtxkegu-934[gucte] owshgfarwv-xdgowj-jwkwsjuz-320[wjgos] gifavtkzcv-treup-jyzggzex-659[gzetv] bjfutsneji-gfxpjy-tujwfyntsx-203[jftns] pxtihgbsxw-ietlmbv-zktll-ybgtgvbgz-371[bgtli] crwwv-zxkav-pefmmfkd-367[fkmvw] sbqiiyvyut-fbqijys-whqii-tulubefcudj-998[xytos] gvcskirmg-gsvvswmzi-fewoix-pskmwxmgw-230[gmswi] eqttqukxg-ejqeqncvg-octmgvkpi-232[qegtc] lqwhuqdwlrqdo-fdqgb-zrunvkrs-439[qdrlu] tinnm-gqojsbusf-vibh-gozsg-480[gsbin] lujbbrornm-ljwmh-orwjwlrwp-849[rwjlb] jef-iushuj-rkddo-efuhqjyedi-868[dejuf] szfyrqriuflj-treup-jrcvj-971[slkjz] ltpedcxots-rpcsn-itrwcdadvn-921[cdtnp] ohmnuvfy-xsy-jolwbumcha-968[hmouy] gntmfefwitzx-wfintfhynaj-uqfxynh-lwfxx-wjhjnansl-905[fnwxh] xcitgcpixdcpa-tvv-hwxeexcv-271[cxvei] jyfvnlupj-qlssfilhu-ayhpupun-227[zbydk] wdjcvuvmyjpn-zbb-vxlpdndodji-291[djvbn] wfummczcyx-dyffsvyuh-xymcah-630[ycfmh] cebwrpgvyr-wryylorna-phfgbzre-freivpr-897[opgba] cjpibabsepvt-tdbwfohfs-ivou-fohjoffsjoh-363[fobhj] zekvierkzferc-jtrmvexvi-ylek-wzeretzex-425[erzkv] sgmtkzoi-pkrrehkgt-ygrky-228[kgrty] iruzfrtkzmv-jtrmvexvi-ylek-jkfirxv-971[nvfye] dfcxsqhwzs-pogysh-obozmgwg-870[goshw] yuxufmdk-sdmpq-vqxxknqmz-bgdotmeuzs-326[tidcv] iuxxuyobk-igtje-ygrky-878[mflrz] laffe-igtje-vaxingyotm-800[aefgi] tpspahyf-nyhkl-wshzapj-nyhzz-zhslz-643[hzpsy] diozmivodjivg-xviyt-ozxcijgjbt-473[cmtlp] pyknyegle-njyqrga-epyqq-pcyaosgqgrgml-314[gyqep] bwx-amkzmb-zijjqb-tijwzibwzg-824[egorq] drxevkzt-vxx-uvjzxe-581[xvezd] ktfitzbgz-cxeeruxtg-wxitkmfxgm-761[txgef] htsxzrjw-lwfij-wfggny-ywfnsnsl-801[cjidb] oxmeeuruqp-nmewqf-pqeusz-742[eqump] hqfxxnknji-kzeed-ojqqdgjfs-jslnsjjwnsl-671[jnsqd] pbybeshy-rtt-phfgbzre-freivpr-221[rbepf] pdjqhwlf-edvnhw-xvhu-whvwlqj-231[hwvdj] gcfcnuls-aluxy-vumeyn-lywycpcha-188[cylua] plolwdub-judgh-edvnhw-pdqdjhphqw-699[dhpwj] udpsdjlqj-hjj-pdqdjhphqw-751[jdhpq] amjmpdsj-pyzzgr-qyjcq-886[jmpqy] lahxpnwrl-ljwmh-bqryyrwp-667[tifxe] drxevkzt-avccpsvre-uvgcfpdvek-191[vcedk] xzwrmkbqtm-rmttgjmiv-apqxxqvo-928[lmkgz] eqnqthwn-tcddkv-fgrctvogpv-648[tvcdg] bjfutsneji-ojqqdgjfs-ijajqturjsy-515[jqsfi] sebehvkb-hqrryj-ixyffydw-166[siyrz] zlkprjbo-doxab-mixpqfz-doxpp-jxohbqfkd-783[yjhzq] eza-dpncpe-nsznzwlep-opdtry-821[sdeti] tbxmlkfwba-yxphbq-xkxivpfp-523[slfmk] ucynmlgxcb-hcjjwzcyl-umpiqfmn-548[cmjln] lxwbdvna-pajmn-bljenwpna-qdwc-dbna-cnbcrwp-199[nabwc] eadalsjq-yjsvw-wyy-jwsuimakalagf-892[ajswy] fruurvlyh-mhoobehdq-zrunvkrs-907[rhuov] sbqiiyvyut-vbemuh-sedjqydcudj-686[ltadr] fkqbokxqflkxi-avb-lmboxqflkp-991[kbflq] lhkhszqx-fqzcd-atmmx-kzanqzsnqx-677[qzxah] cebwrpgvyr-hafgnoyr-cynfgvp-tenff-qrcnegzrag-793[rxmql] ajmrxjlcren-cxy-bnlanc-ouxfna-lxwcjrwvnwc-927[cnxaj] hqtyeqsjylu-isqludwuh-xkdj-tulubefcudj-244[udjlq] vdzonmhydc-azrjds-cdudknoldms-157[lzowh] uwtojhynqj-kqtbjw-zxjw-yjxynsl-333[grmkp] myxcewob-qbkno-oqq-ecob-docdsxq-614[oqbcd] rkpqxyib-gbiivybxk-abpfdk-419[bikpx] zlilocri-zelzlixqb-qbzeklildv-497[ucyzj] pinovwgz-xviyt-vivgtndn-499[vingt] gcfcnuls-aluxy-luvvcn-xymcah-318[cluan] sebehvkb-fbqijys-whqii-husuylydw-400[bhisy] rdchjbtg-vgpst-eaphixr-vgphh-rjhidbtg-htgkxrt-323[hgtrp] pualyuhapvuhs-jshzzpmplk-wshzapj-nyhzz-zlycpjlz-175[zphla] atyzghrk-sgmtkzoi-hgyqkz-yzuxgmk-228[gkzyh] ohmnuvfy-mwupyhayl-bohn-yhachyylcha-630[hyacl] oxjmxdfkd-avb-pqloxdb-211[dxboa] iqmbazulqp-bdavqofuxq-omzpk-ruzmzouzs-482[zqumo] zsxyfgqj-gzssd-wjxjfwhm-619[jsfgw] qvbmzvibqwvit-jcvvg-abwziom-512[tcrkb] xgjougizobk-lruckx-aykx-zkyzotm-826[koxzg] bkzrrhehdc-rbzudmfdq-gtms-zmzkxrhr-755[rzdhm] myxcewob-qbkno-cmkfoxqob-rexd-zebmrkcsxq-302[syrvm] zekvierkzferc-treup-tfrkzex-uvgrikdvek-867[ekrvz] cvabijtm-lgm-bziqvqvo-330[vbimq] vhglnfxk-zktwx-ktuubm-vhgmtbgfxgm-553[gkmtx] xst-wigvix-fyrrc-vieguymwmxmsr-490[yentm] ktfitzbgz-fbebmtkr-zktwx-xzz-lmhktzx-111[ztkbx] vdzonmhydc-eknvdq-sqzhmhmf-963[xacdu] dmpuamofuhq-otaoaxmfq-efadmsq-742[amfoq] htqtwkzq-gfxpjy-wjxjfwhm-827[fnred] sbnqbhjoh-xfbqpojafe-cbtlfu-dpoubjonfou-311[kezry] qyujihctyx-vumeyn-lywycpcha-604[ychua] ide-htrgti-tvv-uxcpcrxcv-973[ctvir] bxaxipgn-vgpst-snt-gtprfjxhxixdc-791[xgpti] nbhofujd-dipdpmbuf-dvtupnfs-tfswjdf-363[dfpub] apuut-nxvqzibzm-cpio-mznzvmxc-291[zmcin] uzfqdzmfuazmx-otaoaxmfq-pqhqxabyqzf-768[pzmry] tpspahyf-nyhkl-ibuuf-klwhyatlua-253[xkrsz] iqmbazulqp-vqxxknqmz-efadmsq-950[jrnox] bpvctixr-rpcsn-igpxcxcv-375[cpxir] ytu-xjhwjy-uqfxynh-lwfxx-yjhmstqtld-489[xyhjt] qvbmzvibqwvit-ntwemz-kwvbiqvumvb-720[vbimq] mhi-lxvkxm-ietlmbv-zktll-vnlmhfxk-lxkobvx-553[eusnm] tpspahyf-nyhkl-jhukf-wbyjohzpun-487[hpyfj] avw-zljyla-qlssfilhu-zlycpjlz-929[lzajs] sawlkjevaz-xwogap-skngodkl-290[akglo] xgjougizobk-laffe-lruckx-gtgreyoy-774[goefk] aoubshwq-qobrm-qcohwbu-qighcasf-gsfjwqs-948[qsbho] wifilzof-vumeyn-lyuwkocmcncih-968[avixc] uiovmbqk-xtiabqk-oziaa-mvoqvmmzqvo-382[moqva] sawlkjevaz-oywrajcan-dqjp-lqnydwoejc-342[ajwcd] kfg-jvtivk-jtrmvexvi-ylek-rercpjzj-529[jvekr] houngfgxjuay-igtje-giwaoyozout-228[gouai] gcfcnuls-aluxy-mwupyhayl-bohn-ijyluncihm-916[tacdb] cjpibabsepvt-cvooz-ufdiopmphz-155[pobci] iuxxuyobk-igtje-sgtgmksktz-878[uwcvx] thnulapj-ibuuf-ylzlhyjo-305[sfdnr] xzwrmkbqtm-rmttgjmiv-zmamizkp-434[ifpry] yhwooebeaz-zua-yqopkian-oanreya-680[aoeyn] tfcfiwlc-wcfnvi-wzeretzex-243[cefwi] guahyncw-xsy-uwkocmcncih-864[qsmtb] ovbunmneqbhf-rtt-qrfvta-689[zymsd] rgllk-eomhqzsqd-tgzf-ymdwqfuzs-638[qzdfg] ryexqpqhteki-sqdto-seqjydw-skijecuh-iuhlysu-946[eqshi] avw-zljyla-qlssfilhu-mpuhujpun-383[luahj] pynffvsvrq-onfxrg-znantrzrag-143[nrfag] ikhcxvmbex-xzz-phkdlahi-839[cstrx] mvhkvbdib-wvnfzo-zibdizzmdib-187[bizdv] ipvohghykvbz-wshzapj-nyhzz-huhsfzpz-747[hzpsv] htqtwkzq-hmthtqfyj-ijuqtdrjsy-151[tqhjy] xzz-ftgtzxfxgm-865[tupfq] jyfvnlupj-jhukf-klwhyatlua-747[jydsc] mbiyqoxsm-mkxni-kxkvicsc-510[ikmxc] bgmxkgtmbhgte-ietlmbv-zktll-labiibgz-163[bglti] vdzonmhydc-bqxnfdmhb-rbzudmfdq-gtms-lzmzfdldms-469[arkps] forwcoqhwjs-gqojsbusf-vibh-rsgwub-688[dgqsb] qcffcgwjs-pogysh-qcbhowbasbh-688[bchsf] apuut-xviyt-yzqzgjkhzio-317[zituy] ide-htrgti-qjccn-jhtg-ithixcv-479[itchg] kgjgrypw-epybc-hcjjwzcyl-cleglccpgle-262[qphrv] atyzghrk-lruckx-jkvruesktz-384[krtuz] hqtyeqsjylu-rqiauj-vydqdsydw-998[gqeba] uwtojhynqj-gfxpjy-qfgtwfytwd-177[fjtwy] nglmtuex-xzz-ftgtzxfxgm-839[xgtzf] ncjzrpytn-clmmte-epnsyzwzrj-951[yqksh] gntmfefwitzx-gzssd-htsyfnsrjsy-333[cngmk] qcbgiasf-ufors-qvcqczohs-hfowbwbu-168[bcfoq] wlqqp-gcrjkzt-xirjj-dribvkzex-529[ycrxs] drxevkzt-irdgrxzex-jtrmvexvi-ylek-glityrjzex-321[erxit] ovbunmneqbhf-qlr-znexrgvat-559[nbeqr] bwx-amkzmb-jiasmb-camz-bmabqvo-512[bmazc] vcibutulxiom-vohhs-womnigyl-mylpcwy-838[fczlm] fmsledevhsyw-ikk-hitpscqirx-230[owjnv] ykhknbqh-ywjzu-ykwpejc-odellejc-940[xguqm] nsyjwsfyntsfq-gzssd-uzwhmfxnsl-203[sfnwy] mtzslklcozfd-clmmte-nzyeltyxpye-301[tmlui] dsxxw-cee-kypicrgle-106[ecxdg] ujqgywfau-aflwjfslagfsd-tskcwl-ghwjslagfk-476[fagls] nchhg-jcvvg-mvoqvmmzqvo-642[vmcgh] cjpibabsepvt-tdbwfohfs-ivou-efqmpznfou-831[mvwiq] votubcmf-njmjubsz-hsbef-dboez-dpbujoh-fohjoffsjoh-129[izchs] njmjubsz-hsbef-fhh-nbobhfnfou-337[unims] iwcjapey-lhwopey-cnwoo-hkceopeyo-576[oecpw] ydjuhdqjyedqb-fbqijys-whqii-efuhqjyedi-322[qdijy] bknsykmdsfo-lkcuod-mecdywob-cobfsmo-250[obcdk] sbqiiyvyut-zubboruqd-cqdqwucudj-530[uqbdc] etaqigpke-dcumgv-vgejpqnqia-960[egqai] ykjoqian-cnwza-nwxxep-paydjkhkcu-134[pcdmt] iehepwnu-cnwza-lhwopey-cnwoo-nawymqeoepekj-108[ewnop] vagreangvbany-rtt-phfgbzre-freivpr-221[raegv] surmhfwloh-sodvwlf-judvv-xvhu-whvwlqj-595[vhwlu] qekrixmg-ikk-gywxsqiv-wivzmgi-256[jsykh] sno-rdbqds-bgnbnkzsd-otqbgzrhmf-495[rypqa] guahyncw-vohhs-nywbhifias-214[hains] sno-rdbqds-atmmx-bnmszhmldms-365[posvl] zovldbkfz-zxkav-zlxqfkd-zlkqxfkjbkq-575[zrqmk] ykhknbqh-zua-owhao-888[hakob] xmrrq-vqw-ugflsafewfl-372[isvjx] wdjcvuvmyjpn-wpiit-vxlpdndodji-395[cvdlm] wyvqljapsl-ihzrla-zopwwpun-123[lpwaz] kdijqrbu-tou-husuylydw-816[uvcwx] fhezusjybu-fbqijys-whqii-husuylydw-764[uyhis] jyfvnlupj-kfl-mpuhujpun-773[ujpfl] hafgnoyr-pubpbyngr-nanylfvf-715[nkyzs] jfifqxov-doxab-oxyyfq-absbilmjbkq-341[qmgrk] nij-mywlyn-wuhxs-wiuncha-uwkocmcncih-188[cnwhi] amjmpdsj-afmamjyrc-ylyjwqgq-470[jmayq] rdggdhxkt-eaphixr-vgphh-jhtg-ithixcv-921[yvuxl] ucynmlgxcb-qaytclecp-fslr-dglylagle-184[tudeg] dpmpsgvm-tdbwfohfs-ivou-sfdfjwjoh-363[qhgxy] bqvvu-ykhknbqh-fahhuxawj-wymqeoepekj-498[hekqa] qczcftiz-xszzmpsob-sbuwbssfwbu-818[sbzcf] aietsrmdih-hci-wlmttmrk-360[imthr] xst-wigvix-ikk-qevoixmrk-256[ikxve] nzydfxpc-rclop-nzwzcqfw-mfyyj-opalcexpye-405[cpyfz] frqvxphu-judgh-udeelw-uhdftxlvlwlrq-933[ludhe] jsehsyafy-jsttal-hmjuzskafy-892[sajyf] zbytomdsvo-mrymyvkdo-vyqscdsmc-276[mydos] tcorcikpi-ecpfa-eqcvkpi-fgxgnqrogpv-934[jziot] ytu-xjhwjy-hfsid-wjxjfwhm-905[jhwfx] hjgbwuladw-tmffq-suimakalagf-554[afglm] pyknyegle-zsllw-nspafyqgle-730[leygn] gifavtkzcv-avccpsvre-uvjzxe-607[zhayg] bpvctixr-snt-tcvxcttgxcv-973[vrteq] wyvqljapsl-jovjvshal-zlycpjlz-175[nrwfe] kwzzwaqdm-lgm-aitma-122[amwzd] iqmbazulqp-dmnnuf-qzsuzqqduzs-690[qhzsm] udskkaxawv-xdgowj-xafsfuafy-138[nailf] ipvohghykvbz-wshzapj-nyhzz-yljlpcpun-929[lwyvn] forwcoqhwjs-foppwh-hsqvbczcum-636[chowf] pualyuhapvuhs-msvdly-svnpzapjz-903[pasuv] xgjougizobk-vrgyzoi-mxgyy-xkykgxin-436[tjykb] sedikcuh-whqtu-rkddo-cqdqwucudj-348[brlqi] elrkdcdugrxv-fdqgb-uhfhlylqj-465[dlfgh] mhi-lxvkxm-lvtoxgzxk-angm-ltexl-917[xlmgk] bqvvu-fahhuxawj-yqopkian-oanreya-212[cpdwf] buzahisl-jhukf-thyrlapun-903[hualb] rgllk-oaxadrgx-nmewqf-pqbxakyqzf-690[aqxfg] iuruxlar-irgyyolokj-jek-ynovvotm-488[ohpdn] xmtjbzidx-nxvqzibzm-cpio-yzkgjthzio-811[zixbj] xmrrq-ugfkmewj-yjsvw-usfvq-ugslafy-ghwjslagfk-866[fgsju] yhtwhnpun-wshzapj-nyhzz-vwlyhapvuz-851[hznpw] zgmfyxypbmsq-zyqicr-kypicrgle-340[ycgim] uwtojhynqj-hfsid-htfynsl-wjfhvznxnynts-489[nhfjs] fab-eqodqf-dmnnuf-bgdotmeuzs-196[dfbem] wifilzof-wuhxs-wiuncha-lyuwkocmcncih-578[ciwhu] gspsvjyp-veffmx-pefsvexsvc-516[svefp] yknnkoera-xwogap-bejwjyejc-732[ejakn] nsyjwsfyntsfq-gfxpjy-knsfshnsl-333[sfnyj] fodvvlilhg-gbh-ghvljq-595[vgprj] nuatmlmdpage-bxmefuo-sdmee-emxqe-482[emadu] jvyyvzpcl-msvdly-vwlyhapvuz-903[vylpz] fruurvlyh-iorzhu-vdohv-517[hruvo] houngfgxjuay-hgyqkz-ykxboiky-618[ygkho] gsrwyqiv-kvehi-gerhc-gsexmrk-xiglrspskc-750[grsei] pualyuhapvuhs-qlssfilhu-zhslz-799[hlsua] nwlddtqtpo-nlyoj-nzletyr-opdtry-119[tdlno] fydelmwp-prr-nfdezxpc-dpcgtnp-535[pdcef] qmpmxevc-kvehi-jpsaiv-hizipstqirx-672[ipveh] nzwzcqfw-nlyoj-nzletyr-opawzjxpye-587[znwye] bpvctixr-rwdrdapit-hpath-973[prtad] gzefmnxq-omzpk-oazfmuzyqzf-430[zfmoq] wpuvcdng-hnqygt-vgejpqnqia-102[tmdxr] aoubshwq-foppwh-igsf-hsghwbu-610[tsrzk] wihmogyl-aluxy-mwupyhayl-bohn-mbcjjcha-422[vuypz] cqwdujys-uww-sedjqydcudj-478[djuwc] votubcmf-tdbwfohfs-ivou-sfbdrvjtjujpo-883[fobjt] gpbepvxcv-ytaanqtpc-apqdgpidgn-427[pagcd] bnknqetk-eknvdq-qdrdzqbg-885[qdknb] uwtojhynqj-wfruflnsl-hfsid-wjxjfwhm-541[fjwhl] zhdsrqlchg-fodvvlilhg-gbh-frqwdlqphqw-361[hlqdg] cvabijtm-jcvvg-lmxizbumvb-174[vbmci] fruurvlyh-fdqgb-ghsorbphqw-205[hrbfg] pualyuhapvuhs-msvdly-thyrlapun-279[uahlp] iehepwnu-cnwza-ydkykhwpa-ajcejaanejc-212[oqwrn] bqvvu-xwogap-yqopkian-oanreya-680[ckqtm] ktwbhtvmbox-vahvhetmx-mxvaghehzr-917[hvmtx] uzfqdzmfuazmx-omzpk-oamfuzs-fqotzaxask-274[mnilo] gntmfefwitzx-idj-rfsfljrjsy-931[fjirs] tcrjjzwzvu-tfiifjzmv-tyftfcrkv-vexzevvizex-399[vzfte] oaddaeuhq-vqxxknqmz-qzsuzqqduzs-404[qzdua] sorozgxe-mxgjk-yigbktmkx-natz-zxgototm-514[hejid] eadalsjq-yjsvw-ujqgywfau-tskcwl-kwjnauwk-554[wajks] lxuxaodu-rwcnawjcrxwju-ljwmh-fxatbqxy-693[xwaju] plolwdub-judgh-fdqgb-frdwlqj-vdohv-153[dlbfg] kdijqrbu-jef-iushuj-sqdto-seqjydw-kiuh-juijydw-218[iqtvx] tfejldvi-xiruv-tfcfiwlc-srjbvk-jyzggzex-243[fijvc] jchipqat-ltpedcxots-uadltg-tcvxcttgxcv-609[ezynj] ryexqpqhteki-sxesebqju-udwyduuhydw-816[eudqy] iuxxuyobk-xgjougizobk-hatte-sgtgmksktz-436[pwdlc] gcfcnuls-aluxy-wuhxs-wiuncha-guleyncha-136[ucahl] ugfkmewj-yjsvw-usfvq-ugslafy-mkwj-lwklafy-476[ohqre] laffe-vxupkizork-vrgyzoi-mxgyy-uvkxgzouty-488[awgqz] eqttqukxg-hnqygt-rwtejcukpi-570[tqegk] yuxufmdk-sdmpq-ngzzk-ruzmzouzs-534[zumdk] ktwbhtvmbox-ietlmbv-zktll-kxtvjnblbmbhg-553[btlkm] qxdwpopgsdjh-eaphixr-vgphh-prfjxhxixdc-999[hpxdg] bnmrtldq-fqzcd-oqnidbshkd-qzaahs-cdoknxldms-703[lxvwe] gokzyxsjon-nio-gybucryz-172[oygnz] cqwdujys-uww-cqhaujydw-660[wucdj] mbggf-pualyuhapvuhs-msvdly-aljouvsvnf-123[ngwhl] crwwv-oxaflxzqfsb-zelzlixqb-ixyloxqlov-913[lxoqz] qlm-pbzobq-ciltbo-abmxoqjbkq-861[bqolm] oqnidbshkd-dff-rghoohmf-313[dfhob] lzfmdshb-eknvdq-cdudknoldms-937[dklmn] wsvsdkbi-qbkno-nio-ecob-docdsxq-614[jsetb] zlilocri-zxkav-zlxqfkd-qoxfkfkd-835[kflxz] wlqqp-upv-vexzevvizex-165[vepqx] vcibutulxiom-vumeyn-womnigyl-mylpcwy-838[myilu] pelbtravp-cynfgvp-tenff-svanapvat-663[kzmfp] xgvnndadzy-wpiit-jkzmvodjin-421[dinjv] foadouwbu-pogysh-fsqswjwbu-480[osuwb] yrwxefpi-hci-wxsveki-308[iewxc] tmrszakd-azrjds-otqbgzrhmf-105[rzadm] sbnqbhjoh-dboez-dpbujoh-usbjojoh-155[bohjd] eqnqthwn-gii-fgrctvogpv-908[ginqt] uiovmbqk-jcvvg-amzdqkma-356[mvakq] sbejpbdujwf-gmpxfs-pqfsbujpot-857[pbfjs] ide-htrgti-ytaanqtpc-stepgibtci-531[mnyed] aietsrmdih-glsgspexi-gywxsqiv-wivzmgi-230[igsem] htqtwkzq-xhfajsljw-mzsy-zxjw-yjxynsl-931[cmkfr] ckgvutofkj-xgjougizobk-yigbktmkx-natz-lotgtiotm-436[tgkoi] nwlddtqtpo-upwwjmply-fdpc-epdetyr-509[pdtwe] irdgrxzex-sleep-jyzggzex-373[tvnma] crwwv-zxkav-qoxfkfkd-939[lyjmh] ejpanjwpekjwh-nwzekwypera-oywrajcan-dqjp-nawymqeoepekj-368[zmuyt] lzfmdshb-rbzudmfdq-gtms-knfhrshbr-495[bdfhm] nchhg-rmttgjmiv-uizsmbqvo-252[mghit] amjmpdsj-aylbw-rpyglgle-626[lagjm] dfcxsqhwzs-pogysh-qighcasf-gsfjwqs-220[sfghq] xjgjmapg-nxvqzibzm-cpio-nojmvbz-707[jmzbg] zntargvp-enoovg-qrirybczrag-663[scjtg] bkzrrhehdc-qzaahs-qdzbpthrhshnm-391[zjbto] hafgnoyr-wryylorna-erprvivat-429[rayno] apwmeclga-afmamjyrc-rpyglgle-262[aglmc] jsvagsulanw-jsttal-hmjuzskafy-606[asjlt] bnknqetk-lhkhszqx-fqzcd-cxd-zmzkxrhr-651[kzhqx] ykhknbqh-nwxxep-nayaerejc-966[enahk] vrurcjah-pajmn-kdwwh-cajrwrwp-667[rwajc] vhehkyne-utldxm-vhgmtbgfxgm-891[ghmet] zotts-dyffsvyuh-xymcah-812[yfhst] vhglnfxk-zktwx-vtgwr-vnlmhfxk-lxkobvx-319[gvnom] ajvyjprwp-mhn-nwprwnnarwp-563[npwra] guahyncw-chnylhuncihuf-jfumncw-alumm-guleyncha-110[zjirh] hwdtljsnh-jll-xfqjx-801[jlhxd] xjgjmapg-mvwwdo-xjiovdihzio-525[ijodg] pybgmyargtc-zgmfyxypbmsq-zsllw-asqrmkcp-qcptgac-262[cgmpy] aflwjfslagfsd-hdsklau-yjskk-esfsywewfl-528[sflak] lugjuacha-dyffsvyuh-xypyfijgyhn-708[yfhua] lxaaxbren-mhn-cnlqwxuxph-823[nzsvm] sehheiylu-tou-cqdqwucudj-738[xciqn] slqryzjc-djmucp-qrmpyec-808[sznhq] ykjoqian-cnwza-bhksan-opknwca-264[ankco] pualyuhapvuhs-lnn-bzly-alzapun-721[auzfj] tfiifjzmv-wcfnvi-jkfirxv-997[fivjc] lsyrkjkbnyec-mkxni-mykdsxq-vyqscdsmc-562[ksycm] fnjyxwrinm-lujbbrornm-ajkkrc-nwprwnnarwp-927[zmyco] pyknyegle-amlqskcp-epybc-hcjjwzcyl-qcptgacq-860[cpyel] rzvkjiduzy-ezggtwzvi-kpmxcvndib-811[zivdg] wyvqljapsl-yhiipa-bzly-alzapun-773[alpyi] joufsobujpobm-dipdpmbuf-bdrvjtjujpo-415[gvkud] zloolpfsb-zxkav-zlxqfkd-lmboxqflkp-393[lfkox] zilqwikbqdm-jcvvg-kwvbiqvumvb-174[vbiqk] kzeed-wfggny-xmnuunsl-853[negud] ftzgxmbv-xzz-phkdlahi-657[grbhi] bnqqnrhud-bzmcx-sqzhmhmf-131[hmqbn] zntargvp-pnaql-pbngvat-nanylfvf-169[napvf] jxdkbqfz-pzxsbkdbo-erkq-absbilmjbkq-315[uzmcf] jshzzpmplk-buzahisl-kfl-klzpnu-695[lzkph] pualyuhapvuhs-msvdly-jbzavtly-zlycpjl-825[lyapu] lujbbrornm-ouxfna-xynajcrxwb-667[bnrxa] dmpuamofuhq-nmewqf-pqhqxabyqzf-482[lndmj] cvabijtm-moo-zmikycqaqbqwv-148[mqabc] wyvqljapsl-msvdly-zlycpjlz-435[lyjps] fmsledevhsyw-ikk-gywxsqiv-wivzmgi-204[isvwe] ide-htrgti-snt-sthxvc-297[tyvnc] guahyncw-luvvcn-qilembij-292[tcrsd] udskkaxawv-wyy-kwjnauwk-710[kwauy] aczupnetwp-clmmte-dezclrp-379[ynpmz] ikhcxvmbex-ietlmbv-zktll-vnlmhfxk-lxkobvx-449[lxkvb] rzvkjiduzy-xcjxjgvoz-rjmfncjk-707[tmnki] enzcntvat-cynfgvp-tenff-ynobengbel-923[neftb] vkrhzxgbv-bgmxkgtmbhgte-lvtoxgzxk-angm-kxtvjnblbmbhg-111[iwvbg] esyfwlau-tskcwl-jwsuimakalagf-398[ywmzb] lhkhszqx-fqzcd-bzmcx-nodqzshnmr-287[zhqcd] nzwzcqfw-ojp-dstaatyr-977[dsznk] qfkkj-xlrypetn-nlyoj-xlcvpetyr-691[lczde] wifilzof-luvvcn-nywbhifias-552[sxghy] nchhg-kivlg-zmamizkp-928[ghikm] tipfxvezt-tcrjjzwzvu-upv-kirzezex-295[zetvi] gsvvswmzi-tpewxmg-kveww-gsrxemrqirx-698[wegmr] pynffvsvrq-sybjre-ernpdhvfvgvba-663[epsqt] sedikcuh-whqtu-vbemuh-udwyduuhydw-894[udhwe] tmrszakd-bzmcx-rsnqzfd-183[zdmrs] zilqwikbqdm-jcvvg-wxmzibqwva-798[iqvwb] lejkrscv-jtrmvexvi-ylek-nfibjyfg-815[ejvfi] zsxyfgqj-jll-qtlnxynhx-151[lxjnq] gbc-frperg-onfxrg-qrirybczrag-923[rgbcf] xjgjmapg-kgvnodx-bmvnn-nvgzn-343[ngvjm] dmybmsuzs-ngzzk-mocgueufuaz-534[uzmgs] dmpuamofuhq-omzpk-oamfuzs-pqbxakyqzf-482[mafop] fbebmtkr-zktwx-unggr-ehzblmbvl-787[begkl] zntargvp-enoovg-ybtvfgvpf-481[vgfno] fubrjhqlf-gbh-vhuylfhv-933[hfblu] fruurvlyh-fdqgb-frdwlqj-whfkqrorjb-569[tmdlw] ixccb-udeelw-ghvljq-335[nibrq] tcorcikpi-dwppa-fgukip-570[qnzgc] ibghopzs-pibbm-rsdzcmasbh-428[bshim] apuut-wpiit-nzmqdxzn-889[inptu] qzoggwtwsr-pibbm-igsf-hsghwbu-246[gbswh] atyzghrk-yigbktmkx-natz-uvkxgzouty-488[pxeoy] mbiyqoxsm-mkxni-bokmaescsdsyx-796[erynw] qxdwpopgsdjh-uadltg-itrwcdadvn-401[mzukc] tinnm-rms-kcfygvcd-688[cmndf] crwwv-mixpqfz-doxpp-xkxivpfp-107[tpawu] qxdwpopgsdjh-qphzti-itrwcdadvn-999[lenub] jqwpihizlwca-lgm-abwziom-538[iwalm] votubcmf-dboez-dpbujoh-gjobodjoh-909[szlxy] nwzekwypera-oywrajcan-dqjp-iwjwcaiajp-446[awjpc] lxuxaodu-vrurcjah-pajmn-ljwmh-cnlqwxuxph-329[uxahj] gvaaz-ezf-efwfmpqnfou-779[scdpt] jsvagsulanw-hdsklau-yjskk-vwhdgqewfl-190[saklw] yrwxefpi-fewoix-irkmriivmrk-828[irefk] jrncbavmrq-rtt-fgbentr-819[rtbna] tpspahyf-nyhkl-msvdly-klwsvftlua-409[lsyaf] veqtekmrk-tpewxmg-kveww-qerekiqirx-100[szdiy] ykhknbqh-ydkykhwpa-hkceopeyo-108[khyeo] gifavtkzcv-treup-tfrkzex-dribvkzex-503[ekrtv] hafgnoyr-pubpbyngr-bcrengvbaf-351[bgnra] ide-htrgti-gpqqxi-gtprfjxhxixdc-999[ixgtd] yhtwhnpun-ipvohghykvbz-wshzapj-nyhzz-zavyhnl-617[hznyp] enqvbnpgvir-pynffvsvrq-rtt-erprvivat-559[vrnpt] jxdkbqfz-yrkkv-pxibp-159[kbpxd] etyyx-rbzudmfdq-gtms-rdquhbdr-833[drbmq] owshgfarwv-udskkaxawv-hdsklau-yjskk-ogjckzgh-398[kasgh] xst-wigvix-gerhc-irkmriivmrk-828[ilntc] ugfkmewj-yjsvw-wyy-klgjsyw-684[wyjgk] zloolpfsb-mixpqfz-doxpp-pbosfzbp-211[topig] fruurvlyh-vfdyhqjhu-kxqw-orjlvwlfv-569[vfhlr] xst-wigvix-fyrrc-vigimzmrk-516[irgmv] rnqnyfwd-lwfij-wfggny-wjxjfwhm-281[wfjng] rdchjbtg-vgpst-ytaanqtpc-sthxvc-557[tcagh] fubrjhqlf-fdqgb-frdwlqj-dftxlvlwlrq-465[flqdr] qlm-pbzobq-pzxsbkdbo-erkq-xznrfpfqflk-679[bqfkp] ltpedcxots-rpcsn-bpcpvtbtci-921[dtejs] froruixo-edvnhw-ghsorbphqw-231[horwb] bjfutsneji-hmthtqfyj-fsfqdxnx-333[fjthn] yhtwhnpun-lnn-zavyhnl-669[wpsgy] dmpuamofuhq-ngzzk-xmnadmfadk-742[madfk] ejpanjwpekjwh-ywjzu-oanreyao-498[yzjwm] eza-dpncpe-qwzhpc-afcnsldtyr-353[ivxnu] qekrixmg-nippcfier-gywxsqiv-wivzmgi-464[yxkwm] avw-zljyla-ibuuf-ylzlhyjo-383[lyaju] lqwhuqdwlrqdo-mhoobehdq-rshudwlrqv-621[qdhlo] qvbmzvibqwvit-jcvvg-apqxxqvo-200[vqbix] ugjjgkanw-esyfwlau-jsttal-ugflsafewfl-164[fgcep] shoewudys-isqludwuh-xkdj-ijehqwu-504[stjyd] luxciuwncpy-vohhs-yhachyylcha-214[hcyal] gifavtkzcv-sleep-ivjvrity-685[vieta] rzvkjiduzy-xviyt-yzqzgjkhzio-161[ziyjk] iehepwnu-cnwza-ykjoqian-cnwza-ywjzu-ykwpejc-iwjwcaiajp-316[wajci] sorozgxe-mxgjk-jek-vaxingyotm-956[goxej] dmpuamofuhq-dmnnuf-dqmocgueufuaz-560[umdfa] hjgbwuladw-kusnwfywj-zmfl-ugflsafewfl-450[aezbn] esyfwlau-usfvq-ugslafy-ghwjslagfk-294[fsagl] shmml-sybjre-erfrnepu-195[ngkjp] jlidywncfy-ohmnuvfy-wuhxs-wiuncha-ijyluncihm-240[xtjsm] ixeumktoi-lruckx-aykx-zkyzotm-436[kximo] nzydfxpc-rclop-upwwjmply-xlylrpxpye-535[plyxc] fodvvlilhg-sodvwlf-judvv-pdunhwlqj-725[krngz] xjmmjndqz-ezggtwzvi-adivixdib-733[idzgj] pbybeshy-pnaql-pbngvat-znantrzrag-533[anbpg] fnjyxwrinm-ljwmh-lxjcrwp-bqryyrwp-329[rwjyl] lhkhszqx-fqzcd-okzrshb-fqzrr-cdoknxldms-391[zdhkq] pynffvsvrq-ohaal-znantrzrag-637[anrfv] hafgnoyr-sybjre-genvavat-767[ngacu] lhkhszqx-fqzcd-bgnbnkzsd-lzmzfdldms-443[ynael] lugjuacha-wbiwifuny-mufym-786[uafim] vkrhzxgbv-xzz-ftgtzxfxgm-995[xzgft] uzfqdzmfuazmx-rxaiqd-emxqe-170[mqxza] ajvyjprwp-snuuhknjw-anlnrerwp-771[njprw] zuv-ykixkz-igtje-iugzotm-zxgototm-930[lifhb] mfklstdw-wyy-ksdwk-294[kwdsy] kyelcrga-slqryzjc-hcjjwzcyl-qrmpyec-990[kypqm] vkppo-sxesebqju-tulubefcudj-400[uebjp] ynukcajey-xqjju-lqnydwoejc-394[jycen] qzlozfhmf-qzchnzbshud-qzaahs-qdzbpthrhshnm-287[hzqsa] kmjezxodgz-mvwwdo-ncdkkdib-109[dkmow] oazegyqd-sdmpq-ngzzk-bgdotmeuzs-482[zdgem] qfkkj-mldvpe-cpdplcns-561[pcdkl] hvbizodx-ezggtwzvi-xjiovdihzio-577[voqzy] iuxxuyobk-inuiurgzk-xkikobotm-722[ikuox] jyddc-gsvvswmzi-jpsaiv-jmrergmrk-958[cpedy] vhkkhlbox-unggr-hixktmbhgl-449[hgkbl] clotzlnetgp-nsznzwlep-dpcgtnpd-145[tehzy] plolwdub-judgh-hjj-dqdobvlv-543[zkryh] ajmrxjlcren-ouxfna-ydalqjbrwp-355[ajrln] uqtqbizg-ozilm-lgm-amzdqkma-304[mqzag] lnkfaypeha-zua-lqnydwoejc-914[aelny] ibghopzs-pwcvonofrcig-qobrm-aobousasbh-844[obsac] ocipgvke-eqpuwogt-itcfg-tcddkv-gpikpggtkpi-804[salbg] ajmrxjlcren-lqxlxujcn-uxprbcrlb-823[lrxcj] rgndvtcxr-ytaanqtpc-sthxvc-843[tcanr] hqcfqwydw-sxesebqju-qdqboiyi-894[qbdei] tbxmlkfwba-gbiivybxk-qbzeklildv-757[biklv] vetllbybxw-utldxm-vhgmtbgfxgm-735[bglmt] mfklstdw-hdsklau-yjskk-vwhsjlewfl-528[xyuts] pxtihgbsxw-vtgwr-nlxk-mxlmbgz-657[xgblm] bnmrtldq-fqzcd-dff-lzqjdshmf-677[szdpt] xekdwvwnzkqo-sawlkjevaz-fahhuxawj-nayaerejc-654[zdeyh] gzefmnxq-bxmefuo-sdmee-xmnadmfadk-170[medfx] gpsxdprixkt-eaphixr-vgphh-rjhidbtg-htgkxrt-115[hgprt] eza-dpncpe-hplazytkpo-awldetn-rcldd-xlcvpetyr-535[tnpmg] bnmrtldq-fqzcd-eknvdq-sdbgmnknfx-781[dnqbf] nzcczdtgp-dnlgpyrpc-sfye-opgpwzaxpye-899[pcgyz] nwzekwypera-ydkykhwpa-odellejc-992[pwqrh] oknkvcta-itcfg-gii-wugt-vguvkpi-154[giktv] tcrjjzwzvu-upv-kvtyefcfxp-373[vcfjp] xst-wigvix-ikk-stivexmsrw-230[isxkt] fkqbokxqflkxi-zelzlixqb-qoxfkfkd-705[mntlq] qlm-pbzobq-yxphbq-zrpqljbo-pbosfzb-237[bpqoz] drxevkzt-avccpsvre-wzeretzex-269[ervzc] ksodcbwnsr-pogysh-oqeiwgwhwcb-480[mxdsl] tyepcyletzylw-qwzhpc-xlylrpxpye-613[tvcgy] rnqnyfwd-lwfij-hmthtqfyj-qtlnxynhx-437[ukdrt] oxjmxdfkd-jfifqxov-doxab-yxphbq-ixyloxqlov-393[xodfq] tcorcikpi-ejqeqncvg-fgrnqaogpv-804[cgqei] hqtyeqsjylu-zubboruqd-qsgkyiyjyed-712[yqubd] hvbizodx-ezggtwzvi-gjbdnodxn-967[dgzbi] zntargvp-enoovg-fgbentr-923[gneor] mvydjvxodqz-wvnfzo-hvmfzodib-447[zfpes] emixwvqhml-zijjqb-lmdmtwxumvb-148[mbijl] frqvxphu-judgh-gbh-whfkqrorjb-179[jwmgn] kyelcrga-njyqrga-epyqq-dglylagle-782[glyae] npmhcargjc-pyzzgr-bctcjmnkclr-522[crgjm] pxtihgbsxw-xzz-tvjnblbmbhg-943[bxght] oknkvcta-itcfg-hnqygt-qrgtcvkqpu-206[tcgkq] amlqskcp-epybc-zyqicr-sqcp-rcqrgle-522[bnemi] enqvbnpgvir-pnaql-fuvccvat-299[vnacp] xlrypetn-mldvpe-cpnptgtyr-509[nugrq] mbggf-qlssfilhu-klclsvwtlua-383[lsfgu] wlsiayhcw-wuhxs-wiuncha-mniluay-656[wahiu] gvaaz-cbtlfu-efqmpznfou-415[byzhx] rzvkjiduzy-nxvqzibzm-cpio-hvivbzhzio-343[zivbh] bqxnfdmhb-dff-otqbgzrhmf-781[fbdhm] wihmogyl-aluxy-wuhxs-wiuncha-lyuwkocmcncih-838[chuwi] enzcntvat-onfxrg-hfre-grfgvat-689[nkvyi] xgjougizobk-igtje-iugzotm-ygrky-540[giojk] mbggf-kfl-aljouvsvnf-773[fglva] qzoggwtwsr-xszzmpsob-sbuwbssfwbu-662[sbwzg] wsvsdkbi-qbkno-mkxni-mykdsxq-nofovyzwoxd-744[kodns] tpspahyf-nyhkl-lnn-klzpnu-721[nlphk] pejji-nio-bomosfsxq-380[oijsb] amlqskcp-epybc-cee-nspafyqgle-132[dsayt] luxciuwncpy-xsy-lyuwkocmcncih-240[cuyil] irdgrxzex-gcrjkzt-xirjj-vexzevvizex-165[xerzi] lxaaxbren-snuuhknjw-ujkxajcxah-381[axjnu] ktfitzbgz-ynssr-xzz-wxiehrfxgm-839[sjagq] hafgnoyr-enzcntvat-pnaql-pbngvat-genvavat-975[antvg] dfcxsqhwzs-qobrm-fsqswjwbu-896[sqwbf] zsxyfgqj-xhfajsljw-mzsy-xytwflj-619[jfsxy] yhwooebeaz-ywjzu-ykwpejc-hkceopeyo-706[eoywc] mvydjvxodqz-wpiit-kpmxcvndib-863[yrjnz] otzkxtgzoutgr-igtje-iugzotm-iutzgotsktz-332[tgzoi] pdjqhwlf-sodvwlf-judvv-vdohv-855[vdfhj] gpewwmjmih-fyrrc-gywxsqiv-wivzmgi-724[iwgmr] oqnidbshkd-idkkxadzm-rsnqzfd-391[lpscd] rgndvtcxr-hrpktcvtg-wjci-uxcpcrxcv-765[crtvx] esyfwlau-tmffq-xafsfuafy-970[fasuy] gvaaz-dipdpmbuf-efqbsunfou-545[zmynh] zsxyfgqj-wfggny-uzwhmfxnsl-463[cvqjn] oazegyqd-sdmpq-ngzzk-emxqe-430[flhis] jvuzbtly-nyhkl-zjhclunly-obua-zlycpjlz-643[ueimk] surmhfwloh-vfdyhqjhu-kxqw-ghsorbphqw-205[hqwfo] pualyuhapvuhs-zjhclunly-obua-thuhnltlua-825[ficqs] wbhsfbohwcboz-rms-oqeiwgwhwcb-194[wbhoc] gpsxdprixkt-ytaanqtpc-bpcpvtbtci-635[qkzhc] rnqnyfwd-lwfij-xhfajsljw-mzsy-qfgtwfytwd-931[fwjyd] ubhatstkwhnl-ktuubm-vnlmhfxk-lxkobvx-787[gtsqv] lqwhuqdwlrqdo-udeelw-dftxlvlwlrq-413[ldqwe] kloqemlib-lygbzq-pqloxdb-991[lbqod] veqtekmrk-tpewxmg-kveww-hiwmkr-282[ekwmr] rflsjynh-ytu-xjhwjy-jll-knsfshnsl-333[jlshn] bknsykmdsfo-pvygob-domrxyvyqi-432[yobdk] mybbycsfo-bkllsd-kxkvicsc-822[yzxcq] zixppfcfba-yxphbq-absbilmjbkq-991[gbhts] udskkaxawv-uzgugdslw-klgjsyw-684[gksuw] clxalrtyr-mfyyj-qtylyntyr-665[ylrta] uiovmbqk-jiasmb-lmaqov-694[mabio] xmtjbzidx-mvwwdo-zibdizzmdib-161[dizbm] wyvqljapsl-jovjvshal-bzly-alzapun-643[lajvp] zlilocri-zxkav-mrozexpfkd-445[rifng] pinovwgz-zbb-hvmfzodib-811[bziov] rtqlgevkng-dwppa-vgejpqnqia-284[gpqae] vrurcjah-pajmn-ljwmh-jlzdrbrcrxw-667[lmdrk] jlidywncfy-dyffsvyuh-ijyluncihm-838[yficd] cebwrpgvyr-sybjre-qrirybczrag-741[tsrqd] pbafhzre-tenqr-onfxrg-grpuabybtl-949[rbaef] lahxpnwrl-ljwmh-lxjcrwp-nwprwnnarwp-433[seonp] iuxxuyobk-igtje-iugzotm-iutzgotsktz-644[tiugo] qfkkj-prr-fdpc-epdetyr-951[prdef] nchhg-akidmvomz-pcvb-nqvivkqvo-954[osgtz] htwwtxnaj-gzssd-ijufwyrjsy-385[jswty] myxcewob-qbkno-mrymyvkdo-bokmaescsdsyx-328[sezot] rzvkjiduzy-mvwwdo-ncdkkdib-499[mfyze] emixwvqhml-lgm-uizsmbqvo-798[milqv] xmtjbzidx-wvnfzo-vivgtndn-941[nvdit] bknsykmdsfo-zvkcdsm-qbkcc-cobfsmoc-198[cksbm] gsrwyqiv-kvehi-fyrrc-jmrergmrk-906[regik] bqvvu-oywrajcan-dqjp-nawymqeoepekj-524[aejqn] upq-tfdsfu-sbccju-bobmztjt-883[btucf] surmhfwloh-fruurvlyh-mhoobehdq-orjlvwlfv-933[zymnj] wkqxodsm-tovvilokx-gybucryz-588[okvxy] nchhg-ntwemz-twoqabqka-902[ahnqt] iqmbazulqp-rgllk-rxaiqd-fqotzaxask-950[dtanc] ejpanjwpekjwh-nwxxep-bejwjyejc-732[jewpn] ajmrxjlcren-fnjyxwrinm-lqxlxujcn-vjwjpnvnwc-329[yhgwz] qcbgiasf-ufors-qvcqczohs-aofyshwbu-532[scfoq] jsehsyafy-vqw-ugflsafewfl-970[mfzcn] fab-eqodqf-qss-geqd-fqefuzs-560[qfesd] jef-iushuj-uww-sedjqydcudj-322[qyadz] kfg-jvtivk-jtrmvexvi-ylek-ivtvzmzex-347[wmlfu] pxtihgbsxw-ietlmbv-zktll-wxiehrfxgm-371[xiltb] wfintfhynaj-hmthtqfyj-jslnsjjwnsl-463[jnfhs] forwcoqhwjs-foppwh-kcfygvcd-480[cfowh] kzgwomvqk-rmttgjmiv-camz-bmabqvo-616[mvabg] pybgmyargtc-aylbw-amyrgle-nspafyqgle-392[yaglb] jyfvnlupj-ihzrla-lunpullypun-149[lytps] dpmpsgvm-cbtlfu-xpsltipq-467[plmst] oxaflxzqfsb-avb-zrpqljbo-pbosfzb-965[bfoza] amlqskcp-epybc-afmamjyrc-bctcjmnkclr-392[cmabj] encuukhkgf-tcddkv-yqtmujqr-362[kucdq] lqwhuqdwlrqdo-edvnhw-hqjlqhhulqj-595[sywmh] njmjubsz-hsbef-qspkfdujmf-cbtlfu-vtfs-uftujoh-857[fujsb] dsxxw-djmucp-umpiqfmn-340[mdpux] aflwjfslagfsd-hdsklau-yjskk-dstgjslgjq-736[sjlad] ynukcajey-ywjzu-iwjwcaiajp-758[sthmn] froruixo-lqwhuqdwlrqdo-fdqgb-uhdftxlvlwlrq-621[gtcry] chnylhuncihuf-jfumncw-alumm-mylpcwym-526[tyodr] ujoon-qphzti-uxcpcrxcv-817[copux] bkwzkqsxq-cmkfoxqob-rexd-ckvoc-666[kcoqx] pelbtravp-enqvbnpgvir-qlr-qrfvta-403[wqynx] yhtwhnpun-ibuuf-thuhnltlua-643[trfed] willimcpy-yaa-wihnuchgyhn-344[hiyac] thnulapj-jovjvshal-mpuhujpun-799[juhpa] nzcczdtgp-mldvpe-lnbftdtetzy-821[qvnmi] qzlozfhmf-idkkxadzm-btrsnldq-rdquhbd-209[dqzbf] ajvyjprwp-ouxfna-vjwjpnvnwc-407[jnpvw] hcd-gsqfsh-dzoghwq-ufogg-zcuwghwqg-688[nwgox] jrncbavmrq-qlr-genvavat-169[arvnq] crwwv-yrkkv-jxkxdbjbkq-653[ylpzs] pejji-tovvilokx-vyqscdsmc-146[vcijo] ikhcxvmbex-lvtoxgzxk-angm-inkvatlbgz-189[xgkva] jyddc-wgezirkiv-lyrx-xiglrspskc-620[ircdg] ajyqqgdgcb-aylbw-amyrgle-rpyglgle-210[glyab] mhi-lxvkxm-yehpxk-kxvxbobgz-319[lcest] rkpqxyib-gbiivybxk-lmboxqflkp-211[vustn] jchipqat-rdadguja-hrpktcvtg-wjci-tcvxcttgxcv-999[ctagj] ovbunmneqbhf-fpniratre-uhag-grpuabybtl-949[banru] nchhg-xtiabqk-oziaa-abwziom-174[aibho] dwbcjkun-ljwmh-ydalqjbrwp-303[jwbdl] lxuxaodu-krxqjijamxdb-bljenwpna-qdwc-bnaerlnb-563[ycjlt] yhkpvhjapcl-wshzapj-nyhzz-shivyhavyf-461[hyapv] udglrdfwlyh-mhoobehdq-wudlqlqj-959[dlhqo] myxcewob-qbkno-lsyrkjkbnyec-lexxi-cdybkqo-588[nfdem] fnjyxwrinm-ljwmh-lxwcjrwvnwc-459[wjncl] udpsdjlqj-udeelw-ghvljq-491[djleq] zloolpfsb-yrkkv-mrozexpfkd-783[koflp] drxevkzt-jtrmvexvi-ylek-ivrthlzjzkzfe-997[evzkr] ykjoqian-cnwza-ywjzu-ykwpejc-opknwca-264[wacjk] xekdwvwnzkqo-zua-zalwnpiajp-992[awzkn] fydelmwp-aczupnetwp-prr-cplnbftdtetzy-847[ptecd] lxwbdvna-pajmn-ouxfna-anjlzdrbrcrxw-563[anrxb] xfbqpojafe-gmpxfs-tbmft-545[rgdzm] kzeed-ojqqdgjfs-ijuqtdrjsy-411[jdqes] ktiaaqnqml-ntwemz-uizsmbqvo-642[azvew] udpsdjlqj-gbh-whfkqrorjb-725[rnqmt] lahxpnwrl-ouxfna-ydalqjbrwp-745[alnpr] dsxxw-bwc-mncpyrgmlq-548[cmwxb] joufsobujpobm-gvaaz-qmbtujd-hsbtt-fohjoffsjoh-727[ojbfh] laffe-jek-ynovvotm-670[efova] nzcczdtgp-ojp-xlcvpetyr-353[nvmak] kgjgrypw-epybc-djmucp-qyjcq-496[sqhmg] ykjoqian-cnwza-ywjzu-klanwpekjo-680[ajknw] nbhofujd-dipdpmbuf-efqbsunfou-415[fubdn] oaddaeuhq-ngzzk-fqotzaxask-144[hbxcm] lujbbrornm-vjpwncrl-snuuhknjw-ldbcxvna-bnaerln-459[nblrj] xgvnndadzy-wvnfzo-yzkvmohzio-135[znovd] jchipqat-tvv-jhtg-ithixcv-271[ymstr] xtwtelcj-rclop-nlyoj-dstaatyr-431[ntags] iutyaskx-mxgjk-jek-xkykgxin-618[kxgij] pxtihgbsxw-ktwbhtvmbox-cxeeruxtg-tgterlbl-943[txbeg] xfbqpojafe-dboez-dpbujoh-mbcpsbupsz-441[bpode] qfkkj-mfyyj-opalcexpye-613[yefjk] ejpanjwpekjwh-lhwopey-cnwoo-nawymqeoepekj-836[ewjop] qjopwxha-xqjju-odellejc-732[jeloq] bnknqetk-atmmx-lzmzfdldms-261[mdkln] xgsvgmotm-pkrrehkgt-sgtgmksktz-332[gktms] ryexqpqhteki-vbemuh-huqsgkyiyjyed-244[tjsqx] xjinphzm-bmvyz-ytz-yzkvmohzio-239[oznyv] eqttqukxg-rncuvke-itcuu-cpcnauku-180[jztvf] xgjougizobk-xghhoz-ygrky-696[gohkx] mtzslklcozfd-nsznzwlep-opgpwzaxpye-769[zplen] kgjgrypw-epybc-pyzzgr-jmegqrgaq-626[gprye] jlidywncfy-wbiwifuny-mniluay-396[iynwf] myvybpev-mkxni-mykdsxq-psxkxmsxq-536[rxnml] ibghopzs-qobrm-rsdzcmasbh-246[bshmo] jyfvnlupj-wshzapj-nyhzz-klwsvftlua-201[jlzaf] dzczkrip-xiruv-avccpsvre-cfxzjkztj-113[czrvi] dmbttjgjfe-dboez-dpbujoh-nbslfujoh-493[bjdoe] kfg-jvtivk-gifavtkzcv-srjbvk-jvimztvj-347[aymns] ktwbhtvmbox-vetllbybxw-ietlmbv-zktll-wxlbzg-241[bltvw] tmrszakd-cxd-qdrdzqbg-417[dqrza] nzydfxpc-rclop-nsznzwlep-nfdezxpc-dpcgtnp-899[ynbfk] fruurvlyh-mhoobehdq-rshudwlrqv-491[hrudl] odkasqzuo-pkq-emxqe-144[qekoa] hwbba-dcumgv-vtckpkpi-180[bckpv] lsyrkjkbnyec-cmkfoxqob-rexd-wkbuodsxq-718[yfzcq] xgvnndadzy-kgvnodx-bmvnn-xjiovdihzio-395[ndvio] willimcpy-vumeyn-omyl-nymncha-890[nmyux] mbggf-zjhclunly-obua-yljlpcpun-487[lubcg] ryexqpqhteki-sqdto-tuiywd-608[xhjzp] egdytrixat-gpqqxi-prfjxhxixdc-193[xidgp] nbhofujd-dszphfojd-cbtlfu-sftfbsdi-909[fdbsh] rflsjynh-gfxpjy-htsyfnsrjsy-489[istpm] vkrhzxgbv-vetllbybxw-ietlmbv-zktll-phkdlahi-189[lbvhk] lujbbrornm-ouxfna-uxprbcrlb-459[ozvca] pbafhzre-tenqr-fpniratre-uhag-erprvivat-117[raept] xgvnndadzy-xjmmjndqz-ytz-nvgzn-577[nzdgj] houngfgxjuay-pkrrehkgt-jkyomt-618[dltyf] bjfutsneji-hmthtqfyj-jslnsjjwnsl-411[jsntf] sgmtkzoi-lruckx-rghuxgzuxe-774[guxkr] nuatmlmdpage-nmewqf-abqdmfuaze-326[zbewa] dsxxw-zsllw-qyjcq-912[lqswx] cvabijtm-kivlg-kwibqvo-aitma-226[mvuhw] yuxufmdk-sdmpq-qss-bgdotmeuzs-768[sdmuq] qspkfdujmf-fhh-usbjojoh-597[elvgu] htqtwkzq-gfxpjy-hzxytrjw-xjwanhj-359[jpytc] gbc-frperg-pnaql-pbngvat-grpuabybtl-169[bgpar] yhkpvhjapcl-qlssfilhu-klclsvwtlua-123[lhsac] nglmtuex-vtgwr-vhtmbgz-ftkdxmbgz-813[emnca] atyzghrk-lruckx-ygrky-592[kryga] dkqjcbctfqwu-tcddkv-tgegkxkpi-362[kcdtg] sawlkjevaz-bhksan-lqnydwoejc-914[aejkl] kdijqrbu-uww-ijehqwu-712[uwijq] rwcnawjcrxwju-snuuhknjw-mnbrpw-121[wnjru] vrurcjah-pajmn-mhn-bcxajpn-225[ajnch] clotzlnetgp-mldvpe-cpdplcns-353[lpcde] wihmogyl-aluxy-dyffsvyuh-womnigyl-mylpcwy-682[khzto] qcbgiasf-ufors-dzoghwq-ufogg-kcfygvcd-428[mselb] kwtwznct-ktiaaqnqml-akidmvomz-pcvb-bmkpvwtwog-824[kmtwa] crwwv-oxyyfq-pqloxdb-289[oqwxy] iutyaskx-mxgjk-ckgvutofkj-lruckx-jkvgxzsktz-852[kxgjt] irgyyolokj-yigbktmkx-natz-giwaoyozout-930[oygik] yhtwhnpun-buzahisl-jhukf-jvhapun-mpuhujpun-565[uhnpj] fbebmtkr-zktwx-ktuubm-ybgtgvbgz-761[ifsyt] lejkrscv-avccpsvre-dribvkzex-165[vcerk] avw-zljyla-yhiipa-jvuahputlua-617[aluhi] xjmmjndqz-wpiit-xjiovdihzio-889[ijdmo] pbybeshy-fpniratre-uhag-jbexfubc-819[snuje] ktwbhtvmbox-vtgwr-phkdlahi-683[htbkv] avw-zljyla-wshzapj-nyhzz-ylzlhyjo-409[zlyah] tcrjjzwzvu-treup-tfrkzex-drerxvdvek-633[retvz] zlkprjbo-doxab-ciltbo-qoxfkfkd-627[nmwxj] vkrhzxgbv-lvtoxgzxk-angm-labiibgz-995[gbvxz] gpbepvxcv-hrpktcvtg-wjci-sthxvc-609[cvptg] hwbba-gii-fgrctvogpv-804[gbiva] nwlddtqtpo-nsznzwlep-dstaatyr-275[tdnal] ovbunmneqbhf-fpniratre-uhag-hfre-grfgvat-637[fraeg] pkl-oaynap-fahhuxawj-nayaerejc-888[mnchz] etaqigpke-hnqygt-qrgtcvkqpu-752[antmz] lugjuacha-wuhxs-ijyluncihm-214[hfsun] zloolpfsb-zxkav-abpfdk-341[abfkl] bknsykmdsfo-mkxni-mykdsxq-bokmaescsdsyx-822[skmdx] xjgjmapg-zbb-hvivbzhzio-499[bzghi] amjmpdsj-ajyqqgdgcb-qaytclecp-fslr-qrmpyec-652[smgnt] qczcftiz-dzoghwq-ufogg-rsgwub-714[gzcfo] gokzyxsjon-wsvsdkbi-qbkno-nio-myxdksxwoxd-900[oksxd] ktfitzbgz-vtgwr-vhtmbgz-lxkobvxl-969[tbgvz] hqtyeqsjylu-uww-efuhqjyedi-270[dytgj] ovbunmneqbhf-pnaql-pbngvat-freivprf-845[nbfpv] kzgwomvqk-akidmvomz-pcvb-aitma-902[makvi] sedikcuh-whqtu-zubboruqd-bqrehqjeho-790[hqube] kwvacumz-ozilm-jcvvg-lmaqov-382[vmacl] rgndvtcxr-qjccn-prfjxhxixdc-661[cxrdj] tbxmlkfwba-oxyyfq-tlohpelm-523[uhvaf] iuxxuyobk-inuiurgzk-vaxingyotm-514[iuxgk] odkasqzuo-omzpk-oamfuzs-ymzmsqyqzf-170[zmoqs] ktwbhtvmbox-unggr-lxkobvxl-527[bxgkl] ynssr-vtgwr-mxvaghehzr-423[rghsv] sgmtkzoi-kmm-lotgtiotm-670[mtogi] ugdgjxmd-vqw-kwjnauwk-944[wdgjk] rdggdhxkt-jchipqat-snt-gthtpgrw-713[tghdp] zvyvgnel-tenqr-wryylorna-npdhvfvgvba-663[vnrya] jsvagsulanw-usfvq-ugslafy-esjcwlafy-762[fygle] zsxyfgqj-wfggny-hzxytrjw-xjwanhj-931[jgwxy] wkqxodsm-tovvilokx-dbksxsxq-822[cpsgv] mbiyqoxsm-tovvilokx-yzobkdsyxc-458[oxybi] lzfmdshb-bzmcx-bnzshmf-vnqjrgno-261[ujfyc] oknkvcta-itcfg-dcumgv-hkpcpekpi-258[ckpgi] iuxxuyobk-inuiurgzk-sgtgmksktz-202[ztjvk] hjgbwuladw-hdsklau-yjskk-ljsafafy-372[mvkts] rdadguja-eaphixr-vgphh-tcvxcttgxcv-739[acght] nsyjwsfyntsfq-idj-xmnuunsl-983[nsfju] gifavtkzcv-wcfnvi-rthlzjzkzfe-971[zfvci] qvbmzvibqwvit-jiasmb-zmamizkp-278[imbvz] houngfgxjuay-ckgvutofkj-yigbktmkx-natz-ykxboiky-930[kgyot] guahyncw-wuhxs-lyuwkocmcncih-500[chuwn] gpbepvxcv-ytaanqtpc-bpgztixcv-479[pctva] ksodcbwnsr-pogysh-gsfjwqsg-584[sgowb] dmybmsuzs-pkq-mzmxkeue-612[meksu] xmtjbzidx-xviyt-vxlpdndodji-577[dxijt] dpmpsgvm-kfmmzcfbo-bobmztjt-701[mbfop] oxjmxdfkd-pzxsbkdbo-erkq-xznrfpfqflk-627[jhlvw] npmhcargjc-aylbw-amyrgle-pcacgtgle-652[acgle] votubcmf-fhh-tfswjdft-701[fthbc] gzefmnxq-dmnnuf-geqd-fqefuzs-482[fenqd] dmpuamofuhq-oazegyqd-sdmpq-eomhqzsqd-tgzf-emxqe-378[mctsn] gzefmnxq-dmnnuf-etubbuzs-508[nubef] bwx-amkzmb-ntwemz-ivitgaqa-902[noeig] rdchjbtg-vgpst-qphzti-pcpanhxh-635[hptcg] qzchnzbshud-atmmx-sqzhmhmf-131[hmzqs] tipfxvezt-treup-tfrkzex-cfxzjkztj-633[tzefx] mvhkvbdib-wpiit-vivgtndn-603[ivbdn] hqfxxnknji-ojqqdgjfs-htsyfnsrjsy-957[bdtai] clxalrtyr-clmmte-dezclrp-275[lcrem] fubrjhqlf-udpsdjlqj-udeelw-ghyhorsphqw-387[hdjlq] qzoggwtwsr-dzoghwq-ufogg-hsqvbczcum-792[goqwz] nvrgfezqvu-sleep-ivtvzmzex-113[evzfg] fruurvlyh-iorzhu-orjlvwlfv-881[jcdtf] myxcewob-qbkno-mkxni-mykdsxq-nozvyiwoxd-900[oxkmn] wyvqljapsl-jhukf-jvhapun-aljouvsvnf-955[jvalu] tpspahyf-nyhkl-jhukf-zhslz-643[pytob] kgjgrypw-epybc-rmn-qcapcr-qaytclecp-fslr-nspafyqgle-938[mxunk] yknnkoera-zua-klanwpekjo-446[dphwe] kzgwomvqk-xtiabqk-oziaa-bziqvqvo-278[qaiko] iruzfrtkzmv-wcfnvi-rercpjzj-555[rzcfi] diozmivodjivg-apuut-nxvqzibzm-cpio-yzkvmohzio-447[iozvm] fydelmwp-ojp-nzyeltyxpye-405[nyzmg] ktiaaqnqml-ziuxioqvo-kivlg-kwibqvo-zmikycqaqbqwv-564[qikva] xst-wigvix-ikk-vieguymwmxmsr-724[imxgk] jfifqxov-doxab-ciltbo-jxohbqfkd-965[obfxd] rdggdhxkt-hrpktcvtg-wjci-rdcipxcbtci-531[ctdgi] awzwhofm-ufors-qobrm-qcohwbu-oqeiwgwhwcb-896[mkvzu] vagreangvbany-fpniratre-uhag-qrcnegzrag-689[xfuaz] vjpwncrl-lqxlxujcn-jlzdrbrcrxw-693[lrcjx] ibghopzs-dzoghwq-ufogg-rsdzcmasbh-948[ghosz] ynssr-vhglnfxk-zktwx-ietlmbv-zktll-phkdlahi-917[lkhti] tfcfiwlc-treup-tfrkzex-dribvkzex-685[efrtc] frqvxphu-judgh-fkrfrodwh-hqjlqhhulqj-803[wjnmk] vhkkhlbox-xzz-kxtvjnblbmbhg-631[bhkxl] ltpedcxots-snt-stepgibtci-297[tscei] nzwzcqfw-nlyoj-xlylrpxpye-275[lynpw] ejpanjwpekjwh-nwilwcejc-zua-hkceopeyo-498[ypoze] sno-rdbqds-azrjds-rghoohmf-859[dorsh] qzoggwtwsr-suu-qcbhowbasbh-480[bswgh] gvcskirmg-ikk-gywxsqiv-wivzmgi-698[rmvil] ktwbhtvmbox-ftzgxmbv-vtgwr-ftkdxmbgz-163[tbgmv] oxmeeuruqp-omzpk-oamfuzs-efadmsq-716[meoua] xjinphzm-bmvyz-hvbizodx-xviyt-xjvodib-ozxcijgjbt-343[ixbjv] jyfvnlupj-ibuuf-svnpzapjz-851[gmsnf]|]
rickerbh/AoC
AoC2016/src/AoC201604.hs
mit
48,937
0
12
1,587
863
444
419
74
2
{- | module: $Header$ description: Bytes license: MIT maintainer: Joe Leslie-Hurd <joe@gilith.com> stability: provisional portability: portable -} module OpenTheory.Byte where import qualified OpenTheory.Natural.Uniform as Uniform import qualified OpenTheory.Primitive.Byte as Byte import qualified OpenTheory.Primitive.Natural as Natural import qualified OpenTheory.Primitive.Random as Random width :: Natural.Natural width = 8 modulus :: Natural.Natural modulus = 2 ^ width random :: Random.Random -> Byte.Byte random r = Byte.fromNatural (Uniform.random modulus r)
gilith/opentheory
data/haskell/opentheory-byte/src/OpenTheory/Byte.hs
mit
574
0
8
72
107
67
40
11
1
-- ---------------------------------------------------------------------- -- GenI surface realiser -- Copyright (C) 2009 Eric Kow -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- ---------------------------------------------------------------------- module NLP.GenI.Test where import Control.Applicative import Data.List ( isPrefixOf ) import Data.Maybe import System.Environment ( getArgs ) import Test.Framework import NLP.GenI.Test.FeatureStructure ( suite ) import NLP.GenI.Test.Parser ( suite ) import NLP.GenI.Test.GeniVal ( suite ) import NLP.GenI.Test.LexicalSelection ( suite ) import NLP.GenI.Test.Lexicon ( suite ) import NLP.GenI.Test.Morphology ( suite ) import NLP.GenI.Test.Polarity ( suite ) import NLP.GenI.Test.Semantics ( suite ) import NLP.GenI.Test.Simple.SimpleBuilder ( suite ) import NLP.GenI.Regression runTests :: IO () runTests = do args <- filter (not . (`isPrefixOf` "--unit-tests")) `fmap` getArgs funcSuite <- NLP.GenI.Regression.mkSuite opts_ <- interpretArgsOrExit args let topts = fromMaybe emptyOptions (ropt_test_options opts_) opts = opts_ { ropt_test_options = Just $ setMaxTests 25 topts } flip defaultMainWithOpts opts [ NLP.GenI.Test.GeniVal.suite , NLP.GenI.Test.Parser.suite , NLP.GenI.Test.FeatureStructure.suite , NLP.GenI.Test.LexicalSelection.suite , NLP.GenI.Test.Lexicon.suite , NLP.GenI.Test.Morphology.suite , NLP.GenI.Test.Polarity.suite , NLP.GenI.Test.Semantics.suite , NLP.GenI.Test.Simple.SimpleBuilder.suite , funcSuite ] setMaxTests :: Int -> TestOptions -> TestOptions setMaxTests m opts = case topt_maximum_generated_tests opts of Nothing -> opts { topt_maximum_generated_tests = Just m } Just _ -> opts emptyOptions :: TestOptions emptyOptions = TestOptions Nothing Nothing Nothing Nothing Nothing Nothing
kowey/GenI
geni-test/NLP/GenI/Test.hs
gpl-2.0
2,584
0
13
461
447
278
169
41
2
------------------------------------------------------------------------------- {-# LANGUAGE Arrows #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} module Main (main) where -------------------------------------------------------------------------------- import Data.Monoid ((<>), mconcat, mappend) import Prelude hiding (id) import qualified Text.Pandoc as Pandoc -------------------------------------------------------------------------------- import Hakyll -------------------------------------------------------------------------------- -- | Entry point main :: IO () main = hakyllWith config $ do -- Static files match ("favicon.ico" .||. "robots.txt") $ do route idRoute compile copyFileCompiler -- Compress CSS match "css/*" $ do route idRoute compile compressCssCompiler -- Copy JS match "js/*" $ do route idRoute compile copyFileCompiler -- copy static assets let assets = ["404.html", "github-btn.html", "images/*", "reveal.js/**"] match (foldr1 (.||.) assets) $ do route idRoute compile copyFileCompiler -- Copy Fonts match "fonts/*" $ do route idRoute compile copyFileCompiler -- Build tags tags <- buildTags "posts/*" (fromCapture "tags/*.html") -- Render each and every post match "posts/*" $ do route $ setExtension ".html" compile $ do pandocCompiler >>= saveSnapshot "content" >>= loadAndApplyTemplate "templates/post.html" (postCtx tags) >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls -- Render each and every slide match "slides/*" $ do route $ setExtension ".html" compile $ do pandocRevealJsCompiler >>= saveSnapshot "content" >>= loadAndApplyTemplate "templates/slides.html" defaultContext >>= relativizeUrls -- Render each and every news match "news/*" $ do route $ setExtension ".html" compile $ do pandocCompiler >>= saveSnapshot "content" >>= relativizeUrls -- Post list create ["posts.html"] $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "posts/*" let ctx = constField "title" "Posts" <> listField "posts" (postCtx tags) (return posts) <> defaultContext makeItem "" >>= loadAndApplyTemplate "templates/posts.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx >>= relativizeUrls -- Slide list create ["slides.html"] $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "slides/*" let ctx = constField "title" "Slides" <> listField "posts" (postCtx tags) (return posts) <> defaultContext makeItem "" >>= loadAndApplyTemplate "templates/posts.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx >>= relativizeUrls -- News list match "news.html" $ do route idRoute compile $ do news <- recentFirst =<< loadAll "news/*" let ctx = constField "title" "News" <> listField "news" (postCtx tags) (return news) <> defaultContext getResourceBody >>= applyAsTemplate ctx >>= loadAndApplyTemplate "templates/main.html" ctx >>= relativizeUrls -- Post tags tagsRules tags $ \tag pattern -> do let title = "Posts tagged " ++ tag -- Copied from posts, need to refactor route idRoute compile $ do posts <- recentFirst =<< loadAll pattern let ctx = constField "title" title <> listField "posts" (postCtx tags) (return posts) <> defaultContext makeItem "" >>= loadAndApplyTemplate "templates/posts.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx >>= relativizeUrls create ["tags.html"] $ do route idRoute compile $ do let ctx = constField "title" "Tags" `mappend` defaultContext renderTagCloud 100 300 tags >>= makeItem >>= loadAndApplyTemplate "templates/tags.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx >>= relativizeUrls -- Index match "index.html" $ do route idRoute compile $ do news <- fmap (take 3) . recentFirst =<< loadAll "news/*" let ctx = listField "news" (postCtx tags) (return news) <> constField "title" "Index" `mappend` defaultContext getResourceBody >>= applyAsTemplate ctx >>= loadAndApplyTemplate "templates/main.html" ctx >>= relativizeUrls -- Blog match "blog.html" $ do route idRoute compile $ do posts <- fmap (take 18) . recentFirst =<< loadAll "posts/*" let indexContext = constField "title" "Blog" <> listField "posts" (postCtx tags) (return posts) <> field "tags" (\_ -> renderTagCloud 100 300 tags) <> defaultContext getResourceBody >>= applyAsTemplate indexContext >>= loadAndApplyTemplate "templates/default.html" indexContext >>= relativizeUrls -- Read templates match "templates/*" $ compile $ templateCompiler -- Render some static pages match (fromList ["about.markdown"]) $ do route $ setExtension ".html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/contacts.html" defaultContext >>= loadAndApplyTemplate "templates/main.html" defaultContext >>= relativizeUrls match (fromList ["projects.markdown", "research.markdown"]) $ do route $ setExtension ".html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/main.html" defaultContext >>= relativizeUrls -- Render RSS feed create ["rss.xml"] $ do let title = "Atom feed" route idRoute compile $ do loadAllSnapshots "posts/*" "content" >>= fmap (take 10) . recentFirst >>= renderAtom (feedConfiguration title) feedCtx -------------------------------------------------------------------------------- pandocRevealJsCompiler :: Compiler (Item String) pandocRevealJsCompiler = let writerOptions = Pandoc.def { Pandoc.writerHtml5 = True, Pandoc.writerSlideVariant=Pandoc.RevealJsSlides } in pandocCompilerWith defaultHakyllReaderOptions writerOptions -------------------------------------------------------------------------------- postCtx :: Tags -> Context String postCtx tags = mconcat [ modificationTimeField "mtime" "%U" , dateField "date" "%B %e, %Y" , tagsField "tags" tags , defaultContext ] -------------------------------------------------------------------------------- feedCtx :: Context String feedCtx = mconcat [ bodyField "description" , defaultContext ] -------------------------------------------------------------------------------- config :: Configuration config = defaultConfiguration { deployCommand = "rsync --checksum --delete -ave 'ssh' \ \_site/* shi2wei3@github.com:shi2wei3.github.io" } -------------------------------------------------------------------------------- feedConfiguration :: String -> FeedConfiguration feedConfiguration title = FeedConfiguration { feedTitle = "John - " ++ title , feedDescription = "Personal blog of Wei Shi" , feedAuthorName = "Wei Shi" , feedAuthorEmail = "shi2wie3@gmail.com" , feedRoot = "http://shi2wei3.github.io" } --------------------------------------------------------------------------------
shi2wei3/hakyll_blog
src/Main.hs
gpl-2.0
8,478
0
22
2,700
1,607
759
848
171
1
module Tree ( Tree(..) , singleton , treeInsert , YesNo(..) ) where import Data.Monoid import qualified Data.Foldable as F class YesNo a where yesno :: a -> Bool data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) singleton :: a -> Tree a singleton x = Node x Empty Empty treeInsert :: (Ord a) => a -> Tree a -> Tree a treeInsert x Empty = singleton x treeInsert x (Node a left right) | x == a = Node x left right | x < a = Node a (treeInsert x left) right | x > a = Node a left (treeInsert x right) treeElem :: (Ord a) => a -> Tree a -> Bool treeElem x Empty = False treeElem x (Node a left right) | x == a = True | x < a = treeElem x left | x > a = treeElem x right instance YesNo (Tree a) where yesno Empty = False yesno _ = True instance Functor Tree where fmap f Empty = Empty fmap f (Node x l r) = Node (f x) (fmap f l) (fmap f r) instance F.Foldable Tree where foldMap f Empty = mempty foldMap f (Node x l r) = F.foldMap f l `mappend` f x `mappend` F.foldMap f r treeToList :: Tree a -> [a] treeToList = F.foldMap (\x -> [x])
friedbrice/Haskell
ch11/Tree.hs
gpl-2.0
1,192
0
9
370
565
287
278
37
1
{-| Implementation of cluster-wide logic. This module holds all pure cluster-logic; I\/O related functionality goes into the /Main/ module for the individual binaries. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.HTools.Cluster ( -- * Types AllocDetails(..) , AllocSolution(..) , EvacSolution(..) , Table(..) , CStats(..) , AllocNodes , AllocResult , AllocMethod , AllocSolutionList -- * Generic functions , totalResources , computeAllocationDelta -- * First phase functions , computeBadItems -- * Second phase functions , printSolutionLine , formatCmds , involvedNodes , getMoves , splitJobs -- * Display functions , printNodes , printInsts -- * Balacing functions , doNextBalance , tryBalance , compCV , compCVNodes , compDetailedCV , printStats , iMoveToJob -- * IAllocator functions , genAllocNodes , tryAlloc , tryGroupAlloc , tryMGAlloc , tryNodeEvac , tryChangeGroup , collapseFailures , allocList -- * Allocation functions , iterateAlloc , tieredAlloc -- * Node group functions , instanceGroup , findSplitInstances , splitCluster ) where import Control.Applicative ((<$>), liftA2) import Control.Arrow ((&&&)) import Control.Monad (unless) import qualified Data.IntSet as IntSet import Data.List import Data.Maybe (fromJust, fromMaybe, isJust, isNothing) import Data.Ord (comparing) import Text.Printf (printf) import Ganeti.BasicTypes import Ganeti.HTools.AlgorithmParams (AlgorithmOptions(..)) import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Nic as Nic import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Group as Group import Ganeti.HTools.Types import Ganeti.Compat import qualified Ganeti.OpCodes as OpCodes import Ganeti.Utils import Ganeti.Utils.Statistics import Ganeti.Types (EvacMode(..), mkNonEmpty) -- * Types -- | Allocation details for an instance, specifying -- | required number of nodes, and -- | an optional group (name) to allocate to data AllocDetails = AllocDetails Int (Maybe String) deriving (Show) -- | Allocation\/relocation solution. data AllocSolution = AllocSolution { asFailures :: [FailMode] -- ^ Failure counts , asAllocs :: Int -- ^ Good allocation count , asSolution :: Maybe Node.AllocElement -- ^ The actual allocation result , asLog :: [String] -- ^ Informational messages } -- | Node evacuation/group change iallocator result type. This result -- type consists of actual opcodes (a restricted subset) that are -- transmitted back to Ganeti. data EvacSolution = EvacSolution { esMoved :: [(Idx, Gdx, [Ndx])] -- ^ Instances moved successfully , esFailed :: [(Idx, String)] -- ^ Instances which were not -- relocated , esOpCodes :: [[OpCodes.OpCode]] -- ^ List of jobs } deriving (Show) -- | Allocation results, as used in 'iterateAlloc' and 'tieredAlloc'. type AllocResult = (FailStats, Node.List, Instance.List, [Instance.Instance], [CStats]) -- | Type alias for easier handling. type AllocSolutionList = [(Instance.Instance, AllocSolution)] -- | A type denoting the valid allocation mode/pairs. -- -- For a one-node allocation, this will be a @Left ['Ndx']@, whereas -- for a two-node allocation, this will be a @Right [('Ndx', -- ['Ndx'])]@. In the latter case, the list is basically an -- association list, grouped by primary node and holding the potential -- secondary nodes in the sub-list. type AllocNodes = Either [Ndx] [(Ndx, [Ndx])] -- | The empty solution we start with when computing allocations. emptyAllocSolution :: AllocSolution emptyAllocSolution = AllocSolution { asFailures = [], asAllocs = 0 , asSolution = Nothing, asLog = [] } -- | The empty evac solution. emptyEvacSolution :: EvacSolution emptyEvacSolution = EvacSolution { esMoved = [] , esFailed = [] , esOpCodes = [] } -- | The complete state for the balancing solution. data Table = Table Node.List Instance.List Score [Placement] deriving (Show) -- | Cluster statistics data type. data CStats = CStats { csFmem :: Integer -- ^ Cluster free mem , csFdsk :: Integer -- ^ Cluster free disk , csFspn :: Integer -- ^ Cluster free spindles , csAmem :: Integer -- ^ Cluster allocatable mem , csAdsk :: Integer -- ^ Cluster allocatable disk , csAcpu :: Integer -- ^ Cluster allocatable cpus , csMmem :: Integer -- ^ Max node allocatable mem , csMdsk :: Integer -- ^ Max node allocatable disk , csMcpu :: Integer -- ^ Max node allocatable cpu , csImem :: Integer -- ^ Instance used mem , csIdsk :: Integer -- ^ Instance used disk , csIspn :: Integer -- ^ Instance used spindles , csIcpu :: Integer -- ^ Instance used cpu , csTmem :: Double -- ^ Cluster total mem , csTdsk :: Double -- ^ Cluster total disk , csTspn :: Double -- ^ Cluster total spindles , csTcpu :: Double -- ^ Cluster total cpus , csVcpu :: Integer -- ^ Cluster total virtual cpus , csNcpu :: Double -- ^ Equivalent to 'csIcpu' but in terms of -- physical CPUs, i.e. normalised used phys CPUs , csXmem :: Integer -- ^ Unnacounted for mem , csNmem :: Integer -- ^ Node own memory , csScore :: Score -- ^ The cluster score , csNinst :: Int -- ^ The total number of instances } deriving (Show) -- | A simple type for allocation functions. type AllocMethod = Node.List -- ^ Node list -> Instance.List -- ^ Instance list -> Maybe Int -- ^ Optional allocation limit -> Instance.Instance -- ^ Instance spec for allocation -> AllocNodes -- ^ Which nodes we should allocate on -> [Instance.Instance] -- ^ Allocated instances -> [CStats] -- ^ Running cluster stats -> Result AllocResult -- ^ Allocation result -- | A simple type for the running solution of evacuations. type EvacInnerState = Either String (Node.List, Instance.Instance, Score, Ndx) -- * Utility functions -- | Verifies the N+1 status and return the affected nodes. verifyN1 :: [Node.Node] -> [Node.Node] verifyN1 = filter Node.failN1 {-| Computes the pair of bad nodes and instances. The bad node list is computed via a simple 'verifyN1' check, and the bad instance list is the list of primary and secondary instances of those nodes. -} computeBadItems :: Node.List -> Instance.List -> ([Node.Node], [Instance.Instance]) computeBadItems nl il = let bad_nodes = verifyN1 $ getOnline nl bad_instances = map (`Container.find` il) . sort . nub $ concatMap (\ n -> Node.sList n ++ Node.pList n) bad_nodes in (bad_nodes, bad_instances) -- | Extracts the node pairs for an instance. This can fail if the -- instance is single-homed. FIXME: this needs to be improved, -- together with the general enhancement for handling non-DRBD moves. instanceNodes :: Node.List -> Instance.Instance -> (Ndx, Ndx, Node.Node, Node.Node) instanceNodes nl inst = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_p = Container.find old_pdx nl old_s = Container.find old_sdx nl in (old_pdx, old_sdx, old_p, old_s) -- | Zero-initializer for the CStats type. emptyCStats :: CStats emptyCStats = CStats 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -- | Update stats with data from a new node. updateCStats :: CStats -> Node.Node -> CStats updateCStats cs node = let CStats { csFmem = x_fmem, csFdsk = x_fdsk, csAmem = x_amem, csAcpu = x_acpu, csAdsk = x_adsk, csMmem = x_mmem, csMdsk = x_mdsk, csMcpu = x_mcpu, csImem = x_imem, csIdsk = x_idsk, csIcpu = x_icpu, csTmem = x_tmem, csTdsk = x_tdsk, csTcpu = x_tcpu, csVcpu = x_vcpu, csNcpu = x_ncpu, csXmem = x_xmem, csNmem = x_nmem, csNinst = x_ninst, csFspn = x_fspn, csIspn = x_ispn, csTspn = x_tspn } = cs inc_amem = Node.fMem node - Node.rMem node inc_amem' = if inc_amem > 0 then inc_amem else 0 inc_adsk = Node.availDisk node inc_imem = truncate (Node.tMem node) - Node.nMem node - Node.xMem node - Node.fMem node inc_icpu = Node.uCpu node inc_idsk = truncate (Node.tDsk node) - Node.fDsk node inc_ispn = Node.tSpindles node - Node.fSpindles node inc_vcpu = Node.hiCpu node inc_acpu = Node.availCpu node inc_ncpu = fromIntegral (Node.uCpu node) / iPolicyVcpuRatio (Node.iPolicy node) in cs { csFmem = x_fmem + fromIntegral (Node.fMem node) , csFdsk = x_fdsk + fromIntegral (Node.fDsk node) , csFspn = x_fspn + fromIntegral (Node.fSpindles node) , csAmem = x_amem + fromIntegral inc_amem' , csAdsk = x_adsk + fromIntegral inc_adsk , csAcpu = x_acpu + fromIntegral inc_acpu , csMmem = max x_mmem (fromIntegral inc_amem') , csMdsk = max x_mdsk (fromIntegral inc_adsk) , csMcpu = max x_mcpu (fromIntegral inc_acpu) , csImem = x_imem + fromIntegral inc_imem , csIdsk = x_idsk + fromIntegral inc_idsk , csIspn = x_ispn + fromIntegral inc_ispn , csIcpu = x_icpu + fromIntegral inc_icpu , csTmem = x_tmem + Node.tMem node , csTdsk = x_tdsk + Node.tDsk node , csTspn = x_tspn + fromIntegral (Node.tSpindles node) , csTcpu = x_tcpu + Node.tCpu node , csVcpu = x_vcpu + fromIntegral inc_vcpu , csNcpu = x_ncpu + inc_ncpu , csXmem = x_xmem + fromIntegral (Node.xMem node) , csNmem = x_nmem + fromIntegral (Node.nMem node) , csNinst = x_ninst + length (Node.pList node) } -- | Compute the total free disk and memory in the cluster. totalResources :: Node.List -> CStats totalResources nl = let cs = foldl' updateCStats emptyCStats . Container.elems $ nl in cs { csScore = compCV nl } -- | Compute the delta between two cluster state. -- -- This is used when doing allocations, to understand better the -- available cluster resources. The return value is a triple of the -- current used values, the delta that was still allocated, and what -- was left unallocated. computeAllocationDelta :: CStats -> CStats -> AllocStats computeAllocationDelta cini cfin = let CStats {csImem = i_imem, csIdsk = i_idsk, csIcpu = i_icpu, csNcpu = i_ncpu, csIspn = i_ispn } = cini CStats {csImem = f_imem, csIdsk = f_idsk, csIcpu = f_icpu, csTmem = t_mem, csTdsk = t_dsk, csVcpu = f_vcpu, csNcpu = f_ncpu, csTcpu = f_tcpu, csIspn = f_ispn, csTspn = t_spn } = cfin rini = AllocInfo { allocInfoVCpus = fromIntegral i_icpu , allocInfoNCpus = i_ncpu , allocInfoMem = fromIntegral i_imem , allocInfoDisk = fromIntegral i_idsk , allocInfoSpn = fromIntegral i_ispn } rfin = AllocInfo { allocInfoVCpus = fromIntegral (f_icpu - i_icpu) , allocInfoNCpus = f_ncpu - i_ncpu , allocInfoMem = fromIntegral (f_imem - i_imem) , allocInfoDisk = fromIntegral (f_idsk - i_idsk) , allocInfoSpn = fromIntegral (f_ispn - i_ispn) } runa = AllocInfo { allocInfoVCpus = fromIntegral (f_vcpu - f_icpu) , allocInfoNCpus = f_tcpu - f_ncpu , allocInfoMem = truncate t_mem - fromIntegral f_imem , allocInfoDisk = truncate t_dsk - fromIntegral f_idsk , allocInfoSpn = truncate t_spn - fromIntegral f_ispn } in (rini, rfin, runa) -- | The names and weights of the individual elements in the CV list, together -- with their statistical accumulation function and a bit to decide whether it -- is a statistics for online nodes. detailedCVInfoExt :: [((Double, String), ([Double] -> Statistics, Bool))] detailedCVInfoExt = [ ((1, "free_mem_cv"), (getStdDevStatistics, True)) , ((1, "free_disk_cv"), (getStdDevStatistics, True)) , ((1, "n1_cnt"), (getSumStatistics, True)) , ((1, "reserved_mem_cv"), (getStdDevStatistics, True)) , ((4, "offline_all_cnt"), (getSumStatistics, False)) , ((16, "offline_pri_cnt"), (getSumStatistics, False)) , ((1, "vcpu_ratio_cv"), (getStdDevStatistics, True)) , ((1, "cpu_load_cv"), (getStdDevStatistics, True)) , ((1, "mem_load_cv"), (getStdDevStatistics, True)) , ((1, "disk_load_cv"), (getStdDevStatistics, True)) , ((1, "net_load_cv"), (getStdDevStatistics, True)) , ((2, "pri_tags_score"), (getSumStatistics, True)) , ((1, "spindles_cv"), (getStdDevStatistics, True)) ] -- | The names and weights of the individual elements in the CV list. detailedCVInfo :: [(Double, String)] detailedCVInfo = map fst detailedCVInfoExt -- | Holds the weights used by 'compCVNodes' for each metric. detailedCVWeights :: [Double] detailedCVWeights = map fst detailedCVInfo -- | The aggregation functions for the weights detailedCVAggregation :: [([Double] -> Statistics, Bool)] detailedCVAggregation = map snd detailedCVInfoExt -- | The bit vector describing which parts of the statistics are -- for online nodes. detailedCVOnlineStatus :: [Bool] detailedCVOnlineStatus = map snd detailedCVAggregation -- | Compute statistical measures of a single node. compDetailedCVNode :: Node.Node -> [Double] compDetailedCVNode node = let mem = Node.pMem node dsk = Node.pDsk node n1 = fromIntegral $ if Node.failN1 node then length (Node.sList node) + length (Node.pList node) else 0 res = Node.pRem node ipri = fromIntegral . length $ Node.pList node isec = fromIntegral . length $ Node.sList node ioff = ipri + isec cpu = Node.pCpuEff node DynUtil c1 m1 d1 nn1 = Node.utilLoad node DynUtil c2 m2 d2 nn2 = Node.utilPool node (c_load, m_load, d_load, n_load) = (c1/c2, m1/m2, d1/d2, nn1/nn2) pri_tags = fromIntegral $ Node.conflictingPrimaries node spindles = Node.instSpindles node / Node.hiSpindles node in [ mem, dsk, n1, res, ioff, ipri, cpu , c_load, m_load, d_load, n_load , pri_tags, spindles ] -- | Compute the statistics of a cluster. compClusterStatistics :: [Node.Node] -> [Statistics] compClusterStatistics all_nodes = let (offline, nodes) = partition Node.offline all_nodes offline_values = transpose (map compDetailedCVNode offline) ++ repeat [] -- transpose of an empty list is empty and not k times the empty list, as -- would be the transpose of a 0 x k matrix online_values = transpose $ map compDetailedCVNode nodes aggregate (f, True) (onNodes, _) = f onNodes aggregate (f, False) (_, offNodes) = f offNodes in zipWith aggregate detailedCVAggregation $ zip online_values offline_values -- | Update a cluster statistics by replacing the contribution of one -- node by that of another. updateClusterStatistics :: [Statistics] -> (Node.Node, Node.Node) -> [Statistics] updateClusterStatistics stats (old, new) = let update = zip (compDetailedCVNode old) (compDetailedCVNode new) online = not $ Node.offline old updateStat forOnline stat upd = if forOnline == online then updateStatistics stat upd else stat in zipWith3 updateStat detailedCVOnlineStatus stats update -- | Update a cluster statistics twice. updateClusterStatisticsTwice :: [Statistics] -> (Node.Node, Node.Node) -> (Node.Node, Node.Node) -> [Statistics] updateClusterStatisticsTwice s a = updateClusterStatistics (updateClusterStatistics s a) -- | Compute cluster statistics compDetailedCV :: [Node.Node] -> [Double] compDetailedCV = map getStatisticValue . compClusterStatistics -- | Compute the cluster score from its statistics compCVfromStats :: [Statistics] -> Double compCVfromStats = sum . zipWith (*) detailedCVWeights . map getStatisticValue -- | Compute the /total/ variance. compCVNodes :: [Node.Node] -> Double compCVNodes = sum . zipWith (*) detailedCVWeights . compDetailedCV -- | Wrapper over 'compCVNodes' for callers that have a 'Node.List'. compCV :: Node.List -> Double compCV = compCVNodes . Container.elems -- | Compute online nodes from a 'Node.List'. getOnline :: Node.List -> [Node.Node] getOnline = filter (not . Node.offline) . Container.elems -- * Balancing functions -- | Compute best table. Note that the ordering of the arguments is important. compareTables :: Table -> Table -> Table compareTables a@(Table _ _ a_cv _) b@(Table _ _ b_cv _ ) = if a_cv > b_cv then b else a -- | Applies an instance move to a given node list and instance. applyMoveEx :: Bool -- ^ whether to ignore soft errors -> Node.List -> Instance.Instance -> IMove -> OpResult (Node.List, Instance.Instance, Ndx, Ndx) -- Failover (f) applyMoveEx force nl inst Failover = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst new_nl = do -- Maybe monad new_p <- Node.addPriEx (Node.offline old_p || force) int_s inst new_s <- Node.addSec int_p inst old_sdx let new_inst = Instance.setBoth inst old_sdx old_pdx return (Container.addTwo old_pdx new_s old_sdx new_p nl, new_inst, old_sdx, old_pdx) in new_nl -- Failover to any (fa) applyMoveEx force nl inst (FailoverToAny new_pdx) = do let (old_pdx, old_sdx, old_pnode, _) = instanceNodes nl inst new_pnode = Container.find new_pdx nl force_failover = Node.offline old_pnode || force new_pnode' <- Node.addPriEx force_failover new_pnode inst let old_pnode' = Node.removePri old_pnode inst inst' = Instance.setPri inst new_pdx nl' = Container.addTwo old_pdx old_pnode' new_pdx new_pnode' nl return (nl', inst', new_pdx, old_sdx) -- Replace the primary (f:, r:np, f) applyMoveEx force nl inst (ReplacePrimary new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p || force new_nl = do -- Maybe monad -- check that the current secondary can host the instance -- during the migration tmp_s <- Node.addPriEx force_p int_s inst let tmp_s' = Node.removePri tmp_s inst new_p <- Node.addPriEx force_p tgt_n inst new_s <- Node.addSecEx force_p tmp_s' inst new_pdx let new_inst = Instance.setPri inst new_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx int_p old_sdx new_s nl, new_inst, new_pdx, old_sdx) in new_nl -- Replace the secondary (r:ns) applyMoveEx force nl inst (ReplaceSecondary new_sdx) = let old_pdx = Instance.pNode inst old_sdx = Instance.sNode inst old_s = Container.find old_sdx nl tgt_n = Container.find new_sdx nl int_s = Node.removeSec old_s inst force_s = Node.offline old_s || force new_inst = Instance.setSec inst new_sdx new_nl = Node.addSecEx force_s tgt_n inst old_pdx >>= \new_s -> return (Container.addTwo new_sdx new_s old_sdx int_s nl, new_inst, old_pdx, new_sdx) in new_nl -- Replace the secondary and failover (r:np, f) applyMoveEx force nl inst (ReplaceAndFailover new_pdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_pdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_s = Node.offline old_s || force new_nl = do -- Maybe monad new_p <- Node.addPri tgt_n inst new_s <- Node.addSecEx force_s int_p inst new_pdx let new_inst = Instance.setBoth inst new_pdx old_pdx return (Container.add new_pdx new_p $ Container.addTwo old_pdx new_s old_sdx int_s nl, new_inst, new_pdx, old_pdx) in new_nl -- Failver and replace the secondary (f, r:ns) applyMoveEx force nl inst (FailoverAndReplace new_sdx) = let (old_pdx, old_sdx, old_p, old_s) = instanceNodes nl inst tgt_n = Container.find new_sdx nl int_p = Node.removePri old_p inst int_s = Node.removeSec old_s inst force_p = Node.offline old_p || force new_nl = do -- Maybe monad new_p <- Node.addPriEx force_p int_s inst new_s <- Node.addSecEx force_p tgt_n inst old_sdx let new_inst = Instance.setBoth inst old_sdx new_sdx return (Container.add new_sdx new_s $ Container.addTwo old_sdx new_p old_pdx int_p nl, new_inst, old_sdx, new_sdx) in new_nl -- | Applies an instance move to a given node list and instance. applyMove :: Node.List -> Instance.Instance -> IMove -> OpResult (Node.List, Instance.Instance, Ndx, Ndx) applyMove = applyMoveEx False -- | Tries to allocate an instance on one given node. allocateOnSingle :: Node.List -> Instance.Instance -> Ndx -> OpResult Node.AllocElement allocateOnSingle nl inst new_pdx = let p = Container.find new_pdx nl new_inst = Instance.setBoth inst new_pdx Node.noSecondary in do Instance.instMatchesPolicy inst (Node.iPolicy p) (Node.exclStorage p) new_p <- Node.addPri p inst let new_nl = Container.add new_pdx new_p nl new_score = compCV new_nl return (new_nl, new_inst, [new_p], new_score) -- | Tries to allocate an instance on a given pair of nodes. allocateOnPair :: [Statistics] -> Node.List -> Instance.Instance -> Ndx -> Ndx -> OpResult Node.AllocElement allocateOnPair stats nl inst new_pdx new_sdx = let tgt_p = Container.find new_pdx nl tgt_s = Container.find new_sdx nl in do Instance.instMatchesPolicy inst (Node.iPolicy tgt_p) (Node.exclStorage tgt_p) new_p <- Node.addPri tgt_p inst new_s <- Node.addSec tgt_s inst new_pdx let new_inst = Instance.setBoth inst new_pdx new_sdx new_nl = Container.addTwo new_pdx new_p new_sdx new_s nl new_stats = updateClusterStatisticsTwice stats (tgt_p, new_p) (tgt_s, new_s) return (new_nl, new_inst, [new_p, new_s], compCVfromStats new_stats) -- | Tries to perform an instance move and returns the best table -- between the original one and the new one. checkSingleStep :: Bool -- ^ Whether to unconditionally ignore soft errors -> Table -- ^ The original table -> Instance.Instance -- ^ The instance to move -> Table -- ^ The current best table -> IMove -- ^ The move to apply -> Table -- ^ The final best table checkSingleStep force ini_tbl target cur_tbl move = let Table ini_nl ini_il _ ini_plc = ini_tbl tmp_resu = applyMoveEx force ini_nl target move in case tmp_resu of Bad _ -> cur_tbl Ok (upd_nl, new_inst, pri_idx, sec_idx) -> let tgt_idx = Instance.idx target upd_cvar = compCV upd_nl upd_il = Container.add tgt_idx new_inst ini_il upd_plc = (tgt_idx, pri_idx, sec_idx, move, upd_cvar):ini_plc upd_tbl = Table upd_nl upd_il upd_cvar upd_plc in compareTables cur_tbl upd_tbl -- | Given the status of the current secondary as a valid new node and -- the current candidate target node, generate the possible moves for -- a instance. possibleMoves :: MirrorType -- ^ The mirroring type of the instance -> Bool -- ^ Whether the secondary node is a valid new node -> Bool -- ^ Whether we can change the primary node -> (Bool, Bool) -- ^ Whether migration is restricted and whether -- the instance primary is offline -> Ndx -- ^ Target node candidate -> [IMove] -- ^ List of valid result moves possibleMoves MirrorNone _ _ _ _ = [] possibleMoves MirrorExternal _ False _ _ = [] possibleMoves MirrorExternal _ True _ tdx = [ FailoverToAny tdx ] possibleMoves MirrorInternal _ False _ tdx = [ ReplaceSecondary tdx ] possibleMoves MirrorInternal _ _ (True, False) tdx = [ ReplaceSecondary tdx ] possibleMoves MirrorInternal True True (False, _) tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx , ReplacePrimary tdx , FailoverAndReplace tdx ] possibleMoves MirrorInternal True True (True, True) tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx , FailoverAndReplace tdx ] possibleMoves MirrorInternal False True _ tdx = [ ReplaceSecondary tdx , ReplaceAndFailover tdx ] -- | Compute the best move for a given instance. checkInstanceMove :: AlgorithmOptions -- ^ Algorithmic options for balancing -> [Ndx] -- ^ Allowed target node indices -> Table -- ^ Original table -> Instance.Instance -- ^ Instance to move -> Table -- ^ Best new table for this instance checkInstanceMove opts nodes_idx ini_tbl@(Table nl _ _ _) target = let force = algIgnoreSoftErrors opts disk_moves = algDiskMoves opts inst_moves = algInstanceMoves opts rest_mig = algRestrictedMigration opts opdx = Instance.pNode target osdx = Instance.sNode target bad_nodes = [opdx, osdx] nodes = filter (`notElem` bad_nodes) nodes_idx mir_type = Instance.mirrorType target use_secondary = elem osdx nodes_idx && inst_moves aft_failover = if mir_type == MirrorInternal && use_secondary -- if drbd and allowed to failover then checkSingleStep force ini_tbl target ini_tbl Failover else ini_tbl primary_drained = Node.offline . flip Container.find nl $ Instance.pNode target all_moves = if disk_moves then concatMap (possibleMoves mir_type use_secondary inst_moves (rest_mig, primary_drained)) nodes else [] in -- iterate over the possible nodes for this instance foldl' (checkSingleStep force ini_tbl target) aft_failover all_moves -- | Compute the best next move. checkMove :: AlgorithmOptions -- ^ Algorithmic options for balancing -> [Ndx] -- ^ Allowed target node indices -> Table -- ^ The current solution -> [Instance.Instance] -- ^ List of instances still to move -> Table -- ^ The new solution checkMove opts nodes_idx ini_tbl victims = let Table _ _ _ ini_plc = ini_tbl -- we're using rwhnf from the Control.Parallel.Strategies -- package; we don't need to use rnf as that would force too -- much evaluation in single-threaded cases, and in -- multi-threaded case the weak head normal form is enough to -- spark the evaluation tables = parMap rwhnf (checkInstanceMove opts nodes_idx ini_tbl) victims -- iterate over all instances, computing the best move best_tbl = foldl' compareTables ini_tbl tables Table _ _ _ best_plc = best_tbl in if length best_plc == length ini_plc then ini_tbl -- no advancement else best_tbl -- | Check if we are allowed to go deeper in the balancing. doNextBalance :: Table -- ^ The starting table -> Int -- ^ Remaining length -> Score -- ^ Score at which to stop -> Bool -- ^ The resulting table and commands doNextBalance ini_tbl max_rounds min_score = let Table _ _ ini_cv ini_plc = ini_tbl ini_plc_len = length ini_plc in (max_rounds < 0 || ini_plc_len < max_rounds) && ini_cv > min_score -- | Run a balance move. tryBalance :: AlgorithmOptions -- ^ Algorithmic options for balancing -> Table -- ^ The starting table -> Maybe Table -- ^ The resulting table and commands tryBalance opts ini_tbl = let evac_mode = algEvacMode opts mg_limit = algMinGainLimit opts min_gain = algMinGain opts Table ini_nl ini_il ini_cv _ = ini_tbl all_inst = Container.elems ini_il all_nodes = Container.elems ini_nl (offline_nodes, online_nodes) = partition Node.offline all_nodes all_inst' = if evac_mode then let bad_nodes = map Node.idx offline_nodes in filter (any (`elem` bad_nodes) . Instance.allNodes) all_inst else all_inst reloc_inst = filter (\i -> Instance.movable i && Instance.autoBalance i) all_inst' node_idx = map Node.idx online_nodes fin_tbl = checkMove opts node_idx ini_tbl reloc_inst (Table _ _ fin_cv _) = fin_tbl in if fin_cv < ini_cv && (ini_cv > mg_limit || ini_cv - fin_cv >= min_gain) then Just fin_tbl -- this round made success, return the new table else Nothing -- * Allocation functions -- | Build failure stats out of a list of failures. collapseFailures :: [FailMode] -> FailStats collapseFailures flst = map (\k -> (k, foldl' (\a e -> if e == k then a + 1 else a) 0 flst)) [minBound..maxBound] -- | Compares two Maybe AllocElement and chooses the best score. bestAllocElement :: Maybe Node.AllocElement -> Maybe Node.AllocElement -> Maybe Node.AllocElement bestAllocElement a Nothing = a bestAllocElement Nothing b = b bestAllocElement a@(Just (_, _, _, ascore)) b@(Just (_, _, _, bscore)) = if ascore < bscore then a else b -- | Update current Allocation solution and failure stats with new -- elements. concatAllocs :: AllocSolution -> OpResult Node.AllocElement -> AllocSolution concatAllocs as (Bad reason) = as { asFailures = reason : asFailures as } concatAllocs as (Ok ns) = let -- Choose the old or new solution, based on the cluster score cntok = asAllocs as osols = asSolution as nsols = bestAllocElement osols (Just ns) nsuc = cntok + 1 -- Note: we force evaluation of nsols here in order to keep the -- memory profile low - we know that we will need nsols for sure -- in the next cycle, so we force evaluation of nsols, since the -- foldl' in the caller will only evaluate the tuple, but not the -- elements of the tuple in nsols `seq` nsuc `seq` as { asAllocs = nsuc, asSolution = nsols } -- | Sums two 'AllocSolution' structures. sumAllocs :: AllocSolution -> AllocSolution -> AllocSolution sumAllocs (AllocSolution aFails aAllocs aSols aLog) (AllocSolution bFails bAllocs bSols bLog) = -- note: we add b first, since usually it will be smaller; when -- fold'ing, a will grow and grow whereas b is the per-group -- result, hence smaller let nFails = bFails ++ aFails nAllocs = aAllocs + bAllocs nSols = bestAllocElement aSols bSols nLog = bLog ++ aLog in AllocSolution nFails nAllocs nSols nLog -- | Given a solution, generates a reasonable description for it. describeSolution :: AllocSolution -> String describeSolution as = let fcnt = asFailures as sols = asSolution as freasons = intercalate ", " . map (\(a, b) -> printf "%s: %d" (show a) b) . filter ((> 0) . snd) . collapseFailures $ fcnt in case sols of Nothing -> "No valid allocation solutions, failure reasons: " ++ (if null fcnt then "unknown reasons" else freasons) Just (_, _, nodes, cv) -> printf ("score: %.8f, successes %d, failures %d (%s)" ++ " for node(s) %s") cv (asAllocs as) (length fcnt) freasons (intercalate "/" . map Node.name $ nodes) -- | Annotates a solution with the appropriate string. annotateSolution :: AllocSolution -> AllocSolution annotateSolution as = as { asLog = describeSolution as : asLog as } -- | Reverses an evacuation solution. -- -- Rationale: we always concat the results to the top of the lists, so -- for proper jobset execution, we should reverse all lists. reverseEvacSolution :: EvacSolution -> EvacSolution reverseEvacSolution (EvacSolution f m o) = EvacSolution (reverse f) (reverse m) (reverse o) -- | Generate the valid node allocation singles or pairs for a new instance. genAllocNodes :: Group.List -- ^ Group list -> Node.List -- ^ The node map -> Int -- ^ The number of nodes required -> Bool -- ^ Whether to drop or not -- unallocable nodes -> Result AllocNodes -- ^ The (monadic) result genAllocNodes gl nl count drop_unalloc = let filter_fn = if drop_unalloc then filter (Group.isAllocable . flip Container.find gl . Node.group) else id all_nodes = filter_fn $ getOnline nl all_pairs = [(Node.idx p, [Node.idx s | s <- all_nodes, Node.idx p /= Node.idx s, Node.group p == Node.group s]) | p <- all_nodes] in case count of 1 -> Ok (Left (map Node.idx all_nodes)) 2 -> Ok (Right (filter (not . null . snd) all_pairs)) _ -> Bad "Unsupported number of nodes, only one or two supported" -- | Try to allocate an instance on the cluster. tryAlloc :: (Monad m) => Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> AllocNodes -- ^ The allocation targets -> m AllocSolution -- ^ Possible solution list tryAlloc _ _ _ (Right []) = fail "Not enough online nodes" tryAlloc nl _ inst (Right ok_pairs) = let cstat = compClusterStatistics $ Container.elems nl psols = parMap rwhnf (\(p, ss) -> foldl' (\cstate -> concatAllocs cstate . allocateOnPair cstat nl inst p) emptyAllocSolution ss) ok_pairs sols = foldl' sumAllocs emptyAllocSolution psols in return $ annotateSolution sols tryAlloc _ _ _ (Left []) = fail "No online nodes" tryAlloc nl _ inst (Left all_nodes) = let sols = foldl' (\cstate -> concatAllocs cstate . allocateOnSingle nl inst ) emptyAllocSolution all_nodes in return $ annotateSolution sols -- | Given a group/result, describe it as a nice (list of) messages. solutionDescription :: (Group.Group, Result AllocSolution) -> [String] solutionDescription (grp, result) = case result of Ok solution -> map (printf "Group %s (%s): %s" gname pol) (asLog solution) Bad message -> [printf "Group %s: error %s" gname message] where gname = Group.name grp pol = allocPolicyToRaw (Group.allocPolicy grp) -- | From a list of possibly bad and possibly empty solutions, filter -- only the groups with a valid result. Note that the result will be -- reversed compared to the original list. filterMGResults :: [(Group.Group, Result AllocSolution)] -> [(Group.Group, AllocSolution)] filterMGResults = foldl' fn [] where unallocable = not . Group.isAllocable fn accu (grp, rasol) = case rasol of Bad _ -> accu Ok sol | isNothing (asSolution sol) -> accu | unallocable grp -> accu | otherwise -> (grp, sol):accu -- | Sort multigroup results based on policy and score. sortMGResults :: [(Group.Group, AllocSolution)] -> [(Group.Group, AllocSolution)] sortMGResults sols = let extractScore (_, _, _, x) = x solScore (grp, sol) = (Group.allocPolicy grp, (extractScore . fromJust . asSolution) sol) in sortBy (comparing solScore) sols -- | Determines if a group is connected to the networks required by the -- | instance. hasRequiredNetworks :: Group.Group -> Instance.Instance -> Bool hasRequiredNetworks ng = all hasNetwork . Instance.nics where hasNetwork = maybe True (`elem` Group.networks ng) . Nic.network -- | Removes node groups which can't accommodate the instance filterValidGroups :: [(Group.Group, (Node.List, Instance.List))] -> Instance.Instance -> ([(Group.Group, (Node.List, Instance.List))], [String]) filterValidGroups [] _ = ([], []) filterValidGroups (ng:ngs) inst = let (valid_ngs, msgs) = filterValidGroups ngs inst in if hasRequiredNetworks (fst ng) inst then (ng:valid_ngs, msgs) else (valid_ngs, ("group " ++ Group.name (fst ng) ++ " is not connected to a network required by instance " ++ Instance.name inst):msgs) -- | Finds an allocation solution for an instance on a group findAllocation :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Gdx -- ^ The group to allocate to -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result (AllocSolution, [String]) findAllocation mggl mgnl mgil gdx inst cnt = do let belongsTo nl' nidx = nidx `elem` map Node.idx (Container.elems nl') nl = Container.filter ((== gdx) . Node.group) mgnl il = Container.filter (belongsTo nl . Instance.pNode) mgil group' = Container.find gdx mggl unless (hasRequiredNetworks group' inst) . failError $ "The group " ++ Group.name group' ++ " is not connected to\ \ a network required by instance " ++ Instance.name inst solution <- genAllocNodes mggl nl cnt False >>= tryAlloc nl il inst return (solution, solutionDescription (group', return solution)) -- | Finds the best group for an instance on a multi-group cluster. -- -- Only solutions in @preferred@ and @last_resort@ groups will be -- accepted as valid, and additionally if the allowed groups parameter -- is not null then allocation will only be run for those group -- indices. findBestAllocGroup :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Maybe [Gdx] -- ^ The allowed groups -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result (Group.Group, AllocSolution, [String]) findBestAllocGroup mggl mgnl mgil allowed_gdxs inst cnt = let groups_by_idx = splitCluster mgnl mgil groups = map (\(gid, d) -> (Container.find gid mggl, d)) groups_by_idx groups' = maybe groups (\gs -> filter ((`elem` gs) . Group.idx . fst) groups) allowed_gdxs (groups'', filter_group_msgs) = filterValidGroups groups' inst sols = map (\(gr, (nl, il)) -> (gr, genAllocNodes mggl nl cnt False >>= tryAlloc nl il inst)) groups''::[(Group.Group, Result AllocSolution)] all_msgs = filter_group_msgs ++ concatMap solutionDescription sols goodSols = filterMGResults sols sortedSols = sortMGResults goodSols in case sortedSols of [] -> Bad $ if null groups' then "no groups for evacuation: allowed groups was" ++ show allowed_gdxs ++ ", all groups: " ++ show (map fst groups) else intercalate ", " all_msgs (final_group, final_sol):_ -> return (final_group, final_sol, all_msgs) -- | Try to allocate an instance on a multi-group cluster. tryMGAlloc :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result AllocSolution -- ^ Possible solution list tryMGAlloc mggl mgnl mgil inst cnt = do (best_group, solution, all_msgs) <- findBestAllocGroup mggl mgnl mgil Nothing inst cnt let group_name = Group.name best_group selmsg = "Selected group: " ++ group_name return $ solution { asLog = selmsg:all_msgs } -- | Try to allocate an instance to a group. tryGroupAlloc :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> String -- ^ The allocation group (name) -> Instance.Instance -- ^ The instance to allocate -> Int -- ^ Required number of nodes -> Result AllocSolution -- ^ Solution tryGroupAlloc mggl mgnl ngil gn inst cnt = do gdx <- Group.idx <$> Container.findByName mggl gn (solution, msgs) <- findAllocation mggl mgnl ngil gdx inst cnt return $ solution { asLog = msgs } -- | Calculate the new instance list after allocation solution. updateIl :: Instance.List -- ^ The original instance list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Instance.List -- ^ The updated instance list updateIl il Nothing = il updateIl il (Just (_, xi, _, _)) = Container.add (Container.size il) xi il -- | Extract the the new node list from the allocation solution. extractNl :: Node.List -- ^ The original node list -> Maybe Node.AllocElement -- ^ The result of the allocation attempt -> Node.List -- ^ The new node list extractNl nl Nothing = nl extractNl _ (Just (xnl, _, _, _)) = xnl -- | Try to allocate a list of instances on a multi-group cluster. allocList :: Group.List -- ^ The group list -> Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> [(Instance.Instance, AllocDetails)] -- ^ The instance to -- allocate -> AllocSolutionList -- ^ Possible solution -- list -> Result (Node.List, Instance.List, AllocSolutionList) -- ^ The final solution -- list allocList _ nl il [] result = Ok (nl, il, result) allocList gl nl il ((xi, AllocDetails xicnt mgn):xies) result = do ares <- case mgn of Nothing -> tryMGAlloc gl nl il xi xicnt Just gn -> tryGroupAlloc gl nl il gn xi xicnt let sol = asSolution ares nl' = extractNl nl sol il' = updateIl il sol allocList gl nl' il' xies ((xi, ares):result) -- | Function which fails if the requested mode is change secondary. -- -- This is useful since except DRBD, no other disk template can -- execute change secondary; thus, we can just call this function -- instead of always checking for secondary mode. After the call to -- this function, whatever mode we have is just a primary change. failOnSecondaryChange :: (Monad m) => EvacMode -> DiskTemplate -> m () failOnSecondaryChange ChangeSecondary dt = fail $ "Instances with disk template '" ++ diskTemplateToRaw dt ++ "' can't execute change secondary" failOnSecondaryChange _ _ = return () -- | Run evacuation for a single instance. -- -- /Note:/ this function should correctly execute both intra-group -- evacuations (in all modes) and inter-group evacuations (in the -- 'ChangeAll' mode). Of course, this requires that the correct list -- of target nodes is passed. nodeEvacInstance :: Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTDiskless}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance _ _ _ (Instance.Instance {Instance.diskTemplate = DTPlain}) _ _ = fail "Instances of type plain cannot be relocated" nodeEvacInstance _ _ _ (Instance.Instance {Instance.diskTemplate = DTFile}) _ _ = fail "Instances of type file cannot be relocated" nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTSharedFile}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTBlock}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTRbd}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTExt}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il mode inst@(Instance.Instance {Instance.diskTemplate = dt@DTGluster}) gdx avail_nodes = failOnSecondaryChange mode dt >> evacOneNodeOnly nl il inst gdx avail_nodes nodeEvacInstance nl il ChangePrimary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) _ _ = do (nl', inst', _, _) <- opToResult $ applyMove nl inst Failover let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx Failover return (nl', il', ops) nodeEvacInstance nl il ChangeSecondary inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = evacOneNodeOnly nl il inst gdx avail_nodes -- The algorithm for ChangeAll is as follows: -- -- * generate all (primary, secondary) node pairs for the target groups -- * for each pair, execute the needed moves (r:s, f, r:s) and compute -- the final node list state and group score -- * select the best choice via a foldl that uses the same Either -- String solution as the ChangeSecondary mode nodeEvacInstance nl il ChangeAll inst@(Instance.Instance {Instance.diskTemplate = DTDrbd8}) gdx avail_nodes = do let no_nodes = Left "no nodes available" node_pairs = [(p,s) | p <- avail_nodes, s <- avail_nodes, p /= s] (nl', il', ops, _) <- annotateResult "Can't find any good nodes for relocation" . eitherToResult $ foldl' (\accu nodes -> case evacDrbdAllInner nl il inst gdx nodes of Bad msg -> case accu of Right _ -> accu -- we don't need more details (which -- nodes, etc.) as we only selected -- this group if we can allocate on -- it, hence failures will not -- propagate out of this fold loop Left _ -> Left $ "Allocation failed: " ++ msg Ok result@(_, _, _, new_cv) -> let new_accu = Right result in case accu of Left _ -> new_accu Right (_, _, _, old_cv) -> if old_cv < new_cv then accu else new_accu ) no_nodes node_pairs return (nl', il', ops) -- | Generic function for changing one node of an instance. -- -- This is similar to 'nodeEvacInstance' but will be used in a few of -- its sub-patterns. It folds the inner function 'evacOneNodeInner' -- over the list of available nodes, which results in the best choice -- for relocation. evacOneNodeOnly :: Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> Instance.Instance -- ^ The instance to be evacuated -> Gdx -- ^ The group we're targetting -> [Ndx] -- ^ The list of available nodes -- for allocation -> Result (Node.List, Instance.List, [OpCodes.OpCode]) evacOneNodeOnly nl il inst gdx avail_nodes = do op_fn <- case Instance.mirrorType inst of MirrorNone -> Bad "Can't relocate/evacuate non-mirrored instances" MirrorInternal -> Ok ReplaceSecondary MirrorExternal -> Ok FailoverToAny (nl', inst', _, ndx) <- annotateResult "Can't find any good node" . eitherToResult $ foldl' (evacOneNodeInner nl inst gdx op_fn) (Left "no nodes available") avail_nodes let idx = Instance.idx inst il' = Container.add idx inst' il ops = iMoveToJob nl' il' idx (op_fn ndx) return (nl', il', ops) -- | Inner fold function for changing one node of an instance. -- -- Depending on the instance disk template, this will either change -- the secondary (for DRBD) or the primary node (for shared -- storage). However, the operation is generic otherwise. -- -- The running solution is either a @Left String@, which means we -- don't have yet a working solution, or a @Right (...)@, which -- represents a valid solution; it holds the modified node list, the -- modified instance (after evacuation), the score of that solution, -- and the new secondary node index. evacOneNodeInner :: Node.List -- ^ Cluster node list -> Instance.Instance -- ^ Instance being evacuated -> Gdx -- ^ The group index of the instance -> (Ndx -> IMove) -- ^ Operation constructor -> EvacInnerState -- ^ Current best solution -> Ndx -- ^ Node we're evaluating as target -> EvacInnerState -- ^ New best solution evacOneNodeInner nl inst gdx op_fn accu ndx = case applyMove nl inst (op_fn ndx) of Bad fm -> let fail_msg = "Node " ++ Container.nameOf nl ndx ++ " failed: " ++ show fm in either (const $ Left fail_msg) (const accu) accu Ok (nl', inst', _, _) -> let nodes = Container.elems nl' -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes new_accu = Right (nl', inst', new_cv, ndx) in case accu of Left _ -> new_accu Right (_, _, old_cv, _) -> if old_cv < new_cv then accu else new_accu -- | Compute result of changing all nodes of a DRBD instance. -- -- Given the target primary and secondary node (which might be in a -- different group or not), this function will 'execute' all the -- required steps and assuming all operations succceed, will return -- the modified node and instance lists, the opcodes needed for this -- and the new group score. evacDrbdAllInner :: Node.List -- ^ Cluster node list -> Instance.List -- ^ Cluster instance list -> Instance.Instance -- ^ The instance to be moved -> Gdx -- ^ The target group index -- (which can differ from the -- current group of the -- instance) -> (Ndx, Ndx) -- ^ Tuple of new -- primary\/secondary nodes -> Result (Node.List, Instance.List, [OpCodes.OpCode], Score) evacDrbdAllInner nl il inst gdx (t_pdx, t_sdx) = do let primary = Container.find (Instance.pNode inst) nl idx = Instance.idx inst -- if the primary is offline, then we first failover (nl1, inst1, ops1) <- if Node.offline primary then do (nl', inst', _, _) <- annotateResult "Failing over to the secondary" . opToResult $ applyMove nl inst Failover return (nl', inst', [Failover]) else return (nl, inst, []) let (o1, o2, o3) = (ReplaceSecondary t_pdx, Failover, ReplaceSecondary t_sdx) -- we now need to execute a replace secondary to the future -- primary node (nl2, inst2, _, _) <- annotateResult "Changing secondary to new primary" . opToResult $ applyMove nl1 inst1 o1 let ops2 = o1:ops1 -- we now execute another failover, the primary stays fixed now (nl3, inst3, _, _) <- annotateResult "Failing over to new primary" . opToResult $ applyMove nl2 inst2 o2 let ops3 = o2:ops2 -- and finally another replace secondary, to the final secondary (nl4, inst4, _, _) <- annotateResult "Changing secondary to final secondary" . opToResult $ applyMove nl3 inst3 o3 let ops4 = o3:ops3 il' = Container.add idx inst4 il ops = concatMap (iMoveToJob nl4 il' idx) $ reverse ops4 let nodes = Container.elems nl4 -- The fromJust below is ugly (it can fail nastily), but -- at this point we should have any internal mismatches, -- and adding a monad here would be quite involved grpnodes = fromJust (gdx `lookup` Node.computeGroups nodes) new_cv = compCVNodes grpnodes return (nl4, il', ops, new_cv) -- | Computes the nodes in a given group which are available for -- allocation. availableGroupNodes :: [(Gdx, [Ndx])] -- ^ Group index/node index assoc list -> IntSet.IntSet -- ^ Nodes that are excluded -> Gdx -- ^ The group for which we -- query the nodes -> Result [Ndx] -- ^ List of available node indices availableGroupNodes group_nodes excl_ndx gdx = do local_nodes <- maybe (Bad $ "Can't find group with index " ++ show gdx) Ok (lookup gdx group_nodes) let avail_nodes = filter (not . flip IntSet.member excl_ndx) local_nodes return avail_nodes -- | Updates the evac solution with the results of an instance -- evacuation. updateEvacSolution :: (Node.List, Instance.List, EvacSolution) -> Idx -> Result (Node.List, Instance.List, [OpCodes.OpCode]) -> (Node.List, Instance.List, EvacSolution) updateEvacSolution (nl, il, es) idx (Bad msg) = (nl, il, es { esFailed = (idx, msg):esFailed es}) updateEvacSolution (_, _, es) idx (Ok (nl, il, opcodes)) = (nl, il, es { esMoved = new_elem:esMoved es , esOpCodes = opcodes:esOpCodes es }) where inst = Container.find idx il new_elem = (idx, instancePriGroup nl inst, Instance.allNodes inst) -- | Node-evacuation IAllocator mode main function. tryNodeEvac :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide, not per group) -> Instance.List -- ^ Instance list (cluster-wide) -> EvacMode -- ^ The evacuation mode -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryNodeEvac _ ini_nl ini_il mode idxs = let evac_ndx = nodesToEvacuate ini_il mode idxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) evac_ndx offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let gdx = instancePriGroup nl inst pdx = Instance.pNode inst in updateEvacSolution state (Instance.idx inst) $ availableGroupNodes group_ndx (IntSet.insert pdx excl_ndx) gdx >>= nodeEvacInstance nl il mode inst gdx ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Change-group IAllocator mode main function. -- -- This is very similar to 'tryNodeEvac', the only difference is that -- we don't choose as target group the current instance group, but -- instead: -- -- 1. at the start of the function, we compute which are the target -- groups; either no groups were passed in, in which case we choose -- all groups out of which we don't evacuate instance, or there were -- some groups passed, in which case we use those -- -- 2. for each instance, we use 'findBestAllocGroup' to choose the -- best group to hold the instance, and then we do what -- 'tryNodeEvac' does, except for this group instead of the current -- instance group. -- -- Note that the correct behaviour of this function relies on the -- function 'nodeEvacInstance' to be able to do correctly both -- intra-group and inter-group moves when passed the 'ChangeAll' mode. tryChangeGroup :: Group.List -- ^ The cluster groups -> Node.List -- ^ The node list (cluster-wide) -> Instance.List -- ^ Instance list (cluster-wide) -> [Gdx] -- ^ Target groups; if empty, any -- groups not being evacuated -> [Idx] -- ^ List of instance (indices) to be evacuated -> Result (Node.List, Instance.List, EvacSolution) tryChangeGroup gl ini_nl ini_il gdxs idxs = let evac_gdxs = nub $ map (instancePriGroup ini_nl . flip Container.find ini_il) idxs target_gdxs = (if null gdxs then Container.keys gl else gdxs) \\ evac_gdxs offline = map Node.idx . filter Node.offline $ Container.elems ini_nl excl_ndx = foldl' (flip IntSet.insert) IntSet.empty offline group_ndx = map (\(gdx, (nl, _)) -> (gdx, map Node.idx (Container.elems nl))) $ splitCluster ini_nl ini_il (fin_nl, fin_il, esol) = foldl' (\state@(nl, il, _) inst -> let solution = do let ncnt = Instance.requiredNodes $ Instance.diskTemplate inst (grp, _, _) <- findBestAllocGroup gl nl il (Just target_gdxs) inst ncnt let gdx = Group.idx grp av_nodes <- availableGroupNodes group_ndx excl_ndx gdx nodeEvacInstance nl il ChangeAll inst gdx av_nodes in updateEvacSolution state (Instance.idx inst) solution ) (ini_nl, ini_il, emptyEvacSolution) (map (`Container.find` ini_il) idxs) in return (fin_nl, fin_il, reverseEvacSolution esol) -- | Standard-sized allocation method. -- -- This places instances of the same size on the cluster until we're -- out of space. The result will be a list of identically-sized -- instances. iterateAlloc :: AllocMethod iterateAlloc nl il limit newinst allocnodes ixes cstats = let depth = length ixes newname = printf "new-%d" depth::String newidx = Container.size il newi2 = Instance.setIdx (Instance.setName newinst newname) newidx newlimit = fmap (flip (-) 1) limit in case tryAlloc nl il newi2 allocnodes of Bad s -> Bad s Ok (AllocSolution { asFailures = errs, asSolution = sols3 }) -> let newsol = Ok (collapseFailures errs, nl, il, ixes, cstats) in case sols3 of Nothing -> newsol Just (xnl, xi, _, _) -> if limit == Just 0 then newsol else iterateAlloc xnl (Container.add newidx xi il) newlimit newinst allocnodes (xi:ixes) (totalResources xnl:cstats) -- | Predicate whether shrinking a single resource can lead to a valid -- allocation. sufficesShrinking :: (Instance.Instance -> AllocSolution) -> Instance.Instance -> FailMode -> Maybe Instance.Instance sufficesShrinking allocFn inst fm = case dropWhile (isNothing . asSolution . fst) . takeWhile (liftA2 (||) (elem fm . asFailures . fst) (isJust . asSolution . fst)) . map (allocFn &&& id) $ iterateOk (`Instance.shrinkByType` fm) inst of x:_ -> Just . snd $ x _ -> Nothing -- | Tiered allocation method. -- -- This places instances on the cluster, and decreases the spec until -- we can allocate again. The result will be a list of decreasing -- instance specs. tieredAlloc :: AllocMethod tieredAlloc nl il limit newinst allocnodes ixes cstats = case iterateAlloc nl il limit newinst allocnodes ixes cstats of Bad s -> Bad s Ok (errs, nl', il', ixes', cstats') -> let newsol = Ok (errs, nl', il', ixes', cstats') ixes_cnt = length ixes' (stop, newlimit) = case limit of Nothing -> (False, Nothing) Just n -> (n <= ixes_cnt, Just (n - ixes_cnt)) sortedErrs = map fst $ sortBy (comparing snd) errs suffShrink = sufficesShrinking (fromMaybe emptyAllocSolution . flip (tryAlloc nl' il') allocnodes) newinst bigSteps = filter isJust . map suffShrink . reverse $ sortedErrs progress (Ok (_, _, _, newil', _)) (Ok (_, _, _, newil, _)) = length newil' > length newil progress _ _ = False in if stop then newsol else let newsol' = case Instance.shrinkByType newinst . last $ sortedErrs of Bad _ -> newsol Ok newinst' -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' in if progress newsol' newsol then newsol' else case bigSteps of Just newinst':_ -> tieredAlloc nl' il' newlimit newinst' allocnodes ixes' cstats' _ -> newsol -- * Formatting functions -- | Given the original and final nodes, computes the relocation description. computeMoves :: Instance.Instance -- ^ The instance to be moved -> String -- ^ The instance name -> IMove -- ^ The move being performed -> String -- ^ New primary -> String -- ^ New secondary -> (String, [String]) -- ^ Tuple of moves and commands list; moves is containing -- either @/f/@ for failover or @/r:name/@ for replace -- secondary, while the command list holds gnt-instance -- commands (without that prefix), e.g \"@failover instance1@\" computeMoves i inam mv c d = case mv of Failover -> ("f", [mig]) FailoverToAny _ -> (printf "fa:%s" c, [mig_any]) FailoverAndReplace _ -> (printf "f r:%s" d, [mig, rep d]) ReplaceSecondary _ -> (printf "r:%s" d, [rep d]) ReplaceAndFailover _ -> (printf "r:%s f" c, [rep c, mig]) ReplacePrimary _ -> (printf "f r:%s f" c, [mig, rep c, mig]) where morf = if Instance.isRunning i then "migrate" else "failover" mig = printf "%s -f %s" morf inam::String mig_any = printf "%s -f -n %s %s" morf c inam::String rep n = printf "replace-disks -n %s %s" n inam::String -- | Converts a placement to string format. printSolutionLine :: Node.List -- ^ The node list -> Instance.List -- ^ The instance list -> Int -- ^ Maximum node name length -> Int -- ^ Maximum instance name length -> Placement -- ^ The current placement -> Int -- ^ The index of the placement in -- the solution -> (String, [String]) printSolutionLine nl il nmlen imlen plc pos = let pmlen = (2*nmlen + 1) (i, p, s, mv, c) = plc old_sec = Instance.sNode inst inst = Container.find i il inam = Instance.alias inst npri = Node.alias $ Container.find p nl nsec = Node.alias $ Container.find s nl opri = Node.alias $ Container.find (Instance.pNode inst) nl osec = Node.alias $ Container.find old_sec nl (moves, cmds) = computeMoves inst inam mv npri nsec -- FIXME: this should check instead/also the disk template ostr = if old_sec == Node.noSecondary then printf "%s" opri::String else printf "%s:%s" opri osec::String nstr = if s == Node.noSecondary then printf "%s" npri::String else printf "%s:%s" npri nsec::String in (printf " %3d. %-*s %-*s => %-*s %12.8f a=%s" pos imlen inam pmlen ostr pmlen nstr c moves, cmds) -- | Return the instance and involved nodes in an instance move. -- -- Note that the output list length can vary, and is not required nor -- guaranteed to be of any specific length. involvedNodes :: Instance.List -- ^ Instance list, used for retrieving -- the instance from its index; note -- that this /must/ be the original -- instance list, so that we can -- retrieve the old nodes -> Placement -- ^ The placement we're investigating, -- containing the new nodes and -- instance index -> [Ndx] -- ^ Resulting list of node indices involvedNodes il plc = let (i, np, ns, _, _) = plc inst = Container.find i il in nub . filter (>= 0) $ [np, ns] ++ Instance.allNodes inst -- | From two adjacent cluster tables get the list of moves that transitions -- from to the other getMoves :: (Table, Table) -> [MoveJob] getMoves (Table _ initial_il _ initial_plc, Table final_nl _ _ final_plc) = let plctoMoves (plc@(idx, p, s, mv, _)) = let inst = Container.find idx initial_il inst_name = Instance.name inst affected = involvedNodes initial_il plc np = Node.alias $ Container.find p final_nl ns = Node.alias $ Container.find s final_nl (_, cmds) = computeMoves inst inst_name mv np ns in (affected, idx, mv, cmds) in map plctoMoves . reverse . drop (length initial_plc) $ reverse final_plc -- | Inner function for splitJobs, that either appends the next job to -- the current jobset, or starts a new jobset. mergeJobs :: ([JobSet], [Ndx]) -> MoveJob -> ([JobSet], [Ndx]) mergeJobs ([], _) n@(ndx, _, _, _) = ([[n]], ndx) mergeJobs (cjs@(j:js), nbuf) n@(ndx, _, _, _) | null (ndx `intersect` nbuf) = ((n:j):js, ndx ++ nbuf) | otherwise = ([n]:cjs, ndx) -- | Break a list of moves into independent groups. Note that this -- will reverse the order of jobs. splitJobs :: [MoveJob] -> [JobSet] splitJobs = fst . foldl mergeJobs ([], []) -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatJob :: Int -> Int -> (Int, MoveJob) -> [String] formatJob jsn jsl (sn, (_, _, _, cmds)) = let out = printf " echo job %d/%d" jsn sn: printf " check": map (" gnt-instance " ++) cmds in if sn == 1 then ["", printf "echo jobset %d, %d jobs" jsn jsl] ++ out else out -- | Given a list of commands, prefix them with @gnt-instance@ and -- also beautify the display a little. formatCmds :: [JobSet] -> String formatCmds = unlines . concatMap (\(jsn, js) -> concatMap (formatJob jsn (length js)) (zip [1..] js)) . zip [1..] -- | Print the node list. printNodes :: Node.List -> [String] -> String printNodes nl fs = let fields = case fs of [] -> Node.defaultFields "+":rest -> Node.defaultFields ++ rest _ -> fs snl = sortBy (comparing Node.idx) (Container.elems nl) (header, isnum) = unzip $ map Node.showHeader fields in printTable "" header (map (Node.list fields) snl) isnum -- | Print the instance list. printInsts :: Node.List -> Instance.List -> String printInsts nl il = let sil = sortBy (comparing Instance.idx) (Container.elems il) helper inst = [ if Instance.isRunning inst then "R" else " " , Instance.name inst , Container.nameOf nl (Instance.pNode inst) , let sdx = Instance.sNode inst in if sdx == Node.noSecondary then "" else Container.nameOf nl sdx , if Instance.autoBalance inst then "Y" else "N" , printf "%3d" $ Instance.vcpus inst , printf "%5d" $ Instance.mem inst , printf "%5d" $ Instance.dsk inst `div` 1024 , printf "%5.3f" lC , printf "%5.3f" lM , printf "%5.3f" lD , printf "%5.3f" lN ] where DynUtil lC lM lD lN = Instance.util inst header = [ "F", "Name", "Pri_node", "Sec_node", "Auto_bal" , "vcpu", "mem" , "dsk", "lCpu", "lMem", "lDsk", "lNet" ] isnum = False:False:False:False:False:repeat True in printTable "" header (map helper sil) isnum -- | Shows statistics for a given node list. printStats :: String -> Node.List -> String printStats lp nl = let dcvs = compDetailedCV $ Container.elems nl (weights, names) = unzip detailedCVInfo hd = zip3 (weights ++ repeat 1) (names ++ repeat "unknown") dcvs header = [ "Field", "Value", "Weight" ] formatted = map (\(w, h, val) -> [ h , printf "%.8f" val , printf "x%.2f" w ]) hd in printTable lp header formatted $ False:repeat True -- | Convert a placement into a list of OpCodes (basically a job). iMoveToJob :: Node.List -- ^ The node list; only used for node -- names, so any version is good -- (before or after the operation) -> Instance.List -- ^ The instance list; also used for -- names only -> Idx -- ^ The index of the instance being -- moved -> IMove -- ^ The actual move to be described -> [OpCodes.OpCode] -- ^ The list of opcodes equivalent to -- the given move iMoveToJob nl il idx move = let inst = Container.find idx il iname = Instance.name inst lookNode n = case mkNonEmpty (Container.nameOf nl n) of -- FIXME: convert htools codebase to non-empty strings Bad msg -> error $ "Empty node name for idx " ++ show n ++ ": " ++ msg ++ "??" Ok ne -> Just ne opF = OpCodes.OpInstanceMigrate { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opMigrationMode = Nothing -- default , OpCodes.opOldLiveMode = Nothing -- default as well , OpCodes.opTargetNode = Nothing -- this is drbd , OpCodes.opTargetNodeUuid = Nothing , OpCodes.opAllowRuntimeChanges = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opMigrationCleanup = False , OpCodes.opIallocator = Nothing , OpCodes.opAllowFailover = True } opFA n = opF { OpCodes.opTargetNode = lookNode n } -- not drbd opR n = OpCodes.OpInstanceReplaceDisks { OpCodes.opInstanceName = iname , OpCodes.opInstanceUuid = Nothing , OpCodes.opEarlyRelease = False , OpCodes.opIgnoreIpolicy = False , OpCodes.opReplaceDisksMode = OpCodes.ReplaceNewSecondary , OpCodes.opReplaceDisksList = [] , OpCodes.opRemoteNode = lookNode n , OpCodes.opRemoteNodeUuid = Nothing , OpCodes.opIallocator = Nothing } in case move of Failover -> [ opF ] FailoverToAny np -> [ opFA np ] ReplacePrimary np -> [ opF, opR np, opF ] ReplaceSecondary ns -> [ opR ns ] ReplaceAndFailover np -> [ opR np, opF ] FailoverAndReplace ns -> [ opF, opR ns ] -- * Node group functions -- | Computes the group of an instance. instanceGroup :: Node.List -> Instance.Instance -> Result Gdx instanceGroup nl i = let sidx = Instance.sNode i pnode = Container.find (Instance.pNode i) nl snode = if sidx == Node.noSecondary then pnode else Container.find sidx nl pgroup = Node.group pnode sgroup = Node.group snode in if pgroup /= sgroup then fail ("Instance placed accross two node groups, primary " ++ show pgroup ++ ", secondary " ++ show sgroup) else return pgroup -- | Computes the group of an instance per the primary node. instancePriGroup :: Node.List -> Instance.Instance -> Gdx instancePriGroup nl i = let pnode = Container.find (Instance.pNode i) nl in Node.group pnode -- | Compute the list of badly allocated instances (split across node -- groups). findSplitInstances :: Node.List -> Instance.List -> [Instance.Instance] findSplitInstances nl = filter (not . isOk . instanceGroup nl) . Container.elems -- | Splits a cluster into the component node groups. splitCluster :: Node.List -> Instance.List -> [(Gdx, (Node.List, Instance.List))] splitCluster nl il = let ngroups = Node.computeGroups (Container.elems nl) in map (\(gdx, nodes) -> let nidxs = map Node.idx nodes nodes' = zip nidxs nodes instances = Container.filter ((`elem` nidxs) . Instance.pNode) il in (gdx, (Container.fromList nodes', instances))) ngroups -- | Compute the list of nodes that are to be evacuated, given a list -- of instances and an evacuation mode. nodesToEvacuate :: Instance.List -- ^ The cluster-wide instance list -> EvacMode -- ^ The evacuation mode we're using -> [Idx] -- ^ List of instance indices being evacuated -> IntSet.IntSet -- ^ Set of node indices nodesToEvacuate il mode = IntSet.delete Node.noSecondary . foldl' (\ns idx -> let i = Container.find idx il pdx = Instance.pNode i sdx = Instance.sNode i dt = Instance.diskTemplate i withSecondary = case dt of DTDrbd8 -> IntSet.insert sdx ns _ -> ns in case mode of ChangePrimary -> IntSet.insert pdx ns ChangeSecondary -> withSecondary ChangeAll -> IntSet.insert pdx withSecondary ) IntSet.empty
ribag/ganeti-experiments
src/Ganeti/HTools/Cluster.hs
gpl-2.0
78,781
1
23
24,729
17,185
9,326
7,859
1,273
8
-- Copyright 2016, 2017 Robin Raymond -- -- This file is part of Purple Muon -- -- Purple Muon is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Purple Muon is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with Purple Muon. If not, see <http://www.gnu.org/licenses/>. {-| Module : Client.States.MenuState.Types Description : The types used for the menu state. Copyright : (c) Robin Raymond, 2016-2017 License : GPL-3 Maintainer : robin@robinraymond.de Portability : POSIX -} {-# LANGUAGE TemplateHaskell #-} module Client.States.MenuState.Types ( State(..), menuSprites, menuItems, menuFonts ) where import qualified Control.Lens as CLE import qualified Client.Assets.Font as CAF import qualified Client.Assets.Sprite as CAS import qualified Client.Video.Menu as CVM data State = State { _menuSprites :: CAS.SpriteLoaderType , _menuItems :: [CVM.MenuItem] , _menuFonts :: CAF.FontLoaderType } CLE.makeLenses ''State
r-raymond/purple-muon
src/Client/States/MenuState/Types.hs
gpl-3.0
1,447
0
10
286
125
89
36
13
0
-- Copyright (C) 2011,2012 Makoto Nishiura. -- This file is part of ERASM++. -- ERASM++ is free software; you can redistribute it and/or modify it under -- the terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. -- ERASM++ is distributed in the hope that it will be useful, but WITHOUT ANY -- WARRANTY; without even the implied warranty of MERCHANTABILITY or -- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- for more details. -- You should have received a copy of the GNU General Public License -- along with ERASM++; see the file COPYING. If not see -- <http://www.gnu.org/licenses/>. {-# OPTIONS_GHC -F -pgmF preprocess #-} --m4_include(my_ghc_testframework.m4) module ErasmCommon( Mode(..) , Byte , OperandSize(..) , AddressSize(..) , Doc , Pretty(..) , (<>) , (<+>) , (<$>) , (<$$>) , (@?=) , on , the , uniq , uniqBy , equivalenceClasses , cartesianProduct , cartesianProductBy , distinct , mutually , combi2 , Named , name , (-->) , (<-->) , toInt , prettyAssertPostCondition , assertPostCondition , ErasmCommon.runTests , module Control.Monad , module Data.Char , module Data.List , module Data.Maybe , module Combinators ) where import qualified Test.HUnit import Test.HUnit((@?=)) import Test.QuickCheck hiding((><)) import Test.QuickCheck.Gen import UU.PPrint(Doc,Pretty(..),(<>),(<+>),(<$$>),(<$>)) import Control.Monad import Data.Char import Data.Word import Data.List import Data.Maybe import Data.Function import Combinators hiding(and,or,(<>),(!)) infixr 0 --> , <--> (-->) :: Bool -> Bool -> Bool a --> b = not a || b (<-->) :: Bool -> Bool -> Bool a <--> b = a == b toInt :: (Num a , Integral a) => a -> Int toInt = fromInteger . toInteger data Mode = X64 | X86 deriving(Eq,Ord,Enum,Bounded,Show) instance Arbitrary Mode where arbitrary = elements [minBound..maxBound] type Byte = Word8 data OperandSize = Op16 | Op32 | Op64 deriving(Eq,Ord,Enum,Bounded,Show) instance Arbitrary OperandSize where arbitrary = elements [minBound..maxBound] data AddressSize = Addr16 | Addr32 | Addr64 deriving(Eq,Ord,Enum,Bounded,Show) instance Arbitrary AddressSize where arbitrary = elements [minBound..maxBound] class Named a where name :: a -> String the :: (Eq a) => [a] -> a the (x:xs) | all (x==) xs = x | otherwise = ERROR((show "list does not consist of unique element")) the [] = ERROR(("empty list")) equivalenceClasses :: (a -> a -> Bool) -> [a] -> [[a]] equivalenceClasses r [] = [] equivalenceClasses r (x:xs) = let (ys,zs) = partition (r x) xs in (x:ys) : equivalenceClasses r zs ASSERT_EQ((equivalenceClasses (==) [1,2,1,3,4]),([[1,1],[2],[3],[4]])) ASSERT_EQ((uniq [1,1,2,3,4,4]),([1,2,3,4])) uniq :: Eq a => [a] -> [a] uniq xs = map head $ group xs uniqBy :: (a -> a -> Bool) -> [a] -> [a] uniqBy cmp xs = map head $ groupBy cmp xs ASSERT_EQ((cartesianProductBy (+) [1,2] [3,4]),([4,5,5,6])) cartesianProduct :: [a] -> [b] -> [(a,b)] cartesianProduct xs ys = [(x,y) | x <- xs , y <- ys ] cartesianProductBy :: (a -> b -> c) -> [a] -> [b] -> [c] cartesianProductBy f xs ys = [f x y | x<- xs , y <- ys] distinct :: Ord a => [a] -> Bool distinct xs = length xs == length (uniq $ sort xs ) ASSERT_EQ((distinct [3,4,5,2]),(True)) ASSERT_EQ((distinct [3,4,3,2]),(False)) mutually :: (a -> a -> Bool) -> [a] -> Bool mutually p xs = all (uncurry p) $ combi2 xs combi2 :: [a] -> [(a,a)] combi2 [] = [] combi2 [x] = [] combi2 (x:xs) = [(x,y) | y <- xs ] ++ combi2 xs assertPostCondition :: (a -> Bool) -> a -> a assertPostCondition c x | c x = x | otherwise = ERROR(("check failed")) prettyAssertPostCondition :: Pretty a => String -> (a -> Bool) -> a -> a prettyAssertPostCondition info c x | c x = x | otherwise = ERROR((show $ pretty "check failed" <$> pretty info <$> pretty x ))
nishiuramakoto/erasm-plusplus
src/haskell/ErasmCommon.hs
gpl-3.0
4,698
0
12
1,516
1,586
905
681
-1
-1
module Example.Eg66 (eg66) where import Graphics.Radian import ExampleUtils eg66 :: IO Html eg66 = do d <- readJSON "fathers.json" let ages = (flatten $ d .^ "fathers" #^ "daughters") #^ "age" x = seqStep 0 (length ages) 1 plot = Plot [ps] # [height.=300, aspect.=1.6] ps = Points x ages # [markerSize.=100] source = exampleSource "Eg66.hs" return [shamlet| <h3> Example 66 (hierarchical JSON data) ^{plot} ^{source} |]
openbrainsrc/hRadian
examples/Example/Eg66.hs
mpl-2.0
464
3
14
111
159
83
76
-1
-1
module Handler.ProjectBlog where import Import import Handler.Comment as Com import Handler.Discussion import Handler.Utils import Model.Blog import Model.Comment import Model.Comment.ActionPermissions import Model.Comment.HandlerInfo import Model.Comment.Mods import Model.Comment.Sql import Model.Markdown import Model.User import View.Comment import View.Project import View.User import Widgets.Preview import Widgets.Time import Data.Default import qualified Data.Text as T import Data.Tree (Forest, Tree) import qualified Data.Tree as Tree import Text.Cassius (cassiusFile) -- | Sanity check for Project Comment pages. -- Redirects if the comment was rethreaded. -- 404 if the comment doesn't exist. 403 if permission denied. checkComment :: Text -> Text -> CommentId -> Handler (Maybe (Entity User), Entity Project, Comment) checkComment project_handle post_name comment_id = do muser <- maybeAuth (project, comment) <- checkComment' (entityKey <$> muser) project_handle post_name comment_id return (muser, project, comment) -- | Like checkComment, but authentication is required. checkCommentRequireAuth :: Text -> Text -> CommentId -> Handler (Entity User, Entity Project, Comment) checkCommentRequireAuth project_handle post_name comment_id = do user@(Entity user_id _) <- requireAuth (project, comment) <- checkComment' (Just user_id) project_handle post_name comment_id return (user, project, comment) -- | Abstract checkComment and checkCommentRequireAuth. You shouldn't use this function directly. checkComment' :: Maybe UserId -> Text -> Text -> CommentId -> Handler (Entity Project, Comment) checkComment' muser_id project_handle post_name comment_id = do redirectIfRethreaded comment_id (project, blog_post, ecomment) <- runYDB $ do (project@(Entity project_id _), Entity _ blog_post) <- fetchProjectBlogPostDB project_handle post_name let has_permission = exprCommentProjectPermissionFilter muser_id (val project_id) ecomment <- fetchCommentDB comment_id has_permission return (project, blog_post, ecomment) case ecomment of Left CommentNotFound -> notFound Left CommentPermissionDenied -> permissionDenied "You don't have permission to view this comment." Right comment -> if commentDiscussion comment /= blogPostDiscussion blog_post then notFound else return (project, comment) checkBlogPostCommentActionPermission :: (CommentActionPermissions -> Bool) -> Entity User -> Text -> Entity Comment -> Handler () checkBlogPostCommentActionPermission can_perform_action user project_handle comment@(Entity comment_id _) = do action_permissions <- lookupErr "checkBlogPostCommentActionPermission: comment id not found in map" comment_id <$> makeProjectCommentActionPermissionsMap (Just user) project_handle def [comment] unless (can_perform_action action_permissions) $ permissionDenied "You don't have permission to perform this action." makeBlogPostCommentForestWidget :: Maybe (Entity User) -> ProjectId -> Text -> Text -> [Entity Comment] -> CommentMods -> Handler MaxDepth -> Bool -> Widget -> Handler (Widget, Forest (Entity Comment)) makeBlogPostCommentForestWidget muser project_id project_handle post_name comments = makeCommentForestWidget (projectBlogCommentHandlerInfo muser project_id project_handle post_name) comments muser makeBlogPostCommentTreeWidget :: Maybe (Entity User) -> ProjectId -> Text -> Text -> Entity Comment -> CommentMods -> Handler MaxDepth -> Bool -> Widget -> Handler (Widget, Tree (Entity Comment)) makeBlogPostCommentTreeWidget muser project_id project_handle d comment mods max_depth is_preview widget_under_root_comment = do (widget, [tree]) <- makeBlogPostCommentForestWidget muser project_id project_handle d [comment] mods max_depth is_preview widget_under_root_comment return (widget, tree) makeBlogPostCommentActionWidget :: MakeCommentActionWidget -> Text -> Text -> CommentId -> CommentMods -> Handler MaxDepth -> Handler (Widget, Tree (Entity Comment)) makeBlogPostCommentActionWidget make_comment_action_widget project_handle post_name comment_id mods get_max_depth = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle post_name comment_id make_comment_action_widget (Entity comment_id comment) user (projectCommentHandlerInfo (Just user) project_id project_handle) mods get_max_depth False projectBlogDiscussionPage :: Text -> Text -> Widget -> Widget projectBlogDiscussionPage project_handle post_name widget = do $(widgetFile "project_blog_discussion_wrapper") toWidget $(cassiusFile "templates/comment.cassius") -- | Require any of the given Roles, failing with permissionDenied if none are satisfied. requireRolesAny :: [Role] -> Text -> Text -> Handler (UserId, Entity Project) requireRolesAny roles project_handle err_msg = do user_id <- requireAuthId (project, ok) <- runYDB $ do project@(Entity project_id _) <- getBy404 (UniqueProjectHandle project_handle) ok <- userHasRolesAnyDB roles user_id project_id return (project, ok) unless ok $ permissionDenied err_msg return (user_id, project) -------------------------------------------------------------------------------- -- /p/#Text/blog getProjectBlogR :: Text -> Handler Html getProjectBlogR project_handle = do maybe_from <- fmap (key . PersistInt64 . read . T.unpack) <$> lookupGetParam "from" post_count <- fromMaybe 10 <$> fmap (read . T.unpack) <$> lookupGetParam "from" Entity project_id project <- runYDB $ getBy404 $ UniqueProjectHandle project_handle let apply_offset blog = maybe id (\from_blog rest -> blog ^. BlogPostId >=. val from_blog &&. rest) maybe_from (posts, next) <- fmap (splitAt post_count) $ runDB $ select $ from $ \blog -> do where_ $ apply_offset blog $ blog ^. BlogPostProject ==. val project_id orderBy [ desc $ blog ^. BlogPostTs, desc $ blog ^. BlogPostId ] limit (fromIntegral post_count + 1) return blog renderRouteParams <- getUrlRenderParams let nextRoute next_id = renderRouteParams (ProjectBlogR project_handle) [("from", toPathPiece next_id)] discussion = DiscussionOnProject $ Entity project_id project mviewer_id <- maybeAuthId userIsTeamMember <- maybe (pure False) (\u -> runDB $ userIsProjectTeamMemberDB u project_id) mviewer_id defaultLayout $ do snowdriftTitle $ projectName project <> " Blog" $(widgetFile "project_blog") -------------------------------------------------------------------------------- -- /p/#Text/blog/!new getNewBlogPostR :: Text -> Handler Html getNewBlogPostR project_handle = do (_, Entity _ project) <- requireRolesAny [Admin, TeamMember] project_handle "You do not have permission to post to this project's blog." (blog_form, _) <- generateFormPost $ projectBlogForm Nothing defaultLayout $ do snowdriftTitle $ "Post To " <> projectName project <> " Blog" $(widgetFile "new_blog_post") postNewBlogPostR :: Text -> Handler Html postNewBlogPostR project_handle = do (viewer_id, Entity project_id _) <- requireRolesAny [Admin, TeamMember] project_handle "You do not have permission to post to this project's blog." ((result, _), _) <- runFormPost $ projectBlogForm Nothing case result of FormSuccess project_blog@ProjectBlog {..} -> lookupPostMode >>= \case Just PostMode -> do void $ runSDB $ postBlogPostDB projectBlogTitle projectBlogHandle viewer_id project_id projectBlogContent alertSuccess "posted" redirect $ ProjectBlogR project_handle _ -> previewBlogPost viewer_id project_handle project_blog x -> do alertDanger $ T.pack $ show x redirect $ NewBlogPostR project_handle -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text getBlogPostR :: Text -> Text -> Handler Html getBlogPostR project_handle blog_post_handle = do (Entity _ project, Entity _ blog_post) <- runYDB $ fetchProjectBlogPostDB project_handle blog_post_handle defaultLayout $ do snowdriftDashTitle (projectName project <> " Blog") (blogPostTitle blog_post) renderBlogPost project_handle blog_post NotPreview -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/edit checkEditBlogPostPermissions :: Text -> Handler UserId checkEditBlogPostPermissions project_handle = fst <$> requireRolesAny [Admin, TeamMember] project_handle "only the admin or a team member can edit a blog post" getEditBlogPostR :: Text -> Text -> Handler Html getEditBlogPostR project_handle blog_post_handle = do (Entity _ project, Entity _ BlogPost {..}) <- runYDB $ fetchProjectBlogPostDB project_handle blog_post_handle void $ checkEditBlogPostPermissions project_handle (blog_form, enctype) <- generateFormPost $ projectBlogForm $ Just $ ProjectBlog blogPostTitle blog_post_handle $ concatContent blogPostTopContent blogPostBottomContent defaultLayout $ do snowdriftDashTitle (projectName project <> " Blog") "Edit" $(widgetFile "edit_blog_post") postEditBlogPostR :: Text -> Text -> Handler Html postEditBlogPostR project_handle blog_post_handle = do (_, Entity blog_post_id BlogPost {..}) <- runYDB $ fetchProjectBlogPostDB project_handle blog_post_handle viewer_id <- checkEditBlogPostPermissions project_handle ((result, _), _) <- runFormPost $ projectBlogForm Nothing case result of FormSuccess project_blog@ProjectBlog {..} -> lookupPostMode >>= \case Just PostMode -> do runDB $ updateBlogPostDB viewer_id blog_post_id project_blog alertSuccess "Blog post updated" redirect $ BlogPostR project_handle projectBlogHandle _ -> previewBlogPost viewer_id project_handle project_blog FormMissing -> do alertDanger "No data provided" redirect $ BlogPostR project_handle blog_post_handle FormFailure errs -> do alertDanger $ "Form failure: " <> T.intercalate ", " errs redirect $ BlogPostR project_handle blog_post_handle -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId getBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getBlogPostCommentR project_handle post_name comment_id = do (muser, Entity project_id _, comment) <- checkComment project_handle post_name comment_id (widget, comment_tree) <- makeBlogPostCommentTreeWidget muser project_id project_handle post_name (Entity comment_id comment) def getMaxDepth False mempty case muser of Nothing -> return () Just (Entity user_id _) -> runDB (userMaybeViewProjectCommentsDB user_id project_id (map entityKey (Tree.flatten comment_tree))) defaultLayout $ projectBlogDiscussionPage project_handle post_name widget -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/approve getApproveBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getApproveBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeApproveCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postApproveBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postApproveBlogPostCommentR project_handle post_name comment_id = do (user@(Entity user_id _), _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_approve user project_handle (Entity comment_id comment) postApproveComment user_id comment_id comment redirect (BlogPostCommentR project_handle post_name comment_id) -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/claim getClaimBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getClaimBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeClaimCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postClaimBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postClaimBlogPostCommentR project_handle post_name comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_claim user project_handle (Entity comment_id comment) postClaimComment user comment_id comment (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect (BlogPostCommentR project_handle post_name comment_id) Just (widget, form) -> defaultLayout $ previewWidget form "claim" $ projectBlogDiscussionPage project_handle post_name widget -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/close getCloseBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getCloseBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeCloseCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postCloseBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postCloseBlogPostCommentR project_handle post_name comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_close user project_handle (Entity comment_id comment) postCloseComment user comment_id comment (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect (BlogPostCommentR project_handle post_name comment_id) Just (widget, form) -> defaultLayout $ previewWidget form "close" $ projectBlogDiscussionPage project_handle post_name widget -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/delete getDeleteBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getDeleteBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeDeleteCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postDeleteBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postDeleteBlogPostCommentR project_handle post_name comment_id = do (user, _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_delete user project_handle (Entity comment_id comment) was_deleted <- postDeleteComment comment_id if was_deleted then redirect $ BlogPostDiscussionR project_handle post_name else redirect $ BlogPostCommentR project_handle post_name comment_id -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/edit getEditBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getEditBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeEditCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postEditBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postEditBlogPostCommentR project_handle post_name comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_edit user project_handle (Entity comment_id comment) postEditComment user (Entity comment_id comment) (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect $ BlogPostCommentR project_handle post_name comment_id -- Edit made. Just (widget, form) -> defaultLayout $ previewWidget form "post" $ projectBlogDiscussionPage project_handle post_name widget -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/flag getFlagBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getFlagBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeFlagCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postFlagBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postFlagBlogPostCommentR project_handle post_name comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_flag user project_handle (Entity comment_id comment) postFlagComment user (Entity comment_id comment) (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect $ BlogPostDiscussionR post_name project_handle Just (widget, form) -> defaultLayout $ previewWidget form "flag" $ projectBlogDiscussionPage project_handle post_name widget -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/reply getReplyBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getReplyBlogPostCommentR project_handle post_name parent_id = do (widget, _) <- makeBlogPostCommentActionWidget makeReplyCommentWidget project_handle post_name parent_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postReplyBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postReplyBlogPostCommentR project_handle post_name parent_id = do (user, Entity project_id _, parent) <- checkCommentRequireAuth project_handle post_name parent_id Entity _ BlogPost{..} <- runYDB $ getBy404 $ UniqueBlogPost project_id post_name checkBlogPostCommentActionPermission can_reply user project_handle (Entity parent_id parent) postNewComment (Just parent_id) user blogPostDiscussion (makeProjectCommentActionPermissionsMap (Just user) project_handle def) >>= \case ConfirmedPost (Left err) -> do alertDanger err redirect $ ReplyBlogPostCommentR project_handle post_name parent_id ConfirmedPost (Right _) -> redirect $ BlogPostCommentR project_handle post_name parent_id Com.Preview (widget, form) -> defaultLayout $ previewWidget form "post" $ projectBlogDiscussionPage project_handle post_name widget -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/rethread getRethreadBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getRethreadBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeRethreadCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postRethreadBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postRethreadBlogPostCommentR project_handle post_name comment_id = do (user@(Entity user_id _), _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_rethread user project_handle (Entity comment_id comment) postRethreadComment user_id comment_id comment -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/retract getRetractBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getRetractBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeRetractCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postRetractBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postRetractBlogPostCommentR project_handle post_name comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_retract user project_handle (Entity comment_id comment) postRetractComment user comment_id comment (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect $ BlogPostCommentR project_handle post_name comment_id Just (widget, form) -> defaultLayout $ previewWidget form "retract" $ projectBlogDiscussionPage project_handle post_name widget -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/tags getBlogPostCommentTagsR :: Text -> Text -> CommentId -> Handler Html getBlogPostCommentTagsR _ _ = getCommentTags -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/tag/#TagId getBlogPostCommentTagR :: Text -> Text -> CommentId -> TagId -> Handler Html getBlogPostCommentTagR _ _ = getCommentTagR postBlogPostCommentTagR :: Text -> Text -> CommentId -> TagId -> Handler () postBlogPostCommentTagR _ _ = postCommentTagR -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/tag/apply, -- /p/#Text/blog/c/#CommentId/tag/create postBlogPostCommentApplyTagR, postBlogPostCommentCreateTagR :: Text -> Text -> CommentId -> Handler Html postBlogPostCommentApplyTagR project_handle _ = applyOrCreate postCommentApplyTag project_handle postBlogPostCommentCreateTagR project_handle _ = applyOrCreate postCommentCreateTag project_handle applyOrCreate :: (CommentId -> Handler ()) -> Text -> CommentId -> Handler Html applyOrCreate action project_handle comment_id = do action comment_id redirect (ProjectCommentR project_handle comment_id) -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/tag/new getBlogPostCommentAddTagR :: Text -> Text -> CommentId -> Handler Html getBlogPostCommentAddTagR project_handle post_name comment_id = do (user@(Entity user_id _), Entity project_id _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_add_tag user project_handle (Entity comment_id comment) getProjectCommentAddTag comment_id project_id user_id -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/unclaim getUnclaimBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getUnclaimBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeUnclaimCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postUnclaimBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html postUnclaimBlogPostCommentR project_handle post_name comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_unclaim user project_handle (Entity comment_id comment) postUnclaimComment user comment_id comment (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect $ BlogPostCommentR project_handle post_name comment_id Just (widget, form) -> defaultLayout $ previewWidget form "unclaim" $ projectBlogDiscussionPage project_handle post_name widget -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/watch getWatchBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getWatchBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeWatchCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postWatchBlogPostCommentR ::Text -> Text -> CommentId -> Handler Html postWatchBlogPostCommentR project_handle post_name comment_id = do (viewer@(Entity viewer_id _), _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_watch viewer project_handle (Entity comment_id comment) postWatchComment viewer_id comment_id redirect $ BlogPostCommentR project_handle post_name comment_id -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/c/#CommentId/unwatch getUnwatchBlogPostCommentR :: Text -> Text -> CommentId -> Handler Html getUnwatchBlogPostCommentR project_handle post_name comment_id = do (widget, _) <- makeBlogPostCommentActionWidget makeUnwatchCommentWidget project_handle post_name comment_id def getMaxDepth defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postUnwatchBlogPostCommentR ::Text -> Text -> CommentId -> Handler Html postUnwatchBlogPostCommentR project_handle post_name comment_id = do (viewer@(Entity viewer_id _), _, comment) <- checkCommentRequireAuth project_handle post_name comment_id checkBlogPostCommentActionPermission can_watch viewer project_handle (Entity comment_id comment) postUnwatchComment viewer_id comment_id redirect $ BlogPostCommentR project_handle post_name comment_id -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/d getBlogPostDiscussionR :: Text -> Text -> Handler Html getBlogPostDiscussionR project_handle post_name = getDiscussion $ getBlogPostDiscussion project_handle post_name getBlogPostDiscussion :: Text -> Text -> (DiscussionId -> ExprCommentCond -> DB [Entity Comment]) -> Handler Html getBlogPostDiscussion project_handle post_name get_root_comments = do muser <- maybeAuth let muser_id = entityKey <$> muser (Entity project_id project, root_comments) <- runYDB $ do p@(Entity project_id _) <- getBy404 $ UniqueProjectHandle project_handle Entity _ blog_post <- getBy404 $ UniqueBlogPost project_id post_name let has_permission = exprCommentProjectPermissionFilter muser_id (val project_id) root_comments <- get_root_comments (blogPostDiscussion blog_post) has_permission return (p, root_comments) (comment_forest_no_css, _) <- makeBlogPostCommentForestWidget muser project_id project_handle post_name root_comments def getMaxDepth False mempty let has_comments = not (null root_comments) comment_forest = do comment_forest_no_css toWidget $(cassiusFile "templates/comment.cassius") (comment_form, _) <- generateFormPost commentNewTopicForm defaultLayout $ do snowdriftTitle $ projectName project <> " Discussion" $(widgetFile "project_blog_discuss") -------------------------------------------------------------------------------- -- /p/#Text/blog/#Text/d/new getNewBlogPostDiscussionR :: Text -> Text -> Handler Html getNewBlogPostDiscussionR project_handle post_name = do void requireAuth let widget = commentNewTopicFormWidget defaultLayout $ projectBlogDiscussionPage project_handle post_name widget postNewBlogPostDiscussionR :: Text -> Text -> Handler Html postNewBlogPostDiscussionR project_handle post_name = do user <- requireAuth Entity _ BlogPost{..} <- runYDB $ do Entity project_id _ <- getBy404 $ UniqueProjectHandle project_handle getBy404 $ UniqueBlogPost project_id post_name postNewComment Nothing user blogPostDiscussion (makeProjectCommentActionPermissionsMap (Just user) project_handle def) >>= \case ConfirmedPost (Left err) -> do alertDanger err redirect $ NewBlogPostDiscussionR project_handle post_name ConfirmedPost (Right comment_id) -> redirect $ BlogPostCommentR project_handle post_name comment_id Com.Preview (widget, form) -> defaultLayout $ previewWidget form "post" $ projectBlogDiscussionPage project_handle post_name widget
chreekat/snowdrift
Handler/ProjectBlog.hs
agpl-3.0
30,095
0
18
5,634
6,345
3,097
3,248
-1
-1
-- -- Copyright 2017-2018 Azad Bolour -- Licensed under GNU Affero General Public License v3.0 - -- https://github.com/azadbolour/boardgame/blob/master/LICENSE.md -- {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE DisambiguateRecordFields #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} module BoardGame.Server.Domain.PieceProvider ( PieceProvider(..) , BoardGame.Server.Domain.PieceProvider.take , takePieces , swapOne , pieceProviderType , mkDefaultCyclicPieceProvider ) where import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Except (MonadError(..)) import BoardGame.Common.Domain.Piece (Piece, Piece(Piece)) import qualified BoardGame.Common.Domain.PieceProviderType as PieceProviderType import BoardGame.Common.Domain.PieceProviderType import BoardGame.Server.Domain.GameError (GameError) -- The piece generator types are closed in this implementation. -- TODO. Would be nice to have an open piece generator implementation model. -- Had some type system issues using type classes. -- TODO. Name cyclic constructor parameters. -- | Piece generator. -- Included in the common package to allow client tests -- to generate pieces consistently with the server. data PieceProvider = RandomPieceProvider { counter :: Integer, randomizer :: IO Char} | CyclicPieceProvider Integer String take :: (MonadError GameError m, MonadIO m) => PieceProvider -> m (Piece, PieceProvider) take (provider @ RandomPieceProvider {counter, randomizer}) = do letter <- liftIO $ randomizer let piece = Piece letter (show counter) let nextProvider = RandomPieceProvider (counter + 1) randomizer return (piece, nextProvider) take (CyclicPieceProvider count cycler) = do let count' = count + 1 piece = Piece (head cycler) (show count') return (piece, CyclicPieceProvider count' (drop 1 cycler)) -- TODO. Best practices to disambiguate against Prelude [take]? take' :: (MonadError GameError m, MonadIO m) => PieceProvider -> m (Piece, PieceProvider) take' = BoardGame.Server.Domain.PieceProvider.take takePieces :: (MonadError GameError m, MonadIO m) => PieceProvider -> Int -> m ([Piece], PieceProvider) takePieces provider max = takePiecesAux provider [] max takePiecesAux :: (MonadError GameError m, MonadIO m) => PieceProvider -> [Piece] -> Int -> m ([Piece], PieceProvider) takePiecesAux provider list n = if n <= 0 then return (list, provider) else do (piece, provider1) <- take' provider (pieces, provider2) <- takePiecesAux provider1 (piece:list) (n - 1) return (pieces, provider2) swapOne :: (MonadError GameError m, MonadIO m) => PieceProvider -> Piece -> m (Piece, PieceProvider) swapOne provider piece = do (swappedPiece, provider1) <- take' provider -- provider2 <- give provider1 piece return (swappedPiece, provider1) pieceProviderType :: PieceProvider -> PieceProviderType pieceProviderType (RandomPieceProvider _ _) = PieceProviderType.Random pieceProviderType (CyclicPieceProvider _ _) = PieceProviderType.Cyclic caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" mkDefaultCyclicPieceProvider :: PieceProvider mkDefaultCyclicPieceProvider = CyclicPieceProvider 0 (cycle caps)
azadbolour/boardgame
haskell-server/src/BoardGame/Server/Domain/PieceProvider.hs
agpl-3.0
3,252
1
13
481
766
430
336
54
2
-- | Layer module, defining functions to work on a neural network layer, which -- is a list of neurons module AI.HNN.Layer where import AI.HNN.Neuron import Control.Arrow import Data.Vector (Vector(), fromList, sum, toList, zipWith) import Data.List (foldl') -- * Layer creation -- | Creates a layer compound of n neurons with the Sigmoid transfer function, -- all having the given threshold and weights. createSigmoidLayerU :: Int -> Double -> Vector Double -> [Neuron] createSigmoidLayerU n threshold weights = take n . repeat $ neuron where neuron = createNeuronSigmoidU threshold weights -- | Creates a layer compound of n neurons with the Heavyside transfer -- function, all having the given threshold and weights. createHeavysideLayerU :: Int -> Double -> Vector Double -> [Neuron] createHeavysideLayerU n threshold weights = take n . repeat $ neuron where neuron = createNeuronSigmoidU threshold weights -- | Creates a layer compound of n neurons with the sigmoid transfer function, -- all having the given threshold and weights. createSigmoidLayer :: Int -> Double -> [Double] -> [Neuron] createSigmoidLayer n threshold = createSigmoidLayerU n threshold . fromList -- | Creates a layer compound of n neurons with the sigmoid transfer function, -- all having the given threshold and weights. createHeavysideLayer :: Int -> Double -> [Double] -> [Neuron] createHeavysideLayer n threshold = createHeavysideLayerU n threshold . fromList -- * Computation -- | Computes the outputs of each Neuron of the layer computeLayerU :: [Neuron] -> Vector Double -> Vector Double computeLayerU ns inputs = fromList $ map (\n -> computeU n inputs) ns -- | Computes the outputs of each Neuron of the layer computeLayer :: [Neuron] -> [Double] -> [Double] computeLayer ns = toList . computeLayerU ns . fromList -- * Learning -- | Trains each neuron with the given sample and the given learning ratio learnSampleLayerU :: Double -> [Neuron] -> (Vector Double, Vector Double) -> [Neuron] learnSampleLayerU alpha ns (xs, ys) = Prelude.zipWith (\n y -> learnSampleU alpha n (xs, y)) ns $ toList ys -- | Trains each neuron with the given sample and the given learning ratio learnSampleLayer :: Double -> [Neuron] -> ([Double], [Double]) -> [Neuron] learnSampleLayer alpha ns = learnSampleLayerU alpha ns . (fromList *** fromList) -- | Trains each neuron with the given samples and the given learning ratio learnSamplesLayerU :: Double -> [Neuron] -> [(Vector Double, Vector Double)] -> [Neuron] learnSamplesLayerU alpha = Data.List.foldl' (learnSampleLayerU alpha) -- | Trains each neuron with the given samples and the given learning ratio learnSamplesLayer :: Double -> [Neuron] -> [([Double], [Double])] -> [Neuron] learnSamplesLayer alpha ns = learnSamplesLayerU alpha ns . map (fromList *** fromList) -- * Quadratic Error -- | Returns the quadratic error of a layer for a given sample quadErrorU :: [Neuron] -> (Vector Double, Vector Double) -> Double quadErrorU ns (xs, ys) = (/2) $ Data.Vector.sum $ Data.Vector.zipWith (\o y -> (y - o)**2) os ys where os = computeLayerU ns xs -- | Returns the quadratic error of a layer for a given sample quadError :: [Neuron] -> ([Double], [Double]) -> Double quadError ns = quadErrorU ns . (fromList *** fromList)
alpmestan/HNN-0.1
AI/HNN/Layer.hs
lgpl-3.0
3,290
0
11
561
798
441
357
37
1
module Network.Haskoin.Wallet.KeyRing ( -- *Database KeyRings initWallet , newKeyRing , keyRings , keyRingSource , getKeyRing -- *Database Accounts , accounts , accountSource , newAccount , addAccountKeys , getAccount , isMultisigAccount , isReadAccount , isCompleteAccount -- *Database Addresses , getAddress , addressSourceAll , addressSource , addressPage , unusedAddresses , addressCount , setAddrLabel , addressPrvKey , useAddress , generateAddrs , setAccountGap , firstAddrTime , getPathRedeem , getPathPubKey -- *Database Bloom Filter , getBloomFilter -- * Helpers , subSelectAddrCount ) where import Control.Monad (unless, when, liftM) import Control.Monad.Trans (MonadIO, liftIO) import Control.Monad.Base (MonadBase) import Control.Monad.Catch (MonadThrow) import Control.Monad.Trans.Resource (MonadResource) import Control.Exception (throwIO, throw) import Data.Text (Text, unpack) import Data.Maybe (mapMaybe, listToMaybe) import Data.Time.Clock (getCurrentTime) import Data.Conduit (Source, mapOutput, await, ($$)) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Data.List (nub) import Data.Word (Word32) import qualified Data.ByteString as BS (ByteString, null) import qualified Database.Persist as P (updateWhere, update , (=.)) import Database.Esqueleto ( Value(..), SqlExpr, SqlQuery , InnerJoin(..), on , select, from, where_, val, sub_select, countRows, count, unValue , orderBy, limit, asc, desc, offset, selectSource, get , max_, not_, isNothing, case_, when_, then_, else_ , (^.), (==.), (&&.), (>.), (-.), (<.) -- Reexports from Database.Persist , SqlPersistT, Entity(..) , getBy, insertUnique, insertMany_, insert_ ) import Network.Haskoin.Crypto import Network.Haskoin.Block import Network.Haskoin.Script import Network.Haskoin.Node import Network.Haskoin.Util import Network.Haskoin.Constants import Network.Haskoin.Node.HeaderTree import Network.Haskoin.Wallet.Types import Network.Haskoin.Wallet.Model {- Initialization -} initWallet :: MonadIO m => Double -> SqlPersistT m () initWallet fpRate = do prevConfigRes <- select $ from $ \c -> return $ count $ c ^. KeyRingConfigId let cnt = maybe 0 unValue $ listToMaybe prevConfigRes if cnt == (0 :: Int) then do time <- liftIO getCurrentTime -- Create an initial bloom filter -- TODO: Compute a random nonce let bloom = bloomCreate (filterLen 0) fpRate 0 BloomUpdateNone insert_ $ KeyRingConfig { keyRingConfigHeight = 0 , keyRingConfigBlock = headerHash genesisHeader , keyRingConfigBloomFilter = bloom , keyRingConfigBloomElems = 0 , keyRingConfigBloomFp = fpRate , keyRingConfigVersion = 1 , keyRingConfigCreated = time } else return () -- Nothing to do {- KeyRing -} -- | Create a new KeyRing from a seed newKeyRing :: MonadIO m => KeyRingName -> BS.ByteString -> SqlPersistT m KeyRing newKeyRing name seed | BS.null seed = liftIO . throwIO $ WalletException "The seed is empty" | otherwise = do now <- liftIO getCurrentTime let keyRing = KeyRing { keyRingName = name , keyRingMaster = makeXPrvKey seed , keyRingCreated = now } insertUnique keyRing >>= \resM -> case resM of Just _ -> return keyRing _ -> liftIO . throwIO $ WalletException $ unwords [ "KeyRing", unpack name, "already exists" ] keyRings :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => SqlPersistT m [KeyRing] keyRings = liftM (map entityVal) $ select $ from return -- | Stream all KeyRings keyRingSource :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Source (SqlPersistT m) KeyRing keyRingSource = mapOutput entityVal $ selectSource $ from return -- Helper functions to get a KeyRing if it exists, or throw an exception -- otherwise. getKeyRing :: MonadIO m => KeyRingName -> SqlPersistT m (Entity KeyRing) getKeyRing name = getBy (UniqueKeyRing name) >>= \resM -> case resM of Just keyRingEnt -> return keyRingEnt _ -> liftIO . throwIO $ WalletException $ unwords [ "KeyRing", unpack name, "does not exist." ] {- Account -} -- | Fetch all the accounts in a keyring accounts :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => KeyRingId -> SqlPersistT m [KeyRingAccount] accounts ki = liftM (map entityVal) $ select $ accountsFrom ki -- | Stream all accounts in a keyring accountSource :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => KeyRingId -> Source (SqlPersistT m) KeyRingAccount accountSource ki = mapOutput entityVal $ selectSource $ accountsFrom ki accountsFrom :: KeyRingId -> SqlQuery (SqlExpr (Entity KeyRingAccount)) accountsFrom ki = from $ \a -> do where_ $ a ^. KeyRingAccountKeyRing ==. val ki return a -- | Create a new account newAccount :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRing -> AccountName -> AccountType -> [XPubKey] -> SqlPersistT m (Entity KeyRingAccount) newAccount (Entity ki keyRing) accountName accountType extraKeys = do unless (validAccountType accountType) $ liftIO . throwIO $ WalletException "Invalid account type" -- Get the next account derivation derivM <- if accountTypeRead accountType then return Nothing else liftM Just $ nextAccountDeriv ki -- Derive the next account key let f d = [ deriveXPubKey (derivePath d $ keyRingMaster keyRing) ] keys = (maybe [] f derivM) ++ extraKeys -- Build the account now <- liftIO getCurrentTime let acc = KeyRingAccount { keyRingAccountKeyRing = ki , keyRingAccountName = accountName , keyRingAccountType = accountType , keyRingAccountDerivation = derivM , keyRingAccountKeys = keys , keyRingAccountGap = 0 , keyRingAccountCreated = now } -- Check if all the keys are valid unless (isValidAccKeys acc) $ liftIO . throwIO $ WalletException "Invalid account keys" -- Insert our account in the database let canSetGap = isCompleteAccount acc newAcc = acc{ keyRingAccountGap = if canSetGap then 10 else 0 } insertUnique newAcc >>= \resM -> case resM of -- The account got created. Just ai -> do let accE = Entity ai newAcc -- If we can set the gap, create the gap addresses when canSetGap $ do _ <- createAddrs accE AddressExternal 20 _ <- createAddrs accE AddressInternal 20 return () return accE -- The account already exists Nothing -> liftIO . throwIO $ WalletException $ unwords [ "Account", unpack accountName, "already exists" ] -- | Add new thirdparty keys to a multisignature account. This function can -- fail if the multisignature account already has all required keys. addAccountKeys :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -- ^ Account Entity -> [XPubKey] -- ^ Thirdparty public keys to add -> SqlPersistT m KeyRingAccount -- ^ Account information addAccountKeys (Entity ai acc) keys -- We can only add keys on incomplete accounts | isCompleteAccount acc = liftIO . throwIO $ WalletException "The account is already complete" | null keys || (not $ isValidAccKeys accKeys) = liftIO . throwIO $ WalletException "Invalid account keys" | otherwise = do let canSetGap = isCompleteAccount accKeys updGap = if canSetGap then [ KeyRingAccountGap P.=. 10 ] else [] newAcc = accKeys{ keyRingAccountGap = if canSetGap then 10 else 0 } -- Update the account with the keys and the new gap if it is complete P.update ai $ (KeyRingAccountKeys P.=. newKeys) : updGap -- If we can set the gap, create the gap addresses when canSetGap $ do let accE = Entity ai newAcc _ <- createAddrs accE AddressExternal 20 _ <- createAddrs accE AddressInternal 20 return () return newAcc where newKeys = keyRingAccountKeys acc ++ keys accKeys = acc{ keyRingAccountKeys = newKeys } isValidAccKeys :: KeyRingAccount -> Bool isValidAccKeys KeyRingAccount{..} = case keyRingAccountType of AccountRegular _ -> length keyRingAccountKeys == 1 -- read-only accounts can have 0 keys. Otherwise 1 key is required. AccountMultisig r _ n -> goMultisig n (if r then 0 else 1) where goMultisig n minLen = length keyRingAccountKeys == length (nub keyRingAccountKeys) && length keyRingAccountKeys <= n && length keyRingAccountKeys >= minLen -- | Compute the next derivation path for a new account nextAccountDeriv :: MonadIO m => KeyRingId -> SqlPersistT m HardPath nextAccountDeriv ki = do lastRes <- select $ from $ \a -> do where_ ( a ^. KeyRingAccountKeyRing ==. val ki &&. not_ (isNothing (a ^. KeyRingAccountDerivation)) ) orderBy [ desc (a ^. KeyRingAccountId) ] limit 1 return $ a ^. KeyRingAccountDerivation return $ case lastRes of (Value (Just (prev :| i)):_) -> prev :| (i + 1) _ -> Deriv :| 0 -- Helper functions to get an Account if it exists, or throw an exception -- otherwise. getAccount :: MonadIO m => KeyRingName -> AccountName -> SqlPersistT m (KeyRing, Entity KeyRingAccount) getAccount keyRingName accountName = do as <- select $ from $ \(k `InnerJoin` a) -> do on $ a ^. KeyRingAccountKeyRing ==. k ^. KeyRingId where_ ( k ^. KeyRingName ==. val keyRingName &&. a ^. KeyRingAccountName ==. val accountName ) return (k, a) case as of ((Entity _ k, accEnt):_) -> return (k, accEnt) _ -> liftIO . throwIO $ WalletException $ unwords [ "Account", unpack accountName, "does not exist" ] {- Addresses -} -- | Get an address if it exists, or throw an exception otherwise. Fetching -- addresses in the hidden gap will also throw an exception. getAddress :: MonadIO m => Entity KeyRingAccount -- ^ Account Entity -> AddressType -- ^ Address type -> KeyIndex -- ^ Derivation index (key) -> SqlPersistT m (Entity KeyRingAddr) -- ^ Address getAddress accE@(Entity ai _) addrType index = do res <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType &&. x ^. KeyRingAddrIndex ==. val index &&. x ^. KeyRingAddrIndex <. subSelectAddrCount accE addrType ) limit 1 return x case res of (addrE:_) -> return addrE _ -> liftIO . throwIO $ WalletException $ unwords [ "Invalid address index", show index ] -- | Stream all addresses in the wallet, including hidden gap addresses. This -- is useful for building a bloom filter. addressSourceAll :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Source (SqlPersistT m) KeyRingAddr addressSourceAll = mapOutput entityVal $ selectSource $ from return -- | Stream all addresses in one account. Hidden gap addresses are not included. addressSource :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -- ^ Account Entity -> AddressType -- ^ Address Type -> Source (SqlPersistT m) KeyRingAddr -- ^ Source of addresses addressSource accE@(Entity ai _) addrType = mapOutput entityVal $ selectSource $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType &&. x ^. KeyRingAddrIndex <. subSelectAddrCount accE addrType ) return x -- | Get addresses by pages. addressPage :: MonadIO m => Entity KeyRingAccount -- ^ Account Entity -> AddressType -- ^ Address type -> PageRequest -- ^ Page request -> SqlPersistT m ([KeyRingAddr], Word32) -- ^ Page result addressPage accE@(Entity ai _) addrType page@PageRequest{..} | validPageRequest page = do cnt <- addressCount accE addrType let (d, m) = cnt `divMod` pageLen maxPage = max 1 $ d + min 1 m when (pageNum > maxPage) $ liftIO . throwIO $ WalletException $ unwords [ "Invalid page number", show pageNum ] if cnt == 0 then return ([], maxPage) else do res <- liftM (map entityVal) $ select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType &&. x ^. KeyRingAddrIndex <. val cnt ) let order = if pageReverse then asc else desc orderBy [ order (x ^. KeyRingAddrIndex) ] limit $ fromIntegral pageLen offset $ fromIntegral $ (pageNum - 1) * pageLen return x -- Flip the order back to ASC if we had it DEC let f = if pageReverse then id else reverse return (f res, maxPage) | otherwise = liftIO . throwIO $ WalletException $ concat [ "Invalid page request" , " (Page: ", show pageNum, ", Page size: ", show pageLen, ")" ] -- | Get a count of all the addresses in an account addressCount :: MonadIO m => Entity KeyRingAccount -- ^ Account Entity -> AddressType -- ^ Address type -> SqlPersistT m Word32 -- ^ Address Count addressCount (Entity ai acc) addrType = do res <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType ) return countRows let cnt = maybe 0 unValue $ listToMaybe res return $ if cnt > keyRingAccountGap acc then cnt - keyRingAccountGap acc else 0 -- | Get a list of all unused addresses. unusedAddresses :: MonadIO m => Entity KeyRingAccount -- ^ Account ID -> AddressType -- ^ Address type -> SqlPersistT m [KeyRingAddr] -- ^ Unused addresses unusedAddresses (Entity ai acc) addrType = do liftM (reverse . map entityVal) $ select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType ) orderBy [ desc $ x ^. KeyRingAddrIndex ] limit $ fromIntegral $ keyRingAccountGap acc offset $ fromIntegral $ keyRingAccountGap acc return x -- | Add a label to an address. setAddrLabel :: MonadIO m => Entity KeyRingAccount -- ^ Account ID -> KeyIndex -- ^ Derivation index -> AddressType -- ^ Address type -> Text -- ^ New label -> SqlPersistT m KeyRingAddr setAddrLabel accE i addrType label = do Entity addrI addr <- getAddress accE addrType i P.update addrI [ KeyRingAddrLabel P.=. label ] return $ addr{ keyRingAddrLabel = label } -- | Returns the private key of an address. addressPrvKey :: MonadIO m => KeyRing -- ^ KeyRing -> Entity KeyRingAccount -- ^ Account Entity -> KeyIndex -- ^ Derivation index of the address -> AddressType -- ^ Address type -> SqlPersistT m PrvKeyC -- ^ Private key addressPrvKey keyRing accE@(Entity ai _) index addrType = do res <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType &&. x ^. KeyRingAddrIndex ==. val index &&. x ^. KeyRingAddrIndex <. subSelectAddrCount accE addrType ) return (x ^. KeyRingAddrFullDerivation) case res of (Value (Just deriv):_) -> return $ xPrvKey $ derivePath deriv $ keyRingMaster keyRing _ -> liftIO . throwIO $ WalletException "Invalid address" -- | Create new addresses in an account and increment the internal bloom filter. -- This is a low-level function that simply creates the desired amount of new -- addresses in an account, disregarding visible and hidden address gaps. You -- should use the function `setAccountGap` if you want to control the gap of an -- account instead. createAddrs :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -> AddressType -> Word32 -> SqlPersistT m [KeyRingAddr] createAddrs (Entity ai acc) addrType n | n == 0 = liftIO . throwIO $ WalletException $ unwords [ "Invalid value", show n ] | not (isCompleteAccount acc) = liftIO . throwIO $ WalletException $ unwords [ "Keys are still missing from the incomplete account" , unpack $ keyRingAccountName acc ] | otherwise = do now <- liftIO getCurrentTime -- Find the next derivation index from the last address lastRes <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType ) return $ max_ (x ^. KeyRingAddrIndex) let nextI = case lastRes of (Value (Just lastI):_) -> lastI + 1 _ -> 0 build (addr, keyM, rdmM, i) = KeyRingAddr { keyRingAddrAccount = ai , keyRingAddrAddress = addr , keyRingAddrIndex = i , keyRingAddrType = addrType , keyRingAddrLabel = "" -- Full derivation from the master key , keyRingAddrFullDerivation = let f d = toMixed d :/ branchType :/ i in f <$> keyRingAccountDerivation acc -- Partial derivation under the account derivation , keyRingAddrDerivation = Deriv :/ branchType :/ i , keyRingAddrRedeem = rdmM , keyRingAddrKey = keyM , keyRingAddrCreated = now } res = map build $ take (fromIntegral n) $ deriveFrom nextI -- Save the addresses and increment the bloom filter insertMany_ res incrementFilter res return res where -- Branch type (external = 0, internal = 1) branchType = addrTypeIndex addrType deriveFrom = case keyRingAccountType acc of AccountMultisig _ m _ -> let f (a, r, i) = (a, Nothing, Just r, i) deriv = Deriv :/ branchType in map f . derivePathMSAddrs (keyRingAccountKeys acc) deriv m AccountRegular _ -> case keyRingAccountKeys acc of (key:_) -> let f (a, k, i) = (a, Just k, Nothing, i) in map f . derivePathAddrs key (Deriv :/ branchType) [] -> throw $ WalletException $ unwords [ "createAddrs: No key available in regular account" , unpack $ keyRingAccountName acc ] -- | Generate all the addresses up to a certain index generateAddrs :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -> AddressType -> KeyIndex -> SqlPersistT m Int generateAddrs accE@(Entity _ _) addrType genIndex = do cnt <- addressCount accE addrType let toGen = (fromIntegral genIndex) - (fromIntegral cnt) + 1 if toGen > 0 then do _ <- createAddrs accE addrType $ fromIntegral toGen return toGen else return 0 -- | Use an address and make sure we have enough gap addresses after it. -- Returns the new addresses that have been created. useAddress :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => KeyRingAddr -> SqlPersistT m [KeyRingAddr] useAddress KeyRingAddr{..} = do res <- select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val keyRingAddrAccount &&. x ^. KeyRingAddrType ==. val keyRingAddrType &&. x ^. KeyRingAddrIndex >. val keyRingAddrIndex ) return countRows case res of ((Value cnt):_) -> get keyRingAddrAccount >>= \accM -> case accM of Just acc -> do let accE = Entity keyRingAddrAccount acc gap = fromIntegral (keyRingAccountGap acc) :: Int missing = 2*gap - cnt if missing > 0 then createAddrs accE keyRingAddrType $ fromIntegral missing else return [] _ -> return [] -- Should not happen _ -> return [] -- Should not happen -- | Set the address gap of an account to a new value. This will create new -- internal and external addresses as required. The gap can only be increased, -- not decreased in size. setAccountGap :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => Entity KeyRingAccount -- ^ Account Entity -> Word32 -- ^ New gap value -> SqlPersistT m KeyRingAccount setAccountGap accE@(Entity ai acc) gap | not (isCompleteAccount acc) = liftIO . throwIO $ WalletException $ unwords [ "Keys are still missing from the incomplete account" , unpack $ keyRingAccountName acc ] | missing <= 0 = liftIO . throwIO $ WalletException "The gap of an account can only be increased" | otherwise = do _ <- createAddrs accE AddressExternal $ fromInteger $ missing*2 _ <- createAddrs accE AddressInternal $ fromInteger $ missing*2 P.update ai [ KeyRingAccountGap P.=. gap ] return $ acc{ keyRingAccountGap = gap } where missing = toInteger gap - toInteger (keyRingAccountGap acc) -- Return the creation time of the first address in the wallet. firstAddrTime :: MonadIO m => SqlPersistT m (Maybe Timestamp) firstAddrTime = do res <- select $ from $ \x -> do orderBy [ asc (x ^. KeyRingAddrId) ] limit 1 return $ x ^. KeyRingAddrCreated return $ case res of (Value d:_) -> Just $ toPOSIX d _ -> Nothing where toPOSIX = fromInteger . round . utcTimeToPOSIXSeconds {- Bloom filters -} -- | Add the given addresses to the bloom filter. If the number of elements -- becomes too large, a new bloom filter is computed from scratch. incrementFilter :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => [KeyRingAddr] -> SqlPersistT m () incrementFilter addrs = do (bloom, elems, _) <- getBloomFilter let newElems = elems + (length addrs * 2) if filterLen newElems > filterLen elems then computeNewFilter else setBloomFilter (addToFilter bloom addrs) newElems -- | Generate a new bloom filter from the data in the database computeNewFilter :: (MonadIO m, MonadThrow m, MonadBase IO m, MonadResource m) => SqlPersistT m () computeNewFilter = do (_, _, fpRate) <- getBloomFilter -- Create a new empty bloom filter -- TODO: Choose a random nonce for the bloom filter -- TODO: Check global bloom filter length limits cntRes <- select $ from $ \x -> return $ count $ x ^. KeyRingAddrId let elems = maybe 0 unValue $ listToMaybe cntRes newBloom = bloomCreate (filterLen elems) fpRate 0 BloomUpdateNone bloom <- addressSourceAll $$ bloomSink newBloom setBloomFilter bloom elems where bloomSink bloom = await >>= \addrM -> case addrM of Just addr -> bloomSink $ addToFilter bloom [addr] _ -> return bloom -- Compute the size of a filter given a number of elements. Scale -- the filter length by powers of 2. filterLen :: Int -> Int filterLen = round . pow2 . ceiling . log2 where pow2 x = (2 :: Double) ** fromInteger x log2 x = logBase (2 :: Double) (fromIntegral x) -- | Add elements to a bloom filter addToFilter :: BloomFilter -> [KeyRingAddr] -> BloomFilter addToFilter bloom addrs = bloom3 where pks = mapMaybe keyRingAddrKey addrs rdms = mapMaybe keyRingAddrRedeem addrs -- Add the Hash160 of the addresses f1 b a = bloomInsert b $ encode' $ getAddrHash a bloom1 = foldl f1 bloom $ map keyRingAddrAddress addrs -- Add the redeem scripts f2 b r = bloomInsert b $ encodeOutputBS r bloom2 = foldl f2 bloom1 rdms -- Add the public keys f3 b p = bloomInsert b $ encode' p bloom3 = foldl f3 bloom2 pks -- | Returns a bloom filter containing all the addresses in this wallet. This -- includes internal and external addresses. The bloom filter can be set on a -- peer connection to filter the transactions received by that peer. getBloomFilter :: MonadIO m => SqlPersistT m (BloomFilter, Int, Double) getBloomFilter = do res <- select $ from $ \c -> do limit 1 return ( c ^. KeyRingConfigBloomFilter , c ^. KeyRingConfigBloomElems , c ^. KeyRingConfigBloomFp ) case res of ((Value b, Value n, Value fp):_) -> return (b, n, fp) _ -> liftIO . throwIO $ WalletException "getBloomFilter: Database not initialized" -- | Save a bloom filter and the number of elements it contains setBloomFilter :: MonadIO m => BloomFilter -> Int -> SqlPersistT m () setBloomFilter bloom elems = P.updateWhere [] [ KeyRingConfigBloomFilter P.=. bloom , KeyRingConfigBloomElems P.=. elems ] -- Helper function to compute the redeem script of a given derivation path -- for a given multisig account. getPathRedeem :: KeyRingAccount -> SoftPath -> RedeemScript getPathRedeem acc@KeyRingAccount{..} deriv = case keyRingAccountType of AccountMultisig _ m _ -> if isCompleteAccount acc then sortMulSig $ PayMulSig pubKeys m else throw $ WalletException $ unwords [ "getPathRedeem: Incomplete multisig account" , unpack keyRingAccountName ] _ -> throw $ WalletException $ unwords [ "getPathRedeem: Account", unpack keyRingAccountName , "is not a multisig account" ] where f = toPubKeyG . xPubKey . derivePubPath deriv pubKeys = map f keyRingAccountKeys -- Helper function to compute the public key of a given derivation path for -- a given non-multisig account. getPathPubKey :: KeyRingAccount -> SoftPath -> PubKeyC getPathPubKey acc@KeyRingAccount{..} deriv | isMultisigAccount acc = throw $ WalletException $ unwords [ "getPathPubKey: Account", unpack keyRingAccountName , "is not a regular non-multisig account" ] | otherwise = case keyRingAccountKeys of (key:_) -> xPubKey $ derivePubPath deriv key _ -> throw $ WalletException $ unwords [ "getPathPubKey: No keys are available in account" , unpack keyRingAccountName ] {- Helpers -} subSelectAddrCount :: Entity KeyRingAccount -> AddressType -> SqlExpr (Value KeyIndex) subSelectAddrCount (Entity ai acc) addrType = sub_select $ from $ \x -> do where_ ( x ^. KeyRingAddrAccount ==. val ai &&. x ^. KeyRingAddrType ==. val addrType ) let gap = val $ keyRingAccountGap acc return $ case_ [ when_ (countRows >. gap) then_ (countRows -. gap) ] (else_ $ val 0) validMultisigParams :: Int -> Int -> Bool validMultisigParams m n = n >= 1 && n <= 15 && m >= 1 && m <= n validAccountType :: AccountType -> Bool validAccountType t = case t of AccountRegular _ -> True AccountMultisig _ m n -> validMultisigParams m n isMultisigAccount :: KeyRingAccount -> Bool isMultisigAccount acc = case keyRingAccountType acc of AccountRegular _ -> False AccountMultisig _ _ _ -> True isReadAccount :: KeyRingAccount -> Bool isReadAccount acc = case keyRingAccountType acc of AccountRegular r -> r AccountMultisig r _ _ -> r isCompleteAccount :: KeyRingAccount -> Bool isCompleteAccount acc = case keyRingAccountType acc of AccountRegular _ -> length (keyRingAccountKeys acc) == 1 AccountMultisig _ _ n -> length (keyRingAccountKeys acc) == n
tphyahoo/haskoin-wallet
Network/Haskoin/Wallet/KeyRing.hs
unlicense
29,147
1
25
8,884
7,236
3,697
3,539
-1
-1
{- Reverse a string Reverse a sentence ("bob likes dogs" -> "dogs likes bob") Find the minimum value in a list Find the maximum value in a list Calculate a remainder (given a numerator and denominator) Return distinct values from a list including duplicates (i.e. "1 3 5 3 7 3 1 1 5" -> "1 3 5 7") Return distinct values and their counts (i.e. the list above becomes "1(3) 3(3) 5(2) 7(1)") Given a string of expressions (only variables, +, and -) and a set of variable/value pairs (i.e. a=1, b=7, c=3, d=14) return the result of the expression ("a + b+c -d" would be -3). -} problem_one = reverse problem_two = unwords . reverse . words problem_three::(Ord a)=>[a]->a problem_three = foldl1 min problem_four::(Ord a)=>[a]->a problem_four = foldl1 max problem_five = rem problem_six::(Eq a)=>[a]->[a] problem_six = foldl (\acc e->(if elem e acc then acc else e:acc)) [] {- problem_seven::(Eq a)=>[a]->[a] problem_seven lst = let count::(Eq a)=>a->[a]->Int count elem = length . filter (==elem) add_counts::[(a, Int)] add_counts = map (\x->(x, count x lst)) lst in problem_six add_counts -} a = take 99 [2..] b = a c = a >>= \x-> map ($x) $ map (^) b main = print $ length $ problem_six c
Crazycolorz5/Haskell-Code
fizzBuzz_tasks.hs
unlicense
1,286
6
10
305
230
120
110
13
2
module Main where import MiniLambda import MiniLambda.Parser import MiniLambda.Definitions import System.IO (hFlush, stdout) main :: IO () main = do putStr "> " hFlush stdout input <- dropWhile (==' ') <$> getLine handle input main handle :: String -> IO () handle "" = return () handle input = putStrLn $ either show eval (parseExpression input) where eval = show . evalFullWith prelude
phipsgabler/mini-lambda
app/Main.hs
unlicense
404
0
10
79
150
75
75
16
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} import qualified Data.ByteString.Char8 as C import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.ByteString.Unsafe as BLU import Data.ByteString.Lazy.Builder #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 707 import Data.ByteString.Lazy.Builder.ASCII #endif import Data.Maybe(fromJust) import Data.Monoid import Data.Int import System.IO import Data.Char data I = I { _i1 :: {-# UNPACK #-} !Int , _i2 :: {-# UNPACK #-} !Int , _i3 :: {-# UNPACK #-} !Int } isqrt = ceiling . sqrt . fromIntegral {-# INLINE isqrt #-} venom :: Int -> Int -> Int -> Int64 venom h p a = r' where (h', p', a') = (fromIntegral h, fromIntegral p, fromIntegral a) :: (Int64, Int64, Int64) !b = 2*a'-p' !delta = sqrt . fromIntegral $ (b*b+(8*p'*(h'-a'))) !r = ((fromIntegral b) + delta ) / (fromIntegral (2*p)) :: Double !r' = 2 * (ceiling r) - 1 {-# INLINE venom_ #-} venom_ :: Int -> Int -> Int -> Int64 venom_ h p a = r' where !h' = fromIntegral h :: Int64 !p' = fromIntegral p :: Int64 !a' = fromIntegral a :: Int64 !b = 2*a'-p' !delta2 = b*b + 8*p'*(h'-a') !delta = isqrt delta2 !r = (b + delta - 1) `div` (2*p') !r' = 2*r+1 venom' (I h p a) = venom_ h p a {-# INLINE venom' #-} readj3 = C.foldl' go (1, (I 0 0 0)) where go (!k, !i@(I x y z)) c | c == ' ' = (succ k, i) | k == 1 = (k, I (10*x+ord c - ord '0') y z) | k == 2 = (k, I x (10*y+ord c - ord '0') z) | k == 3 = (k, I x y (10*z+ord c - ord '0')) go :: (Int, I) -> Char -> (Int, I) {-# INLINE go #-} readi3_ s = C.readInt s >>= \(!i1, !s1) -> (C.readInt . BLU.unsafeTail) s1 >>= \(!i2, !s2) -> (C.readInt . BLU.unsafeTail) s2 >>= \(!i3, _) -> return $! (I i1 i2 i3) {-# INLINE readi3_ #-} {-# INLINE readi3 #-} {-# INLINE readj3 #-} readi3 = fromJust . readi3_ --readi3 = snd . readj3 pr = foldr p1 "" where p1 x = shows x . showString "\n" p1 :: Int64 -> ShowS {-# INLINE p1 #-} {-# INLINE pr #-} main = L.getContents >>= processinputs {-# INLINE process1 #-} {-# INLINE processall #-} {-# INLINE processinputs #-} process1 = putStr . pr . map (venom' . readi3) . C.lines processall [] = return () processall ccs@(c:[]) = process1 c processall ccs@(c1:c2:cs) = process1 c1' >> processall (c2' : cs) where !c'@(!c1', c1'') = C.breakEnd (== '\n') c1 !c2' = C.concat [c1'', c2] processinputs = processall . L.toChunks . L.tail . snd . L.break (== '\n')
wangbj/haskell
venom.hs
bsd-2-clause
2,575
9
13
662
1,113
601
512
69
1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} module Data.Interface.Type.Type where import qualified Data.Functor.Foldable as FF import Data.Interface.Name import Data.Interface.Source ( Origin ) data Type = Con TypeConLink -- ^ type constructors | Apply (TypeApply Type) -- ^ type constructor application | Fun Type Type -- ^ (->) type constructor | Var TypeVar -- ^ type variables ("a") | Forall [TypeVar] Type -- ^ forall qualifiers / constraints | Context [Pred Type] Type -- ^ class and equality predicates deriving (Show, Eq, Ord) -- | The open-recursion form of `Type` that enables composition with other -- functors. See `Data.Interface.Type.Diff` for how this is used to construct -- a tree of type differences. data TypeF a = ConF TypeConLink -- ^ type constructors | ApplyF (TypeApply a) -- ^ type constructor application | FunF a a -- ^ (->) type constructor | VarF TypeVar -- ^ type variables ("a") | ForallF [TypeVar] a -- ^ forall qualifiers / constraints | ContextF [Pred Type] a -- ^ class and equality predicates deriving (Show, Eq, Ord, Functor, Foldable, Traversable) type instance FF.Base Type = TypeF instance FF.Foldable Type where project t0 = case t0 of Con l -> ConF l Apply a -> ApplyF a Fun a b -> FunF a b Var v -> VarF v Forall vs t -> ForallF vs t Context ps t -> ContextF ps t instance FF.Unfoldable Type where embed f = case f of ConF l -> Con l ApplyF a -> Apply a FunF a b -> Fun a b VarF v -> Var v ForallF vs t -> Forall vs t ContextF ps t -> Context ps t instance TraverseNames Type where traverseNames f = fmap FF.embed . traverseNames f . FF.project -- | only includes type constructors instance (TraverseNames a) => TraverseNames (TypeF a) where traverseNames f t0 = case t0 of ConF c -> ConF <$> traverseNames f c ContextF ps t -> ContextF <$> traverse (traverseNames f) ps <*> traverseNames f t _ -> traverse (traverseNames f) t0 -- | A "link" to a type constructor. -- -- When performing diff analysis for a type, identical TypeConLinks indicate -- a form of "shallow" type equality. Depending on the origin of the links, -- it may be desirable to look up the TypeCon referenced by the link in order -- to measure "deep" type equality. type TypeConLink = Qual RawName -- | A class or equality predicate data Pred a = ClassPred [a] | EqPred EqRel a a deriving (Show, Eq, Ord, Functor) -- | A choice of equality relation. Copied from GHC.Type. data EqRel = NomEq | ReprEq deriving (Show, Eq, Ord) instance (TraverseNames a) => TraverseNames (Pred a) where traverseNames f p = case p of ClassPred ts -> ClassPred <$> traverse (traverseNames f) ts EqPred r a b -> EqPred r <$> traverseNames f a <*> traverseNames f b data TypeVar = TypeVar String Kind deriving (Show, Eq, Ord) varName :: TypeVar -> String varName (TypeVar n _) = n varKind :: TypeVar -> Kind varKind (TypeVar _ k) = k data TypeCon = TypeCon { typeConName :: RawName , typeConOrigin :: Origin , typeConKind :: Kind , typeConInfo :: TypeConInfo } deriving (Show, Eq, Ord) data TypeConInfo = ConAlgebraic -- ^ data/newtype declaration | ConSynonym -- ^ type synonym | ConClass -- ^ class declaration deriving (Show, Eq, Ord) type instance Space TypeCon = 'Types instance HasRawName TypeCon where rawName = typeConName rename f tcon = tcon { typeConName = f (typeConName tcon) } instance HasNamespace TypeCon where namespace _ = Types instance TraverseNames TypeCon where traverseNames f (TypeCon n o k i) = TypeCon <$> f n <*> pure o <*> traverseNames f k <*> pure i typeName :: Type -> Maybe RawName typeName t0 = case t0 of Con l -> Just $ rawName l _ -> Nothing stripForall :: Type -> Type stripForall t0 = case FF.project t0 of ForallF _ t -> t _ -> t0 data TypeApply t = ConApply t [t] | ConList t | ConTuple Int [t] deriving (Show, Eq, Ord, Functor, Foldable, Traversable) takeApply :: Type -> Maybe (TypeApply Type) takeApply t0 = case t0 of Apply a -> Just a _ -> Nothing data Kind = KindVar String | StarKind -- ^ Lifted types (*) | HashKind -- ^ Unlifted types (#) | SuperKind -- ^ the type of kinds (BOX) | ConstraintKind -- ^ Constraints | PromotedType (Qual RawName) -- ^ promoted type using DataKinds | FunKind Kind Kind deriving (Show, Eq, Ord) {- Kind notes: TODO: GHC also has AnyK and OpenKind -} instance TraverseNames Kind where traverseNames f k = case k of PromotedType q -> PromotedType <$> traverseNames f q FunKind k0 k1 -> FunKind <$> traverseNames f k0 <*> traverseNames f k1 _ -> pure k -- | Determine the codomain of a `FunKind`. resultKind :: Kind -> Maybe Kind resultKind k0 = case k0 of FunKind _ k -> Just k _ -> Nothing showsKind :: Kind -> ShowS showsKind k = case k of KindVar s -> showString s StarKind -> showChar '*' HashKind -> showChar '#' SuperKind -> showString "BOX" ConstraintKind -> showString "Constraint" PromotedType t -> showString "[showsKind: ERROR PromotedType TODO]" FunKind ka kr -> showsKind ka . showString " -> " . showsKind kr showKind :: Kind -> String showKind k = showsKind k "" type Arity = Int -- | The kind of a basic type constructor. basicTypeConKind :: Arity -> Kind basicTypeConKind a | a < 0 = error "basicTypeConKind: negative arity" | otherwise = go a where go 0 = StarKind go n = FunKind StarKind $ go (n-1)
cdxr/haskell-interface
src/Data/Interface/Type/Type.hs
bsd-3-clause
6,160
0
13
1,794
1,627
840
787
146
7
-------------------------------------------------------------------- -- | -- Module : Network.Delicious.User -- Copyright : (c) Galois, Inc. 2008 -- License : BSD3 -- -- Maintainer : Sigbjorn Finne <sigbjorn.finne@gmail.com> -- Stability : provisional -- Portability : portable -- -------------------------------------------------------------------- module Network.Delicious.RSS ( getHotlist -- :: DM [Post] , getRecentBookmarks -- :: DM [Post] , getTagBookmarks -- :: Tag -> DM [Post] , getTagsBookmarks -- :: [Tag] -> DM [Post] , getPopularBookmarks -- :: DM [Post] , getTagPopularBookmarks -- :: Tag -> DM [Post] , getSiteAlerts -- :: DM [Post] , getUserBookmarks -- :: String -> DM [Post] , getUserTagBookmarks -- :: String -> Tag -> DM [Post] , getUserTaggedBookmarks -- :: String -> [Tag] -> DM [Post] , getUserInfo -- :: String -> DM [Post] , getUserPublicTags -- :: String -> DM [Post] , getUserSubscriptions -- :: String -> DM [Post] , getUserInboxBookmarks -- :: String -> String -> DM [Post] , getNetworkMemberBookmarks -- :: String -> DM [Post] , getNetworkMemberTaggedBookmarks -- :: String -> [Tag] -> DM [Post] , getNetworkMembers -- :: String -> DM [Post] , getNetworkFans -- :: String -> DM [Post] , getURLBookmarks -- :: URLString -> DM [Post] {- , getURLSummary -- :: URLString -> DM [Post] -} ) where import Network.Delicious.Types import Network.Delicious.Fetch import Text.Feed.Query import Text.Feed.Types import Text.Feed.Import import Data.Maybe import Data.List ( intercalate ) import Network.Curl import Data.ByteString ( pack ) import Data.Digest.OpenSSL.MD5 -- ToDo: -- * support for 'count' parameter -- * plain/fancy deli_base :: URLString deli_base = "http://feeds.delicious.com/v2" hotlist_url :: {-URL-}String hotlist_url = deli_base ++ "/rss/" recent_url :: {-URL-}String recent_url = deli_base ++ "/rss/recent" popular_url :: {-URL-}String popular_url = deli_base ++ "/rss/popular" user_url :: {-URL-}String user_url = deli_base ++ "/rss/" alert_url :: {-URL-}String alert_url = deli_base ++ "/rss/alerts" tag_url :: {-URL-}String tag_url = deli_base ++ "/rss/tag/" tags_url :: {-URL-}String tags_url = deli_base ++ "/rss/tags/" inbox_url :: {-URL-}String inbox_url = deli_base ++ "/rss/inbox/" network_url :: {-URL-}String network_url = deli_base ++ "/rss/network/" network_mem_url :: {-URL-}String network_mem_url = deli_base ++ "/rss/networkmembers/" network_fans_url :: {-URL-}String network_fans_url = deli_base ++ "/rss/networkfans/" b_url_url :: {-URL-}String b_url_url = deli_base ++ "/rss/url/" {- UNUSED: b_urlinfo_url :: {-URL-}String b_urlinfo_url = deli_base ++ "/rss/urlinfo/" -} buildUrl :: (String -> URLString -> IO a) -> URLString -> DM a buildUrl f u = do mbc <- getCount ua <- getUAgent liftIO (f ua (case mbc of { Nothing -> u ; Just c -> u++"?count="++show c})) performCall :: String -> URLString -> DM [Post] performCall loc u = do ls <- buildUrl readContentsURL u case parseFeedString ls of Nothing -> fail (loc ++ " invalid RSS feed") Just f -> return (map toPost (feedItems f)) -- getHotlist :: DM [Post] getHotlist = performCall "getHotlist" hotlist_url getRecentBookmarks :: DM [Post] getRecentBookmarks = performCall "getRecentBookmarks" recent_url getTagBookmarks :: Tag -> DM [Post] getTagBookmarks tg = performCall "getTagBookmarks" eff_url where eff_url = tag_url ++ tg getTagsBookmarks :: [Tag] -> DM [Post] getTagsBookmarks tgs = performCall "getTagsBookmarks" eff_url where eff_url = tag_url ++ intercalate "+" tgs getPopularBookmarks :: DM [Post] getPopularBookmarks = performCall "getPopularBookmarks" popular_url getTagPopularBookmarks :: Tag -> DM [Post] getTagPopularBookmarks tg = performCall "getTagPopularBookmarks" eff_url where eff_url = popular_url ++ '/':tg getSiteAlerts :: DM [Post] getSiteAlerts = performCall "getSiteAlerts" alert_url getUserBookmarks :: String -> DM [Post] getUserBookmarks u = performCall "getUserBookmarks" eff_url where eff_url = user_url ++ u getUserTagBookmarks :: String -> Tag -> DM [Post] getUserTagBookmarks u tg = performCall "getUserTagBookmarks" eff_url where eff_url = user_url ++ u ++ '/':tg getUserTaggedBookmarks :: String -> [Tag] -> DM [Post] getUserTaggedBookmarks u tgs = performCall "getUserTaggedBookmarks" eff_url where eff_url = user_url ++ u ++ '/':intercalate "+" tgs getUserInfo :: String -> DM [Post] getUserInfo u = performCall "getUserInfo" eff_url where eff_url = user_url ++ "userinfo/" ++ u getUserPublicTags :: String -> DM [Post] getUserPublicTags u = performCall "getUserPublicTags" eff_url where eff_url = tags_url ++ u getUserSubscriptions :: String -> DM [Post] getUserSubscriptions u = performCall "getUserSubscriptions" eff_url where eff_url = user_url ++ "subscriptions/" ++ u getUserInboxBookmarks :: String -> String -> DM [Post] getUserInboxBookmarks u key = performCall "getUserInboxBookmarks" eff_url where eff_url = inbox_url ++ u ++ "?private="++key getNetworkMemberBookmarks :: String -> DM [Post] getNetworkMemberBookmarks u = performCall "getNetworkMemberBookmarks" eff_url where eff_url = network_url ++ u getNetworkMemberTaggedBookmarks :: String -> [Tag] -> DM [Post] getNetworkMemberTaggedBookmarks u tgs = performCall "getNetworkMemberTaggedBookmarks" eff_url where eff_url = network_url ++ u ++ '/':intercalate "+" tgs getNetworkMembers :: String -> DM [Post] getNetworkMembers u = performCall "getNetworkMembers" eff_url where eff_url = network_mem_url ++ u getNetworkFans :: String -> DM [Post] getNetworkFans u = performCall "getNetworkFans" eff_url where eff_url = network_fans_url ++ u getURLBookmarks :: URLString -> DM [Post] getURLBookmarks url = performCall "getURLBookmarks" eff_url where eff_url = b_url_url ++ hashUrl url {- Not on offer for RSS backend: getURLSummary :: URLString -> DM [Post] getURLSummary url = do ls <- buildUrl readContentsURL (b_urlinfo_url ++ hashUrl url) case parseFeedString ls of Nothing -> fail ("getURLSummary: invalid RSS feed") Just f -> return (map toPost (feedItems f)) -} toPost :: Item -> Post toPost i = nullPost { postHref = fromMaybe "" (getItemLink i) , postDesc = fromMaybe "" (getItemTitle i) , postUser = fromMaybe "" (getItemAuthor i) , postTags = getItemCategories i , postStamp = fromMaybe "" (getItemPublishDate i) } hashUrl :: URLString -> String hashUrl s = md5sum (pack (map (fromIntegral.fromEnum) s))
GaloisInc/delicious
Network/Delicious/RSS.hs
bsd-3-clause
6,778
0
15
1,319
1,456
795
661
131
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} module Console ( Console , exitSuccess' , getLine' , putStrLn' , runConsole , runConsoleM , runConsolePure , runConsolePureM ) where import Prelude (error) import Control.Applicative (pure) import Control.Monad ((>>=), (>>)) import Data.Either (Either(Left, Right)) import Data.Function (($), (.)) import Data.List (reverse) import Data.Maybe (Maybe(Just, Nothing)) import Data.String (String) import Data.Tuple (snd) import System.Exit (exitSuccess) import System.IO (IO, getLine, putStrLn) import Control.Monad.Freer (Member, send, run, runM, handleRelay, handleRelayS) import Control.Monad.Freer.Internal (Arr, Eff(Val, E), decomp, qApp, tsingleton) ------------------------------------------------------------------------------- -- Effect Model -- ------------------------------------------------------------------------------- data Console s where PutStrLn :: String -> Console () GetLine :: Console String ExitSuccess :: Console () putStrLn' :: Member Console r => String -> Eff r () putStrLn' = send . PutStrLn getLine' :: Member Console r => Eff r String getLine' = send GetLine exitSuccess' :: Member Console r => Eff r () exitSuccess' = send ExitSuccess ------------------------------------------------------------------------------- -- Effectful Interpreter Simple -- ------------------------------------------------------------------------------- runConsole :: Eff '[Console, IO] w -> IO w runConsole req = runM (handleRelay pure go req) where go :: Console v -> Arr '[IO] v w -> Eff '[IO] w go (PutStrLn msg) q = send (putStrLn msg) >>= q go GetLine q = send getLine >>= q go ExitSuccess q = send exitSuccess >>= q ------------------------------------------------------------------------------- -- Pure Interpreter Simple -- ------------------------------------------------------------------------------- runConsolePure :: [String] -> Eff '[Console] w -> [String] runConsolePure inputs req = reverse . snd $ run (handleRelayS (inputs, []) (\s _ -> pure s) go req) where go :: ([String], [String]) -> Console v -> (([String], [String]) -> Arr '[] v ([String], [String])) -> Eff '[] ([String], [String]) go (is, os) (PutStrLn msg) q = q (is, msg : os) () go (i:is, os) GetLine q = q (is, os) i go ([], _) GetLine _ = error "Not enough lines" go (_, os) ExitSuccess _ = pure ([], os) ------------------------------------------------------------------------------- -- Effectful Interpreter for Deeper Stack -- ------------------------------------------------------------------------------- runConsoleM :: Member IO r => Eff (Console ': r) w -> Eff r w runConsoleM (Val x) = pure x runConsoleM (E u q) = case decomp u of Right (PutStrLn msg) -> send (putStrLn msg) >> runConsoleM (qApp q ()) Right GetLine -> send getLine >>= runConsoleM . qApp q Right ExitSuccess -> send exitSuccess Left u' -> E u' (tsingleton (runConsoleM . qApp q)) ------------------------------------------------------------------------------- -- Pure Interpreter for Deeper Stack -- ------------------------------------------------------------------------------- runConsolePureM :: [String] -> Eff (Console ': r) w -> Eff r (Maybe w,([String],[String])) -- ^ (Nothing for ExitSuccess, (unconsumed input, produced output)) runConsolePureM inputs = f (inputs,[]) where f :: ([String],[String]) -> Eff (Console ': r) w -> Eff r (Maybe w,([String],[String])) f st (Val x) = pure (Just x, st) f st@(is,os) (E u q) = case decomp u of Right (PutStrLn msg) -> f (is, msg : os) (qApp q ()) Right GetLine -> case is of x:s -> f (s,os) (qApp q x) [] -> error "Not enough lines" Right ExitSuccess -> pure (Nothing, st) Left u' -> E u' (tsingleton (f st . qApp q))
IxpertaSolutions/freer-effects
examples/src/Console.hs
bsd-3-clause
4,210
0
15
945
1,360
741
619
78
6
-- Warn.hs {-# OPTIONS_GHC -Wall #-} module Warn( warn ) where import System.IO import System.IO.Unsafe warningsEnabled :: Bool warningsEnabled = True warn :: String -> a -> a warn msg x | warningsEnabled = (unsafePerformIO $ hPutStrLn stderr msg) `seq` x | otherwise = x
ghorn/conceptual-design
Warn.hs
bsd-3-clause
298
0
9
71
88
49
39
10
1
module Util where import ClassyPrelude import Data.Aeson.Types newtype TypeTag a b = TypeTag { unTTag :: b } toTag :: b -> TypeTag a b toTag = TypeTag jsonOptions :: Options jsonOptions = defaultOptions { fieldLabelModifier = camelTo '_' . filter (/= '_') } jsonEnumOptions :: Options jsonEnumOptions = jsonOptions { allNullaryToStringTag = True } lcPrefixedEnumOptions :: String -> Options lcPrefixedEnumOptions prefix = jsonEnumOptions { constructorTagModifier = toLower . (stripPrefix prefix >>= flip fromMaybe) } withDropPrefix :: String -> Options -> Options withDropPrefix prefix o = o { fieldLabelModifier = fieldLabelModifier o . (stripPrefix prefix >>= flip fromMaybe) } withDropConstructorPrefix :: String -> Options -> Options withDropConstructorPrefix prefix o = o { constructorTagModifier = constructorTagModifier o . (stripPrefix prefix >>= flip fromMaybe) } mapLeft :: (a -> c) -> Either a b -> Either c b mapLeft f (Left a) = Left $ f a mapLeft _ (Right a) = return a
JustusAdam/bitbucket-github-migrate
src/Util.hs
bsd-3-clause
1,021
0
10
189
313
168
145
19
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} ------------------------------------------------------------------------------- -- | -- Module : Yesod.Comments.Utils -- Copyright : (c) Patrick Brisbin 2010 -- License : as-is -- -- Maintainer : pbrisbin@gmail.com -- Stability : unstable -- Portability : unportable -- ------------------------------------------------------------------------------- module Yesod.Comments.Utils ( commentUserDetails , currentUserDetails , requireUserDetails , defaultUserDetails , isCommentingUser , gravatar ) where import Yesod import Yesod.Auth import Yesod.Comments.Core import Data.Text (Text) import Data.Maybe (fromMaybe) import Network.Gravatar hiding (gravatar) import qualified Network.Gravatar as G -- | Map the commenter's id to user details or return defaults. commentUserDetails :: YesodComments m => Comment -> HandlerT m IO UserDetails commentUserDetails c = return . fromMaybe (defaultUserDetails c) =<< case (cIsAuth c, fromPathPiece (cUserName c)) of (True, Just uid) -> userDetails uid _ -> return Nothing -- | Returns @Nothing@ if user is not authenticated currentUserDetails :: YesodComments m => HandlerT m IO (Maybe UserDetails) currentUserDetails = do muid <- maybeAuthId case muid of Just uid -> userDetails uid _ -> return Nothing -- | Halts with @permissionDenied@ if user is not authenticated requireUserDetails :: YesodComments m => HandlerT m IO (UserDetails) requireUserDetails = do mudetails <- currentUserDetails case mudetails of Just udetails -> return udetails _ -> permissionDenied "you must be logged in" -- | For a comment that was not authenticated or cannot be mapped, the -- default details are the id and email stored directly on the comment. defaultUserDetails :: Comment -> UserDetails defaultUserDetails c = UserDetails (cUserName c) (cUserName c) (cUserEmail c) -- | Given pixel size and email, return the gravatar url gravatar :: Int -> Text -> String gravatar s = G.gravatar defaultConfig { gDefault = Just MM, gSize = Just $ Size s } isCommentingUser :: YesodComments m => Comment -> HandlerT m IO Bool isCommentingUser comment = do mudetails <- currentUserDetails cudetails <- commentUserDetails comment return $ maybe False (== cudetails) mudetails
pbrisbin/yesod-comments
Yesod/Comments/Utils.hs
bsd-3-clause
2,481
0
10
513
482
256
226
44
2
{-# LANGUAGE UndecidableInstances #-} module Data.ByteString.IsoBaseFileFormat.Util.TypeLayout where import Data.Kind import Data.Type.Bool import Data.Type.Equality import GHC.TypeLits ---- type family IsRuleConform (b :: k) (r :: l) :: Bool ---- data TopLevel :: Type -> Type type instance IsRuleConform t (TopLevel rule) = IsRuleConform t rule ---- data OneOf :: [Type] -> Type type instance IsRuleConform t (OneOf '[]) = 'False type instance IsRuleConform t (OneOf (r ': rs)) = IsRuleConform t r || IsRuleConform t (OneOf rs) ---- data MatchSymbol :: Symbol -> Type type instance IsRuleConform b (MatchSymbol fourcc) = ToSymbol b == fourcc type family ToSymbol t :: Symbol ---- data OnceOptionalX t data SomeOptionalX t data SomeMandatoryX t type instance IsRuleConform (bs :: [Type]) (sq :: [Type]) = IsSequence bs sq type family IsSequence (bs :: [k]) (rs :: [j]) :: Bool where IsSequence '[] '[] = 'True IsSequence (b ': bs) '[] = 'False -- IsSequence '[] (OnceOptionalX r ': rs) = IsSequence '[] rs IsSequence (b ': bs) (OnceOptionalX r ': rs) = If (IsRuleConform b r) (IsSequence bs rs) (IsSequence (b ': bs) rs) -- IsSequence '[] (SomeOptionalX r ': rs) = IsSequence '[] rs IsSequence (b ': bs) (SomeOptionalX r ': rs) = If (IsRuleConform b r) (IsSequence bs (SomeOptionalX r ': rs)) (IsSequence (b ': bs) rs ) -- IsSequence '[] (SomeMandatoryX r ': rs) = 'False IsSequence (b ': bs) (SomeMandatoryX r ': rs) = IsRuleConform b r && IsSequence bs (SomeOptionalX r ': rs) -- IsSequence '[] (r ': rs) = 'False IsSequence (b ': bs) (r ': rs) = IsRuleConform b r && IsSequence bs rs
sheyll/isobmff-builder
src/Data/ByteString/IsoBaseFileFormat/Util/TypeLayout.hs
bsd-3-clause
1,807
0
11
485
721
395
326
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.Extras.Internal.Queue.SeqQ -- Copyright : (c) Tim Watson 2012 - 2013 -- License : BSD3 (see the file LICENSE) -- -- Maintainer : Tim Watson <watson.timothy@gmail.com> -- Stability : experimental -- -- A simple FIFO queue implementation backed by @Data.Sequence@. ----------------------------------------------------------------------------- module Control.Distributed.Process.Extras.Internal.Queue.SeqQ ( SeqQ , empty , isEmpty , singleton , enqueue , dequeue , peek ) where import Data.Sequence ( Seq , ViewR(..) , (<|) , viewr ) import qualified Data.Sequence as Seq (empty, singleton, null) newtype SeqQ a = SeqQ { q :: Seq a } deriving (Show) instance Eq a => Eq (SeqQ a) where a == b = (q a) == (q b) {-# INLINE empty #-} empty :: SeqQ a empty = SeqQ Seq.empty isEmpty :: SeqQ a -> Bool isEmpty = Seq.null . q {-# INLINE singleton #-} singleton :: a -> SeqQ a singleton = SeqQ . Seq.singleton {-# INLINE enqueue #-} enqueue :: SeqQ a -> a -> SeqQ a enqueue s a = SeqQ $ a <| q s {-# INLINE dequeue #-} dequeue :: SeqQ a -> Maybe (a, SeqQ a) dequeue s = maybe Nothing (\(s' :> a) -> Just (a, SeqQ s')) $ getR s {-# INLINE peek #-} peek :: SeqQ a -> Maybe a peek s = maybe Nothing (\(_ :> a) -> Just a) $ getR s getR :: SeqQ a -> Maybe (ViewR a) getR s = case (viewr (q s)) of EmptyR -> Nothing a -> Just a
qnikst/distributed-process-extras
src/Control/Distributed/Process/Extras/Internal/Queue/SeqQ.hs
bsd-3-clause
1,511
0
11
329
454
251
203
40
2
{-# LANGUAGE NoMonomorphismRestriction, DeriveDataTypeable #-} {-# OPTIONS -Wall #-} module Data.Numbering ( Numbering(..), -- * Construction enumNu, enumNu', nuFromSet, nuFromDistinctVector, nuFromDistinctVectorG, finiteTypeNu, idNu, emptyNu, -- ** From a list nuFromDistinctList, nuFromDistinctUnboxList, nuFromDistinctIntList, nuFromList, nuFromUnboxList, nuFromIntList, -- * Transformation mapNu, reindexNu, consolidateNu, consolidateUnboxNu, nuTake, -- ** Particular reindexings reverseNu, nuDrop, -- * Combination sumNu, eitherNu, prodNu, pairNu, -- * Destruction nuIndices, nuElements, nuToList, nuToDistinctList, nuToVector, nuToDistinctVector, NumberingBrokenInvariantException(..), checkNu, ) where import Control.Exception import Control.Monad import Data.Map(Map) import Data.Maybe import Data.Monoid(mempty) import Data.Typeable(Typeable) import Data.Vector.Unboxed(Unbox) import qualified Data.IntMap as IM import qualified Data.IntSet as IS import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import qualified Data.Vector.Unboxed as VU import Debug.Trace import Data.Function -- | Invariant: -- -- @ -- For all i in 0 .. 'nuLength' - 1, -- 'toInt' ('fromInt' i) == i -- @ -- -- This implies that -- -- @ -- For all a of the form 'fromInt' i (with i in 0 .. 'nuLength' - 1), -- 'fromInt' ('toInt' a) = a -- @ -- -- The behaviour of @fromInt@ for out-of-bounds indices and that of @toInt@ for elements not occuring in the numbering is undefined. -- -- Thus, assuming the invariant holds, @toInt@ is uniquely determined by @fromInt@ (on valid inputs). data Numbering a = UnsafeMkNumbering { toInt :: a -> Int, fromInt :: Int -> a, nuLength :: Int } -- ^ \"Unsafe\" because the invariant isn't checked. instance Show a => Show (Numbering a) where showsPrec prec nu = showParen (prec > 10) (showString "nuFromDistinctList " . showsPrec 11 (nuElements nu)) -- | Assumes that the invariant holds. instance Eq a => Eq (Numbering a) where nu1 == nu2 = ((==) `on` nuLength) nu1 nu2 && all (\i -> fromInt nu1 i == fromInt nu2 i) (nuIndices nu1) -- | @enumNu a b@ creates a numbering of the elements @[a .. b]@ (inclusively). enumNu :: (Enum a) => a -> a -> Numbering a enumNu min_ max_ = enumNu' (fromEnum min_) (fromEnum max_) -- | @enumNu' i j@ creates a numbering of the elements @[toEnum i .. toEnum j]@ (inclusively). enumNu' :: Enum a => Int -> Int -> Numbering a enumNu' mini maxi = UnsafeMkNumbering { toInt = subtract mini . fromEnum , fromInt = toEnum . (+) mini , nuLength = maxi-mini+1 } -- | Creates a numbering for an 'Either'-like type, given numberings for the summand types. sumNu :: (a1 -> a) -- ^ 'Left' equivalent -> (a2 -> a) -- ^ 'Right' equivalent -> ((a1 -> Int) -> (a2 -> Int) -> a -> Int) -- ^ 'either' equivalent -> Numbering a1 -> Numbering a2 -> Numbering a sumNu left_ right_ either_ nu1 nu2 = let n1 = nuLength nu1 in UnsafeMkNumbering (either_ (toInt nu1) ((+ n1) . toInt nu2)) (\i -> case i-n1 of i' | i' < 0 -> left_ (fromInt nu1 i) | otherwise -> right_ (fromInt nu2 i')) (n1+nuLength nu2) eitherNu :: Numbering a -> Numbering b -> Numbering (Either a b) eitherNu = sumNu Left Right either -- | Creates a numbering for an pair-like type, given numberings for the component types. prodNu :: (a -> a2) -- ^ 'fst' equivalent -> (a -> a1) -- ^ 'snd' equivalent -> (a2 -> a1 -> a) -- ^ @(,)@ equivalent -> Numbering a2 -> Numbering a1 -> Numbering a prodNu fst_ snd_ prod nu1 nu2 = let n2 = nuLength nu2 in UnsafeMkNumbering (\a -> toInt nu1 (fst_ a) * n2 + toInt nu2 (snd_ a)) (\i -> case divMod i n2 of (i1,i2) -> prod (fromInt nu1 i1) (fromInt nu2 i2) ) (n2*nuLength nu1) pairNu :: Numbering a -> Numbering b -> Numbering (a, b) pairNu = prodNu fst snd (,) nuIndices :: Numbering a -> [Int] nuIndices nu = [0.. nuLength nu-1] nuElements :: Numbering a -> [a] nuElements nu = fmap (fromInt nu) (nuIndices nu) -- | = 'nuElements'. nuToList :: Numbering a -> [a] nuToList = nuElements -- | = 'nuElements'. Won't actually be distinct if the invariant is broken. nuToDistinctList :: Numbering a -> [a] nuToDistinctList = nuElements nuToVector :: VG.Vector v a => Numbering a -> v a nuToVector nu = VG.generate (nuLength nu) (fromInt nu) -- | = 'nuToVector'. Won't actually be distinct if the invariant is broken. nuToDistinctVector :: VG.Vector v a => Numbering a -> v a nuToDistinctVector nu = VG.generate (nuLength nu) (fromInt nu) data NumberingBrokenInvariantException a = NumberingBrokenInvariantException { nbie_index :: Int, nbie_fromIntOfIndex :: a, nbie_toIntOfFromIntOfIndex :: Int } deriving (Show,Typeable) instance (Show a, Typeable a) => Exception (NumberingBrokenInvariantException a) checkNu :: Numbering a -> Either (NumberingBrokenInvariantException a) () checkNu nu = mapM_ (\i -> let a_i = fromInt nu i i_a_i = toInt nu a_i in unless (i == i_a_i) (Left (NumberingBrokenInvariantException i a_i i_a_i))) (nuIndices nu) -- | (Uses a 'Map' because "Data.Set" doesn't expose the necessary index-based API) nuFromSet :: Map Int ignored -> Numbering Int nuFromSet m = UnsafeMkNumbering (\i -> fst (M.elemAt i m)) (\a -> fromMaybe (error ("nuFromSet: Element not in Numbering: "++show a)) (M.lookupIndex a m)) (M.size m) -- | The distinctness precondition is checked (we have to create a map anyway). nuFromDistinctVector :: (Ord a, Show a, VG.Vector v a) => v a -> Numbering a nuFromDistinctVector = nuFromDistinctVectorG mempty M.insertWithKey M.lookup -- | Allows customization of the map type used. nuFromDistinctVectorG :: (Show a, VG.Vector v a) => map -- ^ 'M.empty' equivalent -> ((a -> Int -> Int -> t) -> a -> Int -> map -> map) -- ^ 'M.insertWithKey' equivalent -> (a -> map -> Maybe Int) -- ^ 'M.lookup' equivalent -> v a -> Numbering a nuFromDistinctVectorG _empty _insertWithKey _lookup v = let m = VG.ifoldl' (\r i a -> _insertWithKey _err a i r) _empty v _err a i1 i2 = error ("nuFromDistinctVector: duplicate: " ++ show a++ " at indices "++show (i1,i2)) in UnsafeMkNumbering (\a -> fromMaybe (error ("nuFromDistinctVector: Element not in Numbering: "++show a)) (_lookup a m)) (v VG.!) (VG.length v) -- | See 'nuFromDistinctVector'. nuFromDistinctList :: (Ord a, Show a) => [a] -> Numbering a nuFromDistinctList = nuFromDistinctVector . V.fromList -- | See 'nuFromDistinctVector'. nuFromDistinctUnboxList :: (Ord a, Show a, Unbox a) => [a] -> Numbering a nuFromDistinctUnboxList = nuFromDistinctVector . VU.fromList nuFromDistinctIntList :: [Int] -> Numbering Int nuFromDistinctIntList = nuFromDistinctVectorG mempty IM.insertWithKey IM.lookup . VU.fromList -- | Uniquifies the input first (resulting in an unspecified order). nuFromList :: (Ord a, Show a) => [a] -> Numbering a nuFromList = nuFromDistinctList . S.toList . S.fromList -- | Uniquifies the input first (resulting in an unspecified order). nuFromUnboxList :: (Ord a, Show a, Unbox a) => [a] -> Numbering a nuFromUnboxList = nuFromDistinctUnboxList . S.toList . S.fromList -- | Uniquifies the input first (resulting in an unspecified order). nuFromIntList :: [Int] -> Numbering Int nuFromIntList = nuFromDistinctIntList . IS.toList . IS.fromList -- | Numbering of all elements of a finite type. finiteTypeNu :: (Enum a, Bounded a) => Numbering a finiteTypeNu = enumNu minBound maxBound -- | Identity numbering idNu :: Int -- ^ The 'nuLength' -> Numbering Int idNu = UnsafeMkNumbering id id emptyNu :: Numbering a emptyNu = UnsafeMkNumbering { nuLength = 0, toInt = \_ -> error "emptyNu/toInt", fromInt = \i -> error ("emptyNu/fromInt "++show i) } -- | In @mapNu f g nu@, the arguments must satisfy -- -- @ -- For all i in 0 .. 'nuLength' nu - 1, -- (g . f) a == a -- where -- a = 'fromInt' nu i -- @ mapNu :: (a -> b) -> (b -> a) -> Numbering a -> Numbering b mapNu toNew toOld nu = UnsafeMkNumbering { toInt = toInt nu . toOld, fromInt = toNew . fromInt nu, nuLength = nuLength nu } -- | In @reindexNu k f g nu@, the arguments must satisfy -- -- @ -- For all i in 0 .. k, -- (g . f) i == i -- @ -- -- Note: Decreasing the length with this function will /not/ release any memory retained -- by the closures in the input numbering (e.g. the vector, for numberings created by 'nuFromDistinctVector'). Use 'consolidateNu' afterwards for that. reindexNu :: Int -- ^ New 'nuLength' -> (Int -> Int) -- ^ Old index to new index -> (Int -> Int) -- ^ New index to old index -> Numbering a -> Numbering a reindexNu newLength toNewIndex toOldIndex nu = (if newLength > oldLength then trace ("reindexNu: Warning: newLength > oldLength "++show (newLength,oldLength)++ ". This implies that the new-to-old-index function is non-injective, or "++ "relies on the behaviour of the input numbering outside of its bounds.") else id) UnsafeMkNumbering { toInt = toNewIndex . toInt nu, fromInt = fromInt nu . toOldIndex, nuLength = newLength } where oldLength = nuLength nu reverseNu :: Numbering a -> Numbering a reverseNu nu = reindexNu n (pred n -) (pred n -) nu where n = nuLength nu -- Identity for arg at least equal to the input length. -- -- See the note in 'consolidateNu' about memory usage. nuTake :: Int -> Numbering a -> Numbering a nuTake k nu | k >= nuLength nu = nu | k <= 0 = emptyNu | otherwise = nu { nuLength = k } idBoxedVector :: V.Vector a -> V.Vector a idBoxedVector = id idUnboxedVector :: VU.Vector a -> VU.Vector a idUnboxedVector = id -- | Semantic 'id' (for in-bounds inputs), but backs the numbering with a new vector and map having just the required length (example: @consolidateNu ('nuTake' 1 ('nuFromDistinctVector' largeVector))@). consolidateNu :: (Ord a, Show a) => Numbering a -> Numbering a consolidateNu = nuFromDistinctVector . idBoxedVector . nuToDistinctVector -- | Like 'consolidateNu', but uses unboxed vectors. consolidateUnboxNu :: (Ord a, Show a, Unbox a) => Numbering a -> Numbering a consolidateUnboxNu = nuFromDistinctVector . idUnboxedVector . nuToDistinctVector -- | Identity for nonpositive arg. nuDrop :: Int -> Numbering a -> Numbering a nuDrop k nu | k <= 0 = nu | k >= n = emptyNu | otherwise = reindexNu (n - k) (subtract k) (+ k) nu where n = nuLength nu
DanielSchuessler/numbering
Data/Numbering.hs
bsd-3-clause
11,333
0
16
2,916
2,896
1,555
1,341
226
2
{-# LANGUAGE PatternGuards, ParallelListComp, TemplateHaskell, CPP #-} module ApiCompat.ShowInfo where import Control.Applicative ( (<$>) ) import Data.Char ( isAlphaNum ) import Data.Function ( on ) import Data.Generics ( Data, Typeable, listify, everywhere ) import Data.Generics.Aliases ( extT ) import Data.Maybe ( fromJust, listToMaybe ) import Data.Ord ( comparing ) import Data.List ( sort, sortBy, groupBy, intersperse ) import qualified Data.Map as M import Language.Haskell.TH import Language.Haskell.TH.Lift ( lift ) import Language.Haskell.TH.Instances ( ) import Language.Haskell.TH.PprLib import Language.Haskell.TH.Syntax (Name(..), NameFlavour(..)) --TODO: remove contexts from methods --TODO: list instances next to classes / datatypes showInfos :: [(String, [Name])] -> ExpQ showInfos ms = lift . unlines . concat =<< mapM show_info ms where show_info (m, ns) = do infos <- mapM safe_reify ns return $ [ "----------------------------------------" , "module " ++ m ] ++ map (either id (("\n"++) . show . infoDoc)) (sortBy comp infos) ++ [""] safe_reify n = recover (return . Left $ "-- Couldn't reify " ++ pprint n) (Right <$> reify n) comp (Left _) _ = LT comp (Right _) (Left _) = GT comp (Right l) (Right r) = comparing infoName l r infoDoc :: Info -> Doc infoDoc info = case info of (ClassI d _) -> dec False $ deUnique d --(ClassOpI) -> (TyConI d) -> dec False $ deUnique d (FamilyI d _) -> dec False $ deUnique d --(PrimTyConI n i b) -> --(DataConI ) -> (VarI n t _ f) -> vcat [fixity f n, dec False . SigD n $ deUnique t] --(TyVarI n t) -> _ -> empty where tyvars = hcat . punctuate space . map ppr commaize = hcat . punctuate (text ", ") vnest l = (l $+$) . nest 2 . vcat name n | all (not . isAlphaNum) $ nameBase n = parens $ ppr n | otherwise = ppr n prd (ClassP n ts) = hcat $ punctuate space (name n : map flat_typ ts) prd (EqualP l r) = flat_typ l <+> text "~" <+> flat_typ r prds [] = text "()" prds xs = parens . nest 1 . foldl1 ($$) $ [nl] ++ (intersperse (text ",") . map prd $ sort xs) ++ [nl] where nl = text "" context = (<+> text "=>") . prds derivings = parens . commaize . map ppr . sort forall tvs ctx = hcat [ text "forall ", tyvars tvs, text ". " ] $+$ context ctx flat_typ (ForallT v c t) = parens $ hcat [forall v c, flat_typ t] flat_typ (SigT t k) = parens $ hcat [flat_typ t, text "::", ppr k] flat_typ (VarT n) = name n flat_typ (ConT n) = name n flat_typ ArrowT = text "(->)" flat_typ ListT = text "[]" flat_typ (AppT ListT r) = brackets $ flat_typ r flat_typ t@(AppT (AppT ArrowT _) _) = parens . hcat $ punctuate (text " -> ") $ map flat_typ ts -- = hcat [flat_typ l, text " ->", flat_typ r] where ts = tyUnArrow t flat_typ (AppT ArrowT l) = parens $ hcat [flat_typ l, text " ->"] flat_typ t = case f of (TupleT i) -> parens (tup_txt i) (UnboxedTupleT i) -> parens $ hcat [text "# ", tup_txt i, text " #"] _ -> hcat $ punctuate space (flat_typ f : flats) where (f:rs) = tyUnApp t flats = map flat_typ rs tup_txt i = commaize flats <> text (replicate (i - length flats) ',') typ (ForallT tvs ctx t) = hcat [text "forall ", tyvars tvs, text "."] $+$ nest 2 (context ctx $+$ typ t) typ t = vb_infix flat_typ "->" $ tyUnArrow t vb_infix f s xs = vcat $ map ((<+> text s) . f) (init xs) ++ [f $ last xs] vf_infix _ _ [] = empty vf_infix f s (x:xs) = vcat $ text (replicate (length s) ' ') <+> f x : map ((text s <+>) . f) xs dec _ (ClassD ctx n tvs fds decs) = vnest (text "class" <+> context ctx) [ vnest (hcat [name n, space, tyvars tvs, pp_fds, text " where"]) (map (dec True) decs) ] where pp_fds | [] <- fds = empty | otherwise = text "|" <+> commaize (map ppr fds) dec _ (SigD n t ) = name n <+> text "::" $$ nest 2 (typ t) dec _ (DataD ctx n tvs cs ds) = datalike "data " ctx n tvs cs ds dec _ (NewtypeD ctx n tvs cs ds) = datalike "newtype " ctx n tvs [cs] ds dec _ (TySynD n tvs t ) = text "type" <+> name n <+> tyvars tvs <+> text "=" <+> flat_typ t dec inClass (FamilyD flavour n tvs k) = text header <+> name n <+> tyvars tvs $$ kind where header = (if inClass then id else (++" family")) $ case flavour of TypeFam -> "type" DataFam -> "data" kind = maybe empty (nest 2 . (text "::" <+>) . ppr) k dec _ x = text $ "-- can't pretty-print:\n" ++ show x strict s = text $ case s of NotStrict -> "" IsStrict -> "!" Unpacked -> "{-# UNPACK #-} !" field (NotStrict, t) = flat_typ t field (s, t) = strict s <+> parens (flat_typ t) rec_field (n, s, t) = name n <+> text "::" <+> field (s, t) con (NormalC n fs) = vnest (name n) $ map field fs con (RecC n fs) = vnest (name n) $ map rec_field fs con (InfixC l n r) = vnest (name n) $ map field [l, r] con (ForallC tvs ctx c) = vnest (forall tvs ctx) [con c] datalike d ctx n tvs cs ds = vnest (hcat [text d, context ctx]) [ hcat [name n, space, tyvars tvs, enull $ text " ="] , enull $ vf_infix con "|" cs , text "deriving" <+> derivings ds ] where enull x = if null cs then empty else x fixity (Fixity l d) n = text $ concat [ "infix", dir, " ", show l, " ", show $ name n ] where dir = case d of InfixL -> "l" InfixR -> "r" InfixN -> "" -- Utils tyRemoveForall :: Type -> Type tyRemoveForall (ForallT _ _ t) = t tyRemoveForall t = t tyUnApp :: Type -> [Type] tyUnApp = reverse . helper where helper (AppT l r) = r : helper l helper x = [x] tyUnArrow :: Type -> [Type] tyUnArrow = helper where helper (AppT (AppT ArrowT l) r) = l : helper r helper x = [x] everywhereMaybe :: (Typeable a, Data b) => (a -> Maybe a) -> b -> b everywhereMaybe f = everywhere (id `extT` replace) where replace x | Just x' <- f x = x' | otherwise = x deUnique :: Data a => a -> a deUnique d = everywhereMaybe (`M.lookup` rewrites) d where rewrites = M.fromList . concatMap (process . map deUniqueName) . groupBy ((==) `on` nameBase) $ allNames d process [n] = [n] process ns = [ (n, mkName $ nameBase n' ++ replicate p '\'') | (n, n') <- ns | p <- [0..] ] deUniqueName n@(Name o (NameU _)) = (n, Name o NameS) deUniqueName n = (n, n) allNames :: Data a => a -> [Name] allNames = map head . groupBy (==) . sort . listify (const True :: Name -> Bool) decName :: Dec -> Maybe Name decName (FunD n _ ) = Just n decName (TySynD n _ _ ) = Just n decName (FamilyD _ n _ _ ) = Just n decName (NewtypeD _ n _ _ _ ) = Just n decName (DataD _ n _ _ _ ) = Just n decName (ClassD _ n _ _ _ ) = Just n decName (InstanceD _ t _ ) | ((ConT n):_) <- tyUnApp t = Just n | otherwise = Nothing decName (DataInstD _ n _ _ _ ) = Just n decName (NewtypeInstD _ n _ _ _ ) = Just n decName (ValD p _ _ ) = listToMaybe $ patNames p decName (SigD n _ ) = Just n decName (TySynInstD n _ _ ) = Just n decName (ForeignD (ImportF _ _ _ n _)) = Just n decName (ForeignD (ExportF _ _ n _)) = Just n #if __GLASGOW_HASKELL__ < 706 decName (PragmaD (InlineP n _ )) = Just n decName (PragmaD (SpecialiseP n _ _)) = Just n #else decName (PragmaD (InlineP n _ _ _)) = Just n decName (PragmaD (SpecialiseP n _ _ _)) = Just n #endif decName _ = Nothing patNames :: Pat -> [Name] patNames (VarP n ) = [n] patNames (TupP p ) = concatMap patNames p patNames (UnboxedTupP p ) = concatMap patNames p patNames (InfixP l _ r ) = patNames l ++ patNames r patNames (UInfixP l _ r ) = patNames l ++ patNames r patNames (ParensP p ) = patNames p patNames (BangP p ) = patNames p patNames (TildeP p ) = patNames p patNames (AsP n p ) = n : patNames p patNames (RecP _ f ) = concatMap (patNames . snd) f patNames (ListP p ) = concatMap patNames p patNames (SigP p _ ) = patNames p patNames (ViewP _ p ) = patNames p patNames _ = [] infoName :: Info -> Name infoName (ClassI d _ ) = fromJust $ decName d infoName (ClassOpI n _ _ _) = n infoName (TyConI d ) = fromJust $ decName d infoName (FamilyI d _ ) = fromJust $ decName d infoName (PrimTyConI n _ _ ) = n infoName (DataConI n _ _ _) = n infoName (VarI n _ _ _) = n infoName (TyVarI n _ ) = n
mgsloan/api-compat
src/ApiCompat/ShowInfo.hs
bsd-3-clause
9,184
1
17
3,040
3,905
1,962
1,943
194
37
module System.Spinner ( withSpin , withSpin' , Spinner(..) ) where import Control.Monad (when) import Control.Concurrent (forkIO, threadDelay) import Data.IORef (newIORef, readIORef, writeIORef) import Data.Function (fix) import System.IO (hPutStr, hFlush, stderr) data Spinner = Plain | Shobon | Custom [String] spinnerStrings :: Spinner -> [String] spinnerStrings Plain = ["/", "-", "\\", "|"] spinnerStrings Shobon = [ "(´・ω・`)" , "( ´・ω・)" , "( ´・ω)" , "( ´・)" , "( ´)" , "(` )" , "(・` )" , "(ω・` )" , "(・ω・` )" ] spinnerStrings (Custom x) = x withSpin :: Int -> Spinner -> IO a -> IO a withSpin duration stype f = do let spinner = spinnerStrings stype endRef <- newIORef False forkIO . ($ cycle spinner) . fix $ \loop (str:xs) -> do hPutStr stderr ("\ESC[s\ESC[1K" ++ str ++ "\ESC[0K\ESC[u") hFlush stderr threadDelay duration end <- readIORef endRef when (not end) (loop xs) a <- f writeIORef endRef True return a withSpin' :: IO a -> IO a withSpin' = withSpin 100000 Plain -- main = withSpin' $ do -- threadDelay 2000000 -- putStrLn "◝(*´꒳`*)◜"
lotz84/spinner
src/System/Spinner.hs
bsd-3-clause
1,457
0
14
544
388
207
181
37
1
{-# LANGUAGE PatternGuards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS -fno-warn-name-shadowing #-} {-# OPTIONS -fno-warn-orphans #-} -- ModName (ModuleName l) module Language.Haskell.Names.Imports (processImports) where import Fay.Compiler.ModuleT import qualified Language.Haskell.Names.GlobalSymbolTable as Global import Language.Haskell.Names.ScopeUtils import Language.Haskell.Names.SyntaxUtils import Language.Haskell.Names.Types import Control.Applicative import Control.Arrow import Control.Monad.Writer import Data.Either import Data.Foldable (fold, foldMap) import Data.Lens.Light import qualified Data.Map as Map import Data.Maybe import qualified Data.Set as Set import Language.Haskell.Exts.Annotated instance ModName (ModuleName l) where modToString (ModuleName _ s) = s preludeName :: String preludeName = "Prelude" processImports :: (MonadModule m, ModuleInfo m ~ Symbols) => ExtensionSet -> [ImportDecl l] -> m ([ImportDecl (Scoped l)], Global.Table) processImports exts importDecls = do (annotated, tbl) <- runWriterT $ mapM (WriterT . processImport) importDecls let isPreludeImported = not . null $ [ () | ImportDecl { importModule = ModuleName _ modName } <- importDecls , modName == preludeName ] importPrelude = ImplicitPrelude `Set.member` exts && not isPreludeImported tbl' <- if not importPrelude then return tbl else do -- FIXME currently we don't have a way to signal an error when -- Prelude cannot be found syms <- fold `liftM` getModuleInfo preludeName return $ tbl <> computeSymbolTable False -- not qualified (ModuleName () preludeName) syms return (annotated, tbl') processImport :: (MonadModule m, ModuleInfo m ~ Symbols) => ImportDecl l -> m (ImportDecl (Scoped l), Global.Table) processImport imp = do mbi <- getModuleInfo (importModule imp) case mbi of Nothing -> let e = EModNotFound (importModule imp) in return (scopeError e imp, Global.empty) Just syms -> return $ resolveImportDecl syms imp resolveImportDecl :: Symbols -> ImportDecl l -> (ImportDecl (Scoped l), Global.Table) resolveImportDecl syms (ImportDecl l mod qual src impSafe pkg mbAs mbSpecList) = let (mbSpecList', impSyms) = (fmap fst &&& maybe syms snd) $ resolveImportSpecList mod syms <$> mbSpecList tbl = computeSymbolTable qual (fromMaybe mod mbAs) impSyms info = case mbSpecList' of Just sl | Scoped (ScopeError e) _ <- ann sl -> ScopeError e _ -> Import tbl in (ImportDecl (Scoped info l) (Scoped (ImportPart syms) <$> mod) qual src impSafe pkg (fmap noScope mbAs) mbSpecList' , tbl) resolveImportSpecList :: ModuleName l -> Symbols -> ImportSpecList l -> (ImportSpecList (Scoped l), Symbols) resolveImportSpecList mod allSyms (ImportSpecList l isHiding specs) = let specs' = map (resolveImportSpec mod isHiding allSyms) specs mentionedSyms = mconcat $ rights $ map ann2syms specs' importedSyms = computeImportedSymbols isHiding allSyms mentionedSyms newAnn = Scoped (ImportPart importedSyms) l in (ImportSpecList newAnn isHiding specs', importedSyms) -- | This function takes care of the possible 'hiding' clause computeImportedSymbols :: Bool -> Symbols -- ^ all symbols -> Symbols -- ^ mentioned symbols -> Symbols -- ^ imported symbols computeImportedSymbols isHiding (Symbols vs ts) mentionedSyms = case isHiding of False -> mentionedSyms True -> let Symbols hvs hts = mentionedSyms allTys = symbolMap st_origName ts hidTys = symbolMap st_origName hts allVls = symbolMap sv_origName vs hidVls = symbolMap sv_origName hvs in Symbols (Set.fromList $ Map.elems $ allVls Map.\\ hidVls) (Set.fromList $ Map.elems $ allTys Map.\\ hidTys) symbolMap :: Ord s => (a -> s) -> Set.Set a -> Map.Map s a symbolMap f is = Map.fromList [(f i, i) | i <- Set.toList is] resolveImportSpec :: ModuleName l -> Bool -> Symbols -> ImportSpec l -> ImportSpec (Scoped l) -- NB: this can be made more efficient resolveImportSpec mod isHiding syms spec = case spec of IVar _ (NoNamespace {}) n -> let matches = mconcat $ -- Strictly speaking, the isConstructor check is unnecessary -- because constructors are lexically different from anything -- else. [ mkVal info | info <- vs , not (isConstructor info) , sv_origName info ~~ n] in checkUnique (ENotExported Nothing n mod) matches spec -- FIXME think about data families etc. IVar _ (TypeNamespace {}) _ -> error "'type' namespace is not supported yet" -- FIXME IAbs _ n | isHiding -> -- This is a bit special. 'C' may match both types/classes and -- data constructors. -- FIXME Still check for uniqueness? let Symbols vlMatches tyMatches = mconcat [ mkVal info | info <- vs, sv_origName info ~~ n] <> mconcat [ mkTy info | info <- ts, st_origName info ~~ n] in if Set.null tyMatches && Set.null vlMatches then scopeError (ENotExported Nothing n mod) spec else Scoped (ImportPart (Symbols vlMatches tyMatches)) <$> spec | otherwise -> let matches = mconcat [mkTy info | info <- ts, st_origName info ~~ n] in checkUnique (ENotExported Nothing n mod) matches spec -- FIXME -- What about things like: -- head(..) -- String(..) -- ? IThingAll l n -> let matches = [ info | info <- ts, st_origName info ~~ n] subs = mconcat [ mkVal info | n <- matches , info <- vs , Just n' <- return $ sv_parent info , n' == st_origName n ] n' = checkUnique (ENotExported Nothing n mod) (foldMap mkTy matches) n in case ann n' of e@(Scoped ScopeError{} _) -> IThingAll e n' _ -> IThingAll (Scoped (ImportPart (subs <> foldMap mkTy matches)) l ) n' IThingWith l n cns -> let matches = [info | info <- ts, st_origName info ~~ n] n' = checkUnique (ENotExported Nothing n mod) (foldMap mkTy matches) n typeName = st_origName $ head matches -- should be safe (cns', cnSyms) = resolveCNames syms typeName (\cn -> ENotExported (Just n) (unCName cn) mod) cns in IThingWith (Scoped (ImportPart (cnSyms <> foldMap mkTy matches)) l ) n' cns' where (~~) :: OrigName -> Name l -> Bool OrigName { origGName = GName { gName = n } } ~~ n' = n == nameToString n' isConstructor :: SymValueInfo n -> Bool isConstructor SymConstructor {} = True isConstructor _ = False vs = Set.toList $ syms^.valSyms ts = Set.toList $ syms^.tySyms ann2syms :: Annotated a => a (Scoped l) -> Either (Error l) (Symbols) ann2syms a = case ann a of Scoped (ScopeError e) _ -> Left e Scoped (ImportPart syms) _ -> Right syms _ -> Left $ EInternal "ann2syms" checkUnique :: Functor f => Error l -> Symbols -> f l -> f (Scoped l) checkUnique notFound syms@(Symbols vs ts) f = case Set.size vs + Set.size ts of 0 -> scopeError notFound f 1 -> Scoped (ImportPart syms) <$> f -- there should be no clashes, and it should be checked elsewhere _ -> scopeError (EInternal "ambiguous import") f
beni55/fay
src/haskell-names/Language/Haskell/Names/Imports.hs
bsd-3-clause
8,276
0
20
2,745
2,306
1,162
1,144
225
8
----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.SHFSTM.Internal -- Copyright : (c) D. Sabel, Goethe-University, Frankfurt a.M., Germany -- License : BSD-style -- -- Maintainer : sabel <at> ki.cs.uni-frankfurt -- Stability : experimental -- Portability : non-portable (needs GHC and extensions) -- -- -- This module implements transaction execution ----------------------------------------------------------------------------- {-# OPTIONS_GHC -XDeriveDataTypeable -XExistentialQuantification #-} module Control.Concurrent.SHFSTM.Internal ( TLOG(), emptyTLOG, RetryException(..), globalRetry, commit, newTVarWithLog, readTVarWithLog, writeTVarWithLog, orElseWithLog, orRetryWithLog ) where import Prelude hiding(catch) import Control.Exception import Control.Concurrent import Control.Concurrent.SHFSTM.Internal.TVar import Control.Concurrent.SHFSTM.Internal.TransactionLog import qualified Data.Map as Map import qualified Data.Set as Set import Data.List import Data.IORef import Data.Maybe import Data.Typeable #ifdef DEBUG import Control.Concurrent.SHFSTM.Internal.Debug(sPutStrLn) #endif -- | The 'RetryException' is thrown from the committing transaction -- to conflicting transactions data RetryException = RetryException deriving (Typeable,Show) instance Exception RetryException -- | 'newTVarWithLog' creates a new TVar newTVarWithLog :: TLOG -- ^ the transaction log -> a -- ^ the content of the TVar -> IO (TVar a) newTVarWithLog (TLOG tlog) content = uninterruptibleMask_ $ do mid <- myThreadId tvar_Id <- nextCounter lg <- readIORef tlog -- access the Transaction-Log let ((la,ln,lw):xs) = tripelStack lg -- access the La,Ln,Lw lists -- Create the TVar ... content_global <- newMVar content -- set global content pointer_local_content <- newIORef [content] let mp = (Map.insert mid pointer_local_content Map.empty) content_local <- seq mp (newMVar mp) notify_list <- newMVar (Set.empty) unset_lock <- newEmptyMVar -- loc <- newIORef (Just mid) content_waiting_queue <- newMVar [] -- empty broadcast list content_tvarx <- newMVar (TV {globalContent = content_global, localContent = content_local, notifyList = notify_list, lock = unset_lock, waitingQueue = content_waiting_queue -- local = loc }) let tvany = TVarAny (tvar_Id,content_tvarx) let tva = TVarA content_tvarx let tvar = TVar (tva,tvany) -- ------------- #ifdef DEBUG if (Set.member tvany ln) then error "PANIC" else do sPutStrLn (show mid ++ " creates local TVar *********" ++ show tvany) #endif writeIORef tlog (lg{tripelStack=((Set.insert tvany la,Set.insert tvany ln,lw):xs)}) -- adjust the Transaction Log return tvar -- | 'readTVarWithLog' performs the readTVar-operation readTVarWithLog :: TLOG -- ^ the transaction log -> TVar a -- ^ the 'TVar' -> IO a -- ^ the content of the 'TVar' (local) readTVarWithLog (TLOG tlog) (ptvar@(TVar (_,tvany))) = do res <- tryReadTVarWithLog (TLOG tlog) ptvar case res of Right r -> return r Left blockvar -> do mid <- myThreadId #ifdef DEBUG sPutStrLn (show mid ++ "wait in read on TVar" ++ show tvany) #endif takeMVar blockvar readTVarWithLog (TLOG tlog) ptvar tryReadTVarWithLog (TLOG tlog) ptvar@(TVar (TVarA tva,tvany@(TVarAny tx))) = uninterruptibleMask_ $ do _tva <- takeMVar tva -- access the TVar lg <- readIORef tlog -- access the Log-File let ((la,ln,lw):xs) = tripelStack lg mid <- myThreadId -- the ThreadId if tvany `Set.member` la then do -- x in L_a, local copy exists uninterruptibleMask_ ( do localmap <- readMVar (localContent _tva) lk <- readIORef $ fromJust $ Map.lookup mid localmap let (x:xs) = lk putMVar tva _tva return (Right x) ) else -- TVar not in read TVars do uninterruptibleMask_ ( do b <- isEmptyMVar (lock _tva) if b -- not locked then do nl <- takeMVar (notifyList _tva) putMVar (notifyList _tva) (Set.insert mid nl) -- add to notifyList globalC <- readMVar (globalContent _tva) -- read global content content_local <- newIORef [globalC] mp <- takeMVar (localContent _tva) writeIORef tlog (lg{readTVars = Set.insert tvany (readTVars lg),tripelStack = ((Set.insert tvany la,ln,lw):xs)}) putMVar (localContent _tva) (Map.insert mid content_local mp) -- copy to local tvar stack #ifdef DEBUG putStrLn (show mid ++ " has created local content for " ++ show tvany) #endif -- adjust the transaction log putMVar tva _tva return (Right globalC) else -- locked do blockvar <- newEmptyMVar wq <- takeMVar (waitingQueue _tva) putMVar (waitingQueue _tva) (blockvar:wq) putMVar tva _tva #ifdef DEBUG -- sPutStrLn (show mid ++ "wait in readTVar") #endif return (Left blockvar) ) -- | 'writeTVarWithLog' performs the writeTVar operation and -- adjusts the transaction log accordingly writeTVarWithLog :: TLOG -- ^ the transaction log -> TVar a -- ^ the 'TVar' -> a -- ^ the new content -> IO () writeTVarWithLog (TLOG tlog) ptvar@(TVar (_,tvany)) con = do res <- tryWriteTVarWithLog (TLOG tlog) ptvar con case res of Right r -> return r Left blockvar -> do #ifdef DEBUG mid <- myThreadId sPutStrLn (show mid ++ "wait in write on TVar" ++ show tvany) #endif takeMVar blockvar writeTVarWithLog (TLOG tlog) ptvar con tryWriteTVarWithLog (TLOG tlog) ptvar@(TVar (TVarA tva,tvany@(TVarAny (id,m)))) con = uninterruptibleMask_ $ do _tva <- takeMVar tva -- access the TVar lg <- readIORef tlog -- access the Log-File let ((la,ln,lw):xs) = tripelStack lg mid <- myThreadId -- the ThreadId if tvany `Set.member` la then do -- x in L_a, local copy exists uninterruptibleMask_ ( do localmap <- readMVar (localContent _tva) let ioref_with_old_content = fromJust $ Map.lookup mid localmap lk <- readIORef ioref_with_old_content let (x:ys) = lk writeIORef ioref_with_old_content (con:ys) writeIORef tlog (lg{tripelStack = ((la,ln,Set.insert (tvany) lw):xs)}) putMVar tva _tva return $ Right () ) else -- TVar not in read TVars do uninterruptibleMask_ ( do b <- isEmptyMVar (lock _tva) if b -- not locked then do globalC <- readMVar (globalContent _tva) -- read global content content_local <- newIORef [con] mp <- takeMVar (localContent _tva) putMVar (localContent _tva) (Map.insert mid content_local mp) -- copy to local tvar stack -- adjust the transaction log writeIORef tlog (lg{readTVars = Set.insert tvany (readTVars lg),tripelStack = ((Set.insert tvany la,ln,Set.insert tvany lw):xs)}) putMVar tva _tva return (Right ()) else -- locked do blockvar <- newEmptyMVar wq <- takeMVar (waitingQueue _tva) putMVar (waitingQueue _tva) (wq ++ [blockvar]) putMVar tva _tva #ifdef DEBUG -- sPutStrLn (show mid ++ "wait in writeTVar") #endif return (Left blockvar) ) writeStartWithLog' (TLOG tlog) = uninterruptibleMask_ $ do mid <- myThreadId lg <- readIORef tlog -- access the Log-File mid <- myThreadId let ((la,ln,lw):_) = tripelStack lg let t = readTVars lg let xs = (t `Set.union` ((Set.\\) la ln)) -- x1,...,xn #ifdef DEBUG sPutStrLn (show mid ++ "will lock " ++ show (xs)) #endif res <- uninterruptibleMask_ (grabLocks mid (Data.List.sort $ Set.elems xs) []) case res of Right _ -> do writeIORef tlog (lg{lockingSet = xs}) -- K := xs #ifdef DEBUG sPutStrLn (show mid ++ "has locked " ++ show (xs)) #endif return (Right ()) Left lock -> return (Left lock) -- | 'writeStartWithLog' starts the commit phase, by -- locking the read and written TVars writeStartWithLog :: TLOG -- ^ the transaction log -> IO () writeStartWithLog (TLOG tlog) = do res <- writeStartWithLog' (TLOG tlog) case res of Left lock -> do mid <- myThreadId #ifdef DEBUG sPutStrLn (show mid ++ " busy wait in writeStart") #endif takeMVar lock yield threadDelay 1000 writeStartWithLog (TLOG tlog) Right () -> return () grabLocks mid [] _ = return (Right ()) grabLocks mid ((ptvar@(TVarAny (i,tvany))):xs) held = uninterruptibleMask_ $ do _tvany <- takeMVar tvany #ifdef DEBUG mid <- myThreadId sPutStrLn (show mid ++ " inside grabLocks for TVar" ++ show i) #endif b <- tryPutMVar (lock _tvany) mid if b -- not locked then do #ifdef DEBUG mid <- myThreadId sPutStrLn (show mid ++ " has lock for TVar" ++ show i) -- debugTLOG (tlog) #endif putMVar tvany _tvany #ifdef DEBUG mid <- myThreadId sPutStrLn (show mid ++ " outside grabLocks for TVar" ++ show i) #endif grabLocks mid xs (ptvar:held) else do -- already locked waiton <- newEmptyMVar l <- takeMVar (waitingQueue _tvany) putMVar (waitingQueue _tvany) (l ++ [waiton]) putMVar tvany _tvany mapM_ (\(TVarAny (i,tvany)) -> do _tv <- takeMVar tvany takeMVar (lock _tv) #ifdef DEBUG mid <- myThreadId sPutStrLn (show mid ++ " released lock for TVar" ++ show i) -- debugTLOG (tlog) #endif putMVar tvany _tv) (reverse held) #ifdef DEBUG mid <- myThreadId sPutStrLn (show mid ++ " outside grabLocks for TVar (with fail)" ++ show i) #endif return (Left waiton) iterateClearWithLog (TLOG tlog) [] = return () iterateClearWithLog (TLOG tlog) ((TVarAny (id,tvany)):xs) = do mid <- myThreadId uninterruptibleMask_ $ do lg <- readIORef tlog _tvany <- takeMVar tvany ns <- takeMVar (notifyList _tvany) -- remove thread id from notify list: putMVar (notifyList _tvany) (Set.delete mid ns) putMVar tvany _tvany iterateClearWithLog (TLOG tlog) xs -- iterate clearWrite as long as possible (i.e. until the T-List is empty) -- Note: the iteration is not atomic (as in the paper) -- | 'writeClearWithLog' removes the notify entries of the committing transaction writeClearWithLog (TLOG tlog) = do lg <- readIORef tlog -- access the Log-File let xs = Set.elems (readTVars lg) iterateClearWithLog (TLOG tlog) xs writeIORef tlog (lg{readTVars=Set.empty}) getIds [] ls = return (Set.elems ls) getIds ((TVarAny (_,tvany)):xs) ls = do l <- uninterruptibleMask_ (do _tvany <- takeMVar tvany l <- takeMVar (notifyList _tvany) putMVar (notifyList _tvany) (Set.empty) putMVar tvany _tvany return l ) getIds xs (Set.union l ls) -- | 'sendRetryWithLog' sends exceptions to the conflicting threads sendRetryWithLog :: TLOG -- ^ the transaction log -> IO () sendRetryWithLog (TLOG tlog) = uninterruptibleMask_ $ do lg <- readIORef tlog -- access the Log-File mid <- myThreadId let ((la,ln,lw):xs) = tripelStack lg openLW <- getIds (Set.elems lw) (Set.empty) notify openLW notify [] = return () notify (tid:xs) = do mid <- myThreadId #ifdef DEBUG sPutStrLn (show mid ++ " tries to send exception to" ++ show tid) #endif -- ack <- newEmptyMVar throwTo tid (RetryException) -- send retry, #ifdef DEBUG sPutStrLn (show mid ++ " successfully sent exception to" ++ show tid) #endif notify xs -- | 'writeTVWithLog' performs the write-Operations of the committing thread. writeTVWithLog :: TLOG -- ^ the transaction log -> IO () writeTVWithLog (TLOG tlog) = do lg <- readIORef tlog -- access the Log-File mid <- myThreadId let ((la,ln,lw):xs) = tripelStack lg let tobewritten = ((Set.\\) lw ln) writeTVars (Set.elems tobewritten) writeIORef tlog lg{tripelStack=((la,ln,(Set.empty)):xs)} writeTVars [] = return () writeTVars ((TVarAny (tid,tvany)):xs) = do mid <- myThreadId _tvany <- takeMVar tvany localMap <- takeMVar (localContent _tvany) case Map.lookup mid localMap of Just conp -> do con <- readIORef conp let (ltv:stackedcontent) = con putMVar (localContent _tvany) (Map.delete mid localMap) -- copy to global storage takeMVar (globalContent _tvany) putMVar (globalContent _tvany) ltv putMVar tvany _tvany writeTVars xs -- ------------------------------------------------ -- unlockTVWithLog implements (unlockTV) -- ------------------------------------------------ -- | 'unlockTVWithLog' remove the locks of the TVars during commit unlockTVWithLog :: TLOG -- ^ the transaction log -> IO () unlockTVWithLog (TLOG tlog) = uninterruptibleMask_ $ do lg <- readIORef tlog -- access the Log-File mid <- myThreadId let ((la,ln,lw):xs) = tripelStack lg let k = lockingSet lg unlockTVars (Set.elems k) #ifdef DEBUG sPutStrLn (show mid ++ "unlocked" ++ show k) #endif writeIORef tlog lg{lockingSet = Set.empty} unlockTVars [] = return () unlockTVars ((TVarAny (i,tvany)):xs) = uninterruptibleMask_ $ do mid <- myThreadId #ifdef DEBUG sPutStrLn (show mid ++ "will unlock TVar " ++ show i) #endif _tvany <- takeMVar tvany wq <- takeMVar (waitingQueue _tvany) takeMVar (lock _tvany) #ifdef DEBUG sPutStrLn (show mid ++ "removed lock of TVar " ++ show i) #endif putMVar (waitingQueue _tvany) [] mapM_ (\mv -> putMVar mv ()) wq putMVar tvany _tvany #ifdef DEBUG sPutStrLn (show mid ++ "unlock of TVar " ++ show i ++ "done") #endif unlockTVars xs -- | 'writeTVnWithLog' writes the newly created TVars during commit writeTVnWithLog :: TLOG -- ^ the transaction log -> IO () writeTVnWithLog (TLOG tlog) = do lg <- readIORef tlog -- access the Log-File mid <- myThreadId let ((la,ln,lw):xs) = tripelStack lg let t = readTVars lg let k = lockingSet lg let toBeWritten = Set.elems ln writeNew toBeWritten writeIORef tlog lg{tripelStack=((la,Set.empty,lw):xs)} writeNew [] = return () writeNew ((TVarAny (i,tvany)):xs) = do mid <- myThreadId _tvany <- takeMVar tvany lmap <- takeMVar (localContent _tvany) if Map.null (Map.delete mid lmap) then case (Map.lookup mid lmap) of Just conp -> do (con:_) <- readIORef conp takeMVar (globalContent _tvany) putMVar (globalContent _tvany) con putMVar (localContent _tvany) (Map.empty) putMVar tvany _tvany writeNew xs else #ifdef DEBUG do sPutStrLn ((show mid) ++ " panic: keys in localcontent" ++ show ( Map.keys (Map.delete mid lmap)) ++ "of local TVar" ++ show i) #endif error "panic" -- ------------------------------------------------ -- writeEndWithLog implements (writeEnd) -- ------------------------------------------------ -- | 'writeEndWithLog' clears the local TVars, during commit writeEndWithLog :: TLOG -- ^ the transaction log -> IO () writeEndWithLog (TLOG tlog) = do lg <- readIORef tlog -- access the Log-File mid <- myThreadId let ((la,ln,lw):xs) = tripelStack lg let t = readTVars lg let k = lockingSet lg clearEntries (Set.elems la) clearEntries [] = return () clearEntries ((TVarAny (_,tvany)):xs) = do mid <- myThreadId _tvany <- takeMVar tvany localmap <- takeMVar (localContent _tvany) putMVar (localContent _tvany) (Map.delete mid localmap) putMVar tvany _tvany -- ------------------------------------------------ -- commit performs all the operations for committing -- ------------------------------------------------ -- | 'commit' performs the operations for committing -- -- - 'writeStartWithLog' to lock the read and to-be-written TVars -- -- - 'writeClearWithLog' (iteratively) to remove the notify entries of the committing transaction -- -- - 'sendRetryWithLog' (iteratively) to abort conflicting transactions -- -- - 'writeTVWithLog' (iteratively) to write the local contents in to the global memory -- -- - 'writeTVnWithLog' (iteratively) to create the newly created TVars in the global memory -- -- - 'writeEndWithLog' to clear the local TVar stack -- -- - 'unlockTVWithLog' (iteratively) to unlock the global TVars commit :: TLOG -- ^ the transaction logs -> IO () commit (TLOG tlog) = do mid <- myThreadId #ifdef DEBUG sPutStrLn (show mid ++ " starting commit") -- debugTLOG (tlog) #endif -- yield writeStartWithLog (TLOG tlog) -- writeStart #ifdef DEBUG sPutStrLn (show mid ++ " writeStart finished") -- debugTLOG (tlog) #endif -- yield writeClearWithLog (TLOG tlog) -- clearWrite phase #ifdef DEBUG sPutStrLn (show mid ++ " clearWith finished") -- debugTLOG (tlog) #endif -- yield sendRetryWithLog (TLOG tlog) -- sendRetry phase #ifdef DEBUG sPutStrLn (show mid ++ " sendRetry finished") -- debugTLOG (tlog) #endif -- yield writeTVWithLog (TLOG tlog) -- writeTV phase #ifdef DEBUG sPutStrLn (show mid ++ " writeTV finished") -- debugTLOG (tlog) #endif -- yield writeTVnWithLog (TLOG tlog) -- writeTVn phase #ifdef DEBUG sPutStrLn (show mid ++ " writeTVn finished") -- debugTLOG (tlog) #endif -- yield writeEndWithLog (TLOG tlog) -- writeTVn phase #ifdef DEBUG sPutStrLn (show mid ++ " writeEnd finished") -- debugTLOG (tlog) #endif #ifdef DEBUG sPutStrLn (show mid ++ " unlockTV starts") -- debugTLOG (tlog) #endif unlockTVWithLog (TLOG tlog) -- unlockTV phase #ifdef DEBUG sPutStrLn (show mid ++ " unlockTV finished") -- debugTLOG (tlog) #endif -- ------------------------------------------------ -- retryCGlobWithLog implements (retryCGlob) -- ------------------------------------------------ -- | 'retryCGlobWithLog' performs the removal of notify entries during retry retryCGlobWithLog :: TLOG -- ^ the transaction log -> IO () retryCGlobWithLog (TLOG tlog) = do lg <- readIORef tlog -- access the Log-File mid <- myThreadId let t = Set.elems (readTVars lg) uninterruptibleMask_ $ do removeNotifyEntries mid t writeIORef tlog lg{readTVars = Set.empty} removeNotifyEntries mid [] = return () removeNotifyEntries mid ((TVarAny (i,tvany)):xs) = uninterruptibleMask_ $ do _tvany <- takeMVar tvany nlist <- takeMVar (notifyList _tvany) putMVar (notifyList _tvany) (Set.delete mid nlist) putMVar tvany _tvany removeNotifyEntries mid xs -- ------------------------------------------------ -- retryEndWithLog implements (retryEnd) (slightly modified) -- ------------------------------------------------ -- | 'retryEndWithLog' resets the transaction log and the local tvar content during retry retryEndWithLog :: TLOG -- ^ the transaction log -> IO () retryEndWithLog (TLOG tlog) = do lg <- readIORef tlog -- access the Log-File mid <- myThreadId let ((la,ln,lw):xs) = tripelStack lg let tvset = (la `Set.union` ln `Set.union` lw) let toBeResetted = Set.elems tvset uninterruptibleMask_ $ do resetEntries mid toBeResetted writeIORef tlog (lg{tripelStack = ((Set.empty,Set.empty, Set.empty):xs)}) resetEntries mid [] = return () resetEntries mid ((TVarAny (_,tvany)):xs) = uninterruptibleMask_ $ do _tvany <- takeMVar tvany localmap <- takeMVar (localContent _tvany) putMVar (localContent _tvany) (Map.delete mid localmap) putMVar tvany _tvany resetEntries mid xs -- ---------------------------- -- globalRetry should be called when the transaction retries ------------------------------- -- | 'globalRetry' should be called to retry a transaction, it iteratively -- perform 'retryCGlobWithLog' and then 'retryEndWithLog' globalRetry :: TLOG -- ^ the transaction log -> IO () globalRetry (TLOG tlog) = catch ( do mid <- myThreadId uninterruptibleMask_ (retryCGlobWithLog (TLOG tlog)) #ifdef DEBUG sPutStrLn (show mid ++ " finished retryCGlob") #endif uninterruptibleMask_ (retryEndWithLog (TLOG tlog)) #ifdef DEBUG sPutStrLn (show mid ++ " finished retryEnd") #endif ) (\(RetryException) -> globalRetry (TLOG tlog)) -- ------------------------------------------------ -- orElseWithLog (performs (orElse), i.e duplication of stacks etc. -- ------------------------------------------------ -- | 'orElseWithLog' should be called for the evaluation of 'orElse' to duplicate the local TVar stacks and -- the entries in the transaction log orElseWithLog :: TLOG -- ^ the transaction log -> IO () orElseWithLog (TLOG tlog) = do lg <- readIORef tlog -- access the Log-File mid <- myThreadId #ifdef DEBUG sPutStrLn (show mid ++ " orElse start") #endif let ((la,ln,lw):xs) = tripelStack lg -- double all local TVars uninterruptibleMask_ ( do doubleLocalTVars mid (Set.elems la) writeIORef tlog (lg{tripelStack=(la,ln,lw):((la,ln,lw):xs)}) ) doubleLocalTVars mid [] = return () doubleLocalTVars mid ((TVarAny (_,tvany)):xs) = uninterruptibleMask_ $ do _tvany <- takeMVar tvany localmap <- takeMVar (localContent _tvany) case Map.lookup mid localmap of Just conp -> do (x:ys) <- readIORef conp writeIORef conp (x:x:ys) putMVar (localContent _tvany) localmap putMVar tvany _tvany doubleLocalTVars mid xs -- ------------------------------------------------ -- orRetryWithLog (performs (orRetry), i.e removal -- ------------------------------------------------ -- | 'orRetryWithLog' should be called when the left expression of an 'orElse' evaluates to 'retry' -- it pops all stacks (local TVars and transaction log) orRetryWithLog :: TLOG -- ^ the transaction log -> IO () orRetryWithLog (TLOG tlog) = do lg <- readIORef tlog -- access the Log-File mid <- myThreadId #ifdef DEBUG sPutStrLn (show mid ++ " orRetry") #endif let ((la,ln,lw):xs) = tripelStack lg uninterruptibleMask_ $ do undoubleLocalTVars mid (Set.elems la) writeIORef tlog (lg{tripelStack=(xs)}) undoubleLocalTVars mid [] = return [] undoubleLocalTVars mid ((TVarAny (_,tvany)):xs) = uninterruptibleMask_ $ do _tvany <- takeMVar tvany localmap <- takeMVar (localContent _tvany) case (Map.lookup mid localmap) of Just conp -> do (l:ltv) <- readIORef conp writeIORef conp ltv putMVar tvany _tvany putMVar (localContent _tvany) localmap undoubleLocalTVars mid xs -- ************************************************************************************* -- only for debugging: generate a global TVar quickly newGlobalTVar content = do tvar_Id <- nextCounter -- Create the TVar ... content_global <- newMVar content -- set global content content_local <- newMVar (Map.empty) notify_list <- newMVar (Set.empty) unset_lock <- newEmptyMVar -- loc <- newIORef Nothing content_waiting_queue <- newMVar [] -- empty broadcast list content_tvarx <- newMVar (TV {globalContent = content_global, localContent = content_local, notifyList = notify_list, lock = unset_lock, waitingQueue = content_waiting_queue -- local = loc }) let tvany = TVarAny (tvar_Id,content_tvarx) let tva = TVarA content_tvarx let tvar = TVar (tva,tvany) return tvar
dsabel/stmshf
Control/Concurrent/SHFSTM/Internal.hs
bsd-3-clause
26,818
0
26
8,642
6,578
3,255
3,323
468
3
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main where import Control.Applicative import Control.Monad import Control.Monad.Reader import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.List (nub) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE import qualified Data.Map.Strict as M import Data.Text (Text) import qualified Data.Text as T import Data.Time.Calendar (Day (..)) import Data.Time.Clock (UTCTime (..), secondsToDiffTime) import qualified Data.Vector as V import Database.Bloodhound import GHC.Generics (Generic) import Network.HTTP.Client import qualified Network.HTTP.Types.Status as NHTS import Prelude hiding (filter, putStrLn) import Test.Hspec import Test.QuickCheck.Property.Monoid import Test.Hspec.QuickCheck (prop) import Test.QuickCheck testServer :: Server testServer = Server "http://localhost:9200" testIndex :: IndexName testIndex = IndexName "bloodhound-tests-twitter-1" testMapping :: MappingName testMapping = MappingName "tweet" withTestEnv :: BH IO a -> IO a withTestEnv = withBH defaultManagerSettings testServer validateStatus :: Response body -> Int -> Expectation validateStatus resp expected = (NHTS.statusCode $ responseStatus resp) `shouldBe` (expected :: Int) createExampleIndex :: BH IO Reply createExampleIndex = createIndex defaultIndexSettings testIndex deleteExampleIndex :: BH IO Reply deleteExampleIndex = deleteIndex testIndex data ServerVersion = ServerVersion Int Int Int deriving (Show, Eq, Ord) es14 :: ServerVersion es14 = ServerVersion 1 4 0 es13 :: ServerVersion es13 = ServerVersion 1 3 0 es12 :: ServerVersion es12 = ServerVersion 1 2 0 es11 :: ServerVersion es11 = ServerVersion 1 1 0 es10 :: ServerVersion es10 = ServerVersion 1 0 0 serverBranch :: ServerVersion -> ServerVersion serverBranch (ServerVersion majorVer minorVer patchVer) = ServerVersion majorVer minorVer patchVer mkServerVersion :: [Int] -> Maybe ServerVersion mkServerVersion [majorVer, minorVer, patchVer] = Just (ServerVersion majorVer minorVer patchVer) mkServerVersion _ = Nothing getServerVersion :: IO (Maybe ServerVersion) getServerVersion = liftM extractVersion (withTestEnv getStatus) where version' = T.splitOn "." . number . version toInt = read . T.unpack parseVersion v = map toInt (version' v) extractVersion = join . liftM (mkServerVersion . parseVersion) testServerBranch :: IO (Maybe ServerVersion) testServerBranch = getServerVersion >>= \v -> return $ liftM serverBranch v atleast :: ServerVersion -> IO Bool atleast v = testServerBranch >>= \x -> return $ x >= Just (serverBranch v) atmost :: ServerVersion -> IO Bool atmost v = testServerBranch >>= \x -> return $ x <= Just (serverBranch v) is :: ServerVersion -> IO Bool is v = testServerBranch >>= \x -> return $ x == Just (serverBranch v) when' :: Monad m => m Bool -> m () -> m () when' b f = b >>= \x -> when x f data Location = Location { lat :: Double , lon :: Double } deriving (Eq, Generic, Show) data Tweet = Tweet { user :: Text , postDate :: UTCTime , message :: Text , age :: Int , location :: Location } deriving (Eq, Generic, Show) instance ToJSON Tweet instance FromJSON Tweet instance ToJSON Location instance FromJSON Location data TweetMapping = TweetMapping deriving (Eq, Show) instance ToJSON TweetMapping where toJSON TweetMapping = object ["tweet" .= object ["properties" .= object ["location" .= object ["type" .= ("geo_point" :: Text)]]]] exampleTweet :: Tweet exampleTweet = Tweet { user = "bitemyapp" , postDate = UTCTime (ModifiedJulianDay 55000) (secondsToDiffTime 10) , message = "Use haskell!" , age = 10000 , location = Location 40.12 (-71.34) } otherTweet :: Tweet otherTweet = Tweet { user = "notmyapp" , postDate = UTCTime (ModifiedJulianDay 55000) (secondsToDiffTime 11) , message = "Use haskell!" , age = 1000 , location = Location 40.12 (-71.34) } insertData :: BH IO () insertData = do _ <- deleteExampleIndex _ <- createExampleIndex _ <- putMapping testIndex testMapping TweetMapping _ <- indexDocument testIndex testMapping exampleTweet (DocId "1") _ <- refreshIndex testIndex return () insertOther :: BH IO () insertOther = do _ <- indexDocument testIndex testMapping otherTweet (DocId "2") _ <- refreshIndex testIndex return () searchTweet :: Search -> BH IO (Either String Tweet) searchTweet search = do reply <- searchByIndex testIndex search let result = eitherDecode (responseBody reply) :: Either String (SearchResult Tweet) let myTweet = fmap (hitSource . head . hits . searchHits) result return myTweet searchExpectNoResults :: Search -> BH IO () searchExpectNoResults search = do reply <- searchByIndex testIndex search let result = eitherDecode (responseBody reply) :: Either String (SearchResult Tweet) let emptyHits = fmap (hits . searchHits) result liftIO $ emptyHits `shouldBe` Right [] searchExpectAggs :: Search -> BH IO () searchExpectAggs search = do reply <- searchAll search let isEmpty x = return (M.null x) let result = decode (responseBody reply) :: Maybe (SearchResult Tweet) liftIO $ (result >>= aggregations >>= isEmpty) `shouldBe` Just False searchValidBucketAgg :: (BucketAggregation a, FromJSON a, Show a) => Search -> Text -> (Text -> AggregationResults -> Maybe (Bucket a)) -> BH IO () searchValidBucketAgg search aggKey extractor = do reply <- searchAll search let bucketDocs = docCount . head . buckets let result = decode (responseBody reply) :: Maybe (SearchResult Tweet) let count = result >>= aggregations >>= extractor aggKey >>= \x -> return (bucketDocs x) liftIO $ count `shouldBe` Just 1 searchTermsAggHint :: [ExecutionHint] -> BH IO () searchTermsAggHint hints = do let terms hint = TermsAgg $ (mkTermsAggregation "user") { termExecutionHint = Just hint } let search hint = mkAggregateSearch Nothing $ mkAggregations "users" $ terms hint forM_ hints $ searchExpectAggs . search forM_ hints (\x -> searchValidBucketAgg (search x) "users" toTerms) searchTweetHighlight :: Search -> BH IO (Either String (Maybe HitHighlight)) searchTweetHighlight search = do reply <- searchByIndex testIndex search let result = eitherDecode (responseBody reply) :: Either String (SearchResult Tweet) let myHighlight = fmap (hitHighlight . head . hits . searchHits) result return myHighlight searchExpectSource :: Source -> Either String Value -> BH IO () searchExpectSource src expected = do _ <- insertData let query = QueryMatchQuery $ mkMatchQuery (FieldName "_all") (QueryString "haskell") let search = (mkSearch (Just query) Nothing) { source = Just src } reply <- searchAll search let result = eitherDecode (responseBody reply) :: Either String (SearchResult Value) let value = fmap (hitSource . head . hits . searchHits) result liftIO $ value `shouldBe` expected data BulkTest = BulkTest { name :: Text } deriving (Eq, Generic, Show) instance FromJSON BulkTest instance ToJSON BulkTest noDuplicates :: Eq a => [a] -> Bool noDuplicates xs = nub xs == xs instance Arbitrary RegexpFlags where arbitrary = oneof [ pure AllRegexpFlags , pure NoRegexpFlags , SomeRegexpFlags <$> arbitrary ] instance Arbitrary a => Arbitrary (NonEmpty a) where arbitrary = liftA2 (:|) arbitrary arbitrary instance Arbitrary RegexpFlag where arbitrary = oneof [ pure AnyString , pure Automaton , pure Complement , pure Empty , pure Intersection , pure Interval ] arbitraryScore :: Gen Score arbitraryScore = fmap getPositive <$> arbitrary instance Arbitrary Text where arbitrary = T.pack <$> arbitrary instance (Arbitrary k, Arbitrary v, Ord k) => Arbitrary (M.Map k v) where arbitrary = M.fromList <$> arbitrary instance Arbitrary IndexName where arbitrary = IndexName <$> arbitrary instance Arbitrary MappingName where arbitrary = MappingName <$> arbitrary instance Arbitrary DocId where arbitrary = DocId <$> arbitrary instance Arbitrary a => Arbitrary (Hit a) where arbitrary = Hit <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitraryScore <*> arbitrary <*> arbitrary instance Arbitrary a => Arbitrary (SearchHits a) where arbitrary = sized $ \n -> resize (n `div` 2) $ do tot <- getPositive <$> arbitrary score <- arbitraryScore hs <- arbitrary return $ SearchHits tot score hs main :: IO () main = hspec $ do describe "index create/delete API" $ do it "creates and then deletes the requested index" $ withTestEnv $ do -- priming state. _ <- deleteExampleIndex resp <- createExampleIndex deleteResp <- deleteExampleIndex liftIO $ do validateStatus resp 200 validateStatus deleteResp 200 describe "document API" $ do it "indexes, gets, and then deletes the generated document" $ withTestEnv $ do _ <- insertData docInserted <- getDocument testIndex testMapping (DocId "1") let newTweet = eitherDecode (responseBody docInserted) :: Either String (EsResult Tweet) liftIO $ (fmap _source newTweet `shouldBe` Right exampleTweet) describe "bulk API" $ do it "inserts all documents we request" $ withTestEnv $ do _ <- insertData let firstTest = BulkTest "blah" let secondTest = BulkTest "bloo" let firstDoc = BulkIndex testIndex testMapping (DocId "2") (toJSON firstTest) let secondDoc = BulkCreate testIndex testMapping (DocId "3") (toJSON secondTest) let stream = V.fromList [firstDoc, secondDoc] _ <- bulk stream _ <- refreshIndex testIndex fDoc <- getDocument testIndex testMapping (DocId "2") sDoc <- getDocument testIndex testMapping (DocId "3") let maybeFirst = eitherDecode $ responseBody fDoc :: Either String (EsResult BulkTest) let maybeSecond = eitherDecode $ responseBody sDoc :: Either String (EsResult BulkTest) liftIO $ do fmap _source maybeFirst `shouldBe` Right firstTest fmap _source maybeSecond `shouldBe` Right secondTest describe "query API" $ do it "returns document for term query and identity filter" $ withTestEnv $ do _ <- insertData let query = TermQuery (Term "user" "bitemyapp") Nothing let filter = IdentityFilter <&&> IdentityFilter let search = mkSearch (Just query) (Just filter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for terms query and identity filter" $ withTestEnv $ do _ <- insertData let query = TermsQuery (NE.fromList [(Term "user" "bitemyapp")]) let filter = IdentityFilter <&&> IdentityFilter let search = mkSearch (Just query) (Just filter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for match query" $ withTestEnv $ do _ <- insertData let query = QueryMatchQuery $ mkMatchQuery (FieldName "user") (QueryString "bitemyapp") let search = mkSearch (Just query) Nothing myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for multi-match query" $ withTestEnv $ do _ <- insertData let fields = [FieldName "user", FieldName "message"] let query = QueryMultiMatchQuery $ mkMultiMatchQuery fields (QueryString "bitemyapp") let search = mkSearch (Just query) Nothing myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for bool query" $ withTestEnv $ do _ <- insertData let innerQuery = QueryMatchQuery $ mkMatchQuery (FieldName "user") (QueryString "bitemyapp") let query = QueryBoolQuery $ mkBoolQuery [innerQuery] [] [] let search = mkSearch (Just query) Nothing myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for boosting query" $ withTestEnv $ do _ <- insertData let posQuery = QueryMatchQuery $ mkMatchQuery (FieldName "user") (QueryString "bitemyapp") let negQuery = QueryMatchQuery $ mkMatchQuery (FieldName "user") (QueryString "notmyapp") let query = QueryBoostingQuery $ BoostingQuery posQuery negQuery (Boost 0.2) let search = mkSearch (Just query) Nothing myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for common terms query" $ withTestEnv $ do _ <- insertData let query = QueryCommonTermsQuery $ CommonTermsQuery (FieldName "user") (QueryString "bitemyapp") (CutoffFrequency 0.0001) Or Or Nothing Nothing Nothing Nothing let search = mkSearch (Just query) Nothing myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet describe "sorting" $ do it "returns documents in the right order" $ withTestEnv $ do _ <- insertData _ <- insertOther let sortSpec = DefaultSortSpec $ mkSort (FieldName "age") Ascending let search = Search Nothing (Just IdentityFilter) (Just [sortSpec]) Nothing Nothing False (From 0) (Size 10) Nothing reply <- searchByIndex testIndex search let result = eitherDecode (responseBody reply) :: Either String (SearchResult Tweet) let myTweet = fmap (hitSource . head . hits . searchHits) result liftIO $ myTweet `shouldBe` Right otherTweet describe "filtering API" $ do it "returns document for composed boolmatch and identity" $ withTestEnv $ do _ <- insertData let queryFilter = BoolFilter (MustMatch (Term "user" "bitemyapp") False) <&&> IdentityFilter let search = mkSearch Nothing (Just queryFilter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for term filter" $ withTestEnv $ do _ <- insertData let termFilter = TermFilter (Term "user" "bitemyapp") False let search = mkSearch Nothing (Just termFilter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for existential filter" $ withTestEnv $ do _ <- insertData let search = mkSearch Nothing (Just (ExistsFilter (FieldName "user"))) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for geo boundingbox filter" $ withTestEnv $ do _ <- insertData let box = GeoBoundingBox (LatLon 40.73 (-74.1)) (LatLon 40.10 (-71.12)) let bbConstraint = GeoBoundingBoxConstraint (FieldName "tweet.location") box False GeoFilterMemory let geoFilter = GeoBoundingBoxFilter bbConstraint let search = mkSearch Nothing (Just geoFilter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "doesn't return document for nonsensical boundingbox filter" $ withTestEnv $ do _ <- insertData let box = GeoBoundingBox (LatLon 0.73 (-4.1)) (LatLon 0.10 (-1.12)) let bbConstraint = GeoBoundingBoxConstraint (FieldName "tweet.location") box False GeoFilterMemory let geoFilter = GeoBoundingBoxFilter bbConstraint let search = mkSearch Nothing (Just geoFilter) searchExpectNoResults search it "returns document for geo distance filter" $ withTestEnv $ do _ <- insertData let geoPoint = GeoPoint (FieldName "tweet.location") (LatLon 40.12 (-71.34)) let distance = Distance 10.0 Miles let optimizeBbox = OptimizeGeoFilterType GeoFilterMemory let geoFilter = GeoDistanceFilter geoPoint distance SloppyArc optimizeBbox False let search = mkSearch Nothing (Just geoFilter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for geo distance range filter" $ withTestEnv $ do _ <- insertData let geoPoint = GeoPoint (FieldName "tweet.location") (LatLon 40.12 (-71.34)) let distanceRange = DistanceRange (Distance 0.0 Miles) (Distance 10.0 Miles) let geoFilter = GeoDistanceRangeFilter geoPoint distanceRange let search = mkSearch Nothing (Just geoFilter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "doesn't return document for wild geo distance range filter" $ withTestEnv $ do _ <- insertData let geoPoint = GeoPoint (FieldName "tweet.location") (LatLon 40.12 (-71.34)) let distanceRange = DistanceRange (Distance 100.0 Miles) (Distance 1000.0 Miles) let geoFilter = GeoDistanceRangeFilter geoPoint distanceRange let search = mkSearch Nothing (Just geoFilter) searchExpectNoResults search it "returns document for geo polygon filter" $ withTestEnv $ do _ <- insertData let points = [LatLon 40.0 (-70.00), LatLon 40.0 (-72.00), LatLon 41.0 (-70.00), LatLon 41.0 (-72.00)] let geoFilter = GeoPolygonFilter (FieldName "tweet.location") points let search = mkSearch Nothing (Just geoFilter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "doesn't return document for bad geo polygon filter" $ withTestEnv $ do _ <- insertData let points = [LatLon 40.0 (-70.00), LatLon 40.0 (-71.00), LatLon 41.0 (-70.00), LatLon 41.0 (-71.00)] let geoFilter = GeoPolygonFilter (FieldName "tweet.location") points let search = mkSearch Nothing (Just geoFilter) searchExpectNoResults search it "returns document for ids filter" $ withTestEnv $ do _ <- insertData let filter = IdsFilter (MappingName "tweet") [DocId "1"] let search = mkSearch Nothing (Just filter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for Double range filter" $ withTestEnv $ do _ <- insertData let filter = RangeFilter (FieldName "age") (RangeDoubleGtLt (GreaterThan 1000.0) (LessThan 100000.0)) RangeExecutionIndex False let search = mkSearch Nothing (Just filter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for UTCTime date filter" $ withTestEnv $ do _ <- insertData let filter = RangeFilter (FieldName "postDate") (RangeDateGtLt (GreaterThanD (UTCTime (ModifiedJulianDay 55000) (secondsToDiffTime 9))) (LessThanD (UTCTime (ModifiedJulianDay 55000) (secondsToDiffTime 11)))) RangeExecutionIndex False let search = mkSearch Nothing (Just filter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "returns document for regexp filter" $ withTestEnv $ do _ <- insertData let filter = RegexpFilter (FieldName "user") (Regexp "bite.*app") AllRegexpFlags (CacheName "test") False (CacheKey "key") let search = mkSearch Nothing (Just filter) myTweet <- searchTweet search liftIO $ myTweet `shouldBe` Right exampleTweet it "doesn't return document for non-matching regexp filter" $ withTestEnv $ do _ <- insertData let filter = RegexpFilter (FieldName "user") (Regexp "boy") AllRegexpFlags (CacheName "test") False (CacheKey "key") let search = mkSearch Nothing (Just filter) searchExpectNoResults search describe "Aggregation API" $ do it "returns term aggregation results" $ withTestEnv $ do _ <- insertData let terms = TermsAgg $ mkTermsAggregation "user" let search = mkAggregateSearch Nothing $ mkAggregations "users" terms searchExpectAggs search searchValidBucketAgg search "users" toTerms it "can give collection hint parameters to term aggregations" $ when' (atleast es13) $ withTestEnv $ do _ <- insertData let terms = TermsAgg $ (mkTermsAggregation "user") { termCollectMode = Just BreadthFirst } let search = mkAggregateSearch Nothing $ mkAggregations "users" terms searchExpectAggs search searchValidBucketAgg search "users" toTerms it "can give execution hint paramters to term aggregations" $ when' (atmost es11) $ withTestEnv $ do _ <- insertData searchTermsAggHint [Map, Ordinals] it "can give execution hint paramters to term aggregations" $ when' (is es12) $ withTestEnv $ do _ <- insertData searchTermsAggHint [GlobalOrdinals, GlobalOrdinalsHash, GlobalOrdinalsLowCardinality, Map, Ordinals] it "can give execution hint paramters to term aggregations" $ when' (atleast es12) $ withTestEnv $ do _ <- insertData searchTermsAggHint [GlobalOrdinals, GlobalOrdinalsHash, GlobalOrdinalsLowCardinality, Map] it "returns date histogram aggregation results" $ withTestEnv $ do _ <- insertData let histogram = DateHistogramAgg $ mkDateHistogram (FieldName "postDate") Minute let search = mkAggregateSearch Nothing (mkAggregations "byDate" histogram) searchExpectAggs search searchValidBucketAgg search "byDate" toDateHistogram it "returns date histogram using fractional date" $ withTestEnv $ do _ <- insertData let periods = [Year, Quarter, Month, Week, Day, Hour, Minute, Second] let fractionals = map (FractionalInterval 1.5) [Weeks, Days, Hours, Minutes, Seconds] let intervals = periods ++ fractionals let histogram = mkDateHistogram (FieldName "postDate") let search interval = mkAggregateSearch Nothing $ mkAggregations "byDate" $ DateHistogramAgg (histogram interval) let expect interval = searchExpectAggs (search interval) let valid interval = searchValidBucketAgg (search interval) "byDate" toDateHistogram forM_ intervals expect forM_ intervals valid describe "Highlights API" $ do it "returns highlight from query when there should be one" $ withTestEnv $ do _ <- insertData _ <- insertOther let query = QueryMatchQuery $ mkMatchQuery (FieldName "_all") (QueryString "haskell") let testHighlight = Highlights Nothing [FieldHighlight (FieldName "message") Nothing] let search = mkHighlightSearch (Just query) testHighlight myHighlight <- searchTweetHighlight search liftIO $ myHighlight `shouldBe` Right (Just (M.fromList [("message",["Use <em>haskell</em>!"])])) it "doesn't return highlight from a query when it shouldn't" $ withTestEnv $ do _ <- insertData _ <- insertOther let query = QueryMatchQuery $ mkMatchQuery (FieldName "_all") (QueryString "haskell") let testHighlight = Highlights Nothing [FieldHighlight (FieldName "user") Nothing] let search = mkHighlightSearch (Just query) testHighlight myHighlight <- searchTweetHighlight search liftIO $ myHighlight `shouldBe` Right Nothing describe "Source filtering" $ do it "doesn't include source when sources are disabled" $ withTestEnv $ do searchExpectSource NoSource (Left "key \"_source\" not present") it "includes a source" $ withTestEnv $ do searchExpectSource (SourcePatterns (PopPattern (Pattern "message"))) (Right (Object (HM.fromList [("message", String "Use haskell!")]))) it "includes sources" $ withTestEnv $ do searchExpectSource (SourcePatterns (PopPatterns [Pattern "user", Pattern "message"])) (Right (Object (HM.fromList [("user",String "bitemyapp"),("message", String "Use haskell!")]))) it "includes source patterns" $ withTestEnv $ do searchExpectSource (SourcePatterns (PopPattern (Pattern "*ge"))) (Right (Object (HM.fromList [("age", Number 10000),("message", String "Use haskell!")]))) it "excludes source patterns" $ withTestEnv $ do searchExpectSource (SourceIncludeExclude (Include []) (Exclude [Pattern "l*", Pattern "*ge", Pattern "postDate"])) (Right (Object (HM.fromList [("user",String "bitemyapp")]))) describe "ToJSON RegexpFlags" $ do it "generates the correct JSON for AllRegexpFlags" $ toJSON AllRegexpFlags `shouldBe` String "ALL" it "generates the correct JSON for NoRegexpFlags" $ toJSON NoRegexpFlags `shouldBe` String "NONE" it "generates the correct JSON for SomeRegexpFlags" $ let flags = AnyString :| [ Automaton , Complement , Empty , Intersection , Interval ] in toJSON (SomeRegexpFlags flags) `shouldBe` String "ANYSTRING|AUTOMATON|COMPLEMENT|EMPTY|INTERSECTION|INTERVAL" prop "removes duplicates from flags" $ \(flags :: RegexpFlags) -> let String str = toJSON flags flagStrs = T.splitOn "|" str in noDuplicates flagStrs describe "omitNulls" $ do it "checks that omitNulls drops list elements when it should" $ let dropped = omitNulls $ [ "test1" .= (toJSON ([] :: [Int])) , "test2" .= (toJSON ("some value" :: Text))] in dropped `shouldBe` Object (HM.fromList [("test2", String "some value")]) it "checks that omitNulls doesn't drop list elements when it shouldn't" $ let notDropped = omitNulls $ [ "test1" .= (toJSON ([1] :: [Int])) , "test2" .= (toJSON ("some value" :: Text))] in notDropped `shouldBe` Object (HM.fromList [ ("test1", Array (V.fromList [Number 1.0])) , ("test2", String "some value")]) it "checks that omitNulls drops non list elements when it should" $ let dropped = omitNulls $ [ "test1" .= (toJSON Null) , "test2" .= (toJSON ("some value" :: Text))] in dropped `shouldBe` Object (HM.fromList [("test2", String "some value")]) it "checks that omitNulls doesn't drop non list elements when it shouldn't" $ let notDropped = omitNulls $ [ "test1" .= (toJSON (1 :: Int)) , "test2" .= (toJSON ("some value" :: Text))] in notDropped `shouldBe` Object (HM.fromList [ ("test1", Number 1.0) , ("test2", String "some value")]) describe "Monoid (SearchHits a)" $ do prop "abides the monoid laws" $ eq $ prop_Monoid (T :: T (SearchHits ()))
silkapp/bloodhound
tests/tests.hs
bsd-3-clause
28,356
0
33
7,810
8,083
3,908
4,175
577
1