code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Network.HTTPMock.WebServers.Scotty (startServer) where import ClassyPrelude import Control.Lens import Data.Default import Data.Conduit ( runResourceT , ($$)) import Data.Conduit.List (consume) import Data.Maybe (maybe) import Network.HTTP.Types ( Method(..) , notFound404 , ok200) import qualified Web.Scotty as S import Web.Scotty ( Options(..) , ActionM , ScottyM , text , header , status , notFound , scottyOpts) import qualified Network.Wai as W import Network.Wai.Handler.Warp ( Settings(settingsPort) , defaultSettings) import Network.HTTPMock.Interactions (getResponse) import Network.HTTPMock.Types startServer :: IORef HTTPMocker -> IO () startServer mockerR = do mocker <- readIORef mockerR let port = mocker ^. options . mockerPort scottyOpts (makeOpts port) $ scottyRoutes mockerR makeOpts :: Port -> Options makeOpts port = def { verbose = 0 , settings = defaultSettings { settingsPort = port } } scottyRoutes :: IORef HTTPMocker -> ScottyM () scottyRoutes mockerR = do notFound $ do mocker <- liftIO $ readIORef mockerR req <- liftIO . convertToRequest =<< S.request handleMatch mockerR req -- use of mockerR doesn't make sense now, but state will mutate in getResponse eventually handleMatch mockerR req = do mocker <- liftIO $ readIORef mockerR let (mResponse, mocker') = getResponse req mocker liftIO $ writeIORef mockerR mocker' maybe respondNotFound respondSuccess mResponse respondNotFound :: ActionM () respondNotFound = status notFound404 respondSuccess :: FakeResponse -> ActionM () respondSuccess resp = do status $ resp ^. responseStatus mapM_ setHeader $ resp ^. responseHeaders text $ resp ^. responseBody where setHeader = uncurry header convertToRequest :: W.Request -> IO Request convertToRequest r = do body <- consumeBody r return $ Request (W.requestMethod r) (decodeUtf8 . W.serverName $ r) (W.serverPort r) (W.requestHeaders r) (W.isSecure r) (W.pathInfo r) (W.queryString r) body --TODO: cleanup consumeBody :: W.Request -> IO ByteString consumeBody r = do chunks <- runResourceT $ W.requestBody r $$ consume return $ concat chunks
MichaelXavier/HTTPMock
src/Network/HTTPMock/WebServers/Scotty.hs
bsd-2-clause
2,873
0
12
1,026
677
356
321
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Terrain where import Data.Aeson import GHC.Generics import Control.Lens import GPS type Loc = (Int, Int) data TerrainFeature = Clear | Restricted | SeverelyRestricted | Water | Town deriving (Show, Eq, Generic) data Terrain = Terrain { _terrainMaskCols :: Int , _terrainMaskRows :: Int , _terrainMask :: [(Loc, TerrainFeature)] , _terrainScale :: Int -- pixels to match the map overlay } deriving (Show, Eq, Generic) makeLenses ''Terrain instance FromJSON TerrainFeature instance ToJSON TerrainFeature instance FromJSON Terrain instance ToJSON Terrain isCorrectLoc :: Loc -> Terrain -> Bool isCorrectLoc (lx, ly) t = (lx >= 0 && lx < t ^. terrainMaskCols) && (ly >= 0 && ly < t ^. terrainMaskRows) locFromGPS :: GPS -> Terrain -> Maybe Loc locFromGPS g t = mbloc where scale = t ^. terrainScale f proj = truncate $ proj g / fromIntegral scale lx = f gpsX ly = f gpsY mbloc = if isCorrectLoc (lx, ly) t then Just (lx, ly) else Nothing getTerrainFeatureLoc :: Loc -> Terrain -> Maybe TerrainFeature getTerrainFeatureLoc l t = mbtf where mbtf = if not (isCorrectLoc l t) then Nothing else case lookup l (t ^. terrainMask) of Just tf -> Just tf Nothing -> Just Clear -- clear if no feature getTerrainFeatureGPS :: GPS -> Terrain -> Maybe TerrainFeature getTerrainFeatureGPS g t = locFromGPS g t >>= \l -> getTerrainFeatureLoc l t
nbrk/ld
library/Terrain.hs
bsd-2-clause
1,592
0
11
429
478
256
222
47
3
module IRC.Commands ( -- * Types Channel , Password -- * IRC Functions , nick , user , joinChan , part , quit , privmsg ) where import IRC.Base type Channel = String type Password = String mkMessage :: String -> [Parameter] -> Message mkMessage cmd params = Message Nothing cmd params nick :: UserName -> Message nick u = mkMessage "NICK" [u] user :: UserName -> ServerName -> ServerName -> RealName -> Message user u h s r = mkMessage "USER" [u,h,s,r] joinChan :: Channel -> Message joinChan c = mkMessage "JOIN" [c] part :: Channel -> Message part c = mkMessage "PART" [c] quit :: Maybe String -> Message quit (Just m) = mkMessage "QUIT" [m] quit Nothing = mkMessage "QUIT" [] privmsg :: String -> String -> Message privmsg c m = mkMessage "PRIVMSG" [c,m]
scvalex/logorrhea
lib/IRC/Commands.hs
bsd-3-clause
874
0
8
254
294
160
134
27
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ExistentialQuantification #-} {- | 'Var' is the reference type used for incremental computing. It has a cached value and a list of dependent children to update when it changes. The update propogation happens automatically when using either 'modifyVar' or 'writeVar'. Same with the 'STM' variants. Additionally updates can be triggered manually with 'update' 'Var' is low level and is used by 'Tweakable' and to create incremental expressions. -} module Control.Tweak.Var ( -- * Reference for Incremental Computing Var (..) -- ** Existential Var Wrapper , AnyVar (..) -- ** Helpers , Update , Children , Cacheable (..) -- * Lenses , output , identifier -- * Dependency Manipulation , update , addChild , addChildSTM -- * Var IO CRU , newVar , readVar , modifyVar , writeVar -- * Var STM CRU , newVarSTM , readVarSTM , modifyVarSTM , writeVarSTM ) where import Control.Concurrent.STM import Control.Lens hiding (children) import Control.Applicative import Data.Map (Map) import qualified Data.Map as M import Data.UniqueSTM class Render a where render :: a -> IO String -- | The type of update actions type Update = STM () -- | The container for a 'Var's dependent 'Var's. type Children = Map AnyVar Update -- | This a reference for incremental computation. Not only does it include a value, -- But is also has a list of actions to execute when it is updated. data Var a = Var { _output :: TVar a -- ^ The cached value of the the 'Var' , _children :: TVar Children -- ^ A collection of actions to execute when the value of the 'Var' is updated , _identifier :: Unique -- ^ This is so to references to the same 'Var' are not added to '_children' -- collection } -- | Just checks pointer equality not value equality instance Eq (Var a) where (==) = varEq varEq :: Var a -> Var b -> Bool varEq (Var _ _ x) (Var _ _ y) = x == y instance Ord (Var a) where compare = varCompare varCompare :: Var a -> Var b -> Ordering varCompare (Var _ _ x) (Var _ _ y) = compare x y instance Show a => Render (Var a) where render Var {..} = fmap show . atomically . readTVar $ _output -- | a 'Lens' for the cached ref output :: Lens (Var a) (Var b) (TVar a) (TVar b) output = lens _output (\x y -> x {_output = y}) -- | a 'Lens' for the unique identifier associated with this 'Var' identifier :: Lens (Var a) (Var a) Unique Unique identifier = lens _identifier (\x y -> x { _identifier = y }) -- An existential wrapper for a 'Var'. This is useful when we need a list of -- 'Var's data AnyVar = forall a. AnyVar (Var a) instance Eq AnyVar where AnyVar x == AnyVar y = varEq x y instance Ord AnyVar where compare (AnyVar x) (AnyVar y) = varCompare x y -- A class for accessing the children of 'Var' or something that has a 'Var' -- inside it. class Cacheable a where children :: Lens' a (TVar Children) instance Cacheable (Var a) where children = lens _children (\x y -> x { _children = y }) instance Cacheable AnyVar where children = lens (\(AnyVar x) -> view children x) (\(AnyVar x) y -> AnyVar $ set children y x) -- | Recursively call update on the children of a 'Var' like thing update :: Cacheable a => a -> STM () update x = do dict <- readTVar $ x^.children sequence_ . M.elems $ dict mapM_ update . M.keys $ dict -- | Create a new 'Var'. See 'newVarSTM' for the 'STM' version. newVar :: a -> IO (Var a) newVar = atomically . newVarSTM -- | Create a new 'Var'. See 'newVar' for the 'IO' version. newVarSTM :: a -> STM (Var a) newVarSTM x = Var <$> newTVar x <*> newTVar M.empty <*> newUniqueSTM -- | Read the cached value of a 'Var'. See 'readVarSTM' for an 'STM' version readVar :: Var a -> IO a readVar = atomically . readVarSTM -- | Read the cached value of a 'Var'. See 'readVar' for an 'IO' version readVarSTM :: Var a -> STM a readVarSTM = readTVar . view output -- | Modify a 'Var' and update the children. -- See 'modifyVar' for the 'IO' version modifyVarSTM :: Var a -> (a -> a) -> STM () modifyVarSTM var@(Var v _ _) f = do modifyTVar v f update var -- | Modify a 'Var' and update the children. -- See 'modifyVarSTM' for the 'STM' version modifyVar :: Var a -> (a -> a) -> IO () modifyVar v = atomically . modifyVarSTM v -- | Write a new value into a 'Var' and update all of the children. -- See 'writeVar' for the 'IO' version writeVarSTM :: Var a -> a -> STM () writeVarSTM v = modifyVarSTM v . const -- | Write a new value into a 'Var' and update all of the children. -- See 'writeVarSTM' for the 'STM' version writeVar :: Var a -> a -> IO () writeVar v = modifyVar v . const -- | Add a dependent child to the 'Var's children, or any type that has 'Var' like -- Children -- See 'addChildSTM' for the 'STM' version addChild :: Cacheable a => a -- ^ The input that contains the reference to add children to -> AnyVar -- ^ The child 'Var' existentially wrapped up. The important info here -- is the unique 'Var' id. -> Update -- ^ The update action to call when the input is updated. -> IO () addChild x k = atomically . addChildSTM x k -- | Add a dependent child to the 'Var's children, or any type that has 'Var' like -- Children -- See 'addChild' for the 'IO' version addChildSTM :: Cacheable a => a -- ^ The input that contains the reference to add children to -> AnyVar -- ^ The child 'Var' existentially wrapped up. The important info here -- is the unique 'Var' id. -> Update -- ^ The update action to call when the input is updated. -> STM () addChildSTM x k = modifyTVar (x^.children) . M.insert k
jfischoff/tweak
src/Control/Tweak/Var.hs
bsd-3-clause
6,038
0
10
1,590
1,267
679
588
99
1
-- Copyright (c) 2010-2011 -- The President and Fellows of Harvard College. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- 3. Neither the name of the University nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND -- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. -------------------------------------------------------------------------------- -- | -- Module : Language.C.Quote -- Copyright : (c) Harvard University 2010-2011 -- License : BSD-style -- Maintainer : [email protected] -- -- There are three modules that provide quasiquoters, each for a different C -- variant. 'Language.C.Quote.C' parses C99, 'Language.C.Quote.GCC' parses C99 -- plus GNU extensions, and 'Language.C.Quote.CUDA' parses C99 plus GNU and CUDA -- extensions. The quasiquoters generate Template Haskell expressions that use -- data constructors that must be in scope where the quasiquoted expression -- occurs. You will be safe if you add the following imports to any module using -- the quasiquoters provided by this package: -- -- > import qualified Data.Loc -- > import qualified Data.Symbol -- > import qualified Language.C.Syntax -- -- These modules may also be imported unqualified, of course. The quasioquoters -- also use some constructors defined in the standard Prelude, so if it is not -- imported by default, it must be imported qualified. -- -- The following quasiquoters are defined: -- -- [@cdecl@] Declaration, of type @'InitGroup'@. -- -- [@cedecl@] External declarations (top-level declarations in a C file, -- including function definitions and declarations), of type @'Definition'@. -- -- [@cenum@] Component of an @enum@ definition, of type @'CEnum'@. -- -- [@cexp@] Expression, of type @'Exp'@. -- -- [@cfun@] Function definition, of type @'Func'@. -- -- [@cinit@] Initializer, of type @'Initializer'@. -- -- [@cparam@] Declaration of a function parameter, of type @'Param'@. -- -- [@csdecl@] Declaration of a struct member, of type @'FieldGroup'@. -- -- [@cty@] A C type, of type @'Type'@. -- -- [@cunit@] A compilation unit, of type @['Definition']@. -- -- Antiquotations allow splicing in subterms during quotation. These subterms -- may bound to a Haskell variable or may be the value of a Haskell -- expression. Antiquotations appear in a quasiquotation in the form -- @$ANTI:VARID@, where @VARID@ is a Haskell variable identifier, or in the form -- @$ANTI:(EXP)@, where @EXP@ is a Haskell expressions (the parentheses must -- appear in this case). Additionally, @$VARID@ is shorthand for @$exp:VARID@ -- and @$(EXP)@ is shorthand for @$exp:(EXP)@. The following antiquotations -- (ANTI) are supported: -- -- [@id@] A C identifier. The argument must have type @'String'@. -- -- [@int@] An @integer@ constant. The argument must be an instance of -- @'Integral'@. -- -- [@uint@] An @unsigned integer@ constant. The argument must be an instance of -- @'Integral'@. -- -- [@lint@] A @long integer@ constant. The argument must be an instance of -- @'Integral'@. -- -- [@ulint@] An @unsigned long integer@ constant. The argument must be an -- instance of @'Integral'@. -- -- [@float@] A @float@ constant. The argument must be an instance of -- @'Fractional'@. -- -- [@double@] A @double@ constant. The argument must be an instance of -- @'Fractional'@. -- -- [@long double@] A @long double@ constant. The argument must be an instance -- of @'Fractional'@. -- -- [@char@] A @char@ constant. The argument must have type @'Char'@. -- -- [@string@] A string (@char*@) constant. The argument must have type -- @'String'@. -- -- [@exp@] A C expression. The argument must be an instance of @'ToExp'@. -- -- [@func@] A function definition. The argument must have type @'Func'@. -- -- [@args@] A list of function arguments. The argument must have type @['Exp']@. -- -- [@decl@] A declaration. The argument must have type @'InitGroup'@. -- -- [@decls@] A list of declarations. The argument must have type -- @['InitGroup']@. -- -- [@sdecl@] A struct member declaration. The argument must have type -- @'FieldGroup'@. -- -- [@sdecls@] A list of struct member declarations. The argument must have type -- @['FieldGroup']@. -- -- [@enum@] An enum member. The argument must have type @'CEnum'@. -- -- [@enums@] An list of enum members. The argument must have type @['CEnum']@. -- -- [@esc@] An arbitrary top-level C "definition," such as an @#include@ or a -- @#define@. The argument must have type @'String'@. -- -- [@edecl@] An external definition. The argument must have type @'Definition'@. -- -- [@edecls@] An list of external definitions. The argument must have type -- @['Definition']@. -- -- [@item@] A statement block item. The argument must have type @'BlockItem'@. -- -- [@items@] A list of statement block item. The argument must have type -- @['BlockItem']@. -- -- [@stm@] A statement. The argument must have type @'Stm'@. -- -- [@stms@] A list statements. The argument must have type @['Stm']@. -- -- [@ty@] A C type. The argument must have type @'Type'@. -- -- [@spec@] A declaration specifier. The argument must have type @'DeclSpec'@. -- -- [@param@] A function parameter. The argument must have type @'Param'@. -- -- [@params@] A list of function parameters. The argument must have type -- @['Param']@. -------------------------------------------------------------------------------- module Language.C.Quote where import Language.C.Quote.Base import Language.C.Syntax
HIPERFIT/language-c-quote
Language/C/Quote.hs
bsd-3-clause
6,712
0
4
1,068
175
169
6
3
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RecordWildCards #-} module Database.Cassandra.Pool ( CPool , Server , defServer , defServers , KeySpace , Cassandra (..) , createCassandraPool , withResource -- * Low Level Utilities , openThrift ) where ------------------------------------------------------------------------------ import Control.Applicative ((<$>)) import Control.Arrow import Control.Concurrent import Control.Concurrent.STM import Control.Exception (SomeException, handle, onException) import Control.Monad (forM_, forever, join, liftM2, unless, when) import Data.ByteString (ByteString) import Data.List (find, nub, partition) import Data.Maybe import Data.Pool import Data.Set (Set) import qualified Data.Set as S import Data.Time.Clock (NominalDiffTime, UTCTime, diffUTCTime, getCurrentTime) import qualified Database.Cassandra.Thrift.Cassandra_Client as C import qualified Database.Cassandra.Thrift.Cassandra_Types as C import Network import Prelude hiding (catch) import System.IO (Handle (..), hClose) import System.Mem.Weak (addFinalizer) import Thrift.Protocol.Binary import Thrift.Transport import Thrift.Transport.Framed import Thrift.Transport.Handle ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | A round-robin pool of cassandra connections type CPool = Pool Cassandra ------------------------------------------------------------------------------ -- | A (ServerName, Port) tuple type Server = (HostName, Int) -- | A localhost server with default configuration defServer :: Server defServer = ("127.0.0.1", 9160) -- | A single localhost server with default configuration defServers :: [Server] defServers = [defServer] ------------------------------------------------------------------------------ type KeySpace = String ------------------------------------------------------------------------------ data Cassandra = Cassandra { cHandle :: Handle , cFramed :: FramedTransport Handle , cProto :: BinaryProtocol (FramedTransport Handle) } -- | Create a pool of connections to a cluster of Cassandra boxes -- -- Each box in the cluster will get up to n connections. The pool will send -- queries in round-robin fashion to balance load on each box in the cluster. createCassandraPool :: [Server] -- ^ List of servers to connect to -> Int -- ^ Number of stripes to maintain -> Int -- ^ Max connections per stripe -> NominalDiffTime -- ^ Kill each connection after this many seconds -> KeySpace -- ^ Each pool operates on a single KeySpace -> IO CPool createCassandraPool servers numStripes perStripe maxIdle ks = do sring <- newTVarIO $ mkRing servers pool <- createPool (cr 4 sring) dest numStripes maxIdle perStripe -- forkIO (serverDiscoveryThread sring ks pool) return pool where cr :: Int -> ServerRing -> IO Cassandra cr n sring = do s@(host, p) <- atomically $ do ring@Ring{..} <- readTVar sring writeTVar sring (next ring) return current handle (handler n sring s) $ do (h,ft,proto) <- openThrift host p C.set_keyspace (proto, proto) ks return $ Cassandra h ft proto handler :: Int -> ServerRing -> Server -> SomeException -> IO Cassandra handler 0 _ _ e = error $ "Can't connect to cassandra after several tries: " ++ show e handler n sring server e = do -- we need a temporary removal system for servers; something -- with a TTL just removing them from ring is dangerous, what if -- the network is partitioned for a little while? -- modifyServers sring (removeServer server) -- wait 100ms to avoid crazy loops threadDelay 100000 cr (n-1) sring dest h = hClose $ cHandle h ------------------------------------------------------------------------------- -- | Open underlying thrift connection openThrift host port = do h <- hOpen (host, PortNumber (fromIntegral port)) ft <- openFramedTransport h let p = BinaryProtocol ft return (h, ft, p) ------------------------------------------------------------------------------ modifyServers :: TVar (Ring a) -> (Ring a -> Ring a) -> IO () modifyServers sring f = atomically $ do ring@Ring{..} <- readTVar sring writeTVar sring $ f ring return () ------------------------------------------------------------------------------ serverDiscoveryThread :: TVar (Ring Server) -> String -> Pool Cassandra -> IO b serverDiscoveryThread sring ks pool = forever $ do withResource pool (updateServers sring ks) threadDelay 60000000 ------------------------------------------------------------------------------ updateServers :: TVar (Ring Server) -> String -> Cassandra -> IO () updateServers sring ks (Cassandra _ _ p) = do ranges <- C.describe_ring (p,p) ks let hosts = concat $ catMaybes $ map C.f_TokenRange_endpoints ranges servers = nub $ map (\e -> first (const e) defServer) hosts -- putStrLn $ "Cassy: Discovered new servers: " ++ show servers modifyServers sring (addNewServers servers) ------------------------------------------------------------------------------ type ServerRing = TVar (Ring Server) ------------------------------------------------------------------------------ data Ring a = Ring { allItems :: Set a , current :: !a , used :: [a] , upcoming :: [a] } ------------------------------------------------------------------------------ mkRing [] = error "Can't make a ring from empty list" mkRing all@(a:as) = Ring (S.fromList all) a [] as ------------------------------------------------------------------------------ next :: Ring a -> Ring a next Ring{..} | (n:rest) <- upcoming = Ring allItems n (current : used) rest next Ring{..} | (n:rest) <- reverse (current : used) = Ring allItems n [] rest ------------------------------------------------------------------------------ removeServer :: Ord a => a -> Ring a -> Ring a removeServer s r@Ring{..} | s `S.member` allItems = Ring all' cur' [] up' | otherwise = r where all' = S.delete s allItems cur' : up' = S.toList all' ------------------------------------------------------------------------------ addNewServers :: [Server] -> Ring Server -> Ring Server addNewServers servers Ring{..} = Ring all' current' used' (new ++ upcoming') where all' = S.fromList servers new = S.toList $ all' S.\\ allItems used' = filter (`S.member` all') used (current':upcoming') = filter (`S.member` all') (current:upcoming)
Soostone/cassy
src/Database/Cassandra/Pool.hs
bsd-3-clause
7,911
0
16
2,372
1,602
862
740
137
2
module Language.Gator.Gates.Input where import Language.Gator.IO data Input = Input Name GateID deriving (Show, Eq, Ord) instance GIdent Input where gid (Input _ g) = g instance Named Input where name (Input n _) = n instance Out Input
sw17ch/gator
src/Language/Gator/Gates/Input.hs
bsd-3-clause
253
0
8
55
95
51
44
9
0
{-# LANGUAGE PatternSynonyms #-} module SimpleExpr where import Text.Parsec hiding (State) import Text.Parsec.String import Data.Char import Data.Monoid import qualified Data.Map as Map import Data.Map (Map) import Control.Monad.State.Lazy data Expr b = Application (Expr b) (Expr b) | Lambda b (Expr b) | PolyLambda b (Expr b) | ForAll b (Expr b) | Variable b | Literal LiteralValue (Expr b) | LitArrow deriving (Show,Eq) instance Functor Expr where fmap f (Application a b) = Application (fmap f a) (fmap f b) fmap f (Lambda b e) = Lambda (f b) (fmap f e) fmap f (PolyLambda b e) = PolyLambda (f b) (fmap f e) fmap f (ForAll b e) = ForAll (f b) (fmap f e) fmap f (Variable v) = Variable (f v) fmap f (Literal v t) = Literal v (fmap f t) fmap _ LitArrow = LitArrow instance Foldable Expr where foldMap f (Application a b) = foldMap f a <> foldMap f b foldMap f (Lambda b e) = f b <> foldMap f e foldMap f (PolyLambda b e) = f b <> foldMap f e foldMap f (ForAll b e) = f b <> foldMap f e foldMap f (Variable v) = f v foldMap f (Literal _ t) = foldMap f t foldMap _ LitArrow = mempty compileShow :: String -> IO () compileShow = putStrLn . uniqueExpr . (\(Right a) -> a) . compile compile :: String -> Either ParseError (Expr (Unique Name)) compile = (lexScopeIt . typeIt <$>) . parseIt where parseIt = parse parseExpr "" enumIt = enumerateExpr lexScopeIt = lexicallyScopeExpr typeIt = id lexeme :: Parser a -> Parser a lexeme = (<*(spaces<?>"Lexical Whitespace")) parseExpr :: Parser ParsedExpr parseExpr = chainl1 (lexeme realParse <?> "Expression") parseAppl <?> "Applicable Expression" where realParse = parseParenExpr <|> parseLambda <|> (Variable <$> parseName) parseParenExpr :: Parser ParsedExpr parseParenExpr = (lexeme (char '(') <?> "Open Paren") *> parseExpr <* (lexeme (char ')') <?> "Close Paren") parseAppl :: Parser (Expr a -> Expr a -> Expr a) parseAppl = pure Application parseTrivialTypedName :: Parser TypedName parseTrivialTypedName = Typed <$> pure kindStar <*> (Unique <$> pure 0 <*> parseName) parseName :: Parser Name parseName = lexeme (many1 alphaNum) <?> "Name" parseLambda :: Parser ParsedExpr parseLambda = Lambda <$> (lexeme (char '\\') *> parseName <* lexeme (string "->")) <*> parseExpr <?> "Lambda" -- In hind sight I should probably have used a fold or a StateT Int -- Later: Compare this original attempt to the one using a state monad below -- even Later: Compare this to traverse :P --enumerateExpr :: Expr Name -> Expr (Unique Name) --enumerateExpr = snd . go 0 --where --go :: Int -> Expr Name -> (Int, Expr (Unique Name)) --go n (Application a b) = (n'',Application a' b') --where --(n',a') = go n a --(n'',b') = go n' b --go n (Lambda b e) = let (n',e') = go (succ n) e in (n', Lambda (Unique n b) e') --go n (PolyLambda b e) = let (n',e') = go (succ n) e in (n', PolyLambda (Unique n b) e') --go n (ForAll b e) = let (n',e') = go (succ n) e in (n', ForAll (Unique n b) e') --go n (Variable v) = (succ n, Variable (Unique n v)) --go n (Literal v t) = let (n',t') = go n t in (n',Literal v t') --go n LitArrow = (n,LitArrow) instance Traversable Expr where --traverse :: Applicative p => (a -> p b) -> Expr a -> p (Expr b) traverse f expr = go expr where go (Application a b) = Application <$> go a <*> go b go (Lambda b e) = Lambda <$> f b <*> go e go (PolyLambda b e) = PolyLambda <$> f b <*> go e go (ForAll b e) = ForAll <$> f b <*> go e go (Variable v) = Variable <$> f v go (Literal v t) = Literal v <$> go t go LitArrow = pure LitArrow inlineExpr :: Eq b => b -> Expr b -> Expr b -> Expr b inlineExpr n beta (Application a b) = Application (inlineExpr n beta a) (inlineExpr n beta b) inlineExpr n beta (Lambda bind e) = Lambda bind (inlineExpr n beta e) inlineExpr n beta (PolyLambda bind e) = PolyLambda bind (inlineExpr n beta e) inlineExpr n beta (ForAll bind e) = ForAll bind (inlineExpr n beta e) inlineExpr n beta (Variable v) = if n == v then beta else Variable v inlineExpr n beta (Literal v t) = Literal v (inlineExpr n beta t) inlineExpr _ _ LitArrow = LitArrow -- Label every binder in increasing order enumerateExpr :: Expr Name -> Expr (Unique Name) enumerateExpr expr = evalState (traverse fresh expr) 0 where fresh :: Name -> State Int (Unique Name) fresh v = do modify (+1) u <- get return (Unique u v) -- \x -> (\x -> x) x -- 1 2 2 1 -- -- \a -> (\a -> a) -- 1 2 2 data LexicalError = UndeclaredVariable String deriving (Eq,Show) lexicallyScopeExpr :: ParsedExpr -> Expr (Unique Name) lexicallyScopeExpr expr = evalState (go Map.empty expr) 0 where go :: Map Name Int -> Expr Name -> State Int (Expr (Unique Name)) -- for Applications, do the first, then the second go m (Application a b) = Application <$> go m a <*> go m b -- for Lambdas, push the new variable in, then pop it out afterward (don't save m') go m (Lambda b e) = do u <- fresh Lambda (Unique u b) <$> (go (Map.insert b u m) e) go m (PolyLambda b e) = do u <- fresh PolyLambda (Unique u b) <$> (go (Map.insert b u m) e) go m (ForAll b e) = do u <- fresh ForAll (Unique u b) <$> (go (Map.insert b u m) e) -- For variables, check if the Variable is in scope, and use the created Id if it is. Otherwise, error out immediatley go m (Variable v) = do case Map.lookup v m of Just a -> return $ Variable (Unique a v) Nothing -> error $ show $ UndeclaredVariable (show v) -- Literal Values are not affected by scope go m (Literal v t) = Literal v <$> go m t -- Literal Arrows are not affected by scope go m LitArrow = pure LitArrow fresh :: State Int Int fresh = const <$> get <*> modify (+1) pattern Function from to <- Application (Application LitArrow from) to function :: SimpleExpr -> SimpleExpr -> SimpleExpr function from to = Application (Application LitArrow from) to -- \a::* -> \b::* -> \x::a::* -> \y::b::* -> x::a::* -- :: ∀a::* (∀b::* (b::* -> a::*)) -- :: * -- -- \t::* -> \a::t -> a::t -- :: ∀t::* (t::* -> t::*) -- :: * -- -- \a::Int::* -> \b::Int::* -> a::Int::* -- :: Int::* -> Int::* -> Int::* -- :: * cleanExpr :: SimpleExpr -> String cleanExpr = printExpr cleanName fancyExpr :: SimpleExpr -> String fancyExpr = printExpr showTyped where showTyped (Typed t (Unique u s)) = s ++ "[" ++ show u ++ "] :: " ++ fancyExpr t plainExpr :: ParsedExpr -> String plainExpr = printExpr id uniqueExpr :: Expr (Unique Name) -> String uniqueExpr = printExpr showUnique where showUnique (Unique u s) = s ++ "[" ++ show u ++ "]" printExpr :: (a -> String) -> Expr a -> String printExpr f (Function from to) = printExpr f from ++ " -> " ++ printExpr f to printExpr f LitArrow = "{->}" printExpr f (Application a b) = printExpr f a ++ " " ++ printExpr f b printExpr f (Lambda bind e) = "(λ" ++ f bind ++ "." ++ printExpr f e ++ ")" printExpr f (PolyLambda bind e) = "(POLYλ" ++ f bind ++ "." ++ printExpr f e ++ ")" printExpr f (ForAll bind e) = "(∀" ++ f bind ++ "." ++ printExpr f e ++ ")" printExpr f (Variable bind) = f bind printExpr f (Literal l _) = show l type Name = {-Source Name-}String data Unique a = Unique {-Unique-}Int a deriving Show data Typed a = Typed {-Type-}SimpleExpr a deriving (Show,Eq) type TypedName = Typed (Unique Name) type SimpleExpr = Expr TypedName type ParsedExpr = Expr Name typedName :: String -> Int -> SimpleExpr -> TypedName typedName s u t = Typed t (Unique u s) instance Eq (Unique a) where (==) (Unique ua _) (Unique ub _) = ua == ub cleanName :: TypedName -> String cleanName (Typed _ (Unique _ name)) = name data LiteralValue = IntValue Int | StringValue String deriving (Eq) instance Show LiteralValue where show (IntValue i) = show i show (StringValue s) = show s kindStar :: SimpleExpr kindStar = Literal (StringValue "*") sort sort :: SimpleExpr sort = Literal (StringValue "[%]") sort idEx :: SimpleExpr idEx = Lambda x (Variable x) where x = typedName "x" 0 intType intType = (Literal (StringValue "Int") kindStar) k :: SimpleExpr k = Lambda x (Lambda underScoreDiscard (Variable x)) where x = typedName "x" 0 intType underScoreDiscard = typedName "_" 1 intType intType = (Literal (StringValue "Int") kindStar) -- -- bigLambda = ^a::* -> \x::a -> x::a -- bigLambda :: forall a. a -> a -- bigLambda :: Lambda (TypedName "X" 2 kindStar) (Application (Application LitArrow x) x) -- bigLambda :: SimpleExpr bigLambda = PolyLambda bigX (Lambda x (Variable x)) where bigX = typedName "X" 0 kindStar x = typedName "x" 1 (Variable bigX) errorTest :: SimpleExpr errorTest = Application (Lambda x (Variable x)) (Literal (StringValue "meow") (Literal (StringValue "NotInt") kindStar)) where intType = Literal (StringValue "Int") kindStar x = typedName "x" 0 intType -- \x -> x -- :: forall a. a -> a -- \@X::* -> \x::X -> x::X -- :: forall x. x -> x -- -- (*::sort -> (t::* -> t::*)::*) :: sort -> * -- -- id :: *::sort -> (t::* -> t::*)::* -- id = \t::* -> (\x::t -> x::t) -- -- monoId :: (Int::*) -> (Int::*) -- monoId = \x::Int -> x::Int -- -- * :: sort -- ((Int::*) -> (Int::*)) :: * -- timesTwo :: Int -> Int -- timesTwo = \x::Int -> ((times :: Int -> (Int -> Int)) (x::Int) (2::Int)) -- KINDaequal! Haha! get it? KIND? lol kindaEqual :: SimpleExpr -> SimpleExpr -> Bool kindaEqual (Literal (StringValue "*") _) (Literal (StringValue "*") _) = True kindaEqual a b = a == b data TypeError = MismatchedTypes SimpleExpr SimpleExpr | NotAFunction SimpleExpr SimpleExpr deriving Eq instance Show TypeError where show (MismatchedTypes a b) = "Type {" ++ show a ++ "} did not match {" ++ show b ++ "}" show (NotAFunction a b) = "Type {" ++ show a ++ "} is not a function, but was applied to {" ++ show b ++ "}" getType :: SimpleExpr -> Either TypeError SimpleExpr getType (Variable (Typed typ _)) = Right typ --getType (Function funcIn funcOut) = case getType funcIn of --Left e -> Left e --Right a -> Right $ function funcIn funcOut getType (Application appA appB) = case getType appA of Right (Function funcIn funcOut) -> case getType appB of Right appBType -> if kindaEqual funcIn appBType then Right funcOut else Left $ MismatchedTypes funcIn appBType Left e -> Left e Right a -> Left $ NotAFunction appA appB Left e -> Left e getType (Lambda (Typed typ _) e) = case getType e of Right t -> Right $ function typ t Left e -> Left e getType (PolyLambda tyName e) = getType e >>= (Right . ForAll tyName) getType (ForAll _ e) = getType e getType (Literal _ t) = Right t getType LitArrow = Right $ function kindStar (function kindStar kindStar) getTypes :: SimpleExpr -> [SimpleExpr] getTypes e = e : case getType e of Right (Literal (StringValue "[%]") _) -> [sort] Right typ -> getTypes typ Left _ -> [] addType :: Expr (Unique Name) -> Either TypeError SimpleExpr addType (Application appA appB) = Application <$> addType appA <*> addType appB addType (Lambda b e) = Lambda <$> printTypes :: SimpleExpr -> IO () printTypes = mapM_ print . getTypes --substitute :: TypedName -> TypedName -> SimpleExpr -> SimpleExpr --substitute f r (Application a b) = Application (substitute f r a) (substitute f r b) --substitute f r (Lambda b@(Typed t (Unique u s)) e) = --Lambda --(if b == f then r else typedName s u (substitute f r t)) -- (substitute f r e) --substitute f r (Variable v@(Typed t (Unique u s))) = -- if v == f -- then Variable r -- else Variable (typedName s u (substitute f r t)) --substitute _ _ l@(Literal _ _) = l --substitute _ _ LitArrow = LitArrow betaReduce :: Eq b => Expr b -> Expr b betaReduce (Application (Lambda b e) beta) = inlineExpr b beta e betaReduce x = x
Lazersmoke/rhc
src/SimpleExpr.hs
bsd-3-clause
11,888
0
15
2,674
3,886
1,965
1,921
-1
-1
data AB = A | B deriving Show data S = Rec S AB | Atom AB deriving Show testPackrat :: S testPackrat = fromReturn $ drvS $ parse [A, B, B] fromReturn (Return x _) = x data Return a = Return a Derivs | LR Bool | Fail data Derivs = Derivs { drvS :: Return S, chars :: Return AB } parse :: [AB] -> Derivs parse s = d where d = Derivs (ds d { drvS = LR False }) dab ds drv = case drvS drv of Return r rest -> case chars rest of Return B rest' -> Return (Rec r B) rest' _ -> Fail LR False -> case drvS d { drvS = ds drv { drvS = Fail } } of Return r rest -> case chars rest of Return B rest' -> Return (Rec r B) rest' _ -> Fail _ -> case chars d of Return A rest -> Return (Atom A) rest _ -> Fail _ -> case chars d of Return A rest -> Return (Atom A) rest _ -> Fail dab = case s of c : cs -> Return c $ parse cs _ -> Fail
YoshikuniJujo/papillon
test/leftRecursion/abb.hs
bsd-3-clause
873
4
18
258
442
223
219
29
9
module EFA.Flow.Cumulated.AssignMap where import qualified EFA.Flow.Cumulated.Variable as Var import qualified EFA.Graph.Topology.Node as Node import EFA.Report.FormatValue (FormatValue, formatAssign) import EFA.Report.Format (Format) import qualified Data.Map as Map ; import Data.Map (Map) import Data.Monoid (Monoid, mappend, mempty) type Any node a = Map (Var.Any node) a newtype AssignMap node a = AssignMap (Any node a) instance (Ord node) => Monoid (AssignMap node a) where mempty = AssignMap Map.empty mappend (AssignMap map0) (AssignMap map1) = AssignMap (Map.unionWith (error "duplicate variable") map0 map1) singleton :: Var.Any node -> a -> AssignMap node a singleton idx a = AssignMap (Map.singleton idx a) lift0 :: Any node v -> AssignMap node v lift0 = AssignMap lift1 :: (Any node v0 -> Any node v) -> AssignMap node v0 -> AssignMap node v lift1 f (AssignMap signal0) = AssignMap (f signal0) lift2 :: (Any node v0 -> Any node v1 -> Any node v) -> AssignMap node v0 -> AssignMap node v1 -> AssignMap node v lift2 f (AssignMap signal0) (AssignMap signal1) = AssignMap (f signal0 signal1) intersectionWith :: (Ord node) => (a -> b -> c) -> AssignMap node a -> AssignMap node b -> AssignMap node c intersectionWith f = lift2 (Map.intersectionWith f) difference :: (Ord node) => AssignMap node v -> AssignMap node v -> AssignMap node v difference = lift2 Map.difference filter :: Ord node => (v -> Bool) -> AssignMap node v -> AssignMap node v filter f = lift1 (Map.filter f) format :: (Node.C node, FormatValue v, Format output) => AssignMap node v -> [output] format (AssignMap assigns) = Map.elems (Map.mapWithKey formatAssign assigns)
energyflowanalysis/efa-2.1
src/EFA/Flow/Cumulated/AssignMap.hs
bsd-3-clause
1,782
0
10
393
676
352
324
59
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Database.Persist.File.BlackBox where import Control.Applicative import Control.Monad.State.Class import Control.Monad.Trans.State import Database.Persist.File.Base import Test.QuickCheck.Gen newtype Partition a = Partition { unPart :: Gen a } deriving (Functor, Applicative, Monad) partFromList :: [a] -> Partition a partFromList = Partition . elements newtype Boundary a = Boundary { unBoundary :: Gen a } deriving (Functor, Applicative, Monad) boundaryFromList :: [a] -> Boundary a boundaryFromList = Boundary . elements newtype StateTransition s a = StateTransition { unStTrans :: StateT s Gen a } deriving (Functor, Applicative, Monad, MonadState s) fromStateTrans :: s -> StateTransition s a -> Gen (a, s) fromStateTrans s = flip runStateT s . unStTrans -- Converts the paramteric data type to generator class ToGen g where toGen :: g a -> Gen a instance ToGen [] where toGen = elements instance ToGen Partition where toGen = unPart instance ToGen Boundary where toGen = unBoundary -- Converts a generator to a parametric data type class FromGen g where fromGen :: Gen a -> g a instance FromGen Partition where fromGen = Partition instance FromGen Boundary where fromGen = Boundary
andorp/file-persist
src/Database/Persist/File/BlackBox.hs
bsd-3-clause
1,308
0
8
225
358
201
157
34
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} module Main (main) where import Bot (connect, disconnect, runBot) import Control.Exception (bracket) import Control.Monad (when) import Data.Configurator (load, Worth(..), require) import Data.List (intercalate) import Data.Version (showVersion) import Paths_Dikunt (getDataFileName, version) import qualified System.Console.CmdArgs as CMD import System.Console.CmdArgs ((&=)) import System.Environment (getEnv, setEnv) import System.IO (stderr, hPutStrLn) import qualified System.Log.Formatter as Log import qualified System.Log.Handler as Log import qualified System.Log.Handler.Simple as Log import qualified System.Log.Logger import qualified System.Log.Logger as Log import qualified Types.BotTypes as BT data Dikunt = Dikunt { server :: String , nickname :: String , password :: String , channel :: String , port :: Integer , pluginArgs :: [String] , withPlugins :: [FilePath] , withoutPlugins :: [FilePath] , pluginLocations :: [FilePath] } deriving (CMD.Data, CMD.Typeable, Show, Eq) dikunt :: String -> Dikunt dikunt vers = Dikunt { server = "irc.freenode.org" &= CMD.help "Server to connect to" , nickname = "dikunt" &= CMD.help "Nick to use" , password = CMD.def &= CMD.help "Password to use" , channel = "#dikufags" &= CMD.help "Channel to connect to" , port = 6667 &= CMD.help "Port to connect to" , pluginArgs = [] &= CMD.explicit &= CMD.name "plugin-arg" &= CMD.help "Argument that is passed to all plugins started by Dikunt." , withPlugins = [] &= CMD.explicit &= CMD.name "with-plugin" &= CMD.help "Path to plugins to run besides what is specified in the \ \configuration" , withoutPlugins = [] &= CMD.explicit &= CMD.name "without-plugin" &= CMD.help "Path to plugins to ignore i.e. they are not run even though \ \they are specified in the configuration" , pluginLocations = [] &= CMD.explicit &= CMD.name "plugin-location" &= CMD.help "Path to folder containing plugins that are not on the \ \current $PATH" } &= CMD.help "Bot to run on IRC channels" &= CMD.summary ("Dikunt v" ++ vers ++ " (C) Magnus Stavngaard") &= CMD.helpArg [CMD.explicit, CMD.name "help", CMD.name "h"] &= CMD.versionArg [CMD.explicit, CMD.name "version", CMD.name "v"] getBotConfig :: Dikunt -> Maybe BT.BotConfig getBotConfig (Dikunt serv nick pass chan p _ _ _ _) = BT.botConfig serv nick pass chan p {- | Allocate resources used by the bot. Setup logging and connection to IRC - server. -} setup :: BT.BotConfig -- ^ Configuration of bot. -> [FilePath] -- ^ List of plugins to startup. -> [String] -- ^ List of arguments to plugins. -> [FilePath] -- ^ List of data files the program uses. -> IO BT.Bot setup conf plugins args dfiles = do -- Remove default stderr logging. Log.updateGlobalLogger Log.rootLoggerName Log.removeHandler -- Setup stderr log for errors. handleErr <- Log.streamHandler stderr Log.ERROR >>= \lh -> return $ Log.setFormatter lh logFormatter Log.updateGlobalLogger Log.rootLoggerName (Log.addHandler handleErr) -- Setup file log for received messages. messageLog <- getDataFileName "data/msgLog.db" handleMsg <- Log.fileHandler messageLog Log.INFO >>= \lh -> return $ Log.setFormatter lh logFormatter Log.updateGlobalLogger "messages" (Log.addHandler handleMsg) Log.updateGlobalLogger "messages" (System.Log.Logger.setLevel Log.INFO) -- Setup file log for received privmsgs. privMsgLog <- getDataFileName "data/privmsgLog.db" handlePrivMsg <- Log.fileHandler privMsgLog Log.INFO >>= \lh -> return $ Log.setFormatter lh logFormatter Log.updateGlobalLogger "messages.PRIVMSG" (Log.addHandler handlePrivMsg) -- Setup stderr logger for main. handleMain <- Log.streamHandler stderr Log.INFO >>= \lh -> return $ Log.setFormatter lh logFormatter Log.updateGlobalLogger "main" (Log.addHandler handleMain) Log.updateGlobalLogger "main" (System.Log.Logger.setLevel Log.INFO) -- Setup stderr logger for monitoring. handleMonitor <- Log.streamHandler stderr Log.INFO >>= \lh -> return $ Log.setFormatter lh logFormatter Log.updateGlobalLogger "monitoring" (Log.addHandler handleMonitor) Log.updateGlobalLogger "monitoring" (System.Log.Logger.setLevel Log.INFO) -- Startup Bot. Log.infoM "main" $ unwords [ "Starting bot with configuration" , show conf , "and plugins" , show plugins , "and plugin arguments" , show args , "and data file locations" , show dfiles ] connect conf plugins args where logFormatter = Log.simpleLogFormatter "[$time : $loggername : $prio] $msg" {- | Free resources used by the bot. Close files and connection to IRC - server. -} tearDown :: BT.Bot -- ^ Bot to disconnect. -> IO () tearDown bot = do Log.infoM "main" "Going down" disconnect bot Log.removeAllHandlers main :: IO () main = do arguments <- CMD.cmdArgs $ dikunt (showVersion version) configName <- getDataFileName "data/dikunt.config" config <- load [ Required configName ] config_executables <- require config "pathPlugins" :: IO [String] dataFileLocations <- dataFiles -- Extend $PATH with the extra locations. when (not . null $ pluginLocations arguments) $ do path <- getEnv "PATH" setEnv "PATH" (path ++ ":" ++ intercalate ":" (pluginLocations arguments)) let pluginArguments = pluginArgs arguments executables = filter (\x -> not (x `elem` withoutPlugins arguments)) (config_executables ++ withPlugins arguments) -- Start, loop and stop bot. case getBotConfig arguments of Just botConfig -> bracket (setup botConfig executables pluginArguments dataFileLocations) tearDown runBot -- TODO: Consider how to log this with hslogger. Nothing -> hPutStrLn stderr "Something wrong with configuration" dataFiles :: IO [String] dataFiles = mapM getDataFileName [ "data/InsultData.db" , "data/trump.txt" , "data/WordReplacerData.db" , "data/privmsgLog.db" , "data/msgLog.db" ]
bus000/Dikunt
main/Main.hs
bsd-3-clause
6,402
0
16
1,446
1,517
796
721
122
2
{-# LANGUAGE FlexibleInstances, InstanceSigs, PolyKinds, RankNTypes, ScopedTypeVariables, TypeFamilies, TypeOperators #-} module Data.Higher.Graph ( Rec(..) , RecF(..) , Graph(..) , var , mu , wrap , gfold , grfold , fold , rfold , transform , liftRec , pjoin , modifyGraph , eqRec ) where import Control.Applicative import Data.Higher.Functor import Data.Higher.Functor.Eq import Data.Higher.Functor.Recursive import Data.Higher.Functor.Show import Data.Higher.Transformation data RecF f v b a = Mu (v a -> f b a) | In (f b a) data Rec f v a = Var (v a) | Rec (RecF f v (Rec f v) a) newtype Graph f a = Graph { unGraph :: forall v. Rec f v a } -- Smart constructors var :: v a -> Rec f v a var = Var mu :: (v a -> f (Rec f v) a) -> Rec f v a mu = Rec . Mu wrap :: f (Rec f v) ~> Rec f v wrap = Rec . In -- Folds iter :: forall f a b. HFunctor f => (a ~> b) -> (RecF f a b ~> b) -> Rec f a ~> b iter f alg = go where go :: Rec f a ~> b go rec = case rec of Var a -> f a Rec r -> alg (hfmap go r) gfold :: HFunctor f => (v ~> c) -> (forall a. (v a -> c a) -> c a) -> (f c ~> c) -> Graph f ~> c gfold var bind recur = grfold var bind recur . unGraph grfold :: forall f v c. HFunctor f => (v ~> c) -> (forall a. (v a -> c a) -> c a) -> (f c ~> c) -> Rec f v ~> c grfold var bind algebra = iter var $ \ rec -> case rec of Mu g -> bind (algebra . g) In fa -> algebra fa fold :: HFunctor f => (f c ~> c) -> (forall a. c a) -> Graph f ~> c fold alg k = rfold alg k . unGraph rfold :: HFunctor f => (f c ~> c) -> (forall a. c a) -> Rec f c ~> c rfold alg k = grfold id ($ k) alg -- Maps transform :: HFunctor f => (forall v. f (Rec g v) ~> g (Rec g v)) -> Graph f ~> Graph g transform f = modifyGraph (hoist f) hoist :: HFunctor f => (f (Rec g a) ~> g (Rec g a)) -> Rec f a ~> Rec g a hoist f = iter var $ \ rc -> case rc of Mu g -> mu (f . g) In r -> wrap (f r) liftRec :: (f (Rec f v) ~> g (Rec g v)) -> Rec f v ~> Rec g v liftRec f rc = case rc of Var v -> var v Rec (Mu g) -> mu (f . g) Rec (In r) -> wrap (f r) pjoin :: HFunctor f => Rec f (Rec f v) ~> Rec f v pjoin = iter id $ \ rc -> case rc of Mu g -> mu (g . var) In r -> wrap r modifyGraph :: (forall v. Rec f v ~> Rec g v) -> Graph f ~> Graph g modifyGraph f g = Graph (f (unGraph g)) -- Equality eqRec :: HEqF f => Int -> Rec f (Const Int) a -> Rec f (Const Int) a -> Bool eqRec n a b = case (a, b) of (Var x, Var y) -> x == y (Rec (Mu g), Rec (Mu h)) -> let a = g (Const (succ n)) b = h (Const (succ n)) in heqF (eqRec (succ n)) a b (Rec (In x), Rec (In y)) -> heqF (eqRec n) x y _ -> False -- Show showsRec :: HShowF f => String -> Int -> Rec f (Const Char) a -> ShowS showsRec s n rec = case rec of Var c -> showChar (getConst c) Rec (Mu g) -> showString "Mu (\\ " . showChar (head s) . showString " ->\n " . hshowsPrecF (showsRec (tail s)) n (g (Const (head s))) . showString "\n)\n" Rec (In fa) -> hshowsPrecF (showsRec s) n fa -- Instances instance HEqF f => Eq (Graph f a) where a == b = eqRec 0 (unGraph a) (unGraph b) instance HEqF f => Eq (Rec f (Const Int) a) where a == b = eqRec 0 a b instance HShowF f => Show (Graph f a) where showsPrec n = showsPrec n . (unGraph :: Graph f ~> Rec f (Const Char)) instance HShowF f => Show (Rec f (Const Char) a) where showsPrec = showsRec (iterate succ 'a') instance HFunctor f => HFunctor (RecF f v) where hfmap f rec = case rec of Mu g -> Mu (hfmap f . g) In r -> In (hfmap f r) type instance Base (Rec f v) = f
robrix/derivative-parsing
src/Data/Higher/Graph.hs
bsd-3-clause
3,637
0
16
1,049
2,043
1,027
1,016
94
4
{-# LANGUAGE TupleSections, TypeFamilies, FlexibleContexts, RankNTypes, PackageImports #-} module Data.Pipe ( PipeClass(..), PipeChoice(..), (=@=), runPipe_, convert, Pipe, finally, bracket ) where import Data.Pipe.Core
YoshikuniJujo/simple-pipe
src/Data/Pipe.hs
bsd-3-clause
225
4
5
28
53
36
17
6
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} module Lanthanum.API.Files where import Control.Monad.Trans.Resource import Data.ByteString.Lazy (ByteString) import Network.Wai.Parse import Servant data Mem data Tmp class KnownBackend b where type Storage b :: * withBackend :: Proxy b -> (BackEnd (Storage b) -> IO r) -> IO r instance KnownBackend Mem where type Storage Mem = ByteString withBackend Proxy f = f lbsBackEnd instance KnownBackend Tmp where type Storage Tmp = FilePath withBackend Proxy f = runResourceT . withInternalState $ \s -> f (tempFileBackEnd s) -- * Files combinator, to get all of the uploaded files data Files b type MultiPartData b = ([Param], [File (Storage b)]) instance (KnownBackend b, HasServer api) => HasServer (Files b :> api) where type ServerT (Files b :> api) m = MultiPartData b -> ServerT api m route Proxy subserver req respond = withBackend pb $ \b -> do dat <- parseRequestBody b req route (Proxy :: Proxy api) (subserver dat) req respond where pb = Proxy :: Proxy b type FilesMem = Files Mem type FilesTmp = Files Tmp
fizruk/lanthanum
src/Lanthanum/API/Files.hs
bsd-3-clause
1,258
0
13
243
374
202
172
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE CPP #-} #ifdef DEBUG_CONFLICT_SETS {-# LANGUAGE ImplicitParams #-} #endif module Distribution.Solver.Modular.Validate (validateTree) where -- Validation of the tree. -- -- The task here is to make sure all constraints hold. After validation, any -- assignment returned by exploration of the tree should be a complete valid -- assignment, i.e., actually constitute a solution. import Control.Applicative import Control.Monad.Reader hiding (sequence) import Data.List as L import Data.Map as M import Data.Set as S import Data.Traversable import Prelude hiding (sequence) import Language.Haskell.Extension (Extension, Language) import Distribution.Compiler (CompilerInfo(..)) import Distribution.Solver.Modular.Assignment import qualified Distribution.Solver.Modular.ConflictSet as CS import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.Index import Distribution.Solver.Modular.Package import Distribution.Solver.Modular.Tree import Distribution.Solver.Modular.Version import qualified Distribution.Solver.Modular.WeightedPSQ as W import Distribution.Solver.Types.PackagePath import Distribution.Solver.Types.PkgConfigDb (PkgConfigDb, pkgConfigPkgIsPresent) #ifdef DEBUG_CONFLICT_SETS import GHC.Stack (CallStack) #endif -- In practice, most constraints are implication constraints (IF we have made -- a number of choices, THEN we also have to ensure that). We call constraints -- that for which the preconditions are fulfilled ACTIVE. We maintain a set -- of currently active constraints that we pass down the node. -- -- We aim at detecting inconsistent states as early as possible. -- -- Whenever we make a choice, there are two things that need to happen: -- -- (1) We must check that the choice is consistent with the currently -- active constraints. -- -- (2) The choice increases the set of active constraints. For the new -- active constraints, we must check that they are consistent with -- the current state. -- -- We can actually merge (1) and (2) by saying the the current choice is -- a new active constraint, fixing the choice. -- -- If a test fails, we have detected an inconsistent state. We can -- disable the current subtree and do not have to traverse it any further. -- -- We need a good way to represent the current state, i.e., the current -- set of active constraints. Since the main situation where we have to -- search in it is (1), it seems best to store the state by package: for -- every package, we store which versions are still allowed. If for any -- package, we have inconsistent active constraints, we can also stop. -- This is a particular way to read task (2): -- -- (2, weak) We only check if the new constraints are consistent with -- the choices we've already made, and add them to the active set. -- -- (2, strong) We check if the new constraints are consistent with the -- choices we've already made, and the constraints we already have. -- -- It currently seems as if we're implementing the weak variant. However, -- when used together with 'preferEasyGoalChoices', we will find an -- inconsistent state in the very next step. -- -- What do we do about flags? -- -- Like for packages, we store the flag choices we have already made. -- Now, regarding (1), we only have to test whether we've decided the -- current flag before. Regarding (2), the interesting bit is in discovering -- the new active constraints. To this end, we look up the constraints for -- the package the flag belongs to, and traverse its flagged dependencies. -- Wherever we find the flag in question, we start recording dependencies -- underneath as new active dependencies. If we encounter other flags, we -- check if we've chosen them already and either proceed or stop. -- | The state needed during validation. data ValidateState = VS { supportedExt :: Extension -> Bool, supportedLang :: Language -> Bool, presentPkgs :: PkgconfigName -> VR -> Bool, index :: Index, saved :: Map QPN (FlaggedDeps QPN), -- saved, scoped, dependencies pa :: PreAssignment, qualifyOptions :: QualifyOptions } newtype Validate a = Validate (Reader ValidateState a) deriving (Functor, Applicative, Monad, MonadReader ValidateState) runValidate :: Validate a -> ValidateState -> a runValidate (Validate r) = runReader r -- | A preassignment comprises knowledge about variables, but not -- necessarily fixed values. data PreAssignment = PA PPreAssignment FAssignment SAssignment -- | A (partial) package preassignment. Qualified package names -- are associated with constrained instances. Constrained instances -- record constraints about the instances that can still be chosen, -- and in the extreme case fix a concrete instance. type PPreAssignment = Map QPN (CI QPN) validate :: Tree d c -> Validate (Tree d c) validate = cata go where go :: TreeF d c (Validate (Tree d c)) -> Validate (Tree d c) go (PChoiceF qpn rdm gr ts) = PChoice qpn rdm gr <$> sequence (W.mapWithKey (goP qpn) ts) go (FChoiceF qfn rdm gr b m d ts) = do -- Flag choices may occur repeatedly (because they can introduce new constraints -- in various places). However, subsequent choices must be consistent. We thereby -- collapse repeated flag choice nodes. PA _ pfa _ <- asks pa -- obtain current flag-preassignment case M.lookup qfn pfa of Just rb -> -- flag has already been assigned; collapse choice to the correct branch case W.lookup rb ts of Just t -> goF qfn rb t Nothing -> return $ Fail (varToConflictSet (F qfn)) (MalformedFlagChoice qfn) Nothing -> -- flag choice is new, follow both branches FChoice qfn rdm gr b m d <$> sequence (W.mapWithKey (goF qfn) ts) go (SChoiceF qsn rdm gr b ts) = do -- Optional stanza choices are very similar to flag choices. PA _ _ psa <- asks pa -- obtain current stanza-preassignment case M.lookup qsn psa of Just rb -> -- stanza choice has already been made; collapse choice to the correct branch case W.lookup rb ts of Just t -> goS qsn rb t Nothing -> return $ Fail (varToConflictSet (S qsn)) (MalformedStanzaChoice qsn) Nothing -> -- stanza choice is new, follow both branches SChoice qsn rdm gr b <$> sequence (W.mapWithKey (goS qsn) ts) -- We don't need to do anything for goal choices or failure nodes. go (GoalChoiceF rdm ts) = GoalChoice rdm <$> sequence ts go (DoneF rdm s ) = pure (Done rdm s) go (FailF c fr ) = pure (Fail c fr) -- What to do for package nodes ... goP :: QPN -> POption -> Validate (Tree d c) -> Validate (Tree d c) goP qpn@(Q _pp pn) (POption i _) r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages pkgPresent <- asks presentPkgs -- obtain the present pkg-config pkgs idx <- asks index -- obtain the index svd <- asks saved -- obtain saved dependencies qo <- asks qualifyOptions -- obtain dependencies and index-dictated exclusions introduced by the choice let (PInfo deps _ mfr) = idx ! pn ! i -- qualify the deps in the current scope let qdeps = qualifyDeps qo qpn deps -- the new active constraints are given by the instance we have chosen, -- plus the dependency information we have for that instance -- TODO: is the False here right? let newactives = Dep False {- not exe -} qpn (Fixed i (P qpn)) : L.map (resetVar (P qpn)) (extractDeps pfa psa qdeps) -- We now try to extend the partial assignment with the new active constraints. let mnppa = extend extSupported langSupported pkgPresent (P qpn) ppa newactives -- In case we continue, we save the scoped dependencies let nsvd = M.insert qpn qdeps svd case mfr of Just fr -> -- The index marks this as an invalid choice. We can stop. return (Fail (varToConflictSet (P qpn)) fr) _ -> case mnppa of Left (c, d) -> -- We have an inconsistency. We can stop. return (Fail c (Conflicting d)) Right nppa -> -- We have an updated partial assignment for the recursive validation. local (\ s -> s { pa = PA nppa pfa psa, saved = nsvd }) r -- What to do for flag nodes ... goF :: QFN -> Bool -> Validate (Tree d c) -> Validate (Tree d c) goF qfn@(FN (PI qpn _i) _f) b r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages pkgPresent <- asks presentPkgs -- obtain the present pkg-config pkgs svd <- asks saved -- obtain saved dependencies -- Note that there should be saved dependencies for the package in question, -- because while building, we do not choose flags before we see the packages -- that define them. let qdeps = svd ! qpn -- We take the *saved* dependencies, because these have been qualified in the -- correct scope. -- -- Extend the flag assignment let npfa = M.insert qfn b pfa -- We now try to get the new active dependencies we might learn about because -- we have chosen a new flag. let newactives = extractNewDeps (F qfn) b npfa psa qdeps -- As in the package case, we try to extend the partial assignment. case extend extSupported langSupported pkgPresent (F qfn) ppa newactives of Left (c, d) -> return (Fail c (Conflicting d)) -- inconsistency found Right nppa -> local (\ s -> s { pa = PA nppa npfa psa }) r -- What to do for stanza nodes (similar to flag nodes) ... goS :: QSN -> Bool -> Validate (Tree d c) -> Validate (Tree d c) goS qsn@(SN (PI qpn _i) _f) b r = do PA ppa pfa psa <- asks pa -- obtain current preassignment extSupported <- asks supportedExt -- obtain the supported extensions langSupported <- asks supportedLang -- obtain the supported languages pkgPresent <- asks presentPkgs -- obtain the present pkg-config pkgs svd <- asks saved -- obtain saved dependencies -- Note that there should be saved dependencies for the package in question, -- because while building, we do not choose flags before we see the packages -- that define them. let qdeps = svd ! qpn -- We take the *saved* dependencies, because these have been qualified in the -- correct scope. -- -- Extend the flag assignment let npsa = M.insert qsn b psa -- We now try to get the new active dependencies we might learn about because -- we have chosen a new flag. let newactives = extractNewDeps (S qsn) b pfa npsa qdeps -- As in the package case, we try to extend the partial assignment. case extend extSupported langSupported pkgPresent (S qsn) ppa newactives of Left (c, d) -> return (Fail c (Conflicting d)) -- inconsistency found Right nppa -> local (\ s -> s { pa = PA nppa pfa npsa }) r -- | We try to extract as many concrete dependencies from the given flagged -- dependencies as possible. We make use of all the flag knowledge we have -- already acquired. extractDeps :: FAssignment -> SAssignment -> FlaggedDeps QPN -> [Dep QPN] extractDeps fa sa deps = do d <- deps case d of Simple sd _ -> return sd Flagged qfn _ td fd -> case M.lookup qfn fa of Nothing -> mzero Just True -> extractDeps fa sa td Just False -> extractDeps fa sa fd Stanza qsn td -> case M.lookup qsn sa of Nothing -> mzero Just True -> extractDeps fa sa td Just False -> [] -- | We try to find new dependencies that become available due to the given -- flag or stanza choice. We therefore look for the choice in question, and then call -- 'extractDeps' for everything underneath. extractNewDeps :: Var QPN -> Bool -> FAssignment -> SAssignment -> FlaggedDeps QPN -> [Dep QPN] extractNewDeps v b fa sa = go where go :: FlaggedDeps QPN -> [Dep QPN] go deps = do d <- deps case d of Simple _ _ -> mzero Flagged qfn' _ td fd | v == F qfn' -> L.map (resetVar v) $ if b then extractDeps fa sa td else extractDeps fa sa fd | otherwise -> case M.lookup qfn' fa of Nothing -> mzero Just True -> go td Just False -> go fd Stanza qsn' td | v == S qsn' -> L.map (resetVar v) $ if b then extractDeps fa sa td else [] | otherwise -> case M.lookup qsn' sa of Nothing -> mzero Just True -> go td Just False -> [] -- | Extend a package preassignment. -- -- Takes the variable that causes the new constraints, a current preassignment -- and a set of new dependency constraints. -- -- We're trying to extend the preassignment with each dependency one by one. -- Each dependency is for a particular variable. We check if we already have -- constraints for that variable in the current preassignment. If so, we're -- trying to merge the constraints. -- -- Either returns a witness of the conflict that would arise during the merge, -- or the successfully extended assignment. extend :: (Extension -> Bool) -- ^ is a given extension supported -> (Language -> Bool) -- ^ is a given language supported -> (PkgconfigName -> VR -> Bool) -- ^ is a given pkg-config requirement satisfiable -> Var QPN -> PPreAssignment -> [Dep QPN] -> Either (ConflictSet, [Dep QPN]) PPreAssignment extend extSupported langSupported pkgPresent var = foldM extendSingle where extendSingle :: PPreAssignment -> Dep QPN -> Either (ConflictSet, [Dep QPN]) PPreAssignment extendSingle a (Ext ext ) = if extSupported ext then Right a else Left (varToConflictSet var, [Ext ext]) extendSingle a (Lang lang) = if langSupported lang then Right a else Left (varToConflictSet var, [Lang lang]) extendSingle a (Pkg pn vr) = if pkgPresent pn vr then Right a else Left (varToConflictSet var, [Pkg pn vr]) extendSingle a (Dep is_exe qpn ci) = let ci' = M.findWithDefault (Constrained []) qpn a in case (\ x -> M.insert qpn x a) <$> merge ci' ci of Left (c, (d, d')) -> Left (c, L.map (Dep is_exe qpn) (simplify (P qpn) d d')) Right x -> Right x -- We're trying to remove trivial elements of the conflict. If we're just -- making a choice pkg == instance, and pkg => pkg == instance is a part -- of the conflict, then this info is clear from the context and does not -- have to be repeated. simplify v (Fixed _ var') c | v == var && var' == var = [c] simplify v c (Fixed _ var') | v == var && var' == var = [c] simplify _ c d = [c, d] -- | Merge constrained instances. We currently adopt a lazy strategy for -- merging, i.e., we only perform actual checking if one of the two choices -- is fixed. If the merge fails, we return a conflict set indicating the -- variables responsible for the failure, as well as the two conflicting -- fragments. -- -- Note that while there may be more than one conflicting pair of version -- ranges, we only return the first we find. -- -- TODO: Different pairs might have different conflict sets. We're -- obviously interested to return a conflict that has a "better" conflict -- set in the sense the it contains variables that allow us to backjump -- further. We might apply some heuristics here, such as to change the -- order in which we check the constraints. merge :: #ifdef DEBUG_CONFLICT_SETS (?loc :: CallStack) => #endif CI QPN -> CI QPN -> Either (ConflictSet, (CI QPN, CI QPN)) (CI QPN) merge c@(Fixed i g1) d@(Fixed j g2) | i == j = Right c | otherwise = Left (CS.union (varToConflictSet g1) (varToConflictSet g2), (c, d)) merge c@(Fixed (I v _) g1) (Constrained rs) = go rs -- I tried "reverse rs" here, but it seems to slow things down ... where go [] = Right c go (d@(vr, g2) : vrs) | checkVR vr v = go vrs | otherwise = Left (CS.union (varToConflictSet g1) (varToConflictSet g2), (c, Constrained [d])) merge c@(Constrained _) d@(Fixed _ _) = merge d c merge (Constrained rs) (Constrained ss) = Right (Constrained (rs ++ ss)) -- | Interface. validateTree :: CompilerInfo -> Index -> PkgConfigDb -> Tree d c -> Tree d c validateTree cinfo idx pkgConfigDb t = runValidate (validate t) VS { supportedExt = maybe (const True) -- if compiler has no list of extensions, we assume everything is supported (\ es -> let s = S.fromList es in \ x -> S.member x s) (compilerInfoExtensions cinfo) , supportedLang = maybe (const True) (flip L.elem) -- use list lookup because language list is small and no Ord instance (compilerInfoLanguages cinfo) , presentPkgs = pkgConfigPkgIsPresent pkgConfigDb , index = idx , saved = M.empty , pa = PA M.empty M.empty M.empty , qualifyOptions = defaultQualifyOptions idx }
mydaum/cabal
cabal-install/Distribution/Solver/Modular/Validate.hs
bsd-3-clause
18,341
0
20
5,118
3,670
1,912
1,758
197
14
{-# OPTIONS_HADDOCK not-home #-} module Pinchot.Rules where import Control.Monad (join) import Control.Monad.Trans.State (get, put, State) import qualified Control.Monad.Trans.State as State import qualified Data.List.NonEmpty as NE import Data.Set (Set) import qualified Data.Set as Set import qualified Language.Haskell.TH as T import Pinchot.Types -- | Name a 'Rule' for use in error messages. If you do not name a -- rule using this combinator, the rule's type name will be used in -- error messages. label :: Rule t -> String -> Rule t label (Rule n _ t) s = Rule n (Just s) t -- | Infix synonym for 'label'. Example: -- 'Pinchot.Examples.Postal.rDigit'. (<?>) :: Rule t -> String -> Rule t (<?>) = label infixr 0 <?> -- | Constructs a 'Rule' with no description. rule :: RuleName -> RuleType t -> Rule t rule n = Rule n Nothing -- | Creates a terminal production rule. Example: -- 'Pinchot.Examples.Postal.rLetter'. terminal :: RuleName -> T.Q (T.TExp (t -> Bool)) -- ^ Valid terminal symbols. This is a typed Template Haskell -- expression. To use it, make sure you have -- -- > {-# LANGUAGE TemplateHaskell #-} -- -- at the top of your module, and then use the Template Haskell -- quotes, like this: -- -- > terminal "AtoZ" [|| (\c -> c >= 'A' && c <= 'Z') ||] -> Rule t terminal n i = rule n (Terminal (Predicate i)) -- | Creates a non-terminal production rule. This is the most -- flexible way to create non-terminals. You can even create a -- non-terminal that depends on itself. Example: -- 'Pinchot.Examples.Postal.rLetters'. nonTerminal :: RuleName -- ^ Will be used for the name of the resulting type -> [(BranchName, [Rule t])] -- ^ Branches of the non-terminal production rule. This list -- must have at least one element; otherwise, an error will -- result. -> Rule t nonTerminal n branches = case NE.nonEmpty branches of Nothing -> error $ "nonTerminal: rule has no branches: " ++ n Just bs -> rule n . NonTerminal . fmap (uncurry Branch) $ bs -- | Creates a non-terminal production rule where each branch has -- only one production. This function ultimately uses -- 'nonTerminal'. Each branch is assigned a 'BranchName' that is -- -- @RULE_NAME'PRODUCTION_NAME@ -- -- where @RULE_NAME@ is the name of the rule itself, and -- @PRODUCTION_NAME@ is the rule name for what is being produced. -- -- Example: 'Pinchot.Examples.Postal.rDirection'. union :: RuleName -- ^ Will be used for the name of the resulting type -> [Rule t] -- ^ List of branches. There must be at least one branch; -- otherwise a compile-time error will occur. -> Rule t union n rs = nonTerminal n (fmap f rs) where f rule@(Rule branchName _ _) = (n ++ '\'' : branchName, [rule]) -- | Creates a production for a sequence of terminals. Useful for -- parsing specific words. When used with 'Pinchot.syntaxTrees', the -- resulting data type is a @newtype@ that wraps a @'NE.NonEmpty' -- (t, a)@, where @t@ is the type of the token (often 'Char') and @a@ -- is an arbitrary metadata type. -- -- Examples: 'Pinchot.Examples.Postal.rBoulevard'. series :: RuleName -- ^ Will be used for the name of the resulting type, and for the -- name of the sole data constructor -> [t] -- ^ The list of tokens to use. This must have at least one item; -- otherwise this function will apply 'error'. This list must be -- finite. -> Rule t series n = rule n . Series . get . NE.nonEmpty where get Nothing = error $ "term function used with empty list for rule: " ++ n get (Just a) = a -- | Creates a newtype wrapper. Example: -- 'Pinchot.Examples.Postal.rCity'. wrap :: RuleName -- ^ Will be used for the name of the resulting data type, and for -- the name of the sole data constructor -> Rule t -- ^ The resulting 'Rule' simply wraps this 'Rule'. -> Rule t wrap n r = rule n (Wrap r) -- | Creates a new non-terminal production rule with only one -- alternative where each field has a record name. The name of each -- record is: -- -- @_r\'RULE_NAME\'INDEX\'FIELD_TYPE@ -- -- where @RULE_NAME@ is the name of this rule, @INDEX@ is the index number -- for this field (starting with 0), and @FIELD_TYPE@ is the type of the -- field itself. -- -- Currently there is no way to change the names of the record fields. -- -- Example: 'Pinchot.Examples.Postal.rAddress'. record :: RuleName -- ^ The name of this rule, which is used both as the type name -- and for the name of the sole data constructor -> [Rule t] -- ^ The right-hand side of this rule. This sequence can be empty, -- which results in an epsilon production. -> Rule t record n rs = rule n (Record rs) -- | Creates a rule for a production that optionally produces another -- rule. The name for the created 'Rule' is the name of the 'Rule' to -- which this function is applied, with @'Opt@ appended to the end. -- -- Example: 'Pinchot.Examples.Postal.rOptNewline'. opt :: Rule t -> Rule t opt r@(Rule innerNm _ _) = rule n (Opt r) where n = innerNm ++ "'Opt" -- | Creates a rule for the production of a sequence of other rules. -- The name for the created 'Rule' is the name of the 'Rule' to which -- this function is applied, with @'Star@ appended. -- -- Example: 'Pinchot.Examples.Postal.rPreSpacedWord'. star :: Rule t -> Rule t star r@(Rule innerNm _ _) = rule (innerNm ++ "'Star") (Star r) -- | Creates a rule for a production that appears at least once. The -- name for the created 'Rule' is the name of the 'Rule' to which this -- function is applied, with @'Plus@ appended. -- -- Example: 'Pinchot.Examples.Postal.rDigits'. plus :: Rule t -> Rule t plus r@(Rule innerNm _ _) = rule (innerNm ++ "'Plus") (Plus r) -- | Gets all ancestor rules to this 'Rule'. Includes the current -- rule if it has not already been seen. getAncestors :: Rule t -> State (Set RuleName) [Rule t] getAncestors r@(Rule name _ ty) = do set <- get if Set.member name set then return [] else do put (Set.insert name set) case ty of Terminal _ -> return [r] NonTerminal bs -> do ass <- fmap join . traverse branchAncestors . NE.toList $ bs return $ r : ass Wrap c -> do cs <- getAncestors c return $ r : cs Record ls -> do cs <- fmap join . traverse getAncestors $ ls return $ r : cs Opt c -> do cs <- getAncestors c return $ r : cs Star c -> do cs <- getAncestors c return $ r : cs Plus c -> do cs <- getAncestors c return $ r : cs Series _ -> return [r] where branchAncestors (Branch _ rs) = fmap join . traverse getAncestors $ rs -- | Gets all ancestor 'Rule's. Includes the current 'Rule'. Skips -- duplicates. family :: Rule t -> [Rule t] family rule = State.evalState (getAncestors rule) Set.empty -- | Gets all the ancestor 'Rule's of a sequence of 'Rule'. Includes -- each 'Rule' that is in the sequence. Skips duplicates. families :: [Rule t] -> [Rule t] families = join . flip State.evalState Set.empty . traverse getAncestors
massysett/pinchot
pinchot/lib/Pinchot/Rules.hs
bsd-3-clause
7,155
0
19
1,645
1,326
708
618
106
9
module Din ( module Din , module Exports ) where import Din.Monad as Exports
elliottt/din
src/Din.hs
bsd-3-clause
86
0
4
23
21
15
6
4
0
{-# LANGUAGE FlexibleContexts #-} module Kuelmann97 where import Verilog import Equivalence import Graph import BDDGraph (BDD(B), BDDState, runBDDState, negateBDD, initialBDD, cashOut, bddZero, bddOne, bddAndMany, reduceAll, bddPurge, logBDD) --Graph (BDD, initialBDD, negateBDD, bddOne, bddAnd) --import BDD import Control.Monad.State import Control.Monad.Writer import Data.Maybe import Control.Monad.Trans.Class import Control.Monad.Trans.Maybe import Data.List hiding (union) import Data.Graph.Inductive import Debug.Trace import qualified Data.Map as M import qualified Data.IntMap as I import qualified Data.Set as S import Text.Printf --type KS a = WriterT String (State (G, M.Map BDD Node)) a -- --type KS a = WriterT [Log] (State (G, M.Map BDD Node, M.Map Node BDD)) a type KS = WriterT [String] (StateT (G, M.Map BDD Node, M.Map Node BDD, Int) BDDState) liftX :: BDDState a -> KS a liftX = lift . lift liftY :: BDDState a -> MaybeT KS a liftY = lift . liftX getNodeBddM :: KS (M.Map Node BDD) getNodeBddM = do (_, _, m, _) <- get return m getBddNodeM :: KS (M.Map BDD Node) getBddNodeM = do (_, m, _, _) <- get return m getCount :: KS Int getCount = do (g, m1, m2, c) <- get put (g, m1, m2, c+1) return c getBDD :: Node -> MaybeT KS BDD getBDD n = do MaybeT $ M.lookup n <$> getNodeBddM --getBDDfromEdge :: LEdge Bool -> MaybeT KS BDD getBDDfromEdge :: LEdge Bool -> MaybeT KS BDD getBDDfromEdge (o, _, v) = do bdd <- getBDD o if v then return bdd else liftY $ negateBDD bdd --Just bdd <- getBDD o --liftX $ negateBDD bdd --bdd <- runMaybeT $ getBDD o --return bdd --negateBDD bdd {-case mbdd of Nothing -> return Nothing Just bdd -> if v then return $ Just bdd else return $ Just bdd -} --do negBdd <- lift $ negateBDD bdd --return Just negBdd putG :: G -> KS () putG g = do (_, x, y, z) <- get put (g, x, y, z) getG :: KS G getG = do (g, _, _, _) <- get return g -- | Merges 2 nodes in the graph. -- | The left one is removed and the right one is mantained -- | All the sucessors are moved to the node that remains. mergeNodes :: (Node, Node) -> KS () mergeNodes (n1, n2) = do g <- getG let [c1, c2] = sort [n1, n2] es = out g c2 -- getting the edges of n2 des = [(o, d) | (o, d, l) <- es] -- preparing to remove the edges from n2 es' = [(c1, d, l) | (o, d, l) <- es] --preparing to add the edges to n1 g' = insEdges es' $ delEdges des g putG g' --liftX $ logBDD ("// before purge of " ++ show c2) purgeNode c2 {- g'' <- getG lift $ tell [("// before merge " ++ show (c1, c2) ++ "\n" ++ showGraph g ++ "\n")] lift $ tell [("// after merge " ++ show (c1, c2) ++ "\n" ++ showGraph g' ++ "\n")] lift $ tell [("// after purge " ++ show c2 ++ "\n" ++ showGraph g'' ++ "\n")] liftX $ logBDD ("after purge of " ++ show c2) -} isWire n g = case l of Wire _ -> True _ -> False where Just l = lab g n purgeNode :: Node -> KS () purgeNode n = do g <- getG when (gelem n g && isWire n g && outdeg g n == 0) $ do --liftX $ bddPurge (B n) putG (delNode n g) mapM_ purgeNode [o | (o, _, _) <- inn g n] getPreds :: Node -> KS (Node, [(Node, Bool)]) getPreds y = do g <- getG return (y, sort $ [(o, v) | (o, d, v) <- inn g y]) checkResult :: KS (Either String Bool) checkResult = do g <- getG ps <- mapM getPreds (getOutputs g) let ps' = sortBy (\a b -> snd a `compare` snd b) ps ps'' = groupBy (\a b -> snd a == snd b) ps' r = all (\x -> length x >= 2) ps'' return $ -- $ traceShow (getOutputs g, ps'', r) $ Right r storeBDD :: BDD -> Node -> KS () storeBDD bdd n = do (g, m1, m2, c) <- get put (g, M.insert bdd n m1, M.insert n bdd m2, c) deleteBDD :: Node -> KS () deleteBDD n = do (g, m1, m2, c) <- get put (g, m1, M.delete n m2, c) kuelmannNode :: Node -> KS () kuelmannNode n1 = do g <- getG c <- getCount runMaybeT $ do bdd <- calcBDDNode n1 lift $ storeBDD bdd n1 cash <- liftX $ reduceAll >> cashOut mapM_ mergeNodes cash -- TODO merge Nodes trace (printf "Current Node: %5d -- %5d/%5d Cash Out %s" n1 c (size g) (show cash)) $ return () {- kuelmannNode :: Node -> KS () kuelmannNode n1 = do (g, m1, m2) <- get mbdd <- calcBDDNode n1 case mbdd of Nothing -> return () --tell $ "Could not create BDD for " ++ show n1 Just bdd -> case M.lookup bdd m1 of Nothing -> storeBDD bdd n1 Just n2 -> do --lift $ tell $ [(g, "BDDs match: "++ show (n1, n2) ++ " -> "++ show bdd)] nr <- mergeNodes n1 n2 storeBDD bdd nr -} {- calcBDDNode' n = do mbdd <- calcBDDNode n case mbdd of Nothing -> return () Just bdd -> storeBDD bdd n return mbdd -} calcBDDNode :: Node -> MaybeT KS BDD calcBDDNode n = do g <- lift getG if indeg g n == 0 then case val g n of Wire _ -> error "should not be empty" Output _ -> error "should not be empty" ValZero -> return bddZero ValOne -> return bddOne Input _ -> liftY $ initialBDD n else do let inp_edges = (inn g n) is <- mapM getBDDfromEdge inp_edges liftY $ bddAndMany (Just n) is runKS :: [Node] -> [Node] -> G -> KS a -> (a, [String]) runKS is ns g m = (r, kuelLog ++ bddLog) --((a0, [String]), (BDDGraph.T, [(Node, Node)])) where (((r, kuelLog), bddLog), (bddGraphRes, eqs)) = runBDDState is ns $ flip evalStateT (g, M.empty, M.empty, 1) (runWriterT m) -- | Checks Equivalence of circuits based on Kuelmann97 equivKuelmann97_2 :: Verilog -> Verilog -> (Either String Bool, [String]) equivKuelmann97_2 v1 v2 = runKS inputs ns g $ do mapM_ kuelmannNode todo checkResult where g = makeGraphV [v1, v2] todo = mybfs g inputs = getInputs g ns = nodes g
wuerges/vlsi_verification
src/Kuelmann97.hs
bsd-3-clause
6,051
0
14
1,761
1,867
985
882
129
6
{-# LANGUAGE DeriveFoldable , DeriveFunctor , TypeFamilies #-} module IntSet ( IntSet , singleton , insert , member , notMember , delete , intersection ) where import Control.Lens import Data.Constraint import Data.Foldable import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Semigroup import Int newtype IntSet a = IntSet { unIntSet :: IntMap a } deriving ( Functor , Foldable ) instance IsInt a => Semigroup (IntSet a) where x <> y = IntSet $ unIntSet x <> unIntSet y instance IsInt a => Monoid (IntSet a) where mempty = IntSet IntMap.empty mappend x y = IntSet $ mappend (unIntSet x) (unIntSet y) mconcat = IntSet . mconcat . fmap unIntSet type instance Index (IntSet a) = a type instance IxValue (IntSet a) = a instance IsInt a => Contains (IntSet a) where type Containing (IntSet a) f = Functor f contains k f s = f (member k s) <&> \ b -> if b then insert k s else delete k s {-# INLINE contains #-} containsProof _ _ = Sub Dict singleton :: IsInt a => a -> IntSet a singleton a = IntSet $ IntMap.singleton (toInt a) a insert :: IsInt a => a -> IntSet a -> IntSet a insert a = IntSet . IntMap.insert (toInt a) a . unIntSet member :: IsInt a => a -> IntSet a -> Bool member a = IntMap.member (toInt a) . unIntSet notMember :: IsInt a => a -> IntSet a -> Bool notMember a = IntMap.notMember (toInt a) . unIntSet delete :: IsInt a => a -> IntSet a -> IntSet a delete a = IntSet . IntMap.delete (toInt a) . unIntSet intersection :: IsInt a => IntSet a -> IntSet b -> IntSet a intersection xs ys = IntSet $ IntMap.intersection (unIntSet xs) (unIntSet ys)
sonyandy/mlf
src/IntSet.hs
bsd-3-clause
1,796
0
9
498
666
338
328
48
1
-- | -- Module : LambdaCat.History -- Copyright : Andreas Baldeau, Daniel Ehlers -- License : BSD3 -- Maintainer : Andreas Baldeau <[email protected]>, -- Daniel Ehlers <[email protected]> -- Stability : Alpha -- -- This module provides lambdacat's history functionality. The history is -- not stored linear as in other browsers, it is stored as a tree. This way -- navigating backwards and then along another path no navigation history is -- lost. module LambdaCat.History ( -- * The data structure History -- * Construction , singleton -- * Navigation , back , forward -- * Modification , insert , insertAndForward , updateCurrent -- * Query , current , hasBack , hasForward , getForwards ) where import Data.IntMap ( IntMap ) import qualified Data.IntMap as IntMap import Data.Maybe ( fromJust , isJust ) import Network.URI -- | Directed tree with 'URI's as weights. type History = DTree URI -- | Weighted directed tree data DTree a = DTree { dTreeWeight :: a -- ^ Weight of the node. , dTreeBack :: Maybe (Int, DTree a) -- ^ The nodes parent, if any. -- The Int is the number by which -- this node can be reached from -- its parent. , dTreeForward :: IntMap (DTree a) -- ^ The numbered childs. } deriving Show -- | A tree with one node. singleton :: a -- ^ The weight for the node. -> DTree a -- ^ The new tree. singleton weight = DTree { dTreeWeight = weight , dTreeBack = Nothing , dTreeForward = IntMap.empty } -- | Move backwards in the tree. back :: DTree a -- ^ Tree to navigate in. -> Maybe (DTree a) -- ^ Just the parent node or Nothing if none. back dt = case dTreeBack dt of Just (index, dt') -> let newDt = dt { dTreeBack = Nothing } forwMap = dTreeForward dt' in Just dt' { dTreeForward = IntMap.insert index newDt forwMap } Nothing -> Nothing -- | Indicates, if a back operation on the tree is possible. hasBack :: DTree a -> Bool hasBack = isJust . dTreeBack -- | Move forward in the tree. forward :: Int -- ^ Number of the child node to navigate to. -> DTree a -- ^ The tree to navigate in. -> Maybe (DTree a) -- ^ Just the child node or Nothing if not existing. forward index dt = case mdt' of Just dt' -> Just $ dt' { dTreeBack = Just (index, newDt) } Nothing -> Nothing where forwMap = dTreeForward dt (mdt', forwMap') = IntMap.updateLookupWithKey (\_ -> const Nothing) index forwMap newDt = dt { dTreeForward = forwMap' } -- | Returns the weight of the trees current node. current :: DTree a -> a current = dTreeWeight -- | Replace the weight at the current node. updateCurrent :: a -> DTree a -> DTree a updateCurrent a tree = tree { dTreeWeight = a } -- | Indicates if a forward operation on this tree is possible. hasForward :: DTree a -> Bool hasForward = not . IntMap.null . dTreeForward -- | Returns a list of child nodes identified by its numbers and their -- weights. getForwards :: DTree a -> [(Int, a)] getForwards = map withSnd . IntMap.toList . dTreeForward where withSnd :: (Int, DTree a) -> (Int, a) withSnd (key, dt) = (key, dTreeWeight dt) -- | Insert a new child node adjacent to the trees current node. insert :: a -> DTree a -> DTree a insert weight dt = dt { dTreeForward = IntMap.insert (newIndex forwMap) newDt forwMap } where forwMap = dTreeForward dt newDt = singleton weight -- | Insert a new child node adjacent to the tress current node and then -- move forward to it. insertAndForward :: a -> DTree a -> DTree a insertAndForward weight dt = fromJust . forward index $ dt { dTreeForward = IntMap.insert index newDt forwMap } where forwMap = dTreeForward dt newDt = singleton weight index = newIndex forwMap -- | Internal function to generate the next free index on an IntMap. newIndex :: IntMap a -> Int newIndex m | IntMap.null m = 0 | otherwise = 1 + fst (IntMap.findMax m)
baldo/lambdacat
LambdaCat/History.hs
bsd-3-clause
4,378
0
14
1,339
857
477
380
87
2
module Fragnix.SliceSymbols ( updateEnvironment , findMainSliceIDs , lookupLocalIDs ) where import Fragnix.Slice (SliceID,sliceIDModuleName) import Fragnix.LocalSlice (LocalSliceID) import Language.Haskell.Names ( Environment, Symbol(symbolName,symbolModule)) import Language.Haskell.Exts ( ModuleName(ModuleName),Name(Ident)) import Data.Map ( Map) import qualified Data.Map as Map ( toList,lookup,map) import Control.Monad ( guard) -- | Find the possible IDs of the main slice in a map from symbol to slice. findMainSliceIDs :: Map Symbol SliceID -> [SliceID] findMainSliceIDs symbolSlices = do (symbol,sliceID) <- Map.toList symbolSlices guard (symbolName symbol == Ident () "main") return sliceID -- | Replace in the given environment the original module of all symbols -- with the ID of the binding slice. updateEnvironment :: Map Symbol SliceID -> Environment -> Environment updateEnvironment symbolSlices environment = Map.map (map (updateSymbol symbolSlices)) environment -- | When the given symbol is in the map replace its original module with -- the SliceID from the map. updateSymbol :: Map Symbol SliceID -> Symbol -> Symbol updateSymbol symbolSlices symbol = case Map.lookup symbol symbolSlices of Nothing -> symbol Just sliceID -> symbol { symbolModule = ModuleName () (sliceIDModuleName sliceID) } -- | Look up the slice IDs for all symbols in the given Map. lookupLocalIDs :: Map Symbol LocalSliceID -> Map LocalSliceID SliceID -> Map Symbol SliceID lookupLocalIDs symbolLocalIDs slices = Map.map (\localSliceID -> case Map.lookup localSliceID slices of Just sliceID -> sliceID Nothing -> error "symbol's local slice id not found") symbolLocalIDs
phischu/fragnix
src/Fragnix/SliceSymbols.hs
bsd-3-clause
1,745
0
12
308
403
218
185
33
2
module Main where import System.Environment (getArgs, getProgName) import Control.Monad (when) import System.Exit (exitSuccess, exitFailure) import Import (importModules, concatModules, listupModules) import Options (getOptions, Options(..)) import WatchFile (watchFiles) main :: IO [FilePath] main = do args <- getArgs progName <- getProgName (options, (input:_)) <- getOptions progName args let out = optOutput options if optWatch options then do watchFiles $ performImport input out else performImport input out performImport :: FilePath -> FilePath -> IO [FilePath] performImport filename out = do modules <- importModules filename writeFile out =<< concatModules modules listupModules modules
ayachigin/importjs
src/Main.hs
bsd-3-clause
735
0
11
125
233
122
111
21
2
module Main where import Control.Monad (void) import Sound.Player (appMain) main :: IO () main = void appMain
potomak/haskell-player
app/Main.hs
bsd-3-clause
114
0
6
21
42
24
18
5
1
----------------------------------------------------------------------------- -- | -- Module : Network.AWS.AWSConnection -- Copyright : (c) Greg Heartsfield 2007 -- License : BSD3 -- -- Connection and authentication info for an Amazon AWS request. ----------------------------------------------------------------------------- module Network.AWS.AWSConnection ( -- * Constants defaultAmazonS3Host, defaultAmazonS3Port, -- * Function Types amazonS3Connection, amazonS3ConnectionFromEnv, -- * Data Types AWSConnection(..) ) where import System.Environment -- | An Amazon Web Services connection. Everything needed to connect -- and authenticate requests. data AWSConnection = AWSConnection { awsHost :: String, -- ^ Service provider hostname awsPort :: Int, -- ^ Service provider port number awsAccessKey :: String, -- ^ Access Key ID awsSecretKey :: String -- ^ Secret Access Key } deriving (Show) -- | Hostname used for connecting to Amazon's production S3 service (@s3.amazonaws.com@). defaultAmazonS3Host :: String defaultAmazonS3Host = "s3.amazonaws.com" -- | Port number used for connecting to Amazon's production S3 service (@80@). defaultAmazonS3Port :: Int defaultAmazonS3Port = 80 -- | Create an AWSConnection to Amazon from credentials. Uses the -- production service. amazonS3Connection :: String -- ^ Access Key ID -> String -- ^ Secret Access Key -> AWSConnection -- ^ Connection to Amazon S3 amazonS3Connection = AWSConnection defaultAmazonS3Host defaultAmazonS3Port -- | Retrieve Access and Secret keys from environment variables -- AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, respectively. -- Either variable being undefined or empty will result in -- 'Nothing'. amazonS3ConnectionFromEnv :: IO (Maybe AWSConnection) amazonS3ConnectionFromEnv = do ak <- getEnvKey "AWS_ACCESS_KEY_ID" sk0 <- getEnvKey "AWS_ACCESS_KEY_SECRET" sk1 <- getEnvKey "AWS_SECRET_ACCESS_KEY" return $ case (ak, sk0, sk1) of ("", _, _) -> Nothing ( _, "", "") -> Nothing ( _, "", _) -> Just (amazonS3Connection ak sk1) ( _, _, _) -> Just (amazonS3Connection ak sk0) where getEnvKey s = catch (getEnv s) (const $ return "")
necrobious/hS3
Network/AWS/AWSConnection.hs
bsd-3-clause
2,395
0
13
566
326
193
133
30
4
module Main ( main ) where ------------------------------------------------------------------------------- import Control.Applicative import Control.Monad.State import Data.Attoparsec.ByteString import qualified Data.ByteString as BS import Debug.Trace import Test.Tasty import Test.Tasty.HUnit ------------------------------------------------------------------------------- import Database.Redis.RDB ------------------------------------------------------------------------------- main :: IO () main = defaultMain testSuite ------------------------------------------------------------------------------- testSuite :: TestTree testSuite = testGroup "redis-rdb-parser" [ testCase "parses an example file" $ do bs <- BS.readFile "test/data/example.rdb" print (parseOnly rdbP bs) assertFailure "todo test" ] ------------------------------------------------------------------------------- rdbP :: Parser (RDBMagicNumber, RDBVersionNumber, [(RDBDatabaseSelector, KVPair)], RCRC64, EOF) rdbP = do mn <- rdbMagicNumberP vn <- traceShow ("mn", mn) rdbVersionNumberP kvps <- many (trace "try left" (Left <$> rdbDatabaseSelectorP) <|> trace "tryRight" (Right <$> kvPairP)) eof <- eofP crc <- checksumP return (mn, vn, kvState kvps, crc, eof) ------------------------------------------------------------------------------- kvState :: [Either RDBDatabaseSelector KVPair] -> [(RDBDatabaseSelector, KVPair)] kvState eithers = concat $ flip evalState (RDBDatabaseSelector 0) $ forM eithers $ \e -> do case e of Left sel -> do put sel return mempty Right kvp -> do sel <- get return [(sel, kvp)]
MichaelXavier/redis-rdb-parser
test/Main.hs
bsd-3-clause
1,753
0
16
334
402
212
190
36
2
module TriPt2 ( TriPt2(..), triMidPt2, triAreaPt2, triAreaMidPt2 ) where import Pt2 newtype TriPt2 a = TriPt2 (Pt2 a,Pt2 a,Pt2 a) deriving Show triMidPt2 :: Fractional a => TriPt2 a -> Pt2 a triMidPt2 (TriPt2 (a,b,c)) = ( a + b + c ) `divPt2` 3 -- | NOTE: clockwise area is positive, counterclockwise is negative triAreaPt2 :: Fractional a => TriPt2 a -> a triAreaPt2 (TriPt2 (a,b,c)) = (a - c) `crossPt2` (a - b) / 2 -- | NOTE: clockwise area is positive, counterclockwise is negative triAreaMidPt2 :: Fractional a => TriPt2 a -> (a, Pt2 a) triAreaMidPt2 t = (triAreaPt2 t, triMidPt2 t)
trenttobler/hs-asteroids
src/TriPt2.hs
bsd-3-clause
632
0
8
149
233
129
104
13
1
module Main where import ABS.Runtime import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.Runners.Html import System.IO.Silently (hCapture) import System.Environment (getArgs, withArgs) import System.IO import Control.Monad (replicateM_, replicateM) import Control.Monad.Trans.Class (lift) import Control.Concurrent (threadDelay) import Data.IORef (readIORef, modifyIORef') main :: IO () main = do args <- getArgs -- append to stdin args withArgs ("-j1":args) $ -- don't run tests in parallel because it messes output hSetBuffering stderr LineBuffering >> defaultMainWithIngredients (htmlRunner:defaultIngredients)( localOption (mkTimeout 10000000) $ -- timeouts any test at 10s testGroup "coop-scheduling" [ testCase "case_fifo" case_fifo , testCase "case_future_forwarding" case_future_forwarding , testCase "case_await_boolean" case_await_boolean ]) data C = C { x :: Int} -- an obj with 1 attribute -- object's smart constructor c' = C { x = 0} -- we have to use stderr stream because tasty uses stdout and interferes println' :: String -> ABS' () println' = lift . hPutStrLn stderr case_fifo :: IO () case_fifo = do let method1 this = do lift $ threadDelay 10 suspend this println' "m1" let method2 this = do lift $ threadDelay 10 suspend this println' "m2" let main = withArgs [] $ main_is' (\ this -> do o1 <- lift $ newlocal' this (const $ return ()) c' o2 <- lift $ newlocal' this (const $ return ()) c' fs <- replicateM 100 (lift $ do f1 <- o1 <!> method1 f2 <- o2 <!> method2 return [f1,f2] ) mapM_ (\ f -> awaitFuture' this f) (concat fs) -- so that main does not exit too early ) (pure ()) (outStr, ()) <- hCapture [stderr] main let outLines = lines outStr assertEqual "Wrong size of output" 200 (length $ outLines) assertEqual "Async method calls not in COG-FIFO order" (take 200 $ cycle ["m1","m2"]) outLines assertEqual "Wrong nr. of m1 method calls" 100 (countElem "m1" $ outLines) assertEqual "Wrong nr. of m2 method calls" 100 (countElem "m2" $ outLines) case_future_forwarding :: IO () case_future_forwarding = do let method1 this = do lift $ threadDelay 10 suspend this return 3 let method2 f this = do awaitFuture' this f res <- lift $ get f let res' = res + 1 println' (show res') return res' let main = withArgs [] $ main_is' (\ this -> do o1 <- lift $ new (const $ return ()) c' o2 <- lift $ new (const $ return ()) c' replicateM_ 100 (do f1 <- lift $ o1 <!> method1 f2 <- lift $ o2 <!> method2 f1 awaitFuture' this f2 res <- lift $ get f1 lift $ threadDelay 10 println' (show res) ) ) (pure ()) (outStr, ()) <- hCapture [stderr] main let outLines = lines outStr assertEqual "Interleaving of future forwarding err'ed" (take 200 $ cycle ["4","3"]) outLines case_await_boolean :: IO () case_await_boolean = do let inc this@(Obj' contents _) = do lift $ threadDelay 10 awaitBool' this (\ C { x = x } -> x == 0) lift $ modifyIORef' contents (\ C { x = x } -> C { x = x + 1}) println' "inc" suspend this return () let dec this@(Obj' contents _) = do lift $ threadDelay 10 awaitBool' this (\ C { x = x } -> x == 1) lift $ modifyIORef' contents (\ C { x = x } -> C { x = x - 1}) println' "dec" suspend this return () let check this@(Obj' contents _) = do C { x = x } <- lift $ readIORef contents return x let main = withArgs [] $ main_is' (\ this -> do o1 <- lift $ new (const $ return ()) c' fs <- replicateM 100 (lift $ do f1 <- o1 <!> dec f2 <- o1 <!> inc return [f1,f2] ) mapM_ (\ f -> awaitFuture' this f) (concat fs) lift $ threadDelay 1000 f <- lift $ o1 <!> check res <- lift $ get f lift $ assertEqual "wrong last value" 0 res ) (pure ()) let main_local = withArgs [] $ main_is' (\ this -> do o1 <- lift $ newlocal' this (const $ return ()) c' fs <- replicateM 100 (lift $ do f1 <- o1 <!> dec f2 <- o1 <!> inc return [f1,f2] ) mapM_ (\ f -> awaitFuture' this f) (concat fs) lift $ threadDelay 1000 f <- lift $ o1 <!> check awaitFuture' this f res <- lift $ get f lift $ assertEqual "wrong last value" 0 res ) (pure ()) (outStr, ()) <- hCapture [stderr] main let outLines = lines outStr (outStr_local, ()) <- hCapture [stderr] main_local let outLines_local = lines outStr_local assertEqual "Interleaving of boolean-awaits err'ed" (take 200 $ cycle ["inc","dec"]) outLines assertEqual "Local interleaving of boolean-awaits err'ed" (take 200 $ cycle ["inc","dec"]) outLines_local countElem :: Eq a => a -> [a] -> Int countElem i = length . filter (i==)
abstools/habs-runtime
tests/unit.hs
bsd-3-clause
6,136
0
23
2,545
1,909
917
992
130
1
import GHC.Generics import Control.Monad import Control.Monad.Reader import System.IO import Database.Seakale.PostgreSQL hiding (withConn) import Database.Seakale.PostgreSQL.FromRow import Database.Seakale.Store import Database.Seakale.Store.Join import Shared newtype TableStats = TableStats { numRows :: Integer } deriving Generic instance Storable PSQL Two One TableStats where data EntityID TableStats = TableStatsID String String deriving Generic relation _ = Relation { relationName = "pg_stat_user_tables" , relationIDColumns = ["schemaname", "relname"] , relationColumns = ["n_live_tup"] } instance FromRow PSQL Two (EntityID TableStats) instance FromRow PSQL One TableStats data TableStatsProperty backend n a where TableStatsNumRows :: TableStatsProperty PSQL One Integer instance Property backend TableStats TableStatsProperty where toColumns _ TableStatsNumRows = ["n_live_tup"] data TableInfo = TableInfo { hasRules :: Bool , hasTriggers :: Bool } deriving Generic instance Storable PSQL Two Two TableInfo where data EntityID TableInfo = TableInfoID String String deriving Generic relation _ = Relation { relationName = "pg_tables" , relationIDColumns = ["schemaname", "tablename"] , relationColumns = ["hasrules", "hastriggers"] } instance FromRow PSQL Two (EntityID TableInfo) instance FromRow PSQL Two TableInfo dbProg :: Select [Entity (LeftJoin TableStats TableInfo)] dbProg = selectJoin (leftJoin_ (JLeft EntityID ==~ JRight EntityID)) (JLeft TableStatsNumRows >. 0) (asc (JLeft TableStatsNumRows)) main :: IO () main = withConn $ \conn -> do eRes <- runReaderT (runRequest defaultPSQL (runSelectT dbProg)) conn case eRes of Left err -> hPutStrLn stderr $ "Error: " ++ show err Right res -> forM_ res $ \(Entity (LeftJoinID (TableStatsID schemaName relName) _) (LeftJoin TableStats{..} mInfo)) -> do putStr $ "Table " ++ schemaName ++ "." ++ relName ++ " has around " ++ show numRows ++ " rows" case mInfo of Nothing -> putStrLn "." Just TableInfo{..} -> putStrLn $ " (has rules: " ++ show hasRules ++ ", has triggers: " ++ show hasTriggers ++ ")."
thoferon/seakale
demo/src/Join.hs
bsd-3-clause
2,312
0
23
527
643
340
303
-1
-1
{-# LANGUAGE CPP #-} -- ghc options {-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- {-# OPTIONS_GHC -fno-warn-missing-signatures #-} -- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-} -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <[email protected]> -- Stability : experimental -- Portability: non-portable -- -- pretty printing of binders for Pire's abstract and concrete syntax module Pire.Pretty.Binder where import Pire.Syntax.Binder import Pire.Pretty.Common import Pire.Pretty.Nm () import Pire.Pretty.Ws () import Pire.Pretty.Pattern () import Pire.Pretty.Token () import Text.PrettyPrint as TPP #ifdef MIN_VERSION_GLASGOW_HASKELL #if MIN_VERSION_GLASGOW_HASKELL(7,10,3,0) -- ghc >= 7.10.3 #else -- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined #endif #else -- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x) import Control.Applicative #endif dispBinder :: Disp s => Binder s -> M Doc dispBinder (Binder v) = disp v dispBinder (Binder_ v ws) = (<>) <$> (disp v) <*> disp ws dispBinder (BinderInBrackets bo bnd bc) = do dbo <- disp bo dbnd <- disp bnd dbc <- disp bc return $ dbo <> dbnd <> dbc -- return $ text "error: dispBinder(BinderInBrackets ...)" -- dispBinder (BinderInBrackets bo (Binder v ws) bc) = (<>) <$> (disp v) <*> disp ws dispBinder (InvisibleBinder i) = disp i -- maybe more like this (unfinished) -- nm <- asNm WildcardName i -- return $ nm instance Disp s => Disp (Binder s) where disp p = dispBinder p
reuleaux/pire
src/Pire/Pretty/Binder.hs
bsd-3-clause
1,895
0
9
418
278
159
119
24
1
{-# LANGUAGE OverloadedStrings #-} module AudioResource where import Data.Aeson import Control.Applicative data AudioResource = AudioResource [String] String deriving (Show) instance FromJSON AudioResource where parseJSON (Object x) = AudioResource <$> x .: "Audio" <*> x .: "download" parseJSON _ = fail "Failed to parse AudioResource object"
ksaveljev/udemy-downloader
AudioResource.hs
mit
352
0
9
53
85
46
39
8
0
-- © 2001 Peter Thiemann module Wash.PPM where import Char data Pixmap = Pixmap { width :: Int , height :: Int , maximumColorValue :: Int , pixelFun :: Int -> Int -> Pixel } type Pixel = (Int, Int, Int) instance Show Pixmap where show pm = if maximumColorValue pm > 255 then showPixmap pm "P3" showAsciiPixel else showPixmap pm "P6" showBinaryPixel showPixmap pm code showPixel = let w = width pm h = height pm in code ++ '\n' : (show w) ++ '\n' : (show h) ++ '\n' : (show $ maximumColorValue pm) ++ '\n' : [ ch | y <- [1..h], x <- [1..w], ch <- showPixel (pixelAt pm x y)] showAsciiPixel (r, g, b) = show r ++ ' ' : show g ++ ' ' : show b ++ "\n" showBinaryPixel (r, g, b) = [chr r, chr g, chr b] instance Read Pixmap where readsPrec i = readsPixmap readsPixmap ('P':'3':rest) = readsPixmap1 readsAsciiPixel (dropWhile isSpace rest) readsPixmap ('P':'6':rest) = readsPixmap1 readsBinaryPixel (dropWhile isSpace rest) readsPixmap str = [] readsPixmap1 readsPixel str = do (w, rest1) <- reads str (h, rest2) <- reads (dropWhile isSpace rest1) (m, rest3) <- reads (dropWhile isSpace rest2) (pixs, rest4) <- readsPixels w h readsPixel (dropWhile isSpace rest3) return (Pixmap { width = w, height = h, maximumColorValue = m, pixelFun = \x y -> (pixs !! y) !! x } ,dropWhile isSpace rest4) readsPixels w h readsPixel str = if h > 0 then do (sl1, rest1) <- readsScanline w readsPixel str (sls, rest2) <- readsPixels w (h-1) readsPixel rest1 return (sl1 : sls, rest2) else return ([], str) readsScanline w readsPixel str = if w > 0 then do (pix1, rest1) <- readsPixel str (pixs, rest2) <- readsScanline (w-1) readsPixel rest1 return (pix1 : pixs, rest2) else return ([], str) readsAsciiPixel str = do (r, rest1) <- reads (dropWhile isSpace str) (g, rest2) <- reads (dropWhile isSpace rest1) (b, rest3) <- reads (dropWhile isSpace rest2) return ((r,g,b), rest3) readsBinaryPixel (cr:cg:cb:rest) = return ((ord cr, ord cg, ord cb), rest) readsBinaryPixel _ = [] -- ====================================================================== create :: Int -> Int -> Int -> Pixel -> Pixmap create w h m p = Pixmap w h m (const (const p)) oval :: Pixmap -> (Int, Int) -> (Int, Int) -> Pixel -> Bool -> Pixmap line :: Pixmap -> (Int, Int) -> (Int, Int) -> Pixel -> Pixmap rectangle :: Pixmap -> (Int, Int) -> (Int, Int) -> Pixel -> Bool -> Pixmap -- arc -- poly -- text -- bitmap -- image oval pm (xul,yul) (xlr,ylr) p fill = pm { pixelFun = fun } where w2 = (xlr - xul) `div` 2 h2 = (ylr - yul) `div` 2 xm = xul + w2 ym = yul + h2 lastfun = pixelFun pm fun x y | y < yul || y > ylr || x < xul || x > xlr = lastfun x y | d <= 1.0 && (fill || d >= 0.9) = p | otherwise = lastfun x y where d = fromIntegral ((x - xm) ^ 2) / fromIntegral (w2 ^ 2) + fromIntegral ((y - ym) ^ 2) / fromIntegral (h2 ^ 2) rectangle pm (xul,yul) (xlr,ylr) p fill = pm { pixelFun = fun } where lastfun = pixelFun pm fun x y | y < yul || y > ylr || x < xul || x > xlr = lastfun x y | x == xul || x == xlr || y == yul || y == ylr || fill = p | otherwise = lastfun x y -- line = line2 line1 pm (xul,yul) (xlr,ylr) p = pm { pixelFun = fun } where lastfun = pixelFun pm fun x y | x < xul && x < xlr || x > xul && x > xlr || y < yul && y < ylr || y > yul && y > ylr = lastfun x y | (x,y) `elem` points = p | otherwise = lastfun x y -- suppose abs dx >= abs dy dx = xlr - xul dy = ylr - yul adx = abs dx ady = abs dy sdx = signum dx sdy = signum dy points | adx >= ady = k adx ady sdx sdy xlr ylr (adx `div` 2) (xul,yul) | otherwise = [(x,y) | (y,x) <- k ady adx sdy sdx ylr xlr (ady `div` 2) (yul,xul)] k adx ady sdx sdy xlr ylr = m where m v (x, y) | x == xlr && y == ylr = [(x,y)] | otherwise = (x, y) : m nv' (nx, ny) where nv = v - ady nv' | nv > 0 = nv | otherwise = nv + adx nx = x + sdx ny | nv > 0 = y | otherwise = y + sdy line2 pm (xul,yul) (xlr,ylr) p = pm { pixelFun = fun } where lastfun = pixelFun pm dx = fromIntegral (xlr - xul) dy = fromIntegral (ylr - yul) xul' = fromIntegral xul yul' = fromIntegral yul -- solve: dx1 * dx + dy1 * dy = 0 dx1 = - dy dy1 = dx divisor = dy1 * dx - dy fun x y | x < xul && x < xlr || x > xul && x > xlr || y < yul && y < ylr || y > yul && y > ylr = lastfun x y | dx == 0 && x == xul || dy == 0 && y == yul = p | d <= lineWidth = p | otherwise = lastfun x y where x' = fromIntegral x y' = fromIntegral y -- solve: x0 = x + t * dx1 -- && y0 = y + t * dy1 -- && x0 = xul + s * dx -- && y0 = yul + s * dy -- for x0, y0, s, t s = ((x' - xul') * dy1 + yul' - y') / divisor x0 = xul' + s * dx y0 = yul' + s * dy d = (x0 - x')^2 + (y0 - y')^2 lineWidth = 1.0 point pm (x0,y0) p = pm { pixelFun = fun } where lastfun = pixelFun pm fun x y | x == x0 && y == y0 = p | otherwise = lastfun x y comp pm1 pm2 (xul,yul) p = pm1 { pixelFun = fun } where w2 = width pm2 h2 = height pm2 lastfun = pixelFun pm1 fun x y | x2 >= 0 && y2 >= 0 && x2 < w2 && y2 < h2 && p2 /= p = p2 | otherwise = lastfun x y where x2 = x - xul y2 = y - yul p2 = pixelFun pm2 x2 y2 -- for efficiency and versatility rely on external programs: -- ppmmake : create a canvas -- pbmtext : create a text image (pbmtopgm; pgmtoppm) -- pnmcomp : compose two images -- giftopnm : image to portable anymap -- missing: ppmline ppmoval pixelAt :: Pixmap -> Int -> Int -> Pixel pixelAt = pixelFun -- ====================================================================== -- a picture data type -- ====================================================================== type Color = (Int, Int, Int) data Picture = Circle Bool -- radius 1 around origin (filled?) | Square Bool -- unit square, origin= lower left (filled?) | Line -- from origin to (1,0) | Colored Color Picture | Translate (Double, Double) Picture | Rotate Double Picture -- around origin | Scale (Double, Double) Picture | Invert Picture | And [Picture] | Or [Picture] maxcv (Circle _) = 0 maxcv (Square _) = 0 maxcv (Line) = 0 maxcv (Colored (r,g,b) pic) = maximum [r,g,b,maxcv pic] maxcv (Translate _ pic) = maxcv pic maxcv (Rotate _ pic) = maxcv pic maxcv (Scale _ pic) = maxcv pic maxcv (Invert pic) = maxcv pic maxcv (And pics) = maximum (0 : map maxcv pics) maxcv (Or pics) = maximum (0 : map maxcv pics) render :: Picture -> Int -> Int -> Color -> Pixmap render pic w h bg = Pixmap { width = w, height = h, maximumColorValue = maxcv pic, pixelFun = pixelAt } where pixelAt x y = case renderPix pic bg (fromIntegral x) (fromIntegral y) (sqrt 2) of Nothing -> (0,0,0) Just cl -> cl renderPix pic bg fx fy fr = case pic of Circle filled -> -- radius 1 around origin (filled?) let ra = fx * fx + fy * fy in if filled then if ra <= 1 + fr then Just bg else Nothing else if abs (ra - 1) <= fr then Just bg else Nothing Square filled -> -- unit square, origin= lower left (filled?) if filled then if fx + fr >= 0 && fx - fr <= 1 && fy + fr >= 0 && fy - fr <= 1 then Just bg else Nothing else if abs fx <= fr && fy + fr >= 0 && fy - fr <= 1 || abs fy <= fr && fx + fr >= 0 && fx - fr <= 1 || abs (fx - 1) <= fr && fy + fr >= 0 && fy - fr <= 1 || abs (fy - 1) <= fr && fx + fr >= 0 && fx - fr <= 1 then Just bg else Nothing Line -> -- from origin if abs fx <= fr && fy + fr >= 0 && fy - fr <= 1 then Just bg else Nothing Colored clr pic -> renderPix pic bg fx fy fr >> Just clr Translate (dx, dy) pic -> renderPix pic bg (fx - dx) (fy - dy) fr Rotate phi pic -> -- around origin renderPix pic bg (fx * cos (- phi) - fy * sin (- phi)) (fx * sin (- phi) + fy * cos (- phi)) fr Scale (sx, sy) pic -> renderPix pic bg (fx / sx) (fy / sy) (max (abs (fr / sx)) (abs (fr / sy))) Invert pic -> case renderPix pic bg fx fy fr of Just _ -> Nothing Nothing -> Just bg And pics -> foldl (\ j pic -> j >> renderPix pic bg fx fy fr) (Just bg) pics Or pics -> foldl (\ j pic -> case j of Nothing -> renderPix pic bg fx fy fr Just clr -> Just clr ) Nothing pics
Erdwolf/autotool-bonn
src/Wash/PPM.hs
gpl-2.0
8,547
199
42
2,538
2,868
1,737
1,131
220
19
module Snap.Snaplet.Router.Types ( RouterState (..) , HasRouter (..) , PathInfo (..) -- * Re-exported for convenience , Generic ) where import Snap.Snaplet.Router.Internal.Types import Web.Routes (PathInfo, Generic)
lukerandall/snap-web-routes
src/Snap/Snaplet/Router/Types.hs
bsd-3-clause
230
0
5
40
56
39
17
7
0
-- | -- Module : Language.C.Quote -- Copyright : (c) 2010-2011 Harvard University -- (c) 2011-2013 Geoffrey Mainland -- : (c) 2013-2015 Drexel University -- License : BSD-style -- Maintainer : [email protected] -- -- There are five modules that provide quasiquoters, each for a different C -- variant. 'Language.C.Quote.C' parses C99, 'Language.C.Quote.GCC' parses C99 -- plus GNU extensions, 'Language.C.Quote.CUDA' parses C99 plus GNU and CUDA -- extensions, 'Language.C.Quote.OpenCL' parses C99 plus GNU and OpenCL -- extensions and, 'Language.C.Quote.ObjC' parses C99 plus a subset of Objective-C -- -- For version of GHC prior to 7.4, the quasiquoters generate Template Haskell -- expressions that use data constructors that must be in scope where the -- quasiquoted expression occurs. You will be safe if you add the following -- imports to any module using the quasiquoters provided by this package: -- -- > import qualified Data.Loc -- > import qualified Data.Symbol -- > import qualified Language.C.Syntax -- -- These modules may also be imported unqualified, of course. The quasiquoters -- also use some constructors defined in the standard Prelude, so if it is not -- imported by default, it must be imported qualified. On GHC 7.4 and above, you -- can use the quasiquoters without worrying about what names are in scope. -- -- The following quasiquoters are defined: -- -- [@cdecl@] Declaration, of type @'InitGroup'@. -- -- [@cedecl@] External declarations (top-level declarations in a C file, -- including function definitions and declarations), of type @'Definition'@. -- -- [@cenum@] Component of an @enum@ definition, of type @'CEnum'@. -- -- [@cexp@] Expression, of type @'Exp'@. -- -- [@cstm@] Statement, of type @'Stm'@. -- -- [@cstms@] A list of statements, of type @['Stm']@. -- -- [@citem@] Block item, of type @'BlockItem'@. A block item is either a -- declaration or a statement. -- -- [@citems@] A list of block items, of type @['BlockItem']. -- -- [@cfun@] Function definition, of type @'Func'@. -- -- [@cinit@] Initializer, of type @'Initializer'@. -- -- [@cparam@] Declaration of a function parameter, of type @'Param'@. -- -- [@cparams@] Declaration of function parameters, of type @['Param']@. -- -- [@csdecl@] Declaration of a struct member, of type @'FieldGroup'@. -- -- [@ctyquals@] A list of type qualifiers, of type @['TyQual']@. -- -- [@cty@] A C type, of type @'Type'@. -- -- [@cunit@] A compilation unit, of type @['Definition']@. -- -- In addition, Objective-C support defines the following quasiquoters: -- -- [@objcprop@] Property declaration of type @'ObjCIfaceDecl'@. -- -- [@objcifdecls@] Interface declarations of type @['ObjCIfaceDecl']@ -- -- [@objcimdecls@] Class implementation declarations of type @['Definition']@ -- -- [@objcdictelem@] Dictionary element, of type @'ObjCDictElem'@ -- -- [@objcpropattr@] Property attribute element, of type @'ObjCPropAttr'@ -- -- [@objcmethparam@] Method parameter, of type @'ObjCParam'@ -- -- [@objcmethproto@] Method prototype, of type @'ObjCMethodProto'@ -- -- [@objcmethdef@] Method definition, of type @'Definition'@ -- -- [@objcrecv@] Receiver, of type @'ObjCRecv'@ -- -- [@objcarg@] Keyword argument, of type @'ObjCArg'@ -- -- -- Antiquotations allow splicing in subterms during quotation. These subterms -- may bound to a Haskell variable or may be the value of a Haskell -- expression. Antiquotations appear in a quasiquotation in the form -- @$ANTI:VARID@, where @ANTI@ is a valid antiquote specifier and @VARID@ is a -- Haskell variable identifier, or in the form @$ANTI:(EXP)@, where @EXP@ is a -- Haskell expressions (the parentheses must appear in this case). The Haskell -- expression may itself contain a quasiquote, but in that case the final @|]@ -- must be escaped as @\\|\\]@. Additionally, @$VARID@ is shorthand for -- @$exp:VARID@ and @$(EXP)@ is shorthand for @$exp:(EXP)@, i.e., @exp@ is the -- default antiquote specifier. -- -- It is often useful to use typedefs that aren't in scope when quasiquoting, -- e.g., @[cdecl|uint32_t foo;|]@. The quasiquoter will complain when it sees -- this because it thinks @uint32_t@ is an identifier. The solution is to use -- the @typename@ keyword, borrowed from C++, to tell the parser that the -- identifier is actually a type name. That is, we can write @[cdecl|typename -- uint32_t foo;|]@ to get the desired behavior. -- -- Valid antiquote specifiers are: -- -- [@id@] A C identifier. The argument must be an instance of @'ToIdent'@. -- -- [@comment@] A comment to be attached to a statement. The argument must have -- type @'String'@, and the antiquote must appear in a statement context. -- -- [@const@] A constant. The argument must be an instance of @'ToConst'@. -- -- [@int@] An @integer@ constant. The argument must be an instance of -- @'Integral'@. -- -- [@uint@] An @unsigned integer@ constant. The argument must be an instance of -- @'Integral'@. -- -- [@lint@] A @long integer@ constant. The argument must be an instance of -- @'Integral'@. -- -- [@ulint@] An @unsigned long integer@ constant. The argument must be an -- instance of @'Integral'@. -- -- [@llint@] A @long long integer@ constant. The argument must be an instance of -- @'Integral'@. -- -- [@ullint@] An @unsigned long long integer@ constant. The argument must be an -- instance of @'Integral'@. -- -- [@float@] A @float@ constant. The argument must be an instance of -- @'Fractional'@. -- -- [@double@] A @double@ constant. The argument must be an instance of -- @'Fractional'@. -- -- [@long double@] A @long double@ constant. The argument must be an instance -- of @'Fractional'@. -- -- [@char@] A @char@ constant. The argument must have type @'Char'@. -- -- [@string@] A string (@char*@) constant. The argument must have type -- @'String'@. -- -- [@exp@] A C expression. The argument must be an instance of @'ToExp'@. -- -- [@func@] A function definition. The argument must have type @'Func'@. -- -- [@args@] A list of function arguments. The argument must have type @['Exp']@. -- -- [@decl@] A declaration. The argument must have type @'InitGroup'@. -- -- [@decls@] A list of declarations. The argument must have type -- @['InitGroup']@. -- -- [@sdecl@] A struct member declaration. The argument must have type -- @'FieldGroup'@. -- -- [@sdecls@] A list of struct member declarations. The argument must have type -- @['FieldGroup']@. -- -- [@enum@] An enum member. The argument must have type @'CEnum'@. -- -- [@enums@] An list of enum members. The argument must have type @['CEnum']@. -- -- [@esc@] An arbitrary top-level C "definition," such as an @#include@ or a -- @#define@. The argument must have type @'String'@. -- -- [@edecl@] An external definition. The argument must have type @'Definition'@. -- -- [@edecls@] An list of external definitions. The argument must have type -- @['Definition']@. -- -- [@item@] A statement block item. The argument must have type @'BlockItem'@. -- -- [@items@] A list of statement block item. The argument must have type -- @['BlockItem']@. -- -- [@stm@] A statement. The argument must have type @'Stm'@. -- -- [@stms@] A list statements. The argument must have type @['Stm']@. -- -- [@tyqual@] A type qualifier. The argument must have type @'TyQual'@. -- -- [@tyquals@] A list of type qualifiers. The argument must have type -- @['TyQual']@. -- -- [@ty@] A C type. The argument must have type @'Type'@. -- -- [@spec@] A declaration specifier. The argument must have type @'DeclSpec'@. -- -- [@param@] A function parameter. The argument must have type @'Param'@. -- -- [@params@] A list of function parameters. The argument must have type -- @['Param']@. -- -- [@pragma@] A pragma statement. The argument must have type @'String'@. -- -- [@init@] An initializer. The argument must have type @'Initializer'@. -- -- [@inits@] A list of initializers. The argument must have type -- @['Initializer']@. -- -- In addition, Objective-C code can use these antiquote specifiers: -- -- [@ifdecl@] A class interface declaration. The argument must have type -- @'ObjCIfaceDecl'@. -- -- [@ifdecls@] A list of class interface declaration. The argument must have -- type @['ObjCIfaceDecl']@. -- -- [@prop@] A property declaration. The argument must have type -- @'ObjCIfaceDecl'@. -- -- [@props@] A list of property declarations. The argument must have type -- @['ObjCIfaceDecl']@. -- -- [@propattr@] A property attribute. The argument must have type -- @'ObjCPropAttr'@. -- -- [@propattrs@] A list of property attribute. The argument must have type -- @['ObjCPropAttr']@. -- -- [@dictelems@] A list dictionary elements. The argument must have type -- @['ObjCDictElem']@. -- -- [@methparam@] A method parameter. The argument must have type -- @'ObjCParam'@. -- -- [@methparams@] A list of method parameters. The argument must have type -- @['ObjCParam']@. -- -- [@methproto@] A method prototype. The argument must have type -- @'ObjCMethodProto'@. -- -- [@methdef@] A method definition. The argument must have type -- @['Definition']@. -- -- [@methdefs@] A list of method definitions. The argument must have type -- @['Definition']@. -- -- [@recv@] A receiver. The argument must have type @'ObjCRecv'@. -- -- [@kwarg@] A keywords argument. The argument must have type -- @'ObjCArg'@. -- -- [@kwargs@] A list of keyword arguments. The argument must have type -- @['ObjCArg']@. -- -------------------------------------------------------------------------------- module Language.C.Quote ( module Language.C.Quote.Base, module Language.C.Syntax ) where import Language.C.Quote.Base import Language.C.Syntax
flowbox-public/language-c-quote
Language/C/Quote.hs
bsd-3-clause
9,622
0
5
1,524
289
278
11
5
0
-- | -- Module : Foundation.List.ListN -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : portable -- -- A Nat-sized list abstraction -- -- Using this module is limited to GHC 7.10 and above. -- module Foundation.List.ListN ( module X ) where import Basement.Sized.List as X
vincenthz/hs-foundation
foundation/Foundation/List/ListN.hs
bsd-3-clause
357
0
4
67
32
26
6
2
0
{-# LANGUAGE OverloadedStrings #-} -- Turn data types into equivalent Java classes. -- -- easy case: -- data Foo a b = Foo { frotz :: a, xyzzy :: b } -- -- becomes -- class Foo<A, B> { -- private A frotz; -- private B xyzzy; -- Baz(A frotz, B xyzzy) { this.frotz = frotz; this.xyzzy = xyzzy; } -- A getFrotz() { return frotz; } -- B getFrotz() { return xyzzy; } -- // equals, hashCode -- } -- -- complex case: -- data Foo a b = Bar | Baz { frotz :: a, xyzzy :: b } -- -- is turned into -- -- interface Foo<A, B> { -- Bar<A, B> getBar(); -- Baz<A, B> getBaz(); -- boolean isBar(); -- boolean isBaz(); -- } -- -- class Bar<A, B> implements Foo<A, B> { -- Bar() { } -- Bar<A, B> getBar() { return this; } -- Baz<A, B> getBaz() { return null; } -- boolean isBar() { return true; } -- boolean isBaz() { return false; } -- } -- -- class Baz<A, B> implements Foo<A, B> { -- private A frotz; -- private B xyzzy; -- Baz(A frotz, B xyzzy) { this.frotz = frotz; this.xyzzy = xyzzy; } -- A getFrotz() { return frotz; } -- B getFrotz() { return xyzzy; } -- ... -- } -- -- Anonymous fields (as in data Foo = Foo Int Int) will be called -- fiedl1, field2 etc. module JData ( dir, jData ) where import Types import Basic import Java import Package import System.FilePath import Control.Monad import Text.PrettyPrint.HughesPJ import Data.Int package :: String package = base ++ ".types" dir :: FilePath dir = "out" </> "types" -- file header header = [ "package" <+> text package <> ";", "import" <+> "java.util.List" <> ";", "", "@SuppressWarnings" <> "(" <> string "unused" <> ")" ] -- actual worker jData :: AData -> IO () -- simple case: one alternative jData (AData ty@(AType nm _) [con]) | nm == consName con = do vWriteFile (dir </> nm <.> "java") $ show $ vcat $ header ++ [ "public" <+> "class" <+> tipe ty, block $ contents ty con ] -- complex case: several alternatives jData (AData ty@(AType nm tv) cons) = do vWriteFile (dir </> nm <.> "java") $ show $ vcat $ header ++ [ "public" <+> "interface" <+> tipe ty, block $ [ -- getters "public" <+> text cn <+> text ("get" ++ cn) <> "()" <> ";" | con <- cons, let cn = consName con ] ++ [ -- distinguishers "public" <+> "boolean" <+> text ("is" ++ cn) <> "()" <> ";" | con <- cons, let cn = consName con ] ] forM_ cons $ \con -> do let cn = consName con vWriteFile (dir </> cn <.> "java") $ show $ vcat $ header ++ [ "public" <+> "class" <+> text cn <+> "implements" <+> tipe ty, block $ contents ty con ++ concat [ -- getters [ "public" <+> text cn' <+> text ("get" ++ cn') <> "()", block [ "return" <+> res <> ";" | let res = if cn == cn' then "this" else "null" ] ] | con' <- cons, let cn' = consName con' ] ++ concat [ -- distinguishers [ "public" <+> "boolean" <+> text ("is" ++ cn') <> "()", block [ "return" <+> res <> ";" | let res = if cn == cn' then "true" else "false" ] ] | con' <- cons, let cn' = consName con' ] ] return () -- actual class contents contents ty@(AType nm ts) con = let cn = consName con ty' = AType cn (map (const (AVar "?")) ts) in [ -- fields "private" <+> "final" <+> tipe (unbox ty) <+> ident [nm] <> ";" | (nm, ty) <- consArgs con ] ++ [ "", -- constructor hsep ["public", consProto con], block [ "this" <> "." <> ident [nm] <+> "=" <+> ident [nm] <> ";" | (nm, _) <- consArgs con ] ] ++ concat [ -- getters [ "public" <+> tipe (unbox ty) <+> ident ["get", nm] <> "()", block [ "return" <+> ident [nm] <> ";" ] ] | (nm, ty) <- consArgs con ] ++ [ -- toString "public" <+> "String" <+> "toString" <> "()", block [ "return" <+> string (cn ++ "("), nest 4 $ vcat (punctuate (space <> "+" <+> string ", ") [ "+" <+> ident [nm] | (nm, _) <- consArgs con ]) <+> "+" <+> string ")" <> ";" ], -- equals "public" <+> "boolean" <+> "equals" <> "(" <> "Object" <+> "other" <> ")", block $ [ "if" <+> "(" <> "!" <+> "(" <> "other" <+> "instanceof" <+> tipe ty' <> ")" <> ")", nest 4 $ "return" <+> "false" <> ";", tipe ty' <+> ident ["o", nm] <+> "=" <+> "(" <> tipe ty' <> ")" <+> "other" <> ";" ] ++ concat [ [ if unboxed ty' then "if" <+> "(" <> ident [nm'] <+> "!=" <+> rhs <> ")" else "if" <+> "(" <> "!" <> lhs <> "." <> "equals" <> "(" <> rhs <> ")" <> ")", nest 4 $ "return" <+> "false" <> ";" ] | (nm', ty' ) <- consArgs con, let lhs = ident [nm'] rhs = ident ["o", nm] <> "." <> ident ["get", nm'] <> "()" ] ++ [ "return" <+> "true" <> ";" ], -- hashCode "public" <+> "int" <+> "hashCode" <> "()", block $ [ "return", if null (consArgs con) then nest 4 $ text "0;" else nest 4 $ (vcat $ punctuate " +" $ [ boxFunc ty' (ident [nm']) <> "." <> "hashCode" <> "()" <+> "*" <+> text (show i) | ((nm', ty'), i) <- zip (consArgs con) (iterate (*37) (1 :: Int32)) ]) <> ";" ] ]
florianpilz/autotool
server/gen/JData.hs
gpl-2.0
6,094
0
25
2,415
1,687
896
791
109
3
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0"> <title>Collocation Tool Help</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view mergetype="javax.help.UniteAppendMerge"> <name>TOC</name> <label>Contents</label> <type>javax.help.TOCView</type> <data>toc.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine">JavaHelpSearch</data> </view> </helpset>
arraydev/snap-desktop
snap-collocation-ui/src/main/resources/org/esa/snap/collocation/docs/help.hs
gpl-3.0
777
54
44
165
283
143
140
-1
-1
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-} -- | -- Module : Statistics.Internal -- Copyright : (c) 2009 Bryan O'Sullivan -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Scary internal functions. module Statistics.Internal ( inlinePerformIO ) where #if __GLASGOW_HASKELL__ >= 611 import GHC.IO (IO(IO)) #else import GHC.IOBase (IO(IO)) #endif import GHC.Base (realWorld#) #if !defined(__GLASGOW_HASKELL__) import System.IO.Unsafe (unsafePerformIO) #endif -- Lifted from Data.ByteString.Internal so we don't introduce an -- otherwise unnecessary dependency on the bytestring package. -- | Just like unsafePerformIO, but we inline it. Big performance -- gains as it exposes lots of things to further inlining. /Very -- unsafe/. In particular, you should do no memory allocation inside -- an 'inlinePerformIO' block. On Hugs this is just @unsafePerformIO@. {-# INLINE inlinePerformIO #-} inlinePerformIO :: IO a -> a #if defined(__GLASGOW_HASKELL__) inlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r #else inlinePerformIO = unsafePerformIO #endif
fpco/statistics
Statistics/Internal.hs
bsd-2-clause
1,153
0
8
186
116
77
39
10
1
{-# LANGUAGE TemplateHaskell, CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Implementation of the Ganeti data collector types. -} {- Copyright (C) 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.DataCollectors.Types ( addStatus , DCCategory(..) , DCKind(..) , DCReport(..) , DCStatus(..) , DCStatusCode(..) , DCVersion(..) , CollectorData(..) , CollectorMap , buildReport , mergeStatuses , getCategoryName , ReportBuilder(..) , DataCollector(..) ) where import Control.DeepSeq (NFData, rnf) #if !MIN_VERSION_containers(0,5,0) import Control.Seq (using, seqFoldable, rdeepseq) #endif import Data.Char import Data.Ratio import qualified Data.Map as Map import qualified Data.Sequence as Seq import System.Time (ClockTime(..)) import Text.JSON import Ganeti.Constants as C import Ganeti.Objects (ConfigData) import Ganeti.THH import Ganeti.Utils (getCurrentTimeUSec) -- | The possible classes a data collector can belong to. data DCCategory = DCInstance | DCStorage | DCDaemon | DCHypervisor deriving (Show, Eq, Read, Enum, Bounded) -- | Get the category name and return it as a string. getCategoryName :: DCCategory -> String getCategoryName dcc = map toLower . drop 2 . show $ dcc categoryNames :: Map.Map String DCCategory categoryNames = let l = [minBound ..] in Map.fromList $ zip (map getCategoryName l) l -- | The JSON instance for DCCategory. instance JSON DCCategory where showJSON = showJSON . getCategoryName readJSON (JSString s) = let s' = fromJSString s in case Map.lookup s' categoryNames of Just category -> Ok category Nothing -> fail $ "Invalid category name " ++ s' ++ " for type" ++ " DCCategory" readJSON v = fail $ "Invalid JSON value " ++ show v ++ " for type DCCategory" -- | The possible status codes of a data collector. data DCStatusCode = DCSCOk -- ^ Everything is OK | DCSCTempBad -- ^ Bad, but being automatically fixed | DCSCUnknown -- ^ Unable to determine the status | DCSCBad -- ^ Bad. External intervention required deriving (Show, Eq, Ord) -- | The JSON instance for CollectorStatus. instance JSON DCStatusCode where showJSON DCSCOk = showJSON (0 :: Int) showJSON DCSCTempBad = showJSON (1 :: Int) showJSON DCSCUnknown = showJSON (2 :: Int) showJSON DCSCBad = showJSON (4 :: Int) readJSON = error "JSON read instance not implemented for type DCStatusCode" -- | The status of a \"status reporting data collector\". $(buildObject "DCStatus" "dcStatus" [ simpleField "code" [t| DCStatusCode |] , simpleField "message" [t| String |] ]) -- | The type representing the kind of the collector. data DCKind = DCKPerf -- ^ Performance reporting collector | DCKStatus -- ^ Status reporting collector deriving (Show, Eq) -- | The JSON instance for CollectorKind. instance JSON DCKind where showJSON DCKPerf = showJSON (0 :: Int) showJSON DCKStatus = showJSON (1 :: Int) readJSON (JSRational _ x) = if denominator x /= 1 then fail $ "Invalid JSON value " ++ show x ++ " for type DCKind" else let x' = (fromIntegral . numerator $ x) :: Int in if x' == 0 then Ok DCKPerf else if x' == 1 then Ok DCKStatus else fail $ "Invalid JSON value " ++ show x' ++ " for type DCKind" readJSON v = fail $ "Invalid JSON value " ++ show v ++ " for type DCKind" -- | Type representing the version number of a data collector. data DCVersion = DCVerBuiltin | DCVersion String deriving (Show, Eq) -- | The JSON instance for DCVersion. instance JSON DCVersion where showJSON DCVerBuiltin = showJSON C.builtinDataCollectorVersion showJSON (DCVersion v) = showJSON v readJSON (JSString s) = if fromJSString s == C.builtinDataCollectorVersion then Ok DCVerBuiltin else Ok . DCVersion $ fromJSString s readJSON v = fail $ "Invalid JSON value " ++ show v ++ " for type DCVersion" -- | Type for the value field of the `CollectorMap` below. data CollectorData = CPULoadData (Seq.Seq (ClockTime, [Int])) | InstanceCpuLoad (Map.Map String (Seq.Seq (ClockTime, Double))) instance NFData ClockTime where rnf (TOD x y) = rnf x `seq` rnf y #if MIN_VERSION_containers(0,5,0) instance NFData CollectorData where rnf (CPULoadData x) = rnf x rnf (InstanceCpuLoad x) = rnf x #else {- In older versions of the containers library, Seq is not an instance of NFData, so use a generic way to reduce to normal form -} instance NFData CollectorData where rnf (CPULoadData x) = (x `using` seqFoldable rdeepseq) `seq` () rnf (InstanceCpuLoad x) = (x `using` seqFoldable (seqFoldable rdeepseq)) `seq` () #endif -- | Type for the map storing the data of the statefull DataCollectors. type CollectorMap = Map.Map String CollectorData -- | This is the format of the report produced by each data collector. $(buildObject "DCReport" "dcReport" [ simpleField "name" [t| String |] , simpleField "version" [t| DCVersion |] , simpleField "format_version" [t| Int |] , simpleField "timestamp" [t| Integer |] , optionalNullSerField $ simpleField "category" [t| DCCategory |] , simpleField "kind" [t| DCKind |] , simpleField "data" [t| JSValue |] ]) -- | Add the data collector status information to the JSON representation of -- the collector data. addStatus :: DCStatus -> JSValue -> JSValue addStatus dcStatus (JSObject obj) = makeObj $ ("status", showJSON dcStatus) : fromJSObject obj addStatus dcStatus value = makeObj [ ("status", showJSON dcStatus) , ("data", value) ] -- | Helper function for merging statuses. mergeStatuses :: (DCStatusCode, String) -> (DCStatusCode, [String]) -> (DCStatusCode, [String]) mergeStatuses (newStat, newStr) (storedStat, storedStrs) = let resStat = max newStat storedStat resStrs = if newStr == "" then storedStrs else storedStrs ++ [newStr] in (resStat, resStrs) -- | Utility function for building a report automatically adding the current -- timestamp (rounded up to seconds). -- If the version is not specified, it will be set to the value indicating -- a builtin collector. buildReport :: String -> DCVersion -> Int -> Maybe DCCategory -> DCKind -> JSValue -> IO DCReport buildReport name version format_version category kind jsonData = do usecs <- getCurrentTimeUSec let timestamp = usecs * 1000 :: Integer return $ DCReport name version format_version timestamp category kind jsonData -- | A report of a data collector might be stateful or stateless. data ReportBuilder = StatelessR (IO DCReport) | StatefulR (Maybe CollectorData -> IO DCReport) type Name = String -- | Type describing a data collector basic information data DataCollector = DataCollector { dName :: Name -- ^ Name of the data collector , dCategory :: Maybe DCCategory -- ^ Category (storage, instance, ecc) -- of the collector , dKind :: DCKind -- ^ Kind (performance or status reporting) of -- the data collector , dReport :: ReportBuilder -- ^ Report produced by the collector , dUpdate :: Maybe (Maybe CollectorData -> IO CollectorData) -- ^ Update operation for stateful collectors. , dActive :: Name -> ConfigData -> Bool -- ^ Checks if the collector applies for the cluster. , dInterval :: Name -> ConfigData -> Integer -- ^ Interval between collection in microseconds }
mbakke/ganeti
src/Ganeti/DataCollectors/Types.hs
bsd-2-clause
8,946
0
14
2,040
1,620
908
712
135
2
module KeepCafs1 where import KeepCafsBase foreign export ccall "getX" getX :: IO Int getX :: IO Int getX = return x
sdiehl/ghc
testsuite/tests/rts/KeepCafs1.hs
bsd-3-clause
122
0
6
26
38
21
17
6
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : System.IO.Error -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Standard IO Errors. -- ----------------------------------------------------------------------------- module System.IO.Error ( -- * I\/O errors IOError, -- = IOException userError, -- :: String -> IOError mkIOError, -- :: IOErrorType -> String -> Maybe Handle -- -> Maybe FilePath -> IOError annotateIOError, -- :: IOError -> String -> Maybe Handle -- -> Maybe FilePath -> IOError -- ** Classifying I\/O errors isAlreadyExistsError, -- :: IOError -> Bool isDoesNotExistError, isAlreadyInUseError, isFullError, isEOFError, isIllegalOperation, isPermissionError, isUserError, -- ** Attributes of I\/O errors ioeGetErrorType, -- :: IOError -> IOErrorType ioeGetLocation, -- :: IOError -> String ioeGetErrorString, -- :: IOError -> String ioeGetHandle, -- :: IOError -> Maybe Handle ioeGetFileName, -- :: IOError -> Maybe FilePath ioeSetErrorType, -- :: IOError -> IOErrorType -> IOError ioeSetErrorString, -- :: IOError -> String -> IOError ioeSetLocation, -- :: IOError -> String -> IOError ioeSetHandle, -- :: IOError -> Handle -> IOError ioeSetFileName, -- :: IOError -> FilePath -> IOError -- * Types of I\/O error IOErrorType, -- abstract alreadyExistsErrorType, -- :: IOErrorType doesNotExistErrorType, alreadyInUseErrorType, fullErrorType, eofErrorType, illegalOperationErrorType, permissionErrorType, userErrorType, -- ** 'IOErrorType' predicates isAlreadyExistsErrorType, -- :: IOErrorType -> Bool isDoesNotExistErrorType, isAlreadyInUseErrorType, isFullErrorType, isEOFErrorType, isIllegalOperationErrorType, isPermissionErrorType, isUserErrorType, -- * Throwing and catching I\/O errors ioError, -- :: IOError -> IO a catchIOError, -- :: IO a -> (IOError -> IO a) -> IO a catch, -- :: IO a -> (IOError -> IO a) -> IO a tryIOError, -- :: IO a -> IO (Either IOError a) try, -- :: IO a -> IO (Either IOError a) modifyIOError, -- :: (IOError -> IOError) -> IO a -> IO a ) where #ifndef __HUGS__ import qualified Control.Exception.Base as New (catch) #endif #ifndef __HUGS__ import Data.Either #endif import Data.Maybe #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.IO import GHC.IO.Exception import GHC.IO.Handle.Types import Text.Show #endif #ifdef __HUGS__ import Hugs.Prelude(Handle, IOException(..), IOErrorType(..), IO) #endif #ifdef __NHC__ import IO ( IOError () , Handle () , try , ioError , userError , isAlreadyExistsError -- :: IOError -> Bool , isDoesNotExistError , isAlreadyInUseError , isFullError , isEOFError , isIllegalOperation , isPermissionError , isUserError , ioeGetErrorString -- :: IOError -> String , ioeGetHandle -- :: IOError -> Maybe Handle , ioeGetFileName -- :: IOError -> Maybe FilePath ) import qualified NHC.Internal as NHC (IOError(..)) import qualified NHC.DErrNo as NHC (ErrNo(..)) import Data.Maybe (fromJust) import Control.Monad (MonadPlus(mplus)) #endif -- | The construct 'tryIOError' @comp@ exposes IO errors which occur within a -- computation, and which are not fully handled. -- -- Non-I\/O exceptions are not caught by this variant; to catch all -- exceptions, use 'Control.Exception.try' from "Control.Exception". tryIOError :: IO a -> IO (Either IOError a) tryIOError f = catch (do r <- f return (Right r)) (return . Left) #ifndef __NHC__ {-# DEPRECATED try "Please use the new exceptions variant, Control.Exception.try" #-} -- | The 'try' function is deprecated. Please use the new exceptions -- variant, 'Control.Exception.try' from "Control.Exception", instead. try :: IO a -> IO (Either IOError a) try f = catch (do r <- f return (Right r)) (return . Left) #endif #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__) -- ----------------------------------------------------------------------------- -- Constructing an IOError -- | Construct an 'IOError' of the given type where the second argument -- describes the error location and the third and fourth argument -- contain the file handle and file path of the file involved in the -- error if applicable. mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError mkIOError t location maybe_hdl maybe_filename = IOError{ ioe_type = t, ioe_location = location, ioe_description = "", #if defined(__GLASGOW_HASKELL__) ioe_errno = Nothing, #endif ioe_handle = maybe_hdl, ioe_filename = maybe_filename } #endif /* __GLASGOW_HASKELL__ || __HUGS__ */ #ifdef __NHC__ mkIOError EOF location maybe_hdl maybe_filename = NHC.EOFError location (fromJust maybe_hdl) mkIOError UserError location maybe_hdl maybe_filename = NHC.UserError location "" mkIOError t location maybe_hdl maybe_filename = NHC.IOError location maybe_filename maybe_hdl (ioeTypeToErrNo t) where ioeTypeToErrNo AlreadyExists = NHC.EEXIST ioeTypeToErrNo NoSuchThing = NHC.ENOENT ioeTypeToErrNo ResourceBusy = NHC.EBUSY ioeTypeToErrNo ResourceExhausted = NHC.ENOSPC ioeTypeToErrNo IllegalOperation = NHC.EPERM ioeTypeToErrNo PermissionDenied = NHC.EACCES #endif /* __NHC__ */ #ifndef __NHC__ -- ----------------------------------------------------------------------------- -- IOErrorType -- | An error indicating that an 'IO' operation failed because -- one of its arguments already exists. isAlreadyExistsError :: IOError -> Bool isAlreadyExistsError = isAlreadyExistsErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- one of its arguments does not exist. isDoesNotExistError :: IOError -> Bool isDoesNotExistError = isDoesNotExistErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- one of its arguments is a single-use resource, which is already -- being used (for example, opening the same file twice for writing -- might give this error). isAlreadyInUseError :: IOError -> Bool isAlreadyInUseError = isAlreadyInUseErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- the device is full. isFullError :: IOError -> Bool isFullError = isFullErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- the end of file has been reached. isEOFError :: IOError -> Bool isEOFError = isEOFErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- the operation was not possible. -- Any computation which returns an 'IO' result may fail with -- 'isIllegalOperation'. In some cases, an implementation will not be -- able to distinguish between the possible error causes. In this case -- it should fail with 'isIllegalOperation'. isIllegalOperation :: IOError -> Bool isIllegalOperation = isIllegalOperationErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- the user does not have sufficient operating system privilege -- to perform that operation. isPermissionError :: IOError -> Bool isPermissionError = isPermissionErrorType . ioeGetErrorType -- | A programmer-defined error value constructed using 'userError'. isUserError :: IOError -> Bool isUserError = isUserErrorType . ioeGetErrorType #endif /* __NHC__ */ -- ----------------------------------------------------------------------------- -- IOErrorTypes #ifdef __NHC__ data IOErrorType = AlreadyExists | NoSuchThing | ResourceBusy | ResourceExhausted | EOF | IllegalOperation | PermissionDenied | UserError #endif -- | I\/O error where the operation failed because one of its arguments -- already exists. alreadyExistsErrorType :: IOErrorType alreadyExistsErrorType = AlreadyExists -- | I\/O error where the operation failed because one of its arguments -- does not exist. doesNotExistErrorType :: IOErrorType doesNotExistErrorType = NoSuchThing -- | I\/O error where the operation failed because one of its arguments -- is a single-use resource, which is already being used. alreadyInUseErrorType :: IOErrorType alreadyInUseErrorType = ResourceBusy -- | I\/O error where the operation failed because the device is full. fullErrorType :: IOErrorType fullErrorType = ResourceExhausted -- | I\/O error where the operation failed because the end of file has -- been reached. eofErrorType :: IOErrorType eofErrorType = EOF -- | I\/O error where the operation is not possible. illegalOperationErrorType :: IOErrorType illegalOperationErrorType = IllegalOperation -- | I\/O error where the operation failed because the user does not -- have sufficient operating system privilege to perform that operation. permissionErrorType :: IOErrorType permissionErrorType = PermissionDenied -- | I\/O error that is programmer-defined. userErrorType :: IOErrorType userErrorType = UserError -- ----------------------------------------------------------------------------- -- IOErrorType predicates -- | I\/O error where the operation failed because one of its arguments -- already exists. isAlreadyExistsErrorType :: IOErrorType -> Bool isAlreadyExistsErrorType AlreadyExists = True isAlreadyExistsErrorType _ = False -- | I\/O error where the operation failed because one of its arguments -- does not exist. isDoesNotExistErrorType :: IOErrorType -> Bool isDoesNotExistErrorType NoSuchThing = True isDoesNotExistErrorType _ = False -- | I\/O error where the operation failed because one of its arguments -- is a single-use resource, which is already being used. isAlreadyInUseErrorType :: IOErrorType -> Bool isAlreadyInUseErrorType ResourceBusy = True isAlreadyInUseErrorType _ = False -- | I\/O error where the operation failed because the device is full. isFullErrorType :: IOErrorType -> Bool isFullErrorType ResourceExhausted = True isFullErrorType _ = False -- | I\/O error where the operation failed because the end of file has -- been reached. isEOFErrorType :: IOErrorType -> Bool isEOFErrorType EOF = True isEOFErrorType _ = False -- | I\/O error where the operation is not possible. isIllegalOperationErrorType :: IOErrorType -> Bool isIllegalOperationErrorType IllegalOperation = True isIllegalOperationErrorType _ = False -- | I\/O error where the operation failed because the user does not -- have sufficient operating system privilege to perform that operation. isPermissionErrorType :: IOErrorType -> Bool isPermissionErrorType PermissionDenied = True isPermissionErrorType _ = False -- | I\/O error that is programmer-defined. isUserErrorType :: IOErrorType -> Bool isUserErrorType UserError = True isUserErrorType _ = False -- ----------------------------------------------------------------------------- -- Miscellaneous #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__) ioeGetErrorType :: IOError -> IOErrorType ioeGetErrorString :: IOError -> String ioeGetLocation :: IOError -> String ioeGetHandle :: IOError -> Maybe Handle ioeGetFileName :: IOError -> Maybe FilePath ioeGetErrorType ioe = ioe_type ioe ioeGetErrorString ioe | isUserErrorType (ioe_type ioe) = ioe_description ioe | otherwise = show (ioe_type ioe) ioeGetLocation ioe = ioe_location ioe ioeGetHandle ioe = ioe_handle ioe ioeGetFileName ioe = ioe_filename ioe ioeSetErrorType :: IOError -> IOErrorType -> IOError ioeSetErrorString :: IOError -> String -> IOError ioeSetLocation :: IOError -> String -> IOError ioeSetHandle :: IOError -> Handle -> IOError ioeSetFileName :: IOError -> FilePath -> IOError ioeSetErrorType ioe errtype = ioe{ ioe_type = errtype } ioeSetErrorString ioe str = ioe{ ioe_description = str } ioeSetLocation ioe str = ioe{ ioe_location = str } ioeSetHandle ioe hdl = ioe{ ioe_handle = Just hdl } ioeSetFileName ioe filename = ioe{ ioe_filename = Just filename } #elif defined(__NHC__) ioeGetErrorType :: IOError -> IOErrorType ioeGetLocation :: IOError -> String ioeGetErrorType e | isAlreadyExistsError e = AlreadyExists | isDoesNotExistError e = NoSuchThing | isAlreadyInUseError e = ResourceBusy | isFullError e = ResourceExhausted | isEOFError e = EOF | isIllegalOperation e = IllegalOperation | isPermissionError e = PermissionDenied | isUserError e = UserError ioeGetLocation (NHC.IOError _ _ _ _) = "unknown location" ioeGetLocation (NHC.EOFError _ _ ) = "unknown location" ioeGetLocation (NHC.PatternError loc) = loc ioeGetLocation (NHC.UserError loc _) = loc ioeSetErrorType :: IOError -> IOErrorType -> IOError ioeSetErrorString :: IOError -> String -> IOError ioeSetLocation :: IOError -> String -> IOError ioeSetHandle :: IOError -> Handle -> IOError ioeSetFileName :: IOError -> FilePath -> IOError ioeSetErrorType e _ = e ioeSetErrorString (NHC.IOError _ f h e) s = NHC.IOError s f h e ioeSetErrorString (NHC.EOFError _ f) s = NHC.EOFError s f ioeSetErrorString e@(NHC.PatternError _) _ = e ioeSetErrorString (NHC.UserError l _) s = NHC.UserError l s ioeSetLocation e@(NHC.IOError _ _ _ _) _ = e ioeSetLocation e@(NHC.EOFError _ _) _ = e ioeSetLocation (NHC.PatternError _) l = NHC.PatternError l ioeSetLocation (NHC.UserError _ m) l = NHC.UserError l m ioeSetHandle (NHC.IOError o f _ e) h = NHC.IOError o f (Just h) e ioeSetHandle (NHC.EOFError o _) h = NHC.EOFError o h ioeSetHandle e@(NHC.PatternError _) _ = e ioeSetHandle e@(NHC.UserError _ _) _ = e ioeSetFileName (NHC.IOError o _ h e) f = NHC.IOError o (Just f) h e ioeSetFileName e _ = e #endif -- | Catch any 'IOError' that occurs in the computation and throw a -- modified version. modifyIOError :: (IOError -> IOError) -> IO a -> IO a modifyIOError f io = catch io (\e -> ioError (f e)) -- ----------------------------------------------------------------------------- -- annotating an IOError -- | Adds a location description and maybe a file path and file handle -- to an 'IOError'. If any of the file handle or file path is not given -- the corresponding value in the 'IOError' remains unaltered. annotateIOError :: IOError -> String -> Maybe Handle -> Maybe FilePath -> IOError #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__) annotateIOError ioe loc hdl path = ioe{ ioe_handle = hdl `mplus` ioe_handle ioe, ioe_location = loc, ioe_filename = path `mplus` ioe_filename ioe } where mplus :: Maybe a -> Maybe a -> Maybe a Nothing `mplus` ys = ys xs `mplus` _ = xs #endif /* __GLASGOW_HASKELL__ || __HUGS__ */ #if defined(__NHC__) annotateIOError (NHC.IOError msg file hdl code) msg' hdl' file' = NHC.IOError (msg++'\n':msg') (file`mplus`file') (hdl`mplus`hdl') code annotateIOError (NHC.EOFError msg hdl) msg' _ _ = NHC.EOFError (msg++'\n':msg') hdl annotateIOError (NHC.UserError loc msg) msg' _ _ = NHC.UserError loc (msg++'\n':msg') annotateIOError (NHC.PatternError loc) msg' _ _ = NHC.PatternError (loc++'\n':msg') #endif #ifndef __HUGS__ -- | The 'catchIOError' function establishes a handler that receives any -- 'IOError' raised in the action protected by 'catchIOError'. -- An 'IOError' is caught by -- the most recent handler established by one of the exception handling -- functions. These handlers are -- not selective: all 'IOError's are caught. Exception propagation -- must be explicitly provided in a handler by re-raising any unwanted -- exceptions. For example, in -- -- > f = catchIOError g (\e -> if IO.isEOFError e then return [] else ioError e) -- -- the function @f@ returns @[]@ when an end-of-file exception -- (cf. 'System.IO.Error.isEOFError') occurs in @g@; otherwise, the -- exception is propagated to the next outer handler. -- -- When an exception propagates outside the main program, the Haskell -- system prints the associated 'IOError' value and exits the program. -- -- Non-I\/O exceptions are not caught by this variant; to catch all -- exceptions, use 'Control.Exception.catch' from "Control.Exception". catchIOError :: IO a -> (IOError -> IO a) -> IO a catchIOError = New.catch {-# DEPRECATED catch "Please use the new exceptions variant, Control.Exception.catch" #-} -- | The 'catch' function is deprecated. Please use the new exceptions -- variant, 'Control.Exception.catch' from "Control.Exception", instead. catch :: IO a -> (IOError -> IO a) -> IO a catch = New.catch #endif /* !__HUGS__ */
mightymoose/liquidhaskell
benchmarks/base-4.5.1.0/System/IO/Error.hs
bsd-3-clause
17,945
0
11
4,111
2,058
1,211
847
128
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program.Db -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 -- -- Maintainer : [email protected] -- Portability : portable -- -- This provides a 'ProgramDb' type which holds configured and not-yet -- configured programs. It is the parameter to lots of actions elsewhere in -- Cabal that need to look up and run programs. If we had a Cabal monad, -- the 'ProgramDb' would probably be a reader or state component of it. -- -- One nice thing about using it is that any program that is -- registered with Cabal will get some \"configure\" and \".cabal\" -- helpers like --with-foo-args --foo-path= and extra-foo-args. -- -- There's also a hook for adding programs in a Setup.lhs script. See -- hookedPrograms in 'Distribution.Simple.UserHooks'. This gives a -- hook user the ability to get the above flags and such so that they -- don't have to write all the PATH logic inside Setup.lhs. module Distribution.Simple.Program.Db ( -- * The collection of configured programs we can run ProgramDb, emptyProgramDb, defaultProgramDb, restoreProgramDb, -- ** Query and manipulate the program db addKnownProgram, addKnownPrograms, lookupKnownProgram, knownPrograms, getProgramSearchPath, setProgramSearchPath, modifyProgramSearchPath, userSpecifyPath, userSpecifyPaths, userMaybeSpecifyPath, userSpecifyArgs, userSpecifyArgss, userSpecifiedArgs, lookupProgram, updateProgram, configuredPrograms, -- ** Query and manipulate the program db configureProgram, configureAllKnownPrograms, lookupProgramVersion, reconfigurePrograms, requireProgram, requireProgramVersion, ) where import Distribution.Simple.Program.Types import Distribution.Simple.Program.Find import Distribution.Simple.Program.Builtin import Distribution.Simple.Utils import Distribution.Version import Distribution.Text import Distribution.Verbosity import Distribution.Compat.Binary import Data.List ( foldl' ) import Data.Maybe ( catMaybes ) import Data.Tuple (swap) import qualified Data.Map as Map import Control.Monad ( join, foldM ) -- ------------------------------------------------------------ -- * Programs database -- ------------------------------------------------------------ -- | The configuration is a collection of information about programs. It -- contains information both about configured programs and also about programs -- that we are yet to configure. -- -- The idea is that we start from a collection of unconfigured programs and one -- by one we try to configure them at which point we move them into the -- configured collection. For unconfigured programs we record not just the -- 'Program' but also any user-provided arguments and location for the program. data ProgramDb = ProgramDb { unconfiguredProgs :: UnconfiguredProgs, progSearchPath :: ProgramSearchPath, configuredProgs :: ConfiguredProgs } type UnconfiguredProgram = (Program, Maybe FilePath, [ProgArg]) type UnconfiguredProgs = Map.Map String UnconfiguredProgram type ConfiguredProgs = Map.Map String ConfiguredProgram emptyProgramDb :: ProgramDb emptyProgramDb = ProgramDb Map.empty defaultProgramSearchPath Map.empty defaultProgramDb :: ProgramDb defaultProgramDb = restoreProgramDb builtinPrograms emptyProgramDb -- internal helpers: updateUnconfiguredProgs :: (UnconfiguredProgs -> UnconfiguredProgs) -> ProgramDb -> ProgramDb updateUnconfiguredProgs update conf = conf { unconfiguredProgs = update (unconfiguredProgs conf) } updateConfiguredProgs :: (ConfiguredProgs -> ConfiguredProgs) -> ProgramDb -> ProgramDb updateConfiguredProgs update conf = conf { configuredProgs = update (configuredProgs conf) } -- Read & Show instances are based on listToFM -- | Note that this instance does not preserve the known 'Program's. -- See 'restoreProgramDb' for details. -- instance Show ProgramDb where show = show . Map.toAscList . configuredProgs -- | Note that this instance does not preserve the known 'Program's. -- See 'restoreProgramDb' for details. -- instance Read ProgramDb where readsPrec p s = [ (emptyProgramDb { configuredProgs = Map.fromList s' }, r) | (s', r) <- readsPrec p s ] -- | Note that this instance does not preserve the known 'Program's. -- See 'restoreProgramDb' for details. -- instance Binary ProgramDb where put db = do put (progSearchPath db) put (configuredProgs db) get = do searchpath <- get progs <- get return $! emptyProgramDb { progSearchPath = searchpath, configuredProgs = progs } -- | The 'Read'\/'Show' and 'Binary' instances do not preserve all the -- unconfigured 'Programs' because 'Program' is not in 'Read'\/'Show' because -- it contains functions. So to fully restore a deserialised 'ProgramDb' use -- this function to add back all the known 'Program's. -- -- * It does not add the default programs, but you probably want them, use -- 'builtinPrograms' in addition to any extra you might need. -- restoreProgramDb :: [Program] -> ProgramDb -> ProgramDb restoreProgramDb = addKnownPrograms -- ------------------------------- -- Managing unconfigured programs -- | Add a known program that we may configure later -- addKnownProgram :: Program -> ProgramDb -> ProgramDb addKnownProgram prog = updateUnconfiguredProgs $ Map.insertWith combine (programName prog) (prog, Nothing, []) where combine _ (_, path, args) = (prog, path, args) addKnownPrograms :: [Program] -> ProgramDb -> ProgramDb addKnownPrograms progs conf = foldl' (flip addKnownProgram) conf progs lookupKnownProgram :: String -> ProgramDb -> Maybe Program lookupKnownProgram name = fmap (\(p,_,_)->p) . Map.lookup name . unconfiguredProgs knownPrograms :: ProgramDb -> [(Program, Maybe ConfiguredProgram)] knownPrograms conf = [ (p,p') | (p,_,_) <- Map.elems (unconfiguredProgs conf) , let p' = Map.lookup (programName p) (configuredProgs conf) ] -- | Get the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This is the default list of locations where programs are looked for when -- configuring them. This can be overridden for specific programs (with -- 'userSpecifyPath'), and specific known programs can modify or ignore this -- search path in their own configuration code. -- getProgramSearchPath :: ProgramDb -> ProgramSearchPath getProgramSearchPath = progSearchPath -- | Change the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This will affect programs that are configured from here on, so you -- should usually set it before configuring any programs. -- setProgramSearchPath :: ProgramSearchPath -> ProgramDb -> ProgramDb setProgramSearchPath searchpath db = db { progSearchPath = searchpath } -- | Modify the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This will affect programs that are configured from here on, so you -- should usually modify it before configuring any programs. -- modifyProgramSearchPath :: (ProgramSearchPath -> ProgramSearchPath) -> ProgramDb -> ProgramDb modifyProgramSearchPath f db = setProgramSearchPath (f $ getProgramSearchPath db) db -- |User-specify this path. Basically override any path information -- for this program in the configuration. If it's not a known -- program ignore it. -- userSpecifyPath :: String -- ^Program name -> FilePath -- ^user-specified path to the program -> ProgramDb -> ProgramDb userSpecifyPath name path = updateUnconfiguredProgs $ flip Map.update name $ \(prog, _, args) -> Just (prog, Just path, args) userMaybeSpecifyPath :: String -> Maybe FilePath -> ProgramDb -> ProgramDb userMaybeSpecifyPath _ Nothing conf = conf userMaybeSpecifyPath name (Just path) conf = userSpecifyPath name path conf -- |User-specify the arguments for this program. Basically override -- any args information for this program in the configuration. If it's -- not a known program, ignore it.. userSpecifyArgs :: String -- ^Program name -> [ProgArg] -- ^user-specified args -> ProgramDb -> ProgramDb userSpecifyArgs name args' = updateUnconfiguredProgs (flip Map.update name $ \(prog, path, args) -> Just (prog, path, args ++ args')) . updateConfiguredProgs (flip Map.update name $ \prog -> Just prog { programOverrideArgs = programOverrideArgs prog ++ args' }) -- | Like 'userSpecifyPath' but for a list of progs and their paths. -- userSpecifyPaths :: [(String, FilePath)] -> ProgramDb -> ProgramDb userSpecifyPaths paths conf = foldl' (\conf' (prog, path) -> userSpecifyPath prog path conf') conf paths -- | Like 'userSpecifyPath' but for a list of progs and their args. -- userSpecifyArgss :: [(String, [ProgArg])] -> ProgramDb -> ProgramDb userSpecifyArgss argss conf = foldl' (\conf' (prog, args) -> userSpecifyArgs prog args conf') conf argss -- | Get the path that has been previously specified for a program, if any. -- userSpecifiedPath :: Program -> ProgramDb -> Maybe FilePath userSpecifiedPath prog = join . fmap (\(_,p,_)->p) . Map.lookup (programName prog) . unconfiguredProgs -- | Get any extra args that have been previously specified for a program. -- userSpecifiedArgs :: Program -> ProgramDb -> [ProgArg] userSpecifiedArgs prog = maybe [] (\(_,_,as)->as) . Map.lookup (programName prog) . unconfiguredProgs -- ----------------------------- -- Managing configured programs -- | Try to find a configured program lookupProgram :: Program -> ProgramDb -> Maybe ConfiguredProgram lookupProgram prog = Map.lookup (programName prog) . configuredProgs -- | Update a configured program in the database. updateProgram :: ConfiguredProgram -> ProgramDb -> ProgramDb updateProgram prog = updateConfiguredProgs $ Map.insert (programId prog) prog -- | List all configured programs. configuredPrograms :: ProgramDb -> [ConfiguredProgram] configuredPrograms = Map.elems . configuredProgs -- --------------------------- -- Configuring known programs -- | Try to configure a specific program. If the program is already included in -- the collection of unconfigured programs then we use any user-supplied -- location and arguments. If the program gets configured successfully it gets -- added to the configured collection. -- -- Note that it is not a failure if the program cannot be configured. It's only -- a failure if the user supplied a location and the program could not be found -- at that location. -- -- The reason for it not being a failure at this stage is that we don't know up -- front all the programs we will need, so we try to configure them all. -- To verify that a program was actually successfully configured use -- 'requireProgram'. -- configureProgram :: Verbosity -> Program -> ProgramDb -> IO ProgramDb configureProgram verbosity prog conf = do let name = programName prog maybeLocation <- case userSpecifiedPath prog conf of Nothing -> programFindLocation prog verbosity (progSearchPath conf) >>= return . fmap (swap . fmap FoundOnSystem . swap) Just path -> do absolute <- doesExecutableExist path if absolute then return (Just (UserSpecified path, [])) else findProgramOnSearchPath verbosity (progSearchPath conf) path >>= maybe (die notFound) (return . Just . swap . fmap UserSpecified . swap) where notFound = "Cannot find the program '" ++ name ++ "'. User-specified path '" ++ path ++ "' does not refer to an executable and " ++ "the program is not on the system path." case maybeLocation of Nothing -> return conf Just (location, triedLocations) -> do version <- programFindVersion prog verbosity (locationPath location) newPath <- programSearchPathAsPATHVar (progSearchPath conf) let configuredProg = ConfiguredProgram { programId = name, programVersion = version, programDefaultArgs = [], programOverrideArgs = userSpecifiedArgs prog conf, programOverrideEnv = [("PATH", Just newPath)], programProperties = Map.empty, programLocation = location, programMonitorFiles = triedLocations } configuredProg' <- programPostConf prog verbosity configuredProg return (updateConfiguredProgs (Map.insert name configuredProg') conf) -- | Configure a bunch of programs using 'configureProgram'. Just a 'foldM'. -- configurePrograms :: Verbosity -> [Program] -> ProgramDb -> IO ProgramDb configurePrograms verbosity progs conf = foldM (flip (configureProgram verbosity)) conf progs -- | Try to configure all the known programs that have not yet been configured. -- configureAllKnownPrograms :: Verbosity -> ProgramDb -> IO ProgramDb configureAllKnownPrograms verbosity conf = configurePrograms verbosity [ prog | (prog,_,_) <- Map.elems notYetConfigured ] conf where notYetConfigured = unconfiguredProgs conf `Map.difference` configuredProgs conf -- | reconfigure a bunch of programs given new user-specified args. It takes -- the same inputs as 'userSpecifyPath' and 'userSpecifyArgs' and for all progs -- with a new path it calls 'configureProgram'. -- reconfigurePrograms :: Verbosity -> [(String, FilePath)] -> [(String, [ProgArg])] -> ProgramDb -> IO ProgramDb reconfigurePrograms verbosity paths argss conf = do configurePrograms verbosity progs . userSpecifyPaths paths . userSpecifyArgss argss $ conf where progs = catMaybes [ lookupKnownProgram name conf | (name,_) <- paths ] -- | Check that a program is configured and available to be run. -- -- It raises an exception if the program could not be configured, otherwise -- it returns the configured program. -- requireProgram :: Verbosity -> Program -> ProgramDb -> IO (ConfiguredProgram, ProgramDb) requireProgram verbosity prog conf = do -- If it's not already been configured, try to configure it now conf' <- case lookupProgram prog conf of Nothing -> configureProgram verbosity prog conf Just _ -> return conf case lookupProgram prog conf' of Nothing -> die notFound Just configuredProg -> return (configuredProg, conf') where notFound = "The program '" ++ programName prog ++ "' is required but it could not be found." -- | Check that a program is configured and available to be run. -- -- Additionally check that the program version number is suitable and return -- it. For example you could require 'AnyVersion' or @'orLaterVersion' -- ('Version' [1,0] [])@ -- -- It returns the configured program, its version number and a possibly updated -- 'ProgramDb'. If the program could not be configured or the version is -- unsuitable, it returns an error value. -- lookupProgramVersion :: Verbosity -> Program -> VersionRange -> ProgramDb -> IO (Either String (ConfiguredProgram, Version, ProgramDb)) lookupProgramVersion verbosity prog range programDb = do -- If it's not already been configured, try to configure it now programDb' <- case lookupProgram prog programDb of Nothing -> configureProgram verbosity prog programDb Just _ -> return programDb case lookupProgram prog programDb' of Nothing -> return $! Left notFound Just configuredProg@ConfiguredProgram { programLocation = location } -> case programVersion configuredProg of Just version | withinRange version range -> return $! Right (configuredProg, version ,programDb') | otherwise -> return $! Left (badVersion version location) Nothing -> return $! Left (unknownVersion location) where notFound = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but it could not be found." badVersion v l = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but the version found at " ++ locationPath l ++ " is version " ++ display v unknownVersion l = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but the version of " ++ locationPath l ++ " could not be determined." versionRequirement | isAnyVersion range = "" | otherwise = " version " ++ display range -- | Like 'lookupProgramVersion', but raises an exception in case of error -- instead of returning 'Left errMsg'. -- requireProgramVersion :: Verbosity -> Program -> VersionRange -> ProgramDb -> IO (ConfiguredProgram, Version, ProgramDb) requireProgramVersion verbosity prog range programDb = join $ either die return `fmap` lookupProgramVersion verbosity prog range programDb
tolysz/prepare-ghcjs
spec-lts8/cabal/Cabal/Distribution/Simple/Program/Db.hs
bsd-3-clause
17,726
0
20
4,155
2,929
1,601
1,328
258
4
{-# LANGUAGE Unsafe #-} module Check03 where import Check03_B mainN = do let n = mainM 1 print $ n
siddhanathan/ghc
testsuite/tests/safeHaskell/check/Check03.hs
bsd-3-clause
110
0
10
31
32
17
15
6
1
{-# LANGUAGE TemplateHaskell #-} -- | provides the parser functions module EmacsKeys.Parser (Modifier(..) ,parseEmacsKeys) where import Data.Char import Data.Either import Data.List.Split import Language.Haskell.TH.Lift import Text.XkbCommon -- | Represents the accepted modifiers 'C','M','S' data Modifier = Ctrl | Meta | Shift deriving (Show,Eq,Ord) deriveLift ''Modifier parseModifier :: String -> Either Modifier String parseModifier s = case lookup s modifiers of Just m -> Left m Nothing -> Right s parseKeys :: [Either Modifier String] -> Either String ([Modifier],[Keysym]) parseKeys keys = fmap (\keysyms -> (mods,keysyms)) $ sequence $ fmap (parseKeysym . if shift then fmap toUpper else id) $ unparsedSyms where (mods,unparsedSyms) = partitionEithers keys shift = Shift `elem` mods parseKeysym :: String -> Either String Keysym parseKeysym s = case keysymFromName s of Just ks -> Right ks Nothing -> Left $ "Invalid key: \"" ++ s ++ "\"" -- | Parse a string into a list of modifiers and keysyms -- If Shift is part of the modifiers, the keysyms are converted to upper case -- -- >>> parseEmacsKeys "M-a" -- Right ([Meta],[Keysym 97]) -- -- >>> parseEmacsKeys "Return" -- Right ([],[Keysym 65293]) -- -- >>> parseEmacsKeys "S-a" -- Right ([Shift],[Keysym 65]) parseEmacsKeys :: String -> Either String ([Modifier],[Keysym]) parseEmacsKeys = parseKeys . fmap parseModifier . splitOn "-" modifiers :: [(String,Modifier)] modifiers = [("C",Ctrl),("M",Meta),("S",Shift)]
cocreature/emacs-keys
src/EmacsKeys/Parser.hs
isc
1,619
0
11
357
418
235
183
34
2
#!/usr/bin/env runhaskell import System.Environment import Text.Printf main :: IO () main = do (fnPredict: fnObserve: _) <- getArgs predStr <- readFile fnPredict obsvStr <- readFile fnObserve let preds = map (head . words) $ lines predStr obsvs = map (head . words) $ lines obsvStr count :: Bool -> Bool -> Double count bx by = fromIntegral $ length $ filter (\(x,y) -> (x/="0")==bx && (y/="0")==by)$ zip preds obsvs nTP = count True True nFN = count False True nFP = count True False nTN = count False False hss = 2*(nTP*nTN - nFN*nFP)/ ((nTP+nFN)*(nFN+nTN) + (nTP+nFP)*(nFP+nTN)) tss = nTP/(nTP+nFN) - nFP/(nFP+nTN) printf "%f\t%f\n" nTP nFP printf "%f\t%f\n" nFN nTN printf "hss=%f\n" hss printf "tss=%f\n" tss
nushio3/UFCORIN
exe-src/skill-score.hs
mit
878
0
19
280
374
189
185
26
1
{- MsgFragments.hs: helper for backends that need to split up a message into multiple fragments. Part of Flounder: a message passing IDL for Barrelfish Copyright (c) 2007-2010, ETH Zurich. All rights reserved. This file is distributed under the terms in the attached LICENSE file. If you do not find this file, copies can be found by writing to: ETH Zurich D-INFK, Universit\"atstr. 6, CH-8092 Zurich. Attn: Systems Group. -} module MsgFragments where import Data.Bits import Data.List import Data.Ord import qualified CAbsSyntax as C import BackendCommon (Direction (..), intf_bind_var, msg_enum_elem_name, tx_union_elem, rx_union_elem, type_c_type) import Syntax import Arch -- an application level message is specified by one or more transport-level fragments -- for UMP, we have a top-level list of non-cap fragments and separate list of caps data MsgSpec = MsgSpec String [MsgFragment] [CapFieldTransfer] deriving (Show, Eq) -- a message fragment defines the layout of a transport-level message data MsgFragment = MsgFragment [FragmentWord] | OverflowFragment OverflowFragment deriving (Show, Eq) -- some fragments are "special" in that they can overflow and occupy an -- arbitrary number of underlying transport messages, because their size is -- only known at run time data OverflowFragment = -- for marshalling byte arrays: type, data pointer and length fields BufferFragment TypeBuiltin ArgField ArgField -- for marshalling strings: string pointer field | StringFragment ArgField deriving (Show, Eq) -- LMP is a special case where caps can be sent in message fragments data LMPMsgSpec = LMPMsgSpec String [LMPMsgFragment] deriving (Show, Eq) data LMPMsgFragment = LMPMsgFragment MsgFragment (Maybe CapFieldTransfer) deriving (Show, Eq) type FragmentWord = [ArgFieldFragment] -- an arg fragment refers to a (portion of a) primitive value which is part of -- a (possibly larger) message argument, by type, qualified name and bit offset data ArgFieldFragment = ArgFieldFragment TypeBuiltin ArgField Int | MsgCode -- implicit argument, occurs once per message deriving (Show, Eq) -- an argument field names the lowest-level field of an argument -- each entry in the list is a field name and (optional) array index -- eg. foo[3].bar is [NamedField "foo", ArrayField 3, NamedField "bar"] type ArgField = [ArgFieldElt] data ArgFieldElt = NamedField String | ArrayField Integer deriving (Show, Eq) -- modes of transfering a cap data CapTransferMode = GiveAway | Copied deriving (Show, Eq) -- a capability is just identified by the name of its field type CapField = ArgField -- a capability transfer is identified by the name of its field and the type -- of transfer requested data CapFieldTransfer = CapFieldTransfer CapTransferMode ArgField deriving (Show, Eq) -- to generate the above, we use a slightly different intermediate -- representation, which uses a list of fragments of individual fields data FieldFragment = FieldFragment ArgFieldFragment | CapField CapTransferMode ArgField | OverflowField OverflowFragment deriving (Show, Eq) -- builtin type used to transmit message code msg_code_type :: TypeBuiltin msg_code_type = UInt16 build_msg_spec :: Arch -> Int -> Bool -> [TypeDef] -> MessageDef -> MsgSpec build_msg_spec arch words_per_frag contains_msgcode types (Message _ mn args _) -- ensure that we don't produce a completely empty message | (msg_frags ++ overflow_frags) == [] = MsgSpec mn [MsgFragment []] capfield_transfers | otherwise = MsgSpec mn (msg_frags ++ overflow_frags) capfield_transfers where (frags, capfields, overfields) = partition_frags $ build_field_fragments arch types args field_frags = sort_field_fragments arch frags msg_frags = find_msg_fragments arch words_per_frag contains_msgcode field_frags overflow_frags = map OverflowFragment overfields capfield_transfers = map (\(CapField tm cf) -> (CapFieldTransfer tm cf)) capfields -- build an LMP message spec by merging in the caps from a UMP spec build_lmp_msg_spec :: Arch -> [TypeDef] -> MessageDef -> LMPMsgSpec build_lmp_msg_spec arch types msgdef = LMPMsgSpec mn (merge_caps frags caps) where MsgSpec mn frags caps = build_msg_spec arch (lmp_words arch) True types msgdef -- XXX: ensure that we never put a cap together with an overflow fragment -- even though this could work at the transport-level, the current -- LMP code doesn't support it merge_caps :: [MsgFragment] -> [CapFieldTransfer] -> [LMPMsgFragment] merge_caps [] [] = [] merge_caps (mf:restf) [] = (LMPMsgFragment mf Nothing):(merge_caps restf []) merge_caps [] (c:restc) = (LMPMsgFragment (MsgFragment []) (Just c)):(merge_caps [] restc) merge_caps ((mf@(OverflowFragment _)):restf) caps = (LMPMsgFragment mf Nothing):(merge_caps restf caps) merge_caps (mf:restf) (c:restc) = (LMPMsgFragment mf (Just c)):(merge_caps restf restc) -- partition a list of field fragments into (ordinary fields, caps, overflow buffers/strings) partition_frags :: [FieldFragment] -> ([FieldFragment], [FieldFragment], [OverflowFragment]) partition_frags [] = ([], [], []) partition_frags (h:t) = case h of f@(FieldFragment _) -> (f:restf, restc, resto) f@(CapField _ _) -> (restf, f:restc, resto) OverflowField o -> (restf, restc, o:resto) where (restf, restc, resto) = partition_frags t find_msg_fragments :: Arch -> Int -> Bool -> [FieldFragment] -> [MsgFragment] find_msg_fragments arch words_per_frag contains_msgcode frags = group_frags frags first_frag where -- does the first fragment need to contain the message code? first_frag | contains_msgcode = MsgFragment [[MsgCode]] | otherwise = MsgFragment [] group_frags :: [FieldFragment] -> MsgFragment -> [MsgFragment] group_frags [] (MsgFragment []) = [] -- empty fragment, drop it group_frags [] cur = [cur] -- terminated search group_frags ((FieldFragment f):rest) (MsgFragment []) = group_frags rest (MsgFragment [[f]]) group_frags ((FieldFragment f):rest) cur@(MsgFragment wl) -- can we fit another fragment into the current word? | can_fit_word lastword f = group_frags rest (MsgFragment (restwords ++ [lastword ++ [f]])) -- can we fit another word onto the current message fragment? | (length wl) < words_per_frag = group_frags rest (MsgFragment (wl ++ [[f]])) | otherwise = cur:(group_frags rest (MsgFragment [[f]])) where lastword = last wl restwords = init wl bitsizeof = bitsizeof_argfieldfrag arch can_fit_word :: FragmentWord -> ArgFieldFragment -> Bool can_fit_word word frag = (sum $ map bitsizeof word) + bitsizeof frag <= wordsize arch -- sort the list of fragments by size, to optimise packing sort_field_fragments :: Arch -> [FieldFragment] -> [FieldFragment] sort_field_fragments ar = sortBy cmp where cmp (FieldFragment f1) (FieldFragment f2) = comparing (bitsizeof_argfieldfrag ar) f1 f2 build_field_fragments :: Arch -> [TypeDef] -> [MessageArgument] -> [FieldFragment] build_field_fragments arch types args = concat $ map arg_fragments args where arg_fragments :: MessageArgument -> [FieldFragment] arg_fragments (Arg (TypeAlias _ b) v) = arg_fragments (Arg (Builtin b) v) arg_fragments (Arg (Builtin t) (DynamicArray n l)) | t `elem` [UInt8, Int8, Char] = [OverflowField $ BufferFragment t [NamedField n] [NamedField l]] | otherwise = error "dynamic arrays of types other than char/int8/uint8 are not yet supported" arg_fragments (Arg (Builtin b) v) = fragment_builtin [NamedField (varname v)] b arg_fragments (Arg (TypeVar t) v) = fragment_typedef [NamedField (varname v)] (lookup_type_name types t) varname (Name n) = n varname (DynamicArray _ _) = error "dynamic arrays of types other than char/int8/uint8 are not yet supported" fragment_typedef :: ArgField -> TypeDef -> [FieldFragment] fragment_typedef f (TStruct _ fl) = concat [fragment_typeref ((NamedField fn):f) tr | TStructField tr fn <- fl] fragment_typedef f (TArray tr _ len) = concat [fragment_typeref i tr | i <- fields] where fields = [(ArrayField i):f | i <- [0..(len - 1)]] fragment_typedef f (TEnum _ _) = fragment_builtin f (enum_type arch) fragment_typedef f (TAlias _ _) = error "aliases unhandled here" fragment_typedef f (TAliasT _ b) = fragment_builtin f b fragment_typeref :: ArgField -> TypeRef -> [FieldFragment] fragment_typeref f (Builtin b) = fragment_builtin f b fragment_typeref f (TypeAlias _ b) = fragment_builtin f b fragment_typeref f (TypeVar tv) = fragment_typedef f (lookup_type_name types tv) fragment_builtin :: ArgField -> TypeBuiltin -> [FieldFragment] fragment_builtin f Cap = [CapField Copied f] fragment_builtin f GiveAwayCap = [CapField GiveAway f] fragment_builtin f String = [OverflowField $ StringFragment f] fragment_builtin f t = [FieldFragment (ArgFieldFragment t f off) | off <- [0, (wordsize arch) .. (bitsizeof_builtin arch t - 1)]] bitsizeof_argfieldfrag :: Arch -> ArgFieldFragment -> Int bitsizeof_argfieldfrag a (ArgFieldFragment t _ _) = min (wordsize a) (bitsizeof_builtin a t) bitsizeof_argfieldfrag a MsgCode = bitsizeof_builtin a msg_code_type bitsizeof_builtin :: Arch -> TypeBuiltin -> Int bitsizeof_builtin _ UInt8 = 8 bitsizeof_builtin _ UInt16 = 16 bitsizeof_builtin _ UInt32 = 32 bitsizeof_builtin _ UInt64 = 64 bitsizeof_builtin _ Int8 = 8 bitsizeof_builtin _ Int16 = 16 bitsizeof_builtin _ Int32 = 32 bitsizeof_builtin _ Int64 = 64 bitsizeof_builtin a UIntPtr = ptrsize a bitsizeof_builtin a IntPtr = ptrsize a bitsizeof_builtin a Size = sizesize a bitsizeof_builtin _ Bool = 1 bitsizeof_builtin _ IRef = 32 -- FIXME: move out of flounder bitsizeof_builtin _ Char = 8 bitsizeof_builtin _ String = undefined bitsizeof_builtin _ Cap = undefined bitsizeof_builtin _ ErrVal = 32 bitsizeof_builtin _ GiveAwayCap = undefined ------------------------------------------------------- -- Utility function for working with arg fields -- This generates a C expression to access a given field ------------------------------------------------------- argfield_expr :: Direction -> String -> ArgField -> C.Expr argfield_expr TX mn [NamedField n] = tx_union_elem mn n argfield_expr RX mn [NamedField n] = rx_union_elem mn n argfield_expr _ _ [ArrayField n] = error "invalid; top-level array" argfield_expr dir mn ((NamedField n):rest) = C.FieldOf (argfield_expr dir mn rest) n argfield_expr dir mn ((ArrayField i):rest) = C.SubscriptOf (C.DerefPtr $ argfield_expr dir mn rest) (C.NumConstant i) -- generate a C expression for constructing the given word of a message fragment fragment_word_to_expr :: Arch -> String -> String -> FragmentWord -> C.Expr fragment_word_to_expr arch ifn mn frag = mkwordexpr 0 frag where mkwordexpr :: Int -> FragmentWord -> C.Expr mkwordexpr shift [af] = doshift shift (mkfieldexpr af) mkwordexpr shift (af:rest) = C.Binary C.BitwiseOr cur $ mkwordexpr rshift rest where cur = doshift shift (mkfieldexpr af) rshift = shift + bitsizeof_argfieldfrag arch af doshift :: Int -> C.Expr -> C.Expr doshift 0 ex = ex doshift n ex = C.Binary C.LeftShift (C.Cast (C.TypeName "uintptr_t") ex) (C.NumConstant $ toInteger n) mkfieldexpr :: ArgFieldFragment -> C.Expr mkfieldexpr MsgCode = C.Variable $ msg_enum_elem_name ifn mn mkfieldexpr (ArgFieldFragment t af 0) = fieldaccessor t af mkfieldexpr (ArgFieldFragment t af off) = C.Binary C.RightShift (fieldaccessor t af) (C.NumConstant $ toInteger off) -- special-case bool types to ensure we only get the one-bit true/false value -- ticket #231 fieldaccessor Bool af = C.Binary C.NotEquals (argfield_expr TX mn af) (C.Variable "false") fieldaccessor _ af = argfield_expr TX mn af store_arg_frags :: Arch -> String -> String -> C.Expr -> Int -> Int -> [ArgFieldFragment] -> [C.Stmt] store_arg_frags _ _ _ _ _ _ [] = [] store_arg_frags arch ifn mn msgdata_ex word bitoff (MsgCode:rest) = store_arg_frags arch ifn mn msgdata_ex word (bitoff + bitsizeof_argfieldfrag arch MsgCode) rest store_arg_frags _ _ _ _ _ _ ((ArgFieldFragment String _ _):_) = error "strings are not handled here" store_arg_frags arch ifn mn msgdata_ex word bitoff (aff@(ArgFieldFragment t af argoff):rest) = (C.Ex expr):(store_arg_frags arch ifn mn msgdata_ex word (bitoff + bitsize) rest) where bitsize = bitsizeof_argfieldfrag arch aff expr = C.Assignment (argfield_expr RX mn af) assval assval | argoff == 0 = mask msgval | otherwise = C.Binary C.BitwiseOr (argfield_expr RX mn af) (C.Binary C.LeftShift (C.Cast (type_c_type ifn $ Builtin t) (mask msgval)) (C.NumConstant $ toInteger argoff)) msgval | bitoff == 0 = msgword | otherwise = C.Binary C.RightShift msgword (C.NumConstant $ toInteger bitoff) msgword = C.SubscriptOf msgdata_ex $ C.NumConstant $ toInteger word mask ex | bitsize == (wordsize arch) = ex | otherwise = C.Binary C.BitwiseAnd ex (C.HexConstant maskval) where maskval = (shift 1 bitsize) - 1
8l/barrelfish
tools/flounder/MsgFragments.hs
mit
14,228
0
15
3,455
3,680
1,911
1,769
205
14
------------------------------------------------------------------------- -- -- Set.hs -- -- ADT of sets, implemented as ordered lists without repetitions. -- -- (c) Addison-Welsey, 1996-2011. -- --------------------------------------------------------------------------- module Set ( Set , empty , -- Set a sing , -- a -> Set a memSet , -- Ord a => Set a -> a -> Bool union,inter,diff , -- Ord a => Set a -> Set a -> Set a eqSet , -- Eq a => Set a -> Set a -> Bool subSet , -- Ord a => Set a -> Set a -> Bool makeSet , -- Ord a => [a] -> Set a mapSet , -- Ord b => (a -> b) -> Set a -> Set b filterSet , -- (a -> Bool) -> Set a -> Set a foldSet , -- (a -> a -> a) -> a -> Set a -> a showSet , -- (a -> String) -> Set a -> String card , -- Set a -> Int flatten -- Set a -> [a] ) where import Data.List hiding ( union ) -- -- Instance declarations for Eq and Ord instance Eq a => Eq (Set a) where (==) = eqSet instance Ord a => Ord (Set a) where (<=) = leqSet -- The implementation. -- newtype Set a = Set [a] empty :: Set a empty = Set [] sing :: a -> Set a sing x = Set [x] memSet :: Ord a => Set a -> a -> Bool memSet (Set []) y = False memSet (Set (x:xs)) y | x<y = memSet (Set xs) y | x==y = True | otherwise = False union :: Ord a => Set a -> Set a -> Set a union (Set xs) (Set ys) = Set (uni xs ys) uni :: Ord a => [a] -> [a] -> [a] uni [] ys = ys uni xs [] = xs uni (x:xs) (y:ys) | x<y = x : uni xs (y:ys) | x==y = x : uni xs ys | otherwise = y : uni (x:xs) ys inter :: Ord a => Set a -> Set a -> Set a inter (Set xs) (Set ys) = Set (int xs ys) int :: Ord a => [a] -> [a] -> [a] int [] ys = [] int xs [] = [] int (x:xs) (y:ys) | x<y = int xs (y:ys) | x==y = x : int xs ys | otherwise = int (x:xs) ys diff :: Ord a => Set a -> Set a -> Set a diff (Set xs) (Set ys) = Set (dif xs ys) dif :: Ord a => [a] -> [a] -> [a] dif [] ys = [] dif xs [] = xs dif (x:xs) (y:ys) | x<y = x : dif xs (y:ys) | x==y = dif xs ys | otherwise = dif (x:xs) ys subSet :: Ord a => Set a -> Set a -> Bool subSet (Set xs) (Set ys) = subS xs ys subS :: Ord a => [a] -> [a] -> Bool subS [] ys = True subS xs [] = False subS (x:xs) (y:ys) | x<y = False | x==y = subS xs ys | x>y = subS (x:xs) ys eqSet :: Eq a => Set a -> Set a -> Bool eqSet (Set xs) (Set ys) = (xs == ys) leqSet :: Ord a => Set a -> Set a -> Bool leqSet (Set xs) (Set ys) = (xs <= ys) -- makeSet :: Ord a => [a] -> Set a makeSet = Set . remDups . sort where remDups [] = [] remDups [x] = [x] remDups (x:y:xs) | x < y = x : remDups (y:xs) | otherwise = remDups (y:xs) mapSet :: Ord b => (a -> b) -> Set a -> Set b mapSet f (Set xs) = makeSet (map f xs) filterSet :: (a -> Bool) -> Set a -> Set a filterSet p (Set xs) = Set (filter p xs) foldSet :: (a -> a -> a) -> a -> Set a -> a foldSet f x (Set xs) = (foldr f x xs) showSet :: (a->String) -> Set a -> String showSet f (Set xs) = concat (map ((++"\n") . f) xs) card :: Set a -> Int card (Set xs) = length xs -- Breaks the abstraction: used in Relation: flatten (Set xs) = xs -- 16.36 -- Difference between s1 and s2 is the set of elements -- of s1 that don't belong to s2 diff' :: Ord a => Set a -> Set a -> Set a diff' (Set s1) (Set s2) = Set (dif' s1 s2) dif' :: Ord a => [a] -> [a] -> [a] dif' s1 [] = s1 dif' [] _ = [] dif' (x:xs) (y:ys) | x == y = dif' xs ys | x < y = x : dif' xs (y:ys) | x > y = dif (x:xs) ys -- 16.37 symmDiff :: Ord a => Set a -> Set a -> Set a symmDiff s1 s2 = union (diff s1 s2) (diff s2 s1) -- 16.39 setUnion :: Ord a => Set (Set a) -> Set a setUnion ss = foldSet union empty ss -- where -- fn = (\a s -> union a s) setInter :: Ord a => Set (Set a) -> Set a setInter s@(Set ss) = foldSet fn initial rest where initial = head ss rest = makeSet (tail ss) fn = (\a v -> inter a v)
CarmineM74/haskell_craft3e
Set.hs
mit
4,148
32
11
1,358
2,077
1,054
1,023
106
3
---------------------------------------- -- Syntax.hs -- 抽象構文木の定義 -- -- 新入生SG お手本インタプリタ -- 2012/05/23 高島尚希 ---------------------------------------- module Syntax where import Control.Monad -------------------------------- -- トップレベル式 -------------------------------- type TopExpr = [(Id, TypeString, Expr)] type TypeString = String printTopExpr :: TopExpr -> IO () printTopExpr = mapM_ $ \(f,t,_) -> putStrLn $ f ++ " :: " ++ t -------------------------------- -- 式 -------------------------------- -- 識別子(変数名,関数名) type Id = String -- 式の抽象構文木 data Expr = Const ConstId | Prim PrimId | Var Id | Fun Id Expr | App Expr Expr | If Expr Expr Expr | Let Id Expr Expr | LetRec Id Expr Expr | Force Expr Type | Match Expr [(Pat, Expr, Expr)] | Tuple [Expr] | Null deriving Show -- 定数 data ConstId = Int Int | Bool Bool | Char Char | Double Double | Unit deriving (Show,Eq) -- プリミティブ関数 data PrimId = Neg | Not | FNeg | Add | Sub | Mul | Div | Mod | FAdd | FSub | FMul | FDiv | Lt | Le | Gt | Ge | Eq | Ne | And | Or | Cons | Append | MakeLeft | MakeRight | Print | Chr | Ord | ToInt | ToDouble deriving Show -- パターン data Pat = PConst ConstId | PWild | PNull | PVar Id | PCons Pat Pat | PTuple [Pat] | PLeft Pat | PRight Pat deriving Show -------------------------------- -- 型 -------------------------------- -- 型スキーム data TypeScheme = ForAll [TVar] Type deriving Eq -- 型 data Type = TInt | TBool | TChar | TDouble | TUnit | TList Type | TFun Type Type | TVar TVar | TVarName String | TTuple [Type] | TEither Type Type deriving Eq -- 型変数 type TVar = Int -------------------------------- -- 型の表示 -------------------------------- -- Show クラスのインスタンスにする instance Show Type where show TInt = "Int" show TBool = "Bool" show TChar = "Char" show TDouble = "Double" show TUnit = "()" show (TList TChar) = "String" show (TList t) = "[" ++ show t ++ "]" show (TTuple ts) = "(" ++ (tail . init) (show ts) ++ ")" show (TFun t1 t2) = "(" ++ show t1 ++ " -> " ++ show t2 ++ ")" show (TVar n) = show n show (TVarName s) = "\'" ++ s show (TEither t1 t2) = "Either " ++ show t1 ++ " " ++ show t2 -- 型変数に名前を付ける {- TVar 0 のような変数を,TVarName 'a' のようなアルファベットの名前に 置き換えます。足りなくなると a1 b1 ... a2 b2 ... となります。 これは,OCamlが型変数の名前を付けるときの動作です。 ここでも(typeinf同様) State モナドを使っています。 -} type NameStType = (Int, [(TVar,String)]) newtype NameSt a = NameSt { runNameSt :: NameStType -> (a, NameStType) } instance Monad NameSt where return a = NameSt (\s -> (a,s)) (NameSt f) >>= g = NameSt (\st1 -> let (v, st2) = f st1 in runNameSt (g v) st2) findStr :: TVar -> NameSt (Maybe String) findStr v = NameSt (\(n,map) -> (lookup v map, (n,map))) getAndIncrCount :: NameSt Int getAndIncrCount = NameSt (\(n,map) -> (n,(n+1,map))) addName :: TVar -> String -> NameSt () addName v s = NameSt (\(n,map) -> ((),(n,(v,s):map))) nameTVar :: Type -> NameSt Type nameTVar (TFun t1 t2) = do t1' <- nameTVar t1 t2' <- nameTVar t2 return (TFun t1' t2') nameTVar (TList t) = do t' <- nameTVar t return (TList t') nameTVar (TTuple ts) = liftM TTuple $ nameTVarTuple ts nameTVar (TVar v) = do maybeS <- findStr v case maybeS of Just s -> return $ TVarName s Nothing -> do n <- getAndIncrCount let newName = makeName n addName v newName return $ TVarName $ makeName n nameTVar TInt = return TInt nameTVar TBool = return TBool nameTVar TChar = return TChar nameTVar TDouble = return TDouble nameTVar TUnit = return TUnit nameTVar (TVarName s) = return (TVarName s) nameTVar (TEither t1 t2) = do t1' <- nameTVar t1 t2' <- nameTVar t2 return (TEither t1' t2') nameTVarTuple :: [Type] -> NameSt [Type] nameTVarTuple [] = return [] nameTVarTuple (t:ts) = do t' <- nameTVar t ts' <- nameTVarTuple ts return (t':ts') makeName :: Int -> String makeName n = if q == 0 then (dtoc r):"" else (dtoc r):(show q) where dtoc n = toEnum (fromEnum 'a' + n) r = n `mod` 26 q = n `div` 26 runNameTVar :: Type -> Type runNameTVar t = fst $ runNameSt (nameTVar t) (0,[]) instance Show TypeScheme where show (ForAll _ t) = show (runNameTVar t)
lambdataro/Dive
Syntax.hs
mit
4,616
0
15
1,029
1,623
878
745
135
2
-- | Implementation of an execution environment that uses /podman/. module B9.Podman ( Podman (..), ) where import B9.B9Config ( getB9Config, podmanConfigs, ) import B9.B9Config.Podman as X import B9.Container import B9.DiskImages import B9.ShellScript import Control.Lens (view) newtype Podman = Podman PodmanConfig instance Backend Podman where getBackendConfig _ = fmap Podman . view podmanConfigs <$> getB9Config -- supportedImageTypes :: proxy config -> [ImageType] supportedImageTypes _ = [Raw] -- runInEnvironment :: -- forall e. -- (Member BuildInfoReader e, CommandIO e) => -- config -> -- ExecEnv -> -- Script -> -- Eff e Bool runInEnvironment (Podman _dcfg) _env scriptIn = do if emptyScript scriptIn then return True else do error "TODO"
sheyll/b9-vm-image-builder
src/lib/B9/Podman.hs
mit
821
0
11
180
162
94
68
19
0
{-# LANGUAGE Safe #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} module FP15.Compiler.Syntax.Precedence ( -- * Examples -- $examples -- * The Same Typeclass Same(key, same), Self(..), -- * Main Types Assoc(..), PrecNode(..), Tree(..), RightTree(..), PrecParseError(..), -- * Type Synonyms Prec, PrecRepr, Result, -- * Precdence Parsing insDefault, parsePrec, splitInfixNode, -- * Helpers showTree, showTree', showStringTree, getPrec ) where import Control.Applicative import Data.Maybe(mapMaybe) import Data.List.Split(split, whenElt) import Data.List import FP15.Disp import FP15.Types(Prec, Located, getLocated) import qualified Data.Map as M -- | The 'Same' typeclass is for determining the "identity" of an operator. This -- typeclass is needed to deal with the fact that same operators with different -- location info are considered the same. -- -- All instances of the 'Same' typeclass must implement the 'key' function, -- which is used to determine if two values are the 'same'. class (Eq k, Ord k) => Same a k | a -> k where {-# MINIMAL key #-} key :: a -> k same :: a -> a -> Bool same a b = key a == key b -- | The 'Self' type is an instance of 'Same' that has key of the value -- itself. newtype Self a = Self a getSelf :: Self a -> a getSelf (Self x) = x instance (Eq a, Ord a) => Same (Self a) a where key = getSelf instance (Eq a, Ord a) => Same (Located a) a where key = getLocated instance Same Assoc Assoc where key = id -- | Precedence are tie-broken by associativity. type PrecRepr = (Prec, Maybe Assoc) data Assoc = VarA | LeftA | RightA deriving (Eq, Ord, Show, Read) data PrecNode o a = PreN Prec o | InfN Assoc Prec o | TermN a deriving (Eq, Ord, Show, Read) data Tree o a = Pre o (Tree o a) | Inf (Tree o a) o (Tree o a) | Var o [Tree o a] | Term (Maybe a) deriving (Eq, Ord, Show, Read) data RightTree o a = Last [PrecNode o a] | RBranch [PrecNode o a] (Assoc, o) (RightTree o a) deriving (Eq, Ord, Show, Read) data PrecParseError o a = ConsecutiveTerms ![PrecNode o a] | MixingVarOp ![o] ![[PrecNode o a]] deriving (Eq, Ord, Show, Read) instance (Show o, Show a) => Disp (PrecParseError o a) where disp = show type Result r o a = Either (PrecParseError o a) (r o a) showTree :: (Show o, Show a) => Tree o a -> String showTree = showTree' show show showTree' :: (o -> String) -> (a -> String) -> Tree o a -> String showTree' so sa = f where f (Pre o t) = "(" ++ so o ++ " " ++ f t ++ ")" f (Inf a o b) = "(" ++ f a ++ " " ++ so o ++ " " ++ f b ++ ")" f (Var o ts) = "(" ++ so o ++ " " ++ unwords (map f ts) ++ ")" f (Term Nothing) = "_" f (Term (Just x)) = sa x showStringTree :: Tree String String -> String showStringTree = showTree' id id -- | The 'getPrec' function gets the precedence representation of a 'PrecNode'. getPrec :: PrecNode o a -> Maybe PrecRepr getPrec (PreN p _) = Just (p, Nothing) getPrec (InfN a p _) = Just (p, Just a) getPrec _ = Nothing -- | The 'insDefault' function inserts a default infix operator between two -- adjacent terms. Must be done because the precedence parsing functions cannot -- handle two consecutive terms. insDefault :: (Assoc, Prec, o) -> [PrecNode o a] -> [PrecNode o a] insDefault (a, p, o) ns = ins (InfN a p o) ns [] ins :: PrecNode o a -> [PrecNode o a] -> [PrecNode o a] -> [PrecNode o a] ins x [] !acc = acc ins x [a] !acc = acc ++ [a] ins x (a@(TermN _):b:cs) !acc | isTermOrPrefix b = ins x (b:cs) (acc ++ [a, x]) where isTermOrPrefix (TermN _) = True isTermOrPrefix (PreN _ _) = True isTermOrPrefix _ = True ins x (a:b:cs) !acc = ins x (b:cs) (acc ++ [a]) -- | The 'parsePrec' performs precedence parsing from a list of 'PrecNode's. -- -- Precondition: @ns@ is a result of @insDefault@. In other words, @ns@ cannot -- contain two consecutive 'TermN's. parsePrec :: Same o k => [PrecNode o a] -> Result Tree o a parsePrec ns = parsePrec' precs ns where precs = sort $ mapMaybe getPrec ns parsePrec' :: Same o k => [PrecRepr] -> [PrecNode o a] -> Result Tree o a parsePrec' (p2@(p, _):ps) (PreN p0 o : ns) | p0 < p = Pre o <$> parsePrec' (p2:ps) ns parsePrec' (p:ps) ns = joinParts (parsePrec' ps) =<< splitInfixNode p ns -- Base cases parsePrec' _ [] = return $ Term Nothing parsePrec' _ [TermN x] = return $ Term (Just x) parsePrec' _ [InfN _ _ o] = return $ Inf (Term Nothing) o (Term Nothing) parsePrec' _ [PreN _ o] = return $ Pre o (Term Nothing) parsePrec' [] (PreN _ o : xs) = Pre o <$> parsePrec' [] xs parsePrec' [] xs@(_:_) = Left $ ConsecutiveTerms xs -- | Given a 'RightTree' of operators with same precedence, join them into a -- 'Tree'. -- -- Precondition: All nodes must have consistent associativity. joinParts :: Same o k => ([PrecNode o a] -> Result Tree o a) -> RightTree o a -> Result Tree o a joinParts f ps = let (xs, y) = toListR ps in case uniq $ map (\(_, a, _) -> a) xs of Left Nothing -> f y Left (Just VarA) -> -- TODO uniq doesn't work because all location info is unique case uniq $ map (\(_, _, o) -> o) xs of Left (Just o) -> do ys <- mapM (\(x, _, _) -> f x) xs z <- f y return $ Var o (ys ++ [z]) Left Nothing -> error "FP15.Compiler.Precedence.joinParts: impossible" Right os -> Left $ MixingVarOp os $ map (\(a, _, _) -> a) xs ++ [y] Left (Just LeftA) -> do let (x0, xs') = toListL ps y0 <- f x0 ys <- mapM (\(a0, o, b) -> f b >>= \b' -> return (a0, o, b')) xs' return $ foldl (\a (_, o, b') -> Inf a o b') y0 ys Left (Just RightA) -> do z0 <- f y ys <- mapM (\(a, a0, o) -> f a >>= \a' -> return (a', a0, o)) xs return $ foldr (\(a', _, o) b -> Inf a' o b) z0 ys Right _ -> error "FP15.Compiler.Precedence.joinParts: impossible: multiple assocs" toListR :: RightTree o a -> ([([PrecNode o a], Assoc, o)], [PrecNode o a]) toListR (Last x) = ([], x) toListR (RBranch x (a, o) t) = let (xs, y) = toListR t in ((x, a, o):xs, y) toListL :: RightTree o a -> ([PrecNode o a], [(Assoc, o, [PrecNode o a])]) toListL (Last x) = (x, []) toListL (RBranch x (a, o) t) = (x, ys) where ys = f (a, o) t f (a', o') (Last x') = [(a', o', x')] f (a', o') (RBranch x' (a'', o'') t') = (a', o', x'):f (a'', o'') t' uniq :: Same a k => [a] -> Either (Maybe a) [a] uniq l = case M.toList $ M.fromList $ map (\x -> (key x, x)) l of [] -> Left Nothing [(k0, x)] -> Left (Just x) ys -> Right $ map snd ys -- | The 'splitInfixNode' split a list of @PrecNode@s by infix operators of the -- given precedence. -- -- >>> splitInfixNode (0, Just LeftA) [PreN 0 "+"] -- Last [PreN 0 "+"] -- >>> splitInfixNode (0, Just LeftA) [PreN 0 "+", TermN "x"] -- Last [PreN 0 "+",TermN "x"] -- >>> splitInfixNode (0, Just LeftA) [TermN "x", InfN LeftA 0 "+", TermN "y"] -- RBranch [TermN "x"] (LeftA,"+") (Last [TermN "y"]) -- >>> splitInfixNode (0, Just LeftA) [TermN "x", InfN LeftA 0 "+", TermN "y", InfN LeftA 1 "*", TermN "z"] -- RBranch [TermN "x"] (LeftA,"+") (Last [TermN "y",InfN LeftA 1 "*",TermN "z"]) splitInfixNode :: PrecRepr -> [PrecNode o a] -> Result RightTree o a splitInfixNode p = parsePairs . split (whenElt $ isInfixNodeOf p) where parsePairs [x] = return $ Last x parsePairs (x:[InfN a' p' o]:xs) | p == (p', Just a') = RBranch x (a', o) <$> parsePairs xs | otherwise = error "FP15.Compiler.Precedence.splitInfixNode: impossible: wrong prec" parsePairs _ = error "FP15.Compiler.Precedence.splitInfixNode: impossible: empty list" isInfixNodeOf :: PrecRepr -> PrecNode o a -> Bool isInfixNodeOf p (InfN a p' _) = (p', Just a) == p isInfixNodeOf _ _ = False -- $examples -- Here are some examples to demonstrate precedence parsing. -- -- Some definitions to make the inputs more readable. -- -- >>> let (t,l,r,v,p) = (TermN,InfN LeftA,InfN RightA,InfN VarA,PreN) -- -- Left associative operator: -- -- >>> showStringTree $ parsePrec [t"x", l 0 "+", t"y", l 0 "+", t"z", l 0 "-", t"w"] -- "(((x + y) + z) - w)" -- -- Right associative operator: -- -- >>> showStringTree $ parsePrec [t"x", r 0 "+", t"y", r 0 "+", t"z", r 0 "-", t"w"] -- "(x + (y + (z - w)))" -- -- Variadic associative operator: -- -- >>> showStringTree $ parsePrec [t"x", v 0 "><", t"y", v 0 "><", t"z", v 0 "><", t"w"] -- "(>< x y z w)" -- -- For same precedence level, right-associative has higher precedence and -- variadic has lowest. -- -- >>> showStringTree $ parsePrec [t"a", l 0 "->", t"b", l 0 "->", t"d", r 0 "<-", t"c", l 0 "->", t"e"] -- "(((a -> b) -> (d <- c)) -> e)" -- $doctests -- >>> splitInfixNode (0, Just LeftA) [TermN "x", InfN LeftA 0 "+"] -- RBranch [TermN "x"] (LeftA,"+") (Last []) -- >>> splitInfixNode (0, Just LeftA) [InfN LeftA 0 "+"] -- RBranch [] (LeftA,"+") (Last []) -- >>> splitInfixNode (0, Just LeftA) [TermN "x", InfN LeftA 0 "+", TermN "y", InfN LeftA 0 "-", TermN "z"] -- RBranch [TermN "x"] (LeftA,"+") (RBranch [TermN "y"] (LeftA,"-") (Last [TermN "z"])) -- >>> splitInfixNode (0, Just LeftA) [TermN "x", InfN LeftA 0 "+", TermN "y", InfN LeftA 1 "*", TermN "z", InfN LeftA 0 "-"] -- RBranch [TermN "x"] (LeftA,"+") (RBranch [TermN "y",InfN LeftA 1 "*",TermN "z"] (LeftA,"-") (Last [])) -- >>> splitInfixNode (0, Just LeftA) [TermN "x", InfN LeftA 0 "+", TermN "y", InfN LeftA 1 "*", InfN LeftA 0 "-"] -- RBranch [TermN "x"] (LeftA,"+") (RBranch [TermN "y",InfN LeftA 1 "*"] (LeftA,"-") (Last [])) -- >>> splitInfixNode (0, Just LeftA) [TermN "x", InfN LeftA 0 "+", InfN LeftA 1 "*", TermN "z", InfN LeftA 0 "-"] -- RBranch [TermN "x"] (LeftA,"+") (RBranch [InfN LeftA 1 "*",TermN "z"] (LeftA,"-") (Last [])) -- >>> splitInfixNode (1, Just LeftA) [PreN 1 "~", InfN LeftA 1 "*", TermN "z", InfN LeftA 1 "%"] -- RBranch [PreN 1 "~"] (LeftA,"*") (RBranch [TermN "z"] (LeftA,"%") (Last [])) -- >>> splitInfixNode (1, Just LeftA) [TermN "x", InfN LeftA 0 "+", TermN "y"] -- Last [TermN "x",InfN LeftA 0 "+",TermN "y"] -- >>> splitInfixNode (0, Just LeftA) [InfN LeftA 0 "+", TermN "y"] -- RBranch [] (LeftA,"+") (Last [TermN "y"])
Ming-Tang/FP15
src/FP15/Compiler/Syntax/Precedence.hs
mit
10,309
0
19
2,368
3,176
1,708
1,468
-1
-1
-- | -- Module : HGE2D.Engine -- Copyright : (c) 2016 Martin Buck -- License : see LICENSE -- -- Containing functions for the engine, mostly to interact with GLUT and OpenGL module HGE2D.Engine where import HGE2D.Datas import HGE2D.Classes import HGE2D.Time import HGE2D.Render () import Control.Concurrent (newMVar, readMVar, takeMVar, putMVar, swapMVar, MVar) import Graphics.UI.GLUT -------------------------------------------------------------------------------- -- | Main function to run the engine runEngine :: EngineState a -> a -> IO () runEngine es impl = do secs <- getSeconds let ms = toMilliSeconds secs (w, h) = getSize es impl state <- newMVar $ setTime es ms impl (_progName, _args) <- getArgsAndInitialize initialDisplayMode $= [DoubleBuffered] initialWindowSize $= Size (round w) (round h) _window <- createWindow $ getTitle es impl keyboardMouseCallback $= Just (keyboardMouse es state) motionCallback $= Just (mouseGrab es state) passiveMotionCallback $= Just (mouseHover es state) blend $= Enabled blendFunc $= (SrcAlpha, OneMinusSrcAlpha) displayCallback $= display es state reshapeCallback $= Just (reshape es state) idleCallback $= Just (idle es state) mainLoop -------------------------------------------------------------------------------- -- | Function to render the current state of the engine display :: EngineState a -> MVar a -> IO () display es mvarGs = do clear [ColorBuffer] gs <- readMVar mvarGs glRender $ toGlInstr es gs swapBuffers -------------------------------------------------------------------------------- -- | Function to react to changes of the window size reshape :: EngineState a -> MVar a -> Size -> IO () reshape es mvarGs s@(Size width height) = do gs <- takeMVar mvarGs let newState = resize es (realToFrac width, realToFrac height) gs putMVar mvarGs newState viewport $= (Position 0 0, s) postRedisplay Nothing -------------------------------------------------------------------------------- ---TODO here named grab, but engine method named drag, name both the same -- | Mouse grab interactions with the engine mouseGrab :: EngineState a -> MVar a -> Position -> IO () mouseGrab es mvarGs (Position x y) = do gs <- takeMVar mvarGs ---TODO rename let w = fst $ getSize es gs h = snd $ getSize es gs correctedX = realToFrac x * (fst $ getSize es gs) / w correctedY = realToFrac y * (snd $ getSize es gs) / h newState = drag es correctedX correctedY gs putMVar mvarGs newState return () -- | Mouse hover interactions with the engine mouseHover :: EngineState a -> MVar a -> Position -> IO () mouseHover es mvarGs (Position x y) = do gs <- readMVar mvarGs ---TODO rename let w = fst $ getSize es gs h = snd $ getSize es gs correctedX = realToFrac x * (fst $ getSize es gs) / w correctedY = realToFrac y * (snd $ getSize es gs) / h newState = hover es correctedX correctedY gs swapMVar mvarGs newState return () -- | Keyboard and mouse interactions with the engine keyboardMouse :: EngineState a -> MVar a -> Key -> KeyState -> Modifiers -> Position -> IO () keyboardMouse es mvarGs (MouseButton LeftButton) Down _modifiers (Position x y) = mouseDown es mvarGs x y keyboardMouse es mvarGs (MouseButton LeftButton) Up _modifiers (Position x y) = mouseUp es mvarGs x y keyboardMouse es mvarGs (Char c) Down _modifiers (Position x y) = keyDown es mvarGs x y c keyboardMouse es mvarGs (Char c) Up _modifiers (Position x y) = keyUp es mvarGs x y c keyboardMouse _ _ _ _ _ _ = return () -------------------------------------------------------------------------------- -- | MouseDown interaction with the engine mouseDown :: EngineState a -> MVar a -> GLint -> GLint -> IO () mouseDown es mvarGs x y = do gs <- readMVar mvarGs ---TODO rename ---TODO define method for corrections since used here and in hover let w = fst $ getSize es gs h = snd $ getSize es gs correctedX = realToFrac x * (fst $ getSize es gs) / w correctedY = realToFrac y * (snd $ getSize es gs) / h newState = click es correctedX correctedY gs swapMVar mvarGs newState return () -- | MouseUp interaction with the engine mouseUp :: EngineState a -> MVar a -> GLint -> GLint -> IO () mouseUp es mvarGs x y = do gs <- readMVar mvarGs ---TODO rename ---TODO define method for corrections since used here and in hover let w = fst $ getSize es gs h = snd $ getSize es gs correctedX = realToFrac x * (fst $ getSize es gs) / w correctedY = realToFrac y * (snd $ getSize es gs) / h newState = mUp es correctedX correctedY gs swapMVar mvarGs newState return () -------------------------------------------------------------------------------- -- | KeyPress interaction with the engine keyDown :: EngineState a -> MVar a -> GLint -> GLint -> Char -> IO () keyDown es mvarGs x y c = do gs <- readMVar mvarGs ---TODO rename ---TODO define method for corrections since used here and in hover let w = fst $ getSize es gs h = snd $ getSize es gs correctedX = realToFrac x * (fst $ getSize es gs) / w correctedY = realToFrac y * (snd $ getSize es gs) / h newState = kDown es correctedX correctedY c gs swapMVar mvarGs newState return () -- | KeyRelease interaction with the engine keyUp :: EngineState a -> MVar a -> GLint -> GLint -> Char -> IO () keyUp es mvarGs x y c = do gs <- readMVar mvarGs ---TODO rename ---TODO define method for corrections since used here and in hover let w = fst $ getSize es gs h = snd $ getSize es gs correctedX = realToFrac x * (fst $ getSize es gs) / w correctedY = realToFrac y * (snd $ getSize es gs) / h newState = kUp es correctedX correctedY c gs swapMVar mvarGs newState return () -------------------------------------------------------------------------------- -- | Idle function of the engine. Used to e.g. apply changes in time to the game state idle :: EngineState a -> MVar a -> IdleCallback idle es mvarGs = do gs <- readMVar mvarGs secs <- getSeconds let ms = toMilliSeconds secs deltaMs = ms - getTime es gs newState = moveTime es deltaMs (setTime es ms gs) ---TODO currently bot setting the time AND transforming swapMVar mvarGs newState postRedisplay Nothing
I3ck/HGE2D
src/HGE2D/Engine.hs
mit
6,745
0
14
1,757
1,961
949
1,012
114
1
{-# htermination addToFM_C :: Ord a => (b -> b -> b) -> FiniteMap a b -> a -> b -> FiniteMap a b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_addToFM_C_1.hs
mit
118
0
3
27
5
3
2
1
0
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.MediaDevices (enumerateDevices, enumerateDevices_, getSupportedConstraints, getSupportedConstraints_, getUserMedia, getUserMedia_, devicechange, MediaDevices(..), gTypeMediaDevices) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices.enumerateDevices Mozilla MediaDevices.enumerateDevices documentation> enumerateDevices :: (MonadDOM m) => MediaDevices -> m [MediaDeviceInfo] enumerateDevices self = liftDOM (((self ^. jsf "enumerateDevices" ()) >>= readPromise) >>= fromJSArrayUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices.enumerateDevices Mozilla MediaDevices.enumerateDevices documentation> enumerateDevices_ :: (MonadDOM m) => MediaDevices -> m () enumerateDevices_ self = liftDOM (void (self ^. jsf "enumerateDevices" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices.getSupportedConstraints Mozilla MediaDevices.getSupportedConstraints documentation> getSupportedConstraints :: (MonadDOM m) => MediaDevices -> m MediaTrackSupportedConstraints getSupportedConstraints self = liftDOM ((self ^. jsf "getSupportedConstraints" ()) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices.getSupportedConstraints Mozilla MediaDevices.getSupportedConstraints documentation> getSupportedConstraints_ :: (MonadDOM m) => MediaDevices -> m () getSupportedConstraints_ self = liftDOM (void (self ^. jsf "getSupportedConstraints" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices.getUserMedia Mozilla MediaDevices.getUserMedia documentation> getUserMedia :: (MonadDOM m) => MediaDevices -> Maybe MediaStreamConstraints -> m MediaStream getUserMedia self constraints = liftDOM (((self ^. jsf "getUserMedia" [toJSVal constraints]) >>= readPromise) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices.getUserMedia Mozilla MediaDevices.getUserMedia documentation> getUserMedia_ :: (MonadDOM m) => MediaDevices -> Maybe MediaStreamConstraints -> m () getUserMedia_ self constraints = liftDOM (void (self ^. jsf "getUserMedia" [toJSVal constraints])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices.ondevicechange Mozilla MediaDevices.ondevicechange documentation> devicechange :: EventName MediaDevices ondevicechange devicechange = unsafeEventName (toJSString "devicechange")
ghcjs/jsaddle-dom
src/JSDOM/Generated/MediaDevices.hs
mit
3,499
0
14
492
708
413
295
52
1
module TaGenerator.AstParser where import TaGenerator.DocumentParser import Control.Applicative import qualified Data.Text as T import qualified Data.Map as M class FromAst a where fromAst :: Ast -> Maybe a -- Basic instances instance FromAst Bool where fromAst = boolConst instance FromAst T.Text where fromAst = stringLiteral instance FromAst a => FromAst [a] where fromAst = listFromAst -- Parsers boolConst :: Ast -> Maybe Bool boolConst (Variable v) = strToBool v boolConst _ = Nothing strToBool :: String -> Maybe Bool strToBool "yes" = Just True strToBool "no" = Just False stringLiteral :: Ast -> Maybe T.Text stringLiteral (StringLiteral s) = Just $ T.pack s stringLiteral _ = Nothing variable :: Ast -> Maybe String variable (Variable s) = Just s variable _ = Nothing listFromAst :: FromAst a => Ast -> Maybe [a] listFromAst (List l) = mapM fromAst l mapFromValueMap :: FromAst v => ValueMap -> Maybe (M.Map String v) mapFromValueMap vm = M.fromList <$> mapM pairFromAst (M.toList vm) where pairFromAst (k,v) = (,) <$> Just k <*> fromAst v valueMap :: FromAst v => ValueMap -> M.Map String v valueMap = M.mapMaybe fromAst key :: FromAst a => String -> ValueMap -> Maybe a key k vm = M.lookup k vm >>= fromAst
jkpl/tagenerator
src/TaGenerator/AstParser.hs
mit
1,254
0
10
238
466
236
230
34
1
-- | Specification for the exercises of Chapter 3. module Chapter03Spec where import Chapter03 (double, pair, palindrome, second, swap, t0, t1, twice, xs0, xs1, xs2, xs3) import Test.Hspec (Spec, describe, it, shouldBe) import Test.QuickCheck (Property, property, (.&.), (===), (==>)) spec :: Spec spec = do describe "Exercise 1" $ do it "implements xs0" $ do xs0 `shouldBe` [0, 1] it "implements xs1" $ do xs1 `shouldBe` ['a','b','c'] it "implements xs2" $ do xs2 `shouldBe` [(False,'0'),(True,'1')] it "implements xs3" $ property $ \xs -> (not (null xs) ==> (xs3 !! 0) xs === tail (xs :: [Int])) .&. (not (null xs) ==> (xs3 !! 1) xs === init xs) .&. (xs3 !! 2) xs === reverse xs it "implements t0" $ do t0 `shouldBe` ('a','b','c') it "implements t1" $ do t1 `shouldBe` ([False,True],['0','1']) describe "Exercise 2" $ do it "implements function second" $ property $ \xs -> 1 < length xs ==> second xs === (head (tail xs) :: [String]) it "implements function swap" $ property $ \x y -> swap (x, y) === ((y, x) :: ([Bool], String)) it "implements function pair" $ property $ \x y -> pair x y === ((x, y) :: (Char, Int)) it "implements function double" $ property $ \x -> double x === 2.0 * (x :: Double) it "implements function palindrome" $ property $ \xs -> palindrome xs === (reverse xs == (xs :: [Int])) it "implements function twice" $ do twice (+3) 8 `shouldBe` (8 + 3 + 3) twice (++" bar") "foo" `shouldBe` "foo bar bar"
EindhovenHaskellMeetup/meetup
courses/programming-in-haskell/pih-exercises/test/Chapter03Spec.hs
mit
1,665
0
20
492
693
376
317
36
1
module SetGame.PlayGame where import Control.Applicative import Data.List import Data.Maybe import Data.Monoid import System.Random import System.Random.Shuffle import SetGame.Cards import SetGame.GameState drawCards :: Int -> GameState -> GameState drawCards n (GameState board deck sets) = GameState updatedBoard updatedDeck sets where drawn = take n deck updatedBoard = board ++ drawn updatedDeck = deck \\ drawn playRound :: GameState -> GameState playRound (GameState board deck sets) = (drawCards 3 . removeSet . findSet) board where removeSet Nothing = GameState board deck sets removeSet (Just (c1, c2, c3)) = GameState updatedBoard deck updatedSets where updatedBoard = board \\ [c1, c2, c3] updatedSets = sets ++ [(c1, c2, c3)] playRounds :: GameState -> GameState playRounds gameState | shouldQuit gameState = gameState | otherwise = (playRounds . playRound) gameState where shouldQuit (GameState board deck _) = hasNoSets board && deckIsEmpty deck hasNoSets board = isNothing $ findSet board deckIsEmpty deck = deck == mempty shuffleCards :: Deck -> StdGen -> Deck shuffleCards deck generator = shuffle' deck (length deck) generator getShuffledDeck :: StdGen -> Deck getShuffledDeck generator = shuffleCards allCards generator findSet :: Board -> Maybe CardSet findSet board | length board < 3 = Nothing | otherwise = maybeFirst . filter isSet . filter (\(c1, c2, c3) -> allUnique [c1, c2, c3]) $ allCombinations where allCombinations = [(,,)] <*> board <*> board <*> board maybeFirst [] = Nothing maybeFirst (x:_) = Just x isSet :: (Card, Card, Card) -> Bool isSet cards = all (attrPasses cards) cardAccessors where attrPasses (c1, c2, c3) accessor = (\attrs -> allUnique attrs || allSame attrs) . fmap accessor $ [c1, c2, c3] allUnique :: (Eq a) => [a] -> Bool allUnique xs = (== expectedLength) . length . nub $ xs where expectedLength = length xs allSame :: (Eq a) => [a] -> Bool allSame = (== 1) . length . nub
cmwilhelm/setGame
library/SetGame/PlayGame.hs
mit
2,414
0
12
789
741
391
350
54
2
module Main where import Lambda import Parser import Type main = do putStrLn "-----------------------------------------------------" putStrLn "Type Infer to Lambda Expressions!--------------------" putStrLn "Insert the name of the txt with an Lambda expression!" putStrLn "-----------------------------------------------------\n" fileName <- getLine body <- readFile fileName putStrLn $ ("Lambda Expression:\n" ++ body) let parsed = convert body putStrLn $ ("Parsed Expression:\n" ++ show parsed ++ "\n" ) let result = infer parsed putStrLn $ ("Typed Expression:\n" ++ show result) writeFile "out" ((show body) ++ "\n\n\n" ++ (show parsed) ++ "\n\n\n" ++ (show result) ++ "\n")
LeonardoRigon/TypeInfer-LambdaExpressions-in-Haskell
Main.hs
mit
800
0
15
211
184
86
98
17
1
{-# LANGUAGE OverloadedStrings #-} module UtilProperties ( testUtils ) where import Test.Framework.Providers.QuickCheck2 import Test.Framework import Test.QuickCheck import Util import qualified Crypto.Saltine.Internal.Util as U -- | Testing the comparison of keys keyEquality :: ByteString32 -> Property keyEquality k@(ByteString32 bs1) = k === k .&. U.compare bs1 bs1 keyInequality :: ByteString32 -> ByteString32 -> Property keyInequality k1@(ByteString32 bs1) k2@(ByteString32 bs2) = k1 /= k2 ==> not $ U.compare bs1 bs2 testUtils :: Test testUtils = buildTest $ do return $ testGroup "...Utils" [ testProperty "ByteString equality" keyEquality, testProperty "ByteString inequality" keyInequality ]
tel/saltine
tests/UtilProperties.hs
mit
740
0
11
127
184
102
82
18
1
import XMonad import Data.Monoid import System.IO import System.Exit import XMonad.Prompt.RunOrRaise import XMonad.Prompt.Window --import XMonad.Prompt.XMonad import XMonad.Hooks.DynamicLog import XMonad.Hooks.SetWMName import XMonad.Hooks.ManageHelpers import XMonad.Hooks.ManageDocks import XMonad.Hooks.UrgencyHook import XMonad.Hooks.FadeInactive import XMonad.Hooks.EwmhDesktops import XMonad.Layout import XMonad.Layout.NoBorders import XMonad.Layout.ResizableTile import XMonad.Layout.SimplestFloat import XMonad.Util.Run import XMonad.Util.EZConfig import XMonad.Util.XSelection import XMonad.Util.WorkspaceCompare import XMonad.Util.WindowProperties import XMonad.Util.NamedWindows (getName) import Data.List(isPrefixOf) import Data.Ratio ((%)) --import qualified System.IO.UTF8 as U import qualified XMonad.Actions.FlexibleResize as Flex import qualified XMonad.StackSet as W import qualified Data.Map as M -- myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $ [ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf) , ((modm, xK_r ), spawn "/home/zhou/bin/dmenu_wrap_yeganesh") , ((modm .|. shiftMask, xK_c ), kill) , ((controlMask, xK_Print ), spawn "sleep 0.2; scrot -s") , ((0 , xK_Print ), spawn "scrot") -- , ((0 , 0x1008ff11), spawn "amixer set Master 5%- ") -- , ((0 , 0x1008ff13), spawn "amixer set Master 5%+ ") -- , ((0 , 0x1008ff11), spawn "ossmix vmix0-outvol -- -1") -- , ((0 , 0x1008ff13), spawn "ossmix vmix0-outvol -- +1") , ((0 , 0x1008ff2f), spawn "gksudo s2ram") , ((0 , 0x1008ff93), spawn "gksudo pm-hibernate") , ((modm, xK_space ), sendMessage NextLayout) , ((modm, xK_n ), refresh) , ((modm, xK_Tab ), windows W.focusDown) , ((modm, xK_j ), windows W.focusDown) , ((modm, xK_k ), windows W.focusUp ) , ((modm, xK_m ), windows W.focusMaster ) , ((modm, xK_Return), windows W.swapMaster) , ((modm .|. shiftMask, xK_j ), windows W.swapDown ) , ((modm .|. shiftMask, xK_k ), windows W.swapUp ) , ((modm, xK_h ), sendMessage Shrink) , ((modm, xK_l ), sendMessage Expand) , ((modm, xK_t ), withFocused $ windows . W.sink) , ((modm , xK_comma ), sendMessage (IncMasterN 1)) , ((modm , xK_period), sendMessage (IncMasterN (-1))) , ((modm .|. shiftMask, xK_q ), io (exitWith ExitSuccess)) , ((modm .|. shiftMask, xK_r ), spawn "killall conky dzen2 tint2 parcellite nm-applet fcitx volumeicon; xmonad --recompile; xmonad --restart") ] ++ [((m .|. modm, k), windows $ f i) | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_7] , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] ++ [((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f)) | (key, sc) <- zip [xK_w, xK_e, xK_p] [0..] , (f, m) <- [(W.view, 0), (W.shift, shiftMask)]] myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $ [ ((modm, button1), (\w -> focus w >> mouseMoveWindow w >> windows W.shiftMaster)) , ((modm, button2), (\w -> focus w >> windows W.shiftMaster)) , ((modm, button3), (\w -> focus w >> mouseResizeWindow w >> windows W.shiftMaster)) ] myManageHook = composeAll . concat $ [ [isFullscreen --> doFullFloat, isDialog --> doCenterFloat] , [className =? c --> doFloat | c <- myFloats] , [title =? t --> doFloat | t <- myTitleFloats] , [resource =? r --> doIgnore | r <- myIgnores] -- , [className =? s --> doTile | s <- myTiles] ] where myFloats = ["Gpick", "Chromium", "Gimp", "Volumeicon", "MPlayer", "Smplayer2", "Gnome-mplayer", "Tintwizard", "Vlc", "Lxrandr", "Arandr", "Audacious", "Deadbeef", "VirtualBox", "Firefox", "Firefox-bin", "AliWangWang", "Q4wine", "Wine", "Linux-fetion", "Gcalctool", "Gmlive", "Skype", "Ossxmix", "Pidgin", "Emesene", "Openfetion", "Vncviewer", "Cairo-dock", "RipperX", "Goldendict", "PBurn" ] myTitleFloats = ["Downloads", "Preferences", "Save As...", "QEMU", "emacs", "Add-ons", "Firefox", "Chromium", "Exe", "Options", "首选项", "AliWangWang", "阿里旺旺", "Wicd Network Manager"] myIgnores = ["trayer", "dzen", "stalonetray", "systray", "cairo-dock", "Wine"] -- myTiles = ["tilda", "pcmanfm", "thunar", "dolphin", "lxterminal"] myIconDir = "/home/zhou/.xmonad/dzen/layouts/" myBorderWidth = 0 myNormalBorderColor = "#729fcf" myFocusedBorderColor = "#7292cf" myFont = "xft:Droid Serif:pixelsize=9" -- dzen settings: dzFont = "Terminus-8" mySmallFont = "OpenLogos-8" -- workspace colors: dzBgColor = "#FDF6E3" dzFgColor = "#657B83" myCurrentBGColor = "#8FB3D9" myCurrentFGColor = "#002B36" myCurrentCornerColor = "#002B36" myVisibleBGColor = "#28618f" myVisibleFGColor = "white" myVisibleCornerColor = "" myHiddenBGColor = dzBgColor myHiddenFGColor = dzFgColor myHiddenCornerColor = "#DC322F" myHiddenNoWindowsBGColor = dzBgColor myHiddenNoWindowsFGColor = dzFgColor myHiddenNoWindowsCornerColor = "" myUrgentBGColor = "" myUrgentFGColor = "#DC322F" myUrgentCornerColor = "#002B36" myStatusBar :: String myStatusBar = "dzen2 -fn '" ++ dzFont ++ "' -fg '" ++ dzFgColor ++ "' -bg '" ++ dzBgColor ++ "' -e 'button3=' -h '18' -ta l" myConkyBar :: String --myConkyBar = "conky | dzen2 -fg '" ++ dzFgColor ++ "' -bg '" ++ dzBgColor ++ "' -x '700' -h '20' -fn '" ++ dzFont ++ "' -sa c -ta r" myConkyBar = "sleep 5; conky | dzen2 -e '' -h '18' -x '920' -ta r -fg '" ++ dzFgColor ++ "' -bg '" ++dzBgColor ++ "'" --mySysTray :: String --mySysTray = "sleep 3; trayer --expand true --alpha 0 --edge top --align right --SetDockType true --transparent flase --SetPartialStrut true --widthtype request --tint 0xffffff --height 18 --margin 65" myLogHook h = dynamicLogWithPP $ defaultPP { ppCurrent = \wsId -> rangeId wsId myCurrentCornerColor myCurrentBGColor myCurrentFGColor , ppHidden = \wsId -> rangeId wsId myHiddenCornerColor myHiddenBGColor myHiddenFGColor , ppVisible = \wsId -> rangeId wsId myVisibleCornerColor myVisibleBGColor myVisibleFGColor , ppHiddenNoWindows = \wsId -> rangeId wsId myHiddenNoWindowsCornerColor myHiddenNoWindowsBGColor myHiddenNoWindowsFGColor , ppUrgent = \wsId -> rangeId wsId myUrgentCornerColor myUrgentBGColor myUrgentFGColor , ppWsSep = "" , ppSep = " " , ppLayout = dzenColor "#859900" "" . (\ x -> case x of "Tall" -> wrap "^ca(1,xdotool key super+space)" "^ca()" ("^i(" ++ myIconDir ++ "tile.xbm)") "Mirror Tall" -> wrap "^ca(1,xdotool key super+space)" "^ca()" ("^i(" ++ myIconDir ++ "tilebottom.xbm)") -- "SimplestFloat" -> wrap "^ca(1,xdotool key super+space)" "^ca()" ("^i(" ++ myIconDir ++ "floating.xbm)") -- "magnifier" -> "^i(/home/zhou/.xmonad/dzen/layouts/magnifier.xbm)" "Full" -> wrap "^ca(1,xdotool key super+space)" "^ca()" ("^i(" ++ myIconDir ++ "fullscreen.xbm)") ) , ppTitle = ("^fn(SimSun-9)" ++) . dzenColor dzFgColor dzBgColor . dzenEscape , ppOutput = hPutStrLn h } where rangeId wsName cornerColor bgColor fgColor = let base=drop 2 wsName; corner=take 1 wsName; getid1=take 2 wsName; getid=drop 1 getid1 in "^ca(1,xdotool key super+" ++ getid ++ ")^fg(" ++ fgColor ++ ")^bg(" ++ bgColor ++ ") " ++ base ++ "^p(;-2)^fn(" ++ mySmallFont ++ ")^fg(" ++ cornerColor ++ ")" ++ corner ++ " ^fn()^p()^fg()^bg()^ca()" -- myWorkspaces = ["1:Term", "2:Surf", "3:Edit", "4:File", "5:View", "6:Pics"] myWorkspaces = ["Q1Surf", "I2Wine", "U3Edit", "T4File", "J5View", "u6Pics"] -- -- Layouts genericLayout = tiled ||| Mirror tiled ||| Full where -- default tiling algorithm partitions the screen into two panes tiled = Tall nmaster delta ratio -- The default number of windows in the master pane nmaster = 1 -- Default proportion of screen occupied by master pane ratio = 1/2 -- Percent of screen to increment by when resizing panes delta = 3/100 myLayout = genericLayout main :: IO () main = do spawn "/usr/libexec/polkit-gnome-authentication-agent-1" spawn "parcellite" -- spawn "wicd-client" spawn "nm-applet" spawn "volumeicon" spawn "tint2" spawn "urxvt" spawn "compton --config ~/.compton.conf -b" -- spawn "gcdemu" -- spawn "yong" spawn "sleep 3; fcitx " spawn "sleep 4; xmodmap ~/.Xmodmap" dzen <- spawnPipe myStatusBar spawn myConkyBar xmonad $ ewmh defaultConfig { modMask = mod4Mask , focusFollowsMouse = True , borderWidth = myBorderWidth , terminal = "urxvt" , manageHook = manageDocks <+> manageHook defaultConfig <+> myManageHook , logHook = myLogHook dzen >> fadeInactiveLogHook 0xdddddddd -- , logHook = ewmhDesktopsLogHook >> (dynamicLogWithPP $ myLogHook dzen) -- , layoutHook = ewmhDesktopsEventHook $ avoidStruts $ myLayout , layoutHook = avoidStruts $ myLayout , workspaces = myWorkspaces -- , workspaces = ["^ca(1,xdotool key super+1)^fn(OpenLogos-11)Q^ca()","^ca(1,xdotool key super+2)^fn(OpenLogos-12)I^ca()","^ca(1,xdotool key super+3)^fn(OpenLogos-11)U^ca()","^ca(1,xdotool key super+4)^fn(OpenLogos-11)T^ca()","^ca(1,xdotool key super+5)^fn(OpenLogos-11)J^ca()","^ca(1,xdotool key super+6)^fn(OpenLogos-11)A^ca()","^ca(1,xdotool key super+7)^fn(OpenLogos-13)R^ca()^fn(MingLiu-8)"] -- key bindings , keys = myKeys , mouseBindings = myMouseBindings -- , handleEventHook = handleEventHook conf `mappend` fullscreenEventHook }
transtone/transconfig
.xmonad/xmonad.hs
mit
10,615
3
22
2,905
2,178
1,265
913
149
3
{-# LANGUAGE Trustworthy #-} module Scheduler.Main ( MainScheduler , getMainScheduler , runMainScheduler ) where import Control.Concurrent import Control.Concurrent.STM import Data.IORef import Scheduler import Scheduler.Internal import System.IO.Unsafe -- | A scheduler which runs enqueued actions on the main thread. newtype MainScheduler = MainScheduler (TQueue (ScheduledAction MainScheduler)) instance Scheduler MainScheduler where schedule (MainScheduler q) action = do (sa, d) <- newScheduledAction action atomically $ writeTQueue q sa return d schedulerMain s@(MainScheduler q) = do sa <- atomically $ readTQueue q executeScheduledAction s sa -- ohai global variable mainSchedulerRef :: IORef MainScheduler {-# NOINLINE mainSchedulerRef #-} mainSchedulerRef = unsafePerformIO $ do q <- atomically newTQueue newIORef $ MainScheduler q -- | Returns a scheduler representing the main thread. -- -- Note that 'runMainScheduler' must be called for enqueued actions to actually execute. getMainScheduler :: IO MainScheduler getMainScheduler = readIORef mainSchedulerRef -- | Runs the main scheduler indefinitely using the current thread. -- The current thread will be bound if possible. runMainScheduler :: IO () runMainScheduler = let run = getMainScheduler >>= schedulerMain in if rtsSupportsBoundThreads then runInBoundThread run else run
jspahrsummers/RxHaskell
Scheduler/Main.hs
mit
1,514
0
10
347
267
141
126
33
2
module Main where import Language.Egison.Core import Language.Egison.Types import Control.Monad.Error evalTopExprs :: Env -> [TopExpr] -> IO () evalTopExprs _ [] = return () evalTopExprs env (topExpr:rest) = do str <- runIOThrowsREPL $ evalTopExpr env topExpr case topExpr of Test _ -> do putStrLn str evalTopExprs env rest _ -> evalTopExprs env rest main :: IO () main = do env <- primitiveBindings evalTopExprs env topExprs
aretoky/egison2
etc/template-for-test.hs
mit
462
0
12
101
164
81
83
16
2
module Athame where import Athame.Types import Athame.Show import Athame.Read import Athame.Canon
rmartinho/athame
src/Athame.hs
cc0-1.0
99
0
4
12
24
15
9
5
0
module Handler.Echo where import Import getEchoR :: Text -> Handler Html getEchoR txt = defaultLayout $(widgetFile "echo")
ardumont/yesod-lab
Handler/Echo.hs
gpl-2.0
125
0
8
19
39
20
19
4
1
module Cryptography.ComputationalProblems.Reductions.Terms where import Notes makeDefs [ "reduction" , "reduction function" , "performance translation function" , "reducible" ] tReduction :: Note -> Note tReduction t = m t <> "-" <> reduction tReduction' :: Note -> Note tReduction' t = m t <> "-" <> reduction' makeThms [ "composition of reductions" ]
NorfairKing/the-notes
src/Cryptography/ComputationalProblems/Reductions/Terms.hs
gpl-2.0
396
0
7
95
94
50
44
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} -- | -- Module: Main -- Copyright: (C) 2015-2018, Virtual Forge GmbH -- License: GPL2 -- Maintainer: Hans-Christian Esperer <[email protected]> -- Stability: experimental -- Portability: portable -- | -- (De-)compress SAPCAR files module Main where import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Data.Binary.Get import Data.ByteString (ByteString) import Data.Conduit import Foreign.C.Types (CTime(..)) import Path import System.Directory import System.Environment import System.FilePath import System.IO import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import qualified Data.Conduit.List as DCL import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Text.Encoding.Error as TEE import Options import Codec.Archive.SAPCAR import Codec.Archive.SAPCAR.Pat #ifndef mingw32_HOST_OS import System.Posix.Files as SPF #endif import System.Posix.Types (CMode(..), EpochTime(..)) -- |Main entry point main :: IO () main = run it it :: Options -> IO () it options = withSapCarFile (oFilename options) $ do entries <- getEntries let files = ((== CarFile) . cfFileType) `filter` entries let dirs = ((== CarDirectory) . cfFileType) `filter` entries unless (oQuiet options) . liftIO . putStrLn $ show (length entries) ++ " entrie(s) in the archive." when (oListEntries options) $ liftIO $ do putStrLn "\nAll entries:" forM_ entries print putStrLn "" liftIO $ case oExtractDir options of Just extractDir -> do when (oVerbose options) $ putStrLn $ "Setting cwd to " ++ show extractDir setCurrentDirectory extractDir Nothing -> return () when (oDecompress options) $ do unless (oExtractPatFiles options) $ do forM_ dirs $ \dir -> do dirname <- parseRelDir $ T.unpack $ carEntryFilename dir when (oVerbose options) $ liftIO $ putStrLn $ "Creating " ++ show dirname liftIO $ do createDirectoryIfMissing True $ fromRelDir dirname #ifndef mingw32_HOST_OS SPF.setFileMode (fromRelDir dirname) $ CMode $ fromIntegral $ cfPermissions dir let amTime = CTime $ fromIntegral $ cfTimestamp dir SPF.setFileTimes (fromRelDir dirname) amTime amTime #endif forM_ files $ \file -> do filename <- parseRelFile $ T.unpack $ carEntryFilename file unless (oExtractPatFiles options) $ void $ liftIO $ cdim $ fromRelFile filename patWritten <- if (oExtractPatFiles options) then do patInfo <- loadPatInfo file case patInfo of Just patInfo' -> do let transportName = T.unpack . T.strip . TE.decodeUtf8With TEE.lenientDecode . phTransportName $ patInfo' patFilename = "R" ++ drop 4 transportName patExt = take 3 transportName transportFilename = patFilename ++ "." ++ patExt liftIO $ when (oVerbose options) $ do putStrLn "Transport file" putStrLn "===============================================================================" putStrLn $ "Transport file : " ++ show (phTransportName patInfo') putStrLn $ "Title : " ++ show (phTitle patInfo') putStrLn $ "Extracting to : " ++ show transportFilename putStrLn "\n" parsedTransportFilename <- parseRelFile transportFilename unpackPat (fromRelFile parsedTransportFilename) file Nothing -> return True else return False if patWritten then return () -- do nothing here else do when (oVerbose options) $ liftIO $ putStrLn $ "x " ++ fromRelFile filename writeToFile file filename #ifndef mingw32_HOST_OS liftIO $ SPF.setFileMode (fromRelFile filename) $ CMode $ fromIntegral $ cfPermissions file let amTime = CTime $ fromIntegral $ cfTimestamp file liftIO $ SPF.setFileTimes (fromRelFile filename) amTime amTime #endif -- | Write a transport contained inside a PAT file -- return if any bytes were written unpackPat :: FilePath -> CarEntry s -> SapCar s IO Bool unpackPat path file = bracket open close w where open = liftIO $ openBinaryFile path WriteMode close = liftIO . hClose w h = sourceEntry file (patToTransport =$= writePat h) loadPatInfo :: CarEntry s -> SapCar s IO (Maybe PatHeader) loadPatInfo file = sourceEntry file (getPatHeader =$= DCL.head) -- | Provide a conduit sink, write everything that arrives there to -- the given handle. Return True if at least one chunk was written. writePat :: Handle -> Sink S.ByteString IO Bool writePat h = let loop c = do chunk <- await case chunk of Just chunk' -> liftIO (S.hPut h chunk') >> loop True Nothing -> return c in loop False cdim :: FilePath -> IO () cdim fp = do let fpt = T.pack fp parts = T.split (== pathSeparator) fpt when (length parts > 1) $ do let path = T.unpack $ T.intercalate (T.pack [pathSeparator]) $ take (length parts - 1) parts p <- parseRelDir path createDirectoryIfMissing True $ fromRelDir p
VirtualForgeGmbH/hascar
app/Main.hs
gpl-2.0
5,767
0
31
1,803
1,463
729
734
112
5
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable #-} -- | Security protocol represented as a set of roles which are sequences of -- send and receive steps. module Scyther.Protocol ( -- * Types Id(..) , VarId(..) , Pattern(..) , Label(..) , RoleStep(..) , Role(..) , Protocol(..) , RoleStepOrder -- * Queries -- ** Generic variables , variable -- ** Patterns , patFMV , patFAV , subpatterns , patternparts , splitpatterns -- ** Role Steps , stepPat , stepLabel , stepFMV , stepFAV , stepUsedMV , stepBoundMV -- ** Roles , roleFMV , roleFAV , lookupRoleStep , wfRole , roleOrd -- ** Protocols , lookupRole , stateLocale , restrictedStateLocale , labelOrd , protoOrd -- ** Wellformedness , ProtoIllformedness , wfProto , sptProtoIllformedness -- * Construction , patMapFMV -- * Output , isaRoleStep , sptId , sptLabel , sptPattern , sptRoleStep , sptRole , sptProtocol ) where import Safe import Data.List import qualified Data.Set as S import Data.Data import Control.Monad import Extension.Prelude import Text.Isar -- Datatypes ------------ -- | An identifier. newtype Id = Id { getId :: String } deriving( Eq, Ord, Data, Typeable {-! NFData !-} ) instance Show Id where show (Id i) = i -- | Either an agent or message variable. Currently only used for 'Match' steps. data VarId = SAVar Id -- ^ An agent variable. | SMVar Id -- ^ A message variable. deriving( Eq, Ord, Show, Data, Typeable {-! NFData !-} ) -- | A message pattern. data Pattern = PConst Id -- ^ A global constant. | PFresh Id -- ^ A message to be freshly generated. | PAVar Id -- ^ An agent variable. | PMVar Id -- ^ A message variable. | PHash Pattern -- ^ Hashing | PTup Pattern Pattern -- ^ Pairing | PEnc Pattern Pattern -- ^ Symmetric or asymmetric encryption (depent on the key). | PSign Pattern Pattern -- ^ A signature to be verified with the given key. | PSymK Pattern Pattern -- ^ A long-term unidirectional symmetric key. | PShrK Pattern Pattern -- ^ A long-term bi-directional symmetric key. | PAsymPK Pattern -- ^ A long-term public key. | PAsymSK Pattern -- ^ A long-term private key | PAny -- ^ A wildcard (anonymous logical variable). deriving( Eq, Ord, Show, Data, Typeable {-! NFData !-} ) -- | A label of a role step. newtype Label = Label { getLabel :: String } deriving( Eq, Ord, Show, Data, Typeable {-! NFData !-} ) -- | A role step. data RoleStep = Send Label Pattern -- ^ A send step. | Recv Label Pattern -- ^ A receive step. | Match Label Bool VarId Pattern -- ^ A match or not-match step. deriving( Eq, Ord, Show, Data, Typeable {-! NFData !-} ) -- | A role of a protocol. Its name has no operational meaning, but is carried -- along to allow for human readable printing. data Role = Role { roleName :: String , roleSteps :: [RoleStep] } deriving( Eq, Ord, Show, Data, Typeable {-! NFData !-} ) -- | A protocol. As for roles, its name has no operational meaning, but is -- carried along to allow for human readable printing. data Protocol = Protocol { protoName :: String , protoRoles :: [Role] } deriving( Eq, Ord, Show, Data, Typeable {-! NFData !-} ) -- Queries ---------- -- | Find a role in a protocol according to its name. lookupRole :: String -> Protocol -> Maybe Role lookupRole name = find ((== name) . roleName) . protoRoles -- | Find a role step in a role according to its label. lookupRoleStep :: String -> Role -> Maybe RoleStep lookupRoleStep lbl = find ((== lbl) . stepLabel) . roleSteps -- | Case distinction for specification variables. variable :: (Id -> a) -- ^ Function to apply for an agent variable. -> (Id -> a) -- ^ Function to apply for a message variable. -> VarId -> a variable agent _ (SAVar a) = agent a variable _ msg (SMVar m) = msg m -- | Pattern of a role step. stepPat :: RoleStep -> Pattern stepPat (Send _ pt) = pt stepPat (Recv _ pt) = pt stepPat (Match _ _ _ pt) = pt -- | The string label of a role step. stepLabel :: RoleStep -> String stepLabel (Send l _) = getLabel l stepLabel (Recv l _) = getLabel l stepLabel (Match l _ _ _) = getLabel l -- | Pattern subterms. subpatterns :: Pattern -> S.Set Pattern subpatterns pt@(PHash pt1) = S.insert pt $ subpatterns pt1 subpatterns pt@(PTup pt1 pt2) = S.insert pt $ subpatterns pt1 `S.union` subpatterns pt2 subpatterns pt@(PEnc pt1 pt2) = S.insert pt $ subpatterns pt1 `S.union` subpatterns pt2 subpatterns pt@(PSign pt1 pt2) = S.insert pt $ subpatterns pt1 `S.union` subpatterns pt2 subpatterns pt@(PSymK pt1 pt2) = S.insert pt $ subpatterns pt1 `S.union` subpatterns pt2 subpatterns pt@(PShrK pt1 pt2) = S.insert pt $ subpatterns pt1 `S.union` subpatterns pt2 subpatterns pt@(PAsymPK pt1) = S.insert pt $ subpatterns pt1 subpatterns pt@(PAsymSK pt1) = S.insert pt $ subpatterns pt1 subpatterns pt = S.singleton pt -- | Accessible pattern subterms. patternparts :: Pattern -> S.Set Pattern patternparts pt@(PTup pt1 pt2) = S.insert pt $ patternparts pt1 `S.union` patternparts pt2 patternparts pt@(PEnc pt1 _) = S.insert pt $ patternparts pt1 patternparts pt@(PSign pt1 _) = S.insert pt $ patternparts pt1 patternparts pt = S.singleton pt -- | Splitting top-level pairs. splitpatterns :: Pattern -> S.Set Pattern splitpatterns (PTup pt1 pt2) = splitpatterns pt1 `S.union` splitpatterns pt2 splitpatterns (PSign pt _ ) = splitpatterns pt splitpatterns pt = S.singleton pt -- | Free message variables of a pattern. patFMV :: Pattern -> S.Set Id patFMV (PMVar v) = S.singleton v patFMV (PHash pt) = patFMV pt patFMV (PTup pt1 pt2) = patFMV pt1 `S.union` patFMV pt2 patFMV (PEnc pt1 pt2) = patFMV pt1 `S.union` patFMV pt2 patFMV (PSign pt1 pt2) = patFMV pt1 `S.union` patFMV pt2 patFMV (PSymK pt1 pt2) = patFMV pt1 `S.union` patFMV pt2 patFMV (PShrK pt1 pt2) = patFMV pt1 `S.union` patFMV pt2 patFMV (PAsymPK pt) = patFMV pt patFMV (PAsymSK pt) = patFMV pt patFMV _ = S.empty -- | Frees message variables of a role step. stepFMV :: RoleStep -> S.Set Id stepFMV (Match _ _ (SMVar v) pt) = v `S.insert` patFMV pt stepFMV step = patFMV $ stepPat step -- | Free message variables of a role. roleFMV :: Role -> S.Set Id roleFMV = S.unions . map stepFMV . roleSteps -- | Free agent variables of a pattern. patFAV :: Pattern -> S.Set Id patFAV (PAVar v) = S.singleton v patFAV (PHash pt) = patFAV pt patFAV (PTup pt1 pt2) = patFAV pt1 `S.union` patFAV pt2 patFAV (PEnc pt1 pt2) = patFAV pt1 `S.union` patFAV pt2 patFAV (PSign pt1 pt2) = patFAV pt1 `S.union` patFAV pt2 patFAV (PSymK pt1 pt2) = patFAV pt1 `S.union` patFAV pt2 patFAV (PShrK pt1 pt2) = patFAV pt1 `S.union` patFAV pt2 patFAV (PAsymPK pt) = patFAV pt patFAV (PAsymSK pt) = patFAV pt patFAV _ = S.empty -- | Frees agent variables of a role step. stepFAV :: RoleStep -> S.Set Id stepFAV (Match _ _ (SAVar a) pt) = a `S.insert` patFAV pt stepFAV step = patFAV $ stepPat step -- | Free agent variables of a role. roleFAV :: Role -> S.Set Id roleFAV = S.unions . map stepFAV . roleSteps -- | Semantically used message variables of a role step. stepUsedMV :: RoleStep -> S.Set Id stepUsedMV (Send _ pt) = patFMV pt stepUsedMV (Recv _ _) = S.empty stepUsedMV (Match _ eq v pt) | eq = matched | otherwise = matched `S.union` patFMV pt where matched = case v of SAVar _ -> S.empty SMVar m -> S.singleton m -- | Message variables of a role step which are bound there at the latest. stepBoundMV :: RoleStep -> S.Set Id stepBoundMV (Recv _ pt) = patFMV pt stepBoundMV (Match _ True _ pt) = patFMV pt stepBoundMV _ = S.empty -- Well-formedness of protocols and roles ----------------------------------------- data ProtoIllformedness = NonUnique Role | UseBeforeBind Role RoleStep Id | AccessibleLongTermKey Role RoleStep Pattern deriving( Eq, Ord, Show ) -- | Check if a role is well-formed; i.e., all steps are distinct, no -- message variable is sent before it is received, and patterns do not -- contain long-term-keys in accessible positions. wfRole :: Role -> [ProtoIllformedness] wfRole role = msum [ do guard (not . unique $ roleSteps role) return $ NonUnique role , use_before_bind S.empty (roleSteps role) , msum . map accessibleLongTermKeys $ roleSteps role ] where use_before_bind _ [] = mzero use_before_bind bound (step : rs) = do v <- S.toList $ stepUsedMV step guard (not (v `S.member` bound)) return $ UseBeforeBind role step v `mplus` use_before_bind (stepBoundMV step `S.union` bound) rs accessibleLongTermKeys step = do m <- S.toList . patternparts $ stepPat step key <- case m of PSymK _ _ -> return m PAsymSK _ -> return m _ -> mzero return $ AccessibleLongTermKey role step key -- | Check if a protocol is well-formed; i.e., all roles are well-formed. wfProto :: Protocol -> [ProtoIllformedness] wfProto = concatMap wfRole . protoRoles -- | Pretty print a protocol ill-formedness. sptProtoIllformedness :: ProtoIllformedness -> Doc sptProtoIllformedness pif = case pif of NonUnique role -> text $ "role '" ++ roleName role ++ "' contains duplicate steps." UseBeforeBind role step v -> text (roleName role) <> colon <-> sptRoleStep Nothing step <> colon <-> text "message variable" <-> quotes (sptId v) <-> text "used before bound." AccessibleLongTermKey role step _ -> text (roleName role) <> colon <-> sptRoleStep Nothing step <> colon <-> text "long-term keys must not be accessible." -- Various orders on role steps ------------------------------- -- | An order relation on role steps of a role. type RoleStepOrder = [((RoleStep,Role),(RoleStep,Role))] -- | The order of role steps as they are given in the role. roleOrd :: Role -> RoleStepOrder roleOrd role = zip steps (tailDef [] steps) where steps = zip (roleSteps role) (repeat role) -- | The order of role steps in the protocol such that every send step -- occurs before every receive step having the same label. labelOrd :: Protocol -> RoleStepOrder labelOrd proto = [ (send, recv) | send@(Send l _, _) <- steps, recv@(Recv l' _, _) <- steps, l == l' ] where steps = concat [ zip (roleSteps role) (repeat role) | role <- protoRoles proto ] -- | The combination of all role orders and the label order of the protocol. protoOrd :: Protocol -> RoleStepOrder protoOrd proto = labelOrd proto ++ concatMap roleOrd (protoRoles proto) -- Construction --------------- -- | Apply a function to the free message variables of a pattern, replacing -- them by a subpattern. patMapFMV :: (Id -> Pattern) -> Pattern -> Pattern patMapFMV f = go where go (PMVar i) = f i go (PHash pt) = PHash (go pt) go (PTup pt1 pt2) = PTup (go pt1) (go pt2) go (PEnc pt1 pt2) = PEnc (go pt1) (go pt2) go (PSign pt1 pt2) = PSign (go pt1) (go pt2) go (PSymK pt1 pt2) = PSymK (go pt1) (go pt2) go (PShrK pt1 pt2) = PShrK (go pt1) (go pt2) go (PAsymPK pt) = PAsymPK (go pt) go (PAsymSK pt) = PAsymSK (go pt) go pt = pt ------------------------------------------------------------------------------ -- ISAR Output ------------------------------------------------------------------------------ -- | The name of the locale assuming a reachable state of the given protocol. stateLocale :: Protocol -> String stateLocale proto = protoName proto ++ "_state" -- | The name of the locale assuming a reachable state satisfying the axioms of -- the theory. restrictedStateLocale :: Protocol -> String restrictedStateLocale proto = "restricted_" ++ protoName proto ++ "_state" -- | Pretty print a rolestep in ISAR format. If a role is given, then the label -- of the role step in this role is used to abbreviate the step name. isaRoleStep :: IsarConf -> Maybe Role -> RoleStep -> Doc isaRoleStep conf optRole step = case optRole of Just role | step `elem` roleSteps role -> -- abbreviate text $ roleName role ++ "_" ++ stepLabel step _ -> isar conf step instance Isar Id where isar _ (Id i) = text $ "''"++i++"''" instance Isar VarId where isar conf = nestShort' "(" ")" . variable ppAgent ppMsg where ppAgent a = text "AVar" <-> isar conf a ppMsg m = text "MVar" <-> isar conf m instance Isar Label where isar _ (Label l) = text $ "''"++l++"''" instance Isar Pattern where isar conf x = case x of (PConst i) -> text "sC" <-> isar conf i (PFresh i) -> text "sN" <-> isar conf i (PAVar i) -> text "sAV" <-> isar conf i (PMVar i) -> text "sMV" <-> isar conf i (PHash pt) -> text "PHash" <-> ppTup pt pt@(PTup _ _) -> ppTup pt (PEnc m k) -> text "PEnc" <-> sep [ppTup m, ppTup k] (PSign m k) -> text "PSign" <-> sep [ppTup m, ppTup k] (PSymK (PAVar a) (PAVar b)) -> text "sK" <-> isar conf a <-> isar conf b (PSymK a b) -> text "PSymK" <-> sep [ppTup a, ppTup b] (PShrK a b) -> text "sKbd" <-> keyVar a <-> keyVar b (PAsymPK (PAVar a)) -> text "sPK" <-> isar conf a (PAsymPK a) -> text "PAsymPK" <-> ppTup a (PAsymSK (PAVar a)) -> text "sSK" <-> isar conf a (PAsymSK a) -> text "PAsymSK" <-> ppTup a (PAny) -> text "PAny" where -- pretty print a tuple as right associate list ppTup pt@(PTup _ _) = nestShort n left right (fsep $ punctuate comma $ map (isar conf) $ split pt) ppTup pt = nestShort' "(" ")" (isar conf pt) -- split right associate nested tuples split (PTup pt1 pt2) = pt1 : split pt2 split pt = [pt] -- determine output parameters (n,left,right) | isPlainStyle conf = (3, text "<|", text "|>") | otherwise = (2, symbol "\\<langle>", symbol "\\<rangle>") -- extract a variable of a bi-directional key keyVar (PAVar v) = parens $ text "AVar" <-> isar conf v keyVar (PMVar v) = parens $ text "MVar" <-> isar conf v keyVar _ = error $ "bi-directional key '" ++ show x ++ "' not supported." instance Isar RoleStep where isar conf step = case step of Send _ _ -> text "Send" <-> label <-> pattern Recv _ _ -> text "Recv" <-> label <-> pattern Match _ True v _ -> text "MatchEq" <-> label <-> isar conf v <-> pattern Match _ False v _ -> text "NotMatch" <-> label <-> isar conf v <-> pattern where label = isar conf (Label $ stepLabel step) pattern = ppPat (stepPat step) ppPat pt@(PTup _ _) = isar conf pt ppPat pt = nestShort' "(" ")" (isar conf pt) instance Isar Role where isar conf (Role name steps) = text "role" <-> text name $-$ text "where" <-> text "\"" <> text name <-> text "=" $-$ nest 2 ( (vcat $ zipWith (<->) separators (map (isar conf) steps)) $-$ text "]\"" ) where separators = map text ("[" : replicate (length steps - 1) ",") instance Isar Protocol where isar conf (Protocol name roles) = vcat (map (($-$ text "") . isar conf) roles) $-$ text "protocol" <-> text name $-$ sep [text "where" <-> text "\"" <> text name <-> text "=", roleSet] where roleSet = nestShort' "{" "}\"" (fsep $ punctuate comma $ map (text . roleName) roles) ------------------------------------------------------------------------------ -- SP Theory Output ------------------------------------------------------------------------------ sptId :: Id -> Doc sptId = text . getId sptLabel :: Label -> Doc sptLabel = text . getLabel sptPattern :: Pattern -> Doc sptPattern x = case x of (PConst i) -> char '\'' <> sptId i <> char '\'' (PFresh i) -> char '~' <> sptId i (PAVar i) -> sptId i (PMVar i) -> char '?' <> sptId i (PHash m) -> text "h" <> ppBetween 3 "(" ")" m pt@(PTup _ _) -> ppBetween 1 "(" ")" pt (PEnc m k) -> fcat [ppBetween 1 "{" "}" m, sptPattern k] (PSign m k) -> fcat [ppBetween 1 "sign{" "}" m, sptPattern k] (PSymK a b) -> fcat [text "k(", sptPattern a, comma, sptPattern b, text ")"] (PShrK a b) -> fcat [text "k[", sptPattern a, comma, sptPattern b, text "]"] (PAsymPK a) -> text "pk" <> ppBetween 1 "(" ")" a (PAsymSK a) -> text "sk" <> ppBetween 1 "(" ")" a (PAny) -> char '_' where -- pretty print a tuple as right associate list ppBetween n lead finish pt@(PTup _ _) = fcat . (text lead :) . (++[text finish]) . map (nest n) . punctuate (text ", ") . map sptPattern $ split pt ppBetween _ lead finish pt = text lead <> sptPattern pt <> text finish -- split right associate nested tuples split (PTup pt1 pt2) = pt1 : split pt2 split pt = [pt] -- | Pretty print a rolestep. If a role is given, then the label of the role -- step in this role is used to abbreviate the step name. sptRoleStep :: Maybe Role -> RoleStep -> Doc sptRoleStep optRole step = case optRole of Just role | step `elem` roleSteps role -> -- abbreviate text $ roleName role ++ "_" ++ stepLabel step _ -> case step of Send _ _ -> labeled "Send" <> pattern Recv _ _ -> labeled "Recv" <> pattern Match _ True v pt -> labeled "Match" <> matching "->" v pt Match _ False v pt -> labeled "Match" <> matching "#" v pt where labeled name = text $ name ++ "_" ++ stepLabel step matching sym v pt = nestShort' "(" ")" $ ppVar v <-> text sym <-> sptPattern pt pattern = ppPat (stepPat step) ppVar (SAVar a) = sptId a ppVar (SMVar v) = char '?' <> sptId v ppPat pt@(PTup _ _) = sptPattern pt ppPat pt = nestShort' "(" ")" (sptPattern pt) -- | Pretty print a role in SP theory format. sptRole :: Role -> Doc sptRole(Role name steps) = text "role" <-> text name $-$ nestBetween 2 lbrace rbrace ( (vcat $ map (sptRoleStep Nothing) steps) ) -- | Pretty print a protocol in SP theory format. sptProtocol :: Protocol -> Doc sptProtocol (Protocol name roles) = text "protocol" <-> text name $-$ nestBetween 2 lbrace rbrace ( vcat (intersperse (text "") $ map sptRole roles) )
meiersi/scyther-proof
src/Scyther/Protocol.hs
gpl-3.0
18,878
0
16
5,025
5,996
3,041
2,955
354
15
{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE LambdaCase #-} module ProofCas.Backends.SFP.Proofs where import Utils.ABT import Utils.Vars import Utils.Unifier import Dependent.Core.Term import Dependent.Unification.Unification import Dependent.Unification.Elaborator import Control.Lens hiding (rewrite) import Control.Monad import Data.Maybe import Data.Monoid import Data.Foldable hiding (fold) import ProofCas.Rendering (StPart(..)) import ProofCas.Backends.SFP.Status import ProofCas.Backends.SFP.Paths proofStep :: (Status -> Either String Status) -> Status -> Either String Status proofStep f st = do st' <- f st; checkStatus st'; return st' evalAt :: StPath -> Status -> Either String Status evalAt sel st = st & stpath sel (evalIn st) boundIn :: Term -> [String] boundIn (Var _) = [] boundIn (In t) = foldMap (\sc -> names sc ++ boundIn (body sc)) t definedNames :: Term -> [String] definedNames (Var _) = [] definedNames (In (Defined v)) = [v] definedNames (In t) = foldMap (definedNames . body) t freshFor :: Term -> String freshFor t = freshenName unusable "x" where unusable = boundIn t ++ freeVarNames t ++ definedNames t factorOut :: TPath -> Term -> Maybe Term factorOut pa t = do a <- t^?tpath pa let noBound (Var (Bound _ _)) = False noBound (Var _) = True noBound (In t) = all (noBound . body) t guard (noBound a) let param = freshFor t body = t & tpath pa.~F param return $ appH (lamH param body) a factorOutSt :: StPath -> Status -> Either String Status factorOutSt (stpa, pa) = maybe (Left msg) Right . stpart stpa (factorOut pa) where msg = "Can't factor out - contains bound variable" pattern M n = Var (Meta (MetaVar n)) pattern F n = Var (Free (FreeVar n)) pattern S t <- Scope _ _ t pattern App' f x <- In (App (Scope _ _ f) (Scope _ _ x)) handleDrop :: StPath -> StPath -> Status -> Either String Status handleDrop stpa stpa' st = fromMaybe (Right st) $ alaf First foldMap (\f -> f stpa stpa' st) handlers where handlers = [rewrite] useAs :: Term -> Term -> Term -> Status -> Either String (Term, Term, Substitution TermF) useAs ty prf goal st = do let Status sig defs ctx _ _ = st unify' s t = runElaborator (unify substitution context s t) sig defs ctx unifyA n t = case (unify' t goal, metaify n t) of (Left _, Just t') -> unifyA (n + 1) t'; (r, _) -> ((,) n) <$> r metaify n (In (Fun _ s)) = Just (instantiate s [Var (Meta (MetaVar n))]) metaify _ _ = Nothing meta0 = 1 + fold (\case Meta (MetaVar n) -> n; _ -> 0) (foldl' max 0) (flip const) goal (argCount, ((), es)) <- unifyA meta0 ty let argsm = mapM (\i -> lookup (MetaVar i) (_substitution es)) [meta0..argCount - 1] args <- maybe (Left "Couldn't infer all args") Right argsm let ty' = foldl (\(In (Fun _ s)) a -> instantiate s [a]) ty args prf' = foldl appH prf args return (ty', prf', _substitution es) rewrite :: StPath -> StPath -> Status -> Maybe (Either String Status) rewrite stpa@(Assm v, pa@(ConArg n:steps)) stpa'@(Thm, pa') st = do guard $ all (==FunRet) steps && n `elem` [1, 2] In (Con "Op_61" [_, _, _]) <- st^?stpath (parent stpa) eqTy <- st^?stpart (Assm v) target <- st^?stpath stpa' return $ do let Status _ _ _ thm prf = st App' p _ <- maybe (Left "Rewrite target contains bound variable") Right $ factorOut pa' thm let goal = conH "Op_61" (if n == 1 then [M 0, M 1, target] else [M 0, target, M 1]) (In (Con _ [S argTy, S lhs, S rhs]), eqPrf, es) <- useAs eqTy (F v) goal st let (from, to, eqPrf') = if n == 1 then let sym = foldl1 appH [In (Defined "eq_sym"), argTy, lhs, rhs, eqPrf] in (rhs, lhs, sym) else (lhs, rhs, eqPrf) prf' = foldl1 appH [In (Defined "eq_elim"), argTy, p, from, to, eqPrf', prf] return $ st & stpath (Thm, pa').~to & (stpart Prf).~prf' rewrite _ _ _ = Nothing
benzrf/cas
src/ProofCas/Backends/SFP/Proofs.hs
gpl-3.0
3,894
0
22
875
1,860
947
913
83
4
{- - Copyright (C) 2014 Alexander Berntsen <[email protected]> - - This file is part of coreutilhs. - - coreutilhs is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - coreutilhs is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with coreutilhs. If not, see <http://www.gnu.org/licenses/>. -} module Main where import Control.Applicative ((<$>)) import Control.Exception (catch) import Control.Monad (forM_, unless) import Data.Text (pack, toTitle, unpack) import System.Directory (getDirectoryContents) import System.Environment (getArgs) import System.IO.Error (ioeGetErrorString) import Text.Printf (printf) -- Count number of files in a directory. main :: IO () main = do dirs <- getArgs if null dirs then printCount "." else forM_ dirs $ \d -> printCount d printCount :: FilePath -> IO () printCount dir = do count <- countFiles dir unless (count == (-1)) $ print count countFiles :: FilePath -> IO Int countFiles dir = subtract 2 . length <$> filesIn dir filesIn :: FilePath -> IO [FilePath] filesIn dir = getDirectoryContents dir `catch` bork dir bork :: String -> IOError -> IO [FilePath] bork dir err = do printf "cf: cannot stat '%s': %s\n" dir $ unpack . toTitle . pack $ ioeGetErrorString err return [""]
alexander-b/coreutilhs
cf.hs
gpl-3.0
1,696
0
12
308
343
180
163
28
2
module Builtin.Error where import Builtin.Utils import Eval import AST import Object import qualified Data.Map as M errorClass = buildClass "Error" bootError bootError = M.fromList [ ("initialize", VFunction initFn (2,Nothing)) ] initFn :: [Value] -> EvalM() initFn (name:msg:objs) = evalT $ flip Block "Builtin/Error.hs" [ Assign (LIVar "error") $ EValue name , Assign (LIVar "message") $ EValue msg , Assign (LIVar "vars") $ EArray $ map EValue objs ]
antarestrader/sapphire
Builtin/Error.hs
gpl-3.0
479
0
12
93
178
95
83
14
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Gmail.Users.Settings.Filters.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a filter. -- -- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.filters.delete@. module Network.Google.Resource.Gmail.Users.Settings.Filters.Delete ( -- * REST Resource UsersSettingsFiltersDeleteResource -- * Creating a Request , usersSettingsFiltersDelete , UsersSettingsFiltersDelete -- * Request Lenses , usfdUserId , usfdId ) where import Network.Google.Gmail.Types import Network.Google.Prelude -- | A resource alias for @gmail.users.settings.filters.delete@ method which the -- 'UsersSettingsFiltersDelete' request conforms to. type UsersSettingsFiltersDeleteResource = "gmail" :> "v1" :> "users" :> Capture "userId" Text :> "settings" :> "filters" :> Capture "id" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Deletes a filter. -- -- /See:/ 'usersSettingsFiltersDelete' smart constructor. data UsersSettingsFiltersDelete = UsersSettingsFiltersDelete' { _usfdUserId :: !Text , _usfdId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UsersSettingsFiltersDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'usfdUserId' -- -- * 'usfdId' usersSettingsFiltersDelete :: Text -- ^ 'usfdId' -> UsersSettingsFiltersDelete usersSettingsFiltersDelete pUsfdId_ = UsersSettingsFiltersDelete' { _usfdUserId = "me" , _usfdId = pUsfdId_ } -- | User\'s email address. The special value \"me\" can be used to indicate -- the authenticated user. usfdUserId :: Lens' UsersSettingsFiltersDelete Text usfdUserId = lens _usfdUserId (\ s a -> s{_usfdUserId = a}) -- | The ID of the filter to be deleted. usfdId :: Lens' UsersSettingsFiltersDelete Text usfdId = lens _usfdId (\ s a -> s{_usfdId = a}) instance GoogleRequest UsersSettingsFiltersDelete where type Rs UsersSettingsFiltersDelete = () type Scopes UsersSettingsFiltersDelete = '["https://www.googleapis.com/auth/gmail.settings.basic"] requestClient UsersSettingsFiltersDelete'{..} = go _usfdUserId _usfdId (Just AltJSON) gmailService where go = buildClient (Proxy :: Proxy UsersSettingsFiltersDeleteResource) mempty
rueshyna/gogol
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/Filters/Delete.hs
mpl-2.0
3,267
0
15
742
385
232
153
60
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AdExchangeBuyer2.Accounts.Proposals.Pause -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Update the given proposal to pause serving. This method will set the -- \`DealServingMetadata.DealPauseStatus.has_buyer_paused\` bit to true for -- all deals in the proposal. It is a no-op to pause an already-paused -- proposal. It is an error to call PauseProposal for a proposal that is -- not finalized or renegotiating. -- -- /See:/ <https://developers.google.com/authorized-buyers/apis/reference/rest/ Ad Exchange Buyer API II Reference> for @adexchangebuyer2.accounts.proposals.pause@. module Network.Google.Resource.AdExchangeBuyer2.Accounts.Proposals.Pause ( -- * REST Resource AccountsProposalsPauseResource -- * Creating a Request , accountsProposalsPause , AccountsProposalsPause -- * Request Lenses , appXgafv , appUploadProtocol , appAccessToken , appUploadType , appPayload , appProposalId , appAccountId , appCallback ) where import Network.Google.AdExchangeBuyer2.Types import Network.Google.Prelude -- | A resource alias for @adexchangebuyer2.accounts.proposals.pause@ method which the -- 'AccountsProposalsPause' request conforms to. type AccountsProposalsPauseResource = "v2beta1" :> "accounts" :> Capture "accountId" Text :> "proposals" :> CaptureMode "proposalId" "pause" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] PauseProposalRequest :> Post '[JSON] Proposal -- | Update the given proposal to pause serving. This method will set the -- \`DealServingMetadata.DealPauseStatus.has_buyer_paused\` bit to true for -- all deals in the proposal. It is a no-op to pause an already-paused -- proposal. It is an error to call PauseProposal for a proposal that is -- not finalized or renegotiating. -- -- /See:/ 'accountsProposalsPause' smart constructor. data AccountsProposalsPause = AccountsProposalsPause' { _appXgafv :: !(Maybe Xgafv) , _appUploadProtocol :: !(Maybe Text) , _appAccessToken :: !(Maybe Text) , _appUploadType :: !(Maybe Text) , _appPayload :: !PauseProposalRequest , _appProposalId :: !Text , _appAccountId :: !Text , _appCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsProposalsPause' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'appXgafv' -- -- * 'appUploadProtocol' -- -- * 'appAccessToken' -- -- * 'appUploadType' -- -- * 'appPayload' -- -- * 'appProposalId' -- -- * 'appAccountId' -- -- * 'appCallback' accountsProposalsPause :: PauseProposalRequest -- ^ 'appPayload' -> Text -- ^ 'appProposalId' -> Text -- ^ 'appAccountId' -> AccountsProposalsPause accountsProposalsPause pAppPayload_ pAppProposalId_ pAppAccountId_ = AccountsProposalsPause' { _appXgafv = Nothing , _appUploadProtocol = Nothing , _appAccessToken = Nothing , _appUploadType = Nothing , _appPayload = pAppPayload_ , _appProposalId = pAppProposalId_ , _appAccountId = pAppAccountId_ , _appCallback = Nothing } -- | V1 error format. appXgafv :: Lens' AccountsProposalsPause (Maybe Xgafv) appXgafv = lens _appXgafv (\ s a -> s{_appXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). appUploadProtocol :: Lens' AccountsProposalsPause (Maybe Text) appUploadProtocol = lens _appUploadProtocol (\ s a -> s{_appUploadProtocol = a}) -- | OAuth access token. appAccessToken :: Lens' AccountsProposalsPause (Maybe Text) appAccessToken = lens _appAccessToken (\ s a -> s{_appAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). appUploadType :: Lens' AccountsProposalsPause (Maybe Text) appUploadType = lens _appUploadType (\ s a -> s{_appUploadType = a}) -- | Multipart request metadata. appPayload :: Lens' AccountsProposalsPause PauseProposalRequest appPayload = lens _appPayload (\ s a -> s{_appPayload = a}) -- | The ID of the proposal to pause. appProposalId :: Lens' AccountsProposalsPause Text appProposalId = lens _appProposalId (\ s a -> s{_appProposalId = a}) -- | Account ID of the buyer. appAccountId :: Lens' AccountsProposalsPause Text appAccountId = lens _appAccountId (\ s a -> s{_appAccountId = a}) -- | JSONP appCallback :: Lens' AccountsProposalsPause (Maybe Text) appCallback = lens _appCallback (\ s a -> s{_appCallback = a}) instance GoogleRequest AccountsProposalsPause where type Rs AccountsProposalsPause = Proposal type Scopes AccountsProposalsPause = '["https://www.googleapis.com/auth/adexchange.buyer"] requestClient AccountsProposalsPause'{..} = go _appAccountId _appProposalId _appXgafv _appUploadProtocol _appAccessToken _appUploadType _appCallback (Just AltJSON) _appPayload adExchangeBuyer2Service where go = buildClient (Proxy :: Proxy AccountsProposalsPauseResource) mempty
brendanhay/gogol
gogol-adexchangebuyer2/gen/Network/Google/Resource/AdExchangeBuyer2/Accounts/Proposals/Pause.hs
mpl-2.0
6,224
0
19
1,415
868
508
360
127
1
-- | -- General Considerations -- -- <https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf saml-bindings-2.0-os> §3.1 module SAML2.Bindings.General where import Data.ByteString (ByteString) import Data.String (IsString(fromString)) type RelayState = ByteString -- |The name of the parameter used by many protocols for the message itself for requests (False) or responses (True). Often combined with 'SAML2.Core.Protocols.isSAMLResponse'. protocolParameter :: IsString a => Bool -> a protocolParameter False = fromString "SAMLRequest" protocolParameter True = fromString "SAMLResponse" relayStateParameter :: IsString a => a relayStateParameter = fromString "RelayState"
dylex/hsaml2
SAML2/Bindings/General.hs
apache-2.0
695
0
6
80
100
57
43
9
1
{-# LANGUAGE Safe #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Edward Kmett and Ted Cooper -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Ted Cooper <[email protected]> -- Stability : experimental -- Portability : non-portable -- ----------------------------------------------------------------------------- module Control.Concurrent.RCU.Class ( MonadNew(..) , MonadReading(..) , MonadWriting(..) , MonadRCU(..) , copySRef ) where import Control.Applicative import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.Except import Control.Monad.Trans.Identity import Control.Monad.Trans.Maybe import Control.Monad.Trans.Reader import Prelude hiding (read, Read) import qualified Control.Monad.Trans.RWS.Lazy as Lazy import qualified Control.Monad.Trans.RWS.Strict as Strict import qualified Control.Monad.Trans.State.Lazy as Lazy import qualified Control.Monad.Trans.State.Strict as Strict import qualified Control.Monad.Trans.Writer.Lazy as Lazy import qualified Control.Monad.Trans.Writer.Strict as Strict -------------------------------------------------------------------------------- -- * MonadNew -------------------------------------------------------------------------------- class Monad m => MonadNew s m | m -> s where -- | Build a new shared reference newSRef :: a -> m (s a) default newSRef :: (m ~ t n, MonadTrans t, MonadNew s n) => a -> m (s a) newSRef a = lift (newSRef a) instance MonadNew s m => MonadNew s (ReaderT e m) instance (MonadNew s m, Monoid w) => MonadNew s (Strict.WriterT w m) instance (MonadNew s m, Monoid w) => MonadNew s (Lazy.WriterT w m) instance MonadNew s' m => MonadNew s' (Strict.StateT s m) instance MonadNew s' m => MonadNew s' (Lazy.StateT s m) instance (MonadNew s' m, Monoid w) => MonadNew s' (Strict.RWST r w s m) instance (MonadNew s' m, Monoid w) => MonadNew s' (Lazy.RWST r w s m) instance MonadNew s m => MonadNew s (ExceptT e m) instance MonadNew s m => MonadNew s (MaybeT m) instance MonadNew s m => MonadNew s (IdentityT m) -------------------------------------------------------------------------------- -- * MonadReading -------------------------------------------------------------------------------- -- | This is a read-side critical section class MonadNew s m => MonadReading s m | m -> s where -- | Read a shared reference. readSRef :: s a -> m a default readSRef :: (m ~ t n, MonadTrans t, MonadReading s n) => s a -> m a readSRef r = lift (readSRef r) {-# INLINE readSRef #-} -- | Copy a shared reference. copySRef :: MonadReading s m => s a -> m (s a) copySRef r = do a <- readSRef r newSRef a {-# INLINE copySRef #-} instance MonadReading s m => MonadReading s (ReaderT e m) instance (MonadReading s m, Monoid w) => MonadReading s (Strict.WriterT w m) instance (MonadReading s m, Monoid w) => MonadReading s (Lazy.WriterT w m) instance MonadReading s' m => MonadReading s' (Strict.StateT s m) instance MonadReading s' m => MonadReading s' (Lazy.StateT s m) instance (MonadReading s' m, Monoid w) => MonadReading s' (Strict.RWST r w s m) instance (MonadReading s' m, Monoid w) => MonadReading s' (Lazy.RWST r w s m) instance MonadReading s m => MonadReading s (ExceptT e m) instance MonadReading s m => MonadReading s (MaybeT m) instance MonadReading s m => MonadReading s (IdentityT m) -------------------------------------------------------------------------------- -- * MonadWriting -------------------------------------------------------------------------------- -- | This is a write-side critical section class MonadReading s m => MonadWriting s m | m -> s where -- | Write to a shared reference. writeSRef :: s a -> a -> m () default writeSRef :: (m ~ t n, MonadTrans t, MonadWriting s n) => s a -> a -> m () writeSRef r a = lift (writeSRef r a) -- | Synchronize with other writers. -- -- No other writer can straddle this time bound. It will either see writes from before, or writes after, but never -- some of both! synchronize :: m () default synchronize :: (m ~ t n, MonadTrans t, MonadWriting s n) => m () synchronize = lift synchronize instance MonadWriting s m => MonadWriting s (ReaderT e m) instance (MonadWriting s m, Monoid w) => MonadWriting s (Strict.WriterT w m) instance (MonadWriting s m, Monoid w) => MonadWriting s (Lazy.WriterT w m) instance MonadWriting s' m => MonadWriting s' (Strict.StateT s m) instance MonadWriting s' m => MonadWriting s' (Lazy.StateT s m) instance (MonadWriting s' m, Monoid w) => MonadWriting s' (Strict.RWST r w s m) instance (MonadWriting s' m, Monoid w) => MonadWriting s' (Lazy.RWST r w s m) instance MonadWriting s m => MonadWriting s (IdentityT m) instance MonadWriting s m => MonadWriting s (ExceptT e m) instance MonadWriting s m => MonadWriting s (MaybeT m) -------------------------------------------------------------------------------- -- * MonadRCU -------------------------------------------------------------------------------- -- | This is the executor service that can fork, join and execute critical sections. class ( MonadReading s (Reading m) , MonadWriting s (Writing m) , MonadNew s m ) => MonadRCU s m | m -> s where -- | A read-side critical section type Reading m :: * -> * -- | A write-side critical section type Writing m :: * -> * -- | Threads we can fork and join type Thread m :: * -> * -- | Fork a thread forking :: m a -> m (Thread m a) -- | Join a thread joining :: Thread m a -> m a -- | Run a read-side critical section reading :: Reading m a -> m a -- | Run a write-side critical section writing :: Writing m a -> m a instance MonadRCU s m => MonadRCU s (ReaderT e m) where type Reading (ReaderT e m) = ReaderT e (Reading m) type Writing (ReaderT e m) = ReaderT e (Writing m) type Thread (ReaderT e m) = Thread m forking (ReaderT f) = ReaderT $ \a -> forking (f a) joining = lift . joining reading (ReaderT f) = ReaderT $ \a -> reading (f a) writing (ReaderT f) = ReaderT $ \a -> writing (f a) {-# INLINE forking #-} {-# INLINE joining #-} {-# INLINE reading #-} {-# INLINE writing #-} instance MonadRCU s m => MonadRCU s (IdentityT m) where type Reading (IdentityT m) = Reading m type Writing (IdentityT m) = Writing m type Thread (IdentityT m) = Thread m forking (IdentityT m) = IdentityT (forking m) joining = lift . joining reading m = IdentityT (reading m) writing m = IdentityT (writing m) {-# INLINE forking #-} {-# INLINE joining #-} {-# INLINE reading #-} {-# INLINE writing #-} instance MonadRCU s m => MonadRCU s (ExceptT e m) where type Reading (ExceptT e m) = ExceptT e (Reading m) type Writing (ExceptT e m) = ExceptT e (Writing m) type Thread (ExceptT e m) = ExceptT e (Thread m) forking (ExceptT m) = lift $ ExceptT <$> forking m joining (ExceptT m) = ExceptT $ joining m reading (ExceptT m) = ExceptT $ reading m writing (ExceptT m) = ExceptT $ writing m {-# INLINE forking #-} {-# INLINE joining #-} {-# INLINE reading #-} {-# INLINE writing #-} instance MonadRCU s m => MonadRCU s (MaybeT m) where type Reading (MaybeT m) = MaybeT (Reading m) type Writing (MaybeT m) = MaybeT (Writing m) type Thread (MaybeT m) = MaybeT (Thread m) forking (MaybeT m) = lift $ MaybeT <$> forking m joining (MaybeT m) = MaybeT $ joining m reading (MaybeT m) = MaybeT $ reading m writing (MaybeT m) = MaybeT $ writing m {-# INLINE forking #-} {-# INLINE joining #-} {-# INLINE reading #-} {-# INLINE writing #-} instance (MonadRCU s m, Monoid e) => MonadRCU s (Strict.WriterT e m) where type Reading (Strict.WriterT e m) = Strict.WriterT e (Reading m) type Writing (Strict.WriterT e m) = Strict.WriterT e (Writing m) type Thread (Strict.WriterT e m) = Strict.WriterT e (Thread m) forking (Strict.WriterT m) = lift $ Strict.WriterT <$> forking m joining (Strict.WriterT m) = Strict.WriterT $ joining m reading (Strict.WriterT m) = Strict.WriterT $ reading m writing (Strict.WriterT m) = Strict.WriterT $ writing m {-# INLINE forking #-} {-# INLINE joining #-} {-# INLINE reading #-} {-# INLINE writing #-} instance (MonadRCU s m, Monoid e) => MonadRCU s (Lazy.WriterT e m) where type Reading (Lazy.WriterT e m) = Lazy.WriterT e (Reading m) type Writing (Lazy.WriterT e m) = Lazy.WriterT e (Writing m) type Thread (Lazy.WriterT e m) = Lazy.WriterT e (Thread m) forking (Lazy.WriterT m) = lift $ Lazy.WriterT <$> forking m joining (Lazy.WriterT m) = Lazy.WriterT $ joining m reading (Lazy.WriterT m) = Lazy.WriterT $ reading m writing (Lazy.WriterT m) = Lazy.WriterT $ writing m {-# INLINE forking #-} {-# INLINE joining #-} {-# INLINE reading #-} {-# INLINE writing #-}
anthezium/rcu
src/Control/Concurrent/RCU/Class.hs
bsd-2-clause
9,187
0
12
1,707
2,980
1,538
1,442
166
1
module FindingAnAppointment where import Data.List import Data.Char timeOff = -540 timeMax = 599 timeStrToInt ts = ((\(h, m) -> h * 60 + m + timeOff) . mapt ((read :: String -> Int) . filter isDigit) . break (== ':')) ts where mapt f (x, y) = (f x, f y) timeIntToStr t = let t2 = t - timeOff (h, m) = (t2 `div` 60, t2 `mod` 60) hs = if h < 10 then '0':(show h) else show h ms = if m < 10 then '0':(show m) else show m in hs ++ ":" ++ ms getStartTime :: [[(String, String)]] -> Int -> Maybe String getStartTime schedules duration = let runs = findRuns (commonFreeMinutes schedules) in case (find (\(h, l) -> l >= duration) runs) of Just h -> Just (timeIntToStr (fst h)) Nothing -> Nothing where findRuns = map (\(x, y, z) -> (x, y)) . foldr f [] where f x z = if null z then [(x, 1, x)] else let (s, n, e) = head z in if x + n == e then (x, n + 1, e):(tail z) else (x, 1, x):z meetingToMinutes (start, end) = init [(timeStrToInt start)..(timeStrToInt end)] freeMinutes = ((\\) [0..timeMax] . concatMap meetingToMinutes) commonFreeMinutes = foldl1 intersect . map freeMinutes schedules = [ [("09:00", "11:30"), ("13:30", "16:00"), ("16:00", "17:30"), ("17:45", "19:00")] , [("09:15", "12:00"), ("14:00", "16:30"), ("17:00", "17:30")] , [("11:30", "12:15"), ("15:00", "16:30"), ("17:45", "19:00")] ] simpleSchedule = [("09:00", "09:10"), ("09:15", "09:20")]
lisphacker/codewars
FindingAnAppointment.hs
bsd-2-clause
1,912
0
15
802
729
411
318
32
4
{-# LANGUAGE ForeignFunctionInterface #-} -- | -- Copyright : Anders Claesson 2013 -- Maintainer : Anders Claesson <[email protected]> -- module Sym.Perm.Sort ( stackSort , bubbleSort ) where import Sym.Perm import Foreign import Foreign.C.Types import System.IO.Unsafe foreign import ccall unsafe "sortop.h stacksort" c_stacksort :: Ptr CLong -> Ptr CLong -> CLong -> IO () foreign import ccall unsafe "sortop.h bubblesort" c_bubblesort :: Ptr CLong -> Ptr CLong -> CLong -> IO () marshal :: (Ptr CLong -> Ptr CLong -> CLong -> IO ()) -> Perm -> Perm marshal op w = unsafePerformIO . unsafeWith w $ \p -> do let n = size w unsafeNew n $ \q -> op q p (fromIntegral n) {-# INLINE marshal #-} -- | One pass of stack-sort. stackSort :: Perm -> Perm stackSort = marshal c_stacksort {-# INLINE stackSort #-} -- | One pass of bubble-sort. bubbleSort :: Perm -> Perm bubbleSort = marshal c_bubblesort {-# INLINE bubbleSort #-}
akc/sym
Sym/Perm/Sort.hs
bsd-3-clause
981
0
13
209
258
137
121
25
1
module URLMapperSpec where import Test.Hspec import Wikirick.Backends.URLMapper import Wikirick.Import import Wikirick.Repository urlMapper :: URLMapper urlMapper = initURLMapper "/base" beExpanded :: URL -> String -> Expectation beExpanded url expectation = expandURL urlMapper url `shouldBe` expectation urlMapperSpec :: Spec urlMapperSpec = describe "URL mapper" $ do it "expands article pathes" $ do ArticlePath (def & articleTitle .~ "foo") `beExpanded` "/base/wiki/foo" it "expands edit pathes" $ do EditPath (def & articleTitle .~ "bar") `beExpanded` "/base/wiki/bar/edit"
keitax/wikirick
spec/URLMapperSpec.hs
bsd-3-clause
598
0
15
90
155
82
73
15
1
-- Copyright © 2013 Bart Massey -- Demo of Text.Printf.Extensible import Text.Printf.Extensible newtype Unary = Unary Int instance PrintfArg Unary where toField (Unary i) ufmt = case ufmt of FieldFormat {fmtChar = 'U'} -> let (s, i') = if i >= 0 then ("", i) else ("-", (-i)) in formatString (s ++ replicate i' '*') (ufmt {fmtChar = 's'}) _ -> formatInt i ufmt main :: IO () main = do printf "%s %lld %c %d %U %d\n" "hello" (1 :: Int) 'a' 'b' (Unary (-3)) (Unary 5)
BartMassey/extensible-printf
Demo.hs
bsd-3-clause
520
0
16
141
202
109
93
14
1
module Tritium.Screen ( mainMenu ) where import Control.Monad (when) import Control.Monad.State (get, modify) import Control.Lens ((^.)) import SFML.Window.Event (SFEvent (..)) import Tritium.Import import Tritium.UI -- | The main menu. mainMenu :: GameScreen mainMenu ft ev = do state <- get when (state^.setup) $ do Just title <- newText "MonkirtaPursuit" 90 "Tritium" centerTextX title addText title setupDone case ev of Just (SFEvtMouseButtonPressed mbtn mx my) -> debugP $ "Click " ++ show mbtn ++ "@" ++ show mx ++ "," ++ show my _ -> return ()
sulami/Tritium
src/Tritium/Screen.hs
bsd-3-clause
654
0
15
189
214
110
104
20
2
{-# OPTIONS_GHC -Wall #-} module Reporting.Error.Canonicalize where import qualified Text.PrettyPrint as P import qualified AST.Module as Module import qualified AST.Type as Type import qualified AST.Variable as Var import qualified Reporting.Error.Helpers as Help import qualified Reporting.PrettyPrint as P import qualified Reporting.Region as Region import qualified Reporting.Report as Report data Error = Var VarError | Pattern PatternError | Alias AliasError | Import Module.Name ImportError | Export String [String] | DuplicateExport String | Port PortError -- VARIABLES data VarError = VarError { varKind :: String , varName :: String , varProblem :: VarProblem , varSuggestions :: [String] } data VarProblem = Ambiguous | UnknownQualifier String String | QualifiedUnknown String String | ExposedUnknown variable :: String -> String -> VarProblem -> [String] -> Error variable kind name problem suggestions = Var (VarError kind name problem suggestions) -- PATTERN data PatternError = PatternArgMismatch Var.Canonical Int Int argMismatch :: Var.Canonical -> Int -> Int -> Error argMismatch name expected actual = Pattern (PatternArgMismatch name expected actual) -- IMPORTS data ImportError = ModuleNotFound [Module.Name] | ValueNotFound String [String] moduleNotFound :: Module.Name -> [Module.Name] -> Error moduleNotFound name possibilities = Import name (ModuleNotFound possibilities) valueNotFound :: Module.Name -> String -> [String] -> Error valueNotFound name value possibilities = Import name (ValueNotFound value possibilities) -- ALIASES data AliasError = ArgMismatch Var.Canonical Int Int | SelfRecursive String [String] Type.Raw | MutuallyRecursive [(Region.Region, String, [String], Type.Raw)] alias :: Var.Canonical -> Int -> Int -> Error alias name expected actual = Alias (ArgMismatch name expected actual) -- PORTS data PortError = PortError { portName :: String , portIsInbound :: Bool , portRootType :: Type.Canonical , portLocalType :: Type.Canonical , portMessage :: Maybe String } port :: String -> Bool -> Type.Canonical -> Type.Canonical -> Maybe String -> Error port name isInbound rootType localType maybeMessage = Port (PortError name isInbound rootType localType maybeMessage) -- TO REPORT namingError :: String -> String -> Report.Report namingError pre post = Report.simple "NAMING ERROR" pre post toReport :: P.Dealiaser -> Error -> Report.Report toReport dealiaser err = case err of Var (VarError kind name problem suggestions) -> let var = kind ++ " `" ++ name ++ "`" in case problem of Ambiguous -> namingError ("This usage of " ++ var ++ " is ambiguous.") (Help.maybeYouWant suggestions) UnknownQualifier qualifier localName -> namingError ("Cannot find " ++ var ++ ".") ( "The qualifier `" ++ qualifier ++ "` is not in scope. " ++ Help.maybeYouWant (map (\modul -> modul ++ "." ++ localName) suggestions) ) QualifiedUnknown qualifier localName -> namingError ("Cannot find " ++ var ++ ".") ( "`" ++ qualifier ++ "` does not expose `" ++ localName ++ "`. " ++ Help.maybeYouWant (map (\v -> qualifier ++ "." ++ v) suggestions) ) ExposedUnknown -> namingError ("Cannot find " ++ var) (Help.maybeYouWant suggestions) Pattern patternError -> case patternError of PatternArgMismatch var expected actual -> argMismatchReport "Pattern" var expected actual Alias aliasError -> case aliasError of ArgMismatch var expected actual -> argMismatchReport "Type" var expected actual SelfRecursive name tvars tipe -> Report.simple "ALIAS PROBLEM" "This type alias is recursive, forming an infinite type!" $ "Type aliases are just names for more fundamental types, so I go through\n" ++ "and expand them all to know the real underlying type. The problem is that\n" ++ "when I expand a recursive type alias, it keeps getting bigger and bigger.\n" ++ "Dealiasing results in an infinitely large type! Try this instead:\n\n" ++ " type " ++ name ++ concatMap (' ':) tvars ++ " =" ++ P.render (P.nest 8 (P.hang (P.text name) 2 (P.pretty dealiaser True tipe))) ++ "\n\nThis creates a brand new type that cannot be expanded. It is similar types\n" ++ "like List which are recursive, but do not get expanded into infinite types." MutuallyRecursive aliases -> Report.simple "ALIAS PROBLEM" "This type alias is part of a mutually recursive set of type aliases." $ "The following type aliases all depend on each other in some way:\n" ++ concatMap showName aliases ++ "\n\n" ++ "The problem is that when you try to expand any of these type aliases, they\n" ++ "expand infinitely! To fix, first try to centralize them into one alias." where showName (Region.Region start _, name, _, _) = "\n " ++ name ++ replicate (65 - length name) ' ' ++ "line " ++ show (Region.line start) Import name importError -> let moduleName = Module.nameToString name in case importError of ModuleNotFound suggestions -> namingError ("Could not find a module named `" ++ moduleName ++ "`") (Help.maybeYouWant (map Module.nameToString suggestions)) ValueNotFound value suggestions -> namingError ("Module `" ++ moduleName ++ "` does not expose `" ++ value ++ "`") (Help.maybeYouWant suggestions) Export name suggestions -> namingError ("Could not export `" ++ name ++ "` which is not defined in this module.") (Help.maybeYouWant suggestions) DuplicateExport name -> namingError ("You are trying to export `" ++ name ++ "` multiple times!") "Remove duplicates until there is only one listed." Port (PortError name isInbound _rootType localType maybeMessage) -> let boundPort = if isInbound then "inbound port" else "outbound port" preHint = "Trying to send " ++ maybe "an unsupported type" id maybeMessage ++ " through " ++ boundPort ++ " `" ++ name ++ "`" postHint = "The specific unsupported type is:\n\n" ++ P.render (P.nest 4 (P.pretty dealiaser False localType)) ++ "\n\n" ++ "The types of values that can flow through " ++ boundPort ++ "s include:\n" ++ "Ints, Floats, Bools, Strings, Maybes, Lists, Arrays, Tuples,\n" ++ "Json.Values, and concrete records." in Report.simple "PORT ERROR" preHint postHint argMismatchReport :: String -> Var.Canonical -> Int -> Int -> Report.Report argMismatchReport kind var expected actual = let preHint = kind ++ " " ++ Var.toString var ++ " has too " ++ (if actual < expected then "few" else "many") ++ " arguments." postHint = "Expecting " ++ show expected ++ ", but got " ++ show actual ++ "." in Report.simple "ARGUMENT" preHint postHint extractSuggestions :: Error -> Maybe [String] extractSuggestions err = case err of Var (VarError _ _ _ suggestions) -> Just suggestions Pattern _ -> Nothing Alias _ -> Nothing Import _ importError -> case importError of ModuleNotFound suggestions -> Just (map Module.nameToString suggestions) ValueNotFound _ suggestions -> Just suggestions Export _ suggestions -> Just suggestions DuplicateExport _ -> Nothing Port _ -> Nothing
johnpmayer/elm-compiler
src/Reporting/Error/Canonicalize.hs
bsd-3-clause
8,254
0
24
2,486
1,845
954
891
185
14
module Main where import Network.Gitit import Control.Monad import Data.Monoid ((<>)) import Text.XHtml hiding (dir, option, value, header) import Happstack.Server.SimpleHTTP import Options.Applicative import System.Directory import qualified System.FilePath as F import System.Posix.Directory (changeWorkingDirectory) data CmdArgs = CmdArgs {cfgPort :: Int ,cfgDir :: String ,cfgIndex :: Bool } cmdargs :: IO CmdArgs cmdargs = execParser opts where opts = info (helper <*> cmdargsP) (fullDesc <> header "gitit-server - Program to run multiple gitit-wikis") cmdargsP = CmdArgs <$> option auto (long "port" <> short 'p' <> metavar "PORT" <> help "Port to listen") <*> strOption (long "dir" <> short 'd' <> metavar "DIR" <> help "Directory where repositories are located") <*> switch (long "no-listing" <> short 'n' <> help "Whether to not show a directory listing") customizeConfig :: Config -> Config customizeConfig conf = conf {pdfExport = True ,defaultExtension = "md"} configRelDir :: Config -> FilePath -> Config configRelDir conf path' = conf {repositoryPath = path' ,pdfExport = True ,defaultExtension = "md" } indexPage :: [FilePath] -> Bool -> ServerPart Response indexPage ds notShowIndex = ok $ toResponse $ if notShowIndex then p << "" else (p << "Wiki index") +++ ulist << map (\path' -> li << hotlink path' << path') ds handlerFor :: Config -> FilePath-> ServerPart Response handlerFor conf path' = dir path' $ wiki conf { repositoryPath = path'} gitit :: Int -> [FilePath] -> Bool-> IO () gitit port' ds index = do conf <- getDefaultConfig let conf' = customizeConfig conf forM_ ds $ \path' -> do let conf'' = conf' {repositoryPath = path'} createRepoIfMissing conf'' createStaticIfMissing conf' createTemplateIfMissing conf' initializeGititState conf' simpleHTTP nullConf {port = port' } $ (nullDir >> indexPage ds index) `mplus` msum (map (handlerFor conf') ds) main :: IO () main = do cfg <- cmdargs let dir' = cfgDir cfg changeWorkingDirectory dir' ds <- getDirectoryContents "." let ds' = filter ( `notElem` [".", "..", "static", "templates"]) ds ds'' <- filterM doesDirectoryExist ds' gitit (cfgPort cfg) ds'' (cfgIndex cfg)
michelk/gitit-server.hs
src/Main.hs
bsd-3-clause
2,452
0
15
630
742
384
358
70
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Mismi.Autoscaling.Core.Data ( ConfigurationName (..) , Configuration (..) , AutoscalingMarket (..) , GroupName (..) , Group (..) , NonEmpty (..) , GroupResult (..) , ScalingInstance (..) , ProtectedFromScaleIn (..) , MinInstances (..) , DesiredInstances (..) , MaxInstances (..) , Capacity (..) , GroupTag (..) , EC2Tag (..) , Propagate (..) , renderMarket , renderSpotPrice , protectedFromScaleInToBool , protectedFromScaleInFromBool , propagateToBool , propagateFromBool , increaseInstances , decreaseInstances ) where import Data.List.NonEmpty (NonEmpty (..)) import Data.Time (UTCTime) import Mismi.EC2.Core.Data import Mismi.IAM.Core.Data import P newtype ConfigurationName = ConfigurationName { renderConfigurationName :: Text } deriving (Eq, Show, Ord) data Configuration = Configuration { configurationName :: !ConfigurationName , configurationImageId :: !ImageId , configurationInstanceType :: !MismiInstanceType , configurationSecurityGroups :: ![SecurityGroupName] , configurationIam :: !IamRole , configurationUserData :: !UserData , configurationMarket :: !AutoscalingMarket } deriving (Eq, Show, Ord) data AutoscalingMarket = OnDemand | Spot !Text deriving (Eq, Show, Ord) renderMarket :: AutoscalingMarket -> Text renderMarket m = case m of OnDemand -> "ondemand" Spot t -> t renderSpotPrice :: AutoscalingMarket -> Maybe Text renderSpotPrice a = case a of OnDemand -> Nothing Spot v -> Just v newtype GroupName = GroupName { renderGroupName :: Text } deriving (Eq, Show, Ord) data Group = Group { groupName :: !GroupName , groupConfigurationName :: !ConfigurationName , groupCapacity :: !Capacity , groupGroupTags :: ![GroupTag] , groupAvailabilityZones :: !(NonEmpty AvailabilityZone) , groupLoadBalancers :: ![LoadBalancer] } deriving (Eq, Show, Ord) data GroupResult = GroupResult { groupResultName :: !GroupName , groupResultConfName :: !ConfigurationName , groupResultCapacity :: !Capacity , groupResultAvailabilityZones :: !(NonEmpty AvailabilityZone) , groupResultLoadBalances :: ![LoadBalancer] , groupResultInstances :: ![ScalingInstance] , groupResultCreationTime :: !UTCTime , groupResultTags :: ![GroupTag] } deriving (Eq, Show) data ScalingInstance = ScalingInstance { scalingInstanceId :: !InstanceId , scalingInstanceProtected :: !ProtectedFromScaleIn , scalingInstanceAvailabilityZone:: !AvailabilityZone } deriving (Eq, Show) data ProtectedFromScaleIn = ProtectedFromScaleIn | NotProtectedFromScaleIn deriving (Eq, Show, Enum, Bounded) protectedFromScaleInToBool :: ProtectedFromScaleIn -> Bool protectedFromScaleInToBool p = case p of ProtectedFromScaleIn -> True NotProtectedFromScaleIn -> False protectedFromScaleInFromBool :: Bool -> ProtectedFromScaleIn protectedFromScaleInFromBool = bool NotProtectedFromScaleIn ProtectedFromScaleIn newtype MinInstances = MinInstances { minInstances :: Int } deriving (Eq, Show, Ord) newtype DesiredInstances = DesiredInstances { desiredInstances :: Int } deriving (Eq, Show, Ord) newtype MaxInstances = MaxInstances { maxInstances :: Int } deriving (Eq, Show, Ord) data Capacity = Capacity { minCapacity :: !MinInstances , desiredCapacity :: !DesiredInstances , maxCapacity :: !MaxInstances } deriving (Eq, Show, Ord) data GroupTag = GroupTag { groupTag :: !EC2Tag , groupTagPropagateAtLaunch :: !Propagate } deriving (Eq, Show, Ord) data Propagate = Propagate | DontPropagate deriving (Eq, Show, Ord, Enum, Bounded) propagateToBool :: Propagate -> Bool propagateToBool p = case p of Propagate -> True DontPropagate -> False propagateFromBool :: Bool -> Propagate propagateFromBool p = case p of True -> Propagate False -> DontPropagate decreaseInstances :: DesiredInstances -> DesiredInstances decreaseInstances d = DesiredInstances $ (desiredInstances d) - 1 increaseInstances :: DesiredInstances -> DesiredInstances increaseInstances d = DesiredInstances $ (desiredInstances d) + 1
ambiata/mismi
mismi-autoscaling-core/src/Mismi/Autoscaling/Core/Data.hs
bsd-3-clause
4,434
0
11
981
1,047
606
441
215
2
---------------------------------------------------------------------------- -- | -- Module : D -- Copyright : (c) Sergey Vinokurov 2016 -- License : BSD3-style (see LICENSE) -- Maintainer : [email protected] -- Created : Sunday, 23 October 2016 ---------------------------------------------------------------------------- module D (FooTyp(..), BarTyp, module C) where import C data FooTyp = Foo Int data BarTyp = Bar Double data BazTyp = Baz String
sergv/tags-server
test-data/0007resolvable_import_cycle/D.hs
bsd-3-clause
479
0
6
84
58
39
19
5
0
module Board where import Util -------------------------------- -- Cell data Cell = Empty | Gray | Red | Yellow | Purple | Green | Blue | Orange | Cyan deriving Eq cellColor :: (Num t) => Cell -> (t, t, t) cellColor cell = case cell of Gray -> (128, 128, 128) Red -> (255, 0, 0) Yellow -> (255, 255, 0) Purple -> (255, 0, 255) Green -> (0, 255, 0) Blue -> (0, 0, 255) Orange -> (255, 128, 0) Cyan -> (0, 255, 255) -------------------------------- -- BlockType data BlockType = BlockI | BlockO | BlockS | BlockZ | BlockJ | BlockL | BlockT blockPattern :: BlockType -> [[Int]] blockPattern BlockI = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] blockPattern BlockO = [[1, 1], [1, 1]] blockPattern BlockS = [[0, 1, 1], [1, 1, 0]] blockPattern BlockZ = [[1, 1, 0], [0, 1, 1]] blockPattern BlockJ = [[0, 0, 0], [1, 1, 1], [1, 0, 0]] blockPattern BlockL = [[0, 0, 0], [1, 1, 1], [0, 0, 1]] blockPattern BlockT = [[0, 0, 0], [1, 1, 1], [0, 1, 0]] blockRotPattern :: BlockType -> Int -> [[Int]] blockRotPattern blktype rot = rotate rot $ blockPattern blktype blockCell :: BlockType -> Cell blockCell BlockI = Red blockCell BlockO = Yellow blockCell BlockS = Purple blockCell BlockZ = Green blockCell BlockJ = Blue blockCell BlockL = Orange blockCell BlockT = Cyan -- 乱数でブロックを選ぶ randBlockType :: IO BlockType randBlockType = fmap (blockTypes !!) (randN (length blockTypes)) blockTypes :: [BlockType] blockTypes = [BlockI, BlockO, BlockS, BlockZ, BlockJ, BlockL, BlockT] -------------------------------- -- Board type Board = [[Cell]] boardWidth :: Int boardWidth = 10 + 2 boardHeight :: Int boardHeight = 20 + 4 emptyLine :: [Cell] emptyLine = [Gray] ++ replicate (boardWidth - 2) Empty ++ [Gray] emptyBoard :: Board emptyBoard = replicate (boardHeight-1) emptyLine ++ [bottom] where bottom = (replicate boardWidth Gray) inBoard :: Int -> Int -> Bool inBoard x y = 0 <= x && x < boardWidth && 0 <= y && y < boardHeight boardRef :: Board -> Int -> Int -> Cell boardRef board x y = if inBoard x y then board !! y !! x else Empty boardSet :: Board -> Int -> Int -> Cell -> Board boardSet board x y c = if inBoard x y then replace board y (replace (board !! y) x c) else board canMove :: Board -> BlockType -> Int -> Int -> Int -> Bool canMove board blktype x y rot = not $ or $ concat $ idxmap2 isHit pat where pat = blockRotPattern blktype rot isHit (_dx,_dy) 0 = False isHit (dx,dy) 1 = inBoard (x+dx) (y+dy) && boardRef board (x+dx) (y+dy) /= Empty storeBlock :: Board -> BlockType -> Int -> Int -> Int -> Board storeBlock board blktype x y rot = board' where pat = blockRotPattern blktype rot patWithIdx = concat $ idxmap2 pair pat board' = foldl store board $ map fst $ filter ((== 1) . snd) patWithIdx store bord (dx,dy) = boardSet bord (x+dx) (y+dy) (blockCell blktype) getFilledLines :: Board -> [Int] getFilledLines board = map fst $ filter (isFilled . snd) $ zip [0..] $ init board where isFilled = all (/= Empty) . init . tail eraseLines :: Board -> [Int] -> Board eraseLines = foldl (\rs y -> replace rs y emptyLine) fallLines :: Board -> [Int] -> Board fallLines = foldl (\rs y -> emptyLine : remove y rs) landingY :: Board -> BlockType -> Int -> Int -> Int -> Int landingY board blktype x y rot = loop y where loop z | canMove board blktype x (z+1) rot = loop (z+1) | otherwise = z graynize :: Board -> Int -> Board graynize board y = replace board y $ map (\x -> if x == Empty then Empty else Gray) $ board !! y
mokehehe/htetris
Board.hs
bsd-3-clause
3,580
36
12
765
1,690
946
744
85
8
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -funbox-strict-fields #-} module Snap.Snaplet.Storage ( HasStore(..) , StoreConfig(..) , htmlStore -- * Types , Store , Dated(..), ModTimes, times -- * Snap integratoin , storeInit , storeUse , storeGet , storeObject -- * IO functions , newStore, updateStore, lookupStore ) where import Control.Applicative import Control.Concurrent import Control.Lens import qualified Data.ByteString as B import qualified Data.Foldable as F import qualified Data.HashMap.Strict as H import Data.IORef import Data.List (isSuffixOf) import qualified Data.Set as Set import Data.String import Data.Time import Snap import System.Directory import System.Directory.Tree newtype Store a = Store { storeObjects :: IORef (H.HashMap B.ByteString (Dated a)) } -- | Instead of storing just the latest time for when something was updated -- , we store every time that a store object was modified. newtype ModTimes = ModTimes { _allModTimes :: Set.Set UTCTime } deriving (Eq, Show) instance Ord ModTimes where compare (ModTimes a) (ModTimes b) | Set.null a && Set.null b = EQ | Set.null a = LT | Set.null b = GT | otherwise = let (a', arem) = Set.deleteFindMax a (b', brem) = Set.deleteFindMax b in case compare a' b' of EQ -> compare arem brem ltGt -> ltGt mergeModTimes :: ModTimes -> ModTimes -> ModTimes mergeModTimes (ModTimes a) (ModTimes b) = ModTimes (Set.union a b) data Dated a = Dated { date :: !ModTimes, object :: !a } deriving (Show, Eq) makeLensesFor [("object", "_object") ,("date", "_date") ] ''Dated makeLenses ''ModTimes -- | A lens from the dates of a 'Dated' object to a (descending) list of -- modification times. times :: Lens' (Dated a) [UTCTime] times = _date . allModTimes . iso Set.toDescList Set.fromList -------------------------------------------------------------------------------- -- Main logic foldTree :: AnchoredDirTree v -> H.HashMap B.ByteString v foldTree = F.foldl' (\h (k,v) -> H.insert (fromString k) v h) H.empty . zipPaths objectTree :: (FilePath -> IO a) -> FilePath -> IO (H.HashMap B.ByteString (Dated a)) objectTree loadObj root = foldTree <$> readDirectoryWith loadDatedObj root where getModTime p = ModTimes . Set.singleton <$> getModificationTime p loadDatedObj p = Dated <$> getModTime p <*> loadObj p data Load a = Load !FilePath | Keep !a deriving (Show, Eq, Ord) findUpdates :: H.HashMap B.ByteString (Dated a) -> H.HashMap B.ByteString (Dated FilePath) -> H.HashMap B.ByteString (Dated (Load a)) findUpdates m0 m1 = H.unionWith (\(Dated t0 o0) (Dated t1 o1) -> if t1 > t0 then Dated (mergeModTimes t0 t1) o1 else Dated t0 o0) -- remove entries not in the new tree, and make them both the same type. (traverse._object %~ Keep $ H.intersection m0 m1) (traverse._object %~ Load $ m1) data Update a = Update { _loaded :: !Int , _kept :: !Int , _rebuilt :: !(H.HashMap B.ByteString (Dated a)) } makeLenses ''Update loadUpdates :: forall f a. (Applicative f, Monad f) => (FilePath -> f (Maybe a)) -> H.HashMap B.ByteString (Dated (Load a)) -> f (Update a) loadUpdates load hmap = execStateT (insertEach hmap) (Update 0 0 H.empty) where insertEach :: H.HashMap B.ByteString (Dated (Load a)) -> StateT (Update a) f () insertEach = itraverse_ $ \key (Dated t a) -> case a of Load k -> do mobj <- lift (load k) case mobj of Just obj -> do loaded += 1 rebuilt %= H.insert key (Dated t obj) Nothing -> return () Keep x -> do kept += 1 rebuilt %= H.insert key (Dated t x) updateStore :: StoreConfig a -> Store a -> IO (Int, Int) updateStore config store = do oldTree <- readIORef (storeObjects store) newTree <- objectTree return (storeRoot config) update <- loadUpdates (readObject config) $! findUpdates oldTree newTree writeIORef (storeObjects store) (_rebuilt update) return (_loaded update, _kept update) newStore :: StoreConfig a -> IO (Store a) newStore config = do objects <- newIORef H.empty let store = Store objects updated <- updateStore config store print updated return store lookupStore :: B.ByteString -> Store a -> IO (Maybe (Dated a)) lookupStore spath store = H.lookup spath <$> readIORef (storeObjects store) -------------------------------------------------------------------------------- -- Snap integration class HasStore b a | b -> a where storeLens :: SnapletLens (Snaplet b) (Store a) data StoreConfig a = StoreConfig { storeRoot :: !FilePath , readObject :: !(FilePath -> IO (Maybe a)) -- | The interval to poll for updates. Measured in seconds. , pollEvery :: !DiffTime -- | How to log messages. , logUpdate :: !(String -> IO ()) } -- | A store for all .html files in the root directory and its ancestors htmlStore :: FilePath -> StoreConfig B.ByteString htmlStore root = StoreConfig { storeRoot = root , readObject = \fs -> if ".html" `isSuffixOf` fs || ".htm" `isSuffixOf` fs then Just <$> B.readFile fs else return Nothing , pollEvery = 60 -- 1 minute , logUpdate = putStrLn } -- | Use a lens on an object in the store. Calls 'pass' if the object isn't -- there. -- -- Example usage: -- -- @ storeUse "things/stuff.html" (times.latest) @ storeUse :: HasStore b a => B.ByteString -- ^ the key to the object -> Getter (Dated a) r -- ^ the lens -> Handler b v r storeUse key l = withTop' storeLens $ do obj <- liftIO . lookupStore key =<< get case obj of Just o -> return (view l o) Nothing -> pass -- | Get the 'Dated' object from some path in the storage. storeGet :: HasStore b a => B.ByteString -> Handler b v (Dated a) storeGet key = storeUse key id -- | Try read the object from the current request's 'rqPathInfo'. storeObject :: HasStore b a => Handler b v (Dated a) storeObject = storeGet =<< getsRequest rqPathInfo storeInit :: HasStore b a => StoreConfig a -> SnapletInit b (Store a) storeInit config = makeSnaplet "store" "Snap store init" Nothing $ do store <- liftIO (newStore config) reloader <- liftIO . forkIO . forever $ do threadDelay $! floor (1000000 * toRational (pollEvery config)) logUpdate config "snaplet-storage: Updating store ..." (l, k) <- updateStore config store logUpdate config $ "snaplet-storage: Loaded objects: " ++ show l logUpdate config $ "snaplet-storage: Kept objects: " ++ show k logUpdate config "snaplet-storage: Done" onUnload (killThread reloader) return store
mikeplus64/snaplet-storage
src/Snap/Snaplet/Storage.hs
bsd-3-clause
7,188
0
22
1,770
2,168
1,108
1,060
-1
-1
{-# LANGUAGE PackageImports #-} -- | -- Module : Crypto.Hash.Whirlpool -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : unknown -- -- A module containing Whirlpool bindings -- module Crypto.Hash.Whirlpool ( Ctx(..) -- * Incremental hashing Functions , init -- :: Ctx , update -- :: Ctx -> ByteString -> Ctx , updates -- :: Ctx -> [ByteString] -> Ctx , finalize -- :: Ctx -> ByteString -- * Single Pass hashing , hash -- :: ByteString -> ByteString , hashlazy -- :: ByteString -> ByteString ) where import Prelude hiding (init) import qualified Data.ByteString.Lazy as L import Data.ByteString (ByteString) import Crypto.Hash.Internal (digestToByteString, digestToByteStringWitness) import qualified "cryptonite" Crypto.Hash as H -- | Whirlpool Context newtype Ctx = Ctx (H.Context H.Whirlpool) -- | init a context init :: Ctx init = Ctx H.hashInit -- | update a context with a bytestring update :: Ctx -> ByteString -> Ctx update (Ctx ctx) d = Ctx $ H.hashUpdate ctx d -- | updates a context with multiples bytestring updates :: Ctx -> [ByteString] -> Ctx updates (Ctx ctx) d = Ctx $ H.hashUpdates ctx d -- | finalize the context into a digest bytestring finalize :: Ctx -> ByteString finalize (Ctx ctx) = digestToByteString $ H.hashFinalize ctx -- | hash a strict bytestring into a digest bytestring hash :: ByteString -> ByteString hash d = digestToByteStringWitness H.Whirlpool $ H.hash d -- | hash a lazy bytestring into a digest bytestring hashlazy :: L.ByteString -> ByteString hashlazy l = digestToByteStringWitness H.Whirlpool $ H.hashlazy l
vincenthz/hs-cryptohash
Crypto/Hash/Whirlpool.hs
bsd-3-clause
1,700
0
8
337
322
190
132
28
1
-- -- Copyright (c) 2009-2011, ERICSSON AB -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} module Feldspar.Core.Frontend.Switch where import Prelude (($),foldr) import Language.Syntactic (resugar,Syntactic(..)) import Feldspar.Core.Frontend.Eq (Eq((==))) import Feldspar.Core.Frontend.Condition ((?)) import Feldspar.Core.Constructs import Feldspar.Core.Constructs.Switch -- | Select between the cases based on the value of the scrutinee. select :: (Eq a, Syntax b) => Data a -> [(Data a, b)] -> b -> b select s cs def = foldr (\(c,a) b -> c == s ? a $ b) def cs {-# DEPRECATED select "select will generate a tree of if-statements. Use switch instead" #-} -- | Select between the cases based on the value of the scrutinee. -- If no match is found return the first argument switch :: (Eq (Internal a), Syntax a, Syntax b) => b -> [(a, b)] -> a -> b switch def [] _ = def switch def cs s = let s' = resugar s in sugarSymF Switch (foldr (\(c,a) b -> resugar c == s' ? a $ b) def cs)
emwap/feldspar-language
src/Feldspar/Core/Frontend/Switch.hs
bsd-3-clause
2,584
0
15
490
349
213
136
17
1
module Graphics.Gnuplot.Private.OS where gnuplotName :: String gnuplotName = "pgnuplot"
kubkon/gnuplot
os/windows/Graphics/Gnuplot/Private/OS.hs
bsd-3-clause
89
0
4
10
18
12
6
3
1
module TimeTableS.LoadFromServer ( loadFaculties , loadGroups , loadDays ) where import Data.Aeson (FromJSON, decode) import Network.HTTP.Conduit (simpleHttp) import TimeTableS.Types import TimeTableS.Utils ((<$$>)) loadFaculties :: IO [Faculty] loadFaculties = do facs <- faculties <$$> getFacultiesRoot case facs of Nothing -> error "Unable to load from server" Just fs -> return fs loadGroups :: Int -> IO [Group] loadGroups fid = do gs <- groups <$$> getGroupsRoot fid case gs of Nothing -> error "Unable to load from server" Just res -> return res loadDays :: String -> IO [WeekDay] loadDays gid = do tt <- getTimetableRoot gid case tt of Just x -> return $ daysTT x Nothing -> error $ "cannot load timetable for gid " ++ gid -------------------------------------------------------------------------------- getJSON :: FromJSON a => String -> IO (Maybe a) getJSON url = decode <$>simpleHttp url getFacultiesRoot :: IO (Maybe FacultiesRoot) getFacultiesRoot = getJSON "http://cist.nure.ua/ias/app/tt/get_faculties" getTimetableRoot :: String -> IO (Maybe TimeTable) getTimetableRoot gid = getJSON ("http://cist.nure.ua/ias/app/tt/get_schedule?group_id=" ++ gid) getGroupsRoot :: Int -> IO (Maybe GroupsRoot) getGroupsRoot fid = getJSON ("http://cist.nure.ua/ias/app/tt/get_groups?faculty_id=" ++ show fid)
zelinskiy/TimeTableS
src/TimeTableS/LoadFromServer.hs
bsd-3-clause
1,387
0
11
251
386
194
192
36
2
{-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {- | Base module for `AntiQuoter`s, defining some basic type-aliases and and combinators for antiquoting. To for examples in the documentation of this library the following data types defining the untyped lambda calculus syntax: @ data Expr = VarE Var | Lam Var Expr | App Expr Expr | AntiExpr String deriving (Typeable, Data) data Var = Var String | AntiVar String deriving (Typeable, Data) @ (note: the idea for using lambda calculus comes from the original paper on quasi-quoting <http://www.eecs.harvard.edu/~mainland/ghc-quasiquoting/mainland07quasiquoting.pdf>) A simple quasi-quoter without support for antiquoting can be defined by: @ lExp = QuasiQuoter { quoteExp = dataToExpQ (const Nothing) . parseExpr , quotePat = dataToPatQ (const Nothing) . parseExpr , quoteType = error \"No type quoter\" , quoteDec = error \"No declaration quoter\" } parseExpr :: String -> Expr parseExpr = undefined -- implementation omitted @ Now to add antiquoting it is needed to treat the AntiExpr and AntiVar constructors as special and translate them ourselves. This introduces an @`AntiQuoterPass` e p@, which is a specific translation rule from source syntax @e@ to template haskell type @p@. In the example this can be used to defined: @ antiExprE :: AntiQuoterPass Expr Exp antiExprE (AntiExpr s) = Just . varE $ mkName s antiExprE _ = Nothing antiVarE :: AntiQuoterPass Var Exp antiVarE (AntiVar s) = Just . varE $ mkName s antiVarE _ = Nothing antiExprP :: AntiQuoterPass Expr Pat antiExprP (AntiExpr s) = Just . varP $ mkName s antiExprP _ = Nothing antiVarP :: AntiQuoterPass Var Pat antiVarP (AntiVar s) = Just . varP $ mkName s antiVarP _ = Nothing @ Both rules should be used when antiquoting as an exception to the base case (using the default translation, @const Nothing@). Which can be done using @(`<>>`)@, creating an `AntiQuoter`. Where an `AntiQuoter` represents a combination of `AntiQuoterPass`es which can be used to antiquote multiple datatypes. In the example this would result in @ lExp = QuasiQuoter { quoteExp = dataToExpQ antiE . parseExpr , quotePat = dataToPatQ antiP . parseExpr , quoteType = error \"No type quoter\" , quoteDec = error \"No declaration quoter\" } where antiE :: AntiQuoter Exp antiE = antiExprE \<>> antiVarE \<>> const Nothing antiP :: AntiQuoter Pat antiP = antiExprP \<>> antiVarP \<>> const Nothing @ Two little improvements could be made, @const Nothing@ could be replaced by `noAntiQuoter` and the building of the `QuasiQuoter` could be simplified by using `mkQuasiQuoter`. -} module Language.Haskell.AntiQuoter.Base( -- * AntiQuoters AntiQuoterPass, AntiQuoter, AQResult, -- ** Using AntiQuoters mkQuasiQuoter, fromPass, noAntiQuoter, (<<>>), (<<>), (<>>), -- ** Convenience reexport -- | WARNING: when combining AntiQuoter(Pass)es using `extQ` only the -- last (rightmost) pass will be used for any source type. The `<<>` -- and `<>>` don't suffer from this problem. extQ, -- ** Internals WrappedAQResult(..), ) where import Control.Monad import Data.Generics import Language.Haskell.TH import Language.Haskell.TH.Quote infixl 1 <<>,<<>> infixr 2 <>> -- | A single antiquotation for a specific source type. Usually @e@ is a type -- from the parsed language and @q@ is the target type (usually `Pat` or -- `Exp`). A @Just result@ indicates that the input should be antiquoted into -- @result@ while @Nothing@ indicates that there is no special antiquotation. type AntiQuoterPass e q = e -> Maybe (Q q) -- Note, `AQResult` is not used as that would lead to too unclear code and -- documentation. -- | Result of an `AntiQuoterPass` (AntiQuoterPass e q = e -> AQResult q). -- This type-alias is mostly used for combinators which only provides the -- result of the antiquotation and the usecase (thus the pattern to match) -- should be filled in by the user. -- -- See `AntiQuoterPass` on what @Nothing@ and @Just@ mean. type AQResult q = Maybe (Q q) -- | Wrapper for `AQResult`, needed for the typechecker. newtype WrappedAQResult q = AQRW { unAQRW :: AQResult q } -- | An `AntiQuoter` is the combination of several `AntiQuoterPass`es, which -- could have different source types. In the example the -- @AntiQuoterPass Expr Exp@ and @AntiQuoterPass Var Exp@ were combined into -- a single @AntiQuoter Exp@, which antiquoted both @Expr@ and @Pat@. type AntiQuoter q = forall e. Typeable e => AntiQuoterPass e q -- | Create an `AntiQuoter` from an single pass. fromPass :: Typeable e => AntiQuoterPass e q -> AntiQuoter q fromPass aqp = mkQ Nothing aqp -- | An `AnitQuoter` that does no antiquoting by only return Nothing, -- -- > noAntiQuoter = const Nothing -- noAntiQuoter :: AntiQuoter q noAntiQuoter = const Nothing -- | Create an `AntiQuoter` by combining an `AntiQuoter` and an -- `AntiQuoterPass`. This is left biased, see (`<<>>`). (<<>) :: Typeable e => AntiQuoter q -> AntiQuoterPass e q -> AntiQuoter q aq <<> aqp = aq <<>> fromPass aqp -- | Create an `AntiQuoter` by combining an `AntiQuoterPass` and an -- `AntiQuoter`. This is left biased, see (`<<>>`). (<>>) :: Typeable e => AntiQuoterPass e q -> AntiQuoter q -> AntiQuoter q aqp <>> aq = fromPass aqp <<>> aq -- | Combines two `AntiQuoter`s with the same result. It is left biased, thus -- if the first antiquoter returns @Just result@ that is used, otherwise the -- second AntiQuoter is tried. -- Together with `noAntiQuoter` this forms a monoid, but as AntiQuoter is a -- type synonyme no instance is declared. (<<>>) :: AntiQuoter q -> AntiQuoter q -> AntiQuoter q aq1 <<>> aq2 = \e -> aq1 e `mplus` aq2 e -- | Create an QuasiQuoter for expressions and patterns from a parser and two -- antiquoters. The quasiquoter from the example could also have been -- constructed by using @mkQuasiQuoter (return . parse) antiE antiP @. mkQuasiQuoter :: Data a => (String -> Q a) -> AntiQuoter Exp -> AntiQuoter Pat -> QuasiQuoter mkQuasiQuoter parse aqExp aqPat = QuasiQuoter { quoteExp = parse >=> dataToExpQ aqExp , quotePat = parse >=> dataToPatQ aqPat -- To prevent warnings #if MIN_VERSION_template_haskell(2,5,0) , quoteType = error $ "Language.Haskell.Antiquoter: can't handle types" , quoteDec = error $ "Language.Haskell.Antiquoter: can't handle decls" #endif }
Laar/antiquoter
src/Language/Haskell/AntiQuoter/Base.hs
bsd-3-clause
6,511
0
9
1,303
522
305
217
41
1
---------------------------------------------------------------------------- -- | -- Module : Dependency -- Copyright : (c) Sergey Vinokurov 2018 -- License : BSD-2 (see LICENSE) -- Maintainer : [email protected] ---------------------------------------------------------------------------- module Dependency where foo :: Int -> Int foo = id data Foo = Foo { bar :: Int , baz :: Double }
sergv/tags-server
test-data/0019field_names/Dependency.hs
bsd-3-clause
414
0
8
75
46
31
15
6
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE UndecidableInstances, OverlappingInstances, FlexibleInstances #-} ----------------------------------------------------------------------------- -- | -- Module : MuTerm.Framework.DotRep -- Copyright : (c) muterm development team -- License : see LICENSE -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : non-portable -- -- ----------------------------------------------------------------------------- module MuTerm.Framework.DotRep ( module MuTerm.Framework.DotRep, module Data.GraphViz.Attributes) where import qualified Data.Graph import Data.GraphViz.Attributes import Data.Graph.Inductive import Data.Graph.Inductive.Tree import Text.PrettyPrint.HughesPJClass import MuTerm.Framework.Proof class DotRep a where dot, dotSimple :: a -> DotGr dotSimple = dot dot = dotSimple -- | Dummy default instance instance Pretty a => DotRep a where dot x = Text (pPrint x) [] type DotGr = DotGrF (Gr [Attribute] [Attribute]) data DotGrF a = Text Doc [Attribute] | Nodes { nodes :: a , legend :: Maybe (Doc,[Attribute]) , attributes :: [Attribute] , incoming, outgoing :: Node} defaultDot x = Text (pPrint x) [] mkColor x = [ColorName x] label l = Label (StrLabel ('\"' : renderDot l ++ "\"")) renderDot :: Doc -> String renderDot = concatMap escapeNewLines . (`shows` "\\l") where escapeNewLines '\n' = "\\l" escapeNewLines c = [c] -- ------------------------ -- *Info constraints -- ------------------------ -- | Dot instance witness data DotInfo instance DotRep p => Info DotInfo p where data InfoConstraints DotInfo p = DotRep p => DotInfo constraints = DotInfo instance DotRep (SomeInfo DotInfo) where dot (SomeInfo p) = withInfoOf p $ \DotInfo -> dot p dotSimple (SomeInfo p) = withInfoOf p $ \DotInfo -> dotSimple p -- Tuple instances instance DotRep (SomeInfo (DotInfo, a)) where dot (SomeInfo (p::p)) = withInfoOf p $ \(DotInfo :^: (_::InfoConstraints a p)) -> dot p dotSimple (SomeInfo (p::p)) = withInfoOf p $ \(DotInfo :^: (_::InfoConstraints a p)) -> dotSimple p instance DotRep (SomeInfo (a,DotInfo)) where dot (SomeInfo (p::p)) = withInfoOf p $ \((x::InfoConstraints a p) :^: DotInfo) -> dot p dotSimple (SomeInfo (p::p)) = withInfoOf p $ \((x::InfoConstraints a p) :^: DotInfo) -> dotSimple p
pepeiborra/muterm-framework
MuTerm/Framework/DotRep.hs
bsd-3-clause
2,566
0
12
513
724
400
324
-1
-1
module System.Build.Access.Group where class Group r where group :: [(String, [String])] -> r -> r getGroup :: r -> [(String, [String])]
tonymorris/lastik
System/Build/Access/Group.hs
bsd-3-clause
168
0
10
52
63
38
25
9
0
module ScrabbleScoreKata.Day2Spec (spec) where import Test.Hspec import ScrabbleScoreKata.Day2 (score) spec :: Spec spec = do it "is zerp when empty input" $ do score "" `shouldBe` 0 it "lowercase letter" $ do score "a" `shouldBe` 1 it "uppercase letter" $ do score "A" `shouldBe` 1 it "valuable letter" $ do score "f" `shouldBe` 4 it "short word" $ do score "at" `shouldBe` 2 it "short, valuable word" $ do score "zoo" `shouldBe` 12 it "medium" $ do score "street" `shouldBe` 6 it "medium, valuable word" $ do score "quirky" `shouldBe` 22 it "long, mixed-case word" $ do score "OxyphenButazone" `shouldBe` 41 it "english-like word" $ do score "pinata" `shouldBe` 8 it "non-english letter is not scored" $ do score "piñata" `shouldBe` 7
Alex-Diez/haskell-tdd-kata
old-katas/test/ScrabbleScoreKata/Day2Spec.hs
bsd-3-clause
986
0
11
370
278
132
146
27
1
module Gvty.Bindings ( onReshape , onInput , onMotion , onIdle , onDisplay ) where import Control.Lens import Control.Monad.State (execState) import Data.IORef import Graphics.UI.GLUT import Gvty.Graphics import Gvty.World onReshape :: IORef World -> ReshapeCallback onReshape world (Size width height) = do viewport $= (Position 0 0, Size x x) world $~! (worldWindowSize .~ over both fromIntegral (x, x)) where x = if width < height then width else height onInput :: IORef World -> KeyboardMouseCallback onInput world key Down _ (Position mx my) = case key of (MouseButton LeftButton) -> world $~! execState (add mx my) _ -> return () onInput world key Up _ (Position mx my) = case key of (MouseButton LeftButton) -> world $~! execState (fire mx my) _ -> return () onMotion :: IORef World -> MotionCallback onMotion world (Position mx my) = world $~! execState (previewNewObj mx my) onIdle :: IORef World -> IdleCallback onIdle world = do time <- get elapsedTime world $~! execState (move time) postRedisplay Nothing
coffeecup-winner/gvty
Gvty/Bindings.hs
bsd-3-clause
1,210
0
11
355
400
204
196
30
3
module Libv1 ( main' ) where -- v1 : Break the problem into two parts: parsing input (rankings) -- and calculating output (results). -- data ---------------------------------------------------- -- >> Ranking information. data Ranking = Ranking { } deriving Show -- >> Result information. data Result = Result { } deriving Show -- parsing ------------------------------------------------- -- >> Take a file and produce a list of team rankings parseRankings :: String -> IO [Ranking] parseRankings = undefined -- calculating --------------------------------------------- -- >> Take teams rankings and calculate results calculateResults :: [Ranking] -> [Result] calculateResults = undefined -- main ---------------------------------------------------- -- Program Entry main' :: IO () main' = undefined
mfine/hs-talks
src/Libv1.hs
bsd-3-clause
826
2
7
133
101
64
37
12
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Ed25519 ( tests -- :: Int -> Tests ) where import Control.Monad import Data.ByteString (ByteString) import qualified Data.ByteString as S import Crypto.Key import Crypto.Sign.Ed25519 import Test.QuickCheck import Util -------------------------------------------------------------------------------- -- Signatures type KP = (PublicKey Ed25519, SecretKey Ed25519) keypairProp :: (KP -> Bool) -> Property keypairProp k = ioProperty $ k `liftM` createKeypair roundtrip :: ByteString -> Property roundtrip xs = keypairProp $ \(pk,sk) -> verify pk (sign sk xs) roundtrip' :: ByteString -> Property roundtrip' xs = keypairProp $ \(pk,sk) -> verify' pk xs (sign' sk xs) -- Generally the signature format is '<signature><original message>' -- and <signature> is of a fixed length (crypto_sign_BYTES), which in -- ed25519's case is 64. sign' drops the message appended at the end, -- so we just make sure we have constant length signatures. signLength :: (ByteString,ByteString) -> Property signLength (xs,xs2) = keypairProp $ \(_,sk) -> let s1 = unSignature $ sign' sk xs s2 = unSignature $ sign' sk xs2 in S.length s1 == S.length s2 -- ed25519 has a sig length of 64 signLength2 :: ByteString -> Property signLength2 xs = keypairProp $ \(_,sk) -> (64 == S.length (unSignature $ sign' sk xs)) tests :: Int -> Tests tests ntests = [ ("ed25519 roundtrip", wrap roundtrip) , ("ed25519 roundtrip #2", wrap roundtrip') , ("ed25519 signature len", wrap signLength) , ("ed25519 signature len #2", wrap signLength2) ] where wrap :: Testable prop => prop -> IO (Bool, Int) wrap = mkArgTest ntests
thoughtpolice/hs-nacl
tests/Ed25519.hs
bsd-3-clause
1,797
0
12
418
452
253
199
37
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fplugin Brisk.Plugin #-} {-# OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-} module Simple03 where import Control.Monad import Control.Distributed.Process import Control.Distributed.Process.SymmetricProcess import Data.Binary import Data.Typeable import GHC.Generics (Generic) import GHC.Base.Brisk main :: SymSet ProcessId -> Process Int main set = do me <- getSelfPid res <- foldM go 0 set return res where go :: Int -> ProcessId -> Process Int go acc x = do send x () msg <- expect :: Process Int case msg of 0 -> return (1 + acc) _ -> return (2 + acc)
abakst/brisk-prelude
examples/Fold00.hs
bsd-3-clause
861
0
14
257
194
102
92
25
2
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad import Data.ByteString.Char8 (ByteString,useAsCString) import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc (alloca) import Foreign.Marshal.Array (withArray) import Foreign.Storable import HROOT main :: IO () main = do ys <- mapM (\x->useAsCString x return) ["test"] withArray ys $ \pargv -> do alloca $ \pargc -> do poke pargc 0 tapp <- newTApplication ("test" :: ByteString) pargc pargv tcanvas <- newTCanvas ("Test" :: ByteString) ("Test" :: ByteString) 640 480 h2 <- newTH2F ("test" :: ByteString) ("test" :: ByteString) 100 (-5.0) 5.0 100 (-5.0) 5.0 trandom <- newTRandom 65535 let dist1 = gaus trandom 0 2 dist2 = gaus trandom 0 2 let go n | n < 0 = return () | otherwise = do histfill dist1 dist2 h2 go (n-1) go 1000000 draw h2 ("lego" :: ByteString) run tapp 1 delete h2 delete tcanvas delete trandom delete tapp histfill :: IO CDouble -> IO CDouble-> TH2F -> IO () histfill dist1 dist2 hist = do x <- dist1 y <- dist2 fill2 hist x y return ()
wavewave/HROOT
HROOT-generate/template/HROOT/example/random2dApp.hs
gpl-3.0
1,242
0
23
365
459
225
234
39
1
{-# LANGUAGE OverloadedStrings #-} -- Module : Test.AWS.CloudTrail -- Copyright : (c) 2013-2015 Brendan Hay -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Test.AWS.CloudTrail ( tests , fixtures ) where import Network.AWS.CloudTrail import Test.AWS.Gen.CloudTrail import Test.Tasty tests :: [TestTree] tests = [] fixtures :: [TestTree] fixtures = []
fmapfmapfmap/amazonka
amazonka-cloudtrail/test/Test/AWS/CloudTrail.hs
mpl-2.0
752
0
5
201
73
50
23
11
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -Wall #-} {-| Fortran AST annotations used for Hoare logic checking. -} module Camfort.Specification.Hoare.Annotation where import Data.Data import Control.Lens import qualified Language.Fortran.Analysis as F import qualified Language.Fortran.AST as F import qualified Camfort.Analysis.Annotations as Ann import Camfort.Analysis.CommentAnnotator import Camfort.Specification.Hoare.Syntax -- | Annotations meant to appear on the main annotated program's AST. type HA = F.Analysis (HoareAnnotation Ann.A) -- | Annotations meant to appear on the AST inside those Fortran expressions -- that have been parsed from inside logical expression annotations. type InnerHA = F.Analysis Ann.A data HoareAnnotation a = HoareAnnotation { _hoarePrevAnnotation :: a , _hoareSod :: Maybe (SpecOrDecl InnerHA) -- ^ A @static_assert@ specification or @decl_aux@ declaration. , _hoarePUName :: Maybe F.ProgramUnitName -- ^ The name of the program unit that the spec or decl is attached to. } deriving (Show, Eq, Typeable, Data) makeLenses ''HoareAnnotation instance Linkable HA where link ann _ = ann linkPU ann pu = Ann.onPrev (hoarePUName .~ Just (F.puName pu)) ann instance ASTEmbeddable HA (SpecOrDecl InnerHA) where annotateWithAST ann ast = Ann.onPrev (hoareSod .~ Just ast) ann hoareAnn0 :: a -> HoareAnnotation a hoareAnn0 x = HoareAnnotation { _hoarePrevAnnotation = x, _hoareSod = Nothing, _hoarePUName = Nothing }
dorchard/camfort
src/Camfort/Specification/Hoare/Annotation.hs
apache-2.0
1,770
0
12
356
308
179
129
32
1