code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Ternary.Core.Kernel ( Kernel, FirstTwoSteps (Step0, Step1), serial, chain, zipKernelsWith, transformFirstTwo, iterateKernel) where -- A kernel is a machine with an internal state. This state is such a -- fundamental type here, that I decided not to hide it. type Kernel input output state = input -> state -> (output, state) -- Sequential composition serial :: Kernel a b s -> Kernel b c t -> Kernel a c (s,t) serial f g a (s,t) = let (b,u) = f a s (c,v) = b `seq` g b t in c `seq` (c,(u,v)) -- Parallel composition zipKernelsWith :: (b -> d -> z) -> Kernel a b s -> Kernel c d t -> Kernel (a,c) z (s,t) zipKernelsWith op f g (a,c) (s,t) = f a s `op1` g c t where (b,s) `op1` (d,t) = (b `op` d, (s,t)) -- We need a state machine that transforms its input only during the -- first two cycles. data FirstTwoSteps = Step0 | Step1 | After deriving (Show, Eq, Ord) transformFirstTwo :: (a -> a) -> (a -> a) -> Kernel a a FirstTwoSteps transformFirstTwo f _ a Step0 = (f a, Step1) transformFirstTwo _ g a Step1 = (g a, After) transformFirstTwo _ _ a After = (a, After) -- With the chain function below, we define sequential composition of -- a list of kernels, combining states into a list of states. -- The first argument generates a kernel from a parameter. So a list -- of such parameters implicitly defines the list of kernels to be -- chained. But this list of kernels is not materialized: they are -- applied as we stream through the list of parameters. chain :: (p -> Kernel a a s) -> [p] -> Kernel a a [s] chain gen (p:ps) a (u:us) = let (b,v) = gen p a u (c,vs) = b `seq` chain gen ps b us in v `seq` (c,v:vs) chain _ [] a [] = (a,[]) iterateKernel :: Kernel a a s -> Int -> Kernel a a [s] iterateKernel k n = chain (const k) [1..n]
jeroennoels/exact-real
src/Ternary/Core/Kernel.hs
mit
1,843
0
10
449
691
387
304
29
1
{- This module was generated from data in the Kate syntax highlighting file modelines.xml, version 1.2, by Alex Turbov ([email protected]) -} module Text.Highlighting.Kate.Syntax.Modelines (highlight, parseExpression, syntaxName, syntaxExtensions) where import Text.Highlighting.Kate.Types import Text.Highlighting.Kate.Common import Text.ParserCombinators.Parsec hiding (State) import Control.Monad.State import Data.Char (isSpace) import qualified Data.Set as Set -- | Full name of language. syntaxName :: String syntaxName = "Modelines" -- | Filename extensions for this language. syntaxExtensions :: String syntaxExtensions = "" -- | Highlight source code using this syntax definition. highlight :: String -> [SourceLine] highlight input = evalState (mapM parseSourceLine $ lines input) startingState parseSourceLine :: String -> State SyntaxState SourceLine parseSourceLine = mkParseSourceLine (parseExpression Nothing) -- | Parse an expression using appropriate local context. parseExpression :: Maybe (String,String) -> KateParser Token parseExpression mbcontext = do (lang,cont) <- maybe currentContext return mbcontext result <- parseRules (lang,cont) optional $ do eof updateState $ \st -> st{ synStPrevChar = '\n' } pEndLine return result startingState = SyntaxState {synStContexts = [("Modelines","Normal")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []} pEndLine = do updateState $ \st -> st{ synStPrevNonspace = False } context <- currentContext contexts <- synStContexts `fmap` getState st <- getState if length contexts >= 2 then case context of _ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False } ("Modelines","Normal") -> (popContext) >> pEndLine ("Modelines","Modeline") -> (popContext) >> pEndLine ("Modelines","Booleans") -> (popContext) >> pEndLine ("Modelines","Integrals") -> (popContext) >> pEndLine ("Modelines","Strings") -> (popContext) >> pEndLine ("Modelines","RemoveSpaces") -> (popContext) >> pEndLine _ -> return () else return () withAttribute attr txt = do when (null txt) $ fail "Parser matched no text" updateState $ \st -> st { synStPrevChar = last txt , synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) } return (attr, txt) list_ModelineStartKeyword = Set.fromList $ words $ "kate:" list_Booleans = Set.fromList $ words $ "auto-insert-doxygen automatic-spell-checking backspace-indents block-selection bookmark-sorting bom byte-order-marker dynamic-word-wrap folding-markers icon-border indent-pasted-text keep-extra-spaces line-numbers newline-at-eof overwrite-mode persistent-selection replace-tabs-save replace-tabs replace-trailing-space-save smart-home space-indent show-tabs show-trailing-spaces tab-indents word-wrap wrap-cursor" list_True = Set.fromList $ words $ "on true 1" list_False = Set.fromList $ words $ "off false 0" list_Integrals = Set.fromList $ words $ "auto-center-lines font-size indent-mode indent-width tab-width undo-steps word-wrap-column" list_Strings = Set.fromList $ words $ "background-color bracket-highlight-color current-line-color default-dictionary encoding eol end-of-line font hl icon-bar-color mode scheme selection-color syntax word-wrap-marker-color" list_RemoveSpaces = Set.fromList $ words $ "remove-trailing-spaces" list_RemoveSpacesOptions = Set.fromList $ words $ "0 - none modified mod + 1 all * 2" regex_kate'2d'28mimetype'7cwildcard'29'5c'28'2e'2a'5c'29'3a = compileRegex True "kate-(mimetype|wildcard)\\(.*\\):" regex_'5b'5e'3b_'5d = compileRegex True "[^; ]" parseRules ("Modelines","Normal") = (((pDetectSpaces >>= withAttribute CommentTok)) <|> ((pKeyword " \n\t.()!+,<=>%&*/;?[]^{|}~\\" list_ModelineStartKeyword >>= withAttribute KeywordTok) >>~ pushContext ("Modelines","Modeline")) <|> ((pRegExpr regex_kate'2d'28mimetype'7cwildcard'29'5c'28'2e'2a'5c'29'3a >>= withAttribute KeywordTok) >>~ pushContext ("Modelines","Modeline")) <|> ((pLineContinue >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Modelines","Normal")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Modelines","Modeline") = (((pDetectSpaces >>= withAttribute CommentTok)) <|> ((pKeyword " \n\t.()!+,<=>%&*/;?[]^{|}~\\" list_Booleans >>= withAttribute FunctionTok) >>~ pushContext ("Modelines","Booleans")) <|> ((pKeyword " \n\t.()!+,<=>%&*/;?[]^{|}~\\" list_Integrals >>= withAttribute FunctionTok) >>~ pushContext ("Modelines","Integrals")) <|> ((pKeyword " \n\t.()!+,<=>%&*/;?[]^{|}~\\" list_Strings >>= withAttribute FunctionTok) >>~ pushContext ("Modelines","Strings")) <|> ((pKeyword " \n\t.()!+,<=>%&*/;?[]^{|}~\\" list_RemoveSpaces >>= withAttribute FunctionTok) >>~ pushContext ("Modelines","RemoveSpaces")) <|> ((pLineContinue >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Modelines","Modeline")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Modelines","Booleans") = (((pDetectSpaces >>= withAttribute CommentTok)) <|> ((pKeyword " \n\t.()!+,<=>%&*/;?[]^{|}~\\" list_True >>= withAttribute OtherTok)) <|> ((pKeyword " \n\t.()!+,<=>%&*/;?[]^{|}~\\" list_False >>= withAttribute OtherTok)) <|> ((pDetectChar False ';' >>= withAttribute FunctionTok) >>~ (popContext)) <|> ((pLineContinue >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Modelines","Booleans")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Modelines","Integrals") = (((pDetectSpaces >>= withAttribute CommentTok)) <|> ((pInt >>= withAttribute DecValTok)) <|> ((pDetectChar False ';' >>= withAttribute FunctionTok) >>~ (popContext)) <|> ((pLineContinue >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Modelines","Integrals")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Modelines","Strings") = (((pDetectSpaces >>= withAttribute StringTok)) <|> ((pRegExpr regex_'5b'5e'3b_'5d >>= withAttribute StringTok)) <|> ((pDetectChar False ';' >>= withAttribute FunctionTok) >>~ (popContext)) <|> ((pLineContinue >>= withAttribute StringTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Modelines","Strings")) >> pDefault >>= withAttribute StringTok)) parseRules ("Modelines","RemoveSpaces") = (((pDetectSpaces >>= withAttribute CommentTok)) <|> ((pKeyword " \n\t.()!+,<=>%&*/;?[]^{|}~\\" list_RemoveSpacesOptions >>= withAttribute OtherTok) >>~ (popContext)) <|> ((pDetectChar False ';' >>= withAttribute FunctionTok) >>~ (popContext)) <|> ((pLineContinue >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Modelines","RemoveSpaces")) >> pDefault >>= withAttribute CommentTok)) parseRules x = parseRules ("Modelines","Normal") <|> fail ("Unknown context" ++ show x)
ambiata/highlighting-kate
Text/Highlighting/Kate/Syntax/Modelines.hs
gpl-2.0
7,207
0
16
1,103
1,848
996
852
124
9
-- -- riot/Riot/Riot/Version.hs -- -- Copyright (c) Tuomo Valkonen 2004-2005. -- -- 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. -- module Riot.Version where package = "riot" branch = "1" status = "ds" release = "20080618" version = branch++status++"-"++release
opqdonut/riot
Riot/Version.hs
gpl-2.0
472
0
7
81
53
35
18
6
1
module Macro.MetaMacro where import Types defineEnvironment :: String -> Note -> Note defineEnvironment name = liftL $ TeXEnv name [] comm2 :: LaTeXC l => String -> l -> l -> l comm2 name = liftL2 $ \l1 l2 -> TeXComm name [FixArg l1, FixArg l2] comm3 :: LaTeXC l => String -> l -> l -> l -> l comm3 name = liftL3 $ \l1 l2 l3 -> TeXComm name [FixArg l1, FixArg l2, FixArg l3] renewcommand :: LaTeXC l => String -> l -> l renewcommand l = comm2 "renewcommand" $ commS l renewcommand1 :: LaTeXC l => l -> l -> l renewcommand1 = liftL2 $ \l1 l2 -> TeXComm "renewcommand" [FixArg $ raw "\\" <> l1, OptArg "1", FixArg l2] -- Binary operation binop :: Note -> Note -> Note -> Note binop = between -- * Subscript -- | Safe Subscript (!:) :: Note -> Note -> Note x !: y = braces x <> raw "_" <> braces y -- | Prefix Subscript Operator subsc :: Note -> Note -> Note subsc = (!:) -- | Unsafe (in the first argument) Subscript. (.!:) :: LaTeXC l => l -> l -> l x .!: y = x <> raw "_" <> braces y -- * Superscript -- | Superscript (^:) :: Note -> Note -> Note x ^: y = braces x <> raw "^" <> braces y -- | Prefix Superscript Operator supsc :: Note -> Note -> Note supsc = (^:) -- | Unsafe (in the first argument) Superscript. (.^:) :: LaTeXC l => l -> l -> l x .^: y = x <> raw "^" <> braces y -- * Comprehensions compr :: Note -> Note -> Note -> Note -> Note compr sign lower upper content = sign .!: lower .^: upper <> braces content comp :: Note -> Note -> Note -> Note comp sign lower content = braces (sign .!: braces lower) <> braces content
NorfairKing/the-notes
src/Macro/MetaMacro.hs
gpl-2.0
1,568
0
11
361
629
323
306
30
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RecursiveDo, RankNTypes #-} {-# LANGUAGE Arrows #-} module Game where import Keyboard (keyDownEvents, Key( .. )) import Types import SignalUtils import Vector import Random import Event import Enemy (enemiesInit, enemiesStep) import Player (playerInit, playerStep) --import FRP.Elerea.Param import Control.Applicative import Data.Traversable (sequenceA) import Control.Monad.IO.Class (liftIO) import Data.Time.Clock (NominalDiffTime) import Control.Monad.State import Control.Monad.Identity import Control.Auto --DEBUG SHIT KILL LATER import GHC.Stack (errorWithStackTrace) import System.Random (Random, random, randomR) instance Random Key where random g = let (i,g') = randomR (0,3) g in ([UpKey,DownKey,LeftKey,RightKey] !! i, g') randomR _ g = random g data GameState = GameState{ player :: !Player, enemies :: !Enemies } gameInit = GameState playerInit enemiesInit rkey :: Rand Key rkey = fmap ([UpKey,DownKey,LeftKey,RightKey] !!) $ range (0,3) newGame = undefined --stepGame :: Auto m (inputs ...) GameState stepGame :: Arrow a => a b b stepGame = proc x -> do returnA -< x where player = accum (\p (dt,e) -> playerStep dt e p) playerInit enemies = accum (\n (t,p,e) -> enemiesStep t p e n) enemiesInit --hits = arr getHits --attacks = arr (\(keys, p, n) -> getAttacks keys p n) {- type Lens a b = forall f. Functor f => (b -> f b) -> a -> f a class Embed s where lens :: Lens GameState s view :: Lens a b -> a -> b view l = getConst . l Const set :: Lens a b -> a -> b -> a set l = l const hoistState :: Lens s s' -> (forall a . State s' a -> State s a) hoistState l = \x -> StateT $ \g -> let (result, x') = runState x (view l g) in Identity (result, set l g x') -} --hoist :: Auto (State s') a b -> Auto (State s) a b --hoist = hoistA (hoistState lens) --stepGame :: Auto (State GameState) a GameState --stepGame = undefined {- {- proc (inputs ...) -> do where -} --State s t "=" s -> ((),s) --playerStep "::" Time -> Events -> State Player () -- playerAuto :: Auto (State Player) (Time,Events) () -- playerLens :: Lens GameState Player -- hoistA (hoistState playerLens) :: Auto (State Player) a b -> Auto (State GameState) a b -- hoistA (hoistState playerLens) playerAuto :: Auto (State GameState) (Time, Events) () --transferAuto :: (a -> b -> b) -> Auto m {- rkeys :: Signal (Rand [Key]) rkeys = pure . fmap pure $ rkey --Arguments: game step resolution, game seed newGame :: NominalDiffTime -> Int -> SignalGen p (Signal GameState) newGame dt seed = do gameStep <- execute $ start (game seed) t <- timeTicks dt r <- effectful1 (stepIf gameStep) t accumMaybes gameInit r where stepIf f b = if b then fmap Just (f $ 1000 * realToFrac dt) else return Nothing game :: Int -> SignalGen Time (Signal GameState) game seed = mdo let rng = mkStdGen seed player <- transfer playerInit playerStep events enemies <- transfer2 enemiesInit enemiesStep player events keys <- evalRandomSignal rng rkeys -- keyDownEvents [UpKey,DownKey,LeftKey,RightKey,SpaceKey] spawns <- evalRandomSignal rng =<< liftA2 spawnWhen (every 500) (pure player) let attacks = getAttacks <$> keys <*> player <*> enemies hits = getHits <$> player -- debug <- transfer [] debugfun keys events <- delay eventsInit . fmap concat . sequenceA $ [ attacks , spawns , hits -- , debug ] sfx <- transfer3 sfxInit sfxStep player enemies events memo $ liftA3 GameState player enemies sfx debugfun :: Time -> [Key] -> [Event] -> [Event] debugfun t ks es = if SpaceKey `elem` ks then errorWithStackTrace "boop" else [] randomPosition :: Rand Position randomPosition = Vec2 <$> range (-1000,1000) <*> range (-1000,1000) isOut :: Player -> Position -> Bool isOut Player{zoneRadius=r,ppos=p} here = distance p here > r spawnWhen :: Signal Bool -> Signal Player -> Signal (Rand [Event]) spawnWhen s p = f <$> s <*> p where f True p = (\pos -> if isOut p pos then [SpawnEnemy pos] else []) <$> (randomPosition) f False p = pure [] -}
ZSarver/DungeonDash
src/Game.hs
gpl-3.0
4,149
1
11
887
431
257
174
38
1
module Declare.Workspace where import Declare.Layout import Types data Workspace = Workspace { spLayout :: Layout Pix TileRef , spStartTile :: TileRef } deriving (Eq, Ord, Show)
ktvoelker/argon
src/Declare/Workspace.hs
gpl-3.0
191
0
9
39
55
32
23
7
0
---------------------------------------------------------------------- -- | -- Module : Text.TeX.Context -- Copyright : 2015-2017 Mathias Schenner, -- 2015-2016 Language Science Press. -- License : GPL-3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC -- -- Types and functions for traversing TeX structures ---------------------------------------------------------------------- module Text.TeX.Context ( -- * Errors TeXDocError(..) , ThrowsError -- * Contexts , TeXContext , Context(..) -- * Parsers -- ** Types , Parser , runParser , runParserWithState -- * Parser State , getMeta , putMeta , modifyMeta -- ** Combinators , choice , count , sepBy , sepBy1 , sepEndBy , sepEndBy1 , list -- ** Commands , cmd , inCmd , inCmd2 , inCmd3 , inCmdOpt2 , inCmdCheckStar , inCmdWithOpts -- ** Groups , grp , inGrp , inGrpChoice , inMathGrp , inSubScript , inSupScript , grpDown , grpUnwrap , optNested -- ** Low-level parsers , eof , satisfy , dropParents ) where import Text.TeX.Context.Types import Text.TeX.Context.Walk
synsem/texhs
src/Text/TeX/Context.hs
gpl-3.0
1,207
0
5
301
161
116
45
40
0
import qualified NS3473.Rebars as R import qualified NS3473.Concrete as M import qualified NS3473.Walls as W import qualified NS3473.Buckling as X rebar12 = R.Rebar 12 rebar10 = R.Rebar 10 rebar = R.DoubleWallRebars rebar12 100 rebar10 100 40 conc = M.newConc "35" wall = W.Wall 200 2400 conc rebar W.External 1.0 ic = X.ic wall minrar = W.minHorizRebars wall
baalbek/ns3473wall
demo/demo1.hs
gpl-3.0
368
0
6
65
123
69
54
11
1
{- Implementation of BST (binary search tree) Script is absolutly free/libre, but with no guarantee. Author: Ondrej Profant -} import qualified Data.List {- DEF data structure -} data (Ord a, Eq a) => Tree a = Nil | Node (Tree a) a (Tree a) deriving Show {- BASIC Information -} empty :: (Ord a) => Tree a -> Bool empty Nil = True empty _ = False contains :: (Ord a) => (Tree a) -> a -> Bool contains Nil _ = False contains (Node t1 v t2) x | x == v = True | x < v = contains t1 x | x > v = contains t2 x {- BASIC Manipulation -} insert :: (Ord a) => Tree a -> a -> Tree a insert Nil x = Node Nil x Nil insert (Node t1 v t2) x | v == x = Node t1 v t2 | v < x = Node t1 v (insert t2 x) | v > x = Node (insert t1 x) v t2 delete :: (Ord a) => Tree a -> a -> Tree a delete Nil _ = Nil delete (Node t1 v t2) x | x == v = deleteX (Node t1 v t2) | x < v = Node (delete t1 x) v t2 | x > v = Node t1 v (delete t2 x) -- Delete root (is used on subtree) deleteX :: (Ord a) => Tree a -> Tree a deleteX (Node Nil v t2) = t2 deleteX (Node t1 v Nil) = t1 deleteX (Node t1 v t2) = (Node t1 v2 t2) --(delete t2 v2)) where v2 = leftistElement t2 -- Return leftist element of tree (is used on subtree) leftistElement :: (Ord a) => Tree a -> a leftistElement (Node Nil v _) = v leftistElement (Node t1 _ _) = leftistElement t1 -- Create tree from list of elemtents ctree :: (Ord a) => [a] -> Tree a ctree [] = Nil ctree (h:t) = ctree2 (Node Nil h Nil) t where ctree2 tr [] = tr ctree2 tr (h:t) = ctree2 (insert tr h) t -- Create perfect balance BST ctreePB :: (Ord a) => [a] -> Tree a ctreePB [] = Nil ctreePB s = cpb Nil (qsort s) cpb :: (Ord a) => Tree a -> [a] -> Tree a cpb tr [] = tr cpb tr t = cpb (insert tr e) t2 where e = middleEl t t2 = Data.List.delete e t -- Element in middle middleEl :: (Ord a) => [a] -> a middleEl s = mEl s s mEl :: (Ord a) => [a] -> [a] -> a mEl [] (h:s2) = h mEl (_:[]) (h:s2) = h mEl (_:_:s1) (_:s2) = mEl s1 s2 {- PRINT -} inorder :: (Ord a) => Tree a -> [a] inorder Nil = [] inorder (Node t1 v t2) = inorder t1 ++ [v] ++ inorder t2 preorder :: (Ord a) => Tree a -> [a] preorder Nil = [] preorder (Node t1 v t2) = [v] ++ preorder t1 ++ preorder t2 postorder :: (Ord a) => Tree a -> [a] postorder Nil = [] postorder (Node t1 v t2) = postorder t1 ++ postorder t2 ++ [v] -- from wiki levelorder :: (Ord a) => Tree a -> [a] levelorder t = step [t] where step [] = [] step ts = concatMap elements ts ++ step (concatMap subtrees ts) elements Nil = [] elements (Node left x right) = [x] subtrees Nil = [] subtrees (Node left x right) = [left,right] qsort :: (Ord a) => [a] -> [a] qsort [] = [] qsort (h:t) = (qsort [x| x<-t, x < h]) ++ [h] ++ (qsort [x| x<-t, x>=h ])
Kedrigern/example-projects
haskell/bst.hs
gpl-3.0
2,762
12
10
709
1,463
754
709
71
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.ElasticBeanstalk.RequestEnvironmentInfo -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Initiates a request to compile the specified type of information of the -- deployed environment. -- -- Setting the 'InfoType' to 'tail' compiles the last lines from the application -- server log files of every Amazon EC2 instance in your environment. Use 'RetrieveEnvironmentInfo' to access the compiled information. -- -- Related Topics -- -- 'RetrieveEnvironmentInfo' -- -- <http://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_RequestEnvironmentInfo.html> module Network.AWS.ElasticBeanstalk.RequestEnvironmentInfo ( -- * Request RequestEnvironmentInfo -- ** Request constructor , requestEnvironmentInfo -- ** Request lenses , reiEnvironmentId , reiEnvironmentName , reiInfoType -- * Response , RequestEnvironmentInfoResponse -- ** Response constructor , requestEnvironmentInfoResponse ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.ElasticBeanstalk.Types import qualified GHC.Exts data RequestEnvironmentInfo = RequestEnvironmentInfo { _reiEnvironmentId :: Maybe Text , _reiEnvironmentName :: Maybe Text , _reiInfoType :: EnvironmentInfoType } deriving (Eq, Read, Show) -- | 'RequestEnvironmentInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'reiEnvironmentId' @::@ 'Maybe' 'Text' -- -- * 'reiEnvironmentName' @::@ 'Maybe' 'Text' -- -- * 'reiInfoType' @::@ 'EnvironmentInfoType' -- requestEnvironmentInfo :: EnvironmentInfoType -- ^ 'reiInfoType' -> RequestEnvironmentInfo requestEnvironmentInfo p1 = RequestEnvironmentInfo { _reiInfoType = p1 , _reiEnvironmentId = Nothing , _reiEnvironmentName = Nothing } -- | The ID of the environment of the requested data. -- -- If no such environment is found, 'RequestEnvironmentInfo' returns an 'InvalidParameterValue' error. -- -- Condition: You must specify either this or an EnvironmentName, or both. If -- you do not specify either, AWS Elastic Beanstalk returns 'MissingRequiredParameter' error. reiEnvironmentId :: Lens' RequestEnvironmentInfo (Maybe Text) reiEnvironmentId = lens _reiEnvironmentId (\s a -> s { _reiEnvironmentId = a }) -- | The name of the environment of the requested data. -- -- If no such environment is found, 'RequestEnvironmentInfo' returns an 'InvalidParameterValue' error. -- -- Condition: You must specify either this or an EnvironmentId, or both. If -- you do not specify either, AWS Elastic Beanstalk returns 'MissingRequiredParameter' error. reiEnvironmentName :: Lens' RequestEnvironmentInfo (Maybe Text) reiEnvironmentName = lens _reiEnvironmentName (\s a -> s { _reiEnvironmentName = a }) -- | The type of information to request. reiInfoType :: Lens' RequestEnvironmentInfo EnvironmentInfoType reiInfoType = lens _reiInfoType (\s a -> s { _reiInfoType = a }) data RequestEnvironmentInfoResponse = RequestEnvironmentInfoResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'RequestEnvironmentInfoResponse' constructor. requestEnvironmentInfoResponse :: RequestEnvironmentInfoResponse requestEnvironmentInfoResponse = RequestEnvironmentInfoResponse instance ToPath RequestEnvironmentInfo where toPath = const "/" instance ToQuery RequestEnvironmentInfo where toQuery RequestEnvironmentInfo{..} = mconcat [ "EnvironmentId" =? _reiEnvironmentId , "EnvironmentName" =? _reiEnvironmentName , "InfoType" =? _reiInfoType ] instance ToHeaders RequestEnvironmentInfo instance AWSRequest RequestEnvironmentInfo where type Sv RequestEnvironmentInfo = ElasticBeanstalk type Rs RequestEnvironmentInfo = RequestEnvironmentInfoResponse request = post "RequestEnvironmentInfo" response = nullResponse RequestEnvironmentInfoResponse
dysinger/amazonka
amazonka-elasticbeanstalk/gen/Network/AWS/ElasticBeanstalk/RequestEnvironmentInfo.hs
mpl-2.0
4,864
0
9
930
481
298
183
58
1
{-# LANGUAGE InstanceSigs #-} module IdentityT where import Control.Monad (join) newtype Identity a = Identity { runIdentity :: a } deriving (Eq, Show) newtype IdentityT f a = IdentityT { runIdentityT :: f a } deriving (Eq, Show) instance Functor Identity where fmap f (Identity a) = Identity (f a) instance (Functor m) => Functor (IdentityT m) where fmap f (IdentityT fa) = IdentityT (fmap f fa) instance Applicative Identity where pure = Identity (Identity f) <*> (Identity a) = Identity (f a) instance (Applicative m) => Applicative (IdentityT m) where pure x = IdentityT (pure x) (IdentityT fab) <*> (IdentityT fa) = IdentityT (fab <*> fa) instance Monad Identity where return = pure (Identity a) >>= f = f a instance (Monad m) => Monad (IdentityT m) where return = pure (>>=) :: IdentityT m a -> (a -> IdentityT m b) -> IdentityT m b (IdentityT ma) >>= f = IdentityT $ ma >>= runIdentityT . f
dmvianna/haskellbook
src/Ch25-IdentityT.hs
unlicense
962
7
12
223
402
207
195
30
0
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QInputContext.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:36 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Enums.Gui.QInputContext ( StandardFormat, ePreeditFormat, eSelectionFormat ) where import Foreign.C.Types import Qtc.Classes.Base import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr) import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int) import Qtc.Enums.Base import Qtc.Enums.Classes.Core data CStandardFormat a = CStandardFormat a type StandardFormat = QEnum(CStandardFormat Int) ieStandardFormat :: Int -> StandardFormat ieStandardFormat x = QEnum (CStandardFormat x) instance QEnumC (CStandardFormat Int) where qEnum_toInt (QEnum (CStandardFormat x)) = x qEnum_fromInt x = QEnum (CStandardFormat x) withQEnumResult x = do ti <- x return $ qEnum_fromInt $ fromIntegral ti withQEnumListResult x = do til <- x return $ map qEnum_fromInt til instance Qcs (QObject c -> StandardFormat -> IO ()) where connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler = do funptr <- wrapSlotHandler_int slotHandlerWrapper_int stptr <- newStablePtr (Wrap _handler) withObjectPtr _qsig_obj $ \cobj_sig -> withCWString _qsig_nam $ \cstr_sig -> withObjectPtr _qslt_obj $ \cobj_slt -> withCWString _qslt_nam $ \cstr_slt -> qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr) return () where slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO () slotHandlerWrapper_int funptr stptr qobjptr cint = do qobj <- qObjectFromPtr qobjptr let hint = fromCInt cint if (objectIsNull qobj) then do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) else _handler qobj (qEnum_fromInt hint) return () ePreeditFormat :: StandardFormat ePreeditFormat = ieStandardFormat $ 0 eSelectionFormat :: StandardFormat eSelectionFormat = ieStandardFormat $ 1
keera-studios/hsQt
Qtc/Enums/Gui/QInputContext.hs
bsd-2-clause
2,471
0
18
521
596
303
293
52
1
-- -- Copyright © 2014-2015 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- -- | Description: Run /Synchronise/ as a server. module Synchronise.Program.Daemon where import System.Log.Logger import Synchronise.Configuration import Synchronise.Network.Server -- | Start the synchronise daemon. synchronise :: Configuration -> IO () synchronise cfg = do let (_, pri, _) = configServer cfg updateGlobalLogger rootLoggerName (setLevel pri) spawnServer cfg 1
anchor/synchronise
lib/Synchronise/Program/Daemon.hs
bsd-3-clause
690
0
10
128
100
57
43
11
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} module Api.Admin.UserAdmin ( UserAdminApi , userAdminHandlers ) where import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Char8 as B import Data.Pool (Pool, withResource) import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.Types (Query (..)) import Servant import Servant.Server.Experimental.Auth.Cookie import Api.Errors (appJson404) import Api.Login import Api.Types (ResultResp(..)) import Models.Author (Author (..)) import Types type UserAdminApi = "admin" :> "user" :> AuthProtect "cookie-auth" :> Get '[JSON] [Author] :<|> "admin" :> "user" :> Capture "id" Int :> AuthProtect "cookie-auth" :> Get '[JSON] Author :<|> "admin" :> "user" :> ReqBody '[JSON] Author :> AuthProtect "cookie-auth" :> Post '[JSON] Author :<|> "admin" :> "user" :> Capture "id" Int :> ReqBody '[JSON] Author :> AuthProtect "cookie-auth" :> Put '[JSON] ResultResp :<|> "admin" :> "user" :> Capture "id" Int :> AuthProtect "cookie-auth" :> Delete '[JSON] ResultResp userAdminHandlers :: ServerT UserAdminApi SimpleHandler userAdminHandlers = getUsersH :<|> userDetailH :<|> userAddH :<|> userUpdateH :<|> userDeleteH getUsersH :: WithMetadata Username -> SimpleHandler [Author] getUsersH uname = runHandlerDbHelper $ \conn -> do let q = "select * from author" liftIO $ query_ conn q userDetailH :: Int -> WithMetadata Username -> SimpleHandler Author userDetailH userId uname = runHandlerDbHelper $ \conn -> do let q = "select * from author where id = ?" res <- liftIO $ query conn q (Only userId) case res of (x:_) -> return x _ -> throwError $ appJson404 "Unknown author" userAddH :: Author -> WithMetadata Username -> SimpleHandler Author userAddH newAuthor uname = runHandlerDbHelper $ \conn -> do let q = "insert into author (firstname, lastname) values (?, ?) returning id" res <- liftIO $ query conn q (firstName newAuthor , lastName newAuthor) :: SimpleHandler [Only Int] case res of [] -> throwError err400 (uid:_) -> do author <- liftIO $ query conn "select * from author where id = ?" uid if null author then throwError err400 else return $ Prelude.head author userUpdateH :: Int -> Author -> WithMetadata Username -> SimpleHandler ResultResp userUpdateH userId author uname = runHandlerDbHelper $ \conn -> do let q = Query $ B.unwords ["update author set firstname = ?, lastname = ? " , "where id = ?"] result <- liftIO $ execute conn q (firstName author , lastName author , aid author) case result of 0 -> throwError err400 _ -> return $ ResultResp "success" "user updated" userDeleteH :: Int -> WithMetadata Username -> SimpleHandler ResultResp userDeleteH authorId uname = runHandlerDbHelper $ \conn -> do let q = "delete from author where id = ?" result <- liftIO $ execute conn q (Only authorId) case result of 0 -> throwError err400 _ -> return $ ResultResp "success" "user deleted"
pellagic-puffbomb/simpleservantblog
src/Api/Admin/UserAdmin.hs
bsd-3-clause
3,471
0
31
997
931
473
458
67
3
-- | A type lattice for Python 3. module Language.Python.TypeInference.Analysis.TypeLattice ( UnionType (..), ValueType (..), BuiltinType (..), FunctionType (..), ClassType (..), InstanceType (..), HasClassId (..), Env, nabla, check, AType (..), oneType, filterType, filterOr, isBuiltin, isFunction, isClass, isInstance, orInstance, isNum, isIntegral, isSequence, isTuple, isList, allTypes, updateType, applyFunctionType ) where import Control.DeepSeq import Control.Monad (zipWithM) import Data.List (groupBy, intercalate, partition, sortBy) import Data.Map (Map) import Data.Maybe (catMaybes, fromMaybe, isNothing) import Data.Ord (comparing) import Data.Set (Set) import Language.Analysis.DFA.Lattice import Language.Python.TypeInference.Common import Text.Printf import qualified Data.Map as Map import qualified Data.Set as Set -- | Union type: models types of variables. data UnionType = -- | A set of types that the variable may have. UTy (Set ValueType) -- | Top element: we don't know anything about the type. | UTyTop -- | Type variable. Only to be used within function types ('FunTy'). | TypeVariable String deriving (Eq, Ord) instance NFData UnionType where rnf (UTy s) = rnf $ Set.toList s rnf UTyTop = () rnf (TypeVariable v) = rnf v -- | Value type: models types that values can have at runtime. data ValueType = BuiltinType BuiltinType | FunctionType FunctionType | ClassType ClassType | InstanceType InstanceType deriving (Eq, Ord) instance NFData ValueType where rnf (BuiltinType t) = rnf t rnf (FunctionType t) = rnf t rnf (ClassType t) = rnf t rnf (InstanceType t) = rnf t -- | Builtin Python type. See section 3.2 of the language reference. data BuiltinType = NoneType | NotImplementedType | EllipsisType | IntType | BoolType | FloatType | ComplexType | StrType | BytesType | BytearrayType -- unparameterized collection types | TupleType | ListType | SetType | FrozensetType | DictType -- parameterized collection types | TupleOf [UnionType] | ListOf UnionType | SetOf UnionType | FrozensetOf UnionType | DictOf UnionType UnionType deriving (Eq, Ord) instance NFData BuiltinType where rnf bt = case bt of (TupleOf ts) -> rnf ts (ListOf t) -> rnf t (SetOf t) -> rnf t (FrozensetOf t) -> rnf t (DictOf k v) -> rnf (k, v) _ -> () -- | Function type. data FunctionType = -- | Function id identifying a function in the code under analysis. FunId FunctionId -- | Function type with types of arguments and type of return value. | FunTy [UnionType] UnionType deriving (Eq, Ord) instance NFData FunctionType where rnf (FunId i) = rnf i rnf (FunTy a r) = rnf (a, r) -- | Class type. data ClassType = -- | Class with class id, superclasses and class attributes. ClsTy ClassId [ClassType] Env | -- | Reference to a global class type, used when class types -- are flow-insensitive. ClsRef ClassId deriving (Eq, Ord) instance NFData ClassType where rnf (ClsTy t sup e) = rnf (t, sup, Map.toList e) rnf (ClsRef i) = rnf i -- | Class instance type. data InstanceType = -- | Instance with class and instance attributes. InstTy ClassType Env | -- | Reference to a global instance type, used when -- instance types are flow-insensitive. InstRef ClassId deriving (Eq, Ord) instance NFData InstanceType where rnf (InstTy t e) = rnf (t, Map.toList e) rnf (InstRef i) = rnf i -- | Type class for types from which a class id can be extracted. class HasClassId a where getClassId :: a -> ClassId instance HasClassId ClassType where getClassId (ClsTy classId _ _) = classId getClassId (ClsRef classId) = classId instance HasClassId InstanceType where getClassId (InstTy classType _) = getClassId classType getClassId (InstRef classId) = classId -- | An environment, eg, the attributes of a class or object. type Env = Map String UnionType instance Lattice UnionType where bot = UTy Set.empty join UTyTop _ = UTyTop join _ UTyTop = UTyTop join (UTy a) (UTy b) = joinTypes $ Set.toList (a `Set.union` b) join a b = error $ "cannot join types " ++ show a ++ " and " ++ show b joinTypes :: [ValueType] -> UnionType joinTypes types = let joinClasses l = map (ClassType . foldl1 mergeClassTypes) (groupByClassId [t | ClassType t <- l]) joinInstances l = map (InstanceType . foldl1 mergeInstanceTypes) (groupByClassId [t | InstanceType t <- l]) isTupleOf (BuiltinType (TupleOf _)) = True isTupleOf _ = False isTuple (BuiltinType (TupleOf _)) = True isTuple (BuiltinType TupleType) = True isTuple _ = False joinTuples l = if all isTupleOf l then map (BuiltinType . foldl1 mergeTupleTypes) (groupByTupleSize [t | BuiltinType t <- l]) else [BuiltinType TupleType] isListOf (BuiltinType (ListOf _)) = True isListOf _ = False joinListOfTypes ts = [BuiltinType $ ListOf $ joinAll [t | BuiltinType (ListOf t) <- ts]] isSetOf (BuiltinType (SetOf _)) = True isSetOf _ = False joinSetOfTypes ts = [BuiltinType $ SetOf $ joinAll [t | BuiltinType (SetOf t) <- ts]] isFrozensetOf (BuiltinType (FrozensetOf _)) = True isFrozensetOf _ = False joinFrozensetOfTypes ts = [BuiltinType $ FrozensetOf $ joinAll [t | BuiltinType (FrozensetOf t) <- ts]] isDictOf (BuiltinType (DictOf _ _)) = True isDictOf _ = False joinDictOfTypes ts = [BuiltinType $ DictOf (joinAll [t | BuiltinType (DictOf t _) <- ts]) (joinAll [t | BuiltinType (DictOf _ t) <- ts])] pairs = [ (isClass, joinClasses) , (isInstance, joinInstances) , (isTuple, joinTuples) , (isListOf, joinListOfTypes) , (isSetOf, joinSetOfTypes) , (isFrozensetOf, joinFrozensetOfTypes) , (isDictOf, joinDictOfTypes) ] in UTy $ Set.fromList (splitAndMerge pairs types) splitAndMerge :: [(a -> Bool, [a] -> [a])] -> [a] -> [a] splitAndMerge _ [] = [] splitAndMerge [] l = l splitAndMerge ((p, f) : pairs) l = let (yes, no) = partition p l current = if null yes then [] else f yes in current ++ splitAndMerge pairs no -- | Group a list of class or instance types by class id. groupByClassId :: HasClassId a => [a] -> [[a]] groupByClassId list = let sorted = sortBy (comparing getClassId) list in groupBy (\a b -> getClassId a == getClassId b) sorted -- | Group a list of 'TupleOf' types by tuple size. groupByTupleSize :: [BuiltinType] -> [[BuiltinType]] groupByTupleSize list = let sorted = sortBy (comparing (\(TupleOf l) -> length l)) list in groupBy (\(TupleOf a) (TupleOf b) -> length a == length b) sorted -- | Merge two class types that refer to the same class. mergeClassTypes :: ClassType -> ClassType -> ClassType mergeClassTypes (ClsRef classId) _ = ClsRef classId mergeClassTypes _ (ClsRef classId) = ClsRef classId mergeClassTypes (ClsTy classId s1 e1) (ClsTy _ s2 e2) = ClsTy classId (mergeSuperClasses s1 s2) (mergeEnv e1 e2) -- | Merge two instance types that refer to the same class. mergeInstanceTypes :: InstanceType -> InstanceType -> InstanceType mergeInstanceTypes (InstRef classId) _ = InstRef classId mergeInstanceTypes _ (InstRef classId) = InstRef classId mergeInstanceTypes (InstTy c1 e1) (InstTy c2 e2) = InstTy (mergeClassTypes c1 c2) (mergeEnv e1 e2) mergeSuperClasses :: [ClassType] -> [ClassType] -> [ClassType] mergeSuperClasses sup [] = sup mergeSuperClasses [] sup = sup mergeSuperClasses (a:as) (b:bs) | getClassId a == getClassId b = mergeClassTypes a b : mergeSuperClasses as bs | otherwise = a : mergeSuperClasses as (b:bs) mergeEnv :: Env -> Env -> Env mergeEnv = Map.unionWith join -- | Merge two tuple types with the same size (number of elements). mergeTupleTypes :: BuiltinType -> BuiltinType -> BuiltinType mergeTupleTypes (TupleOf a) (TupleOf b) = TupleOf (zipWith join a b) -- | Widening operator: joins two 'UnionType's and jumps to 'UTyTop' if the -- result is too large. Parameterized with three numbers /n/, /m/ and /o/, -- where /n/ is the maximum size of a set of types, /m/ is the maximum nesting -- depth and /o/ is the maximum number of attributes of a class or object. nabla :: Int -> Int -> Int -> UnionType -> UnionType -> UnionType nabla n m o t1 t2 = limitUnionType n m o (t1 `join` t2) -- | Limit the size of a union type; return 'UTyTop' if it is too large. The -- parameters are the same as for 'nabla'. limitUnionType :: Int -> Int -> Int -> UnionType -> UnionType limitUnionType _ _ 0 _ = UTyTop limitUnionType _ _ _ UTyTop = UTyTop limitUnionType n m o (UTy s) | Set.size s > n = UTyTop | otherwise = maybe UTyTop UTy (do let l = Set.toList s l' <- mapM (limitValueType n m (o-1)) l return $ Set.fromList l') -- | Limit the size of a value type; return 'Nothing' if it is too large. The -- parameters are the same as for 'nabla'. limitValueType :: Int -> Int -> Int -> ValueType -> Maybe ValueType limitValueType _ _ 0 _ = Nothing limitValueType n m o t = case t of BuiltinType (TupleOf l) -> if length l > o then Just $ BuiltinType TupleType else Just $ BuiltinType $ TupleOf $ map lu l BuiltinType (ListOf u) -> Just $ BuiltinType $ ListOf (lu u) BuiltinType (SetOf u) -> Just $ BuiltinType $ SetOf (lu u) BuiltinType (FrozensetOf u) -> Just $ BuiltinType $ FrozensetOf (lu u) BuiltinType (DictOf k v) -> Just $ BuiltinType $ DictOf (lu k) (lu v) ClassType c -> do c' <- limitClassType n m o c return $ ClassType c' InstanceType (InstTy cls env) | Map.size env > o -> Nothing | otherwise -> do cls' <- limitClassType n m (o-1) cls let env' = Map.map lu env return $ InstanceType (InstTy cls' env') _ -> Just t where lu = limitUnionType n m (o - 1) -- | Limit the size of a class type; return 'Nothing' if it is too large. The -- parameters are the same as for 'nabla'. limitClassType :: Int -> Int -> Int -> ClassType -> Maybe ClassType limitClassType _ _ _ (ClsRef classId) = Just $ ClsRef classId limitClassType n m o (ClsTy classId sup env) | length sup > o = Nothing | Map.size env > o = Nothing | otherwise = do sup' <- mapM (limitClassType n m (o-1)) sup let env' = Map.map (limitUnionType n m (o-1)) env return $ ClsTy classId sup' env' instance Show UnionType where show (UTy ts) | Set.null ts = "bot" | otherwise = "{" ++ commas (Set.toAscList ts) ++ "}" show UTyTop = "top" show (TypeVariable a) = '!' : a instance Read UnionType where readsPrec _ r = case lex r of [("!", r1)] -> case lex r1 of [(a, r2)] -> [(TypeVariable a, r2)] _ -> [] [("bot", r1)] -> [(UTy Set.empty, r1)] [("top", r1)] -> [(UTyTop, r1)] [("{", r1)] -> case (readCommaList :: ReadS [ValueType]) r1 of [(ts, r2)] -> case lex r2 of [("}", r3)] -> [(UTy (Set.fromList ts), r3)] _ -> [] _ -> [] _ -> [] readCommaList :: Read a => ReadS [a] readCommaList = readSimpleList "," readSemicolonList :: Read a => ReadS [a] readSemicolonList = readSimpleList ";" readSimpleList :: Read a => String -> ReadS [a] readSimpleList sep r = case reads r of [(t, r1)] -> case lex r1 of [(token, r2)] | token == sep -> case readSimpleList sep r2 of [(ts, r3)] -> [(t : ts, r3)] _ -> [] _ -> [([t], r1)] _ -> [([], r)] instance Show ValueType where show (BuiltinType t) = show t show (FunctionType t) = show t show (ClassType t) = show t show (InstanceType t) = show t instance Read ValueType where readsPrec _ r = case (reads :: ReadS BuiltinType) r of [(t, r')] -> [(BuiltinType t, r')] _ -> case (reads :: ReadS FunctionType) r of [(t, r')] -> [(FunctionType t, r')] _ -> case (reads :: ReadS ClassType) r of [(t, r')] -> [(ClassType t, r')] _ -> case (reads :: ReadS InstanceType) r of [(t, r')] -> [(InstanceType t, r')] _ -> [] instance Show BuiltinType where show NotImplementedType = "NotImplementedType" show NoneType = "NoneType" show EllipsisType = "ellipsis" show IntType = "int" show BoolType = "bool" show FloatType = "float" show ComplexType = "complex" show StrType = "str" show BytesType = "bytes" show BytearrayType = "bytearray" show TupleType = "tuple" show ListType = "list" show SetType = "set" show FrozensetType = "frozenset" show DictType = "dict" show (TupleOf ts) = "tuple<" ++ intercalate "; " (map show ts) ++ ">" show (ListOf t) = "list<" ++ show t ++ ">" show (SetOf t) = "set<" ++ show t ++ ">" show (FrozensetOf t) = "frozenset<" ++ show t ++ ">" show (DictOf k v) = "dict<" ++ show k ++ "; " ++ show v ++ ">" instance Read BuiltinType where readsPrec _ r = case lex r of [("NotImplementedType", r')] -> [(NotImplementedType, r')] [("NoneType", r')] -> [(NoneType, r')] [("ellipsis", r')] -> [(EllipsisType, r')] [("int", r')] -> [(IntType, r')] [("bool", r')] -> [(BoolType, r')] [("float", r')] -> [(FloatType, r')] [("complex", r')] -> [(ComplexType, r')] [("str", r')] -> [(StrType, r')] [("bytes", r')] -> [(BytesType, r')] [("bytearray", r')] -> [(BytearrayType, r')] [("tuple", r')] -> case readOfList r' of [(ts, r2)] -> [(TupleOf ts, r2)] _ -> [(TupleType, r')] [("list", r')] -> parameterized ListType ListOf r' [("set", r')] -> parameterized SetType SetOf r' [("frozenset", r')] -> parameterized FrozensetType FrozensetOf r' [("dict", r')] -> case readOfList r' of [([k, v], r2)] -> [(DictOf k v, r2)] _ -> [(DictType, r')] _ -> [] where parameterized :: BuiltinType -> (UnionType -> BuiltinType) -> ReadS BuiltinType parameterized bt bto r = case readOf r of [(t, r')] -> [(bto t, r')] _ -> [(bt, r)] readOf :: ReadS UnionType readOf r = case lex r of [("<", r1)] -> case (reads :: ReadS UnionType) r1 of [(t, r2)] -> case lex r2 of [(">", r3)] -> [(t, r3)] [] -> [] _ -> [] _ -> [] readOfList :: ReadS [UnionType] readOfList r = case lex r of [("<", r1)] -> case (readSemicolonList :: ReadS [UnionType]) r1 of [(ts, r2)] -> case lex r2 of [(">", r3)] -> [(ts, r3)] _ -> [] _ -> [] _ -> [] instance Show FunctionType where show (FunId i) = "fun" ++ show i show (FunTy a r) = "lamba " ++ commas a ++ " -> " ++ show r instance Read FunctionType where readsPrec _ r | r `startsWith` "fun" = let r1 = drop 3 r in case (reads :: ReadS Int) r1 of [(n, r2)] -> [(FunId n, r2)] _ -> [] | r `startsWith` "lambda " = let r1 = drop 7 r in case (readCommaList :: ReadS [UnionType]) r1 of [(argTypes, r2)] -> case lex r2 of [("->", r3)] -> case (reads :: ReadS UnionType) r3 of [(returnType, r4)] -> [(FunTy argTypes returnType, r4)] _ -> [] _ -> [] _ -> [] | otherwise = [] instance Show ClassType where show (ClsTy classId sup env) = printf "class<%d; %s; %s>" classId (show sup) (showMapping env) show (ClsRef classId) = printf "class<%d>" classId instance Read ClassType where readsPrec _ r = case lex r of [("class", r1)] -> case lex r1 of [("<", r2)] -> case (reads :: ReadS Int) r2 of [(classId, r3)] -> case lex r3 of [(">", r4)] -> [(ClsRef classId, r4)] [(";", r4)] -> case (reads :: ReadS [ClassType]) r4 of [(sup, r5)] -> case lex r5 of [(";", r6)] -> case readMapping r6 of [(attrs, r7)] -> case lex r7 of [(">", r8)] -> [(ClsTy classId sup attrs, r8)] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] instance Show InstanceType where show (InstTy cls env) = printf "inst<%s; %s>" (show cls) (showMapping env) show (InstRef classId) = printf "inst<%d>" classId instance Read InstanceType where readsPrec _ r = case lex r of [("inst", r1)] -> case lex r1 of [("<", r2)] -> case (reads :: ReadS Int) r2 of [(classId, r3)] -> case lex r3 of [(">", r4)] -> [(InstRef classId, r4)] _ -> [] _ -> case (reads :: ReadS ClassType) r2 of [(cls, r3)] -> case lex r3 of [(";", r4)] -> case readMapping r4 of [(attrs, r5)] -> case lex r5 of [(">", r6)] -> [(InstTy cls attrs, r6)] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] _ -> [] check :: (Read a, Show a, Eq a) => a -> Bool check a = a == read (show a) -- | Typeclass for types that describe a single Python type. class AType a where toValueType :: a -> ValueType instance AType ValueType where toValueType = id instance AType BuiltinType where toValueType = BuiltinType instance AType FunctionType where toValueType = FunctionType instance AType ClassType where toValueType = ClassType instance AType InstanceType where toValueType = InstanceType -- | Create a union type containing just one value type. oneType :: AType a => a -> UnionType oneType t = UTy $ Set.singleton $ toValueType t -- | Modify the given union type so that it only contains value types for which -- the predicate is true. filterType :: (ValueType -> Bool) -> UnionType -> UnionType filterType _ UTyTop = UTyTop filterType predicate (UTy s) = UTy $ Set.filter predicate s -- | Modify the given union type so that it only contains value types for which -- at least one of the predicates is true. filterOr :: [ValueType -> Bool] -> UnionType -> UnionType filterOr predicates = filterType (isAny predicates) -- | Is it an instance type? isInstance :: ValueType -> Bool isInstance (InstanceType _) = True isInstance _ = False -- | Is it a builtin type? isBuiltin :: ValueType -> Bool isBuiltin (BuiltinType _) = True isBuiltin _ = False -- | Is it a function type? isFunction :: ValueType -> Bool isFunction (FunctionType _) = True isFunction _ = False -- | Is it a class type? isClass :: ValueType -> Bool isClass (ClassType _) = True isClass _ = False -- | Modify the given predicate so that it is true for all instance types. orInstance :: (ValueType -> Bool) -> ValueType -> Bool orInstance f t = f t || isInstance t -- | Is it a built-in numeric type? isNum :: ValueType -> Bool isNum (BuiltinType t) = t `elem` [IntType, BoolType, FloatType, ComplexType] isNum _ = False -- | Is it a built-in integral type? isIntegral :: ValueType -> Bool isIntegral (BuiltinType t) = t `elem` [IntType, BoolType] isIntegral _ = False -- | Is it a built-in sequence type (string, tuple, list)? isSequence :: ValueType -> Bool isSequence (BuiltinType t) = case t of TupleOf _ -> True ListOf _ -> True _ -> t `elem` [StrType, TupleType, ListType] isSequence _ = False -- | Is it a tuple? isTuple :: ValueType -> Bool isTuple (BuiltinType TupleType) = True isTuple (BuiltinType (TupleOf _)) = True isTuple _ = False -- | Is it a list? isList :: ValueType -> Bool isList (BuiltinType ListType) = True isList (BuiltinType (ListOf _)) = True isList _ = False -- | Is any of the predicates true for the value? isAny :: [a -> Bool] -> a -> Bool isAny predicates value = or [p value | p <- predicates] -- | Check if the predicate holds for all value types in the union type. Always -- false for @UTyTop@. allTypes :: (ValueType -> Bool) -> UnionType -> Bool allTypes _ UTyTop = False allTypes p (UTy s) = all p (Set.toList s) -- | Apply the function to all value types in the union type and join the -- results. updateType :: (ValueType -> UnionType) -> UnionType -> UnionType updateType f (UTy s) = joinAll $ map f (Set.toList s) updateType _ t = t -- | Apply a function type ('FunTy') to a list of argument types. applyFunctionType :: [UnionType] -> UnionType -> [UnionType] -> UnionType applyFunctionType argTypes _ arguments | length argTypes /= length arguments = bot applyFunctionType argTypes returnType arguments = let match :: UnionType -> UnionType -> Maybe (Map String UnionType) match UTyTop _ = Just Map.empty match (TypeVariable a) t = Just $ Map.singleton a t match (UTy a) (UTy b) | Set.null (a `Set.intersection` b) = Just Map.empty match _ _ = Nothing in case zipWithM match argTypes arguments of Nothing -> bot Just matched -> fromMaybe bot (replace (Map.unions matched) returnType) class ReplaceVariables a where replace :: Map String UnionType -> a -> Maybe a instance ReplaceVariables UnionType where replace _ UTyTop = Just UTyTop replace m (TypeVariable a) = Map.lookup a m replace m (UTy s) = case mapM (replace m) (Set.toList s) of Nothing -> Nothing Just l -> Just $ UTy $ Set.fromList l instance ReplaceVariables ValueType where replace m (BuiltinType t) = do t' <- replace m t return $ BuiltinType t' replace m (FunctionType t) = do t' <- replace m t return $ FunctionType t' replace m (ClassType t) = do t' <- replace m t return $ ClassType t' replace m (InstanceType t) = do t' <- replace m t return $ InstanceType t' instance ReplaceVariables BuiltinType where replace m (TupleOf ts) = do ts' <- mapM (replace m) ts return $ TupleOf ts' replace m (ListOf t) = do t' <- replace m t return $ ListOf t' replace m (SetOf t) = do t' <- replace m t return $ SetOf t' replace m (FrozensetOf t) = do t' <- replace m t return $ FrozensetOf t' replace m (DictOf k v) = do k' <- replace m k v' <- replace m v return $ DictOf k' v' replace _ t = Just t instance ReplaceVariables FunctionType where replace _ (FunId i) = Just $ FunId i replace m (FunTy a r) = do -- XXX: deal with shadowed type variables a' <- mapM (replace m) a r' <- replace m r return $ FunTy a' r' instance ReplaceVariables ClassType where replace m (ClsTy classId sup env) = do sup' <- mapM (replace m) sup env' <- replaceEnv m env return $ ClsTy classId sup' env' replace _ (ClsRef classId) = Just $ ClsRef classId instance ReplaceVariables InstanceType where replace m (InstTy classId env) = do env' <- replaceEnv m env return $ InstTy classId env' replace _ (InstRef classId) = Just $ InstRef classId replaceEnv :: Map String UnionType -> Env -> Maybe Env replaceEnv m = mapMapM (replace m)
lfritz/python-type-inference
python-type-inference/src/Language/Python/TypeInference/Analysis/TypeLattice.hs
bsd-3-clause
27,942
0
32
10,931
8,322
4,327
3,995
558
9
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} -- due to TypeDiff being a synonym: {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Render where import Control.Arrow ( second ) import Control.Applicative import Control.Monad.Trans.Reader import Data.Monoid import Data.Void ( Void, absurd ) import Data.Functor.Foldable ( cata, embed ) import Data.Interface import Data.Interface.Change import Data.Interface.Type.Diff import System.IO ( stdout ) import Text.PrettyPrint.ANSI.Leijen hiding ( (<>), (<$>), (<+>), (</>) ) import qualified Text.PrettyPrint.ANSI.Leijen as L type Indent = Int data REnv = REnv { reQualContext :: QualContext } deriving (Show) newtype RDoc = RDoc (Reader REnv Doc) instance Monoid RDoc where mempty = RDoc $ pure mempty mappend (RDoc a) (RDoc b) = RDoc $ liftA2 mappend a b unRDoc :: QualContext -> RDoc -> Doc unRDoc qc (RDoc m) = runReader m $ REnv qc withQC :: (QualContext -> Doc) -> RDoc withQC f = RDoc $ f <$> asks reQualContext liftDocOp :: (Doc -> Doc -> Doc) -> RDoc -> RDoc -> RDoc liftDocOp f a b = withQC $ \qc -> f (unRDoc qc a) (unRDoc qc b) (<+>), (</>), (<//>), (<#>) :: RDoc -> RDoc -> RDoc (<+>) = liftDocOp (L.<+>) (</>) = liftDocOp (L.</>) (<//>) = liftDocOp (L.<//>) (<#>) = liftDocOp (L.<$>) infixr 5 </>,<//>,<#> infixr 6 <+> renderToString :: (Render a) => Indent -> QualContext -> a -> String renderToString i qc = ($ "") . renders i qc renders :: (Render a) => Indent -> QualContext -> a -> ShowS renders i qc a = displayS $ renderPretty 0.8 78 $ indent i $ unRDoc qc $ doc a renderStdout :: (Render a) => Indent -> QualContext -> a -> IO () renderStdout i qc a = displayIO stdout $ renderPretty 0.8 78 $ indent i $ unRDoc qc $ doc a -- (Deprecated) node :: RDoc -> [RDoc] -> RDoc node n xs = combine vcat $ n : map (style $ indent 2) xs node' :: String -> [RDoc] -> RDoc node' = node . text' style :: (Doc -> Doc) -> RDoc -> RDoc style f (RDoc m) = RDoc $ fmap f m combine :: (Functor f) => (f Doc -> Doc) -> f RDoc -> RDoc combine f ds = withQC $ \qc -> f $ fmap (unRDoc qc) ds text' :: String -> RDoc text' = doc . text char' :: Char -> RDoc char' = doc . char qual :: Qual String -> RDoc qual q = RDoc $ do qc <- asks reQualContext pure $ text $ resolveQual qc q class Render a where doc :: a -> RDoc doc = RDoc . pure . doc' doc' :: a -> Doc doc' = unRDoc qualifyAll . doc namedDoc :: Named a -> RDoc namedDoc (Named n a) = text' n <#> style (indent 2) (doc a) {-# MINIMAL doc | doc' #-} instance Render RDoc where doc = id {-# INLINABLE doc #-} instance Render Doc where doc' = id {-# INLINABLE doc' #-} instance Render Void where doc = absurd instance Render TypeConInfo where doc i = text' $ case i of ConAlgebraic -> "[algebraic]" ConSynonym -> "[synonym]" ConClass -> "[class]" instance Render TypeCon where doc (TypeCon name origin kind info) = -- TODO node (text' name <+> prefixSig (doc kind)) [ doc info , node (text' $ formatOrigin origin) [] ] formatOrigin :: Origin -> String formatOrigin o = case o of WiredIn -> "[built-in]" UnknownSource -> "[??? source unknown]" KnownSource (Source path (SrcSpan loc0 loc1)) -> '[' : path ++ ':' : showLoc loc0 ++ '-' : showLoc loc1 ++ "]" where showLoc (SrcLoc l c) = show l ++ ":" ++ show c formatPred :: (Render a) => Pred a -> RDoc formatPred p = case p of ClassPred ts -> combine hsep $ map doc ts EqPred{} -> undefined --text' (show p) -- TODO instance Render Export where doc (Named n e) = case e of LocalValue vd -> namedDoc $ Named n vd LocalType td -> namedDoc $ Named n td ReExport m _ns -> qual (Qual m n) <> style (indent 2) (text' "(re-export)") renderIfChanged :: (Diff a c, Render c) => c -> RDoc renderIfChanged d | isChanged d = doc d | otherwise = mempty -- Declarations instance Render ModuleInterface where doc iface = combine vcat [ text' $ "Module: " ++ moduleName iface ] instance Render ValueDecl where doc (ValueDecl t i) = doc i <#> prefixSig (doc t) <> doc line instance Render ValueDeclDiff where doc (ValueDeclDiff t i) = doc i <#> prefixSig (doc t) <> doc line instance Render ValueDeclInfo where doc i = case i of Identifier -> text' "[id]" PatternSyn -> text' "[pattern]" DataCon fields -> node' "[data con]" (map (text' . rawName) fields) instance Render TypeDecl where doc (TypeDecl k i) = doc i <#> prefixSig (doc k) <> doc line instance Render TypeDeclDiff where doc (TypeDeclDiff k i) = doc i <#> prefixSig (doc k) <> doc line instance Render TypeDeclInfo where doc i = case i of DataType Abstract -> text' "[abstract data type]" DataType (DataConList dataCons) -> node' "[data type]" (map (text' . rawName) dataCons) TypeSyn s -> node' "[synonym]" [ text' s ] TypeClass -> text' "[class]" instance Render Kind where doc k = case k of KindVar s -> text' s StarKind -> char' '*' HashKind -> char' '#' SuperKind -> text' "BOX" ConstraintKind -> text' "Constraint" PromotedType q -> qual q FunKind a b -> doc a <+> text' "->" </> doc b {- instance Render ExportDiff where doc ed = case ed of LocalValueDiff dv -> namedDoc dv LocalTypeDiff dt -> namedDoc dt ExportDiff c -> doc c -} -- TODO: make ExportDiff an instance of Diff: --renderChangedExportDiff = renderIfChanged prefixSig :: RDoc -> RDoc prefixSig d = text' "::" <+> style align d instance (Render c, Render a) => Render (Elem c a) where doc e = case e of Added a -> style green $ doc a Removed b -> style red $ doc b Elem c -> doc c namedDoc (Named n e) = case e of Added a -> style green $ namedDoc (Named n a) Removed b -> style red $ namedDoc (Named n b) Elem c -> namedDoc (Named n c) instance (Render a) => Render (Change a) where doc c = case c of NoChange a -> doc a Change a b -> combine vcat [ style red $ text' "-" <+> style align (doc a) , style green $ text' "+" <+> style align (doc b) ] instance (Render a) => Render (Replace a) where doc = doc . toChange instance Render Type where doc = snd . renderTypePrec instance Render TypeDiff where doc = snd . renderTypeDiffPrec data Prec = TopPrec | FunPrec | AppPrec | ConPrec deriving (Show, Eq, Ord) renderTypePrec :: Type -> (Prec, RDoc) renderTypePrec = cata renderTypeAlg renderTypeAlg :: (Render a) => TypeF (Prec, a) -> (Prec, RDoc) renderTypeAlg = undefined -- XXX TODO {- renderTypeAlg t0 = case t0 of VarF (TypeVar s _) -> (ConPrec, text' s) ConF q -> (ConPrec, qual q) ApplyF c a -> (,) AppPrec $ docPrec TopPrec c <+> docPrec AppPrec a FunF a b -> (,) FunPrec $ docPrec FunPrec a <+> text' "->" </> docPrec TopPrec b ForallF vs (_, t) -> (,) TopPrec $ if showForall then doc (renderForall vs) <#> doc t else doc t ContextF ps (_, t) -> (,) TopPrec $ combine tupled (map formatPred ps) <+> text' "=>" </> doc t where showForall = False docPrec :: (Render a) => Prec -> (Prec, a) -> RDoc docPrec prec0 (prec, d) | prec <= prec0 = style parens (doc d) | otherwise = doc d -} renderForall :: [TypeVar] -> Doc renderForall vs = hsep (map text $ "forall" : varNames) <> dot where varNames = map varName vs renderTypeDiffPrec :: TypeDiff -> (Prec, RDoc) renderTypeDiffPrec = cata renderTypeDiffAlg renderTypeDiffAlg :: (Render a) => DiffTypeF Type (Prec, a) -> (Prec, RDoc) renderTypeDiffAlg td0 = case td0 of NoDiffTypeF t -> (ConPrec, doc $ embed t) ReplaceTypeF t0 t1 -> (,) ConPrec $ style braces $ style red (doc $ embed t0) <+> text' "/" <+> style green (doc $ embed t1) SameTypeF fc -> renderTypeAlg $ fmap (second doc) fc where replaceDoc :: Replace Type -> RDoc replaceDoc (Replace t0 t1) = style braces $ style red (doc t0) <+> text' "/" <+> style green (doc t1)
cdxr/haskell-interface
module-diff/Render.hs
bsd-3-clause
8,749
0
14
2,524
2,862
1,460
1,402
206
3
{-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module CmmCallConv ( ParamLocation(..), assignArgumentsPos, globalArgRegs ) where #include "HsVersions.h" import CmmExpr import SMRep import Cmm (Convention(..)) import PprCmm () import Constants import qualified Data.List as L import DynFlags import Outputable -- Calculate the 'GlobalReg' or stack locations for function call -- parameters as used by the Cmm calling convention. data ParamLocation = RegisterParam GlobalReg | StackParam ByteOff instance Outputable ParamLocation where ppr (RegisterParam g) = ppr g ppr (StackParam p) = ppr p -- | JD: For the new stack story, I want arguments passed on the stack to manifest as -- positive offsets in a CallArea, not negative offsets from the stack pointer. -- Also, I want byte offsets, not word offsets. assignArgumentsPos :: DynFlags -> Convention -> (a -> CmmType) -> [a] -> [(a, ParamLocation)] -- Given a list of arguments, and a function that tells their types, -- return a list showing where each argument is passed assignArgumentsPos dflags conv arg_ty reps = assignments where -- The calling conventions (CgCallConv.hs) are complicated, to say the least regs = case (reps, conv) of (_, NativeNodeCall) -> getRegsWithNode dflags (_, NativeDirectCall) -> getRegsWithoutNode dflags ([_], NativeReturn) -> allRegs (_, NativeReturn) -> getRegsWithNode dflags -- GC calling convention *must* put values in registers (_, GC) -> allRegs (_, PrimOpCall) -> allRegs ([_], PrimOpReturn) -> allRegs (_, PrimOpReturn) -> getRegsWithNode dflags (_, Slow) -> noRegs -- The calling conventions first assign arguments to registers, -- then switch to the stack when we first run out of registers -- (even if there are still available registers for args of a different type). -- When returning an unboxed tuple, we also separate the stack -- arguments by pointerhood. (reg_assts, stk_args) = assign_regs [] reps regs stk_args' = case conv of NativeReturn -> part PrimOpReturn -> part GC | length stk_args /= 0 -> panic "Failed to allocate registers for GC call" _ -> stk_args where part = uncurry (++) (L.partition (not . isGcPtrType . arg_ty) stk_args) stk_assts = assign_stk 0 [] (reverse stk_args') assignments = reg_assts ++ stk_assts assign_regs assts [] _ = (assts, []) assign_regs assts (r:rs) regs = if isFloatType ty then float else int where float = case (w, regs) of (W32, (vs, f:fs, ds, ls)) -> k (RegisterParam f, (vs, fs, ds, ls)) (W64, (vs, fs, d:ds, ls)) -> k (RegisterParam d, (vs, fs, ds, ls)) (W80, _) -> panic "F80 unsupported register type" _ -> (assts, (r:rs)) int = case (w, regs) of (W128, _) -> panic "W128 unsupported register type" (_, (v:vs, fs, ds, ls)) | widthInBits w <= widthInBits wordWidth -> k (RegisterParam (v gcp), (vs, fs, ds, ls)) (_, (vs, fs, ds, l:ls)) | widthInBits w > widthInBits wordWidth -> k (RegisterParam l, (vs, fs, ds, ls)) _ -> (assts, (r:rs)) k (asst, regs') = assign_regs ((r, asst) : assts) rs regs' ty = arg_ty r w = typeWidth ty gcp | isGcPtrType ty = VGcPtr | otherwise = VNonGcPtr assign_stk _ assts [] = assts assign_stk offset assts (r:rs) = assign_stk off' ((r, StackParam off') : assts) rs where w = typeWidth (arg_ty r) size = (((widthInBytes w - 1) `div` wORD_SIZE) + 1) * wORD_SIZE off' = offset + size ----------------------------------------------------------------------------- -- Local information about the registers available type AvailRegs = ( [VGcPtr -> GlobalReg] -- available vanilla regs. , [GlobalReg] -- floats , [GlobalReg] -- doubles , [GlobalReg] -- longs (int64 and word64) ) -- Vanilla registers can contain pointers, Ints, Chars. -- Floats and doubles have separate register supplies. -- -- We take these register supplies from the *real* registers, i.e. those -- that are guaranteed to map to machine registers. getRegsWithoutNode, getRegsWithNode :: DynFlags -> AvailRegs getRegsWithoutNode _dflags = ( filter (\r -> r VGcPtr /= node) realVanillaRegs , realFloatRegs , realDoubleRegs , realLongRegs ) -- getRegsWithNode uses R1/node even if it isn't a register getRegsWithNode _dflags = ( if null realVanillaRegs then [VanillaReg 1] else realVanillaRegs , realFloatRegs , realDoubleRegs , realLongRegs ) allFloatRegs, allDoubleRegs, allLongRegs :: [GlobalReg] allVanillaRegs :: [VGcPtr -> GlobalReg] allVanillaRegs = map VanillaReg $ regList mAX_Vanilla_REG allFloatRegs = map FloatReg $ regList mAX_Float_REG allDoubleRegs = map DoubleReg $ regList mAX_Double_REG allLongRegs = map LongReg $ regList mAX_Long_REG realFloatRegs, realDoubleRegs, realLongRegs :: [GlobalReg] realVanillaRegs :: [VGcPtr -> GlobalReg] realVanillaRegs = map VanillaReg $ regList mAX_Real_Vanilla_REG realFloatRegs = map FloatReg $ regList mAX_Real_Float_REG realDoubleRegs = map DoubleReg $ regList mAX_Real_Double_REG realLongRegs = map LongReg $ regList mAX_Real_Long_REG regList :: Int -> [Int] regList n = [1 .. n] allRegs :: AvailRegs allRegs = (allVanillaRegs, allFloatRegs, allDoubleRegs, allLongRegs) noRegs :: AvailRegs noRegs = ([], [], [], []) globalArgRegs :: [GlobalReg] globalArgRegs = map ($VGcPtr) allVanillaRegs ++ allFloatRegs ++ allDoubleRegs ++ allLongRegs
nomeata/ghc
compiler/cmm/CmmCallConv.hs
bsd-3-clause
6,497
2
17
1,905
1,471
831
640
103
21
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} -- {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE AllowAmbiguousTypes #-} -- The following is needed to define MonadPlus instance. It is decidable -- (there is no recursion!), but GHC cannot see that. {-# LANGUAGE UndecidableInstances #-} -- The framework of extensible effects module Eff1 where import Control.Monad import Control.Applicative import OpenUnion41 -- import Data.FastTCQueue -- old? -- import Data.TASequence.FastQueue hiding (tmap) import Data.TASequence.FastCatQueue hiding (tmap) import Data.IORef -- For demonstration of lifting import Data.Monoid -- For demos -- ------------------------------------------------------------------------ -- A monadic library for communication between a handler and -- its client, the administered computation -- Effectful arrow type: a function from a to b that also does effects -- denoted by r newtype Arr r a b = Arr{unArr:: a -> Eff r b} -- An effectful function from 'a' to 'b' that is a composition -- of several effectful functions. The paremeter r describes the overall -- effect. -- The composition members are accumulated in a type-aligned queue type GenArr r a b = FastTCQueue (Arr r) a b -- The Eff monad (not a transformer!) -- It is a fairly standard coroutine monad -- It is NOT a Free monad! There are no Functor constraints -- Status of a coroutine (client): done with the value of type w, -- or sending a request of type Union r with the continuation -- Gen r b a. data Eff r a = Val a | forall b. E !(Union r b) (GenArr r b a) -- Application to the `generalized effectful function' GenArr r b w qApp :: b -> GenArr r b w -> Eff r w qApp x q = case tviewl q of TAEmptyL -> Val x k :< t -> case unArr k x of Val y -> qApp y t E u q -> E u (q >< t) -- Compose effectful arrows (and possibly change the effect!) qComp :: GenArr r a b -> (Eff r b -> Eff r' c) -> Arr r' a c qComp q loop = Arr (\a -> loop $ qApp a q) -- Eff is still a monad and a functor (and Applicative) -- (despite the lack of the Functor constraint) instance Functor (Eff r) where fmap f (Val x) = Val (f x) fmap f (E u q) = E u (q |> Arr (Val . f)) -- does no mapping yet! instance Applicative (Eff r) where pure = Val Val f <*> Val x = Val $ f x Val f <*> E u q = E u (q |> Arr (Val . f)) E u q <*> Val x = E u (q |> Arr (Val . ($ x))) E u q <*> m = E u (q |> Arr (\f -> fmap f m)) instance Monad (Eff r) where {-# INLINE return #-} {-# INLINE (>>=) #-} return = Val Val x >>= k = k x E u q >>= k = E u (q |> Arr k) -- just accumulates continuations -- send a request and wait for a reply send :: Member t r => t v -> Eff r v send t = E (inj t) tempty {- -- A specialization of send useful for explanation send_req :: (Functor req, Typeable req, Member req r) => (forall w. (a -> VE w r) -> req (VE w r)) -> Eff r a send_req req = send (inj . req) -- administer a client: launch a coroutine and wait for it -- to send a request or terminate with a value admin :: Eff r w -> VE w r admin (Eff m) = m Val -- The opposite of admin, occasionally useful -- See the soft-cut for an example -- It is currently quite inefficient. There are better ways reflect :: VE a r -> Eff r a reflect (Val x) = return x reflect (E u) = Eff (\k -> E $ fmap (loop k) u) where loop :: (a -> VE w r) -> VE a r -> VE w r loop k (Val x) = k x loop k (E u) = E $ fmap (loop k) u -} -- ------------------------------------------------------------------------ -- The initial case, no effects -- The type of run ensures that all effects must be handled: -- only pure computations may be run. run :: Eff '[] w -> w run (Val x) = x -- the other case is unreachable since Union [] a cannot be -- constructed. -- Therefore, run is a total function if its argument terminates. -- A convenient pattern: given a request (open union), either -- handle it or relay it. handle_relay :: (a -> Eff r w) -> (forall v. t v -> Arr r v w -> Eff r w) -> Eff (t ': r) a -> Eff r w handle_relay ret _ (Val x) = ret x handle_relay ret h (E u q) = case decomp u of Right x -> h x k Left u -> E u (tsingleton k) where k = qComp q (handle_relay ret h) -- Add something like Control.Exception.catches? It could be useful -- for control with cut. -- Intercept the request and possibly reply to it, but leave it unhandled -- (that's why we use the same r all throuout) interpose :: Member t r => (a -> Eff r w) -> (forall v. t v -> Arr r v w -> Eff r w) -> Eff r a -> Eff r w interpose ret _ (Val x) = ret x interpose ret h (E u q) = case prj u of Just x -> h x k _ -> E u (tsingleton k) where k = qComp q (interpose ret h) -- ------------------------------------------------------------------------ -- The Reader monad -- The request for a value of type e from the current environment -- This is a GADT because the type of values -- returned in response to a (Reader e a) request is not any a; -- we expect in reply the value of type 'e', the value from the -- environment. So, the return type is restricted: 'a ~ e' data Reader e v where Reader :: Reader e e -- One can also define this as -- data Reader e v = (e ~ v) => Reader -- and even without GADTs, using explicit coercion: -- newtype Reader e v = Reader (e->v) -- In the latter case, when we make the request, we make it as Reader id. -- So, strictly speaking, GADTs are not really necessary. -- The signature is inferred ask :: (Member (Reader e) r) => Eff r e ask = send Reader -- The handler of Reader requests. The return type shows that -- all Reader requests are fully handled. runReader' :: Eff (Reader e ': r) w -> e -> Eff r w runReader' m e = loop m where loop (Val x) = return x loop (E u q) = case decomp u of Right Reader -> loop $ qApp e q Left u -> E u (tsingleton (qComp q loop)) -- A different way of writing the above runReader :: Eff (Reader e ': r) w -> e -> Eff r w runReader m e = handle_relay return (\Reader k -> unArr k e) m -- Locally rebind the value in the dynamic environment -- This function is like a relay; it is both an admin for Reader requests, -- and a requestor of them local :: forall e a r. Member (Reader e) r => (e -> e) -> Eff r a -> Eff r a local f m = do e0 <- ask let e = f e0 -- Local signature is needed, as always with GADTs let h :: Reader e v -> Arr r v a -> Eff r a h Reader (Arr g) = g e interpose return h m -- Examples add :: Monad m => m Int -> m Int -> m Int add = liftM2 (+) -- The type is inferred -- t1 :: Member (Reader Int) r => Eff r Int t1 = ask `add` return (1::Int) t1' :: Member (Reader Int) r => Eff r Int t1' = do v <- ask; return (v + 1 :: Int) -- t1r :: Eff r Int t1r = runReader t1 (10::Int) t1rr = 11 == run t1r {- t1rr' = run t1 No instance for (Member (Reader Int) Void) arising from a use of `t1' -} -- Inferred type -- t2 :: (Member (Reader Int) r, Member (Reader Float) r) => Eff r Float t2 = do v1 <- ask v2 <- ask return $ fromIntegral (v1 + (1::Int)) + (v2 + (2::Float)) -- t2r :: Member (Reader Float) r => Eff r Float t2r = runReader t2 (10::Int) -- t2rr :: Eff r Float t2rr = flip runReader (20::Float) . flip runReader (10::Int) $ t2 t2rrr = 33.0 == run t2rr -- The opposite order of layers {- If we mess up, we get an error t2rrr1' = run $ runReader (runReader t2 (20::Float)) (10::Float) No instance for (Member (Reader Int) []) arising from a use of `t2' -} t2rrr' = (33.0 ==) $ run $ runReader (runReader t2 (20::Float)) (10::Int) -- The type is inferred t3 :: Member (Reader Int) r => Eff r Int t3 = t1 `add` local (+ (10::Int)) t1 t3r = (212 ==) $ run $ runReader t3 (100::Int) -- The following example demonstrates true interleaving of Reader Int -- and Reader Float layers {- t4 :: (Member (Reader Int) r, Member (Reader Float) r) => () -> Eff r Float -} t4 = liftM2 (+) (local (+ (10::Int)) t2) (local (+ (30::Float)) t2) t4rr = (106.0 ==) $ run $ runReader (runReader t4 (10::Int)) (20::Float) -- The opposite order of layers gives the same result t4rr' = (106.0 ==) $ run $ runReader (runReader t4 (20::Float)) (10::Int) -- Map an effectful function -- The type is inferred tmap :: Member (Reader Int) r => Eff r [Int] tmap = mapM f [1..5] where f x = ask `add` return x tmapr = ([11,12,13,14,15] ==) $ run $ runReader tmap (10::Int) -- ------------------------------------------------------------------------ -- Exceptions -- exceptions of the type e; no resumption newtype Exc e v = Exc e -- The type is inferred throwError :: (Member (Exc e) r) => e -> Eff r a throwError e = send (Exc e) runError :: Eff (Exc e ': r) a -> Eff r (Either e a) runError = handle_relay (return . Right) (\ (Exc e) _k -> return (Left e)) -- The handler is allowed to rethrow the exception catchError :: Member (Exc e) r => Eff r a -> (e -> Eff r a) -> Eff r a catchError m handle = interpose return (\(Exc e) _k -> handle e) m -- The type is inferred et1 :: Eff r Int et1 = return 1 `add` return 2 et1r = 3 == run et1 -- The type is inferred et2 :: Member (Exc Int) r => Eff r Int et2 = return 1 `add` throwError (2::Int) -- The following won't type: unhandled exception! -- ex2rw = run et2 {- No instance for (Member (Exc Int) Void) arising from a use of `et2' -} -- The inferred type shows that ex21 is now pure et21 :: Eff r (Either Int Int) et21 = runError et2 et21r = Left 2 == run et21 -- The example from the paper newtype TooBig = TooBig Int deriving (Eq, Show) -- The type is inferred ex2 :: Member (Exc TooBig) r => Eff r Int -> Eff r Int ex2 m = do v <- m if v > 5 then throwError (TooBig v) else return v -- specialization to tell the type of the exception runErrBig :: Eff (Exc TooBig ': r) a -> Eff r (Either TooBig a) runErrBig = runError ex2r = runReader (runErrBig (ex2 ask)) (5::Int) ex2rr = Right 5 == run ex2r ex2rr1 = (Left (TooBig 7) ==) $ run $ runReader (runErrBig (ex2 ask)) (7::Int) -- Different order of handlers (layers) ex2rr2 = (Left (TooBig 7) ==) $ run $ runErrBig (runReader (ex2 ask) (7::Int)) -- Implementing the operator <|> from Alternative: -- a <|> b does -- -- tries a, and if succeeds, returns its result -- -- otherwise, tries b, and if succeeds, returns its result -- -- otherwise, throws mappend of exceptions of a and b -- We use MemberU2 in the signature rather than Member to -- ensure that the computation throws only one type of exceptions. -- Otherwise, this construction is not very useful. alttry :: forall e r a. (Monoid e, MemberU2 Exc (Exc e) r) => Eff r a -> Eff r a -> Eff r a alttry ma mb = catchError ma $ \ea -> catchError mb $ \eb -> throwError (mappend (ea::e) eb) -- Test case t_alttry = ([Right 10,Right 10,Right 10,Left "bummer1bummer2"] ==) $ [ run . runError $ (return 1 `add` throwError "bummer1") `alttry` (return 10), run . runError $ (return 10) `alttry` (return 1 `add` throwError "bummer2"), run . runError $ (return 10) `alttry` return 20, run . runError $ (return 1 `add` throwError "bummer1") `alttry` (return 1 `add` throwError "bummer2") ] -- ------------------------------------------------------------------------ -- Non-determinism (choice) -- choose lst non-deterministically chooses one value from the lst -- choose [] thus corresponds to failure -- Unlike Reader, Choose is not a GADT because the type of values -- returned in response to a (Choose a) request is just a, without -- any contraints. newtype Choose a = Choose [a] choose :: Member Choose r => [a] -> Eff r a choose lst = send (Choose lst) -- MonadPlus-like operators are expressible via choose instance Member Choose r => Alternative (Eff r) where empty = choose [] m1 <|> m2 = choose [m1,m2] >>= id instance Member Choose r => MonadPlus (Eff r) where mzero = empty mplus = (<|>) -- The interpreter makeChoice :: forall a r. Eff (Choose ': r) a -> Eff r [a] makeChoice = handle_relay (return . (:[])) (\ (Choose lst) (Arr k) -> handle lst k) where -- Need the signature since local bindings aren't polymorphic any more handle :: [t] -> (t -> Eff r [a]) -> Eff r [a] handle [] _ = return [] handle [x] k = k x handle lst k = fmap concat $ mapM k lst exc1 :: Member Choose r => Eff r Int exc1 = return 1 `add` choose [1,2] exc11 = makeChoice exc1 exc11r = ([2,3] ==) $ run exc11 {- -- ------------------------------------------------------------------------ -- Soft-cut: non-deterministic if-then-else, aka Prolog's *-> -- Declaratively, -- ifte t th el = (t >>= th) `mplus` ((not t) >> el) -- However, t is evaluated only once. In other words, ifte t th el -- is equivalent to t >>= th if t has at least one solution. -- If t fails, ifte t th el is the same as el. ifte :: forall r a b. Member Choose r => Eff r a -> (a -> Eff r b) -> Eff r b -> Eff r b ifte t th el = loop [] (admin t) where loop [] (Val x) = th x -- add all other latent choices of t to th x -- this is like reflection of t loop jq (Val x) = choose ((th x) : map (\t -> reflect t >>= th) jq) >>= id loop jq (E u) = interpose u (loop jq) (\(Choose lst k) -> handle jq lst k) -- Need the signature since local bindings aren't polymorphic any more handle :: [VE a r] -> [t] -> (t -> VE a r) -> Eff r b handle [] [] _ = el -- no more choices left handle (j:jq) [] _ = loop jq j handle jq [x] k = loop jq (k x) handle jq (x:rest) k = loop (map k rest ++ jq) (k x) -- DFS guard' :: Member Choose r => Bool -> Eff r () guard' True = return () guard' False = mzero' -- primes (very inefficiently -- but a good example of ifte) test_ifte = do n <- gen guard' $ n > 1 ifte (do d <- gen guard' $ d < n && d > 1 && n `mod` d == 0 -- _ <- trace ("d: " ++ show d) (return ()) return d) (\_->mzero') (return n) where gen = choose [1..30] test_ifte_run = run . makeChoice $ test_ifte -- [2,3,5,7,11,13,17,19,23,29] -} -- ------------------------------------------------------------------------ -- Combining exceptions and non-determinism -- Example from the paper ex2_2 = ([Right 5,Left (TooBig 7),Right 1] ==) $ run . makeChoice . runErrBig $ ex2 (choose [5,7,1]) -- just like ex1_1 in transf.hs but not at all like ex2_1 in transf.hs -- with different order of handlers, obtain the desired result of -- a high-priority exception ex2_1 = (Left (TooBig 7) ==) $ run . runErrBig . makeChoice $ ex2 (choose [5,7,1]) -- Errror recovery part -- The code is the same as in transf1.hs. The inferred signatures differ -- Was: exRec :: MonadError TooBig m => m Int -> m Int -- exRec :: Member (Exc TooBig) r => Eff r Int -> Eff r Int exRec m = catchError m handler where handler (TooBig n) | n <= 7 = return n handler e = throwError e ex2r_2 = (Right [5,7,1] ==) $ run . runErrBig . makeChoice $ exRec (ex2 (choose [5,7,1])) -- Compare with ex2r_1 from transf1.hs ex2r_2' = ([Right 5,Right 7,Right 1] ==) $ run . makeChoice . runErrBig $ exRec (ex2 (choose [5,7,1])) -- Again, all three choices are accounted for. ex2r_1 = (Left (TooBig 11) ==) $ run . runErrBig . makeChoice $ exRec (ex2 (choose [5,7,11,1])) -- Compare with ex2r_2 from transf1.hs -- ------------------------------------------------------------------------ -- State, strict -- The state request carries with it the state mutator function -- We can use this request both for mutating and getting the state. -- But see below for a better design! data State s v where State :: (s->s) -> State s s -- Use Reader to get the state. So we decompose State into Reader -- and Mutator! -- The signature is inferred put :: Member (State s) r => s -> Eff r () put s = send (State (const s)) >> return () modify :: Member (State s) r => (s -> s) -> Eff r s modify f = send (State f) -- The signature is inferred get :: Member (State s) r => Eff r s get = send (State id) -- Parameterized handle_relay handle_relay_s :: s -> (s -> a -> Eff r w) -> (forall v. s -> t v -> (s -> Arr r v w) -> Eff r w) -> Eff (t ': r) a -> Eff r w handle_relay_s s ret _ (Val x) = ret s x handle_relay_s s ret h (E u q) = case decomp u of Right x -> h s x k Left u -> E u (tsingleton (k s)) where k s = qComp q (handle_relay_s s ret h) runState :: Eff (State s ': r) w -> s -> Eff r (w,s) runState m s = handle_relay_s s (\s x -> return (x,s)) (\s (State t) k -> let s' = t s in unArr (k $! s') $! s') m -- Examples ts1 :: Member (State Int) r => Eff r Int ts1 = do put (10 ::Int) x <- get return (x::Int) ts1r = ((10,10) ==) $ run (runState ts1 (0::Int)) ts2 :: Member (State Int) r => Eff r Int ts2 = do put (10::Int) x <- get put (20::Int) y <- get return (x+y) ts2r = ((30,20) ==) $ run (runState ts2 (0::Int)) -- A different representation of State: decomposing State into mutation -- and Reading. We don't define any new effects: we just handle the -- existing ones. We use State for modification and Reader for inquiring. -- Thus we define a handler for two effects. runStateR :: Eff (State s ': Reader s ': r) w -> s -> Eff r (w,s) runStateR m s = loop s m where loop :: s -> Eff (State s ': Reader s ': r) w -> Eff r (w,s) loop s (Val x) = return (x,s) loop s (E u q) = case decomp u of Right (State t) -> let s' = t s in unArr (k $! s') $! s' Left u -> case decomp u of Right Reader -> unArr (k s) s Left u -> E u (tsingleton (k s)) where k s = qComp q (loop s) -- If we had a Writer, we could have decomposed State into Writer and Reader -- requests. ts11 :: (Member (Reader Int) r, Member (State Int) r) => Eff r Int ts11 = do put (10 ::Int) x <- ask return (x::Int) ts11r = ((10,10) ==) $ run (runStateR ts1 (0::Int)) ts21 :: (Member (Reader Int) r, Member (State Int) r) => Eff r Int ts21 = do put (10::Int) x <- ask put (20::Int) y <- ask return (x+y) ts21r = ((30,20) ==) $ run (runStateR ts2 (0::Int)) -- exceptions and state incr :: Member (State Int) r => Eff r () incr = get >>= put . (+ (1::Int)) tes1 :: (Member (State Int) r, Member (Exc [Char]) r) => Eff r b tes1 = do incr throwError "exc" ter1 = ((Left "exc" :: Either String Int,2) ==) $ run $ runState (runError tes1) (1::Int) ter2 = ((Left "exc" :: Either String (Int,Int)) ==) $ run $ runError (runState tes1 (1::Int)) teCatch :: Member (Exc String) r => Eff r a -> Eff r [Char] teCatch m = catchError (m >> return "done") (\e -> return (e::String)) ter3 = ((Right "exc" :: Either String String,2) ==) $ run $ runState (runError (teCatch tes1)) (1::Int) ter4 = ((Right ("exc",2) :: Either String (String,Int)) ==) $ run $ runError (runState (teCatch tes1) (1::Int)) -- Encapsulation of effects -- The example suggested by a reviewer {- The reviewer outlined an MTL implementation below, writing ``This hides the state effect and I can layer another state effect on top without getting into conflict with the class system.'' class Monad m => MonadFresh m where fresh :: m Int newtype FreshT m a = FreshT { unFreshT :: State Int m a } deriving (Functor, Monad, MonadTrans) instance Monad m => MonadFresh (FreshT m) where fresh = FreshT $ do n <- get; put (n+1); return n See EncapsMTL.hs for the complete code. -} -- There are three possible implementations -- The first one uses State Fresh where -- newtype Fresh = Fresh Int -- We get the `private' effect layer (State Fresh) that does not interfere -- with with other layers. -- This is the easiest implementation. -- The second implementation defines a new effect Fresh data Fresh v where Fresh :: Fresh Int fresh :: Member Fresh r => Eff r Int fresh = send Fresh -- And a handler for it runFresh' :: Eff (Fresh ': r) w -> Int -> Eff r w runFresh' m s = handle_relay_s s (\_s x -> return x) (\s Fresh k -> unArr (k $! s+1) s) m -- Test tfresh' = runTrace $ flip runFresh' 0 $ do n <- fresh trace $ "Fresh " ++ show n n <- fresh trace $ "Fresh " ++ show n {- Fresh 0 Fresh 1 -} {- -- Finally, the worst implementation but the one that answers -- reviewer's question: implementing Fresh in terms of State -- but not revealing that fact. runFresh :: Eff (Fresh :> r) w -> Int -> Eff r w runFresh m s = runState m' s >>= return . fst where m' = loop m loop (Val x) = return x loop (E u q) = case decomp u of Right Fresh -> do n <- get put (n+1::Int) unArr k n Left u -> send (\k -> weaken $ fmap k u) >>= loop tfresh = runTrace $ flip runFresh 0 $ do n <- fresh -- (x::Int) <- get trace $ "Fresh " ++ show n n <- fresh trace $ "Fresh " ++ show n {- If we try to meddle with the encapsulated state, by uncommenting the get statement above, we get: No instance for (Member (State Int) Void) arising from a use of `get' -} -} -- ------------------------------------------------------------------------ -- Tracing (debug printing) data Trace v where Trace :: String -> Trace () -- Printing a string in a trace trace :: Member Trace r => String -> Eff r () trace = send . Trace -- The handler for IO request: a terminal handler runTrace :: Eff '[Trace] w -> IO w runTrace (Val x) = return x runTrace (E u q) = case decomp u of Right (Trace s) -> putStrLn s >> runTrace (qApp () q) -- Nothing more can occur -- Higher-order effectful function -- The inferred type shows that the Trace affect is added to the effects -- of r mapMdebug:: (Show a, Member Trace r) => (a -> Eff r b) -> [a] -> Eff r [b] mapMdebug f [] = return [] mapMdebug f (h:t) = do trace $ "mapMdebug: " ++ show h h' <- f h t' <- mapMdebug f t return (h':t') tMd = runTrace $ runReader (mapMdebug f [1..5]) (10::Int) where f x = ask `add` return x {- mapMdebug: 1 mapMdebug: 2 mapMdebug: 3 mapMdebug: 4 mapMdebug: 5 [11,12,13,14,15] -} -- duplicate layers tdup = runTrace $ runReader m (10::Int) where m = do runReader tr (20::Int) tr tr = do v <- ask trace $ "Asked: " ++ show (v::Int) {- Asked: 20 Asked: 10 -} -- ------------------------------------------------------------------------ -- Lifting: emulating monad transformers newtype Lift m a = Lift (m a) -- We make the Lift layer to be unique, using MemberU2 lift :: (MemberU2 Lift (Lift m) r) => m a -> Eff r a lift = send . Lift -- The handler of Lift requests. It is meant to be terminal runLift :: Monad m => Eff '[Lift m] w -> m w runLift (Val x) = return x runLift (E u q) = case prj u of Just (Lift m) -> m >>= \x -> runLift (qApp x q) -- Nothing cannot occur tl1 = ask >>= \(x::Int) -> lift . print $ x -- tl1r :: IO () tl1r = runLift (runReader tl1 (5::Int)) -- 5 -- Re-implemenation of mapMdebug using Lifting -- The signature is inferred mapMdebug' :: (Show a, MemberU2 Lift (Lift IO) r) => (a -> Eff r b) -> [a] -> Eff r [b] mapMdebug' f [] = return [] mapMdebug' f (h:t) = do lift $ print h h' <- f h t' <- mapMdebug' f t return (h':t') tMd' = runLift $ runReader (mapMdebug' f [1..5]) (10::Int) where f x = ask `add` return x {- 1 2 3 4 5 [11,12,13,14,15] -} {- -- ------------------------------------------------------------------------ -- Co-routines -- The interface is intentionally chosen to be the same as in transf.hs -- The yield request: reporting the value of type a and suspending -- the coroutine. Resuming with the value of type b data Yield a b v = Yield a (b -> v) deriving (Typeable, Functor) -- The signature is inferred yield :: (Typeable a, Typeable b, Member (Yield a b) r) => a -> Eff r b yield x = send (inj . Yield x) -- Status of a thread: done or reporting the value of the type a -- and resuming with the value of type b data Y r a b = Done | Y a (b -> Eff r (Y r a b)) -- Launch a thread and report its status runC :: (Typeable a, Typeable b) => Eff (Yield a b :> r) w -> Eff r (Y r a b) runC m = loop (admin m) where loop (Val x) = return Done loop (E u) = handle_relay u loop $ \(Yield x k) -> return (Y x (loop . k)) -- First example of coroutines yieldInt :: Member (Yield Int ()) r => Int -> Eff r () yieldInt = yield th1 :: Member (Yield Int ()) r => Eff r () th1 = yieldInt 1 >> yieldInt 2 c1 = runTrace (loop =<< runC th1) where loop (Y x k) = trace (show (x::Int)) >> k () >>= loop loop Done = trace "Done" {- 1 2 Done -} -- Add dynamic variables -- The code is essentially the same as that in transf.hs (only added -- a type specializtion on yield). The inferred signature is different though. -- Before it was -- th2 :: MonadReader Int m => CoT Int m () -- Now it is more general: th2 :: (Member (Yield Int ()) r, Member (Reader Int) r) => Eff r () th2 = ask >>= yieldInt >> (ask >>= yieldInt) -- Code is essentially the same as in transf.hs; no liftIO though c2 = runTrace $ runReader (loop =<< runC th2) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> k () >>= loop loop Done = trace "Done" {- 10 10 Done -} -- locally changing the dynamic environment for the suspension c21 = runTrace $ runReader (loop =<< runC th2) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> local (+(1::Int)) (k ()) >>= loop loop Done = trace "Done" {- 10 11 Done -} -- Real example, with two sorts of local rebinding th3 :: (Member (Yield Int ()) r, Member (Reader Int) r) => Eff r () th3 = ay >> ay >> local (+(10::Int)) (ay >> ay) where ay = ask >>= yieldInt c3 = runTrace $ runReader (loop =<< runC th3) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> k () >>= loop loop Done = trace "Done" {- 10 10 20 20 Done -} -- locally changing the dynamic environment for the suspension c31 = runTrace $ runReader (loop =<< runC th3) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> local (+(1::Int)) (k ()) >>= loop loop Done = trace "Done" {- 10 11 21 21 Done -} -- The result is exactly as expected and desired: the coroutine shares the -- dynamic environment with its parent; however, when the environment -- is locally rebound, it becomes private to coroutine. -- We now make explicit that the client computation, run by th4, -- is abstract. We abstract it out of th4 c4 = runTrace $ runReader (loop =<< runC (th4 client)) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> local (+(1::Int)) (k ()) >>= loop loop Done = trace "Done" -- cl, client, ay are monomorphic bindings th4 cl = cl >> local (+(10::Int)) cl client = ay >> ay ay = ask >>= yieldInt {- 10 11 21 21 Done -} -- Even more dynamic example c5 = runTrace $ runReader (loop =<< runC (th client)) (10::Int) where loop (Y x k) = trace (show (x::Int)) >> local (\y->x+1) (k ()) >>= loop loop Done = trace "Done" -- cl, client, ay are monomorphic bindings client = ay >> ay >> ay ay = ask >>= yieldInt -- There is no polymorphic recursion here th cl = do cl v <- ask (if v > (20::Int) then id else local (+(5::Int))) cl if v > (20::Int) then return () else local (+(10::Int)) (th cl) {- 10 11 12 18 18 18 29 29 29 29 29 29 Done -} -- And even more c7 = runTrace $ runReader (runReader (loop =<< runC (th client)) (10::Int)) (1000::Double) where loop (Y x k) = trace (show (x::Int)) >> local (\y->fromIntegral (x+1)::Double) (k ()) >>= loop loop Done = trace "Done" -- cl, client, ay are monomorphic bindings client = ay >> ay >> ay ay = ask >>= \x -> ask >>= \y -> yieldInt (x + round (y::Double)) -- There is no polymorphic recursion here th cl = do cl v <- ask (if v > (20::Int) then id else local (+(5::Int))) cl if v > (20::Int) then return () else local (+(10::Int)) (th cl) {- 1010 1021 1032 1048 1064 1080 1101 1122 1143 1169 1195 1221 1252 1283 1314 1345 1376 1407 Done -} c7' = runTrace $ runReader (runReader (loop =<< runC (th client)) (10::Int)) (1000::Double) where loop (Y x k) = trace (show (x::Int)) >> local (\y->fromIntegral (x+1)::Double) (k ()) >>= loop loop Done = trace "Done" -- cl, client, ay are monomorphic bindings client = ay >> ay >> ay ay = ask >>= \x -> ask >>= \y -> yieldInt (x + round (y::Double)) -- There is no polymorphic recursion here th cl = do cl v <- ask (if v > (20::Int) then id else local (+(5::Double))) cl if v > (20::Int) then return () else local (+(10::Int)) (th cl) {- 1010 1021 1032 1048 1048 1048 1069 1090 1111 1137 1137 1137 1168 1199 1230 1261 1292 1323 Done -} -- ------------------------------------------------------------------------ -- An example of non-trivial interaction of effects, handling of two -- effects together -- Non-determinism with control (cut) -- For the explanation of cut, see Section 5 of Hinze ICFP 2000 paper. -- Hinze suggests expressing cut in terms of cutfalse -- ! = return () `mplus` cutfalse -- where -- cutfalse :: m a -- satisfies the following laws -- cutfalse >>= k = cutfalse (F1) -- cutfalse | m = cutfalse (F2) -- (note: m `mplus` cutfalse is different from cutfalse `mplus` m) -- In other words, cutfalse is the left zero of both bind and mplus. -- -- Hinze also introduces the operation call :: m a -> m a that -- delimits the effect of cut: call m executes m. If the cut is -- invoked in m, it discards only the choices made since m was called. -- Hinze postulates the axioms of call: -- -- call false = false (C1) -- call (return a | m) = return a | call m (C2) -- call (m | cutfalse) = call m (C3) -- call (lift m >>= k) = lift m >>= (call . k) (C4) -- -- call m behaves like m except any cut inside m has only a local effect, -- he says. -- Hinze noted a problem with the `mechanical' derivation of backtracing -- monad transformer with cut: no axiom specifying the interaction of -- call with bind; no way to simplify nested invocations of call. -- We use exceptions for cutfalse -- Therefore, the law ``cutfalse >>= k = cutfalse'' -- is satisfied automatically since all exceptions have the above property. data CutFalse = CutFalse deriving Typeable cutfalse = throwError CutFalse -- The interpreter -- it is like reify . reflect with a twist -- Compare this implementation with the huge implementation of call -- in Hinze 2000 (Figure 9) -- Each clause corresponds to the axiom of call or cutfalse. -- All axioms are covered. -- The code clearly expresses the intuition that call watches the choice points -- of its argument computation. When it encounteres a cutfalse request, -- it discards the remaining choicepoints. -- It completely handles CutFalse effects but not non-determinism call :: Member Choose r => Eff (Exc CutFalse :> r) a -> Eff r a call m = loop [] (admin m) where loop jq (Val x) = return x `mplus'` next jq -- (C2) loop jq (E u) = case decomp u of Right (Exc CutFalse) -> mzero' -- drop jq (F2) Left u -> check jq u check jq u | Just (Choose [] _) <- prj u = next jq -- (C1) check jq u | Just (Choose [x] k) <- prj u = loop jq (k x) -- (C3), optim check jq u | Just (Choose lst k) <- prj u = next $ map k lst ++ jq -- (C3) check jq u = send (\k -> fmap k u) >>= loop jq -- (C4) next [] = mzero' next (h:t) = loop t h -- The signature is inferred tcut1 :: (Member Choose r, Member (Exc CutFalse) r) => Eff r Int tcut1 = (return (1::Int) `mplus'` return 2) `mplus'` ((cutfalse `mplus'` return 4) `mplus'` return 5) tcut1r = run . makeChoice $ call tcut1 -- [1,2] tcut2 = return (1::Int) `mplus'` call (return 2 `mplus'` (cutfalse `mplus'` return 3) `mplus'` return 4) `mplus'` return 5 -- Here we see nested call. It poses no problems... tcut2r = run . makeChoice $ call tcut2 -- [1,2,5] -- More nested calls tcut3 = call tcut1 `mplus'` call (tcut2 `mplus'` cutfalse) tcut3r = run . makeChoice $ call tcut3 -- [1,2,1,2,5] tcut4 = call tcut1 `mplus'` (tcut2 `mplus'` cutfalse) tcut4r = run . makeChoice $ call tcut4 -- [1,2,1,2,5] -}
iu-parfunc/AutoObsidian
interface_brainstorming/06_ExtensibleEffects/newVer/Eff1.hs
bsd-3-clause
32,804
0
17
8,177
6,684
3,511
3,173
-1
-1
module Common.NonBlockingQueueSpec (main, spec) where import Test.Hspec import Test.QuickCheck import qualified PolyGraph.Common.NonBlockingQueue.Properties as QProp spec :: Spec spec = do describe "NonBlockingQueue" $ do it "isFifo" $ property $ (QProp.isFifo :: [QProp.QueueInstruction Int] -> Bool) it "dequeues with something unless queue is empty" $ property $ (QProp.dequeuesUnlessEmpty :: [QProp.QueueInstruction Int] -> Bool) main :: IO () main = hspec spec
rpeszek/GraphPlay
test/Common/NonBlockingQueueSpec.hs
bsd-3-clause
500
0
15
94
140
76
64
13
1
module D_Types where import Data.Word import Data.Int import Data.ByteString.Lazy import Data.Binary.Get data TypeDesc = TD (Int, String, [FieldDescTest], [TypeDesc]) -- id, name, fieldDescs, subtypes type FieldDesc = (String, [Something]) --name, data type FieldDescTest = (String, [Something], ByteString) --name, data, rawData type FieldData = ByteString type Pointer = (Int, Int) -- skill name 'Annotation' type UserType = String data Something = CInt8 Int8 -- 0 | CInt16 Int16 -- 1 | CInt32 Int32 -- 2 | CInt64 Int64 -- 3 | CV64 Int64 -- 4 | GPointer Pointer -- 5 | GBool Bool -- 6 | GInt8 Int8 -- 7 | GInt16 Int16 -- 8 | GInt32 Int32 -- 9 | GInt64 Int64 -- 10 | GV64 Int64 -- 11 | GFloat Float -- 12 | GDouble Double -- 13 | GString String -- 14 | GFArray [Something] -- 15 | GVArray [Something] -- 17 | GList [Something] -- 18 | GSet [Something] -- 19 | GMap [(Something, Something)] -- 20 | GUserType Int Int deriving (Show)
skill-lang/skill
src/main/resources/haskell/D_Types.hs
bsd-3-clause
1,599
0
8
832
273
180
93
33
0
module Data.GeoJSON ( module Data.GeoJSON.Classes , module Data.GeoJSON.Position , module Data.GeoJSON.Geometries , module Data.GeoJSON.Features ) where import Data.GeoJSON.Classes import Data.GeoJSON.Features import Data.GeoJSON.Geometries import Data.GeoJSON.Position
alios/geojson-types
src/Data/GeoJSON.hs
bsd-3-clause
316
0
5
70
60
41
19
9
0
{-# OPTIONS -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances #-} module Fay.Exts.NoAnnotation where import Fay.Compiler.Prelude import Data.List.Split (splitOn) import Data.String import qualified Language.Haskell.Exts.Annotated as A type Alt = A.Alt () type BangType = A.BangType () type ClassDecl = A.ClassDecl () type Decl = A.Decl () type DeclHead = A.DeclHead () type Ex = A.Exp () type Exp = A.Exp () type ExportSpec = A.ExportSpec () type FieldDecl = A.FieldDecl () type FieldUpdate = A.FieldUpdate () type GadtDecl = A.GadtDecl () type GuardedRhs = A.GuardedRhs () type ImportDecl = A.ImportDecl () type ImportSpec = A.ImportSpec () type Literal = A.Literal () type Match = A.Match () type Module = A.Module () type ModuleName = A.ModuleName () type ModulePragma = A.ModulePragma () type Name = A.Name () type Pat = A.Pat () type PatField = A.PatField () type QName = A.QName () type QOp = A.QOp () type QualConDecl = A.QualConDecl () type QualStmt = A.QualStmt () type Rhs = A.Rhs () type Sign = A.Sign () type SpecialCon = A.SpecialCon () type SrcLoc = A.SrcLoc type SrcSpan = A.SrcSpan type SrcSpanInfo = A.SrcSpanInfo type Stmt = A.Stmt () type TyVarBind = A.TyVarBind () type Type = A.Type () unAnn :: Functor f => f a -> f () unAnn = void -- | Helpful for some things. instance IsString (A.Name ()) where fromString n@(c:_) | isAlpha c || c == '_' = A.Ident () n | otherwise = A.Symbol () n fromString [] = error "Name fromString: empty string" -- | Helpful for some things. instance IsString (A.QName ()) where fromString s = case splitOn "." s of [] -> error "QName fromString: empty string" [x] -> A.UnQual () $ fromString x xs -> A.Qual () (fromString $ intercalate "." $ init xs) $ fromString (last xs) -- | Helpful for writing qualified symbols (Fay.*). instance IsString (A.ModuleName ()) where fromString = A.ModuleName ()
beni55/fay
src/Fay/Exts/NoAnnotation.hs
bsd-3-clause
1,946
0
14
408
750
398
352
56
1
{-# LANGUAGE OverloadedStrings #-} module Bead.View.Content.Notifications.Page ( notifications ) where import Control.Monad (forM_) import Data.String (fromString) import Text.Printf (printf) import qualified Bead.Controller.Pages as Pages import Bead.View.Content import Bead.Domain.Entity.Notification import qualified Bead.View.Content.Bootstrap as Bootstrap import qualified Bead.Controller.UserStories as Story (notifications) import Text.Blaze.Html5 as H hiding (link, map) data PageData = PageData { pdNotifications :: [(Notification, NotificationState, NotificationReference)] , pdUserTime :: UserTimeConverter } notifications :: ViewHandler notifications = ViewHandler notificationsPage notificationsPage :: GETContentHandler notificationsPage = do pd <- PageData <$> (userStory Story.notifications) <*> userTimeZoneToLocalTimeConverter return $ notificationsContent pd notificationsContent :: PageData -> IHtml notificationsContent p = do msg <- getI18N return $ do let notifs = pdNotifications p if (null notifs) then do H.p $ fromString $ msg $ msg_Notifications_NoNotifications "There are no notifications." else do Bootstrap.row $ Bootstrap.colMd12 $ do Bootstrap.listGroup $ forM_ notifs $ \(notif, state, ref) -> (if state == Seen then Bootstrap.listGroupLinkItem else Bootstrap.listGroupAlertLinkItem Bootstrap.Info ) (linkFromNotif ref) . fromString $ unwords [ "[" ++ (showDate . pdUserTime p $ notifDate notif) ++ "]" , translateEvent msg $ notifEvent notif ] linkFromNotif :: NotificationReference -> String linkFromNotif = notificationReference (\ak sk ck -> routeWithAnchor (Pages.submissionDetails ak sk ()) ck) (\ak sk _ek -> routeWithAnchor (Pages.submissionDetails ak sk ()) SubmissionDetailsEvaluationDiv) (\sk _ek -> routeOf $ Pages.viewUserScore sk ()) (\ak -> routeOf $ Pages.submissionList ak ()) (\ak -> routeOf $ Pages.viewAssessment ak ()) (routeOf $ Pages.notifications ()) -- System notifications are one liners -- Resolve a notification event to an actual message through the I18N layer. translateEvent :: I18N -> NotificationEvent -> String translateEvent i18n e = case e of NE_CourseAdminCreated course -> printf (i18n $ msg_NE_CourseAdminCreated "A course has been assigned: %s") course NE_CourseAdminAssigned course assignee -> printf (i18n $ msg_NE_CourseAdminAssigned "An administrator has been added to course \"%s\": %s") course assignee NE_TestScriptCreated creator course -> printf (i18n $ msg_NE_TestScriptCreated "%s created a new test script for course \"%s\"") creator course NE_TestScriptUpdated editor script course -> printf (i18n $ msg_NE_TestScriptUpdated "%s modified test script \"%s\" for course \"%s\"") editor script course NE_RemovedFromGroup group deletor -> printf (i18n $ msg_NE_RemovedFromGroup "Removed from group \"%s\" by %s") group deletor NE_GroupAdminCreated course creator group -> printf (i18n $ msg_NE_GroupAdminCreated "A group of course \"%s\" has been assigned by %s: %s") course creator group NE_GroupAssigned group course assignor assignee -> printf (i18n $ msg_NE_GroupAssigned "Group \"%s\" of course \"%s\" has been assigned to %s by %s") group course assignor assignee NE_GroupCreated course creator group -> printf (i18n $ msg_NE_GroupCreated "A group has been created for course \"%s\" by %s: %s") course creator group NE_GroupAssignmentCreated creator group course assignment -> printf (i18n $ msg_NE_GroupAssignmentCreated "%s created a new assignment for group \"%s\" (\"%s\"): %s") creator group course assignment NE_CourseAssignmentCreated creator course assignment -> printf (i18n $ msg_NE_CourseAssignmentCreated "%s created a new assignment for course \"%s\": %s") creator course assignment NE_GroupAssessmentCreated creator group course assessment -> printf (i18n $ msg_NE_GroupAssessmentCreated "%s created a new assessment for group \"%s\" (\"%s\"): %s") creator group course assessment NE_CourseAssessmentCreated creator course assessment -> printf (i18n $ msg_NE_CourseAssessmentCreated "%s created a new assessment for course \"%s\": %s") creator course assessment NE_AssessmentUpdated editor assessment -> printf (i18n $ msg_NE_AssessmentUpdated "%s modified assessment: %s") editor assessment NE_AssignmentUpdated editor assignment -> printf (i18n $ msg_NE_AssignmentUpdated "%s modified assignment: %s") editor assignment NE_EvaluationCreated evaluator submission -> printf (i18n $ msg_NE_EvaluationCreated "%s evaluated submission: %s") evaluator submission NE_AssessmentEvaluationUpdated editor assessment -> printf (i18n $ msg_NE_AssessmentEvaluationUpdated "%s modified evaluation of score: %s") editor assessment NE_AssignmentEvaluationUpdated editor submission -> printf (i18n $ msg_NE_AssignmentEvaluationUpdated "%s modified evaluation of submission: %s") editor submission NE_CommentCreated commenter submission body -> printf (i18n $ msg_NE_CommentCreated "%s commented on submission %s: \"%s\"") commenter submission body
andorp/bead
src/Bead/View/Content/Notifications/Page.hs
bsd-3-clause
5,478
0
26
1,143
1,152
586
566
105
18
{-# LANGUAGE FlexibleContexts, OverloadedStrings, RecordWildCards, ScopedTypeVariables, ConstraintKinds, PatternGuards #-} -- |The HTTP/JSON plumbing used to implement the 'WD' monad. -- -- These functions can be used to create your own 'WebDriver' instances, providing extra functionality for your application if desired. All exports -- of this module are subject to change at any point. module Test.WebDriver.Internal ( mkRequest, sendHTTPRequest , getJSONResult, handleJSONErr, handleRespSessionId , WDResponse(..) ) where import Test.WebDriver.Class import Test.WebDriver.JSON import Test.WebDriver.Session import Test.WebDriver.Exceptions.Internal import Network.HTTP.Client (httpLbs, Request(..), RequestBody(..), Response(..), HttpException(ResponseTimeout)) import Network.HTTP.Types.Header import Network.HTTP.Types.Status (Status(..)) import Data.Aeson import Data.Aeson.Types (typeMismatch) import Data.Text as T (Text, splitOn, null) import qualified Data.Text.Encoding as TE import Data.ByteString.Lazy.Char8 (ByteString) import Data.ByteString.Lazy.Char8 as LBS (length, unpack, null, fromStrict) import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Base64.Lazy as B64 import Control.Monad.Base import Control.Exception.Lifted (throwIO) import Control.Applicative import Control.Exception (Exception, SomeException(..), toException, fromException, try) import Data.String (fromString) import Data.Word (Word8) import Data.Default.Class import Prelude -- hides some "unused import" warnings -- |Constructs an HTTP 'Request' value when given a list of headers, HTTP request method, and URL fragment mkRequest :: (WDSessionState s, ToJSON a) => Method -> Text -> a -> s Request mkRequest meth wdPath args = do WDSession {..} <- getSession let body = case toJSON args of Null -> "" --passing Null as the argument indicates no request body other -> encode other return def { host = wdSessHost , port = wdSessPort , path = wdSessBasePath `BS.append` TE.encodeUtf8 wdPath , requestBody = RequestBodyLBS body , requestHeaders = wdSessRequestHeaders ++ [ (hAccept, "application/json;charset=UTF-8") , (hContentType, "application/json;charset=UTF-8") , (hContentLength, fromString . show . LBS.length $ body) ] , checkStatus = \_ _ _ -> Nothing -- all status codes handled by getJSONResult , method = meth } -- |Sends an HTTP request to the remote WebDriver server sendHTTPRequest :: (WDSessionStateIO s) => Request -> s (Either SomeException (Response ByteString)) sendHTTPRequest req = do s@WDSession{..} <- getSession (nRetries, tryRes) <- liftBase . retryOnTimeout wdSessHTTPRetryCount $ httpLbs req wdSessHTTPManager let h = SessionHistory { histRequest = req , histResponse = tryRes , histRetryCount = nRetries } putSession s { wdSessHist = wdSessHistUpdate h wdSessHist } return tryRes retryOnTimeout :: Int -> IO a -> IO (Int, (Either SomeException a)) retryOnTimeout maxRetry go = retry' 0 where retry' nRetries = do eitherV <- try go case eitherV of (Left e) | Just ResponseTimeout <- fromException e , maxRetry > nRetries -> retry' (succ nRetries) other -> return (nRetries, other) -- |Parses a 'WDResponse' object from a given HTTP response. getJSONResult :: (WDSessionStateControl s, FromJSON a) => Response ByteString -> s (Either SomeException a) getJSONResult r --malformed request errors | code >= 400 && code < 500 = do lastReq <- mostRecentHTTPRequest <$> getSession returnErr . UnknownCommand . maybe reason show $ lastReq --server-side errors | code >= 500 && code < 600 = case lookup hContentType headers of Just ct | "application/json" `BS.isInfixOf` ct -> parseJSON' (maybe body LBS.fromStrict $ lookup "X-Response-Body-Start" headers) >>= handleJSONErr >>= maybe noReturn returnErr | otherwise -> returnHTTPErr ServerError Nothing -> returnHTTPErr (ServerError . ("HTTP response missing content type. Server reason was: "++)) --redirect case (used as a response to createSession requests) | code == 302 || code == 303 = case lookup hLocation headers of Nothing -> returnErr . HTTPStatusUnknown code $ LBS.unpack body Just loc -> do let sessId = last . filter (not . T.null) . splitOn "/" . fromString $ BS.unpack loc modifySession $ \sess -> sess {wdSessId = Just (SessionId sessId)} noReturn -- No Content response | code == 204 = noReturn -- HTTP Success | code >= 200 && code < 300 = if LBS.null body then noReturn else do rsp@WDResponse {rspVal = val} <- parseJSON' body handleJSONErr rsp >>= maybe (handleRespSessionId rsp >> Right <$> fromJSON' val) returnErr -- other status codes: return error | otherwise = returnHTTPErr (HTTPStatusUnknown code) where --helper functions returnErr :: (Exception e, Monad m) => e -> m (Either SomeException a) returnErr = return . Left . toException returnHTTPErr errType = returnErr . errType $ reason noReturn = Right <$> fromJSON' Null --HTTP response variables code = statusCode status reason = BS.unpack $ statusMessage status status = responseStatus r body = responseBody r headers = responseHeaders r handleRespSessionId :: (WDSessionStateIO s) => WDResponse -> s () handleRespSessionId WDResponse{rspSessId = sessId'} = do sess@WDSession { wdSessId = sessId} <- getSession case (sessId, (==) <$> sessId <*> sessId') of -- if our monad has an uninitialized session ID, initialize it from the response object (Nothing, _) -> putSession sess { wdSessId = sessId' } -- if the response ID doesn't match our local ID, throw an error. (_, Just False) -> throwIO . ServerError $ "Server response session ID (" ++ show sessId' ++ ") does not match local session ID (" ++ show sessId ++ ")" _ -> return () handleJSONErr :: (WDSessionStateControl s) => WDResponse -> s (Maybe SomeException) handleJSONErr WDResponse{rspStatus = 0} = return Nothing handleJSONErr WDResponse{rspVal = val, rspStatus = status} = do sess <- getSession errInfo <- fromJSON' val let screen = B64.decodeLenient <$> errScreen errInfo errInfo' = errInfo { errSess = Just sess , errScreen = screen } e errType = toException $ FailedCommand errType errInfo' return . Just $ case status of 7 -> e NoSuchElement 8 -> e NoSuchFrame 9 -> toException . UnknownCommand . errMsg $ errInfo 10 -> e StaleElementReference 11 -> e ElementNotVisible 12 -> e InvalidElementState 13 -> e UnknownError 15 -> e ElementIsNotSelectable 17 -> e JavascriptError 19 -> e XPathLookupError 21 -> e Timeout 23 -> e NoSuchWindow 24 -> e InvalidCookieDomain 25 -> e UnableToSetCookie 26 -> e UnexpectedAlertOpen 27 -> e NoAlertOpen 28 -> e ScriptTimeout 29 -> e InvalidElementCoordinates 30 -> e IMENotAvailable 31 -> e IMEEngineActivationFailed 32 -> e InvalidSelector 33 -> e SessionNotCreated 34 -> e MoveTargetOutOfBounds 51 -> e InvalidXPathSelector 52 -> e InvalidXPathSelectorReturnType _ -> e UnknownError -- |Internal type representing the JSON response object data WDResponse = WDResponse { rspSessId :: Maybe SessionId , rspStatus :: Word8 , rspVal :: Value } deriving (Eq, Show) instance FromJSON WDResponse where parseJSON (Object o) = WDResponse <$> o .:?? "sessionId" .!= Nothing <*> o .: "status" <*> o .:?? "value" .!= Null parseJSON v = typeMismatch "WDResponse" v
wuzzeb/hs-webdriver
src/Test/WebDriver/Internal.hs
bsd-3-clause
8,292
0
21
2,207
2,067
1,086
981
161
26
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE BangPatterns #-} module Constraints.Set.Implementation ( ConstraintError(..), Variance(..), Inclusion, SetExpression(..), SolvedSystem, emptySet, universalSet, setVariable, atom, term, (<=!), solveSystem, leastSolution ) where import Control.Exception import Control.Failure import qualified Data.Foldable as F import Data.Function ( on ) import qualified Data.List as L import Data.Map ( Map ) import qualified Data.Map as M import Data.Maybe ( fromMaybe ) import Data.Monoid import Data.Set ( Set ) import qualified Data.Set as S import Data.Typeable type Worklist v c = Set (PredSegment v c) -- | The type used to represent that inductive form constraint graph -- during saturation. This form is more efficient to saturate. type IFGraph v c = Map (SetExpression v c) (Edges v c) data Edges v c = Edges { predecessors :: Set (SetExpression v c) , successors :: Set (SetExpression v c) } deriving (Eq, Ord) -- | The solved constraint system data SolvedSystem v c = SolvedSystem { systemIFGraph :: IFGraph v c } instance (Eq v, Eq c) => Eq (SolvedSystem v c) where (==) = (==) `on` systemIFGraph -- | A type describing an edge added in one iteration of the -- transitive closure. These let us know which nodes need to be -- revisited in the next iteration (and in which direction - -- predecessor or successor) data PredSegment v c = PSPred (SetExpression v c) (SetExpression v c) | PSSucc (SetExpression v c) (SetExpression v c) deriving (Eq, Ord) -- | Create a set expression representing the empty set emptySet :: SetExpression v c emptySet = EmptySet -- | Create a set expression representing the universal set universalSet :: SetExpression v c universalSet = UniversalSet -- | Create a new set variable with the given label setVariable :: (Ord v) => v -> SetExpression v c setVariable = SetVariable -- | Atomic terms have a label and arity zero. This is a shortcut for -- -- > term conLabel [] [] atom :: (Ord c) => c -> SetExpression v c atom conLabel = ConstructedTerm conLabel [] [] -- | This returns a function to create terms from lists of -- SetExpressions. It is meant to be partially applied so that as -- many terms as possible can share the same reference to a label and -- signature. -- -- The list of variances specifies the variance (Covariant or -- Contravariant) for each argument of the term. A mismatch in the -- length of the variance descriptor and the arguments to the term -- will result in a run-time error. term :: (Ord v, Ord c) => c -> [Variance] -> ([SetExpression v c] -> SetExpression v c) term = ConstructedTerm -- | Construct an inclusion relation between two set expressions. -- -- This is equivalent to @se1 ⊆ se2@. (<=!) :: (Ord c, Ord v) => SetExpression v c -> SetExpression v c -> Inclusion v c (<=!) = Inclusion -- | Tags to mark term arguments as covariant or contravariant. data Variance = Covariant | Contravariant deriving (Eq, Ord, Show) -- | Expressions in the language of set constraints. data SetExpression v c = EmptySet | UniversalSet | SetVariable v | ConstructedTerm c [Variance] [SetExpression v c] deriving (Eq, Ord) instance (Show v, Show c) => Show (SetExpression v c) where show EmptySet = "∅" show UniversalSet = "U" show (SetVariable v) = show v show (ConstructedTerm c _ es) = concat [ show c, "(" , L.intercalate ", " (map show es) , ")" ] -- | An inclusion is a constraint of the form @se1 ⊆ se2@ data Inclusion v c = Inclusion (SetExpression v c) (SetExpression v c) deriving (Eq, Ord) instance (Show v, Show c) => Show (Inclusion v c) where show (Inclusion lhs rhs) = concat [ show lhs, " ⊆ ", show rhs ] -- | The types of errors that can be encountered during constraint -- resolution data ConstraintError v c = NoSolution (Inclusion v c) -- ^ The system has no solution because of the given inclusion constraint | NoVariableLabel v -- ^ When searching for a solution, the requested variable was not present in the constraint graph deriving (Eq, Ord, Show, Typeable) instance (Typeable v, Typeable c, Show v, Show c) => Exception (ConstraintError v c) -- | Simplify one set expression. The expression may be eliminated, -- passed through unchanged, or split into multiple new expressions. simplifyInclusion :: (Ord c, Ord v, Eq v, Eq c) => Inclusion v c -- ^ The inclusion to be simplified -> [Inclusion v c] simplifyInclusion i = case i of -- Eliminate constraints of the form A ⊆ A Inclusion (SetVariable v1) (SetVariable v2) -> if v1 == v2 then [] else [i] Inclusion UniversalSet EmptySet -> error "Malformed constraint univ < emptyset" Inclusion (ConstructedTerm c1 s1 ses1) (ConstructedTerm c2 s2 ses2) -> let sigLen = length s1 triples = zip3 s1 ses1 ses2 in case c1 == c2 && s1 == s2 && sigLen == length ses1 && sigLen == length ses2 of False -> error "Malformed constraint cterm mismatch" True -> concatMap simplifyWithVariance triples Inclusion UniversalSet (ConstructedTerm _ _ _) -> error "Malformed constraint univ < cterm" Inclusion (ConstructedTerm _ _ _) EmptySet -> error "Malformed constraint cterm < emptyset" -- Eliminate constraints of the form A ⊆ 1 Inclusion _ UniversalSet -> [] -- 0 ⊆ A Inclusion EmptySet _ -> [] -- Keep anything else (atomic forms) _ -> [i] -- | Simplifies an inclusion taking variance into account; this is a -- helper for 'simplifyInclusion' that deals with the variance of -- constructed terms. The key here is that contravariant inclusions -- are /flipped/. simplifyWithVariance :: (Ord c, Ord v, Eq v, Eq c) => (Variance, SetExpression v c, SetExpression v c) -> [Inclusion v c] simplifyWithVariance (Covariant, se1, se2) = simplifyInclusion (Inclusion se1 se2) simplifyWithVariance (Contravariant, se1, se2) = simplifyInclusion (Inclusion se2 se1) -- | Simplify all of the inclusions in the initial constraint system. simplifySystem :: (Ord c, Ord v, Eq v, Eq c) => [Inclusion v c] -> [Inclusion v c] simplifySystem = concatMap simplifyInclusion dfs :: (Ord c, Ord v) => IFGraph v c -> SetExpression v c -> Set (SetExpression v c) dfs g = go mempty where go !visited v | S.member v visited = visited | otherwise = case M.lookup v g of Nothing -> S.insert v visited Just Edges { predecessors = ps } -> F.foldl' go (S.insert v visited) ps -- | Compute the least solution for the given variable. This can fail -- if the requested variable is not present in the constraint system -- (see 'ConstraintError'). -- -- LS(y) = All source nodes with a predecessor edge to y, plus LS(x) -- for all x where x has a predecessor edge to y. leastSolution :: (Failure (ConstraintError v c) m, Ord v, Ord c) => SolvedSystem v c -> v -> m [SetExpression v c] leastSolution (SolvedSystem g0) varLabel = do let reached = dfs g0 (SetVariable varLabel) return $ F.foldr addTerm [] reached where -- ex :: ConstraintError v c -- ex = NoVariableLabel varLabel addTerm v acc = case v of ConstructedTerm _ _ _ -> v : acc _ -> acc -- | Simplify and solve the system of set constraints solveSystem :: (Failure (ConstraintError v c) m, Eq c, Eq v, Ord c, Ord v) => [Inclusion v c] -> m (SolvedSystem v c) solveSystem = return . constraintsToIFGraph . simplifySystem -- | The real worker to solve the system and convert from an IFGraph -- to a SolvedGraph. constraintsToIFGraph :: (Ord v, Ord c) => [Inclusion v c] -> SolvedSystem v c constraintsToIFGraph is = SolvedSystem { systemIFGraph = saturateGraph g0 wl } where (g0, wl) = buildInitialGraph is -- | Build an initial IF constraint graph that contains all of the -- vertices and the edges induced by the initial simplified constraint -- system. buildInitialGraph :: (Ord v, Ord c) => [Inclusion v c] -> (IFGraph v c, Worklist v c) buildInitialGraph is = L.foldl' addInclusion (mempty, mempty) is -- | Adds an inclusion to the constraint graph (adding vertices if -- necessary). Returns the set of nodes that are affected (and will -- need more transitive edges). addInclusion :: (Eq c, Ord v, Ord c) => (IFGraph v c, Worklist v c) -> Inclusion v c -> (IFGraph v c, Worklist v c) addInclusion acc i = case i of -- This is the key to an inductive form graph (rather than -- standard form) Inclusion e1@(SetVariable v1) e2@(SetVariable v2) | v1 < v2 -> addSuccEdge acc e1 e2 | otherwise -> addPredEdge acc e1 e2 Inclusion e1@(ConstructedTerm _ _ _) e2@(SetVariable _) -> addPredEdge acc e1 e2 Inclusion e1@(SetVariable _) e2@(ConstructedTerm _ _ _) -> addSuccEdge acc e1 e2 _ -> error "Constraints.Set.Solver.addInclusion: unexpected expression" -- | Add a predecessor edge (l is a predecessor of r) addPredEdge :: (Ord c, Ord v) => (IFGraph v c, Worklist v c) -> SetExpression v c -> SetExpression v c -> (IFGraph v c, Worklist v c) addPredEdge acc@(!g, !work) l r = case M.lookup r g of Nothing -> let es = Edges { predecessors = S.singleton l, successors = S.empty } in (M.insert r es g, S.insert (PSPred l r) work) Just es | S.member l (predecessors es) -> acc | otherwise -> let es' = es { predecessors = S.insert l (predecessors es) } in (M.insert r es' g, S.insert (PSPred l r) work) addSuccEdge :: (Ord c, Ord v) => (IFGraph v c, Worklist v c) -> SetExpression v c -> SetExpression v c -> (IFGraph v c, Worklist v c) addSuccEdge acc@(!g, !work) l r = case M.lookup l g of Nothing -> let es = Edges { predecessors = S.empty, successors = S.singleton r } in (M.insert l es g, S.insert (PSSucc l r) work) Just es | S.member r (successors es) -> acc | otherwise -> let es' = es { successors = S.insert r (successors es) } in (M.insert l es' g, S.insert (PSSucc l r) work) -- | For each node L in the graph, follow its predecessor edges to -- obtain set X. For each ndoe in X, follow its successor edges -- giving a list of R. Generate L ⊆ R and simplify it with -- 'simplifyInclusion'. These are new edges (collect them all in a -- set, discarding existing edges). -- -- After a pass, insert all of the new edges -- -- Repeat until no new edges are found. -- -- An easy optimization is to base the next iteration only on the -- newly-added edges (since any additions in the next iteration must -- be due to those new edges). It would require searching forward -- (for pred edges) and backward (for succ edges). -- -- Also perform online cycle detection per FFSA98 -- -- This function can fail if a constraint generated by the saturation -- implies that no solution is possible. I think that probably -- shouldn't ever happen but I have no proof. saturateGraph :: (Ord v, Ord c, Eq c) => IFGraph v c -> Worklist v c -> IFGraph v c saturateGraph g0 wl0 = let (g1, wl1) = F.foldl' addNewEdges (g0, mempty) wl0 in if S.null wl1 then g1 else saturateGraph g1 wl1 addNewEdges :: (Ord v, Ord c) => (IFGraph v c, Worklist v c) -> PredSegment v c -> (IFGraph v c, Worklist v c) addNewEdges acc@(!g0, _) (PSPred l r) = fromMaybe acc $ do Edges { successors = ss } <- M.lookup r g0 return $ F.foldl' (addNewInclusions l) acc ss where addNewInclusions lhs a rhs = F.foldl' addInclusion a $ simplifyInclusion (Inclusion lhs rhs) addNewEdges acc@(!g0, _) (PSSucc l r) = fromMaybe acc $ do Edges { predecessors = ps } <- M.lookup l g0 return $ F.foldl' (addNewInclusions r) acc ps where addNewInclusions rhs a lhs = F.foldl' addInclusion a $ simplifyInclusion (Inclusion lhs rhs) -- Cycle detection {- -- Track both a visited set and a "the nodes on the cycle" set checkChain :: Bool -> ConstraintEdge -> IFGraph -> Int -> Int -> Maybe IntSet checkChain False _ _ _ _ = Nothing checkChain True tgt g from to = do chain <- snd $ checkChainWorker (mempty, Nothing) tgt g from to return $ IS.insert from chain -- Only checkChainWorker adds things to the visited set checkChainWorker :: (IntSet, Maybe IntSet) -> ConstraintEdge -> IFGraph -> Int -> Int -> (IntSet, Maybe IntSet) checkChainWorker (visited, chain) tgt g from to | from == to = (visited, Just (IS.singleton to)) | otherwise = let visited' = IS.insert from visited in G.foldPre (checkChainEdges tgt g to) (visited', chain) g from -- Once we have a branch of the DFS that succeeds, just keep that -- value. This manages augmenting the set of nodes on the chain checkChainEdges :: ConstraintEdge -> IFGraph -> Int -> Int -> ConstraintEdge -> (IntSet, Maybe IntSet) -> (IntSet, Maybe IntSet) checkChainEdges _ _ _ _ _ acc@(_, Just _) = acc checkChainEdges tgt g to v lbl acc@(visited, Nothing) | tgt /= lbl = acc | IS.member v visited = acc | otherwise = -- If there was no hit on this branch, just return the accumulator -- from the recursive call (which has an updated visited set) case checkChainWorker acc tgt g v to of acc'@(_, Nothing) -> acc' (visited', Just chain) -> (visited', Just (IS.insert v chain)) -- | Ask if we should bother to check for cycles this iteration checkCycles :: BuilderMonad v c Bool checkCycles = do BuilderState _ _ cnt <- get case cnt of Nothing -> return True Just c -> return $ c <= 1000 -- FIXME: Maybe try to mark nodes as "exhausted" after they can't induce -- any new edges? -- -- Also, perhaps use bitmasks instead of sets for something? -- | Try to detect cycles as in FFSA98. Note that this is currently -- broken somehow. It detects cycles just fine, but removing them -- seems to damage the constraint graph somehow making the solving -- phase much slower. tryCycleDetection :: (Ord c, Ord v) => Bool -> IFGraph -> Worklist -> ConstraintEdge -> Int -> Int -> BuilderMonad v c (IFGraph, Worklist) tryCycleDetection _ g2 affected Succ eid1 eid2 = simpleAddEdge g2 affected Succ eid1 eid2 tryCycleDetection removeCycles g2 affected etype eid1 eid2 = case checkChain removeCycles (otherLabel etype) g2 eid1 eid2 of Just chain | not (IS.null chain) -> do -- Make all of the nodes in the cycle refer to the min element -- (the reference bit is taken care of in the node lookup and in -- the result lookup). -- -- For each of the nodes in @rest@, repoint their incoming and -- outgoing edges. BuilderState m v c <- get -- Find all of the edges from any node pointing to a node in -- @rest@. Also find all edges from @rest@ out into the rest of -- the graph. Then resolve those back to inclusions using @v@ -- and call addInclusion over these new inclusions (after -- blowing away the old ones) let (representative, rest) = IS.deleteFindMin chain thisExp = V.unsafeIndex v representative newIncoming = IS.foldr' (srcsOf g2 v chain thisExp) [] rest newInclusions = IS.foldr' (destsOf g2 v chain thisExp) newIncoming rest g3 = IS.foldr' G.removeVertex g2 rest m' = IS.foldr' (replaceWith v representative) m rest put $! BuilderState m' v (fmap (+1) c) foldM (addInclusion False) (g3, affected) newInclusions -- `debug` -- ("Removing " ++ show (IS.size chain) ++ " cycle (" ++ show eid1 ++ -- " to " ++ show eid2 ++ "). " ++ show (CG.numNodes g3) ++ -- " nodes left in the graph.") -- Nothing was affected because we didn't add any edges _ -> simpleAddEdge g2 affected etype eid1 eid2 where otherLabel Succ = Pred otherLabel Pred = Succ srcsOf :: IFGraph -> Vector (SetExpression v c) -> IntSet -> SetExpression v c -> Int -> [Inclusion v c] -> [Inclusion v c] srcsOf g v chain newDst oldId acc = G.foldPre (\srcId _ a -> case IS.member srcId chain of True -> a False -> (V.unsafeIndex v srcId :<= newDst) : a) acc g oldId destsOf :: IFGraph -> Vector (SetExpression v c) -> IntSet -> SetExpression v c -> Int -> [Inclusion v c] -> [Inclusion v c] destsOf g v chain newSrc oldId acc = G.foldSuc (\dstId _ a -> case IS.member dstId chain of True -> a False -> (newSrc :<= V.unsafeIndex v dstId) : a) acc g oldId -- | Change the ID of the node with ID @i@ to @repr@ replaceWith :: (Ord k) => Vector k -> a -> Int -> Map k a -> Map k a replaceWith v repr i m = case M.lookup se m of Nothing -> m Just _ -> M.insert se repr m where se = V.unsafeIndex v i -}
travitch/ifscs
src/Constraints/Set/Implementation.hs
bsd-3-clause
17,569
0
17
4,725
3,288
1,733
1,555
207
10
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} -- | Parses strings into a set of tokens using the given rules. module Youtan.Lexical.Tokenizer ( tokenize , tokenizeDrops , tokenizeT , tokenizeTDrops , Rules , Wrapper ) where import Control.Monad.State import Control.Monad.Except import Youtan.Regex.DFM ( DFM, fromString, longestMatchDFM ) -- | Represents a set of parsing rules. type Rules a = [ ( String, String -> a ) ] -- | Same as 'Rules' with prepared 'DFM' per each rule. data ParsingRules a = ParsingRules { dfm :: !DFM , matches :: ![ String -> a ] , rulesCount :: !Int } -- | Build 'DFM' per each rule. buildParingRules :: Rules a -> [ String ] -> ParsingRules a buildParingRules rules drops = ParsingRules { dfm = mconcat ( map fromString ( map fst rules ++ drops ) ) , matches = map snd rules , rulesCount = length rules } -- | Applies a set of parsing rules to split the input string -- into a set of tokens. tokenize :: MonadPlus m => Rules a -> String -> m a tokenize r = tokenizeDrops r [] -- | Monadic version of 'tokenize' wrappers errors into a monad. tokenizeT :: ( Wrapper w, MonadPlus m ) => Rules a -> String -> w ( m a ) tokenizeT rules = tokenizeTDrops rules [] -- | Applies a set of parsing rules to split the input string -- into a set of tokens. tokenizeDrops :: MonadPlus m => Rules a -> [ String ] -> String -> m a tokenizeDrops r d s = either error id ( tokenizeTDrops r d s ) -- | Monadic version of 'tokenize' wrappers errors into a monad. tokenizeTDrops :: ( Wrapper w, MonadPlus m ) => Rules a -> [ String ] -> String -> w ( m a ) tokenizeTDrops rules drops = evalStateT ( parse mzero ( buildParingRules rules drops ) ) -- | Shortcut for types. type P w a = StateT String w a -- | Shortcut for monad error. type Wrapper w = MonadError String w -- | Chooses the longest match and applis related modifier to it. choice :: Wrapper w => ParsingRules a -> P w ( Maybe a ) choice ParsingRules{..} = do inp <- get case longestMatchDFM dfm inp of Nothing -> failMessage Just ( x, mID ) -> if x > 0 then do modify ( drop x ) return $ if use mID then Just ( ( matches !! mID ) ( take x inp ) ) else Nothing else failMessage where use mDI = mDI < rulesCount failMessage = ( take 10 <$> get ) >>= throwError . (++) "All options failed " -- | Checks if the whole input is consumed. done :: Wrapper w => P w Bool done = null <$> get -- | Splits the input into a set of tokens. parse :: ( MonadPlus m, Wrapper w ) => m a -> ParsingRules a -> P w ( m a ) parse stack rules = do status <- done if status then return stack else do x <- choice rules case x of Just y -> parse ( mplus stack ( pure y ) ) rules Nothing -> parse stack rules
triplepointfive/Youtan
src/Youtan/Lexical/Tokenizer.hs
bsd-3-clause
2,884
0
19
725
826
433
393
68
4
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RecordWildCards #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.FSM.Internal.Process -- Copyright : (c) Tim Watson 2017 -- License : BSD3 (see the file LICENSE) -- -- Maintainer : Tim Watson <[email protected]> -- Stability : experimental -- Portability : non-portable (requires concurrency) -- -- The /Managed Process/ implementation of an FSM process. -- -- See "Control.Distributed.Process.ManagedProcess". ----------------------------------------------------------------------------- module Control.Distributed.Process.FSM.Internal.Process ( start , run ) where import Control.Distributed.Process ( Process , ProcessId , SendPort , sendChan , spawnLocal , handleMessage , wrapMessage ) import qualified Control.Distributed.Process as P ( Message ) import Control.Distributed.Process.Extras (ExitReason) import Control.Distributed.Process.Extras.Time (Delay(Infinity)) import Control.Distributed.Process.FSM.Internal.Types hiding (liftIO) import Control.Distributed.Process.ManagedProcess ( ProcessDefinition(..) , PrioritisedProcessDefinition(filters) , Action , ProcessAction , InitHandler , InitResult(..) , DispatchFilter , ExitState(..) , defaultProcess , prioritised ) import qualified Control.Distributed.Process.ManagedProcess as MP (pserve) import Control.Distributed.Process.ManagedProcess.Server.Priority ( safely ) import Control.Distributed.Process.ManagedProcess.Server ( handleRaw , handleInfo , continue ) import Control.Distributed.Process.ManagedProcess.Internal.Types ( ExitSignalDispatcher(..) , DispatchPriority(PrioritiseInfo) ) import Control.Monad (void) import Data.Maybe (isJust) import qualified Data.Sequence as Q (empty) -- | Start an FSM process start :: forall s d . (Show s, Eq s) => s -> d -> (Step s d) -> Process ProcessId start s d p = spawnLocal $ run s d p -- | Run an FSM process. NB: this is a /managed process listen-loop/ -- and will not evaluate to its result until the server process stops. run :: forall s d . (Show s, Eq s) => s -> d -> (Step s d) -> Process () run s d p = MP.pserve (s, d, p) fsmInit (processDefinition p) fsmInit :: forall s d . (Show s, Eq s) => InitHandler (s, d, Step s d) (State s d) fsmInit (st, sd, prog) = let st' = State st sd prog Nothing (const $ return ()) Q.empty Q.empty in return $ InitOk st' Infinity processDefinition :: forall s d . (Show s) => Step s d -> PrioritisedProcessDefinition (State s d) processDefinition prog = (prioritised defaultProcess { infoHandlers = [ handleInfo handleRpcRawInputs , handleRaw handleAllRawInputs ] , exitHandlers = [ ExitSignalDispatcher (\s _ m -> handleExitReason s m) ] , shutdownHandler = handleShutdown } (walkPFSM prog [])) { filters = (walkFSM prog []) } -- we should probably make a Foldable (Step s d) for these walkFSM :: forall s d . Step s d -> [DispatchFilter (State s d)] -> [DispatchFilter (State s d)] walkFSM st acc | SafeWait evt act <- st = walkFSM act $ safely (\_ m -> isJust $ decodeToEvent evt m) : acc | Await _ act <- st = walkFSM act acc | Sequence ac1 ac2 <- st = walkFSM ac1 $ walkFSM ac2 acc | Init ac1 ac2 <- st = walkFSM ac1 $ walkFSM ac2 acc | Alternate ac1 ac2 <- st = walkFSM ac1 $ walkFSM ac2 acc -- both branches need filter defs | otherwise = acc walkPFSM :: forall s d . Step s d -> [DispatchPriority (State s d)] -> [DispatchPriority (State s d)] walkPFSM st acc | SafeWait evt act <- st = walkPFSM act (checkPrio evt acc) | Await evt act <- st = walkPFSM act (checkPrio evt acc) | Sequence ac1 ac2 <- st = walkPFSM ac1 $ walkPFSM ac2 acc | Init ac1 ac2 <- st = walkPFSM ac1 $ walkPFSM ac2 acc | Alternate ac1 ac2 <- st = walkPFSM ac1 $ walkPFSM ac2 acc -- both branches need filter defs | otherwise = acc where checkPrio ev acc' = (mkPrio ev):acc' mkPrio ev' = PrioritiseInfo $ \s m -> handleMessage m (resolveEvent ev' m s) handleRpcRawInputs :: forall s d . (Show s) => State s d -> (P.Message, SendPort P.Message) -> Action (State s d) handleRpcRawInputs st@State{..} (msg, port) = handleInput msg $ st { stReply = (sendChan port), stTrans = Q.empty, stInput = Just msg } handleAllRawInputs :: forall s d. (Show s) => State s d -> P.Message -> Action (State s d) handleAllRawInputs st@State{..} msg = handleInput msg $ st { stReply = noOp, stTrans = Q.empty, stInput = Just msg } handleExitReason :: forall s d. (Show s) => State s d -> P.Message -> Process (Maybe (ProcessAction (State s d))) handleExitReason st@State{..} msg = let st' = st { stReply = noOp, stTrans = Q.empty, stInput = Just msg } in tryHandleInput st' msg handleShutdown :: forall s d . ExitState (State s d) -> ExitReason -> Process () handleShutdown es er | (CleanShutdown s) <- es = shutdownAux s False | (LastKnown s) <- es = shutdownAux s True where shutdownAux st@State{..} ef = void $ tryHandleInput st (wrapMessage $ Stopping er ef) noOp :: P.Message -> Process () noOp = const $ return () handleInput :: forall s d . (Show s) => P.Message -> State s d -> Action (State s d) handleInput msg st = do res <- tryHandleInput st msg case res of Just act -> return act Nothing -> continue st tryHandleInput :: forall s d. (Show s) => State s d -> P.Message -> Process (Maybe (ProcessAction (State s d))) tryHandleInput st@State{..} msg = do res <- apply st msg stProg case res of Just res' -> applyTransitions res' [] >>= return . Just Nothing -> return Nothing
haskell-distributed/distributed-process-fsm
src/Control/Distributed/Process/FSM/Internal/Process.hs
bsd-3-clause
6,071
0
15
1,446
1,941
1,033
908
124
2
module H99.Arithmetic where import Data.List {- Problem 31 (**) Determine whether a given integer number is prime. Example: * (is-prime 7) T Example in Haskell: P31> isPrime 7 True -} isPrime :: Int -> Bool isPrime n = n `elem` (take n primes) where primes = filterPrime [2..] filterPrime (x:xs) = x : filterPrime [x' | x' <- xs, x' `mod` x /= 0] {- Problem 32 (**) Determine the greatest common divisor of two positive integer numbers. Use Euclid's algorithm. Example: * (gcd 36 63) 9 Example in Haskell: [myGCD 36 63, myGCD (-3) (-6), myGCD (-3) 6] [9,3,3] -} myGCD :: Integral t => t -> t -> t myGCD a b | b == 0 = abs a | r == 0 = abs b | otherwise = myGCD b r where r = a `mod` b {- Problem 33 (*) Determine whether two positive integer numbers are coprime. Two numbers are coprime if their greatest common divisor equals 1. Example: * (coprime 35 64) T Example in Haskell: * coprime 35 64 True -} coprime :: Integral a => a -> a -> Bool coprime a b = myGCD a b == 1 {- Problem 34 (**) Calculate Euler's totient function phi(m). Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m. Example: m = 10: r = 1,3,7,9; thus phi(m) = 4. Note the special case: phi(1) = 1. Example: * (totient-phi 10) 4 Example in Haskell: * totient 10 4 -} totient :: Int -> Int totient 1 = 1 totient n = length $ filter (coprime n) [1..n-1] {- Problem 35 (**) Determine the prime factors of a given positive integer. Construct a flat list containing the prime factors in ascending order. Example: * (prime-factors 315) (3 3 5 7) Example in Haskell: > primeFactors 315 [3, 3, 5, 7] -} primeFactors :: Int -> [Int] primeFactors 1 = [] primeFactors n = spf : primeFactors (n `div` spf) where spf = smallestPrimeFactor primes n smallestPrimeFactor (p:ps) n = if n `mod` p == 0 then p else smallestPrimeFactor ps n primes = filterPrime [2..] filterPrime (x:xs) = x : filterPrime [x' | x' <- xs, x' `mod` x /= 0] primeFactors _ = error "invalid input" {- Problem 36 (**) Determine the prime factors of a given positive integer. Construct a list containing the prime factors and their multiplicity. Example: * (prime-factors-mult 315) ((3 2) (5 1) (7 1)) Example in Haskell: *Main> prime_factors_mult 315 [(3,2),(5,1),(7,1)] -} primeFactorsMult :: Int -> [(Int, Int)] primeFactorsMult = toPair . group . primeFactors where toPair = map (\x -> (head x, length x)) {- Problem 37 (**) Calculate Euler's totient function phi(m) (improved). See problem 34 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem 36 then the function phi(m) can be efficiently calculated as follows: Let ((p1 m1) (p2 m2) (p3 m3) ...) be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula: phi(m) = (p1 - 1) * p1 ** (m1 - 1) * (p2 - 1) * p2 ** (m2 - 1) * (p3 - 1) * p3 ** (m3 - 1) * ... Note that a ** b stands for the b'th power of a. -} totientImproved :: Int -> Int totientImproved m = product [(p - 1) * p ^ (m' - 1) | (p, m') <- primeFactorsMult m] {- Problem 38 (*) Compare the two methods of calculating Euler's totient function. Use the solutions of problems 34 and 37 to compare the algorithms. Take the number of reductions as a measure for efficiency. Try to calculate phi(10090) as an example. (no solution required) -} {- Problem 39 (*) A list of prime numbers. Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range. Example in Haskell: P29> primesR 10 20 [11,13,17,19] -} primesR :: Int -> Int -> [Int] primesR l u = takeWhile (u>) $ dropWhile (l>) primes where primes = filterPrime [2..] filterPrime (x:xs) = x : filterPrime [x' | x' <- xs, x' `mod` x /= 0] {- Problem 40 (**) Goldbach's conjecture. Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than we can go with our Prolog system). Write a predicate to find the two prime numbers that sum up to a given even integer. Example: * (goldbach 28) (5 23) Example in Haskell: *goldbach 28 (5, 23) -} goldbach :: Int -> (Int, Int) goldbach n | odd n || n <= 2 = error "Input should be even and greater than 2!" | otherwise = doGoldbach primeRange where primeRange = primesR 2 n doGoldbach range | r == 0 = (h, l) | r > 0 = doGoldbach $ take (length range - 1) range | r < 0 = doGoldbach $ tail range where h = head range l = last range r = h + l - n {- Problem 41 (**) Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition. In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range 2..3000. Example: * (goldbach-list 9 20) 10 = 3 + 7 12 = 5 + 7 14 = 3 + 11 16 = 3 + 13 18 = 5 + 13 20 = 3 + 17 * (goldbach-list 1 2000 50) 992 = 73 + 919 1382 = 61 + 1321 1856 = 67 + 1789 1928 = 61 + 1867 Example in Haskell: *Exercises> goldbachList 9 20 [(3,7),(5,7),(3,11),(3,13),(5,13),(3,17)] *Exercises> goldbachList' 4 2000 50 [(73,919),(61,1321),(67,1789),(61,1867)] -} goldbachList :: Int -> Int -> [(Int, Int)] goldbachList l u = map goldbach . filter even $ [l..u] goldbachList' :: Int -> Int -> Int -> [(Int, Int)] goldbachList' l u threshold = filter ((threshold<) . fst) $ goldbachList l u
1yefuwang1/haskell99problems
src/H99/Arithmetic.hs
bsd-3-clause
5,883
0
12
1,319
969
509
460
53
2
{-# OPTIONS_GHC -fdefer-typed-holes #-} ---------------------------------------------------------------------------------------------------- -- | -- Module : Numeric.Algebra.Elementary.Pretty -- Copyright : William Knop 2015 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- Pretty printer for elementary algebraic expressions. -- -- __/TODO:/__ Everything. -- -- __/TODO:/__ Write exports. module Numeric.Algebra.Elementary.Pretty where import Numeric.Algebra.Elementary.AST import qualified Text.Nicify as N prettyPrint :: Expr -> String prettyPrint e = N.nicify (show e)
altaic/algebra-elementary
src/Numeric/Algebra/Elementary/Pretty.hs
bsd-3-clause
677
0
7
122
66
46
20
6
1
{-# LANGUAGE TypeFamilies #-} module QueryArrow.ElasticSearch.ESQL where -- http://swizec.com/blog/writing-a-rest-client-in-haskell/swizec/6152 import Prelude hiding (lookup) import Data.Map.Strict (lookup, fromList, Map, keys) import Data.Text (Text) import Data.Set (toAscList) import QueryArrow.Syntax.Term import QueryArrow.Semantics.TypeChecker import QueryArrow.Syntax.Type import QueryArrow.DB.GenericDatabase import Debug.Trace data ElasticSearchQueryExpr = ElasticSearchQueryParam Var | ElasticSearchQueryVar Var | ElasticSearchQueryIntVal Integer | ElasticSearchQueryStrVal Text deriving (Show, Read) data ElasticSearchQuery = ElasticSearchQuery Text (Map Text ElasticSearchQueryExpr) | ElasticSearchInsert Text (Map Text ElasticSearchQueryExpr) | ElasticSearchUpdateProperty Text (Map Text ElasticSearchQueryExpr) (Map Text ElasticSearchQueryExpr) | ElasticSearchDelete Text (Map Text ElasticSearchQueryExpr) | ElasticSearchDeleteProperty Text (Map Text ElasticSearchQueryExpr) [Text] deriving (Show, Read) data ESTrans = ESTrans PredTypeMap (Map PredName (Text, [Text])) translateQueryArg :: [Var] -> Expr -> ([ElasticSearchQueryExpr], [Var]) translateQueryArg env (VarExpr var) = if elem var env then ([ElasticSearchQueryParam var], [var]) else ([ElasticSearchQueryVar var], [var]) translateQueryArg _ (IntExpr i) = ([ElasticSearchQueryIntVal i], []) translateQueryArg _ (StringExpr i) = ([ElasticSearchQueryStrVal i], []) translateQueryArg _ _ = error "unsupported" translateQueryToElasticSearch :: ESTrans -> [Var] -> PredName -> [Expr] -> [Var] -> (ElasticSearchQuery, [Var]) translateQueryToElasticSearch (ESTrans ptm map1) _ pred0 args env = let (args2, params) = mconcat (map (translateQueryArg env) args) (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" in (ElasticSearchQuery type0 (fromList (zip props args2)), params) translateInsertToElasticSearch :: ESTrans -> PredName -> [Expr] -> [Var] -> (ElasticSearchQuery, [Var]) translateInsertToElasticSearch (ESTrans ptm map1) pred0 args env = case lookup pred0 ptm of Nothing -> error ("translateInsertToElasticSearch: cannot find predicate " ++ show pred0) Just (PredType ObjectPred _) -> let (args2, params) = mconcat (map (translateQueryArg env) args) (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" in (ElasticSearchInsert type0 (fromList (zip props args2)), params) Just pt@(PredType PropertyPred _) -> let (args2, params) = mconcat (map (translateQueryArg env) args) keyargs = keyComponents pt args2 propargs = propComponents pt args2 (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" keyprops = keyComponents pt props propprops = propComponents pt props in (ElasticSearchUpdateProperty type0 (fromList (zip keyprops keyargs)) (fromList (zip propprops propargs)), params) translateDeleteToElasticSearch :: ESTrans -> PredName -> [Expr] -> [Var] -> (ElasticSearchQuery, [Var]) translateDeleteToElasticSearch (ESTrans ptm map1) pred0 args env = case lookup pred0 ptm of Nothing -> error ("translateInsertToElasticSearch: cannot find predicate " ++ show pred0) Just (PredType ObjectPred _) -> let (args2, params) = mconcat (map (translateQueryArg env) args) (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" in (ElasticSearchDelete type0 (fromList (zip props args2)), params) Just pt@(PredType PropertyPred _) -> let (args2, params) = mconcat (map (translateQueryArg env) args) keyargs = keyComponents pt args2 propargs = propComponents pt args2 (type0, props) = case lookup pred0 map1 of Just props0 -> props0 Nothing -> error "cannot find predicate" keyprops = keyComponents pt props propprops = propComponents pt props in (ElasticSearchDeleteProperty type0 (fromList (zip keyprops keyargs)) propprops, params) instance IGenericDatabase01 ESTrans where type GDBQueryType ESTrans = (ElasticSearchQuery, [Var]) type GDBFormulaType ESTrans = FormulaT gTranslateQuery trans vars (FAtomicA _ (Atom pred1 args)) env = return (translateQueryToElasticSearch trans (toAscList vars) pred1 args (toAscList env)) gTranslateQuery trans vars (FInsertA _ (Lit Pos (Atom pred1 args))) env = return (translateInsertToElasticSearch trans pred1 args (toAscList env)) gTranslateQuery trans vars (FInsertA _ (Lit Neg (Atom pred1 args))) env = return (translateDeleteToElasticSearch trans pred1 args (toAscList env)) gTranslateQuery _ _ _ _ = error "unsupported" gSupported _ _ (FAtomicA _ _) _ = True gSupported _ _ (FInsertA _ _) _ = True gSupported _ _ _ _ = False
xu-hao/QueryArrow
QueryArrow-db-elastic/src/QueryArrow/ElasticSearch/ESQL.hs
bsd-3-clause
5,342
50
12
1,282
1,563
838
725
94
5
module Main (main) where import Test.Tasty import qualified TChunkedQueue import qualified TMChunkedQueue main :: IO () main = defaultMain $ testGroup "STM ChunkedQueues" [ testGroup "TChunkedQueue" TChunkedQueue.tests , testGroup "TMChunkedQueue" TMChunkedQueue.tests ]
KholdStare/stm-chunked-queues
tests/UnitTests.hs
bsd-3-clause
301
0
9
62
66
37
29
9
1
module Capsir.Runtime where import Capsir import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromJust) -- | An instance of a continuation. Binds an environment to the -- continuation itself. data ContInst v = ContInst (Env v) Cont -- | A runtime value. Each variable is bound to one during continuation -- execution data RuntimeValue v -- | A continuation instance value = InstRuntimeValue (ContInst v) -- | A constant value | ConstRuntimeValue v -- | A variable binding environment. data Env v -- | The empty binding environment. = EmptyEnv -- | A single environment frame. Contains the mappings from variables to -- runtime values for this frame, and references the next environment in -- the chain. | FrameEnv (Map String (RuntimeValue v)) (Env v) -- | A function implementing a single instruction of our code. @m@ is a monad -- that allows a change of state during execution, and @v@ is the value type of -- our instruction set. -- -- The function is passed in a list of values, and returns a continuation index -- and a result list of values. For an instruction CpsExpr, the int is the index -- into the continuation list, and the result is applied to that continuation. type InstFunc m v = [v] -> m (Int, [v]) -- | The concrete parameter type to a value constructor. Can either be an -- int, string, double, or another value. data LitParamVal v = LitParamValConst v | LitParamValInt !Int | LitParamValString !String | LitParamValFloat !Double -- | Type type of a user-defined literal function. Takes a list of literal -- parameters, and returns a value of type a, which is the user-defined runtime -- value type. type LitFunc v = [LitParamVal v] -> v data InstructionSet m v = InstructionSet { instructions :: Map String (InstFunc m v) , literals :: Map String (LitFunc v) } -- | Looks up a variable in the environment. lookupEnv :: String -- ^ The variable to look up -> Env v -- ^ The environment to look it up in -> Maybe (RuntimeValue v) -- ^ Nothing if that value is not bound, -- otherwise @Just value@ where value is the bound -- value. lookupEnv _ EmptyEnv = Nothing lookupEnv name (FrameEnv envMap child) = case Map.lookup name envMap of Just val -> Just val Nothing -> lookupEnv name child -- | Evaluates a literal into a runtime constant. evalLit :: InstructionSet m v -> Literal -> v evalLit instSet (Literal name params) = let litFunc = literals instSet Map.! name evalParam (LitParamLit literal) = LitParamValConst $ evalLit instSet literal evalParam (LitParamInt i) = LitParamValInt i evalParam (LitParamString s) = LitParamValString s evalParam (LitParamFloat f) = LitParamValFloat f evaluatedParams = map evalParam params in litFunc evaluatedParams -- | Evaluates a syntactic Value to a RuntimeValue in the given environment eval :: InstructionSet m v -> Value -> Env v -> RuntimeValue v eval _ (ContValue cont) env = InstRuntimeValue (ContInst env cont) eval _ (VarValue name) env = fromJust (lookupEnv name env) eval instSet (LitValue lit) _ = ConstRuntimeValue $ evalLit instSet lit -- | Evalues a syntactic value as eval, but forces it to be a Continuation -- Instance evalAsCont :: InstructionSet m v -> Value -> Env v -> ContInst v evalAsCont instSet val env = case eval instSet val env of InstRuntimeValue inst -> inst _ -> error "Expected a continuation; Got something else" zipOrError :: [a] -> [b] -> [(a, b)] zipOrError (a:ax) (b:bx) = (a, b) : zipOrError ax bx zipOrError [] [] = [] zipOrError _ _ = error "Mismatched input length in zip" data ExecState v = ExecState (Env v) CpsExpr -- | Applies a set of actual parameters to a continuation to -- generate a new execution state. applyCont :: RuntimeValue v -> [RuntimeValue v] -> ExecState v applyCont (InstRuntimeValue inst) args = let ContInst contEnv (Cont params nextExpr) = inst newFrame = Map.fromList $ zipOrError params args newEnv = FrameEnv newFrame contEnv in ExecState newEnv nextExpr applyCont _ _ = error "Expected a continuation instance" -- | Applies a function to the second item in a pair. applySecond :: (a -> b) -> (c, a) -> (c, b) applySecond f (c, a) = (c, f a) fromConst :: RuntimeValue v -> v fromConst (ConstRuntimeValue v) = v fromConst (InstRuntimeValue _) = error "Expected a constant value." -- | Given a mapping from names to continuations, create a new -- environment where each name is mapped to the instantiation of -- its continuation with the same environment. -- -- [example needed] makeFixedEnv :: [(String, Cont)] -> Env v -> Env v makeFixedEnv bindings env = let newEnv = FrameEnv contMap env -- Instantiates a Cont createContInst c = InstRuntimeValue $ ContInst newEnv c runtimeValPairs = map (applySecond createContInst) bindings contMap = Map.fromList runtimeValPairs in newEnv -- | Takes a single step through the given execution state. Returns either a -- new execution state, or a single runtime value if the program exited. step :: Monad m => InstructionSet m v -> ExecState v -> m (Either (ExecState v) (RuntimeValue v)) step instSet (ExecState env expr) = let stepEval v = eval instSet v env in case expr of Exit val -> return $ Right $ stepEval val Apply args val -> let runtimeArgs = map stepEval args in return $ Left $ applyCont (stepEval val) runtimeArgs Fix bindings nextExpr -> return $ Left $ ExecState (makeFixedEnv bindings env) nextExpr Inst instName args conts -> let instFunc = instructions instSet Map.! instName runtimeArgs = map stepEval args values = map fromConst runtimeArgs in do (branchIndex, results) <- instFunc values let nextCont = conts !! branchIndex let nextContInst = eval instSet nextCont env return $ Left $ applyCont nextContInst (map ConstRuntimeValue results) -- | Calls the function on the init, and loops while the output is left, -- feeding the value back into the function. When it returns Right, yields the -- value. eitherLoop :: Monad m => (a -> m (Either a b)) -> a -> m b eitherLoop stepFunc initVal = let go (Left a) = stepFunc a >>= go go (Right b) = return b in stepFunc initVal >>= go -- | A function that given a user-defined instruction set and an initial -- expression, evaluates it until completion. runCont :: Monad m => InstructionSet m v -> CpsExpr -> m (RuntimeValue v) runCont instSet expr = eitherLoop (step instSet) (ExecState EmptyEnv expr)
naerbnic/capsir
src/Capsir/Runtime.hs
bsd-3-clause
6,892
13
12
1,712
1,567
819
748
108
4
{-# LANGUAGE UnicodeSyntax #-} module System.Linux.Netlink.Internal ( align4 ) where import Data.Bits align4 ∷ (Num n, Bits n) ⇒ n → n align4 n = (n + 3) .&. complement 3 {-# INLINE align4 #-}
mvv/system-linux
src/System/Linux/Netlink/Internal.hs
bsd-3-clause
209
0
7
45
66
38
28
7
1
{- | Module : ./Static/DGNavigation.hs Description : Navigation through the Development Graph Copyright : (c) Ewaryst Schulz, DFKI Bremen 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : non-portable (via imports) Navigation through the Development Graph based on Node and Link predicates using Depth First Search. -} module Static.DGNavigation where import Static.DevGraph import qualified Data.Set as Set import Data.List import Data.Maybe import Data.Graph.Inductive.Graph as Graph import Logic.Grothendieck import Common.Doc import Common.DocUtils import Syntax.AS_Library -- * Navigator Class class DevGraphNavigator a where -- | get all the incoming ledges of the given node incoming :: a -> Node -> [LEdge DGLinkLab] -- | get the label of the given node getLabel :: a -> Node -> DGNodeLab -- | get the local (not referenced) environment of the given node getLocalNode :: a -> Node -> (DGraph, LNode DGNodeLab) getInLibEnv :: a -> (LibEnv -> DGraph -> b) -> b getCurrent :: a -> [LNode DGNodeLab] relocate :: a -> DGraph -> [LNode DGNodeLab] -> a {- | Get all the incoming ledges of the given node and eventually cross the border to an other 'DGraph'. The new 'DevGraphNavigator' is returned with 'DGraph' set to the new graph and current node to the given node. -} followIncoming :: DevGraphNavigator a => a -> Node -> (a, LNode DGNodeLab, [LEdge DGLinkLab]) followIncoming dgn n = (dgn', lbln, incoming dgn' n') where (dgn', lbln@(n', _)) = followNode dgn n -- | get the local (not referenced) label of the given node getLocalLabel :: DevGraphNavigator a => a -> Node -> DGNodeLab getLocalLabel dgnav = snd . snd . getLocalNode dgnav followNode :: DevGraphNavigator a => a -> Node -> (a, LNode DGNodeLab) followNode dgnav n = (relocate dgnav dg [lbln], lbln) where (dg, lbln) = getLocalNode dgnav n -- | get all the incoming ledges of the current node directInn :: DevGraphNavigator a => a -> [LEdge DGLinkLab] directInn dgnav = concatMap (incoming dgnav . fst) $ getCurrent dgnav -- * Navigator Instance {- | The navigator instance consists of a 'LibEnv' a current 'DGraph' and a current 'Node' which is the starting point for navigation through the DG. -} data DGNav = DGNav { dgnLibEnv :: LibEnv , dgnDG :: DGraph , dgnCurrent :: [LNode DGNodeLab] } deriving Show instance Pretty DGNav where pretty dgn = d1 <> text ":" <+> pretty (map fst $ dgnCurrent dgn) where d1 = case optLibDefn $ dgnDG dgn of Just (Lib_defn ln _ _ _) -> pretty ln Nothing -> text "DG" makeDGNav :: LibEnv -> DGraph -> [LNode DGNodeLab] -> DGNav makeDGNav le dg cnl = DGNav le dg cnl' where cnl' | null cnl = filter f $ labNodesDG dg | otherwise = cnl where f (n, _) = not $ any isDefLink $ outDG dg n isDefLink :: LEdge DGLinkLab -> Bool isDefLink = isDefEdge . dgl_type . linkLabel instance DevGraphNavigator DGNav where -- we consider only the definition links in a DGraph incoming dgn = filter isDefLink . innDG (dgnDG dgn) getLabel = labDG . dgnDG getLocalNode (DGNav {dgnLibEnv = le, dgnDG = dg}) = lookupLocalNode le dg getInLibEnv (DGNav {dgnLibEnv = le, dgnDG = dg}) f = f le dg getCurrent (DGNav {dgnCurrent = lblnl}) = lblnl relocate dgn dg lblnl = dgn { dgnDG = dg, dgnCurrent = lblnl } -- * Basic search functionality -- | DFS based search firstMaybe :: (a -> Maybe b) -> [a] -> Maybe b firstMaybe _ [] = Nothing firstMaybe f (x : l) = case f x of Nothing -> firstMaybe f l y -> y {- | Searches all ancestor nodes of the current node and also the current node for a node matching the given predicate -} searchNode :: DevGraphNavigator a => (LNode DGNodeLab -> Bool) -> a -> Maybe (a, LNode DGNodeLab) searchNode p dgnav = firstMaybe (searchNodeFrom p dgnav . fst) $ getCurrent dgnav searchNodeFrom :: DevGraphNavigator a => (LNode DGNodeLab -> Bool) -> a -> Node -> Maybe (a, LNode DGNodeLab) searchNodeFrom p dgnav n = let (dgnav', lbln, ledgs) = followIncoming dgnav n in if p lbln then Just (dgnav', lbln) else firstMaybe (searchNodeFrom p dgnav') $ map linkSource ledgs searchLink :: DevGraphNavigator a => (LEdge DGLinkLab -> Bool) -> a -> Maybe (a, LEdge DGLinkLab) searchLink p dgnav = firstMaybe (searchLinkFrom p dgnav . fst) $ getCurrent dgnav searchLinkFrom :: DevGraphNavigator a => (LEdge DGLinkLab -> Bool) -> a -> Node -> Maybe (a, LEdge DGLinkLab) searchLinkFrom p dgnav n = let (dgnav', _, ledgs) = followIncoming dgnav n in case find p ledgs of Nothing -> firstMaybe (searchLinkFrom p dgnav') $ map linkSource ledgs x -> fmap ((,) dgnav') x -- * Predicates to be used with 'searchNode' -- | This predicate is true for nodes with a nodename equal to the given string dgnPredName :: String -> LNode DGNodeLab -> Maybe (LNode DGNodeLab) dgnPredName n nd@(_, lbl) = if getDGNodeName lbl == n then Just nd else Nothing {- | This predicate is true for nodes which are instantiations of a specification with the given name -} dgnPredParameterized :: String -> LNode DGNodeLab -> Maybe (LNode DGNodeLab) dgnPredParameterized n nd@(_, DGNodeLab { nodeInfo = DGNode { node_origin = DGInst sid } }) | show sid == n = Just nd | otherwise = Nothing dgnPredParameterized _ _ = Nothing {- * Predicates to be used with 'searchLink' This predicate is true for links which are argument instantiations of a parameterized specification with the given name -} dglPredActualParam :: String -> LEdge DGLinkLab -> Maybe (LEdge DGLinkLab) dglPredActualParam n edg@(_, _, DGLink { dgl_origin = DGLinkInstArg sid }) | show sid == n = Just edg | otherwise = Nothing dglPredActualParam _ _ = Nothing -- | This predicate is true for links which are instantiation morphisms dglPredInstance :: LEdge DGLinkLab -> Maybe (LEdge DGLinkLab) dglPredInstance edg@(_, _, DGLink { dgl_origin = DGLinkMorph _ }) = Just edg dglPredInstance _ = Nothing -- * Combined Node Queries -- | Search for the given name in an actual parameter link getActualParameterSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getActualParameterSpec n dgnav = -- search first actual param case searchLink (isJust . dglPredActualParam n) dgnav of Nothing -> Nothing Just (dgn', (sn, _, _)) -> -- get the spec for the param fmap f $ firstMaybe dglPredInstance $ incoming dgnav sn where f edg = let sn' = linkSource edg in (dgn', (sn', getLabel dgnav sn')) -- | Search for the given name in an instantiation node getParameterizedSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getParameterizedSpec n dgnav = -- search first actual param case searchNode (isJust . dgnPredParameterized n) dgnav of Nothing -> Nothing Just (dgn', (sn, _)) -> -- get the spec for the param fmap f $ firstMaybe dglPredInstance $ incoming dgnav sn where f edg = let sn' = linkSource edg in (dgn', (sn', getLabel dgnav sn')) -- | Search for the given name in any node getNamedSpec :: DevGraphNavigator a => String -> a -> Maybe (a, LNode DGNodeLab) getNamedSpec n = searchNode (isJust . dgnPredName n) -- | Combining a search function with an operation on nodes fromSearchResult :: (DevGraphNavigator a) => (a -> Maybe (a, LNode DGNodeLab)) -> (a -> Node -> b) -> a -> Maybe b fromSearchResult sf f dgnav = case sf dgnav of Just (dgn', (n, _)) -> Just $ f dgn' n _ -> Nothing -- * Other utils getLocalSyms :: DevGraphNavigator a => a -> Node -> Set.Set G_symbol getLocalSyms dgnav n = case dgn_origin $ getLocalLabel dgnav n of DGBasicSpec _ _ s -> s _ -> Set.empty linkSource :: LEdge a -> Node linkLabel :: LEdge a -> a linkSource (x, _, _) = x linkLabel (_, _, x) = x
spechub/Hets
Static/DGNavigation.hs
gpl-2.0
8,374
5
26
2,163
2,288
1,179
1,109
128
2
{-# LANGUAGE OverloadedStrings #-} module Db.Mapper where import Control.Applicative import Database.MongoDB import Text.Read (readMaybe) import Types budgetToDocument :: Budget -> Document budgetToDocument (Budget bid uid i d f ds ob cb) = (idFieldIfExists bid) ++ [ "userId" =: uid , "income" =: (incomeToDocuments i) , "demands" =: (demandsToDocuments d) , "fills" =: (fillsToDocuments f) , "demandSummaries" =: (summariesToDocuments ds) , "openingBalance" =: ob , "closingBalance" =: cb ] where idFieldIfExists Nothing = [] idFieldIfExists (Just bid') = ["_id" =: bid'] demandsToDocuments [] = [] demandsToDocuments (x:xs) = demandToDocument x : demandsToDocuments xs fillsToDocuments [] = [] fillsToDocuments (x:xs) = fillToDocument x : fillsToDocuments xs incomeToDocuments [] = [] incomeToDocuments (x:xs) = incomeToDocument x : incomeToDocuments xs summariesToDocuments [] = [] summariesToDocuments (x:xs) = summaryToDocument x : summariesToDocuments xs documentToBudget :: Document -> Maybe Budget documentToBudget d = Budget <$> d !? "_id" <*> at "userId" d <*> (documentsToIncome <$> d !? "income") <*> (documentsToDemands <$> d !? "demands") <*> (documentsToFills <$> d !? "fills") <*> (documentsToSummaries <$> d !? "demandSummaries") <*> at "openingBalance" d <*> at "closingBalance" d where documentsToDemands [] = [] documentsToDemands (x:xs) = documentToDemand x : documentsToDemands xs documentsToFills [] = [] documentsToFills (x:xs) = documentToFill x : documentsToFills xs documentsToIncome [] = [] documentsToIncome (x:xs) = documentToIncome x : documentsToIncome xs documentsToSummaries [] = [] documentsToSummaries (x:xs) = documentToSummary x : documentsToSummaries xs documentToDemand :: Document -> Demand documentToDemand d = Demand (documentToPeriod $ at "period" d) (at "envelope" d) (at "amount" d) documentToFill :: Document -> Fill documentToFill d = Fill (at "date" d) (documentToDemand $ at "demand" d) (at "amount" d) documentToIncome :: Document -> Income documentToIncome d = Income (at "date" d) (at "amount" d) documentToPeriod :: Document -> Period documentToPeriod d = Period (at "start" d) (at "end" d) documentToSummary :: Document -> DemandSummary documentToSummary d = DemandSummary (documentToDemand $ at "demand" d) (at "fillAmount" d) (read $ at "colour" d) demandToDocument :: Demand -> Document demandToDocument (Demand p e a) = [ "period" =: (periodToDocument p) , "envelope" =: e , "amount" =: a ] fillToDocument :: Fill -> Document fillToDocument (Fill d dem a) = [ "date" =: d , "demand" =: (demandToDocument dem) , "amount" =: a ] incomeToDocument :: Income -> Document incomeToDocument (Income d a) = ["date" =: d, "amount" =: a] maybeDocumentToBudget :: Maybe Document -> Maybe Budget maybeDocumentToBudget doc = case doc of Just d -> documentToBudget d Nothing -> Nothing periodToDocument :: Period -> Document periodToDocument (Period s e) = ["start" =: s, "end" =: e] stringToObjectId :: String -> Maybe ObjectId stringToObjectId s = readMaybe s summaryToDocument :: DemandSummary -> Document summaryToDocument (DemandSummary d a c) = [ "demand" =: (demandToDocument d) , "fillAmount" =: a , "colour" =: show c ]
Geeroar/ut-haskell
src/Db/Mapper.hs
apache-2.0
4,130
0
13
1,415
1,143
583
560
83
6
module Main where import VSimR.Timeline import VSimR.Memory import VSimR.Signal import VSimR.Variable -- main = do -- elab
ierton/vsim
Main.hs
bsd-3-clause
142
0
4
36
26
17
9
5
0
{-# LANGUAGE OverloadedStrings #-} module Mimir.Bitfinex.Instances() where import Mimir.Types import Mimir.Bitfinex.Types import Control.Applicative ((<$>), (<*>)) import Control.Monad import Data.Aeson import Data.Aeson.Types (Parser) import Data.Char (toUpper) import qualified Data.HashMap.Strict as HM import Data.Maybe (catMaybes) import qualified Data.Text as T instance FromJSON Ticker where parseJSON (Object v) = Ticker <$> fmap (round . (* 1000) . read) (v .: "timestamp") <*> (readSafe =<< v .: "ask") <*> (readSafe =<< v .: "bid") <*> (readSafe =<< v .: "last_price") parseJSON _ = mzero instance FromJSON BFBalance where parseJSON (Object v) = BFBalance <$> v .: "type" <*> v .: "currency" <*> (readSafe =<< v .: "available") parseJSON _ = mzero instance FromJSON Order where parseJSON (Object v) = Order <$> parseType v <*> v .: "id" <*> (round <$> parseDouble v "timestamp") <*> parseDouble v "original_amount" <*> parseDouble v "price" parseJSON _ = mzero parseType :: HM.HashMap T.Text Value -> Parser OrderType parseType m = do t <- (m .: "type" :: Parser String) s <- (m .: "side" :: Parser String) case (t,s) of ("exchange limit", "buy") -> return LIMIT_BUY ("exchange limit", "sell") -> return LIMIT_SELL ("exchange market", "buy") -> return MARKET_BUY ("exchange market", "sell") -> return MARKET_SELL otherwise -> mzero parseDouble :: HM.HashMap T.Text Value -> T.Text -> Parser Double parseDouble m k = do s <- m .: k case (readsPrec 0 s) of [(v,_)] -> return v _ -> mzero readSafe :: Read a => String -> Parser a readSafe s = case readsPrec 0 s of [(a, _)] -> return a _ -> mzero
ralphmorton/Mimir
src/Mimir/Bitfinex/Instances.hs
bsd-3-clause
1,915
0
14
566
638
339
299
53
5
{-# OPTIONS_GHC -F -pgmF hspec-discover -optF --nested #-} -- import qualified FindSpec -- main :: IO () -- main = FindSpec.main
mkrauskopf/doh
test/main.hs
bsd-3-clause
129
0
2
21
6
5
1
1
0
-- From:http://rosettacode.org/wiki/Temperature_conversion#Haskell -- main = do putStrLn "Please enter temperature in kelvin: " input <- getLine let kelvin = read input :: Double if kelvin < 0.0 then putStrLn "error" else let celsius = kelvin - 273.15 fahrenheit = kelvin * 1.8 - 459.67 rankine = kelvin * 1.8 in do putStrLn ("kelvin: " ++ show kelvin) putStrLn ("celsius: " ++ show celsius) putStrLn ("fahrenheit: " ++ show fahrenheit) putStrLn ("rankine: " ++ show rankine)
junnf/Functional-Programming
codes/temperatures.hs
unlicense
547
0
15
146
155
73
82
16
2
-- The @FamInst@ type: family instance heads {-# LANGUAGE CPP, GADTs #-} module FamInst ( FamInstEnvs, tcGetFamInstEnvs, checkFamInstConsistency, tcExtendLocalFamInstEnv, tcLookupFamInst, tcLookupDataFamInst, tcLookupDataFamInst_maybe, tcInstNewTyCon_maybe, tcTopNormaliseNewTypeTF_maybe, newFamInst ) where import HscTypes import FamInstEnv import InstEnv( roughMatchTcs ) import Coercion hiding ( substTy ) import TcEvidence import LoadIface import TcRnMonad import TyCon import CoAxiom import DynFlags import Module import Outputable import UniqFM import FastString import Util import RdrName import DataCon ( dataConName ) import Maybes import TcMType import TcType import Name import Control.Monad import Data.Map (Map) import qualified Data.Map as Map import Control.Arrow ( first, second ) #include "HsVersions.h" {- ************************************************************************ * * Making a FamInst * * ************************************************************************ -} -- All type variables in a FamInst must be fresh. This function -- creates the fresh variables and applies the necessary substitution -- It is defined here to avoid a dependency from FamInstEnv on the monad -- code. newFamInst :: FamFlavor -> CoAxiom Unbranched -> TcRnIf gbl lcl FamInst -- Freshen the type variables of the FamInst branches -- Called from the vectoriser monad too, hence the rather general type newFamInst flavor axiom@(CoAxiom { co_ax_branches = FirstBranch branch , co_ax_tc = fam_tc }) | CoAxBranch { cab_tvs = tvs , cab_lhs = lhs , cab_rhs = rhs } <- branch = do { (subst, tvs') <- freshenTyVarBndrs tvs ; return (FamInst { fi_fam = tyConName fam_tc , fi_flavor = flavor , fi_tcs = roughMatchTcs lhs , fi_tvs = tvs' , fi_tys = substTys subst lhs , fi_rhs = substTy subst rhs , fi_axiom = axiom }) } {- ************************************************************************ * * Optimised overlap checking for family instances * * ************************************************************************ For any two family instance modules that we import directly or indirectly, we check whether the instances in the two modules are consistent, *unless* we can be certain that the instances of the two modules have already been checked for consistency during the compilation of modules that we import. Why do we need to check? Consider module X1 where module X2 where data T1 data T2 type instance F T1 b = Int type instance F a T2 = Char f1 :: F T1 a -> Int f2 :: Char -> F a T2 f1 x = x f2 x = x Now if we import both X1 and X2 we could make (f2 . f1) :: Int -> Char. Notice that neither instance is an orphan. How do we know which pairs of modules have already been checked? Any pair of modules where both modules occur in the `HscTypes.dep_finsts' set (of the `HscTypes.Dependencies') of one of our directly imported modules must have already been checked. Everything else, we check now. (So that we can be certain that the modules in our `HscTypes.dep_finsts' are consistent.) -} -- The optimisation of overlap tests is based on determining pairs of modules -- whose family instances need to be checked for consistency. -- data ModulePair = ModulePair Module Module -- canonical order of the components of a module pair -- canon :: ModulePair -> (Module, Module) canon (ModulePair m1 m2) | m1 < m2 = (m1, m2) | otherwise = (m2, m1) instance Eq ModulePair where mp1 == mp2 = canon mp1 == canon mp2 instance Ord ModulePair where mp1 `compare` mp2 = canon mp1 `compare` canon mp2 instance Outputable ModulePair where ppr (ModulePair m1 m2) = angleBrackets (ppr m1 <> comma <+> ppr m2) -- Sets of module pairs -- type ModulePairSet = Map ModulePair () listToSet :: [ModulePair] -> ModulePairSet listToSet l = Map.fromList (zip l (repeat ())) checkFamInstConsistency :: [Module] -> [Module] -> TcM () checkFamInstConsistency famInstMods directlyImpMods = do { dflags <- getDynFlags ; (eps, hpt) <- getEpsAndHpt ; let { -- Fetch the iface of a given module. Must succeed as -- all directly imported modules must already have been loaded. modIface mod = case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of Nothing -> panic "FamInst.checkFamInstConsistency" Just iface -> iface ; hmiModule = mi_module . hm_iface ; hmiFamInstEnv = extendFamInstEnvList emptyFamInstEnv . md_fam_insts . hm_details ; hpt_fam_insts = mkModuleEnv [ (hmiModule hmi, hmiFamInstEnv hmi) | hmi <- eltsUFM hpt] ; groups = map (dep_finsts . mi_deps . modIface) directlyImpMods ; okPairs = listToSet $ concatMap allPairs groups -- instances of okPairs are consistent ; criticalPairs = listToSet $ allPairs famInstMods -- all pairs that we need to consider ; toCheckPairs = Map.keys $ criticalPairs `Map.difference` okPairs -- the difference gives us the pairs we need to check now } ; mapM_ (check hpt_fam_insts) toCheckPairs } where allPairs [] = [] allPairs (m:ms) = map (ModulePair m) ms ++ allPairs ms check hpt_fam_insts (ModulePair m1 m2) = do { env1 <- getFamInsts hpt_fam_insts m1 ; env2 <- getFamInsts hpt_fam_insts m2 ; mapM_ (checkForConflicts (emptyFamInstEnv, env2)) (famInstEnvElts env1) } getFamInsts :: ModuleEnv FamInstEnv -> Module -> TcM FamInstEnv getFamInsts hpt_fam_insts mod | Just env <- lookupModuleEnv hpt_fam_insts mod = return env | otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod) ; eps <- getEps ; return (expectJust "checkFamInstConsistency" $ lookupModuleEnv (eps_mod_fam_inst_env eps) mod) } where doc = ppr mod <+> ptext (sLit "is a family-instance module") {- ************************************************************************ * * Lookup * * ************************************************************************ Look up the instance tycon of a family instance. The match may be ambiguous (as we know that overlapping instances have identical right-hand sides under overlapping substitutions - see 'FamInstEnv.lookupFamInstEnvConflicts'). However, the type arguments used for matching must be equal to or be more specific than those of the family instance declaration. We pick one of the matches in case of ambiguity; as the right-hand sides are identical under the match substitution, the choice does not matter. Return the instance tycon and its type instance. For example, if we have tcLookupFamInst 'T' '[Int]' yields (':R42T', 'Int') then we have a coercion (ie, type instance of family instance coercion) :Co:R42T Int :: T [Int] ~ :R42T Int which implies that :R42T was declared as 'data instance T [a]'. -} tcLookupFamInst :: FamInstEnvs -> TyCon -> [Type] -> Maybe FamInstMatch tcLookupFamInst fam_envs tycon tys | not (isOpenFamilyTyCon tycon) = Nothing | otherwise = case lookupFamInstEnv fam_envs tycon tys of match : _ -> Just match [] -> Nothing -- | If @co :: T ts ~ rep_ty@ then: -- -- > instNewTyCon_maybe T ts = Just (rep_ty, co) -- -- Checks for a newtype, and for being saturated -- Just like Coercion.instNewTyCon_maybe, but returns a TcCoercion tcInstNewTyCon_maybe :: TyCon -> [TcType] -> Maybe (TcType, TcCoercion) tcInstNewTyCon_maybe tc tys = fmap (second TcCoercion) $ instNewTyCon_maybe tc tys -- | Like 'tcLookupDataFamInst_maybe', but returns the arguments back if -- there is no data family to unwrap. tcLookupDataFamInst :: FamInstEnvs -> TyCon -> [TcType] -> (TyCon, [TcType], TcCoercion) tcLookupDataFamInst fam_inst_envs tc tc_args | Just (rep_tc, rep_args, co) <- tcLookupDataFamInst_maybe fam_inst_envs tc tc_args = (rep_tc, rep_args, TcCoercion co) | otherwise = (tc, tc_args, mkTcRepReflCo (mkTyConApp tc tc_args)) tcLookupDataFamInst_maybe :: FamInstEnvs -> TyCon -> [TcType] -> Maybe (TyCon, [TcType], Coercion) -- ^ Converts a data family type (eg F [a]) to its representation type (eg FList a) -- and returns a coercion between the two: co :: F [a] ~R FList a tcLookupDataFamInst_maybe fam_inst_envs tc tc_args | isDataFamilyTyCon tc , match : _ <- lookupFamInstEnv fam_inst_envs tc tc_args , FamInstMatch { fim_instance = rep_fam , fim_tys = rep_args } <- match , let co_tc = famInstAxiom rep_fam rep_tc = dataFamInstRepTyCon rep_fam co = mkUnbranchedAxInstCo Representational co_tc rep_args = Just (rep_tc, rep_args, co) | otherwise = Nothing -- | Get rid of top-level newtypes, potentially looking through newtype -- instances. Only unwraps newtypes that are in scope. This is used -- for solving for `Coercible` in the solver. This version is careful -- not to unwrap data/newtype instances if it can't continue unwrapping. -- Such care is necessary for proper error messages. -- -- Does not look through type families. Does not normalise arguments to a -- tycon. -- -- Always produces a representational coercion. tcTopNormaliseNewTypeTF_maybe :: FamInstEnvs -> GlobalRdrEnv -> Type -> Maybe (TcCoercion, Type) tcTopNormaliseNewTypeTF_maybe faminsts rdr_env ty -- cf. FamInstEnv.topNormaliseType_maybe and Coercion.topNormaliseNewType_maybe = fmap (first TcCoercion) $ topNormaliseTypeX_maybe stepper ty where stepper = unwrap_newtype `composeSteppers` \ rec_nts tc tys -> case tcLookupDataFamInst_maybe faminsts tc tys of Just (tc', tys', co) -> modifyStepResultCo (co `mkTransCo`) (unwrap_newtype rec_nts tc' tys') Nothing -> NS_Done unwrap_newtype rec_nts tc tys | data_cons_in_scope tc = unwrapNewTypeStepper rec_nts tc tys | otherwise = NS_Done data_cons_in_scope :: TyCon -> Bool data_cons_in_scope tc = isWiredInName (tyConName tc) || (not (isAbstractTyCon tc) && all in_scope data_con_names) where data_con_names = map dataConName (tyConDataCons tc) in_scope dc = not $ null $ lookupGRE_Name rdr_env dc {- ************************************************************************ * * Extending the family instance environment * * ************************************************************************ -} -- Add new locally-defined family instances tcExtendLocalFamInstEnv :: [FamInst] -> TcM a -> TcM a tcExtendLocalFamInstEnv fam_insts thing_inside = do { env <- getGblEnv ; (inst_env', fam_insts') <- foldlM addLocalFamInst (tcg_fam_inst_env env, tcg_fam_insts env) fam_insts ; let env' = env { tcg_fam_insts = fam_insts' , tcg_fam_inst_env = inst_env' } ; setGblEnv env' thing_inside } -- Check that the proposed new instance is OK, -- and then add it to the home inst env -- This must be lazy in the fam_inst arguments, see Note [Lazy axiom match] -- in FamInstEnv.lhs addLocalFamInst :: (FamInstEnv,[FamInst]) -> FamInst -> TcM (FamInstEnv, [FamInst]) addLocalFamInst (home_fie, my_fis) fam_inst -- home_fie includes home package and this module -- my_fies is just the ones from this module = do { traceTc "addLocalFamInst" (ppr fam_inst) ; isGHCi <- getIsGHCi ; mod <- getModule ; traceTc "alfi" (ppr mod $$ ppr isGHCi) -- In GHCi, we *override* any identical instances -- that are also defined in the interactive context -- See Note [Override identical instances in GHCi] in HscTypes ; let home_fie' | isGHCi = deleteFromFamInstEnv home_fie fam_inst | otherwise = home_fie -- Load imported instances, so that we report -- overlaps correctly ; eps <- getEps ; let inst_envs = (eps_fam_inst_env eps, home_fie') home_fie'' = extendFamInstEnv home_fie fam_inst -- Check for conflicting instance decls ; no_conflict <- checkForConflicts inst_envs fam_inst ; if no_conflict then return (home_fie'', fam_inst : my_fis) else return (home_fie, my_fis) } {- ************************************************************************ * * Checking an instance against conflicts with an instance env * * ************************************************************************ Check whether a single family instance conflicts with those in two instance environments (one for the EPS and one for the HPT). -} checkForConflicts :: FamInstEnvs -> FamInst -> TcM Bool checkForConflicts inst_envs fam_inst = do { let conflicts = lookupFamInstEnvConflicts inst_envs fam_inst no_conflicts = null conflicts ; traceTc "checkForConflicts" $ vcat [ ppr (map fim_instance conflicts) , ppr fam_inst -- , ppr inst_envs ] ; unless no_conflicts $ conflictInstErr fam_inst conflicts ; return no_conflicts } conflictInstErr :: FamInst -> [FamInstMatch] -> TcRn () conflictInstErr fam_inst conflictingMatch | (FamInstMatch { fim_instance = confInst }) : _ <- conflictingMatch = addFamInstsErr (ptext (sLit "Conflicting family instance declarations:")) [fam_inst, confInst] | otherwise = panic "conflictInstErr" addFamInstsErr :: SDoc -> [FamInst] -> TcRn () addFamInstsErr herald insts = ASSERT( not (null insts) ) setSrcSpan srcSpan $ addErr $ hang herald 2 (vcat [ pprCoAxBranchHdr (famInstAxiom fi) 0 | fi <- sorted ]) where getSpan = getSrcLoc . famInstAxiom sorted = sortWith getSpan insts fi1 = head sorted srcSpan = coAxBranchSpan (coAxiomSingleBranch (famInstAxiom fi1)) -- The sortWith just arranges that instances are dislayed in order -- of source location, which reduced wobbling in error messages, -- and is better for users tcGetFamInstEnvs :: TcM FamInstEnvs -- Gets both the external-package inst-env -- and the home-pkg inst env (includes module being compiled) tcGetFamInstEnvs = do { eps <- getEps; env <- getGblEnv ; return (eps_fam_inst_env eps, tcg_fam_inst_env env) }
forked-upstream-packages-for-ghcjs/ghc
compiler/typecheck/FamInst.hs
bsd-3-clause
15,844
0
14
4,693
2,525
1,339
1,186
209
3
module A2 where data T a = C1 a | C2 Int addedC2 = error "added C2 Int to T" over :: (T b) -> b over (C1 x) = x over (C2 a) = addedC2
SAdams601/HaRe
old/testing/addCon/A2AST.hs
bsd-3-clause
141
0
7
43
70
38
32
6
1
{-# Language RankNTypes #-} {-# Language DataKinds #-} {-# Language PolyKinds #-} {-# Language GADTs #-} {-# Language TypeFamilies #-} module T15874 where import Data.Kind data Var where Op :: Var Id :: Var type Varianced = (forall (var :: Var). Type) data family Parser :: Varianced data instance Parser = P
sdiehl/ghc
testsuite/tests/polykinds/T15874.hs
bsd-3-clause
335
0
8
78
64
43
21
13
0
module Complex_Vectors (ComplexF, rootsOfUnity,thetas, norm,distance) where import Complex -- --import Strategies -- import Parallel type ComplexF = Complex Double rootsOfUnity:: Int -> [ComplexF] rootsOfUnity n =( zipWith (:+) cvar svar) -- (map cos (thetas n))- (map sin (thetas n)) where cvar = (map cos (thetas n)) svar = (map sin (thetas n)) thetas:: Int -> [Double] thetas n = --[(2*pi/fromInt n)*fromInt k | k<-[0 .. n-1]] (map(\k -> ((2*pi/fromInt n)*fromInt k)) [k | k<-[0 .. n-1]]) --`using` parListChunk 20 rnf fromInt :: (Num a) => Int -> a fromInt i = fromInteger (toInteger i) norm:: [ComplexF] -> Double norm = sqrt.sum.map((^2).magnitude) distance:: [ComplexF] -> [ComplexF] -> Double distance z w = norm(zipWith (-) z w)
RefactoringTools/HaRe
old/testing/evalMonad/Complex_Vectors.hs
bsd-3-clause
800
0
13
177
304
171
133
17
1
{-# LANGUAGE GADTs #-} module Main where data T t a where T :: (Foldable t, Eq a) => t a -> T t a {-# NOINLINE go #-} go :: T [] a -> Int -> Int go (T _) i = foldr (+) 0 [1..i] main = print (go (T [1::Int]) 20000)
ezyang/ghc
testsuite/tests/perf/should_run/T5835.hs
bsd-3-clause
219
0
10
59
122
67
55
8
1
{-# LANGUAGE TypeInType #-} module T9632 where import Data.Kind data B = T | F data P :: B -> * type B' = B data P' :: B' -> *
olsner/ghc
testsuite/tests/dependent/should_compile/T9632.hs
bsd-3-clause
131
0
5
35
46
29
17
-1
-1
-- !!! Class and instance decl module Test where class K a where op1 :: a -> a -> a op2 :: Int -> a instance K Int where op1 a b = a+b op2 x = x instance K Bool where op1 a b = a -- Pick up the default decl for op2 instance K [a] where op3 a = a -- Oops! Isn't a class op of K
ezyang/ghc
testsuite/tests/rename/should_fail/rnfail008.hs
bsd-3-clause
348
0
8
142
105
56
49
11
0
{-# LANGUAGE CPP #-} #ifdef TESTS module Data.Base58Address (BitcoinAddress, RippleAddress, RippleAddress0(..)) where #else module Data.Base58Address (BitcoinAddress, bitcoinAddressPayload, RippleAddress, rippleAddressPayload) where #endif import Control.Monad (guard) import Control.Arrow ((***)) import Data.Word import Data.Binary (Binary(..), putWord8) import Data.Binary.Get (getByteString) import qualified Crypto.Hash.SHA256 as SHA256 import qualified Data.ByteString as BS import Data.Base58Address.BaseConvert import Data.Base58Address.Alphabet #ifdef TESTS import Test.QuickCheck instance Arbitrary Base58Address where arbitrary = do ver <- arbitrary Positive adr <- arbitrary let bsiz = length (toBase 256 adr) plen <- choose (bsiz,bsiz+100) return $ Base58Address ver adr plen instance Arbitrary BitcoinAddress where arbitrary = fmap BitcoinAddress arbitrary instance Arbitrary RippleAddress where arbitrary = fmap RippleAddress arbitrary newtype RippleAddress0 = RippleAddress0 RippleAddress deriving (Show) instance Arbitrary RippleAddress0 where arbitrary = do adr <- arbitrary `suchThat` (>=0) return $ RippleAddress0 $ RippleAddress $ Base58Address 0 adr 20 #endif newtype BitcoinAddress = BitcoinAddress Base58Address deriving (Ord, Eq) bitcoinAlphabet :: Alphabet bitcoinAlphabet = read "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" bitcoinAddressPayload :: BitcoinAddress -> Integer bitcoinAddressPayload (BitcoinAddress (Base58Address _ p _)) = p instance Show BitcoinAddress where show (BitcoinAddress adr) = showB58 bitcoinAlphabet adr instance Read BitcoinAddress where readsPrec _ s = case decodeB58 bitcoinAlphabet s of Just x -> [(BitcoinAddress x,"")] Nothing -> [] newtype RippleAddress = RippleAddress Base58Address deriving (Ord, Eq) rippleAlphabet :: Alphabet rippleAlphabet = read "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz" rippleAddressPayload :: RippleAddress -> Integer rippleAddressPayload (RippleAddress (Base58Address _ p _)) = p instance Show RippleAddress where show (RippleAddress adr) = showB58 rippleAlphabet adr instance Read RippleAddress where readsPrec _ s = case decodeB58 rippleAlphabet s of Just x -> [(RippleAddress x,"")] Nothing -> [] instance Binary RippleAddress where get = do value <- (fromBase 256 . BS.unpack) `fmap` getByteString 20 return $ RippleAddress (Base58Address 0 value 20) put (RippleAddress (Base58Address 0 value 20)) = do let bytes = toBase 256 value mapM_ putWord8 (replicate (20 - length bytes) 0 ++ bytes) put _ = fail "RippleAddress account ID is always 0, length always 20" -- Version, payload, payload bytesize data Base58Address = Base58Address !Word8 !Integer !Int deriving (Show, Ord, Eq) showB58 :: Alphabet -> Base58Address -> String showB58 alphabet (Base58Address version addr plen) = prefix ++ toString alphabet 58 (fromBase 256 (bytes ++ mkChk bytes) :: Integer) where prefix = replicate (length $ takeWhile (==0) bytes) z bytes = version : replicate (plen - length bytes') 0 ++ bytes' bytes' = toBase 256 addr Just z = toAlphaDigit alphabet 0 decodeB58 :: Alphabet -> String -> Maybe Base58Address decodeB58 alphabet s = do (zs,digits) <- fmap (span (==0)) (toDigits alphabet s) let (chk,bytes) = splitChk $ toBase 256 $ fromBase 58 digits case map fromIntegral zs ++ bytes of [] -> Nothing (version:bytes') -> do guard (mkChk (version:bytes') == chk) return $! Base58Address version (fromBase 256 bytes') (length bytes') splitChk :: [a] -> ([a], [a]) splitChk = (reverse *** reverse) . splitAt 4 . reverse mkChk :: [Word8] -> [Word8] mkChk = BS.unpack . BS.take 4 . SHA256.hash . SHA256.hash . BS.pack
singpolyma/base58address
Data/Base58Address.hs
isc
3,715
10
17
570
1,204
627
577
71
2
module ShadowVarianceChebyshev1 where data T = T { minimum_variance :: Float } deriving (Eq, Show) chebyshev :: (Float, Float) -> Float -> Float -> Float chebyshev (d, ds) min_variance t = let p = if t <= d then 1.0 else 0.0 variance = max (ds - (d * d)) min_variance du = t - d p_max = variance / (variance + (du * du)) in max p p_max factor :: T -> (Float, Float) -> Float -> Float factor shadow (d, ds) t = chebyshev (d, ds) (minimum_variance shadow) t
io7m/r2
com.io7m.r2.documentation/src/main/resources/com/io7m/r2/documentation/haskell/ShadowVarianceChebyshev1.hs
isc
501
0
13
136
215
119
96
14
2
------------------- -- This module defines the following common monads: -- -- SR - state reader monad -- State - (strict) state transformer monad -- IOS - IO monad with state -- Output - output monad -- CPS - continuation passing monad -- -- Most of these monads can be found in Wadler's papers about monads. ---------------------------------------------------------------- module Monads( -- exports a Monad and Functor instance for each of these types: SR, runSR, getSR, State, runS, getS, setS, modS, IOS, runIOS, getIOS, setIOS, modIOS, Output, runO, outO, CPS, runCPS, callcc, getcc ) where ---------------------------------------------------------------- -- For each type defined in this module we provide: -- -- o A Functor instance -- o A Monad instance -- o A function -- -- run<M> :: <M> a -> T a -- -- which executes a computation of type M. This function usually takes -- extra parameters (eg an input state) and returns the value of the -- computation and some output values (eg an output state) -- -- o State monads (ie SR, State and IOS) also provide: -- -- get<M> :: <M> s -- set<M> :: s -> <M> () -- not SR -- mod<M> :: (s -> s) -> <M> () -- not SR -- -- which get the current state, set the state to a new value and apply -- a function to the state, respectively. ---------------------------------------------------------------- ---------------------------------------------------------------- -- The state reader monad ---------------------------------------------------------------- newtype SR s a = SR (s -> a) runSR :: SR s a -> s -> a getSR :: SR s s instance Functor (SR s) where fmap f xs = do x <- xs; return (f x) instance Monad (SR s) where m >>= k = SR (\s -> case (unSR m) s of a -> (unSR (k a)) s) m >> k = SR (\s -> case (unSR m) s of _ -> (unSR k) s) return a = SR (\s -> a) runSR = unSR getSR = SR (\s -> s) -- left inverse of S (not exported) unSR :: SR s a -> (s -> a) unSR (SR m) = m ---------------------------------------------------------------- -- A strict state monad ---------------------------------------------------------------- newtype State s a = S (s -> (a,s)) runS :: State s a -> s -> (a,s) modS :: (s -> s) -> State s () setS :: s -> State s () getS :: State s s instance Functor (State s) where fmap f xs = do x <- xs; return (f x) instance Monad (State s) where m >>= k = S (\s -> case (unS m) s of (a,s') -> (unS (k a)) s') m >> k = S (\s -> case (unS m) s of (_,s') -> (unS k) s') return a = S (\s -> (a,s)) runS = unS modS f = S (\s -> ((),f s)) setS s' = S (\s -> ((),s')) getS = S (\s -> (s,s)) -- left inverse of S (not exported) unS :: State s a -> (s -> (a,s)) unS (S m) = m ---------------------------------------------------------------- -- A standard IO + state monad ---------------------------------------------------------------- newtype IOS s a = IOS (s -> IO (a, s)) runIOS :: IOS s a -> s -> IO (a, s) getIOS :: IOS s s setIOS :: s -> IOS s () modIOS :: (s -> s) -> IOS s s instance Functor (IOS s) where fmap f xs = do x <- xs; return (f x) instance Monad (IOS s) where m >>= k = IOS (\s -> unIOS m s >>= \(a,s') -> unIOS (k a) s') m >> k = IOS (\s -> unIOS m s >>= \(_,s') -> unIOS k s') return a = IOS (\s -> return (a,s)) runIOS = unIOS modIOS f = IOS (\s -> return (s, f s)) setIOS s' = IOS (\s -> return ((),s')) getIOS = IOS (\s -> return (s,s)) -- left inverse of IOS (not exported) unIOS :: IOS s a -> (s -> IO (a, s)) unIOS (IOS m) = m ---------------------------------------------------------------- -- An "output" monad - like that in Wadler's "Essence of Functional -- Programming". ---------------------------------------------------------------- newtype Output s a = O (a, [s] -> [s]) runO :: Output s a -> (a, [s]) outO :: [s] -> Output s () instance Functor (Output s) where fmap f xs = do x <- xs; return (f x) instance Monad (Output s) where m >>= k = O (let (a,r) = unO m; (b,s) = unO (k a) in (b, r . s)) m >> k = O (let (a,r) = unO m; (b,s) = unO k in (b, r . s)) return a = O (a, \s -> s) runO (O (a,s)) = (a, s []) outO s = O ((), (s ++)) -- left inverse of O (not exported) unO :: Output s a -> (a, [s] -> [s]) unO (O m) = m ---------------------------------------------------------------- -- A CPS monad - parameterised over the type of the continuation ---------------------------------------------------------------- newtype CPS r a = CPS ((a -> r) -> r) runCPS :: CPS r a -> (a -> r) -> r callcc :: r -> CPS r a getcc :: ((a -> r) -> CPS r a) -> CPS r a instance Functor (CPS s) where fmap f xs = do x <- xs; return (f x) instance Monad (CPS r) where m >>= k = CPS (\c -> unCPS m (\a -> unCPS (k a) c)) m >> k = CPS (\c -> unCPS m (\a -> unCPS k c)) return a = CPS (\c -> c a) runCPS = unCPS callcc cc = CPS (\c -> cc) getcc m = CPS (\c -> unCPS (m c) c) unCPS :: CPS r a -> ((a -> r) -> r) unCPS (CPS m) = m
jtestard/cse230Winter2015
SOE/haskore/src/Monads.hs
mit
5,122
14
16
1,278
2,000
1,079
921
76
1
module Statistics.SGT.Util where sq :: (Num a) => a -> a sq n = n * n -- for use with non-Double args (//) :: Integral a => a -> a -> Double (//) a b = fromIntegral a / fromIntegral b dbl :: Integral a => a -> Double dbl = fromIntegral dblLog :: Integral a => a -> Double dblLog = log . dbl
marklar/Statistics.SGT
Statistics/SGT/Util.hs
mit
295
0
7
70
128
69
59
-1
-1
{- Using textures instead of surfaces -} {-# LANGUAGE OverloadedStrings #-} module Lesson07 where -- import qualified SDL import Linear.V4 (V4(..)) -- import Control.Concurrent (threadDelay) import Control.Monad (unless,when) -- import qualified Config -- lesson07 :: IO () lesson07 = do SDL.initialize [SDL.InitVideo] window <- SDL.createWindow "Lesson07" Config.winConfig renderer <- SDL.createRenderer window (-1) Config.rdrConfig -- using Hint, comment out for seeing the effects -- reference: https://en.wikipedia.org/wiki/Image_scaling#Scaling_methods -- *************** SDL.HintRenderScaleQuality SDL.$= SDL.ScaleLinear -- *************** -- set a color for renderer SDL.rendererDrawColor renderer SDL.$= V4 minBound minBound maxBound maxBound -- load image into main memory (as a surface) imgSf <- SDL.loadBMP "./img/07/Potion.bmp" -- translate a surface to a texture -- i.e. load image into video memory imgTx <- SDL.createTextureFromSurface renderer imgSf SDL.freeSurface imgSf SDL.showWindow window let loop = do events <- SDL.pollEvents let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events -- clear(i.e. fill) renderer with the color we set SDL.clear renderer -- copy(blit) image texture onto renderer SDL.copy renderer imgTx Nothing Nothing -- A renderer in SDL is basically a buffer -- the present function forces a renderer to flush SDL.present renderer -- threadDelay 20000 unless quit loop loop -- releasing resources SDL.destroyWindow window SDL.destroyRenderer renderer SDL.destroyTexture imgTx SDL.quit
jaiyalas/sdl2-examples
src/Lesson07.hs
mit
1,730
0
18
394
337
168
169
33
1
module Main where import Test.QuickCheck import Tictactoe.Base import Tictactoe.Move.Base import Tictactoe.Def.Move as DefMove import Tictactoe.Att.Move as AttMove import Tictactoe.Bencode.Encoder as Bencode import Tictactoe.Bencode.Decoder as Bencode import Tictactoe.BencodeDict.Encoder as BencodeDict import Tictactoe.BencodeDict.Decoder as BencodeDict testCase :: (Eq a) => a -> a -> Bool testCase res exp = res == exp main :: IO () main = do quickCheck $ testCase (DefMove.moveByScenario DefMove.First [(1, 1, 'x')]) (Just ((0, 0, 'o'), ExpOppositeCorner (2, 2))) quickCheck $ testCase (DefMove.moveByScenario DefMove.First [(0, 2, 'x')]) (Just ((1, 1, 'o'), ExpOppositeSelfCorner (2, 0))) quickCheck $ testCase (DefMove.moveByScenario (ExpOppositeCorner (0, 2)) [(0, 0, 'x'), (1, 1, 'x'), (0, 2, 'o')]) (Just ((2, 0, 'o'), DefMove.NoExp)) quickCheck $ testCase (DefMove.moveByScenario (ExpOppositeSelfCorner (2, 2)) [(0, 0, 'x'), (1, 1, 'o'), (2, 2, 'o')]) (Just ((0, 1, 'o'), DefMove.NoExp)) quickCheck $ testCase (finishingMove [(1, 1, 'x'), (2, 2, 'x')] 'x') (Just (0,0)) quickCheck $ testCase (finishingMove [(1, 1, 'x'), (2, 2, 'x')] 'o') Nothing quickCheck $ testCase (finishingMove [(1,1,'x'),(2,2,'o'),(0,0,'o')] 'x') Nothing quickCheck $ testCase (finishingMove [(1,0,'x'),(1,1,'x')] 'x') (Just (1,2)) quickCheck $ testCase (finishingMove [(1,0,'x'),(1,1,'x')] 'o') Nothing quickCheck $ testCase (finishingMove [(0,0,'x'),(1,1,'x'),(2,2,'o'),(2,0,'x'),(1,0,'o'),(1,2,'o')] 'o') (Just (0,2)) quickCheck $ testCase (finishingMove [(0,0,'x'),(1,1,'x'),(2,2,'o'),(2,0,'x'),(1,0,'o'),(1,2,'o'),(0,2,'x')] 'o') Nothing quickCheck $ testCase (finishingMove [(0,0,'x'),(1,1,'x'),(2,2,'o'),(2,0,'x'),(1,0,'o'),(1,2,'o'),(0,2,'x')] 'x') (Just (0,1)) quickCheck $ testCase (Bencode.parseBoard "ld1:v1:o1:xi2e1:yi1eed1:v1:x1:xi0e1:yi1eed1:v1:o1:xi1e1:yi0eed1:v1:x1:xi2e1:yi0eee") [(2,0,'x'),(1,0,'o'),(0,1,'x'),(2,1,'o')] quickCheck $ testCase (Bencode.stringifyBoard [(2,1,'o'),(0,1,'x'),(1,0,'o'),(2,0,'x')]) "ld1:v1:o1:xi2e1:yi1eed1:v1:x1:xi0e1:yi1eed1:v1:o1:xi1e1:yi0eed1:v1:x1:xi2e1:yi0eee" quickCheck $ testCase (BencodeDict.parseBoard "d1:0d1:v1:x1:xi1e1:yi1ee1:1d1:v1:o1:xi1e1:yi0ee1:2d1:v1:x1:xi0e1:yi2ee1:3d1:v1:o1:xi0e1:yi0eee") [(0,0,'o'),(0,2,'x'),(1,0,'o'),(1,1,'x')] quickCheck $ testCase (BencodeDict.stringifyBoard [(1,1,'x'),(1,0,'o'),(0,2,'x'),(0,0,'o')]) "d1:0d1:v1:x1:xi1e1:yi1ee1:1d1:v1:o1:xi1e1:yi0ee1:2d1:v1:x1:xi0e1:yi2ee1:3d1:v1:o1:xi0e1:yi0eee" quickCheck $ testCase (gameState [] 'x') Ongoing quickCheck $ testCase (gameState [(1,1,'x'),(2,2,'x'),(0,0,'o')] 'x') Ongoing quickCheck $ testCase (gameState [(1,1,'x'),(2,2,'x'),(0,0,'x')] 'x') Won quickCheck $ testCase (gameState [(1,1,'x'),(2,2,'x'),(0,0,'x')] 'o') Lost quickCheck $ testCase (gameState [(0,0,'x'),(0,1,'x'),(0,2,'o'),(1,0,'o'),(1,1,'o'),(1,2,'x'),(2,0,'x'),(2,1,'x'),(2,2,'o')] 'x') Tie
viktorasl/tictactoe-bot
tests/Tictactoe/Tests.hs
mit
2,972
0
13
345
1,607
962
645
35
1
----------------------------------------------------------- -- | -- module: C2HS.C.Extra.Marshal -- copyright: (c) 2016 Tao He -- license: MIT -- maintainer: [email protected] -- -- Convenient marshallers for complicate C types. -- {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 709 {-# LANGUAGE Safe #-} #elif __GLASGOW_HASKELL__ >= 701 {-# LANGUAGE Trustworthy #-} #endif module C2HS.C.Extra.Marshal ( peekIntegral , peekString , peekStringArray , withStringArray , peekIntegralArray , withIntegralArray ) where import Foreign.C.String ( peekCString, withCString ) import Foreign.C.Types ( CChar, CInt, CUInt ) import Foreign.Marshal.Array ( peekArray, withArray ) import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable, peek ) -- | Peek from pointer then cast to another integral type. peekIntegral :: (Integral a, Storable a, Integral b) => Ptr a -> IO b peekIntegral p = if p == nullPtr then return 0 else fromIntegral <$> peek p {-# SPECIALIZE peekIntegral :: Ptr CInt -> IO Int #-} -- | Peek string from a two-dimension pointer of CChar. peekString :: Ptr (Ptr CChar) -> IO String peekString p = if p == nullPtr then return "" else peek p >>= \p' -> if p' == nullPtr then return "" else peekCString p' -- | Peek an array of String and the result's length is given. peekStringArray :: Integral n => n -> Ptr (Ptr CChar) -> IO [String] peekStringArray 0 _ = return [] peekStringArray n p = if p == nullPtr then return [] else peekArray (fromIntegral n) p >>= mapM (\p' -> if p' == nullPtr then return "" else peekCString p') {-# SPECIALIZE peekStringArray :: Int -> Ptr (Ptr CChar) -> IO [String] #-} {-# SPECIALIZE peekStringArray :: CUInt -> Ptr (Ptr CChar) -> IO [String] #-} -- | Use an array of String as argument, usually used to pass multiple names to C -- functions. withStringArray :: [String] -> (Ptr (Ptr CChar) -> IO a) -> IO a withStringArray [] f = f nullPtr withStringArray ss f = do ps <- mapM (\s -> withCString s return) ss withArray ps f -- | Peek an array of integral values and the result's length is given. peekIntegralArray :: (Integral n, Integral m, Storable m) => Int -> Ptr m -> IO [n] peekIntegralArray n p = (map fromIntegral) <$> peekArray n p {-# SPECIALIZE peekIntegralArray :: Int -> Ptr CInt -> IO [Int] #-} {-# SPECIALIZE peekIntegralArray :: Int -> Ptr CUInt -> IO [Int] #-} -- | Use an array of Integral as argument. withIntegralArray :: (Integral a, Integral b, Storable b) => [a] -> (Ptr b -> IO c) -> IO c withIntegralArray ns f = do let ns' = fmap fromIntegral ns withArray ns' f {-# SPECIALIZE withIntegralArray :: [Int] -> (Ptr CInt -> IO c) -> IO c #-} {-# SPECIALIZE withIntegralArray :: [CInt] -> (Ptr CInt -> IO c) -> IO c #-} {-# SPECIALIZE withIntegralArray :: [CUInt] -> (Ptr CUInt -> IO c) -> IO c #-}
sighingnow/mxnet-haskell
c2hs-extra/src/C2HS/C/Extra/Marshal.hs
mit
3,227
0
11
932
638
344
294
51
3
import qualified Data.ByteString.Lazy as LB import HaxParse.Parser import HaxParse.Options import HaxParse.Output import Options.Applicative import System.Exit import System.IO main :: IO () main = do opts <- execParser fullOpts res <- parseFile $ file opts let newOpts = if null (eventTypes opts) then opts else opts { showEvents = True } case res of Left m -> do hPutStrLn stderr $ "Parsing failed: " ++ show m exitFailure Right s -> outputWith newOpts s
pikajude/haxparse
src/Main.hs
mit
607
0
14
223
163
82
81
14
3
module Main (main) where import Data.List (genericLength) import Data.Maybe (catMaybes) import System.Directory (doesFileExist) import System.Exit (exitFailure, exitSuccess) import System.Process (readProcess) import Text.Regex (matchRegex, mkRegex) average :: (Fractional a, Real b) => [b] -> a average xs = realToFrac (sum xs) / genericLength xs expected :: Fractional a => a expected = 90 main :: IO () main = do file <- tix let arguments = ["report", file] output <- readProcess "hpc" arguments "" if average (match output) >= (expected :: Float) then exitSuccess else putStr output >> exitFailure match :: String -> [Int] match = fmap read . concat . catMaybes . fmap (matchRegex regex) . lines where regex = mkRegex "^ *([0-9]*)% " -- The location of the TIX file changed between versions of cabal-install. -- See <https://github.com/tfausak/haskeleton/issues/31> for details. tix :: IO FilePath tix = do let newFile = "tests.tix" oldFile = "dist/hpc/tix/tests/tests.tix" newFileExists <- doesFileExist newFile let file = if newFileExists then newFile else oldFile return file
tfausak/haskeleton
package-name/test-suite/HPC.hs
mit
1,152
0
11
229
348
184
164
29
2
{-# LANGUAGE NoImplicitPrelude #-} module Advent.Day1Spec (main, spec) where import Advent.Day1 import BasePrelude import Test.Hspec import Test.QuickCheck main :: IO () main = hspec spec spec :: Spec spec = do describe "day1Part1" $ do it "equal delimiters cancel out" $ do day1Part1 "(())" `shouldBe` 0 day1Part1 "()()" `shouldBe` 0 it "equal delimiters QC" $ property $ let charCount char = genericLength . filter (==char) in \x -> charCount '(' x - charCount ')' x == day1Part1 x it "excess open parens goes to upper floor" $ do day1Part1 "(((" `shouldBe` 3 day1Part1 "(()(()(" `shouldBe` 3 day1Part1 "))(((((" `shouldBe` 3 it "excess close parens goes to basement" $ do day1Part1 "())" `shouldBe` negate 1 day1Part1 "))(" `shouldBe` negate 1 day1Part1 ")))" `shouldBe` negate 3 day1Part1 ")())())" `shouldBe` negate 3 describe "day1Part2" $ do it "initial close paren reaches the basement immediately" $ do day1Part2 (negate 1) ")" `shouldBe` Just 1 it "()()) enters the basement at position 5" $ do day1Part2 (negate 1) "()())" `shouldBe` Just 5 it "should return Nothing for strings that don't reach the target floor" $ do day1Part2 (negate 1) "(((" `shouldBe` Nothing day1Part2 1 ")))" `shouldBe` Nothing day1Part2 1 "" `shouldBe` Nothing
jhenahan/adventofcode
test/Advent/Day1Spec.hs
mit
1,419
0
17
369
420
202
218
35
1
{-# LANGUAGE OverloadedStrings #-} module Y2021.M02.D18.Exercise where {-- We uploaded the reviews yesterday, but the unicoded wine-reviews also have an (optional) score and an (optional) price-point. We need to upload those data now, as well. --} import qualified Data.Text as T import Y2021.M02.D03.Solution (Review, Review(Review)) import Graph.Query (graphEndpoint, getGraphResponse) import Graph.JSON.Cypher (showAttribs, Cypher) import Data.Relation import Y2021.M02.D08.Solution (extractReviews, fetchWineContext) import qualified Y2021.M02.D15.Solution as Fixed -- so, from a review, we need a set of attributes: rev2attribs :: Review -> [Attribute Integer] rev2attribs = undefined -- recall that these attributes are of type Maybe Int -- now, the matcher is interesting, because we're matching the relation, -- not the node matchQuery :: Review -> Cypher matchQuery rev@(Review rx wx _rev _mbsc _mbpr) = T.pack (unwords ["MATCH (t:Taster)-[r:RATES_WINE]->(w:Wine)", "WHERE id(t) =", show rx, "AND id(w)=", show wx, "SET r +=", showAttribs (rev2attribs rev)]) -- with the above, you should be able to update all the unicoded wine-reviews -- with prices and scores. {-- >>> snd <$> (graphEndpoint >>= fetchWineContext >>= extractReviews (Fixed.thisDir ++ Fixed.fixedFile)) >>> let unis = it >>> graphEndpoint >>= flip getGraphResponse (map matchQuery unis) "...{\"columns\":[],\"data\":[]}],\"errors\":[]}\n" --}
geophf/1HaskellADay
exercises/HAD/Y2021/M02/D18/Exercise.hs
mit
1,478
0
11
245
202
126
76
16
1
module Main where import Puzzle import Solver import System.TimeIt main :: IO () main = analyzeAndSolve oscarsPuzzle --main = analyzeAndSolve mediumPuzzle analyzeAndSolve :: Puzzle -> IO () analyzeAndSolve p = do analyzePuzzle p timeIt $ putStrLn $ show $ solve p timeIt $ putStrLn $ show $ take 100 $ solveAll p -- timeIt $ putStrLn $ show $ length $ solveAll p
johwerm/cube-solver
src/Main.hs
mit
381
0
10
81
106
53
53
11
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, InstanceSigs #-} module LinterUtility (linterSettings) where import Control.Applicative import Data.List.Utils import System.IO import Data.ConfigFile import CompilationUtility import qualified ConfigFile import Printer import Utility data LINTER_SETTINGS = LINTER_SETTINGS { ls_executable :: FilePath, ls_flags :: [String], ls_files :: [FilePath], ls_verbose :: Bool } linterSettings :: ConfigParser -> [FilePath] -> EitherT String IO LINTER_SETTINGS linterSettings cp files = LINTER_SETTINGS <$> ConfigFile.getFile cp "DEFAULT" "utility.linter.executable" <*> (fmap words $ hoistEither $ ConfigFile.get cp "DEFAULT" "utility.linter.flags") <*> pure files <*> (hoistEither $ ConfigFile.getBool cp "DEFAULT" "verbose") instance UtilitySettings LINTER_SETTINGS where executable = ls_executable toStringList ls = concat [ls_flags ls, ls_files ls] utitle _ = Just "Linter" verbose = ls_verbose instance CompilationUtility LINTER_SETTINGS () where defaultValue :: LINTER_SETTINGS -> () defaultValue _ = () failure :: UtilityResult LINTER_SETTINGS -> EitherT String IO () failure r = do dPut [Failure] output <- catchIO $ hGetContents $ ur_stdout r report <- if "" == output then catchIO $ hGetContents $ ur_stderr r else return $ cleanStdout output dPut [Str report, Ln $ "Exit code: " ++ (show $ ur_exit_code r)] throwT "LinterUtility failure" where cleanStdout x = unlines $ (take $ (length $ lines x) - 6) $ lines x success :: UtilityResult LINTER_SETTINGS -> EitherT String IO () success r = do report <- catchIO $ hGetLine $ ur_stdout r dPut [Str " ", Str report, Success]
Prinhotels/goog-closure
src/LinterUtility.hs
mit
1,748
0
15
309
511
262
249
42
1
import System.Random import Control.Monad(when) main = do gen <- getStdGen askForNumber gen askForNumber :: StdGen -> IO () askForNumber gen = do let (randNumber, newGen) = randomR (1,10) gen :: (Int, StdGen) putStr "Which number in the range from 1 to 10 am I thinking of? " numberString <- getLine when (not $ null numberString) $ do let number = read numberString if randNumber == number then putStrLn "You are correct!" else putStrLn $ "Sorry, it was " ++ show randNumber askForNumber newGen
KHs000/haskellToys
src/scripts/guess_the_number.hs
mit
604
0
13
191
172
83
89
16
2
{- | Module : $Header$ Description : Static analysis of CspCASL Copyright : (c) Andy Gimblett, Liam O'Reilly, Markus Roggenbach, Swansea University 2008, C. Maeder, DFKI 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Static analysis of CSP-CASL specifications, following "Tool Support for CSP-CASL", MPhil thesis by Andy Gimblett, 2008. <http://www.cs.swan.ac.uk/~csandy/mphil/> -} module CspCASL.StatAnaCSP where import CASL.AS_Basic_CASL import CASL.Fold import CASL.MixfixParser import CASL.Quantification import CASL.Sign import CASL.StaticAna import CASL.ToDoc () import Common.AS_Annotation import Common.Result import Common.GlobalAnnotations import Common.Id import Common.Lib.State import Common.ExtSign import qualified Common.Lib.MapSet as MapSet import CspCASL.AS_CspCASL import CspCASL.AS_CspCASL_Process import qualified CspCASL.LocalTop as LocalTop import CspCASL.Print_CspCASL import CspCASL.SignCSP import CspCASL.Symbol import qualified Data.Set as Set import qualified Data.Map as Map import Data.Maybe import Control.Monad type CspBasicSpec = BASIC_SPEC CspBasicExt () CspSen {- | The first element of the returned pair (CspBasicSpec) is the same as the inputted version just with some very minor optimisations - none in our case, but for CASL - brackets are otimized. This all that happens, the mixfixed terms are still mixed fixed terms in the returned version. -} basicAnalysisCspCASL :: (CspBasicSpec, CspCASLSign, GlobalAnnos) -> Result (CspBasicSpec, ExtSign CspCASLSign CspSymbol, [Named CspCASLSen]) basicAnalysisCspCASL inp@(_, insig, _) = do (bs, ExtSign sig syms, sens) <- basicAnaAux inp -- check for local top elements in the subsort relation appendDiags $ LocalTop.checkLocalTops $ sortRel sig let ext = extendedInfo sig return (bs, ExtSign sig $ Set.unions $ Set.map caslToCspSymbol syms : toSymbolSet (diffCspSig ext $ extendedInfo insig), sens) basicAnaAux :: (CspBasicSpec, CspCASLSign, GlobalAnnos) -> Result (CspBasicSpec, ExtSign CspCASLSign Symbol, [Named CspCASLSen]) basicAnaAux = basicAnalysis (const return) ana_BASIC_CSP (const return) emptyMix ana_BASIC_CSP :: Ana CspBasicExt CspBasicExt () CspSen CspSign ana_BASIC_CSP mix bs = do let caslMix = emptyMix { mixRules = mixRules mix } case bs of Channels cs _ -> mapM_ (anaChanDecl . item) cs ProcItems ps _ -> mapM_ (anaProcItem caslMix) ps return bs -- Static analysis of channel declarations -- | Statically analyse a CspCASL channel declaration. anaChanDecl :: CHANNEL_DECL -> State CspCASLSign () anaChanDecl (ChannelDecl chanNames chanSort) = do checkSorts [chanSort] -- check channel sort is known sig <- get let ext = extendedInfo sig oldChanMap = chans ext newChanMap <- foldM (anaChannelName chanSort) oldChanMap chanNames sig2 <- get put sig2 { extendedInfo = ext { chans = newChanMap }} -- | Statically analyse a CspCASL channel name. anaChannelName :: SORT -> ChanNameMap -> CHANNEL_NAME -> State CspCASLSign ChanNameMap anaChannelName s m chanName = do sig <- get if Set.member chanName (sortSet sig) then do let err = "channel name already in use as a sort name" addDiags [mkDiag Error err chanName] return m else do when (MapSet.member chanName s m) $ addDiags [mkDiag Warning "redeclared channel" chanName] return $ MapSet.insert chanName s m -- Static analysis of process items -- | Statically analyse a CspCASL process item. anaProcItem :: Mix b s () () -> Annoted PROC_ITEM -> State CspCASLSign () anaProcItem mix annotedProcItem = case item annotedProcItem of Proc_Decl name argSorts alpha -> anaProcDecl name argSorts alpha Proc_Defn name args alpha procTerm -> do let vs = flatVAR_DECLs args argSorts = map snd vs alpha' = case alpha of ProcAlphabet alpha'' -> Set.fromList alpha'' procProfile = ProcProfile argSorts alpha' pn = ParmProcname (FQ_PROCESS_NAME name procProfile) $ map fst vs anaProcDecl name argSorts alpha anaProcEq mix annotedProcItem pn procTerm Proc_Eq parmProcName procTerm -> anaProcEq mix annotedProcItem parmProcName procTerm -- Static analysis of process declarations -- | Statically analyse a CspCASL process declaration. anaProcDecl :: PROCESS_NAME -> PROC_ARGS -> PROC_ALPHABET -> State CspCASLSign () anaProcDecl name argSorts comms = do sig <- get let ext = extendedInfo sig oldProcDecls = procSet ext newProcDecls <- do -- new process declation profile <- anaProcAlphabet argSorts comms -- we no longer add (channel and) proc symbols to the CASL signature if isNameInProcNameMap name profile oldProcDecls -- Check the name (with profile) is new (for warning only) then -- name with profile already in signature do let warn = "process name redeclared with same profile '" ++ show (printProcProfile profile) ++ "':" addDiags [mkDiag Warning warn name] return oldProcDecls else {- New name with profile - add the name to the signature in the state -} return $ addProcNameToProcNameMap name profile oldProcDecls sig2 <- get put sig2 { extendedInfo = ext {procSet = newProcDecls }} -- Static analysis of process equations {- | Find a profile for a process name. Either the profile is given via a parsed fully qualified process name, in which case we check everything is valid and the process name with the profile is known. Or its a plain process name where we must deduce a unique profile if possible. We also know how many variables / parameters the process name has. -} findProfileForProcName :: FQ_PROCESS_NAME -> Int -> ProcNameMap -> State CspCASLSign (Maybe ProcProfile) findProfileForProcName pn numParams procNameMap = case pn of FQ_PROCESS_NAME pn' (ProcProfile argSorts comms) -> do procProfile <- anaProcAlphabet argSorts $ ProcAlphabet $ Set.toList comms if MapSet.member pn' procProfile procNameMap then return $ Just procProfile else do addDiags [mkDiag Error "Fully qualified process name not in signature" pn] return Nothing PROCESS_NAME pn' -> let resProfile = getUniqueProfileInProcNameMap pn' numParams procNameMap in case resultToMaybe resProfile of Nothing -> do addDiags $ diags resProfile return Nothing Just profile' -> return $ Just profile' {- | Analyse a process name an return a fully qualified one if possible. We also know how many variables / parameters the process name has. -} anaProcName :: FQ_PROCESS_NAME -> Int -> State CspCASLSign (Maybe FQ_PROCESS_NAME) anaProcName pn numParams = do sig <- get let ext = extendedInfo sig procDecls = procSet ext simpPn = procNameToSimpProcName pn maybeProf <- findProfileForProcName pn numParams procDecls case maybeProf of Nothing -> return Nothing Just procProfile -> -- We now construct the real fully qualified process name return $ Just $ FQ_PROCESS_NAME simpPn procProfile -- | Statically analyse a CspCASL process equation. anaProcEq :: Mix b s () () -> Annoted a -> PARM_PROCNAME -> PROCESS -> State CspCASLSign () anaProcEq mix a (ParmProcname pn vs) proc = {- the 'annoted a' contains the annotation of the process equation. We do not care what the underlying item is in the annotation (but it probably will be the proc eq) -} do maybeFqPn <- anaProcName pn (length vs) case maybeFqPn of -- Only analyse a process if its name and profile is known Nothing -> return () Just fqPn -> case fqPn of PROCESS_NAME _ -> error "CspCasl.StatAnaCSP.anaProcEq: Impossible case" FQ_PROCESS_NAME _ (ProcProfile argSorts commAlpha) -> do gVars <- anaProcVars pn argSorts vs {- compute global vars Change a procVarList to a FQProcVarList We do not care about the range as we are building fully qualified variables and they have already been checked to be ok. -} let mkFQProcVar (v, s) = Qual_var v s nullRange fqGVars = map mkFQProcVar gVars (termAlpha, fqProc) <- anaProcTerm mix proc (Map.fromList gVars) Map.empty checkCommAlphaSub termAlpha commAlpha proc "process equation" {- put CspCASL Sentences back in to the state with new sentence BUG - What should the constituent alphabet be for this process? probably the same as the inner one! -} addSentences [makeNamedSen $ {- We take the annotated item and replace the inner item, thus preserving the annotations. We then take this annotated sentence and make it a named sentence in accordance to the (if existing) name in the annotations. -} a {item = ExtFORMULA $ ProcessEq fqPn fqGVars commAlpha fqProc}] -- | Statically analyse a CspCASL process equation's global variable names. anaProcVars :: FQ_PROCESS_NAME -> [SORT] -> [VAR] -> State CspCASLSign ProcVarList anaProcVars pn ss vs = let msg str = addDiags [mkDiag Error ("process name applied to " ++ str) pn] >> return [] in fmap reverse $ case compare (length ss) $ length vs of LT -> msg "too many arguments" GT -> msg "not enough arguments" EQ -> foldM anaProcVar [] (zip vs ss) -- | Statically analyse a CspCASL process-global variable name. anaProcVar :: ProcVarList -> (VAR, SORT) -> State CspCASLSign ProcVarList anaProcVar old (v, s) = if v `elem` map fst old then do addDiags [mkDiag Error "Process argument declared more than once" v] return old else return ((v, s) : old) -- Static analysis of process terms {- BUG in fucntion below not returing FQProcesses Statically analyse a CspCASL process term. The process that is returned is a fully qualified process. -} anaProcTerm :: Mix b s () () -> PROCESS -> ProcVarMap -> ProcVarMap -> State CspCASLSign (CommAlpha, PROCESS) anaProcTerm mix proc gVars lVars = case proc of NamedProcess name args r -> do addDiags [mkDiag Debug "Named process" proc] (fqName, al, fqArgs) <- anaNamedProc mix proc name args (lVars `Map.union` gVars) let fqProc = FQProcess (NamedProcess fqName fqArgs r) al r return (al, fqProc) Skip r -> do addDiags [mkDiag Debug "Skip" proc] let fqProc = FQProcess (Skip r) Set.empty r return (Set.empty, fqProc) Stop r -> do addDiags [mkDiag Debug "Stop" proc] let fqProc = FQProcess (Stop r) Set.empty r return (Set.empty, fqProc) Div r -> do addDiags [mkDiag Debug "Div" proc] let fqProc = FQProcess (Div r) Set.empty r return (Set.empty, fqProc) Run es r -> do addDiags [mkDiag Debug "Run" proc] (comms, fqEs) <- anaEventSet es let fqProc = FQProcess (Run fqEs r) comms r return (comms, fqProc) Chaos es r -> do addDiags [mkDiag Debug "Chaos" proc] (comms, fqEs) <- anaEventSet es let fqProc = FQProcess (Chaos fqEs r) comms r return (comms, fqProc) PrefixProcess e p r -> do addDiags [mkDiag Debug "Prefix" proc] (evComms, rcvMap, fqEvent) <- anaEvent mix e (lVars `Map.union` gVars) (comms, pFQTerm) <- anaProcTerm mix p gVars (rcvMap `Map.union` lVars) let newAlpha = comms `Set.union` evComms fqProc = FQProcess (PrefixProcess fqEvent pFQTerm r) newAlpha r return (newAlpha, fqProc) Sequential p q r -> do addDiags [mkDiag Debug "Sequential" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (qComms, qFQTerm) <- anaProcTerm mix q gVars Map.empty let newAlpha = pComms `Set.union` qComms fqProc = FQProcess (Sequential pFQTerm qFQTerm r) newAlpha r return (newAlpha, fqProc) InternalChoice p q r -> do addDiags [mkDiag Debug "InternalChoice" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (qComms, qFQTerm) <- anaProcTerm mix q gVars lVars let newAlpha = pComms `Set.union` qComms fqProc = FQProcess (InternalChoice pFQTerm qFQTerm r) newAlpha r return (newAlpha, fqProc) ExternalChoice p q r -> do addDiags [mkDiag Debug "ExternalChoice" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (qComms, qFQTerm) <- anaProcTerm mix q gVars lVars let newAlpha = pComms `Set.union` qComms fqProc = FQProcess (ExternalChoice pFQTerm qFQTerm r) newAlpha r return (newAlpha, fqProc) Interleaving p q r -> do addDiags [mkDiag Debug "Interleaving" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (qComms, qFQTerm) <- anaProcTerm mix q gVars lVars let newAlpha = pComms `Set.union` qComms fqProc = FQProcess (Interleaving pFQTerm qFQTerm r) newAlpha r return (newAlpha, fqProc) SynchronousParallel p q r -> do addDiags [mkDiag Debug "Synchronous" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (qComms, qFQTerm) <- anaProcTerm mix q gVars lVars let newAlpha = pComms `Set.union` qComms fqProc = FQProcess (SynchronousParallel pFQTerm qFQTerm r) newAlpha r return (newAlpha, fqProc) GeneralisedParallel p es q r -> do addDiags [mkDiag Debug "Generalised parallel" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (synComms, fqEs) <- anaEventSet es (qComms, qFQTerm) <- anaProcTerm mix q gVars lVars let newAlpha = Set.unions [pComms, qComms, synComms] fqProc = FQProcess (GeneralisedParallel pFQTerm fqEs qFQTerm r) newAlpha r return (newAlpha, fqProc) AlphabetisedParallel p esp esq q r -> do addDiags [mkDiag Debug "Alphabetised parallel" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (pSynComms, fqEsp) <- anaEventSet esp checkCommAlphaSub pSynComms pComms proc "alphabetised parallel, left" (qSynComms, fqEsq) <- anaEventSet esq (qComms, qFQTerm) <- anaProcTerm mix q gVars lVars checkCommAlphaSub qSynComms qComms proc "alphabetised parallel, right" let newAlpha = pComms `Set.union` qComms fqProc = FQProcess (AlphabetisedParallel pFQTerm fqEsp fqEsq qFQTerm r) newAlpha r return (newAlpha, fqProc) Hiding p es r -> do addDiags [mkDiag Debug "Hiding" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (hidComms, fqEs) <- anaEventSet es return (pComms `Set.union` hidComms , FQProcess (Hiding pFQTerm fqEs r) (pComms `Set.union` hidComms) r) RenamingProcess p renaming r -> do addDiags [mkDiag Debug "Renaming" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (renAlpha, fqRenaming) <- anaRenaming renaming let newAlpha = pComms `Set.union` renAlpha fqProc = FQProcess (RenamingProcess pFQTerm fqRenaming r) (pComms `Set.union` renAlpha) r return (newAlpha, fqProc) ConditionalProcess f p q r -> do addDiags [mkDiag Debug "Conditional" proc] (pComms, pFQTerm) <- anaProcTerm mix p gVars lVars (qComms, qFQTerm) <- anaProcTerm mix q gVars lVars -- mfs is the fully qualified formula version of f mfs <- anaFormulaCspCASL mix (gVars `Map.union` lVars) f let fFQ = fromMaybe f mfs fComms = maybe Set.empty formulaComms mfs newAlpha = Set.unions [pComms, qComms, fComms] fqProc = FQProcess (ConditionalProcess fFQ pFQTerm qFQTerm r) newAlpha r return (newAlpha, fqProc) FQProcess _ _ _ -> error "CspCASL.StatAnaCSP.anaProcTerm: Unexpected FQProcess" {- | Statically analyse a CspCASL "named process" term. Return the permitted alphabet of the process and also a list of the fully qualified version of the inputted terms. BUG !!! the FQ_PROCESS_NAME may actually need to be a simple process name -} anaNamedProc :: Mix b s () () -> PROCESS -> FQ_PROCESS_NAME -> [TERM ()] -> ProcVarMap -> State CspCASLSign (FQ_PROCESS_NAME, CommAlpha, [TERM ()]) anaNamedProc mix proc pn terms procVars = do maybeFqPn <- anaProcName pn (length terms) case maybeFqPn of Nothing -> {- Return the empty alphabet and the original terms. There is an error in the spec. -} return (pn, Set.empty, terms) Just fqPn -> case fqPn of PROCESS_NAME _ -> error "CspCasl.StatAnaCSP.anaNamedProc: Impossible case" FQ_PROCESS_NAME _ (ProcProfile argSorts permAlpha) -> if length terms == length argSorts then do fqTerms <- mapM (anaNamedProcTerm mix procVars) (zip terms argSorts) {- Return the permitted alphabet of the process and the fully qualifed terms -} return (fqPn, permAlpha, fqTerms) else do let err = "Wrong number of arguments in named process" addDiags [mkDiag Error err proc] {- Return the empty alphabet and the original terms. There is an error in the spec. -} return (pn, Set.empty, terms) {- | Statically analysis a CASL term occurring in a CspCASL "named process" term. -} anaNamedProcTerm :: Mix b s () () -> ProcVarMap -> (TERM (), SORT) -> State CspCASLSign (TERM ()) anaNamedProcTerm mix pm (t, expSort) = do mt <- anaTermCspCASL mix pm t sig <- get case mt of Nothing -> return t {- CASL term analysis failed. Use old term as the fully qualified term, there is a error in the spec anyway. -} Just at -> do let Result ds at' = ccTermCast at expSort sig -- attempt cast; addDiags ds case at' of Nothing -> {- Use old term as the fully qualified term, there is a error in the spec anyway. -} return t Just at'' -> return at'' {- Use the fully qualified (possibly cast) term -} -- Static analysis of event sets and communication types {- | Statically analyse a CspCASL event set. Returns the alphabet of the event set and a fully qualified version of the event set. -} anaEventSet :: EVENT_SET -> State CspCASLSign (CommAlpha, EVENT_SET) anaEventSet eventSet = case eventSet of EventSet es r -> do sig <- get -- fqEsElems is built the reversed order for efficiency. (comms, fqEsElems) <- foldM (anaCommType sig) (Set.empty, []) es vds <- gets envDiags put sig { envDiags = vds } -- reverse the list inside the event set return (comms, EventSet (reverse fqEsElems) r) {- | Statically analyse a proc alphabet (i.e., a list of channel and sort identifiers) to yeild a list of sorts and typed channel names. We also check the parameter sorts and actually construct a process profile. -} anaProcAlphabet :: PROC_ARGS -> PROC_ALPHABET -> State CspCASLSign ProcProfile anaProcAlphabet argSorts (ProcAlphabet commTypes) = do sig <- get checkSorts argSorts {- check argument sorts are known build alphabet: set of CommType values. We do not need the fully qualfied commTypes that are returned (these area used for analysing Event Sets) -} (alpha, _ ) <- foldM (anaCommType sig) (Set.empty, []) commTypes let profile = reduceProcProfile (sortRel sig) (ProcProfile argSorts alpha) return profile {- | Statically analyse a CspCASL communication type. Returns the extended alphabet and the extended list of fully qualified event set elements - [CommType]. -} anaCommType :: CspCASLSign -> (CommAlpha, [CommType]) -> CommType -> State CspCASLSign (CommAlpha, [CommType]) anaCommType sig (alpha, fqEsElems) ct = let res = return (Set.insert ct alpha, ct : fqEsElems) old = return (alpha, fqEsElems) getChSrts ch = Set.toList $ MapSet.lookup ch $ chans $ extendedInfo sig chRes ch rs = let tcs = map (CommTypeChan . TypedChanName ch) rs in return (Set.union alpha $ Set.fromList tcs, tcs ++ fqEsElems) in case ct of CommTypeSort sid -> if Set.member sid (sortSet sig) then res else case getChSrts sid of [] -> do addDiags [mkDiag Error "unknown sort or channel" sid] old cs -> chRes sid cs CommTypeChan (TypedChanName ch sid) -> if Set.member sid (sortSet sig) then case getChSrts ch of [] -> do addDiags [mkDiag Error "unknown channel" ch] old ts -> case filter (\ s -> s == sid || Set.member sid (subsortsOf s sig) || Set.member s (subsortsOf sid sig)) ts of [] -> do let mess = "found no suitably sort '" ++ shows sid "' for channel" addDiags [mkDiag Error mess ch] old rs -> chRes ch rs else do let mess = "unknow sort '" ++ shows sid "' for channel" addDiags [mkDiag Error mess ch] old -- Static analysis of events {- | Statically analyse a CspCASL event. Returns a constituent communication alphabet of the event, mapping for any new locally bound variables and a fully qualified version of the event. -} anaEvent :: Mix b s () () -> EVENT -> ProcVarMap -> State CspCASLSign (CommAlpha, ProcVarMap, EVENT) anaEvent mix e vars = case e of TermEvent t range -> do addDiags [mkDiag Debug "Term event" e] (alpha, newVars, fqTerm) <- anaTermEvent mix t vars let fqEvent = FQTermEvent fqTerm range return (alpha, newVars, fqEvent) InternalPrefixChoice v s range -> do addDiags [mkDiag Debug "Internal prefix event" e] (alpha, newVars, fqVar) <- anaPrefixChoice v s let fqEvent = FQInternalPrefixChoice fqVar range return (alpha, newVars, fqEvent) ExternalPrefixChoice v s range -> do addDiags [mkDiag Debug "External prefix event" e] (alpha, newVars, fqVar) <- anaPrefixChoice v s let fqEvent = FQExternalPrefixChoice fqVar range return (alpha, newVars, fqEvent) ChanSend c t range -> do addDiags [mkDiag Debug "Channel send event" e] {- mfqChan is a maybe fully qualified channel. It will be Nothing if annChanSend failed - i.e. we forget about the channel. -} (alpha, newVars, mfqChan, fqTerm) <- anaChanSend mix c t vars let fqEvent = FQChanSend mfqChan fqTerm range return (alpha, newVars, fqEvent) ChanNonDetSend c v s range -> do addDiags [mkDiag Debug "Channel nondeterministic send event" e] {- mfqChan is the same as in chanSend case. fqVar is the fully qualfied version of the variable. -} (alpha, newVars, mfqChan, fqVar) <- anaChanBinding c v s let fqEvent = FQChanNonDetSend mfqChan fqVar range return (alpha, newVars, fqEvent) ChanRecv c v s range -> do addDiags [mkDiag Debug "Channel receive event" e] {- mfqChan is the same as in chanSend case. fqVar is the fully qualfied version of the variable. -} (alpha, newVars, mfqChan, fqVar) <- anaChanBinding c v s let fqEvent = FQChanRecv mfqChan fqVar range return (alpha, newVars, fqEvent) _ -> error "CspCASL.StatAnaCSP.anaEvent: Unexpected Fully qualified event" {- | Statically analyse a CspCASL term event. Returns a constituent communication alphabet of the event and a mapping for any new locally bound variables and the fully qualified version of the term. -} anaTermEvent :: Mix b s () () -> TERM () -> ProcVarMap -> State CspCASLSign (CommAlpha, ProcVarMap, TERM ()) anaTermEvent mix t vars = do mt <- anaTermCspCASL mix vars t let (alpha, t') = case mt of -- return the alphabet and the fully qualified term Just at -> ([CommTypeSort (sortOfTerm at)], at) -- return the empty alphabet and the original term Nothing -> ([], t) return (Set.fromList alpha, Map.empty, t') {- | Statically analyse a CspCASL internal or external prefix choice event. Returns a constituent communication alphabet of the event and a mapping for any new locally bound variables and the fully qualified version of the variable. -} anaPrefixChoice :: VAR -> SORT -> State CspCASLSign (CommAlpha, ProcVarMap, TERM ()) anaPrefixChoice v s = do checkSorts [s] -- check sort is known let alpha = Set.singleton $ CommTypeSort s let binding = Map.singleton v s let fqVar = Qual_var v s nullRange return (alpha, binding, fqVar) {- | Statically analyse a CspCASL channel send event. Returns a constituent communication alphabet of the event, a mapping for any new locally bound variables, a fully qualified channel (if possible) and the fully qualified version of the term. -} anaChanSend :: Mix b s () () -> CHANNEL_NAME -> TERM () -> ProcVarMap -> State CspCASLSign (CommAlpha, ProcVarMap, (CHANNEL_NAME, SORT), TERM ()) anaChanSend mix c t vars = do sig <- get let ext = extendedInfo sig msg = "CspCASL.StatAnaCSP.anaChanSend: Channel Error" case Set.toList $ MapSet.lookup c $ chans ext of [] -> do addDiags [mkDiag Error "unknown channel" c] {- Use old term as the fully qualified term and forget about the channel, there is an error in the spec -} return (Set.empty, Map.empty, error msg, t) chanSorts -> do mt <- anaTermCspCASL mix vars t case mt of Nothing -> {- CASL analysis failed. Use old term as the fully qualified term and forget about the channel, there is an error in the spec. -} return (Set.empty, Map.empty, error msg, t) Just at -> do let rs = map (\ s -> ccTermCast at s sig) chanSorts addDiags $ concatMap diags rs case filter (isJust . maybeResult . fst) $ zip rs chanSorts of [] -> {- cast failed. Use old term as the fully qualified term, and forget about the channel there is an error in the spec. -} return (Set.empty, Map.empty, error msg, t) [(_, castSort)] -> let alpha = [ CommTypeSort castSort , CommTypeChan $ TypedChanName c castSort] {- Use the real fully qualified term. We do not want to use a cast term here. A cast must be possible, but we do not want to force it! -} in return (Set.fromList alpha, Map.empty, (c, castSort), at) cts -> do -- fail due to an ambiguous chan sort addDiags [mkDiag Error ("ambiguous channel sorts " ++ show (map snd cts)) t] {- Use old term as the fully qualified term and forget about the channel, there is an error in the spec. -} return (Set.empty, Map.empty, error msg, t) getDeclaredChanSort :: (CHANNEL_NAME, SORT) -> CspCASLSign -> Result SORT getDeclaredChanSort (c, s) sig = let cm = chans $ extendedInfo sig in case Set.toList $ MapSet.lookup c cm of [] -> mkError "unknown channel" c css -> case filter (\ cs -> cs == s || Set.member s (subsortsOf cs sig)) css of [] -> mkError "sort not a subsort of channel's sort" s [cs] -> return cs fcs -> mkError ("ambiguous channel sorts " ++ show fcs) s {- | Statically analyse a CspCASL "binding" channel event (which is either a channel nondeterministic send event or a channel receive event). Returns a constituent communication alphabet of the event, a mapping for any new locally bound variables, a fully qualified channel and the fully qualified version of the variable. -} anaChanBinding :: CHANNEL_NAME -> VAR -> SORT -> State CspCASLSign (CommAlpha, ProcVarMap, (CHANNEL_NAME, SORT), TERM ()) anaChanBinding c v s = do checkSorts [s] -- check sort is known sig <- get let qv = Qual_var v s nullRange fqChan = (c, s) Result ds ms = getDeclaredChanSort fqChan sig addDiags ds case ms of Nothing -> return (Set.empty, Map.empty, fqChan, qv) Just _ -> let alpha = [CommTypeSort s, CommTypeChan (TypedChanName c s)] binding = [(v, s)] {- Return the alphabet, var mapping, the fully qualfied channel and fully qualfied variable. Notice that the fully qualified channel's sort should be the lowest sort we can communicate in i.e. the sort of the variable. -} in return (Set.fromList alpha, Map.fromList binding, fqChan, qv) -- Static analysis of renaming and renaming items {- | Statically analyse a CspCASL renaming. Returns the alphabet and the fully qualified renaming. -} anaRenaming :: RENAMING -> State CspCASLSign (CommAlpha, RENAMING) anaRenaming renaming = case renaming of Renaming r -> do fqRenamingTerms <- mapM anaRenamingItem r let rs = concat fqRenamingTerms return ( Set.map CommTypeSort $ Set.unions $ map alphaOfRename rs , Renaming rs) alphaOfRename :: Rename -> Set.Set SORT alphaOfRename (Rename _ cm) = case cm of Just (_, Just (s1, s2)) -> Set.fromList [s1, s2] _ -> Set.empty {- | Statically analyse a CspCASL renaming item. Return the alphabet and the fully qualified list of renaming functions and predicates. -} anaRenamingItem :: Rename -> State CspCASLSign [Rename] anaRenamingItem r@(Rename ri cm) = let predToRen p = Rename ri $ Just (BinPred, Just p) opToRen (o, p) = Rename ri $ Just (if o == Total then TotOp else PartOp, Just p) in case cm of Just (k, ms) -> case k of BinPred -> do ps <- getBinPredsById ri let realPs = case ms of Nothing -> ps Just p -> filter (== p) ps when (null realPs) $ addDiags [mkDiag Error "renaming predicate not found" r] unless (isSingle realPs) $ addDiags [mkDiag Warning "multiple predicates found" r] return $ map predToRen realPs _ -> do os <- getUnaryOpsById ri -- we ignore the user given op kind here! let realOs = case ms of Nothing -> os Just p -> filter ((== p) . snd) os when (null realOs) $ addDiags [mkDiag Error "renaming operation not found" r] unless (isSingle realOs) $ addDiags [mkDiag Warning "multiple operations found" r] when (k == TotOp) $ mapM_ (\ (o, (s1, s2)) -> when (o == Partial) $ addDiags [mkDiag Error ("operation of type '" ++ shows s1 " -> " ++ shows s2 "' is not total") r]) realOs return $ map opToRen realOs Nothing -> do ps <- getBinPredsById ri os <- getUnaryOpsById ri let rs = map predToRen ps ++ map opToRen os when (null rs) $ addDiags [mkDiag Error "renaming predicate or operation not found" ri] unless (isSingle rs) $ addDiags [mkDiag Warning "multiple renamings found" ri] return rs {- | Given a CASL identifier, find all unary operations with that name in the CASL signature, and return a list of corresponding profiles, i.e. kind, argument sort and result sort. -} getUnaryOpsById :: Id -> State CspCASLSign [(OpKind, (SORT, SORT))] getUnaryOpsById ri = do om <- gets opMap return $ Set.fold (\ oty -> case oty of OpType k [s1] s2 -> ((k, (s1, s2)) :) _ -> id) [] $ MapSet.lookup ri om {- | Given a CASL identifier find all binary predicates with that name in the CASL signature, and return a list of corresponding profiles. -} getBinPredsById :: Id -> State CspCASLSign [(SORT, SORT)] getBinPredsById ri = do pm <- gets predMap return $ Set.fold (\ pty -> case pty of PredType [s1, s2] -> ((s1, s2) :) _ -> id) [] $ MapSet.lookup ri pm {- | Given two CspCASL communication alphabets, check that the first's subsort closure is a subset of the second's subsort closure. -} checkCommAlphaSub :: CommAlpha -> CommAlpha -> PROCESS -> String -> State CspCASLSign () checkCommAlphaSub sub super proc context = do sr <- gets sortRel let extras = closeCspCommAlpha sr sub `Set.difference` closeCspCommAlpha sr super unless (Set.null extras) $ let err = "Communication alphabet subset violations (" ++ context ++ ")" ++ show (printCommAlpha extras) in addDiags [mkDiag Error err proc] -- Static analysis of CASL terms occurring in CspCASL process terms. {- | Statically analyse a CASL term appearing in a CspCASL process; any in-scope process variables are added to the signature before performing the analysis. -} anaTermCspCASL :: Mix b s () () -> ProcVarMap -> TERM () -> State CspCASLSign (Maybe (TERM ())) anaTermCspCASL mix pm t = do sig <- get let newVars = Map.union pm (varMap sig) sigext = sig { varMap = newVars } Result ds mt = anaTermCspCASL' mix sigext t addDiags ds return mt idSetOfSig :: CspCASLSign -> IdSets idSetOfSig sig = unite [mkIdSets (allConstIds sig) (allOpIds sig) $ allPredIds sig] {- | Statically analyse a CASL term in the context of a CspCASL signature. If successful, returns a fully-qualified term. -} anaTermCspCASL' :: Mix b s () () -> CspCASLSign -> TERM () -> Result (TERM ()) anaTermCspCASL' mix sig trm = fmap snd $ anaTerm (const return) mix (ccSig2CASLSign sig) Nothing (getRange trm) trm -- | Attempt to cast a CASL term to a particular CASL sort. ccTermCast :: TERM () -> SORT -> CspCASLSign -> Result (TERM ()) ccTermCast t cSort sig = let pos = getRange t msg = (++ "cast term to sort " ++ show cSort) in case optTermSort t of Nothing -> mkError "term without type" t Just termSort | termSort == cSort -> return t | Set.member termSort $ subsortsOf cSort sig -> hint (Sorted_term t cSort pos) (msg "up") pos | Set.member termSort $ supersortsOf cSort sig -> hint (Cast t cSort pos) (msg "down") pos | otherwise -> fatal_error (msg "cannot ") pos {- Static analysis of CASL formulae occurring in CspCASL process terms. -} {- | Statically analyse a CASL formula appearing in a CspCASL process; any in-scope process variables are added to the signature before performing the analysis. -} anaFormulaCspCASL :: Mix b s () () -> ProcVarMap -> FORMULA () -> State CspCASLSign (Maybe (FORMULA ())) anaFormulaCspCASL mix pm f = do addDiags [mkDiag Debug "anaFormulaCspCASL" f] sig <- get let newVars = Map.union pm (varMap sig) sigext = sig { varMap = newVars } Result ds mt = anaFormulaCspCASL' mix sigext f addDiags ds return mt {- | Statically analyse a CASL formula in the context of a CspCASL signature. If successful, returns a fully-qualified formula. -} anaFormulaCspCASL' :: Mix b s () () -> CspCASLSign -> FORMULA () -> Result (FORMULA ()) anaFormulaCspCASL' mix sig = fmap snd . anaForm (const return) mix (ccSig2CASLSign sig) {- | Compute the communication alphabet arising from a formula occurring in a CspCASL process term. -} formulaComms :: FORMULA () -> CommAlpha formulaComms = Set.map CommTypeSort . foldFormula (constRecord (const Set.empty) Set.unions Set.empty) { foldQuantification = \ _ _ varDecls f _ -> let vdSort (Var_decl _ s _) = s in Set.union f $ Set.fromList (map vdSort varDecls) , foldQual_var = \ _ _ s _ -> Set.singleton s , foldApplication = \ _ o _ _ -> case o of Op_name _ -> Set.empty Qual_op_name _ ty _ -> Set.singleton $ res_OP_TYPE ty , foldSorted_term = \ _ _ s _ -> Set.singleton s , foldCast = \ _ _ s _ -> Set.singleton s }
nevrenato/Hets_Fork
CspCASL/StatAnaCSP.hs
gpl-2.0
37,319
0
29
10,760
9,234
4,551
4,683
619
18
module Yi.Char.Unicode (greek, symbols, subscripts, superscripts, checkAmbs, disamb) where import Data.List (isPrefixOf) import Control.Applicative {-# ANN module "HLint: ignore Use string literal" #-} greek :: [(String, String)] greek = [(name, unicode) | (_,name,unicode) <- greekData] ++ [ ([leading,shorthand],unicode) | (Just shorthand,_,unicode) <- greekData , leading <- ['\'', 'g'] ] -- | Triples: (shorthand, name, unicode) greekData :: [(Maybe Char, String, String)] greekData = [(Just 'a', "alpha", "α") ,(Just 'b', "beta", "β") ,(Just 'g', "gamma", "γ") ,(Just 'G', "Gamma", "Γ") ,(Just 'd', "delta", "δ") ,(Just 'D', "Delta", "Δ") ,(Just 'e' , "epsilon", "ε") ,(Just 'z', "zeta", "ζ") ,(Just 'N' , "eta", "η") -- N is close to n which is graphically close ,(Just 'E' , "eta", "η") -- E is close to e which is the start of eta ,(Nothing , "theta", "θ") ,(Nothing , "Theta", "Θ") ,(Just 'i', "iota", "ι") ,(Just 'k', "kapa", "κ") ,(Just 'l', "lambda", "λ") ,(Just 'L', "Lambda", "Λ") ,(Just 'm', "mu", "μ") ,(Just 'n', "nu", "ν") ,(Just 'x', "xi", "ξ") ,(Just 'o', "omicron", "ο") ,(Just 'p' , "pi", "π") ,(Just 'P' , "Pi", "Π") ,(Just 'r', "rho", "ρ") ,(Just 's', "sigma", "σ") ,(Just 'S', "Sigma", "Σ") ,(Just 't', "tau", "τ") ,(Just 'f' , "phi", "φ") ,(Just 'F' , "Phi", "Φ") ,(Just 'c', "chi", "χ") ,(Just 'C', "Chi", "Χ") ,(Nothing , "psi", "ψ") ,(Nothing , "Psi", "Ψ") ,(Just 'w', "omega", "ω") ,(Just 'O', "Omega", "Ω") ] symbols :: [(String, String)] symbols = [ -- parens ("<","⟨") ,(">","⟩") ,("<>","⟨⟩") ,(">>","⟫") ,("<<","⟪") -- These two confuse gnome-terminal. ,("|(","〖") ,(")|","〗") ,("{|", "⦃") ,("|}", "⦄") ,("[[","⟦") ,("]]","⟧") ,("|_","⌊") ,("_|","⌋") ,("|__|","⌊⌋") ,("r|_","⌈") ,("r_|","⌉") ,("r|__|","⌈⌉") ,("[]", "∎") -- quantifiers ,("forall", "∀") ,("all", "∀") ,("exists", "∃") ,("rA", "∀") -- reversed A ,("rE", "∃") -- reversed E ,("/rE", "∄") -- operators ,("<|","◃") -- ,("<|","◁") alternative ,("|>","▹") ,("><","⋈") ,("<)", "◅") ,("(>", "▻") ,("v","∨") ,("u","∪") ,("V","⋁") ,("+u","⊎") ,("u[]","⊔") ,("n[]","⊓") ,("^","∧") ,("/\\", "∧") ,("\\/", "∨") ,("o","∘") ,(".","·") ,("x","×") ,("neg","¬") --- arrows ,("<-","←") ,("->","→") ,("|->","↦") ,("<-|","↤") ,("<--","⟵") ,("-->","⟶") ,("|-->","⟼") ,("==>","⟹") ,("=>","⇒") ,("<=","⇐") ,("<=>","⇔") ,("~>","↝") ,("<~","↜") ,("<-<", "↢") ,(">->", "↣") ,("<->", "↔") ,("|<-", "⇤") ,("->|", "⇥") ,(">>=","↠") --- relations ,("c=","⊆") ,("c","⊂") ,("c-","∈") ,("in","∈") ,("/c-","∉") ,("c/=","⊊") ,("rc=","⊇") -- r for reversed ,("rc","⊃") -- r for reversed ,("rc-","∋") -- r for reversed ,("r/c-","∌") -- r for reversed ,("rc/=","⊋") -- r for reversed ,(">=","≥") ,("=<","≤") ,("c[]","⊏") ,("rc[]","⊐") ,("c[]=","⊑") ,("rc[]=","⊒") ,("/c[]=","⋢") ,("/rc[]=","⋣") ,("c[]/=","⋤") ,("rc[]/=","⋥") ---- equal signs ,("=def","≝") ,("=?","≟") ,("==","≡") ,("~~","≈") ,("~-","≃") ,("~=","≅") ,("~","∼") ,("~~","≈") ,("/=","≠") ,("/==","≢") ,(":=","≔") ,("=:","≕") -- misc ,("_|_","⊥") ,("Top","⊤") ,("l","ℓ") ,("::","∷") ,(":", "∶") ,("0", "∅") ,("*", "★") -- or "⋆" ,("/'l","ƛ") ,("d","∂") ,("#b","♭") -- music bemol ,("#f","♮") -- music flat ,("##","♯") -- music # ,("Hot","♨") ,("Cut","✂") ,("Pen","✎") ,("Tick","✓") -- dashes ,("-","−") -- quotes ,("\"","“”") ,("r`","′") -- turnstyles ,("|-", "⊢") ,("|/-", "⊬") ,("-|", "⊣") ,("|=", "⊨") ,("|/=", "⊭") ,("||-", "⊩") -- circled/squared operators -- ⊝ ⍟ ⎊ ⎉ ,("o+","⊕") ,("o-","⊖") ,("ox","⊗") ,("o/","⊘") ,("o*","⊛") ,("o=","⊜") ,("o.","⊙") ,("oo","⊚") ,("[+]","⊞") ,("[-]","⊟") ,("[x]","⊠") ,("[.]","⊡") ,("[]","∎") ] ++ [ (leading:l, [u]) | leading <- ['|','b'], (l,u) <- [("N",'ℕ') ,("H",'ℍ') ,("P",'ℙ') ,("R",'ℝ') ,("D",'ⅅ') ,("Q",'ℚ') ,("Z",'ℤ') ,("gg",'ℽ') ,("gG",'ℾ') ,("gP",'ℿ') ,("gS",'⅀') ] ] ++ [ ("cP","℘") -- c for cal ,("cL","ℒ") -- c for cal ,("cR","ℛ") -- c for cal ] checkAmbs :: [(String, String)] -> [(String, String)] checkAmbs table = check where ambs = [ (x, y) | v@(x, _) <- table , w@(y, _) <- table , v /= w , x `isPrefixOf` y ] check | null ambs = table | otherwise = error $ "checkAmbs: ambiguous declarations for " ++ show ambs disamb :: [(String, String)] -> [(String, String)] disamb table = map f table where f v@(x, vx) = let ambs = [ w | w@(y, _) <- table , v /= w , x `isPrefixOf` y ] in if null ambs then v else (x ++ " ", vx) -- More: -- arrows: ⇸ ⇆ -- circled operators: ⊕ ⊖ ⊗ ⊘ ⊙ ⊚ ⊛ ⊜ ⊝ ⍟ ⎊ ⎉ -- squared operators: ⊞ ⊟ ⊠ ⊡ -- turnstyles: ⊦ ⊧ -- subscript: ₔ zipscripts :: Char -> String -> String -> [(String, String)] zipscripts c ascii unicode = zip (fmap ((c:) . pure) ascii) (fmap pure unicode) subscripts, superscripts :: [(String, String)] subscripts = zipscripts '_' "0123456789+-=()aeioruvx" "₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎ₐₑᵢₒᵣᵤᵥₓ" superscripts = zipscripts '^' -- NOTE that qCFQSVXYZ are missing "0123456789+-=()abcdefghijklmnoprstuvwxyzABDEGHIJKLMNOPRTUW" "⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖʳˢᵗᵘᵛʷˣʸᶻᴬᴮᴰᴱᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾᴿᵀᵁᵂ"
atsukotakahashi/wi
src/library/Yi/Char/Unicode.hs
gpl-2.0
6,311
61
10
1,582
2,179
1,499
680
221
2
module Couple where import Data.Char import Test.QuickCheck import Test.QuickCheck.All -- unique couple (a,b) such that a*b = n -- As the multiplication is commutative, we consider (a,b) == (b,a) isqrt :: Int -> Int isqrt = floor . sqrt . fromIntegral couple :: Int -> [(Int, Int)] couple n = [(a,b) | a <- [1..isqrt n], b <- [a..n], a * b == n] coupleSimple :: Int -> [(Int, Int)] coupleSimple n = [(a,b) | a <- [1..n], b <- [a..n], a * b == n] -- *Couple> couple 10 -- [(1,10),(2,5)] -- *Couple> couple 12 -- [(1,12),(2,6),(3,4)] -- *Couple> couple 24 -- [(1,24),(2,12),(3,8),(4,6)] -- *Couple> couple 100 -- [(1,100),(2,50),(4,25),(5,20),(10,10)] -- *Couple> couple 1000 -- [(1,1000),(2,500),(4,250),(5,200),(8,125),(10,100),(20,50),(25,40)] -- *Couple> couple 1000 -- [(1,1000),(2,500),(4,250),(5,200),(8,125),(10,100),(20,50),(25,40)] -- *Couple> couple 10000 -- [(1,10000),(2,5000),(4,2500),(5,2000),(8,1250),(10,1000),(16,625),(20,500),(25,400),(40,250),(50,200),(80,125),(100,100)] rg :: Int -> Int -> [a] -> [a] rg inf sup s = take sup $ drop inf s rgc :: Int -> Int -> [(Int, Int, [(Int, Int)])] rgc inf sup = rg inf sup [(n, isqrt n, couple n) | n <- [1..]] -- *Couple> quickCheck (\ x -> all (\ (a,b) -> b <= a) (couple x)) -- C-c C-c*** Failed! Exception: 'user interrupt' (after 27 tests): -- 47540 -- took too long -- test -- property: all a is superior or equal to b -- checkOnly10 p = Q.check (Q.defaultConfig { configMaxTest = 10}) p -- verboseCheck (\ n -> all (\ (a,b) -> ( ((a == b) || (a, b) /= (b, a)) && b <= a && a * b == n) ) (couple n)) -- define the properties to check prop_productOk = (\ n -> all (\ (a,b) -> a * b == n ) (couple n)) prop_coupleIdempotence = (\ x y -> couple x == couple y) prop_coupleInfSqrt = (\ n -> all (\ (a,b) -> a <= isqrt n ) (couple n)) prop_coupleVsCoupleSimple = (\ n -> (couple n) == (coupleSimple n)) -- adding main = do verboseCheckWith stdArgs { maxSuccess = 1000, maxSize = 5 } prop_productOk verboseCheckWith stdArgs { maxSuccess = 1000, maxSize = 5 } prop_coupleIdempotence verboseCheckWith stdArgs { maxSuccess = 1000, maxSize = 5 } prop_coupleInfSqrt verboseCheckWith stdArgs { maxSuccess = 1000, maxSize = 5 } prop_coupleVsCoupleSimple
ardumont/haskell-lab
src/couple.hs
gpl-2.0
2,225
0
11
390
582
334
248
23
1
{-# LANGUAGE DeriveDataTypeable #-} -- Copyright (C) 2008 JP Bernardy -- | This module defines buffer operation on regions module Yi.Buffer.Region ( module Yi.Region , swapRegionsB , deleteRegionB , replaceRegionB , replaceRegionClever , readRegionB , mapRegionB , modifyRegionB , modifyRegionClever , winRegionB , inclusiveRegionB , blockifyRegion ) where import Data.Algorithm.Diff import Yi.Region import Yi.Buffer.Misc import Yi.Prelude import Prelude () import Data.List (length, sort) import Yi.Window (winRegion) winRegionB :: BufferM Region winRegionB = askWindow winRegion -- | Delete an arbitrary part of the buffer deleteRegionB :: Region -> BufferM () deleteRegionB r = deleteNAt (regionDirection r) (fromIntegral (regionEnd r ~- regionStart r)) (regionStart r) -- | Read an arbitrary part of the buffer readRegionB :: Region -> BufferM String readRegionB r = nelemsB (fromIntegral (regionEnd r - i)) i where i = regionStart r -- | Replace a region with a given string. replaceRegionB :: Region -> String -> BufferM () replaceRegionB r s = do deleteRegionB r insertNAt s (regionStart r) -- | As 'replaceRegionB', but do a minimal edition instead of deleting the whole -- region and inserting it back. replaceRegionClever :: Region -> String -> BufferM () replaceRegionClever region text' = savingExcursionB $ do text <- readRegionB region let diffs = getGroupedDiff text text' moveTo (regionStart region) forM_ diffs $ \(d,str) -> do case d of F -> deleteN $ length str B -> rightN $ length str S -> insertN str mapRegionB :: Region -> (Char -> Char) -> BufferM () mapRegionB r f = do text <- readRegionB r replaceRegionB r (fmap f text) -- | Swap the content of two Regions swapRegionsB :: Region -> Region -> BufferM () swapRegionsB r r' | regionStart r > regionStart r' = swapRegionsB r' r | otherwise = do w0 <- readRegionB r w1 <- readRegionB r' replaceRegionB r' w0 replaceRegionB r w1 -- Transform a replace into a modify. replToMod :: (Region -> a -> BufferM b) -> (String -> a) -> Region -> BufferM b replToMod replace transform region = replace region =<< transform <$> readRegionB region -- | Modifies the given region according to the given -- string transformation function modifyRegionB :: (String -> String) -- ^ The string modification function -> Region -- ^ The region to modify -> BufferM () modifyRegionB = replToMod replaceRegionB -- | As 'modifyRegionB', but do a minimal edition instead of deleting the whole -- region and inserting it back. modifyRegionClever :: (String -> String) -> Region -> BufferM () modifyRegionClever = replToMod replaceRegionClever -- | Extend the right bound of a region to include it. inclusiveRegionB :: Region -> BufferM Region inclusiveRegionB r = if regionStart r <= regionEnd r then mkRegion (regionStart r) <$> pointAfter (regionEnd r) else mkRegion <$> pointAfter (regionStart r) <*> pure (regionEnd r) where pointAfter p = pointAt $ do moveTo p rightB -- | See a region as a block/rectangular region, -- since regions are represented by two point, this returns -- a list of small regions form this block region. blockifyRegion :: Region -> BufferM [Region] blockifyRegion r = savingPointB $ do [lowCol,highCol] <- sort <$> mapM colOf [regionStart r, regionEnd r] startLine <- lineOf $ regionStart r endLine <- lineOf $ regionEnd r when (startLine > endLine) $ fail "blockifyRegion: impossible" mapM (\line -> mkRegion <$> pointOfLineColB line lowCol <*> pointOfLineColB line (1 + highCol)) [startLine..endLine]
codemac/yi-editor
src/Yi/Buffer/Region.hs
gpl-2.0
3,857
0
16
931
977
491
486
78
3
{-# LANGUAGE CPP #-} module BPackReader (parseImageFile, parseMapFile, ParsedImage, gliphs, palette, gliphSize, PaletteEntry, Gliph, gliphData, gliphWidth, gliphHeight, gliphDepth, blankGliph, red, green, blue, ParsedTileMap, tileMap, tilesHigh, tilesAcross) where import Text.ParserCombinators.Parsec import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as L8 import qualified Data.ByteString.Internal as LI import qualified Data.Word as DW import Data.List import Data.Bits import Data.Maybe import qualified GHC.Word as W import Control.Exception (bracket, handle) import Control.Monad import System.IO import Text.Printf import Debug.Trace -- For Level Maps #define LEVELMAP_OFFSET_BYTES 130 -- For Tile Sets #define BITMAP_OFFSET_BYTES 54 #define TILE_DIMENSION_PIXELS 16 #define TILE_BITPLANE_BYTES (TILE_DIMENSION_PIXELS * TILE_DIMENSION_PIXELS `div` 8) #define BITPLANES 4 #define TILE_DATA_BYTES (TILE_BITPLANE_BYTES * BITPLANES) #define IMAGE_HEIGHT_TILES 63 #define IMAGE_WIDTH_TILES 21 data BPackedFile = BPF { bit8Marker :: W.Word8, bit16Marker :: W.Word8, size :: Integer, fileData :: L.ByteString } data FileType = CompressedFile | UncompressedFile data UnpackedFile = UPF { rawFileData :: L.ByteString } data Gliph = GL { gliphData :: L.ByteString, gliphWidth :: Int, gliphHeight :: Int, gliphDepth :: Int } data PaletteEntry = PE { red :: Integer, green :: Integer, blue :: Integer, index :: Integer } deriving (Show) data ParsedImage = PI { gliphs :: [Gliph], palette :: [PaletteEntry], gliphSize :: Int } data ParsedTileMap = PTM { tileMap :: [W.Word8], tilesAcross :: Int, tilesHigh :: Int } instance Show Gliph where show g = "Gliph:\n"++(dumpImage (gliphData g) 0) instance Show ParsedTileMap where show tm = "Parsed Tile map has " ++ show (length $ tileMap tm) ++ " tiles in the map" instance Show ParsedImage where show im = "Parsed Image has " ++ show (length $ gliphs im) ++ " shapes and " ++ show (length $ palette im) ++ " colours." instance Show BPackedFile where show im = "Packed image, compressed size: " ++ show (L.length $ fileData im) ++ " (decompressed: " ++ show (size im) ++ ") with markers " ++ show (bit8Marker im) ++ " and " ++ show (bit16Marker im) instance Show UnpackedFile where show im = "Unpacked image, size: " ++ show (L.length $ rawFileData im) matchHeader :: L.ByteString -> Maybe L.ByteString matchHeader fileData = do (head, tail) <- getBytes 4 fileData if (head == L8.pack("BPCK")) then return tail else (fail "failed") getBytes :: Int -> L.ByteString -> Maybe (L.ByteString, L.ByteString) getBytes n str = let count = fromIntegral n both@(prefix,_) = L.splitAt count str in if L.length prefix < count then Nothing else Just both getByte :: L.ByteString -> Maybe (W.Word8, L.ByteString) getByte = L.uncons skipBytes :: Int -> L.ByteString -> Maybe L.ByteString skipBytes n str = do if L.length prefix < count then Nothing else Just tail where count = fromIntegral n (prefix, tail) = L.splitAt count str decompressBytes :: L.ByteString -> W.Word8 -> W.Word8 -> Maybe L.ByteString decompressBytes fileData bit8marker bit16marker = case L.uncons fileData of Just (top, tail) -> if (top == bit8marker) then do (n, rest) <- getByte tail (v, rest) <- getByte rest result <- (decompressBytes rest bit8marker bit16marker) return $ L.append (L.replicate (fromIntegral n) v) result else if (top == bit16marker) then do (n255, rest) <- getByte tail (n, rest) <- getByte rest (v, rest) <- getByte rest result <- decompressBytes rest bit8marker bit16marker return $ L.append (L.replicate ((fromIntegral n255) * 256 + (fromIntegral n)) v) result else do result <- (decompressBytes tail bit8marker bit16marker) return $ L.cons top result Nothing -> Just L.empty unpackAsFile :: BPackedFile -> Maybe UnpackedFile unpackAsFile bpi = do decompressed <- decompressBytes (fileData bpi) (bit8Marker bpi) (bit16Marker bpi) return $ UPF decompressed buildParsedImage :: L.ByteString -> FileType -> Maybe ParsedImage buildParsedImage content filetype = do paletteBytes <- paletteData content let parsedPalette = parsePalette paletteBytes shapes <- case filetype of CompressedFile -> loadCompressedShapes content UncompressedFile -> loadUncompressedShapes content return $ PI shapes parsedPalette TILE_DIMENSION_PIXELS unpackData :: L.ByteString -> Maybe UnpackedFile unpackData fileData = do content <- matchHeader fileData (bit8, content) <- getByte content (bit16, content) <- getByte content content <- skipBytes 4 content (size_255, content) <- getByte content (size, content) <- getByte content unpackAsFile $ BPF bit8 bit16 ((fromIntegral size_255) * 255 + (fromIntegral size)) content parseAsTileMap :: L.ByteString -> FileType -> Maybe ParsedTileMap parseAsTileMap fileData filetype = do tileArray <- loadTileMap fileData return $ PTM tileArray IMAGE_WIDTH_TILES IMAGE_HEIGHT_TILES parseCompressedFile :: Show a => (L.ByteString -> FileType -> Maybe a) -> String -> IO (Maybe a) parseCompressedFile parseFunction fileName = do putStrLn $ "Loading from " ++ fileName handle (\e -> do putStrLn $ "Error loading file: " ++ (show e); return Nothing) $ bracket (openFile fileName ReadMode) hClose $ \h -> do fileData <- L.hGetContents h let unpacked = unpackData fileData let object = case unpacked of Just unpackedFileData -> parseFunction (rawFileData unpackedFileData) CompressedFile Nothing -> parseFunction fileData UncompressedFile case object of Just parsedObject -> putStrLn $ "Loaded: " ++ (show parsedObject) Nothing -> error "Unable to parse file" return object parseImageFile :: String -> IO (Maybe ParsedImage) parseImageFile = parseCompressedFile buildParsedImage parseMapFile :: String -> IO (Maybe ParsedTileMap) parseMapFile = parseCompressedFile parseAsTileMap dumpDecompressed :: String -> IO () dumpDecompressed fileName = do putStrLn $ "Loading from " ++ fileName handle (\e -> do putStrLn $ "Error loading file: " ++ (show e); return ()) $ bracket (openFile fileName ReadMode) hClose $ \h -> do fileData <- L.hGetContents h let image = fromJust $ unpackData fileData putStrLn $ dumpImage (rawFileData image) 0 return () -- Utility function for hexdumping asciiof :: W.Word8 -> String asciiof x = if (x > 20 && x < 127) then [(LI.w2c x)] else "." -- Generates the hex string corresponding to 16 bytes dumpLine :: L.ByteString -> String dumpLine l = dumpRest "" "" l where dumpRest hex ascii l = case (L.uncons l) of Just (head, tail) -> dumpRest (hex ++ (printf "%02X " head)) (ascii ++ (asciiof head)) tail Nothing -> hex ++ ascii -- Hexdumps the image data dumpImage :: L.ByteString -> Int -> String dumpImage imagedata off = printf "%08X " off ++ remainder where remainder = case (getBytes 16 imagedata) of Just (line, rest) -> dumpLine line ++ "\n" ++ dumpImage rest (off + 16) Nothing -> "" -- Reads the palette bytes from the end of the file paletteData :: L.ByteString -> Maybe L.ByteString paletteData imdata = do (header, rest) <- getBytes (fromIntegral $ L.length imdata - 32) imdata (result, tail) <- getBytes 30 rest return result -- Creates a new Palette entry by shifting red, green and blue nibbles from the value provided genColour :: Integer -> Integer -> PaletteEntry genColour value index = PE ((value `shiftR` 8) * 16) (((value .&. 0xF0) `shiftR` 4) * 16) ((value .&. 0x0F) * 16) index -- Takes 30 bytes of palette data, treating each pair of bytes as a short, and generates -- the corresponding palette of 15 colours parsePalette :: L.ByteString -> [PaletteEntry] parsePalette palElements = (map (\(a,b) -> genColour b a) $ zip [1..15] cvalues) ++ [PE 0 0 0 0] where odds = filter (odd . fst) $ map (\(a,b) -> (a, fromIntegral b)) tupList evens = filter (even . fst) $ map (\(a,b) -> (a, (fromIntegral b)*256)) tupList tupList = L.zip (L.pack [0..fromIntegral ((L.length palElements)-1)]) palElements tidy = map snd cvalues = zipWith (+) (tidy odds) (tidy evens) -- Takes the pixel data from four bitplanes to create a tile createGliph :: L.ByteString -> L.ByteString -> L.ByteString -> L.ByteString -> Maybe Gliph createGliph b8 b4 b2 b1 = do bytes <- expandByteStreams b8 b4 b2 b1 return $ GL bytes TILE_DIMENSION_PIXELS TILE_DIMENSION_PIXELS BITPLANES -- Generates an empty Gliph blankGliph :: Gliph blankGliph = let bytecount = TILE_DIMENSION_PIXELS * TILE_DIMENSION_PIXELS in GL (L.replicate bytecount 0) TILE_DIMENSION_PIXELS TILE_DIMENSION_PIXELS BITPLANES -- Takes 4 8-bit words and makes 8 4-bit words expandByte :: W.Word8 -> W.Word8 -> W.Word8 -> W.Word8 -> L.ByteString expandByte b8 b4 b2 b1 = L.pack $ map pixelise [0..7] where pixelise i = (((b8 `shiftR` (7-i)) .&. 1) `shiftL` 3) .|. (((b4 `shiftR` (7-i)) .&. 1) `shiftL` 2) .|. (((b2 `shiftR` (7-i)) .&. 1) `shiftL` 1) .|. ((b1 `shiftR` (7-i) .&. 1)) -- Combines the four incoming bitstreams to create a string of 4-bit words expandByteStreams :: L.ByteString -> L.ByteString -> L.ByteString -> L.ByteString -> Maybe L.ByteString expandByteStreams b8 b4 b2 b1 = do (byte8, b8rest) <- getByte b8 (byte4, b4rest) <- getByte b4 (byte2, b2rest) <- getByte b2 (byte1, b1rest) <- getByte b1 let thisByte = expandByte byte1 byte2 byte4 byte8 case (expandByteStreams b8rest b4rest b2rest b1rest) of Just bs -> Just (thisByte `L.append` bs) Nothing -> Just thisByte -- Gets the number of shapes in an image data block numberOfShapes :: L.ByteString -> Int numberOfShapes imdata = fromIntegral $ ((L.length imdata) - BITMAP_OFFSET_BYTES - TILE_BITPLANE_BYTES) `quot` TILE_DATA_BYTES -- In an uncompressed gliph stream, the bitplanes are interleaved pairs of bytes readGliphStream :: L.ByteString -> Maybe [Gliph] readGliphStream stream = blocksForBitplanes (pairs 0 sEights) (pairs 1 sEights) (pairs 2 sEights) (pairs 3 sEights) where sEights = eights stream eights astream | L.length astream > 8 = let (head, tail) = L.splitAt 8 astream in (L.unpack head) : eights tail | otherwise = [L.unpack astream] pairs n (h:t) = (L.pack $ take 2 (drop (2*n) h)) `L.append` (pairs n t) pairs _ [] = L.empty -- Skip the head then parse the remaining bytes loadUncompressedShapes :: L.ByteString -> Maybe [Gliph] loadUncompressedShapes imdata = do (head, rest) <- getBytes BITMAP_OFFSET_BYTES imdata readGliphStream rest -- Takes a list of tuples of bytes from four bitplanes and returns a series of tiles blocksForBitplanes :: L.ByteString -> L.ByteString -> L.ByteString -> L.ByteString -> Maybe [Gliph] blocksForBitplanes b8 b4 b2 b1 = do (tb8, b8rest) <- getBytes TILE_BITPLANE_BYTES b8 (tb4, b4rest) <- getBytes TILE_BITPLANE_BYTES b4 (tb2, b2rest) <- getBytes TILE_BITPLANE_BYTES b2 (tb1, b1rest) <- getBytes TILE_BITPLANE_BYTES b1 gliphData <- createGliph tb8 tb4 tb2 tb1 case (blocksForBitplanes b8rest b4rest b2rest b1rest) of Just x -> Just (gliphData : x) Nothing -> Just [gliphData] -- Reads in the tile pixel data, turning 4 bitplanes of pixels into an array of tiles of -- 4-bit mapped-palette values loadCompressedShapes :: L.ByteString -> Maybe [Gliph] loadCompressedShapes imdata = do (head, rest) <- getBytes BITMAP_OFFSET_BYTES imdata (bitplane8, rest) <- getBytes bitplaneSeparationBytes rest (bitplane4, rest) <- getBytes bitplaneSeparationBytes rest (bitplane2, rest) <- getBytes bitplaneSeparationBytes rest (bitplane1, rest) <- getBytes bitplaneSeparationBytes rest blocksForBitplanes bitplane8 bitplane4 bitplane2 bitplane1 where bitplaneSeparationBytes = (numberOfShapes imdata) * TILE_BITPLANE_BYTES -- Dumps a list of colours printPalette :: [PaletteEntry] -> IO() printPalette [] = return () printPalette (x:xs) = do putStrLn $ show x printPalette xs -- Dumps the palette corresponding to an unpacked image showPalette :: UnpackedFile -> IO () showPalette image = do putStrLn $ "Data: " ++ (show $ L.length content) case (paletteData content) of Just palElements -> printPalette $ parsePalette palElements Nothing -> putStrLn "Error getting palette" where content = rawFileData image -- Reads the list of tiles from the image data loadTileMap :: L.ByteString -> Maybe [W.Word8] loadTileMap imdata = do (head, rest) <- getBytes LEVELMAP_OFFSET_BYTES imdata (tilemap, rest) <- getBytes (IMAGE_WIDTH_TILES * IMAGE_HEIGHT_TILES) rest return $ L.unpack tilemap
codders/gp3
src/BPackReader.hs
gpl-3.0
16,244
0
20
5,918
4,150
2,141
2,009
253
4
module Te.Util where import Import import Data.Text (concat, pack, Text) import Shelly findRootDir :: Text -> Sh (Maybe FilePath) findRootDir fileToFind = do startingDir <- pwd dir <- go cd startingDir return dir where go = do filePresent <- hasFile fileToFind currentDir <- pwd if filePresent then return $ Just currentDir else recur currentDir recur "/" = return Nothing recur _ = do cd ".." findRootDir fileToFind hasPipe :: FilePath -> Sh Bool hasPipe dir = do startingDir <- pwd cd dir present <- hasFile ".te-pipe" cd startingDir return present hasFile :: Text -> Sh Bool hasFile filename = do let relativeFileName = (fromText . concat) ["./", filename] files <- ls $ fromText "." return $ any (== relativeFileName) files
jetaggart/te
src/Te/Util.hs
gpl-3.0
821
0
12
213
286
135
151
32
3
{-# LANGUAGE FlexibleContexts #-} module Mudblood.Contrib.MG.Guilds ( module Mudblood.Contrib.MG.Guilds.Common , module Mudblood.Contrib.MG.Guilds.Tanjian , module Mudblood.Contrib.MG.Guilds.Zauberer , defaultStatus , guardGuild ) where import Data.Maybe import Data.String.Utils import Text.Printf import Data.Has hiding ((^.)) import Control.Lens import Mudblood import Mudblood.Contrib.MG.State import Mudblood.Contrib.MG.Guilds.Common import Mudblood.Contrib.MG.Guilds.Tanjian import Mudblood.Contrib.MG.Guilds.Zauberer defaultStatus :: (Has R_Common u) => MB u String defaultStatus = do stat <- getU R_Common let lp = stat ^. mgStatLP mlp = stat ^. mgStatMLP kp = stat ^. mgStatKP mkp = stat ^. mgStatMKP return $ printf "LP: %d (%d) | KP: %d (%d)" lp mlp kp mkp guardGuild :: (Has R_Common u) => MGGuild -> a -> MBTrigger u a guardGuild g = keep1 checkGuild where checkGuild _ = getU' R_Common mgGuild >>= guard . (== g)
talanis85/mudblood
src/Mudblood/Contrib/MG/Guilds.hs
gpl-3.0
1,003
0
10
200
273
161
112
28
1
{-| Module: DependentTypes.Parser Description: Parsing functions. -} module DependentTypes.Parser ( DependentTypes.Parser.parse ) where import Control.Monad import DependentTypes.Data import Text.Parsec import Text.Parsec.String -- | Parses the input and returns either a ParseError or a grammatically valid -- Program. parse :: String -> Either ParseError Program parse = Text.Parsec.parse parseProgram "" -- | Parses the program as a whole (i.e. a whole file). parseProgram :: Parser Program parseProgram = do spaces skipMany comment spaces statements <- parseToplevel `endBy` toplevelDelimiter eof return $ Program statements where toplevelDelimiter = spaces >> char '.' >> spaces >> skipMany comment >> spaces -- | Parses toplevel constructs. parseToplevel :: Parser Toplevel parseToplevel = parseType <|> parseFunc <|> parsePrint -- | Parses a type declaration. parseType :: Parser Toplevel parseType = do string "type" spaces typeId <- many letter spaces char ':' spaces signature <- parseSignature constructors <- parseConstructors return $ Type typeId signature constructors -- | Parses a function declaration. parseFunc :: Parser Toplevel parseFunc = do string "func" spaces signatures <- parseSignatures spaces string "where" lambdas <- parseLambdas return $ Func signatures lambdas -- | Parses a print declaration. parsePrint :: Parser Toplevel parsePrint = do string "print" spaces exp <- parsePrintExpressions return $ Print exp -- | Parses the expressions for a print statement. parsePrintExpressions :: Parser [Expression] parsePrintExpressions = parseArg `sepBy` printDelimiter where printDelimiter = (spaces >> char ';' >> spaces) -- | Parses the signature of at least one function. parseSignatures :: Parser [(String, Signature)] parseSignatures = parseFuncSignature `sepBy1` funcSignatureDelimiter where funcSignatureDelimiter = try (spaces >> char ';' >> spaces) -- | Parses the signature of a single function parseFuncSignature :: Parser (String, Signature) parseFuncSignature = do spaces funcId <- many1 letter spaces char ':' spaces signature <- parseSignature return $ (funcId, signature) -- | Parses a type signature. parseSignature :: Parser Signature parseSignature = do types <- parseTypeDef `sepBy1` signatureDelimiter return $ Signature types where signatureDelimiter = try (spaces >> string "->" >> spaces) parseTypeDef :: Parser TypeDef parseTypeDef = parseTypeId <|> parseDepType -- | Parses a type parseTypeId :: Parser TypeDef parseTypeId = liftM TypeId $ many1 letter -- | Parses a dependent type parseDepType :: Parser TypeDef parseDepType = do char '(' typeId <- many1 letter (Args args) <- parseArgs char ')' return $ DepType typeId args -- | Parses a list of constructors for a type. parseConstructors :: Parser [Constructor] parseConstructors = option [] parseConstructor' where constructorDelimiter = spaces >> char ';' >> spaces parseConstructor' = do spaces string "where" spaces parseConstructor `sepBy` constructorDelimiter -- | Parses a constructor for a type. parseConstructor :: Parser Constructor parseConstructor = do constructorId <- many letter args <- parseArgs char ':' spaces signature <- parseSignature constraint <- parseConstraint return $ Constructor constructorId args signature constraint -- | Parses a constraint for a type constructor. parseConstraint :: Parser Constraint parseConstraint = option NoConstraint parseConstraint' where parseConstraint' = do spaces char '|' spaces liftM Constraint $ parseExpression -- | Parses all declaration bodies of a function. parseLambdas :: Parser [Lambda] parseLambdas = parseLambda `sepBy1` lambdaDelimiter where lambdaDelimiter = try (spaces >> char ';' >> spaces) -- | Parses each declaration body of a function parseLambda :: Parser Lambda parseLambda = do spaces func <- many1 letter args <- parseArgs char '=' spaces exp <- parseExpression return $ Lambda func args exp -- | Parses all the arguments for a function declaration. parseArgs :: Parser Args parseArgs = do spaces liftM Args $ parseArg `endBy` argDelimiter where argDelimiter = spaces -- | Parses each argument for a function declaration. parseArg :: Parser Expression parseArg = parseSimpleExpression <|> parseParenthesisExpression -- | Parses an (possibly complex) expression. parseExpression :: Parser Expression parseExpression = parseComposeExpression <|> parseParenthesisExpression -- | Parses a simple expression (i.e. a single word). parseSimpleExpression :: Parser Expression parseSimpleExpression = do expId <- many1 letter return $ ExpId expId -- | Parses a complex expression (i.e. a function call or an expression between -- parentheses. parseComposeExpression :: Parser Expression parseComposeExpression = do liftM ExpList $ (parseSimpleExpression <|> parseParenthesisExpression) `sepBy` try (many1 space) -- | Parses an expression between parentheses. parseParenthesisExpression :: Parser Expression parseParenthesisExpression = do char '(' exp <- parseComposeExpression char ')' return exp -- | Parses a comment. comment :: Parser () comment = string "{-" >> manyTill anyChar (try (string "-}")) >> spaces
ramaciotti/dependent-types
src/lib/DependentTypes/Parser.hs
gpl-3.0
5,397
0
11
1,016
1,201
590
611
137
1
module Game where import Actions (modifiedField, resolve) import qualified Cards import Control.Lens (view, (^.)) import Data.Maybe (fromMaybe) import DataTypes import qualified Decks import GameActionParser (parseGameAction) import qualified GameIO as Gio import Polysemy (Member, Members, Sem) import Polysemy.Input (Input, input) import Polysemy.State (State, evalState) import qualified Polysemy.State as S import Polysemy.Trace (Trace) import Prelude hiding (log) createPlayer :: String -> Player createPlayer name = Player {name = name, deck = Decks.mixed, hand = Decks.mixed, field = [], playerCreature = Cards.defaultPlayerCreature} orElsePass :: Maybe GameAction -> GameAction orElsePass = fromMaybe Pass convertGameAction :: GameAction -> GameState -> [Action] convertGameAction (Play c) _ = c ^. #effects . #onPlay convertGameAction (PlayFromHand i) gs = DiscardFromHand c : c ^. #effects . #onPlay where c = (gs ^. activePlayer . #hand) !! i -- crashes program when i is out of range convertGameAction (ActivateFromField i) gs = c ^. #effects . #onActivate where c = modifiedField activePlayer gs !! i -- crashes program when i is out of range convertGameAction (AnnounceAttack target source) gs = [Attack targetCard sourceCard] where targetCard = modifiedField enemyPlayer gs !! target -- crashes program when target is out of range sourceCard = modifiedField activePlayer gs !! source -- crashes program when source is out of range convertGameAction (AnnounceDirectAttack i) gs = return $ DirectAttack c enemyPlayer where c = (gs ^. activePlayer . #field) !! i -- crashes program when i is out of range convertGameAction EndRound _ = return EndTurn convertGameAction _ _ = [] parseActions :: String -> GameState -> [Action] parseActions = convertGameAction . orElsePass . parseGameAction playGame :: [Action] -> Game r () playGame [] = return () playGame (x : xs) = do Gio.logLn' $ "resolving action: " ++ show x -- Gio.logLn $ "on current state: " ++ show g resolve x playGame xs gameOver :: Member Trace r => Sem r () gameOver = Gio.logLn' "k bye" gameLoop :: Member (Input String) r => Game r () gameLoop = do gs <- S.get Gio.logLn' "" Gio.logLn' "Enemy field:" Gio.displayEnumeratedItems $ modifiedField enemyPlayer gs Gio.logLn' "Your field:" Gio.displayEnumeratedItems $ modifiedField activePlayer gs Gio.logLn' "Player Hand:" Gio.displayEnumeratedItems $ gs ^. activePlayer . #hand Gio.log' "Select action (pass/end/p/c/a/d): " inp <- input if inp == "exit" || inp == "q" then gameOver else do playGame (parseActions inp gs) gameLoop startGame :: Members [Input String, Input Int, Trace] r => Sem r () startGame = do let player1 = createPlayer "player1" let player2 = createPlayer "player2" evalState (GameState (player1, player2)) gameLoop Gio.logLn' "Game end"
MoritzR/CurseOfDestiny
src/Game.hs
gpl-3.0
2,882
0
12
516
879
457
422
-1
-1
removeMultiple :: Int -> [Int] -> [Int] removeMultiple n = filter (\x -> x `mod` n /= 0) getPrimes :: [Int] getPrimes = getPrimes' [2..] where getPrimes' (x:xs) = x : getPrimes' (removeMultiple x xs) getPrimesOpt = getPrimesOpt' [2..] where getPrimesOpt' (x:xs) = x : getPrimesOpt' [y | y <- xs, y `mod` x /= 0]
muralikrishna8/Haskell-problems
infinitePrimeNumbers.hs
gpl-3.0
331
0
10
75
160
86
74
7
1
{-# LANGUAGE TupleSections, Rank2Types, ScopedTypeVariables #-} module Service.Periodic ( forkPeriodic ) where import Control.Concurrent (ThreadId, forkFinally, threadDelay) import Control.Exception (handle, mask) import Control.Monad (void, when) import Control.Monad.Trans.Reader (withReaderT) import Data.Fixed (Fixed(..), Micro) import Data.IORef (writeIORef) import Data.Time.Calendar.OrdinalDate (sundayStartWeek) import Data.Time.Clock (UTCTime(..), diffUTCTime, getCurrentTime) import Data.Time.LocalTime (TimeOfDay(TimeOfDay), timeOfDayToTime) import Has import Service.Types import Service.Log import Service.Notification import Context import Model.Periodic import Model.Token import Model.Volume import Model.Stats import Model.Notification import Controller.Notification import Solr.Index import EZID.Volume -- TODO threadDelay' :: Micro -> IO () threadDelay' (MkFixed t) | t > m' = threadDelay m >> threadDelay' (MkFixed (t - m')) | otherwise = threadDelay (fromInteger t) where m' = toInteger m m = maxBound run :: Period -> Service -> IO () run p = runContextM $ withReaderT BackgroundContext $ do t <- peek focusIO $ logMsg t ("periodic running: " ++ show p) cleanTokens updateVolumeIndex withReaderT (mkSolrIndexingContext . backgroundContext) updateIndex ss <- lookupSiteStats focusIO $ (`writeIORef` ss) . serviceStats when (p >= PeriodWeekly) $ void updateEZID _ <- cleanNotifications updateStateNotifications focusIO $ triggerNotifications (Just p) runPeriodic :: Service -> (forall a . IO a -> IO a) -> IO () runPeriodic rc unmask = loop (if s <= st then d s else s) where st = serviceStartTime rc s = st{ utctDayTime = timeOfDayToTime $ TimeOfDay 7 0 0 } d t = t{ utctDay = succ (utctDay t) } loop t = do n <- getCurrentTime (t', p) <- handle (return . (t ,)) $ do unmask $ threadDelay' $ realToFrac $ diffUTCTime t n return (d t, if 0 == snd (sundayStartWeek (utctDay t)) then PeriodWeekly else PeriodDaily) handle (\(_ :: Period) -> logMsg t "periodic interrupted" (view rc)) $ unmask $ run p rc loop t' forkPeriodic :: Service -> IO ThreadId forkPeriodic rc = forkFinally (mask $ runPeriodic rc) $ \r -> do t <- getCurrentTime logMsg t ("periodic aborted: " ++ show r) (view rc)
databrary/databrary
src/Service/Periodic.hs
agpl-3.0
2,314
0
21
427
819
429
390
64
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} module DBusInterface (rootObject) where import Control.Applicative import Control.Concurrent.STM import Control.Lens hiding ((:>)) import DBus as DBus import DBus.Types import Data.ByteString (ByteString) import Data.Map (Map) import Data.String import qualified Network.Xmpp as Xmpp import Basic import Gpg import Persist import Signals import Transactions import Types import Xmpp ---------------------------------------------------- -- Methods ---------------------------------------------------- instance IsString (ArgumentDescription ('Arg 'Null)) where fromString t = (fromString t :> Done) setCredentialsMethod :: PSState -> Method setCredentialsMethod st = Method (DBus.repMethod $ \u p -> setCredentialsM st u p) "setCredentials" ("username" :> "password" :> Done) Done getCredentialsMethod :: PSState -> Method getCredentialsMethod st = Method (DBus.repMethod $ getCredentialsM st) "getCredentials" Done ("username" :> Done) -- securityHistoryByJidMethod :: Method -- securityHistoryByJidMethod = -- DBus.Method -- (DBus.repMethod $ (stub :: Xmpp.Jid -> IO ( [AkeEvent] -- , [ChallengeEvent] -- , [RevocationEvent] -- , [RevocationSignalEvent] -- ))) -- "securityHistoryByJID" ("peer" :> Done ) -- ( "ake_events" -- :> "challenge_events" -- :> "revocation_events" -- :> "revocation_signal_events" -- :> Done -- ) -- securityHistoryByKeyIdMethod :: Method -- securityHistoryByKeyIdMethod = -- DBus.Method -- (DBus.repMethod $ (stub :: Xmpp.Jid -> IO ( [AkeEvent] -- , [ChallengeEvent] -- , [RevocationEvent] -- , [RevocationSignalEvent] -- ))) -- "securityHistoryByKeyID" ("key_id" :> Done) -- ("ake_events" -- :> "challenge_events" -- :> "revocation_events" -- :> "revocation_signal_events" -- :> Done -- ) removeChallengeMethod :: PSState -> DBus.Method removeChallengeMethod st = DBus.Method (DBus.repMethod $ runPSM st . removeChallenge) "removeChallenge" ("challenge_id" :> Done ) Done initialize :: PSState -> IO PontariusState initialize st = do let stateRef = view psState st readTVarIO stateRef initializeMethod :: PSState -> Method initializeMethod st = DBus.Method (DBus.repMethod $ initialize st) "initialize" Done ( "state" :> Done) getUnlinkedPeers :: PSState -> IO (Map Xmpp.Jid KeyID) getUnlinkedPeers st = snd <$> availableContacts st getUnlinkedPeersMethod :: PSState -> Method getUnlinkedPeersMethod st = DBus.Method (DBus.repMethod $ getUnlinkedPeers st) "getUnlinkedPeers" Done ( "unlinkedPeers" :> Done) markKeyVerifiedMethod :: PSState -> Method markKeyVerifiedMethod st = DBus.Method (DBus.repMethod $ (\kid isV -> runPSM st $ setKeyVerifiedM kid isV )) "identityVerified" ("key_id" :> "is_verified" :> Done) Done revokeIdentityMethod :: PSState -> Method revokeIdentityMethod st = DBus.Method (DBus.repMethod $ runPSM st . revokeIdentity) "revokeIdentity" ("key_id" :> Done) Done createIdentityMethod :: PSState -> Method createIdentityMethod st = DBus.Method (DBus.repMethod $ (runPSM st synchronousCreateGpgKey :: MethodHandlerT IO ByteString)) "createIdentity" Done ("key_id" -- key_id of the newly created key :> Done) initiateChallengeMethod :: PSState -> Method initiateChallengeMethod st = DBus.Method (DBus.repMethod $ \p q s -> runPSM st $ verifyChannel p q s) "initiateChallenge" ("peer" :> "question" :> "secret" :> Done) Done respondChallengeMethod :: PSState -> Method respondChallengeMethod st = DBus.Method (DBus.repMethod $ (\peer secret -> runPSM st $ respondChallenge peer secret)) "respondChallenge" ("peer" :> "secret" :> Done) Done getIdentityChallengesMethod :: PSState -> Method getIdentityChallengesMethod st = DBus.Method (DBus.repMethod $ getIdentityChallengesM st) "getIdentityChallenges" ("key_id" :> Done) ("challenges" :> Done) getTrustStatusMethod :: PSState -> Method getTrustStatusMethod st = DBus.Method (DBus.repMethod $ isKeyVerifiedM st) "keyTrustStatus" ("key_id" :> Done) "is_trusted" addPeerMethod :: PSState -> Method addPeerMethod st = DBus.Method (DBus.repMethod $ methodHandler . runPSM st . addPeerM) "addPeer" ("jid" :> Done) Done removePeerMethod :: PSState -> Method removePeerMethod st = DBus.Method (DBus.repMethod $ (runPSM st . removePeer :: Xmpp.Jid -> MethodHandlerT IO ())) "removePeer" ("peer" :> Done) Done -- registerAccountMethod :: Method -- registerAccountMethod = -- DBus.Method -- (DBus.repMethod $ (stub :: Text -> Text -> Text -> IO ())) -- "registerAccount" ("server" :> "username" :> "password" -- :> Done) -- Done setIdentityMethod :: PSState -> Method setIdentityMethod st = DBus.Method (DBus.repMethod $ setSigningGpgKeyM st) "setIdentity" ("keyID" :> Done) Done newContactMethod :: PSState -> Method newContactMethod st = DBus.Method (DBus.repMethod $ newContactM st) "newContact" ("name" :> Done) "contact_id" linkIdentityMethod :: PSState -> Method linkIdentityMethod st = DBus.Method (DBus.repMethod $ \kid c -> moveIdentity st kid (Just c) ) "linkIdentity" ("identity" :> "contact" :> Done) Done unlinkIdentityMethod :: PSState -> Method unlinkIdentityMethod st = DBus.Method (DBus.repMethod $ \kid -> moveIdentity st kid Nothing ) "unlinkIdentity" ("identity" :> Done) Done getContactsMethod :: PSState -> Method getContactsMethod st = DBus.Method (DBus.repMethod $ runPSM st getContactsM) "getContacts" Done ("contacts" :> Done) removeContactMethod :: PSState -> Method removeContactMethod st = DBus.Method (DBus.repMethod $ runPSM st . removeContactM) "removeContacts" ("contact" :> Done) Done renameContactMethod :: PSState -> Method renameContactMethod st = DBus.Method (DBus.repMethod $ \c name -> runPSM st $ renameContactM c name) "renameContact" ("contact" :> "name" :> Done) Done getContactPeersMethod :: PSState -> Method getContactPeersMethod st = DBus.Method (DBus.repMethod $ runPSM st . Xmpp.getContactPeers) "getContactPeers" ("contact" :> Done) ("peers" :> Done) getContactIdentitiesMethod :: PSState -> Method getContactIdentitiesMethod st = DBus.Method (DBus.repMethod $ runPSM st . getContactIdentities) "getContactIdentities" ("contact" :> Done) ("identities" :> Done) getSessionByJIDMethod :: PSState -> Method getSessionByJIDMethod st = DBus.Method (DBus.repMethod $ io . runPSM st . getJidSessions) "getSessionsByJID" ("jid" :> Done) ("sessions" :> Done) getSessionByIdentityMethod :: PSState -> Method getSessionByIdentityMethod st = DBus.Method (DBus.repMethod $ io . runPSM st . getIdentitySessions) "getSessionsByIdentity" ("identity" :> Done) ("sessions" :> Done) ignorePeerMethod :: PSState -> Method ignorePeerMethod st = DBus.Method (DBus.repMethod $ runPSM st . ignorePeer) "ignorePeer" ("jid" :> Done) Done unignorePeerMethod :: PSState -> Method unignorePeerMethod st = DBus.Method (DBus.repMethod $ runPSM st . unignorePeer) "unignorePeer" ("jid" :> Done) Done linkPeersContactsMethod :: PSState -> Method linkPeersContactsMethod st = DBus.Method (DBus.repMethod $ runPSM st . batchLink) "linkPeers" ("jids and " :> Done) Done ---------------------------------------------------- -- Objects ---------------------------------------------------- xmppInterface :: PSState -> Interface xmppInterface st = Interface [ addPeerMethod st , createIdentityMethod st , getContactIdentitiesMethod st , getContactPeersMethod st , getContactsMethod st , getCredentialsMethod st , getIdentitiesMethod , getIdentityChallengesMethod st , getSessionByIdentityMethod st , getSessionByJIDMethod st , getTrustStatusMethod st , getUnlinkedPeersMethod st , initializeMethod st , initiateChallengeMethod st , linkIdentityMethod st , linkPeersContactsMethod st , markKeyVerifiedMethod st , newContactMethod st , removeChallengeMethod st , removeContactMethod st , removePeerMethod st , renameContactMethod st , respondChallengeMethod st , revokeIdentityMethod st , setCredentialsMethod st , setIdentityMethod st , unlinkIdentityMethod st , ignorePeerMethod st , unignorePeerMethod st -- , registerAccountMethod -- , securityHistoryByJidMethod -- , securityHistoryByKeyIdMethod ] [] [ SSD challengeResultSignal , SSD contactRemovedSignal , SSD contactRenamedSignal , SSD contactStatusChangedSignal , SSD identityAvailabilitySignal , SSD identityUnlinkedSignal , SSD peerTrustStatusChangedSignal , SSD receivedChallengeSignal , SSD subscriptionRequestSignal , SSD unlinkedIdentityAvailabilitySignal , SSD addPeersFailedSignal , SSD removePeersFailedSignal ] [ SomeProperty $ identityProp st ] conObject :: PSState -> Object conObject st = object pontariusInterface (xmppInterface st) rootObject :: PSState -> Objects rootObject st = root pontariusObjectPath (conObject st)
pontarius/pontarius-service
source/DBusInterface.hs
agpl-3.0
11,054
0
11
3,364
2,192
1,157
1,035
260
1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.DynamicWorkspacesPure -- Copyright : (c) David Roundy <[email protected]> -- License : BSD3-style (see LICENSE) -- -- Maintainer : none -- Stability : unstable -- Portability : unportable -- -- Provides bindings to add and delete workspaces. -- ----------------------------------------------------------------------------- module XMonad.Actions.DynamicWorkspacesPure ( -- * Usage -- $usage addWorkspace, addWorkspacePrompt, removeWorkspace, removeWorkspace', removeEmptyWorkspace, removeEmptyWorkspaceAfter, removeEmptyWorkspaceAfterExcept, addHiddenWorkspace, addHiddenWorkspace', addHiddenWorkspace'', withWorkspace, selectWorkspace, renameWorkspace, renameWorkspaceByName, toNthWorkspace, withNthWorkspace ) where import XMonad hiding (workspaces) import XMonad.StackSet hiding (filter, modify, delete) import XMonad.Prompt.Workspace ( Wor(Wor), workspacePrompt ) import XMonad.Prompt ( XPConfig, mkXPrompt ) import XMonad.Util.WorkspaceCompare ( getSortByIndex ) import Data.List (find) import Data.Maybe (isNothing) import Data.Monoid (Endo) import Control.Monad (when) import XMonad.Core hiding (workspaces) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@ file: -- -- > import XMonad.Actions.DynamicWorkspaces -- > import XMonad.Actions.CopyWindow(copy) -- -- Then add keybindings like the following: -- -- > , ((modm .|. shiftMask, xK_BackSpace), removeWorkspace) -- > , ((modm .|. shiftMask, xK_v ), selectWorkspace defaultXPConfig) -- > , ((modm, xK_m ), withWorkspace defaultXPConfig (windows . W.shift)) -- > , ((modm .|. shiftMask, xK_m ), withWorkspace defaultXPConfig (windows . copy)) -- > , ((modm .|. shiftMask, xK_r ), renameWorkspace defaultXPConfig) -- -- > -- mod-[1..9] %! Switch to workspace N -- > -- mod-shift-[1..9] %! Move client to workspace N -- > ++ -- > zip (zip (repeat (modm)) [xK_1..xK_9]) (map (withNthWorkspace W.greedyView) [0..]) -- > ++ -- > zip (zip (repeat (modm .|. shiftMask)) [xK_1..xK_9]) (map (withNthWorkspace W.shift) [0..]) -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". See also the documentation for -- "XMonad.Actions.CopyWindow", 'windows', 'shift', and 'defaultXPConfig'. mkCompl :: [String] -> String -> IO [String] mkCompl l s = return $ filter (\x -> take (length s) x == s) l withWorkspace :: XPConfig -> (String -> X ()) -> X () withWorkspace c job = do ws <- gets (workspaces . windowset) sort <- getSortByIndex let ts = map tag $ sort ws job' t | t `elem` ts = job t | otherwise = addHiddenWorkspace t >> job t mkXPrompt (Wor "") c (mkCompl ts) job' renameWorkspace :: XPConfig -> X () renameWorkspace conf = workspacePrompt conf renameWorkspaceByName renameWorkspaceByName :: String -> X () renameWorkspaceByName w = windows $ \s -> let sett wk = wk { tag = w } setscr scr = scr { workspace = sett $ workspace scr } sets q = q { current = setscr $ current q } in sets $ removeWorkspace' w s toNthWorkspace :: (String -> X ()) -> Int -> X () toNthWorkspace job wnum = do sort <- getSortByIndex ws <- gets (map tag . sort . workspaces . windowset) case drop wnum ws of (w:_) -> job w [] -> return () withNthWorkspace :: (String -> WindowSet -> WindowSet) -> Int -> X () withNthWorkspace job wnum = do sort <- getSortByIndex ws <- gets (map tag . sort . workspaces . windowset) case drop wnum ws of (w:_) -> windows $ job w [] -> return () selectWorkspace :: XPConfig -> X () selectWorkspace conf = workspacePrompt conf $ \w -> do s <- gets windowset if tagMember w s then windows $ greedyView w else addWorkspace w -- | Add a new workspace with the given name, or do nothing if a -- workspace with the given name already exists; then switch to the -- newly created workspace. addWorkspace :: String -> X () addWorkspace newtag = addHiddenWorkspace newtag >> windows (greedyView newtag) -- | Prompt for the name of a new workspace, add it if it does not -- already exist, and switch to it. addWorkspacePrompt :: XPConfig -> X () addWorkspacePrompt conf = mkXPrompt (Wor "New workspace name: ") conf (const (return [])) addWorkspace -- | Add a new hidden workspace with the given name, or do nothing if -- a workspace with the given name already exists. addHiddenWorkspace :: String -> X () addHiddenWorkspace newtag = whenX (gets (not . tagMember newtag . windowset)) $ do l <- asks (layoutHook . config) windows (addHiddenWorkspace' newtag l) -- | Remove the current workspace if it contains no windows. removeEmptyWorkspace :: X () removeEmptyWorkspace = gets (currentTag . windowset) >>= removeEmptyWorkspaceByTag -- | Remove the current workspace. removeWorkspace :: X () removeWorkspace = gets (currentTag . windowset) >>= removeWorkspaceByTag -- | Remove workspace with specific tag if it contains no windows. Only works -- on the current or the last workspace. removeEmptyWorkspaceByTag :: String -> X () removeEmptyWorkspaceByTag t = whenX (isEmpty t) $ removeWorkspaceByTag t -- | Remove workspace with specific tag. Only works on the current or the last workspace. removeWorkspaceByTag :: String -> X () removeWorkspaceByTag torem = do s <- gets windowset case s of StackSet { current = Screen { workspace = cur }, hidden = (w:_) } -> do when (torem==tag cur) $ windows $ view $ tag w windows $ removeWorkspace' torem _ -> return () -- | Remove the current workspace after an operation if it is empty and hidden. -- Can be used to remove a workspace if it is empty when leaving it. The -- operation may only change workspace once, otherwise the workspace will not -- be removed. removeEmptyWorkspaceAfter :: X () -> X () removeEmptyWorkspaceAfter = removeEmptyWorkspaceAfterExcept [] -- | Like 'removeEmptyWorkspaceAfter' but use a list of sticky workspaces, -- whose entries will never be removed. removeEmptyWorkspaceAfterExcept :: [String] -> X () -> X () removeEmptyWorkspaceAfterExcept sticky f = do before <- gets (currentTag . windowset) f after <- gets (currentTag . windowset) when (before/=after && before `notElem` sticky) $ removeEmptyWorkspaceByTag before isEmpty :: String -> X Bool isEmpty t = do wsl <- gets $ workspaces . windowset let mws = find (\ws -> tag ws == t) wsl return $ maybe True (isNothing . stack) mws addHiddenWorkspace' :: i -> l -> StackSet i l a sid sd -> StackSet i l a sid sd addHiddenWorkspace' newtag l s@(StackSet { hidden = ws }) = s { hidden = Workspace newtag l Nothing:ws } addHiddenWorkspace'' :: (Eq i) => i -> l -> StackSet i l a sid sd -> StackSet i l a sid sd addHiddenWorkspace'' newtag l s@(StackSet { hidden = ws}) | tagMember newtag s = s | otherwise = s { hidden = ws ++ [Workspace newtag l Nothing]} removeWorkspace' :: (Eq i) => i -> StackSet i l a sid sd -> StackSet i l a sid sd removeWorkspace' torem s@(StackSet { current = scr@(Screen { workspace = wc }) , hidden = (w:ws) }) | tag w == torem = s { current = scr { workspace = wc { stack = meld (stack w) (stack wc) } } , hidden = ws } where meld Nothing Nothing = Nothing meld x Nothing = x meld Nothing x = x meld (Just x) (Just y) = differentiate (integrate x ++ integrate y) removeWorkspace' _ s = s
duckwork/dots
xmonad/lib/XMonad/Actions/DynamicWorkspacesPure.hs
unlicense
8,869
0
18
2,827
1,935
1,008
927
108
4
module AlecSequences.A279966 (a279966) where import Tables.A274080 (a274080_row) import Data.List (genericIndex, genericLength) a279966 :: Integer -> Integer a279966 1 = 1 a279966 n = genericIndex a279966_list (n - 1) a279966_list :: [Integer] a279966_list = 1 : map count [2..] where count n = genericLength $ filter isFactorOf adjacentLabels where adjacentLabels = map a279966 (a274080_row n) isFactorOf a_i = a_i > 0 && n `mod` a_i == 0
peterokagey/haskellOEIS
src/AlecSequences/A279966.hs
apache-2.0
452
0
12
78
159
86
73
11
1
import Test.Tasty import Test.Tasty.HUnit import Text.ChordPro.Parser import Text.ChordPro.Types import Text.Trifecta main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [unitTests] simpleLyric :: String simpleLyric = concat [ "[C]Cecilia, you're [F]breaking my [C]heart, you're " , "[F]shaking my [C]confidence [G7]daily.\n" ] parseSimpleLyric :: Result [Lyric] parseSimpleLyric = parseString parseLyricLine mempty simpleLyric isSuccess :: Result a -> Bool isSuccess (Success _) = True isSuccess _ = False resultToMaybe :: Result a -> Maybe a resultToMaybe (Success a) = Just a resultToMaybe _ = Nothing unitTests = testGroup "Unit tests" [ testCase "Parse a simple lyric line successfully" $ isSuccess parseSimpleLyric @?= True , testCase "Parse a simple lyric line into correct length" $ (length <$> (resultToMaybe parseSimpleLyric)) @?= Just 12 ]
relrod/chordpro
test/test.hs
bsd-2-clause
950
0
11
193
239
124
115
25
1
{-# LANGUAGE TypeFamilies, RankNTypes, ScopedTypeVariables, ViewPatterns, BangPatterns #-} module OffLattice.HPChain where import OffLattice.Util import LA import qualified LA.Transform as T import qualified LA.Matrix as M import qualified OffLattice.Chain as C import qualified OffLattice.Shape as S import qualified OffLattice.Geo as G import qualified Data.Vector.Fixed as F import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import qualified Data.MonoTraversable as MT import qualified Data.HashSet as HS import qualified Data.Vector.Algorithms.Intro as VSORT type Index = Int type Id = Int type Angle n = n type Radius n = n type Potential n = n type Energy n = n type Range n = n type Vec n = F.ContVec F.N3 n type Pos n = Vec n type Bond n = (Index, Pos n, Vec n) type Matrix n = Vec (Vec n) type Transform n = (Matrix n, Vec n) data HP = H | P deriving (Show, Read, Eq) data HPN = H' | P' | N' deriving Eq instance Show HPN where show H' = "H" show P' = "P" show N' = "N" data HPConfig n = HPConfig { hRadius :: Radius n , pRadius :: Radius n , nRadius :: Radius n , hpPotential :: Potential n , ppPotential :: Potential n , hhPotential :: Potential n , hpRange :: Range n -- Interaction range , bondAngle :: Angle n } deriving (Show, Read, Eq) radius H' = hRadius radius P' = pRadius radius N' = nRadius data HPChain n = HPChain { positions :: !(V.Vector (Pos n)) , residues :: !(V.Vector HPN) , bonds :: !(V.Vector (Bond n)) , indices :: !(V.Vector Index) , config :: !(HPConfig n) } instance forall n. Show n => Show (HPChain n) where show (HPChain ps rs bs is c) = "HPChain {" ++ "\n - positions:" ++ show ps' ++ "\n - residues:" ++ show (V.toList rs) ++ "\n - bonds:" ++ show bs' ++ "\n - indices:" ++ show (V.toList is) ++ "\n - config:" ++ show c where ps' :: [F.Tuple3 n] ps' = V.toList $ V.map F.convert ps bs' = V.toList $ V.map f bs f :: Bond n -> (Index, F.Tuple3 n, F.Tuple3 n) f (i, a, b) = (i, F.convert a, F.convert b) instance ( Ord n , Additive n , Multiplicative n , Floating n , Epsilon n , Show n ) => C.Chain (HPChain n) where type Index (HPChain n) = Index type Angle (HPChain n) = Angle n type Energy (HPChain n) = Energy n indices = indices move = updateChain energy = energy mkHPChain :: forall n. ( Additive n , Multiplicative n , Floating n , Epsilon n , Show n ) => [HP] -> HPConfig n -> HPChain n mkHPChain !hps !hpc = HPChain ps rs bs is hpc where n = length hps * 2 m = length hps !rs = V.fromList $ f hps !ps = V.generate n place !bs = V.generate (m-1) g !is = V.generate (m-1) id (c, s) = let a = bondAngle hpc / 2 in (cos a, sin a) place i = F.mk3 (s * x) (c * y) z where x = fromIntegral (i `div` 2) y | i `mod` 4 > 1 = 1 | otherwise = 0 z | 1 <- i `mod` 4 = 1 | 3 <- i `mod` 4 = (-1) | otherwise = 0 f [] = [] f (H:xs) = N' : H' : f xs f (P:xs) = N' : P' : f xs g i | j <- 2*i = (j, place j, normalize $ place (2 + j) .- place j) rotChain :: forall n. ( Additive n , Multiplicative n , Floating n , Epsilon n ) => Index -> Angle n -> HPChain n -> HPChain n rotChain _ a hpc | a ~= 0 = hpc rotChain i a (HPChain !ps !rs !bs !is !hpc) | i >= V.length is || i < 0 = error "Index out of bounds" | otherwise = HPChain ps' rs bs' is hpc where (!j,!p,!b) = bs V.! i !bs' = V.imap f bs !ps' = V.imap g ps !lng = V.length bs `div` 2 < i || True f j (!k, !p, !b) | j <= i = (k, p, b) | j > i = (k, T.vtmulG p t, M.vmmulG b r) --g i r | i <= j = r -- | i > j = T.vtmulG r t g !i !r | i <= j + 1 = r | i > j + 1 = T.vtmulG r t !t = T.rotAboutG p b a :: Transform n !r = T.rot3 b a :: Matrix n {- updateChain :: forall n. ( Ord n , Additive n , Multiplicative n , Floating n , Epsilon n ) => Int -> Angle n -> HPChain n -> Maybe (HPChain n) updateChain i a c | valid = Just c' | otherwise = Nothing where valid = validShapes s c' = rotChain i a c rs = residues c' ps = positions c ps' = positions c' hpc = config c s = VG.izipWith f ps (positions c') f i a b = let r = radius (rs V.! i) hpc in if r /= 0 then S.capsule i r a b else error "radius is 0!" -} updateChain :: forall n. ( Ord n , Additive n , Multiplicative n , Floating n , Epsilon n ) => Int -> Angle n -> HPChain n -> Maybe (HPChain n) updateChain !i !a c@(HPChain !ps !rs !bs !is !hpc) | valid = Just c' | otherwise = Nothing where !valid = validShapes2 s (j+1) (!j,!_,!_) = bonds c V.! i !c' = rotChain i a c !rs = residues c' !ps = positions c !ps' = positions c' hpc = config c !s = VG.izipWith f ps (positions c') f !i !a !b = let r = radius (rs V.! i) hpc in if r /= 0 then S.capsule i r a b else error "radius is 0!" validShapes :: forall n. ( Ord n , Additive n , Multiplicative n , Epsilon n , Floating n ) => V.Vector (S.Shape Id (Vec n)) -> Bool validShapes !s = MT.oall intersects overlaps where intervals :: Vec (V.Vector (G.Point n Id)) !intervals = F.map (V.modify VSORT.sort) $ G.intervals s !overlaps = HS.filter (\(i,j) -> abs (i-j) > 1) $ G.overlappings intervals intersects (!i,!j) = maybe True (const False) $ G.intersects (s V.! i) (s V.! j) validShapes2 :: forall n. ( Ord n , Additive n , Multiplicative n , Epsilon n , Floating n ) => V.Vector (S.Shape Id (Vec n)) -> Int -> Bool validShapes2 !s !i = MT.oall intersects overlaps where (!a,!b) = V.splitAt i s is, js :: Vec (V.Vector (G.Point n Id)) !is = F.map (V.modify VSORT.sort) $ G.intervals a !js = F.map (V.modify VSORT.sort) $ G.intervals b !overlaps = HS.filter (\(i,j) -> abs (i-j) > 1) $ G.overlappings2 is js intersects (!i,!j) = maybe True (const False) $ G.intersects (s V.! i) (s V.! j) energy :: forall n. ( Ord n , Additive n , Multiplicative n , Epsilon n , Floating n , Show n ) => HPChain n -> Energy n energy !ch@(HPChain !ps !rs !bs !is !hpc) = MT.ofoldr ((+) . enrgy) 0 overlaps where !rng = hpRange $ hpc !pp = ppPotential $ hpc !hp = hpPotential $ hpc !hh = hhPotential $ hpc !xs = V.map f $ V.filter (isHP . snd) $ V.indexed rs f (!i, !_) = if rng /= 0 then S.Sphere rng (ps V.! i) i else error "rng == 0" isHP N' = False isHP _ = True intervals :: Vec (V.Vector (G.Point n Id)) !intervals = F.map (V.modify VSORT.sort) $ G.intervals xs !overlaps = G.overlappings intervals enrgy (!i,!j) = let !d = dist (ps V.! i) (ps V.! j) !e = if d >= rng then (0,0) else pot i j d in fst e pot !i !j !d = let e H' H' = hh e H' P' = hp e P' H' = hp e P' P' = pp p = e (rs V.! i) (rs V.! j) in (min 0 $ ljPotential p 1 d, p)
chalmers-kandidat14/off-lattice
OffLattice/HPChain.hs
bsd-3-clause
8,233
0
16
3,277
3,160
1,601
1,559
207
7
module Main where import System.Environment import System.Exit import System.FilePath import System.FilePath.GlobPattern (GlobPattern, (~~)) import System.IO import System.FSNotify import Control.Monad (forever) import Control.Concurrent (threadDelay) import Data.Text (pack) import Data.Bits ((.&.)) main :: IO () main = do hSetBuffering stdout NoBuffering getArgs >>= parse >>= runWatcher parse :: [String] -> IO FilePath parse ["-h"] = usage >> exitSuccess parse [] = return "." parse (path:_) = return path usage :: IO () usage = putStrLn "Usage: hobbes [path]" runWatcher :: FilePath -> IO () runWatcher path = let (dir, glob) = splitFileName path in withManager $ \m -> do watchTree m dir (globModified glob) printPath forever $ threadDelay 1000000 globModified :: GlobPattern -> Event -> Bool globModified glob evt@(Added _ _) = matchesGlob glob evt globModified glob evt@(Modified _ _) = matchesGlob glob evt globModified _ (Removed _ _) = False matchesGlob :: GlobPattern -> Event -> Bool matchesGlob glob = fileMatchesGlob glob . takeFileName . eventPath printPath :: Event -> IO () printPath = putStrLn . eventPath fileMatchesGlob :: GlobPattern -> FilePath -> Bool fileMatchesGlob [] _ = True fileMatchesGlob "." _ = True fileMatchesGlob glob fp = fp ~~ glob
rob-b/hobbes
Hobbes.hs
bsd-3-clause
1,327
0
13
246
467
244
223
39
1
module Evol.Algo.SGA ( ) where -- evil import Evil.EvoAlgorithm import Evil.Individual import Evil.Spaces import Evil.PPrintable import Evil.RandUtils -- vector import qualified Data.Vector as V newtype SGA = SGA instance EvoAlgorithm SGA () where initialize () gen = undefined nextGen = undefined
kgadek/evil-pareto-tests
src_old/Evol/Algo/SGA.hs
bsd-3-clause
314
2
6
57
65
42
23
-1
-1
module YouTube.Services ( browseChannel , browseMyChannel , createPlaylist , createPlaylists , deletePlaylist , findChannel , insertVideo , listPlaylist , listVideos ) where import GoogleAPIsClient import Helpers (hashURL) import Model (Tournament(..)) import YouTube.Models import Data.Foldable (toList) import Data.List (find, intercalate) import Data.Map as M (empty, fromList, (!)) browseChannel :: YouTubeId -> Int -> Client [Playlist] browseChannel cId count = unwrap <$> listChannelPlaylists cId count where unwrap (Playlists playlists) = playlists browseMyChannel :: Int -> Client [Playlist] browseMyChannel count = do requireOAuth2 myChannel <- channelId <$> findMyChannel browseChannel myChannel count createPlaylist :: Tournament -> Client Playlist createPlaylist t = do requireOAuth2 playlists <- browseMyChannel 1000 findOrCreatePlaylist playlists t createPlaylists :: [Tournament] -> Client (Tournament -> Playlist) createPlaylists [] = return (M.empty M.!) createPlaylists ts = do requireOAuth2 playlists <- browseMyChannel 1000 findOrCreatePlaylists playlists ts deletePlaylist :: YouTubeId -> Client Bool deletePlaylist pId = do requireOAuth2 delete "/playlists" [ ("id", pId) ] findChannel :: String -> Client Channel findChannel name = firstChannel <$> get "/channels" parameters where parameters = [ ("part", "id,contentDetails") , ("forUsername", name ) ] insertVideo :: Video -> Int -> Playlist -> Client Success insertVideo v pos pl = do requireOAuth2 post "/playlistItems" parameters body where parameters = [ ("part", "snippet") ] body = Just (PlaylistItem "" vId pId pos) vId = videoId v pId = playlistId pl listPlaylist :: YouTubeId -> Int -> Client Videos listPlaylist pId count = do requireOAuth2 listPlaylistVideosIds pId count >>= listVideos where listPlaylistVideosIds i c = extractVideosIds <$> listPlaylistContent i c extractVideosIds = map playlistItemVideoId . toList listPlaylistContent :: YouTubeId -> PageSize -> Client PlaylistContent listPlaylistContent pId = getMany "/playlistItems" parameters where part = "contentDetails,snippet" parameters = [ ("part" , part) , ("playlistId", pId ) ] listVideos :: [YouTubeId] -> Client Videos listVideos vIds = toList <$> listVideosBatch (take 50 vIds) (drop 50 vIds) listVideosBatch :: [YouTubeId] -> [YouTubeId] -> Client (Items Video) listVideosBatch [] _ = return mempty listVideosBatch ids otherIds = do let part = "contentDetails,snippet" parameters = [ ("part", part ) , ("id", intercalate "," ids) ] batch <- get "/videos" parameters mappend batch <$> listVideosBatch (take 50 otherIds) (drop 50 otherIds) findMyChannel :: Client Channel findMyChannel = firstChannel <$> get "/channels" parameters where parameters = [ ("part", "id,contentDetails"), ("mine", "true") ] firstChannel :: Items Channel -> Channel firstChannel (Items cs) = head cs listChannelPlaylists :: YouTubeId -> PageSize -> Client Playlists listChannelPlaylists cId = getMany "/playlists" parameters where part = "contentDetails,snippet" parameters = [ ("part" , part) , ("channelId" , cId ) ] findOrCreatePlaylists :: [Playlist] -> [Tournament] -> Client (Tournament -> Playlist) findOrCreatePlaylists _ [] = return (\_ -> error "no tournament") findOrCreatePlaylists ps ts = ((M.!) . M.fromList) <$> mapM (\t -> (,) t <$> findOrCreatePlaylist ps t) ts findOrCreatePlaylist :: [Playlist] -> Tournament -> Client Playlist findOrCreatePlaylist ps tournament = do let previous = find (samePlaylist playlist) ps case previous of Just found -> return found Nothing -> post "/playlists" parameters body where parameters = [ ("part", "contentDetails,snippet,status") ] body = Just playlist where playlist = mkPlaylist tournament samePlaylist :: Playlist -> Playlist -> Bool samePlaylist p1 p2 = playlistTags p1 == playlistTags p2 mkPlaylist :: Tournament -> Playlist mkPlaylist tournament = Playlist "" title description tags where title = tournamentName tournament description = tournamentURL tournament tag = hashURL $ tournamentURL tournament tags = Tags [tag]
ptitfred/ftv-vods
src/YouTube/Services.hs
bsd-3-clause
4,534
0
13
1,067
1,283
667
616
105
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# OPTIONS_HADDOCK -ignore-exports #-} -- | A simple OAuth2 Haskell binding. (This is supposed to be -- independent of the http client used.) module Network.OAuth.OAuth2.Internal where import Data.Aeson import Data.Aeson.Types import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.Maybe import Data.Text.Encoding import Data.Text (Text) import GHC.Generics import URI.ByteString import Lens.Micro import Lens.Micro.Extras import Network.HTTP.Conduit as C import Control.Monad.Catch import qualified Network.HTTP.Types as H -------------------------------------------------- -- * Data Types -------------------------------------------------- -- | Query Parameter Representation data OAuth2 = OAuth2 { oauthClientId :: Text , oauthClientSecret :: Text , oauthOAuthorizeEndpoint :: URI , oauthAccessTokenEndpoint :: URI , oauthCallback :: Maybe (URI) } deriving (Show, Eq) newtype AccessToken = AccessToken { atoken :: Text } deriving (Show, FromJSON, ToJSON) newtype RefreshToken = RefreshToken { rtoken :: Text } deriving (Show, FromJSON, ToJSON) newtype IdToken = IdToken { idtoken :: Text } deriving (Show, FromJSON, ToJSON) newtype ExchangeToken = ExchangeToken { extoken :: Text } deriving (Show, FromJSON, ToJSON) -- | The gained Access Token. Use @Data.Aeson.decode@ to -- decode string to @AccessToken@. The @refreshToken@ is -- special in some cases, -- e.g. <https://developers.google.com/accounts/docs/OAuth2> data OAuth2Token = OAuth2Token { accessToken :: AccessToken , refreshToken :: Maybe RefreshToken , expiresIn :: Maybe Int , tokenType :: Maybe Text , idToken :: Maybe IdToken } deriving (Show, Generic) -- | Parse JSON data into 'OAuth2Token' instance FromJSON OAuth2Token where parseJSON = (genericParseJSON defaultOptions { fieldLabelModifier = camelTo2 '_' }) instance ToJSON OAuth2Token where toEncoding = (genericToEncoding defaultOptions { fieldLabelModifier = camelTo2 '_' }) -------------------------------------------------- -- * Types Synonym -------------------------------------------------- -- | Is either 'Left' containing an error or 'Right' containg a result type OAuth2Result a = Either BSL.ByteString a -- | type synonym of post body content type PostBody = [(BS.ByteString, BS.ByteString)] type QueryParams = [(BS.ByteString, BS.ByteString)] -------------------------------------------------- -- * URLs -------------------------------------------------- -- | Prepare the authorization URL. Redirect to this URL -- asking for user interactive authentication. authorizationUrl :: OAuth2 -> URI authorizationUrl oa = over (queryL . queryPairsL) (\l -> l ++ queryParts) (oauthOAuthorizeEndpoint oa) where queryParts = catMaybes [ Just ("client_id", encodeUtf8 $ oauthClientId oa) , Just ("response_type", "code") , fmap ("redirect_uri",) (fmap serializeURIRef' $ oauthCallback oa) ] -- | Prepare the URL and the request body query for fetching an access token. accessTokenUrl :: OAuth2 -> ExchangeToken -- ^ access code gained via authorization URL -> (URI, PostBody) -- ^ access token request URL plus the request body. accessTokenUrl oa code = accessTokenUrl' oa code (Just "authorization_code") -- | Prepare the URL and the request body query for fetching an access token, with -- optional grant type. accessTokenUrl' :: OAuth2 -> ExchangeToken -- ^ access code gained via authorization URL -> Maybe Text -- ^ Grant Type -> (URI, PostBody) -- ^ access token request URL plus the request body. accessTokenUrl' oa code gt = (uri, body) where uri = oauthAccessTokenEndpoint oa body = catMaybes [ Just ("code", encodeUtf8 $ extoken code) , fmap (("redirect_uri",) . serializeURIRef') $ oauthCallback oa , fmap (("grant_type",) . encodeUtf8) gt ] -- | Using a Refresh Token. Obtain a new access token by -- sending a refresh token to the Authorization server. refreshAccessTokenUrl :: OAuth2 -> RefreshToken -- ^ refresh token gained via authorization URL -> (URI, PostBody) -- ^ refresh token request URL plus the request body. refreshAccessTokenUrl oa token = (uri, body) where uri = oauthAccessTokenEndpoint oa body = [ ("grant_type", "refresh_token") , ("refresh_token", encodeUtf8 $ rtoken token) ] -- | For `GET` method API. appendAccessToken :: URIRef a -- ^ Base URI -> AccessToken -- ^ Authorized Access Token -> URIRef a -- ^ Combined Result appendAccessToken uri t = over (queryL . queryPairsL) (\query -> query ++ (accessTokenToParam t)) uri -- | Create 'QueryParams' with given access token value. accessTokenToParam :: AccessToken -> [(BS.ByteString, BS.ByteString)] accessTokenToParam t = [("access_token", encodeUtf8 $ atoken t)] appendQueryParams :: [(BS.ByteString, BS.ByteString)] -> URIRef a -> URIRef a appendQueryParams params = over (queryL . queryPairsL) (params ++ ) uriToRequest :: MonadThrow m => URI -> m Request uriToRequest uri = do ssl <- case (view (uriSchemeL . schemeBSL) uri) of "http" -> return False "https" -> return True s -> throwM $ InvalidUrlException (show uri) ("Invalid scheme: " ++ show s) let query = fmap (\(a, b) -> (a, Just b)) (view (queryL . queryPairsL) uri) hostL = (authorityL . _Just . authorityHostL . hostBSL) portL = (authorityL . _Just . authorityPortL . _Just . portNumberL) defaultPort = (if ssl then 443 else 80) :: Int req = (setQueryString query) $ defaultRequest { secure = ssl, path = (view pathL uri) } req2 = (over hostLens . maybe id const . preview hostL) uri req req3 = (over portLens . maybe (\_ -> defaultPort) const . preview portL) uri req2 return $ req3 requestToUri :: Request -> URI requestToUri req = URI (Scheme (if secure req then "https" else "http")) (Just (Authority Nothing (Host $ host req) (Just $ Port $ port req))) (path req) (Query $ H.parseSimpleQuery $ queryString req) Nothing hostLens :: Lens' Request BS.ByteString hostLens f req = f (C.host req) <&> \h' -> req { C.host = h' } {-# INLINE hostLens #-} portLens :: Lens' Request Int portLens f req = f (C.port req) <&> \p' -> req { C.port = p' } {-# INLINE portLens #-}
reactormonk/hoauth2
src/Network/OAuth/OAuth2/Internal.hs
bsd-3-clause
6,949
0
16
1,713
1,552
876
676
112
4
--------------------------------------------------------- -- -- Module : ErrorHandling -- Copyright : Bartosz Wójcik (2010) -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : Unstable -- Portability : portable -- -- Error handling data structures, functions, etc. --------------------------------------------------------- -- | Provides data types and basic functions allowing better and direct error handling. module Haslo.ErrorHandling (module Control.Monad.Error ,module Haslo.BasicType ,ValidationError (..) ,ValidMonad ) where import Control.Monad.Error.Class import Control.Monad.Error import Haslo.BasicType import Haslo.InstalmentPlan import Text.PrettyShow import Data.Time (Day ,fromGregorian) -- | Error handlig data type. data ValidationError = -- | Instalment discrepancy: -- Instalment amount, Repayment, Interest paid InstalmentDiscrepancy !Amount !Amount !Amount -- | Incorect interest: -- Principal before, Late interest before, Interest calculated (incorectly), -- Interest rate | IPLInterest !Amount !Interest !Interest !Rate -- | Simple follow up interest mismatch (a1 + a2 - a3 /= a4): -- Error description, a1, a2, a3, a4 | FollowUpInterestError String !Interest !Interest !Amount !Interest -- | Simple follow up mismatch (a1 - a /= a2): -- Error description, a1, a, a2 | FollowUpError String !Amount !Amount !Amount -- | Simpler follow up mismatch (a /= b): -- Error description, a, b | SimplerFollowUpError String !Amount !Amount -- | Deffered interest cannot be paid. | NotPaidDefferedInterest !Interest InstalmentPlan -- | Capital doesn't amortize. This is due to rounding error if happens. | NotAmortized !Amount InstalmentPlan | OtherError String -- Any error can occur independently before and after financing. -- Errors after financing usually are linked to date. -- | FinancingError Day ValidationError -- | We make ValidationError an instance of the Error class -- to be able to throw it as an exception. instance Error ValidationError where noMsg = OtherError "(!)" strMsg s = OtherError s instance Show ValidationError where show (InstalmentDiscrepancy a p iP) = "Instalment discrepancy:\ \instalment amount /= repayment + interest paid (" ++ (showAmtWithLen 8 a) ++ "/=" ++ (showAmtWithLen 8 p) ++ "+" ++ (showAmtWithLen 8 iP) ++ ")" show (IPLInterest p iL i r) = "IPL interest discrepancy: \ \ recalculated interest=" ++ show iR ++ ", given interest=" ++ show i ++ " (principal:" ++ showAmtWithLen 8 p ++ " (late interest:" ++ showWithLenDec 11 6 iL ++ " (interest rate:" ++ show r ++ ")" where iR = (fromIntegral p + iL) * r show (FollowUpInterestError msg a1 a2 a3 a4) = msg ++ show (a1 / 100) ++ " - " ++ show (a2 / 100) ++ " + " ++ showAmtWithLen 8 a3 ++ " /= " ++ show (a4 / 100) show (FollowUpError msg a1 a a2) = msg ++ showAmtWithLen 8 a1 ++ " - " ++ showAmtWithLen 8 a ++ " /= " ++ showAmtWithLen 8 a2 show (SimplerFollowUpError msg a b) = msg ++ showAmtWithLen 8 a ++ " /= " ++ showAmtWithLen 8 b show (NotPaidDefferedInterest iL ip) = "Deferred interest not paid off. Remains:" ++ show (iL / 100) ++ " " ++ show ip show (NotAmortized c ip) = "Principal doesn't amortize fully. Remains:" ++ showAmtWithLen 8 c ++ " " ++ show ip show (OtherError msg) = msg -- show (FinancingError d err) = show d ++ " " ++ show err maybeShow Nothing = "" maybeShow (Just a) = show a ++ " " -- | Monad wrapping error message or correct value. Broadly used. type ValidMonad = Either ValidationError --errMsg moduleName functionName msg = throwError $ OtherError $ -- moduleName ++ " " ++ -- functionName ++ " " ++ -- msg {-errDate :: Day -> ValidMonad a -> ValidMonad a errDate d (Left (FollowUpError w x y z _)) = Left $ FollowUpError w x y z (Just d) errDate d (Left (InstalmentDiscrepancy w x y z _)) = Left $ InstalmentDiscrepancy w x y z (Just d) errDate d (Left (IPLInterest w x y z _)) = Left $ IPLInterest w x y z (Just d) errDate _ x = x-} --data FinancingError = SFinancingError Day ValidationError -- | Allows adding date to any error of @ValidationError@ type. --liftDate :: MonadError ValidationError m => Day -- -> ValidationError -- -> m a --liftDate date err = throwError $ FinancingError date err
bartoszw/haslo
Haslo/ErrorHandling.hs
bsd-3-clause
5,551
41
27
2,080
731
395
336
92
1
{-# LANGUAGE FlexibleInstances, OverloadedStrings #-} module Data.Document ( FromDocument (..) , ToDocument (..) ) where import qualified Database.MongoDB as D import qualified Data.Time.Clock as T class FromDocument a where fromDocument :: D.Document -> a instance FromDocument a => FromDocument (a, T.UTCTime) where fromDocument d = (fromDocument d, D.timestamp $ D.typed $ D.valueAt "_id" d) class ToDocument a where toDocument :: a -> D.Document
RobinKrom/BtcExchanges
src/Data/Document.hs
bsd-3-clause
492
0
9
105
139
79
60
12
0
-- | Creating and rendering dot graphs that correspond to expression graphs. -- Each node has a single output and zero or more inputs. module Dot where import Language.Dot -- cabal install language-dot -- To generate an SVG file: -- -- dot -Tsvg file.dot -o file.svg -- -- Requires `graphviz` to be installed. -- | Identifier type ID = Int -- | Node Label (will be shown in the rendering) type Label = String -- | Input index (first input has index 0) type Input = Int -- | Node color (e.g. \"#AAA\") type Color = String -- | Number of inputs for a node type Arity = Int -- | Expression graph type ExpGraph = [Statement] -- Create a node node :: ID -> Label -> Color -> Arity -> ExpGraph node id lab col ar = return $ NodeStatement (NodeId (NameId (show id)) Nothing) [ AttributeSetValue (NameId "fillcolor") (NameId col) , AttributeSetValue (NameId "label") (NameId labStr) ] where labStr = concat [ "<" , "<TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"0\">" , "<TR>" , "<TD>" , lab , "</TD>" , concatMap mkInp [0 .. ar-1] , "</TR>" , "</TABLE>" , ">" ] mkInp inp = concat [ "<TD PORT=\"inp" , show inp , "\"> &nbsp;&nbsp;" , "</TD>" ] -- Create an edge edge :: ID -- ^ Downstream node -> Input -- ^ Input index of downstream node -> ID -- ^ Upstream node -> ExpGraph edge from inp to = [ NodeStatement ( NodeId (NameId (show from)) (Just (PortI (NameId ("inp" ++ show inp ++ ":c")) Nothing)) -- ":c" is a hack because the `Compass` type doesn't include a -- center direction ) [] , EdgeStatement [ENodeId DirectedEdge (NodeId (NameId (show to)) Nothing)] [] ] -- | Create a sub-graph subGraph :: ID -> ExpGraph -> ExpGraph subGraph id = return . SubgraphStatement . NewSubgraph (Just (StringId ("cluster_" ++ show id))) . (dotted :) where dotted = NodeStatement (NodeId (NameId "graph") Nothing) [ AttributeSetValue (NameId "style") (NameId "dotted")] setRoundedNode :: ExpGraph setRoundedNode = return $ NodeStatement (NodeId (NameId "node") Nothing) [ AttributeSetValue (NameId "style") (StringId "rounded,filled") , AttributeSetValue (NameId "shape") (NameId "box") ] setEdgeStyle :: ExpGraph setEdgeStyle = return $ NodeStatement (NodeId (NameId "edge") Nothing) [ AttributeSetValue (NameId "dir") (NameId "both") , AttributeSetValue (NameId "arrowtail") (NameId "dot") , AttributeSetValue (NameId "tailclip") (NameId "false") ] renderGraph :: ExpGraph -> FilePath -> IO () renderGraph g file = writeFile file $ renderDot $ Graph UnstrictGraph DirectedGraph Nothing $ concat [ setRoundedNode , setEdgeStyle , g ]
emilaxelsson/ag-graph
src/Dot.hs
bsd-3-clause
2,914
0
18
804
722
389
333
71
1
module SimulationDSL ( module SimulationDSL.Language.EquationsDescription , module SimulationDSL.Language.Exp , module SimulationDSL.Data.ExpType , module SimulationDSL.Data.Scalar , module SimulationDSL.Data.Vector3 , module SimulationDSL.Data.Array , module SimulationDSL.Interpreter.SimMachine , module SimulationDSL.Interpreter.Machine , module SimulationDSL.Compiler.SimMachine ) where import SimulationDSL.Data.ExpType import SimulationDSL.Data.Scalar import SimulationDSL.Data.Vector3 import SimulationDSL.Data.Array import SimulationDSL.Language.Exp hiding ( isIntegral, isSigma , containIntegral, containSigma ) import SimulationDSL.Language.EquationsDescription import SimulationDSL.Interpreter.SimMachine import SimulationDSL.Interpreter.Machine ( Machine, machineRegisterValue ) import SimulationDSL.Compiler.SimMachine
takagi/SimulationDSL
SimulationDSL/SimulationDSL.hs
bsd-3-clause
894
0
5
123
146
100
46
20
0
module Main where import Test.Hspec import Test.Hspec.HUnit import Test.HUnit import Data.Char import Data.Either import Data.Maybe import Chess import Chess.FEN import Control.Monad.Instances import Control.Monad assertNothing msg x = assertEqual msg Nothing x assertJust msg (Just x) = return () assertJust msg (Nothing) = assertFailure msg assertEmpty lst = assertEqual "" [] lst must_eq actual expected = assertEqual "" expected actual defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -" begpos = describe "on the beginposition" $ do it "should not allow moving a white piece in blacks turn" $ do (let brd = allowedMove "b1c3" defaultBoard in move "b2b3" brd `must_eq` Left WrongTurn) it "should not allow moving a nonexistent piece" $ do move "a3a4" defaultBoard `must_eq` Left NoPiece brutepos = "8/3k1p2/8/8/4NB2/8/1RP5/4K3 w - -" brutemoves = ["b2b1", "b2b3", "b2b4", "b2b5", "b2b6", "b2b7", "b2b8", "b2a2", "c2c3", "c2c4", "e1d1", "e1d2", "e1e2", "e1f2", "e1f1", "e4d2", "e4c3", "e4c5", "e4d6", "e4f6", "e4g5", "e4g3", "e4f2", "f4e3", "f4d2", "f4c1", "f4e5", "f4d6", "f4c7", "f4b8", "f4g5", "f4h6", "f4g3", "f4h2"] pieces = ["b2", "c2", "e4", "e1", "f4"] enumpos = let Just brd = fromFEN brutepos in describe "brute force" $ do it "should accept all moves" $ do assertEmpty (filter (\x -> not $ valid x brd) brutemoves) it "shouldn't accept any other move" $ do assertEmpty (filter (\x -> valid x brd) (mulMovesExcept pieces brutemoves)) pawnmovepos = "8/8/8/4P3/8/8/8/8 w - -" pawnCapturePosA = "8/8/8/8/8/2pppp2/2PPPP2/8 w - -" pawnCaptureAAllowed = ["c2d3", "d2c3", "d2e3", "e2d3", "e2f3", "f2e3"] piecesA = ["c2", "d2", "e2", "f2"] pawnCapturePosB = "8/8/8/8/8/2pppp2/2PPPP2/8 b - -" pawnCaptureBAllowed = ["d3c2", "c3d2", "e3d2", "d3e2", "f3e2", "e3f2"] piecesB = ["c3", "d3", "e3", "f3"] enPassantPos = "8/3p4/8/8/4P3/8/8/8 w - -" pawn = describe "a pawn" $ do it "can move forward" $ do let Just brd = fromFEN pawnmovepos in case move "e5e6" brd of Right a -> pieceAtStr "e5" a == Nothing && pieceAtStr "e6" a == Just (Piece White Pawn) Left a -> error (show a) it "can't move anywhere else" $ do let Just brd = fromFEN pawnmovepos in assertEmpty $ filter (\x -> valid x brd) (movesExcept "e5" ["e5e6"]) it "can capture pieces 1" $ do let Just brd = fromFEN pawnCapturePosA in assertEmpty $ filter (\x -> not $ valid x brd) pawnCaptureAAllowed it "can't do anything else 1" $ do let Just brd = fromFEN pawnCapturePosA in assertEmpty $ filter (\x -> valid x brd) (mulMovesExcept pieces pawnCaptureAAllowed) it "can capture pieces 2" $ do let Just brd = fromFEN pawnCapturePosB in assertEmpty $ filter (\x -> not $ valid x brd) pawnCaptureBAllowed it "can't do anything else 2" $ do let Just brd = fromFEN pawnCapturePosB in assertEmpty $ filter (\x -> valid x brd) (mulMovesExcept pieces pawnCaptureBAllowed) it "can do an enpassant capture" $ do let brd = allowedMoves ["e4e5", "d7d5", "e5d6"] (unsafeFromFEN enPassantPos) in pieceAt 3 4 brd == Nothing && pieceAt 3 5 brd /= Nothing rookmovepos = "8/8/8/4R3/8/8/8/8 w - -" rookPos = "e5" rookAllowed = ["e5e1", "e5e2", "e5e3", "e5e4", "e5e6", "e5e7", "e5e8", "e5a5", "e5b5", "e5c5", "e5d5", "e5f5", "e5g5", "e5h5"] rook = let Just brd = fromFEN rookmovepos in describe "a rook" $ do it "can move straight" $ do and $ map (\x -> valid x brd) rookAllowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept rookPos rookAllowed) knightpos = "8/8/8/3n4/8/8/8/8 b - -" knightallowed = ["d5c3", "d5b4", "d5b6", "d5c7", "d5e7", "d5f6", "d5f4", "d5e3"] knight = let Just brd = fromFEN knightpos in describe "a knight" $ do it "can move like a knight" $ do and $ map (\x -> valid x brd) knightallowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept "d5" knightallowed) bishoppos = "8/8/8/3b4/8/8/8/8 b - -" bishopallowed = ["d5a2", "d5b3", "d5c4", "d5e6", "d5f7", "d5g8", "d5h1", "d5g2", "d5f3", "d5e4", "d5c6", "d5b7", "d5a8"] bishop = let Just brd = fromFEN bishoppos in describe "a bishop" $ do it "can move diagonally" $ do and $ map (\x -> valid x brd) bishopallowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept "d5" bishopallowed) queenpos = "8/8/8/3q4/8/8/8/8 b - -" queenallowed = ["d5a2", "d5b3", "d5c4", "d5e6", "d5f7", "d5g8", "d5h1", "d5g2", "d5f3", "d5e4", "d5c6", "d5b7", "d5a8", "d5d1", "d5d2", "d5d3", "d5d4", "d5d6", "d5d7", "d5d8", "d5a5", "d5b5", "d5c5", "d5e5", "d5f5", "d5g5", "d5h5"] queen = let Just brd = fromFEN queenpos in describe "a queen" $ do it "can move" $ do and $ map (\x -> valid x brd) queenallowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept "d5" queenallowed) kingpos = "8/8/8/3k4/8/8/8/8 b - - 0 1" kingallowed = ["d5d4", "d5c4", "d5c5", "d5c6", "d5d6", "d5e6", "d5e5", "d5e4"] king = let Just brd = fromFEN kingpos in describe "a king" $ do it "can move exactly one square" $ do and $ map (\x -> valid x brd) kingallowed it "can't move anywhere else" $ do and $ map (\x -> not $ valid x brd) (movesExcept "d5" kingallowed) kingcastlepos = "8/8/8/8/8/8/8/4K2R w KQkq - " kingCastleInbetweenPos = "8/8/8/8/8/8/8/4K1NR w KQkq -" kingCastleCheckPosA = "8/8/8/5r2/8/8/8/4K2R w KQkq -" kingCastleCheckPosB = "8/8/8/6r1/8/8/8/4K2R w KQkq -" kingcastletest = describe "a kingside castle" $ do it "must be accepted" $ do let Just brd = fromFEN kingcastlepos in case move "O-O" brd of Right brd -> do pieceAt 4 0 brd `must_eq` Nothing pieceAt 7 0 brd `must_eq` Nothing pieceAt 5 0 brd `must_eq` Just (Piece White Rook) pieceAt 6 0 brd `must_eq` Just (Piece White King) Left err -> return () it "must not be allowed when piece inbetween" $ do let Just brd = fromFEN kingCastleInbetweenPos in not $ valid "O-O" brd it "must not be allowed when causes check" $ do let Just brd = fromFEN kingCastleCheckPosA in not $ valid "O-O" brd it "must not be allowed when check inbetween" $ do let Just brd = fromFEN kingCastleCheckPosA in not $ valid "O-O" brd queenCastlePos = "8/8/8/8/8/8/8/R3K3 w KQkq -" queenCastleInbetweenPos = "8/8/8/8/8/8/8/R2BK3 w KQkq -" queenCastleCheckPosA = "8/8/8/8/6b1/8/8/R3K3 w KQkq -" queenCastleCheckPosB = "8/8/8/8/5b2/8/8/R3K3 w KQkq -" queencastletest = describe "a queenside castle" $ do it "must be accepted" $ do let Just brd = fromFEN queenCastlePos in case move "O-O-O" brd of Right brd -> pieceAt 4 0 brd == Nothing && pieceAt 7 0 brd == Nothing && pieceAt 3 0 brd == Just (Piece White Rook) && pieceAt 2 0 brd == Just (Piece White King) Left err -> error $ show err it "must not be allowed when piece inbetween" $ do let Just brd = fromFEN queenCastleInbetweenPos in not $ valid "O-O-O" brd it "must not be allowed when causes check" $ do let Just brd = fromFEN queenCastleCheckPosA in not $ valid "O-O-O" brd it "must not be allowed when check inbetween" $ do let Just brd = fromFEN queenCastleCheckPosA in not $ valid "O-O-O" brd checkMoveA = "8/4r3/8/8/3p4/4P3/4K3/8 w - -" checkMoveB = "8/8/8/8/8/8/3KR2r/8 w - -" checkmoves = describe "moves causing check" $ do it "must not be allowed A" $ do let Just brd = fromFEN checkMoveA in move "e3d4" brd == Left CausesCheck it "must not be allowed B" $ do let Just brd = fromFEN checkMoveB in move "e2e3" brd == Left CausesCheck kingCastle = "8/p7/8/8/8/8/8/4K2R w KQkq -" queenCastle = "8/p7/8/8/8/8/8/R3K3 w KQkq -" castletest = describe "castling" $ do it "must not be allowed kingside when kingrook moved" $ do let brd = allowedMoves ["h1h2", "a7a6", "h2h1", "a6a5"] $ unsafeFromFEN kingCastle in move "O-O" brd `must_eq` Left InvalidMove it "must not be allowed queenside when queenrook has moved" $ do let brd = allowedMoves ["a1a2", "a7a6", "a2a1", "a6a5"] $ unsafeFromFEN queenCastle in move "O-O-O" brd `must_eq` Left InvalidMove it "must not be allowed when king has moved" $ do let brd = allowedMoves ["e1e2", "a7a6", "e2e1"] $ unsafeFromFEN kingCastle in move "O-O" brd `must_eq` Left InvalidMove pawnPromotionPos = "8/P7/8/8/8/8/8/8 w KQkq -" pawnPromotionCheck = "8/2K3Pr/8/8/8/8/8/8 w KQkq -" promotion = describe "promotion" $ do it "must be allowed when pawn on last row" $ do let Just brd = fromFEN pawnPromotionPos in case move "a7a8q" brd of Right b -> pieceAt 0 7 b == Just (Piece White Queen) && pieceAt 0 6 b == Nothing _ -> False it "must not be allowed when it causes check" $ do let Just brd = fromFEN pawnPromotionCheck in move "g7g8q" brd == Left CausesCheck fentest = describe "fen" $ do it "must be equal to input fen" $ do toFEN (unsafeFromFEN pawnPromotionPos) `must_eq` pawnPromotionPos toFEN (unsafeFromFEN pawnPromotionCheck) `must_eq` pawnPromotionCheck toFEN (unsafeFromFEN checkMoveA) `must_eq` checkMoveA toFEN (unsafeFromFEN checkMoveB) `must_eq` checkMoveB toFEN (unsafeFromFEN kingCastle) `must_eq` kingCastle toFEN (unsafeFromFEN queenCastle) `must_eq` queenCastle toFEN (unsafeFromFEN staleMatePos) `must_eq` staleMatePos toFEN (unsafeFromFEN queenCastleCheckPosA) `must_eq` queenCastleCheckPosA toFEN (unsafeFromFEN queenCastleCheckPosB) `must_eq` queenCastleCheckPosB toFEN (unsafeFromFEN enpasPos) `must_eq` enpasPos staleMatePos = "7k/8/6r1/4K3/6r1/3r1r2/8/8 w - -" stalematetest = describe "stalemate" $ do it "should be detected" $ do stalemate White $ unsafeFromFEN staleMatePos matePos = "3K2r1/6r1/8/8/8/8/8/2k5 w - -" matetest = describe "mate" $ do it "should be detected" $ do mate White $ unsafeFromFEN matePos enpasPos = "rnbqkbnr/ppp2ppp/8/3pP3/8/8/PPP1PPPP/RNBQKBNR w KQkq d6" enpasTest = describe "read enpassant" $ do it "Must accept e5d6 on rnbqkbnr/ppp2ppp/8/3pP3/8/8/PPP1PPPP/RNBQKBNR w KQkq d6" $ do let Just brd = fromFEN enpasPos in valid "e5d6" brd mulMovesExcept pcs lst = concat $ map (\x -> movesExcept x lst) pcs movesExcept pc lst = (filter (not . flip elem lst) (allMoves pc)) allMoves pc = [pc ++ [(chr (x+97)), (intToDigit (y+1))] | x<-[0..7], y<-[0..7]] tests = describe "The move validator" $ do begpos enumpos pawn rook knight bishop queen king kingcastletest queencastletest checkmoves castletest promotion fentest stalematetest matetest enpasTest unsafeFromFEN = fromJust . fromFEN main = do hspec tests valid a brd = case move a brd of Right brd -> True _ -> False allowedMove a brd = case move a brd of Right brd -> brd Left f -> error ("Move " ++ (show a) ++ " not allowed: " ++ (show f)) allowedMoves mvs brd = foldl (\x y -> allowedMove y x) brd mvs moveSequence brd mvs = foldM (flip moveVerbose) brd mvs moveVerbose mv brd = case move mv brd of Right b -> Right b Left er -> Left (mv, er)
ArnoVanLumig/chesshs
ChessTest.hs
bsd-3-clause
11,303
0
23
2,502
3,711
1,804
1,907
245
2
{-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.ByteString.Fusion -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Stream fusion for ByteStrings. -- -- See the paper /Stream Fusion: From Lists to Streams to Nothing at All/, -- Coutts, Leshchinskiy and Stewart, 2007. -- module Data.ByteString.Fusion ( -- A place holder for Stream Fusion ) where
markflorisson/hpack
testrepo/bytestring-0.9.1.9/Data/ByteString/Fusion.hs
bsd-3-clause
445
0
3
91
24
21
3
2
0
module SudokuParser(parseMatrix) where import Text.ParserCombinators.Parsec import Data.Char parseMatrix :: Parser [[Int]] parseMatrix = do result <- count 9 parseLine _ <- eof return result parseLine :: Parser [Int] parseLine = do result <- count 9 parseDigit _ <- eol return result parseDigit :: Parser Int parseDigit = do result <- digit return (digitToInt result) eol :: Parser String eol = try (string "\n\r") <|> try (string "\r\n") <|> string "\n" <|> string "\r" <?> "end of line"
jaapterwoerds/algorithmx
src/SudokuParser.hs
bsd-3-clause
576
0
11
164
190
93
97
23
1
module Game.Data( Game(..) ) where import GHC.Generics import Control.DeepSeq data Game = Game { gameExit :: Bool } deriving (Generic) instance NFData Game
Teaspot-Studio/gore-and-ash-game
src/client/Game/Data.hs
bsd-3-clause
176
0
8
43
54
32
22
8
0
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Criterion.Collection.Internal.Types ( Workload(..) , WorkloadGenerator , WorkloadMonad(..) , runWorkloadMonad , getRNG , DataStructure(..) , setupData , setupDataIO ) where ------------------------------------------------------------------------------ import Control.DeepSeq import Control.Monad.Reader import Data.Vector (Vector) import System.Random.MWC ------------------------------------------------------------------------------ -- Some thoughts on benchmarking modes -- -- * pre-fill data structure, test an operation workload without modifying the -- data structure, measure time for each operation -- -- ---> allows you to get fine-grained per-operation times with distributions -- -- * pre-fill data structure, get a bunch of work to do (cumulatively modifying -- the data structure), measure time per-operation OR for the whole batch and -- divide out -- -- -- Maybe it will look like this? -- > data MeasurementMode = PerBatch | PerOperation -- > data WorkloadMode = Pure | Mutating ------------------------------------------------------------------------------ newtype WorkloadMonad a = WM (ReaderT GenIO IO a) deriving (Monad, MonadIO) ------------------------------------------------------------------------------ runWorkloadMonad :: WorkloadMonad a -> GenIO -> IO a runWorkloadMonad (WM m) gen = runReaderT m gen ------------------------------------------------------------------------------ getRNG :: WorkloadMonad GenIO getRNG = WM ask ------------------------------------------------------------------------------ -- | Given an 'Int' representing \"input size\", a 'WorkloadGenerator' makes a -- 'Workload'. @Workload@s generate operations to prepopulate data structures -- with /O(n)/ data items, then generate operations on-demand to benchmark your -- data structure according to some interesting distribution. type WorkloadGenerator op = Int -> WorkloadMonad (Workload op) ------------------------------------------------------------------------------ data Workload op = Workload { -- | \"Setup work\" is work that you do to prepopulate a data structure -- to a certain size before testing begins. setupWork :: !(Vector op) -- | Given the number of operations to produce, 'genWorkload' spits out a -- randomly-distributed workload simulation to be used in the benchmark. -- -- | Some kinds of skewed workload distributions (the canonical example -- being \"frequent lookups for a small set of keys and infrequent -- lookups for the others\") need a certain minimum number of operations -- to be generated to be statistically valid, which only the -- 'WorkloadGenerator' would know how to decide. In these cases, you are -- free to return more than @N@ samples from 'genWorkload', and -- @criterion-collection@ will run them all for you. -- -- Otherwise, @criterion-collection@ is free to bootstrap your benchmark -- using as many sample points as it would take to make the results -- statistically relevant. , genWorkload :: !(Int -> WorkloadMonad (Vector op)) } ------------------------------------------------------------------------------ data DataStructure op = forall m . DataStructure { emptyData :: !(Int -> IO m) , runOperation :: !(m -> op -> IO m) } ------------------------------------------------------------------------------ setupData :: m -> (m -> op -> m) -> DataStructure op setupData e r = DataStructure (const $ return e) (\m o -> return $ r m o) ------------------------------------------------------------------------------ setupDataIO :: (Int -> IO m) -> (m -> op -> IO m) -> DataStructure op setupDataIO = DataStructure
cornell-pl/HsAdapton
weak-hashtables/benchmark/src/Criterion/Collection/Internal/Types.hs
bsd-3-clause
3,932
0
14
718
442
265
177
41
1
module EventLoop ( eventLoop ) where import Control.Monad (unless) import Graphics.UI.GLFW (Key (..), KeyState (..), Window, getKey, pollEvents, swapBuffers, windowShouldClose) -- | A simple rendering event loop which repeats the provided action until ESC is -- pressed or that a close event is created otherwise. eventLoop :: Window -> IO () -> IO () eventLoop window action = go where go :: IO () go = do pollEvents action swapBuffers window escState <- getKey window Key'Escape shouldClose <- windowShouldClose window unless (shouldClose || escState == KeyState'Pressed) go
psandahl/outdoor-terrain
src/EventLoop.hs
bsd-3-clause
754
0
12
264
161
86
75
16
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TupleSections #-} module Language.Haskell.Liquid.Bare.DataType ( makeConTypes , makeTyConEmbeds , dataConSpec , meetDataConSpec ) where import DataCon import TyCon import Var import Control.Applicative ((<$>)) import Data.Maybe import Data.Monoid import qualified Data.List as L import qualified Data.HashMap.Strict as M import Language.Fixpoint.Misc (errorstar) import Language.Fixpoint.Types (Symbol, TCEmb, meet) import Language.Haskell.Liquid.GHC.Misc (symbolTyVar) import Language.Haskell.Liquid.Types.PredType (dataConPSpecType) import Language.Haskell.Liquid.Types.RefType (mkDataConIdsTy, ofType, rApp, rVar, uPVar) import Language.Haskell.Liquid.Types import Language.Haskell.Liquid.Misc (mapSnd) import Language.Haskell.Liquid.Types.Variance import Language.Haskell.Liquid.WiredIn import qualified Language.Haskell.Liquid.Measure as Ms import Language.Haskell.Liquid.Bare.Env import Language.Haskell.Liquid.Bare.Lookup import Language.Haskell.Liquid.Bare.OfType ----------------------------------------------------------------------- -- Bare Predicate: DataCon Definitions -------------------------------- ----------------------------------------------------------------------- makeConTypes (name,spec) = inModule name $ makeConTypes' (Ms.dataDecls spec) (Ms.dvariance spec) makeConTypes' :: [DataDecl] -> [(LocSymbol, [Variance])] -> BareM ([(TyCon, TyConP)], [[(DataCon, Located DataConP)]]) makeConTypes' dcs vdcs = unzip <$> mapM (uncurry ofBDataDecl) (group dcs vdcs) where group ds vs = merge (L.sort ds) (L.sortBy (\x y -> compare (fst x) (fst y)) vs) merge (d:ds) (v:vs) | tycName d == fst v = (Just d, Just v) : merge ds vs | tycName d < fst v = (Just d, Nothing) : merge ds (v:vs) | otherwise = (Nothing, Just v) : merge (d:ds) vs merge [] vs = ((Nothing,) . Just) <$> vs merge ds [] = ((,Nothing) . Just) <$> ds dataConSpec :: [(DataCon, DataConP)]-> [(Var, (RType RTyCon RTyVar RReft))] dataConSpec dcs = concatMap mkDataConIdsTy [(dc, dataConPSpecType dc t) | (dc, t) <- dcs] meetDataConSpec xts dcs = M.toList $ L.foldl' upd dcm xts where dcm = M.fromList $ dataConSpec dcs upd dcm (x, t) = M.insert x (maybe t (meet t) (M.lookup x dcm)) dcm ofBDataDecl :: Maybe DataDecl -> (Maybe (LocSymbol, [Variance])) -> BareM ((TyCon, TyConP), [(DataCon, Located DataConP)]) ofBDataDecl (Just (D tc as ps ls cts _ sfun)) maybe_invariance_info = do πs <- mapM ofBPVar ps tc' <- lookupGhcTyCon tc cts' <- mapM (ofBDataCon lc lc' tc' αs ps ls πs) cts let tys = [t | (_, dcp) <- cts', (_, t) <- tyArgs dcp] let initmap = zip (uPVar <$> πs) [0..] let varInfo = L.nub $ concatMap (getPsSig initmap True) tys let defaultPs = varSignToVariance varInfo <$> [0 .. (length πs - 1)] let (tvarinfo, pvarinfo) = f defaultPs return ((tc', TyConP αs πs ls tvarinfo pvarinfo sfun), (mapSnd (Loc lc lc') <$> cts')) where αs = RTV . symbolTyVar <$> as n = length αs lc = loc tc lc' = locE tc f defaultPs = case maybe_invariance_info of {Nothing -> ([], defaultPs); Just (_,is) -> (take n is, if null (drop n is) then defaultPs else (drop n is))} varSignToVariance varsigns i = case filter (\p -> fst p == i) varsigns of [] -> Invariant [(_, b)] -> if b then Covariant else Contravariant _ -> Bivariant ofBDataDecl Nothing (Just (tc, is)) = do tc' <- lookupGhcTyCon tc return ((tc', TyConP [] [] [] tcov tcontr Nothing), []) where (tcov, tcontr) = (is, []) ofBDataDecl Nothing Nothing = errorstar $ "Bare.DataType.ofBDataDecl called on invalid inputs" getPsSig m pos (RAllT _ t) = getPsSig m pos t getPsSig m pos (RApp _ ts rs r) = addps m pos r ++ concatMap (getPsSig m pos) ts ++ concatMap (getPsSigPs m pos) rs getPsSig m pos (RVar _ r) = addps m pos r getPsSig m pos (RAppTy t1 t2 r) = addps m pos r ++ getPsSig m pos t1 ++ getPsSig m pos t2 getPsSig m pos (RFun _ t1 t2 r) = addps m pos r ++ getPsSig m pos t2 ++ getPsSig m (not pos) t1 getPsSig m pos (RHole r) = addps m pos r getPsSig _ _ z = error $ "getPsSig" ++ show z getPsSigPs m pos (RProp _ (RHole r)) = addps m pos r getPsSigPs m pos (RProp _ t) = getPsSig m pos t addps m pos (MkUReft _ ps _) = (flip (,)) pos . f <$> pvars ps where f = fromMaybe (error "Bare.addPs: notfound") . (`L.lookup` m) . uPVar -- TODO:EFFECTS:ofBDataCon ofBDataCon l l' tc αs ps ls πs (c, xts) = do c' <- lookupGhcDataCon c ts' <- mapM (mkSpecType' l ps) ts let cs = map ofType (dataConStupidTheta c') let t0 = rApp tc rs (rPropP [] . pdVarReft <$> πs) mempty return $ (c', DataConP l αs πs ls cs (reverse (zip xs ts')) t0 l') where (xs, ts) = unzip xts rs = [rVar α | RTV α <- αs] makeTyConEmbeds (mod, spec) = inModule mod $ makeTyConEmbeds' $ Ms.embeds spec makeTyConEmbeds' :: TCEmb (Located Symbol) -> BareM (TCEmb TyCon) makeTyConEmbeds' z = M.fromList <$> mapM tx (M.toList z) where tx (c, y) = (, y) <$> lookupGhcTyCon c
abakst/liquidhaskell
src/Language/Haskell/Liquid/Bare/DataType.hs
bsd-3-clause
5,429
0
15
1,368
2,143
1,132
1,011
103
6
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeOperators #-} module Plowtech.Service.Types where import Control.Applicative import Control.Lens import Control.Lens.TH import Control.Monad (mzero) import Control.Monad.Trans.Either import Data.Aeson import Data.Map (Map()) import qualified Data.Map as Map import Data.Maybe import Data.Proxy import Data.Serialize hiding (encode, decode, Get) import Data.Text (Text) import Data.Vinyl import Data.Vinyl.Aeson import Data.Vinyl.Lens import Data.Vinyl.Functor (Const(..), Identity(..), Compose(..)) import GHC.TypeLits import Plowtech.Records.FullTagKey import Servant.API import Data.Vinyl.TypeLevel import Data.Master.Template import Data.Master.Examples (Generatable(..)) -- Orphan instances :\ instance (Eq (f (g x))) => Eq (Compose f g x) where (Compose a) == (Compose b) = a == b instance (Show (f (g x))) => Show (Compose f g x) where show (Compose x) = show x instance (Bounded a) => Bounded (Maybe a) where minBound = Nothing maxBound = Just maxBound instance (Enum a) => Enum (Maybe a) where toEnum x = if x == 0 then Nothing else Just $ toEnum $ x -1 fromEnum Nothing = 0 fromEnum (Just x) = fromEnum x + 1 -- | A newtype for JSON-encoding FullTagKey records newtype FullTagKeyJSON = FullTagKeyJSON { _fullTagKeyJSON :: FullTagKey } fullTagKeyJSON :: Iso' FullTagKey FullTagKeyJSON fullTagKeyJSON = iso FullTagKeyJSON _fullTagKeyJSON instance Checkable FullTagKeyJSON where type Template FullTagKeyJSON = FullTagKeyTemplateJSON type Result FullTagKeyJSON = FullTagKeyValidationJSON checkTemplate template candidate = checkTemplate (template ^. from fullTagKeyTemplateJSON) (candidate ^. from fullTagKeyJSON) ^. fullTagKeyValidationJSON success _ = success (Proxy :: Proxy FullTagKeyValidation) . (^. from fullTagKeyValidationJSON) newtype FullTagKeyValidationJSON = FullTagKeyValidationJSON { _fullTagKeyValidationJSON :: FullTagKeyValidation } fullTagKeyValidationJSON :: Iso' FullTagKeyValidation FullTagKeyValidationJSON fullTagKeyValidationJSON = iso FullTagKeyValidationJSON _fullTagKeyValidationJSON newtype FullTagKeyExamplesJSON = FullTagKeyExamplesJSON { _fullTagKeyExamplesJSON :: FullTagKeyExamples } deriving instance (RecAll (Compose [] FullTagKeyAttr) FullTagKeyFields Show) => Show FullTagKeyExamplesJSON fullTagKeyExamplesJSON :: Iso' FullTagKeyExamples FullTagKeyExamplesJSON fullTagKeyExamplesJSON = iso FullTagKeyExamplesJSON _fullTagKeyExamplesJSON instance Generatable FullTagKeyJSON where type Examples FullTagKeyJSON = FullTagKeyExamplesJSON generateExamples _ template = generateExamples (Proxy :: Proxy FullTagKey) (template ^. from fullTagKeyTemplateJSON) ^. fullTagKeyExamplesJSON instance FromJSON FullTagKeyExamplesJSON where parseJSON = (FullTagKeyExamplesJSON <$>) . recordFromJSON instance ToJSON FullTagKeyExamplesJSON where toJSON = recordToJSON . _fullTagKeyExamplesJSON -- | Fields for the Named record type family NamedField a (field :: Symbol) where NamedField a "name" = Text NamedField a "record" = a -- | Attribute type for the Named record newtype NamedAttr a (field :: Symbol) = NamedAttr { _namedAttr :: NamedField a field } deriving instance (Eq (NamedField a field)) => Eq (NamedAttr a field) namedAttr :: Iso' (NamedField a field) (NamedAttr a field) namedAttr = iso NamedAttr _namedAttr -- | The Named record type Named a = Rec (NamedAttr a) '["name", "record"] -- | A newtype for JSON-encoding Named records newtype NamedJSON a = NamedJSON { _namedJSON :: Named a } deriving instance (Eq (Named a)) => Eq (NamedJSON a) namedJSON :: Iso' (Named a) (NamedJSON a) namedJSON = iso NamedJSON _namedJSON -- | A newtype for JSON-encoding FullTagKeyTemplate records newtype FullTagKeyTemplateJSON = FullTagKeyTemplateJSON { _fullTagKeyTemplateJSON :: FullTagKeyTemplate } fullTagKeyTemplateJSON :: Iso' FullTagKeyTemplate FullTagKeyTemplateJSON fullTagKeyTemplateJSON = iso FullTagKeyTemplateJSON _fullTagKeyTemplateJSON instance Eq FullTagKeyTemplateJSON where (FullTagKeyTemplateJSON a) == (FullTagKeyTemplateJSON b) = (eqReqOn (Proxy :: Proxy "pc") a b) && (eqReqOn (Proxy :: Proxy "slave_id") a b) && (eqReqOn (Proxy :: Proxy "tag_name") a b) && (eqReqOn (Proxy :: Proxy "index") a b) eqReqOn :: (RElem r FullTagKeyFields (RIndex r FullTagKeyFields), (Eq (FullTagKeyField r))) => sing r -> Rec (TemplatesFor Normalized Disjunction FullTagKeyAttr) FullTagKeyFields -> Rec (TemplatesFor Normalized Disjunction FullTagKeyAttr) FullTagKeyFields -> Bool eqReqOn rl template1 template2 = (getCompose $ template1 ^. (rlens rl)) == (getCompose $ template2 ^. (rlens rl)) -- | The Servant API for validation type FullTagKeyValidatorAPI = "templates" :> Get '[JSON] [NamedJSON (Map Text (Has FullTagKeyTemplateJSON))] :<|> "templates" :> ReqBody '[JSON] (NamedJSON (Map Text (Has FullTagKeyTemplateJSON))) :> Post '[JSON] () :<|> "templates" :> Capture "name" Text :> Get '[JSON] (Map Text (Has FullTagKeyTemplateJSON)) :<|> "validate" :> Capture "name" Text :> ReqBody '[JSON] (Map Text FullTagKeyJSON) :> Post '[JSON] (Map Text (MapCheckResult FullTagKeyTemplateJSON FullTagKeyJSON FullTagKeyValidationJSON)) :<|> "examples" :> Capture "name" Text :> Get '[JSON] (Map Text (Has FullTagKeyExamplesJSON)) :<|> Raw instance ToJSON FullTagKeyJSON where toJSON = recordToJSON . _fullTagKeyJSON instance FromJSON FullTagKeyJSON where parseJSON = (FullTagKeyJSON <$>) . recordFromJSON instance (ToJSON a) => ToJSON (NamedJSON a) where toJSON = recordToJSON . _namedJSON instance (FromJSON a) => FromJSON (NamedJSON a) where parseJSON = (NamedJSON <$>) . recordFromJSON instance ToJSON FullTagKeyTemplateJSON where toJSON = recordToJSON . _fullTagKeyTemplateJSON instance FromJSON FullTagKeyTemplateJSON where parseJSON = (FullTagKeyTemplateJSON <$>) . recordFromJSON instance ToJSON FullTagKeyValidationJSON where toJSON = recordToJSON . _fullTagKeyValidationJSON instance FromJSON FullTagKeyValidationJSON where parseJSON = (FullTagKeyValidationJSON <$>) . recordFromJSON instance (ToJSON (NamedField a field)) => ToJSON (NamedAttr a field) where toJSON = toJSON . _namedAttr instance (FromJSON (NamedField a field)) => FromJSON (NamedAttr a field) where parseJSON = (NamedAttr <$>) . parseJSON instance (FromJSON a, ToJSON a) => Serialize (NamedJSON a) where put = put . encode get = get >>= maybe mzero return . decode -- | The proxy for the validation Servant API type fullTagKeyValidatorAPI :: Proxy FullTagKeyValidatorAPI fullTagKeyValidatorAPI = Proxy
plow-technologies/template-service
src/Plowtech/Service/Types.hs
bsd-3-clause
7,042
0
24
1,194
1,877
1,021
856
123
1
module Data.LLVM.Types.Identifiers ( -- * Types Identifier, -- * Accessor identifierAsString, identifierContent, isAnonymousIdentifier, -- * Builders makeAnonymousLocal, makeLocalIdentifier, makeGlobalIdentifier, makeMetaIdentifier ) where import Control.DeepSeq import Data.Hashable import Data.Text ( Text, unpack, pack ) data Identifier = LocalIdentifier { _identifierContent :: !Text , _identifierHash :: !Int } | AnonymousLocalIdentifier { _identifierNumber :: !Int } | GlobalIdentifier { _identifierContent :: !Text , _identifierHash :: !Int } | MetaIdentifier { _identifierContent :: !Text , _identifierHash :: !Int } deriving (Eq, Ord) instance Show Identifier where show LocalIdentifier { _identifierContent = t } = '%' : unpack t show AnonymousLocalIdentifier { _identifierNumber = n } = '%' : show n show GlobalIdentifier { _identifierContent = t } = '@' : unpack t show MetaIdentifier { _identifierContent = t } = '!' : unpack t instance Hashable Identifier where hashWithSalt s (AnonymousLocalIdentifier n) = s `hashWithSalt` n hashWithSalt s i = s `hashWithSalt` _identifierHash i instance NFData Identifier where rnf AnonymousLocalIdentifier {} = () rnf i = _identifierContent i `seq` _identifierHash i `seq` () makeAnonymousLocal :: Int -> Identifier makeAnonymousLocal = AnonymousLocalIdentifier makeLocalIdentifier :: Text -> Identifier makeLocalIdentifier t = LocalIdentifier { _identifierContent = t , _identifierHash = hash t } makeGlobalIdentifier :: Text -> Identifier makeGlobalIdentifier t = GlobalIdentifier { _identifierContent = t , _identifierHash = hash t } makeMetaIdentifier :: Text -> Identifier makeMetaIdentifier t = MetaIdentifier { _identifierContent = t , _identifierHash = hash t } identifierAsString :: Identifier -> String identifierAsString (AnonymousLocalIdentifier n) = show n identifierAsString i = unpack (identifierContent i) identifierContent :: Identifier -> Text identifierContent (AnonymousLocalIdentifier n) = pack (show n) identifierContent i = _identifierContent i isAnonymousIdentifier :: Identifier -> Bool isAnonymousIdentifier AnonymousLocalIdentifier {} = True isAnonymousIdentifier _ = False
travitch/llvm-base-types
src/Data/LLVM/Types/Identifiers.hs
bsd-3-clause
2,587
0
9
717
581
316
265
68
1
module Main ( (|>) , (>>>) ) where import Operators ((|>), (>>>)) test :: [Int] -> Int test = foldr 1.0 (*) test2 :: a -> a -> ( a, a ) test2 = (,) (|>) :: a -> (a -> b) -> b (|>) v f = f v
hecrj/haskell-format
test/specs/operators/output.hs
bsd-3-clause
221
0
8
81
119
74
45
13
1
{-# LANGUAGE ScopedTypeVariables, TypeFamilies, TupleSections #-} module Fuml.Core where import qualified Data.Vector.Storable as VS import Numeric.LinearAlgebra import Data.List (nub) import Lens.Micro import Control.Monad.Identity data Weighted o = Weighted Double o -- |The result of running a predictive model data Predict p a = Predict { model :: p -- ^ the internal state of the model , predict :: Vector Double -> a -- ^ the prediction function } instance Functor (Predict p) where fmap f (Predict m predf) = Predict m (f . predf) newtype Supervisor m o p a = Supervisor { runSupervisor :: Maybe p -> [(Vector Double, o)] -> m (Predict p a) } instance Functor m => Functor (Supervisor m o p) where fmap f (Supervisor sf) = Supervisor $ \mp d -> fmap (fmap f) $ sf mp d -- | Helper function for running simple Supervisors in the Identity monad runSupervisor' :: Supervisor Identity o p a -- ^ the 'Supervisor' value -> [(Vector Double, o)] -- ^ the dataset -> Predict p a -- ^ the 'Predict' value runSupervisor' (Supervisor sf) = runIdentity . sf Nothing oneVsRest :: (Monad m, Eq a, Functor m) => Supervisor m Bool p b -> Supervisor m a [(a,p)] [(a,b)] oneVsRest subsuper = Supervisor $ \_ theData -> do let classes = nub $ map snd theData boolize c (v, c1) = (v, c == c1) train c = fmap (c,) $ runSupervisor subsuper Nothing $ map (boolize c) theData models <- mapM train classes return $ Predict (map (over _2 model) models) $ \v -> map (\(c,pr) -> (c, predict pr v)) models (~~) :: (a -> o) -> [a -> Double] -> [a] -> [(Vector Double, o)] fy ~~ fxs = let f w = (VS.fromList (map ($w) fxs) , fy w) in map f --prepare :: (a -> o) -> [a -> Double] -> [a] -> [(Vector Double, o)] --prepare fo fxs d = fo ~~ fxs $ d
diffusionkinetics/open
fuml/lib/Fuml/Core.hs
mit
1,869
0
15
474
665
358
307
33
1
-- HACKERRANK: Super Digit -- https://www.hackerrank.com/challenges/super-digit module Main where digits :: Integer -> [Integer] digits 0 = [] digits n = m : rest where m = mod n 10 rest = digits (div n 10) solve :: Integer -> Integer solve n = if n < 10 then n else solve $ sum $ digits n main :: IO () main = do nkStr <- getLine let (n:k:_) = map (read :: String -> Integer) $ words nkStr let input = sum (digits n) * k putStrLn $ show (solve input)
everyevery/programming_study
hackerrank/functional/super-digit/super-digit.hs
mit
516
0
13
156
209
106
103
13
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.DeviceFarm.ListProjects -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets information about projects. -- -- /See:/ <http://docs.aws.amazon.com/devicefarm/latest/APIReference/API_ListProjects.html AWS API Reference> for ListProjects. module Network.AWS.DeviceFarm.ListProjects ( -- * Creating a Request listProjects , ListProjects -- * Request Lenses , lpArn , lpNextToken -- * Destructuring the Response , listProjectsResponse , ListProjectsResponse -- * Response Lenses , lprsNextToken , lprsProjects , lprsResponseStatus ) where import Network.AWS.DeviceFarm.Types import Network.AWS.DeviceFarm.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | Represents a request to the list projects operation. -- -- /See:/ 'listProjects' smart constructor. data ListProjects = ListProjects' { _lpArn :: !(Maybe Text) , _lpNextToken :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListProjects' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lpArn' -- -- * 'lpNextToken' listProjects :: ListProjects listProjects = ListProjects' { _lpArn = Nothing , _lpNextToken = Nothing } -- | The projects\' ARNs. lpArn :: Lens' ListProjects (Maybe Text) lpArn = lens _lpArn (\ s a -> s{_lpArn = a}); -- | An identifier that was returned from the previous call to this -- operation, which can be used to return the next set of items in the -- list. lpNextToken :: Lens' ListProjects (Maybe Text) lpNextToken = lens _lpNextToken (\ s a -> s{_lpNextToken = a}); instance AWSRequest ListProjects where type Rs ListProjects = ListProjectsResponse request = postJSON deviceFarm response = receiveJSON (\ s h x -> ListProjectsResponse' <$> (x .?> "nextToken") <*> (x .?> "projects" .!@ mempty) <*> (pure (fromEnum s))) instance ToHeaders ListProjects where toHeaders = const (mconcat ["X-Amz-Target" =# ("DeviceFarm_20150623.ListProjects" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON ListProjects where toJSON ListProjects'{..} = object (catMaybes [("arn" .=) <$> _lpArn, ("nextToken" .=) <$> _lpNextToken]) instance ToPath ListProjects where toPath = const "/" instance ToQuery ListProjects where toQuery = const mempty -- | Represents the result of a list projects request. -- -- /See:/ 'listProjectsResponse' smart constructor. data ListProjectsResponse = ListProjectsResponse' { _lprsNextToken :: !(Maybe Text) , _lprsProjects :: !(Maybe [Project]) , _lprsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListProjectsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lprsNextToken' -- -- * 'lprsProjects' -- -- * 'lprsResponseStatus' listProjectsResponse :: Int -- ^ 'lprsResponseStatus' -> ListProjectsResponse listProjectsResponse pResponseStatus_ = ListProjectsResponse' { _lprsNextToken = Nothing , _lprsProjects = Nothing , _lprsResponseStatus = pResponseStatus_ } -- | If the number of items that are returned is significantly large, this is -- an identifier that is also returned, which can be used in a subsequent -- call to this operation to return the next set of items in the list. lprsNextToken :: Lens' ListProjectsResponse (Maybe Text) lprsNextToken = lens _lprsNextToken (\ s a -> s{_lprsNextToken = a}); -- | Information about the projects. lprsProjects :: Lens' ListProjectsResponse [Project] lprsProjects = lens _lprsProjects (\ s a -> s{_lprsProjects = a}) . _Default . _Coerce; -- | The response status code. lprsResponseStatus :: Lens' ListProjectsResponse Int lprsResponseStatus = lens _lprsResponseStatus (\ s a -> s{_lprsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-devicefarm/gen/Network/AWS/DeviceFarm/ListProjects.hs
mpl-2.0
4,938
0
13
1,149
765
456
309
94
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | -- Module : Test.AWS.S3 -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- module Test.AWS.S3 ( tests , fixtures ) where import Data.Time import Network.AWS.Prelude import Network.AWS.S3 import Test.AWS.Gen.S3 import Test.AWS.Prelude import Test.AWS.S3.Internal import Test.Tasty tests :: [TestTree] tests = [ objectKeyTests ] fixtures :: [TestTree] fixtures = [ testGroup "request" [ testDeleteObjects $ deleteObjects "bucketname" $ delete' & dObjects .~ [ objectIdentifier "sample1.text" , objectIdentifier "sample2.text" ] , testListMultipartUploads $ listMultipartUploads "foo-bucket" & lmuMaxUploads ?~ 3 ] , testGroup "response" [ testGetBucketReplicationResponse $ getBucketReplicationResponse 200 & gbrrsReplicationConfiguration ?~ (replicationConfiguration "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3" & rcRules .~ [ replicationRule "" Enabled (destination "arn:aws:s3:::exampletargetbucket") & rrId ?~ "rule1" ]) , testCopyObjectResponse $ copyObjectResponse 200 & corsCopyObjectResult ?~ (copyObjectResult & corETag ?~ ETag "\"9b2cf535f27731c974343645a3985328\"" & corLastModified ?~ $(mkTime "2009-10-28T22:32:00Z")) , testListPartsResponse $ listPartsResponse 200 & lprsBucket ?~ "example-bucket" & lprsKey ?~ "example-object" & lprsUploadId ?~ "XXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA" & lprsStorageClass ?~ Standard & lprsPartNumberMarker ?~ 1 & lprsNextPartNumberMarker ?~ 3 & lprsMaxParts ?~ 2 & lprsIsTruncated ?~ True & lprsInitiator ?~ (initiator & iId ?~ "arn:aws:iam::111122223333:user/some-user-11116a31-17b5-4fb7-9df5-b288870f11xx" & iDisplayName ?~ "umat-user-11116a31-17b5-4fb7-9df5-b288870f11xx") & lprsOwner ?~ (owner & oId ?~ "75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a" & oDisplayName ?~ "someName") & lprsParts .~ [ part & pPartNumber ?~ 2 & pLastModified ?~ $(mkTime "2010-11-10T20:48:34.000Z") & pETag ?~ "\"7778aef83f66abc1fa1e8477f296d394\"" & pSize ?~ 10485760 , part & pPartNumber ?~ 3 & pLastModified ?~ $(mkTime "2010-11-10T20:48:33.000Z") & pETag ?~ "\"aaaa18db4cc2f85cedef654fccc4a4x8\"" & pSize ?~ 10485760 ] -- FIXME: Has a JSON body, not XML, hence, serialiser error. -- , testGetBucketPolicyResponse $ -- getBucketPolicyResponse 200 -- & gbprPolicy ?~ "foo" ] ]
olorin/amazonka
amazonka-s3/test/Test/AWS/S3.hs
mpl-2.0
3,827
0
31
1,604
491
266
225
66
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Glacier.CompleteVaultLock -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- This operation completes the vault locking process by transitioning the -- vault lock from the 'InProgress' state to the 'Locked' state, which -- causes the vault lock policy to become unchangeable. A vault lock is put -- into the 'InProgress' state by calling InitiateVaultLock. You can obtain -- the state of the vault lock by calling GetVaultLock. For more -- information about the vault locking process, -- <http://docs.aws.amazon.com/amazonglacier/latest/dev/vault-lock.html Amazon Glacier Vault Lock>. -- -- This operation is idempotent. This request is always successful if the -- vault lock is in the 'Locked' state and the provided lock ID matches the -- lock ID originally used to lock the vault. -- -- If an invalid lock ID is passed in the request when the vault lock is in -- the 'Locked' state, the operation returns an 'AccessDeniedException' -- error. If an invalid lock ID is passed in the request when the vault -- lock is in the 'InProgress' state, the operation throws an -- 'InvalidParameter' error. -- -- /See:/ <http://docs.aws.amazon.com/amazonglacier/latest/dev/api-CompleteVaultLock.html AWS API Reference> for CompleteVaultLock. module Network.AWS.Glacier.CompleteVaultLock ( -- * Creating a Request completeVaultLock , CompleteVaultLock -- * Request Lenses , cvlAccountId , cvlVaultName , cvlLockId -- * Destructuring the Response , completeVaultLockResponse , CompleteVaultLockResponse ) where import Network.AWS.Glacier.Types import Network.AWS.Glacier.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | The input values for 'CompleteVaultLock'. -- -- /See:/ 'completeVaultLock' smart constructor. data CompleteVaultLock = CompleteVaultLock' { _cvlAccountId :: !Text , _cvlVaultName :: !Text , _cvlLockId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CompleteVaultLock' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cvlAccountId' -- -- * 'cvlVaultName' -- -- * 'cvlLockId' completeVaultLock :: Text -- ^ 'cvlAccountId' -> Text -- ^ 'cvlVaultName' -> Text -- ^ 'cvlLockId' -> CompleteVaultLock completeVaultLock pAccountId_ pVaultName_ pLockId_ = CompleteVaultLock' { _cvlAccountId = pAccountId_ , _cvlVaultName = pVaultName_ , _cvlLockId = pLockId_ } -- | The 'AccountId' value is the AWS account ID. This value must match the -- AWS account ID associated with the credentials used to sign the request. -- You can either specify an AWS account ID or optionally a single -- apos'-'apos (hyphen), in which case Amazon Glacier uses the AWS account -- ID associated with the credentials used to sign the request. If you -- specify your account ID, do not include any hyphens (apos-apos) in the -- ID. cvlAccountId :: Lens' CompleteVaultLock Text cvlAccountId = lens _cvlAccountId (\ s a -> s{_cvlAccountId = a}); -- | The name of the vault. cvlVaultName :: Lens' CompleteVaultLock Text cvlVaultName = lens _cvlVaultName (\ s a -> s{_cvlVaultName = a}); -- | The 'lockId' value is the lock ID obtained from a InitiateVaultLock -- request. cvlLockId :: Lens' CompleteVaultLock Text cvlLockId = lens _cvlLockId (\ s a -> s{_cvlLockId = a}); instance AWSRequest CompleteVaultLock where type Rs CompleteVaultLock = CompleteVaultLockResponse request = postJSON glacier response = receiveNull CompleteVaultLockResponse' instance ToHeaders CompleteVaultLock where toHeaders = const mempty instance ToJSON CompleteVaultLock where toJSON = const (Object mempty) instance ToPath CompleteVaultLock where toPath CompleteVaultLock'{..} = mconcat ["/", toBS _cvlAccountId, "/vaults/", toBS _cvlVaultName, "/lock-policy/", toBS _cvlLockId] instance ToQuery CompleteVaultLock where toQuery = const mempty -- | /See:/ 'completeVaultLockResponse' smart constructor. data CompleteVaultLockResponse = CompleteVaultLockResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CompleteVaultLockResponse' with the minimum fields required to make a request. -- completeVaultLockResponse :: CompleteVaultLockResponse completeVaultLockResponse = CompleteVaultLockResponse'
fmapfmapfmap/amazonka
amazonka-glacier/gen/Network/AWS/Glacier/CompleteVaultLock.hs
mpl-2.0
5,125
0
9
963
537
331
206
70
1
{-# LANGUAGE DeriveDataTypeable, CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Signal -- Copyright : (c) Andrea Rosatto -- : (c) Jose A. Ortega Ruiz -- : (c) Jochen Keil -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Signal handling, including DBUS when available -- ----------------------------------------------------------------------------- module Signal where import Data.Typeable (Typeable) import Control.Concurrent.STM import Control.Exception hiding (handle) import System.Posix.Signals import Graphics.X11.Xlib.Types (Position) #ifdef DBUS import DBus (IsVariant(..)) import Control.Monad ((>=>)) #endif import Plugins.Utils (safeHead) data WakeUp = WakeUp deriving (Show,Typeable) instance Exception WakeUp data SignalType = Wakeup | Reposition | ChangeScreen | Hide Int | Reveal Int | Toggle Int | TogglePersistent | Action Position deriving (Read, Show) #ifdef DBUS instance IsVariant SignalType where toVariant = toVariant . show fromVariant = fromVariant >=> parseSignalType #endif parseSignalType :: String -> Maybe SignalType parseSignalType = fmap fst . safeHead . reads -- | Signal handling setupSignalHandler :: IO (TMVar SignalType) setupSignalHandler = do tid <- newEmptyTMVarIO installHandler sigUSR2 (Catch $ updatePosHandler tid) Nothing installHandler sigUSR1 (Catch $ changeScreenHandler tid) Nothing return tid updatePosHandler :: TMVar SignalType -> IO () updatePosHandler sig = do atomically $ putTMVar sig Reposition return () changeScreenHandler :: TMVar SignalType -> IO () changeScreenHandler sig = do atomically $ putTMVar sig ChangeScreen return ()
tsiliakis/xmobar
src/Signal.hs
bsd-3-clause
1,955
0
10
436
392
217
175
35
1