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
-- | -- Examples in various locations... -- -- Some random text. Some random text. Some random text. Some random text. -- Some random text. Some random text. Some random text. Some random text. -- Some random text. -- -- >>> let x = 10 -- -- Some random text. Some random text. Some random text. Some random text. -- Some random text. Some random text. Some random text. Some random text. -- Some random text. -- -- -- >>> baz -- "foobar" module Foo ( -- | Some documentation not attached to a particular Haskell entity -- -- >>> test 10 -- *** Exception: Prelude.undefined test, -- | -- >>> fib 10 -- 55 fib, -- | -- >>> bar -- "bar" bar ) where -- | My test -- -- >>> test 20 -- *** Exception: Prelude.undefined test :: Integer -> Integer test = undefined -- | Note that examples for 'fib' include the two examples below -- and the one example with ^ syntax after 'fix' -- >>> foo -- "foo" {- | Example: >>> fib 10 55 -} -- | Calculate Fibonacci number of given `n`. fib :: Integer -- ^ given `n` -- -- >>> fib 10 -- 55 -> Integer -- ^ Fibonacci of given `n` -- -- >>> baz -- "foobar" fib 0 = 0 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) -- ^ Example: -- -- >>> fib 5 -- 5 foo = "foo" bar = "bar" baz = foo ++ bar
beni55/doctest-haskell
tests/integration/testCommentLocation/Foo.hs
mit
1,392
0
8
434
153
106
47
14
1
{-# LANGUAGE Arrows #-} module Agent ( sugAgent ) where import Control.Monad.Random import Control.Monad.State.Strict import FRP.BearRiver import Common import Environment import Discrete import Model import Random import Utils ------------------------------------------------------------------------------------------------------------------------ sugAgent :: RandomGen g => Bool -> AgentId -> SugAgentState -> SugAgent g sugAgent rebirthFlag aid s0 = feedback s0 (proc (ain, s) -> do age <- time -< () (ao, s') <- arrM (\(age, ain, s) -> lift $ runStateT (chapterII rebirthFlag aid ain age) s) -< (age, ain, s) returnA -< (ao, s')) updateAgentState :: RandomGen g => (SugAgentState -> SugAgentState) -> StateT SugAgentState (SugAgentMonad g) () updateAgentState = modify observable :: RandomGen g => StateT SugAgentState (SugAgentMonad g) (SugAgentOut g) observable = get >>= \s -> return $ agentOutObservable $ sugObservableFromState s ------------------------------------------------------------------------------------------------------------------------ -- Chapter II: Life And Death On The Sugarscape ------------------------------------------------------------------------------------------------------------------------ chapterII :: RandomGen g => Bool -> AgentId -> SugAgentIn -> Time -> StateT SugAgentState (SugAgentMonad g) (SugAgentOut g) chapterII rebirthFlag aid _ain _age = do ao <- agentMetabolism ifThenElse (isDead ao) (if rebirthFlag then do (newAid, newA) <- birthNewAgent rebirthFlag return $ newAgent newAid newA ao else return ao) (do agentMove aid ao' <- observable return $ ao <°> ao') agentMetabolism :: RandomGen g => StateT SugAgentState (SugAgentMonad g) (SugAgentOut g) agentMetabolism = do sugarMetab <- gets sugAgSugarMetab sugarLevel <- gets sugAgSugarLevel let newSugarLevel = max 0 (sugarLevel - sugarMetab) updateAgentState (\s' -> s' { sugAgSugarLevel = newSugarLevel }) ifThenElseM starvedToDeath agentDies (return agentOut) where starvedToDeath :: RandomGen g => StateT SugAgentState (SugAgentMonad g) Bool starvedToDeath = do sugar <- gets sugAgSugarLevel return $ sugar <= 0 agentDies :: RandomGen g => StateT SugAgentState (SugAgentMonad g) (SugAgentOut g) agentDies = do env <- lift readEnvironment env' <- unoccupyPosition env lift $ writeEnvironment env' return $ kill agentOut birthNewAgent :: RandomGen g => Bool -> StateT SugAgentState (SugAgentMonad g) (AgentId, SugAgent g) birthNewAgent rebirthFlag = do env <- lift readEnvironment newAid <- lift nextAgentId (newCoord, newCell) <- agentCellOnCoord env (newA, newAState) <- lift $ lift $ randomAgent (newAid, newCoord) (sugAgent rebirthFlag) id -- need to occupy the cell to prevent other agents to occupy it before the spawning of the agent let newCell' = newCell { sugEnvOccupier = Just (cellOccupier newAid newAState) } env' = changeCellAt newCoord newCell' env lift $ writeEnvironment env' return (newAid, newA) agentMove :: RandomGen g => AgentId -> StateT SugAgentState (SugAgentMonad g) () agentMove aid = do env <- lift readEnvironment cellsInSight <- agentLookout env coord <- gets sugAgCoord let unoccupiedCells = filter (cellUnoccupied . snd) cellsInSight ifThenElse (null unoccupiedCells) (do env' <- agentHarvestCell coord env lift $ writeEnvironment env') (do -- NOTE included self but this will be always kicked out because self is occupied by self, need to somehow add this -- what we want is that in case of same sugar on all fields (including self), the agent does not move because staying is the lowest distance (=0) let selfCell = cellAt coord env let unoccupiedCells' = (coord, selfCell) : unoccupiedCells let bf = bestCellFunc let bestCells = selectBestCells bf coord unoccupiedCells' (cellCoord, _) <- lift $ lift $ randomElemM bestCells env' <- agentHarvestCell cellCoord env env'' <- agentMoveTo aid cellCoord env' lift $ writeEnvironment env'') ------------------------------------------------------------------------------ -- ALL FUNCTIONS BELOW TAKE AN ENVIRONMENT AND MAY RETURN AN ENVIRONMENT agentLookout :: RandomGen g => SugEnvironment -> StateT SugAgentState (SugAgentMonad g) [(Discrete2dCoord, SugEnvCell)] agentLookout env = do vis <- gets sugAgVision coord <- gets sugAgCoord return $ neighboursInNeumannDistance coord vis False env unoccupyPosition :: RandomGen g => SugEnvironment -> StateT SugAgentState (SugAgentMonad g) SugEnvironment unoccupyPosition env = do (coord, cell) <- agentCellOnCoord env let cell' = cell { sugEnvOccupier = Nothing } env' = changeCellAt coord cell' env return env' agentCellOnCoord :: RandomGen g => SugEnvironment -> StateT SugAgentState (SugAgentMonad g) (Discrete2dCoord, SugEnvCell) agentCellOnCoord env = do coord <- gets sugAgCoord let cell = cellAt coord env return (coord, cell) agentMoveTo :: RandomGen g => AgentId -> Discrete2dCoord -> SugEnvironment -> StateT SugAgentState (SugAgentMonad g) SugEnvironment agentMoveTo aid cellCoord env = do env' <- unoccupyPosition env updateAgentState (\s -> s { sugAgCoord = cellCoord }) s <- get let cell = cellAt cellCoord env' co = cell { sugEnvOccupier = Just (cellOccupier aid s) } env'' = changeCellAt cellCoord co env' return env'' agentHarvestCell :: RandomGen g => Discrete2dCoord -> SugEnvironment -> StateT SugAgentState (SugAgentMonad g) SugEnvironment agentHarvestCell cellCoord env = do let cell = cellAt cellCoord env sugarLevelAgent <- gets sugAgSugarLevel let sugarLevelCell = sugEnvSugarLevel cell let newSugarLevelAgent = sugarLevelCell + sugarLevelAgent updateAgentState (\s -> s { sugAgSugarLevel = newSugarLevelAgent }) let cellHarvested = cell { sugEnvSugarLevel = 0.0 } env' = changeCellAt cellCoord cellHarvested env return env'
thalerjonathan/phd
thesis/code/concurrent/sugarscape/SugarScapeSTMTVar/src/Agent.hs
gpl-3.0
6,856
49
17
1,949
1,562
797
765
154
2
module ExprDoLetShadowVar where main :: Int main = unsafePerformIO main_ main_ :: IO Int main_ = do { let { x :: a; x = x main } ; let { x :: Int; x = 1 } ; return x}
roberth/uu-helium
test/staticwarnings/ExprDoLetShadowVar.hs
gpl-3.0
170
0
10
44
77
44
33
5
1
{-# LANGUAGE NamedFieldPuns, RecordWildCards #-} module RecordReadRef where {-# ANN module "HLint: ignore Eta reduce" #-} -- TODO(robinpalotai): define and refer separate bindings for accessors. Maybe -- add an option to choose if the bindings will overlap, or if one should go -- on the ::s. So can be switched depending on overlap support from tools. -- Or this can just be a hint to the frontend (assuming backend provides the -- alternative span). -- - @foo defines/binding FieldFoo -- - @bar defines/binding FieldBar -- - @#1Rec defines/binding CtorR data Rec = Rec { foo :: Int, bar :: Int } -- No field references here, only to the introduced local binding (see -- DataRef.hs for more comments). unpack (Rec f b) = f -- - @foo ref FieldFoo access r = foo r -- TODO(robinpalotai): revamp record references, and omit field refs originating -- from wildcard locations (since they are not explicit references?) Also -- elaborate this section here (AST vs interpretation). What does this being -- a syntactic sugar imply? -- TODO(robinpalotai): maybe fix the spans of the wildcard matches to only the -- double-dots. -- - @Rec ref CtorR -- - @"Rec{..}" ref FieldFoo -- - @"Rec{..}" ref FieldBar -- - @foo ref FieldFoo wildcard Rec{..} = foo -- - @foo ref FieldFoo punned Rec{foo} = -- - @foo ref FieldFoo foo -- - @foo ref FieldFoo -- - @baz defines/binding VarBaz reassigned Rec{foo=baz} = -- - @baz ref VarBaz baz -- - @bar ref FieldBar -- - @"Rec{bar,..}" ref FieldFoo rightWild Rec{bar,..} = -- - @foo ref FieldFoo -- - @bar ref FieldBar foo + bar
robinp/haskell-indexer
kythe-verification/testdata/basic/RecordReadRef.hs
apache-2.0
1,603
0
8
319
150
95
55
13
1
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleContexts #-} -- |Functions and types for working with Google Chrome extensions. module Test.WebDriver.Chrome.Extension ( ChromeExtension , loadExtension , loadRawExtension ) where import Data.ByteString.Lazy as LBS import Data.ByteString.Base64.Lazy as B64 import Data.Text.Lazy import Data.Text.Lazy.Encoding (decodeLatin1) import Data.Aeson import Control.Applicative import Control.Monad.Base -- |An opaque type representing a Google Chrome extension. Values of this type -- are passed to the 'Test.Webdriver.chromeExtensions' field. newtype ChromeExtension = ChromeExtension Text deriving (Eq, Show, Read, ToJSON, FromJSON) -- |Load a .crx file as a 'ChromeExtension'. loadExtension :: MonadBase IO m => FilePath -> m ChromeExtension loadExtension path = liftBase $ loadRawExtension <$> LBS.readFile path -- |Load raw .crx data as a 'ChromeExtension'. loadRawExtension :: ByteString -> ChromeExtension loadRawExtension = ChromeExtension . decodeLatin1 . B64.encode
plow-technologies/hs-webdriver
src/Test/WebDriver/Chrome/Extension.hs
bsd-3-clause
1,072
0
7
176
173
104
69
18
1
module Distribution.Utils.NubList ( NubList -- opaque , toNubList -- smart construtor , fromNubList , overNubList , NubListR , toNubListR , fromNubListR , overNubListR ) where import Distribution.Compat.Binary import Data.Monoid import Prelude import Distribution.Simple.Utils (ordNub, listUnion, ordNubRight, listUnionRight) import qualified Text.Read as R -- | NubList : A de-duplicated list that maintains the original order. newtype NubList a = NubList { fromNubList :: [a] } deriving Eq -- NubList assumes that nub retains the list order while removing duplicate -- elements (keeping the first occurence). Documentation for "Data.List.nub" -- does not specifically state that ordering is maintained so we will add a test -- for that to the test suite. -- | Smart constructor for the NubList type. toNubList :: Ord a => [a] -> NubList a toNubList list = NubList $ ordNub list -- | Lift a function over lists to a function over NubLists. overNubList :: Ord a => ([a] -> [a]) -> NubList a -> NubList a overNubList f (NubList list) = toNubList . f $ list -- | Monoid operations on NubLists. -- For a valid Monoid instance we need to satistfy the required monoid laws; -- identity, associativity and closure. -- -- Identity : by inspection: -- mempty `mappend` NubList xs == NubList xs `mappend` mempty -- -- Associativity : by inspection: -- (NubList xs `mappend` NubList ys) `mappend` NubList zs -- == NubList xs `mappend` (NubList ys `mappend` NubList zs) -- -- Closure : appending two lists of type a and removing duplicates obviously -- does not change the type. instance Ord a => Monoid (NubList a) where mempty = NubList [] mappend (NubList xs) (NubList ys) = NubList $ xs `listUnion` ys instance Show a => Show (NubList a) where show (NubList list) = show list instance (Ord a, Read a) => Read (NubList a) where readPrec = readNubList toNubList -- | Helper used by NubList/NubListR's Read instances. readNubList :: (Read a) => ([a] -> l a) -> R.ReadPrec (l a) readNubList toList = R.parens . R.prec 10 $ fmap toList R.readPrec -- | Binary instance for 'NubList a' is the same as for '[a]'. For 'put', we -- just pull off constructor and put the list. For 'get', we get the list and -- make a 'NubList' out of it using 'toNubList'. instance (Ord a, Binary a) => Binary (NubList a) where put (NubList l) = put l get = fmap toNubList get -- | NubListR : A right-biased version of 'NubList'. That is @toNubListR -- ["-XNoFoo", "-XFoo", "-XNoFoo"]@ will result in @["-XFoo", "-XNoFoo"]@, -- unlike the normal 'NubList', which is left-biased. Built on top of -- 'ordNubRight' and 'listUnionRight'. newtype NubListR a = NubListR { fromNubListR :: [a] } deriving Eq -- | Smart constructor for the NubListR type. toNubListR :: Ord a => [a] -> NubListR a toNubListR list = NubListR $ ordNubRight list -- | Lift a function over lists to a function over NubListRs. overNubListR :: Ord a => ([a] -> [a]) -> NubListR a -> NubListR a overNubListR f (NubListR list) = toNubListR . f $ list instance Ord a => Monoid (NubListR a) where mempty = NubListR [] mappend (NubListR xs) (NubListR ys) = NubListR $ xs `listUnionRight` ys instance Show a => Show (NubListR a) where show (NubListR list) = show list instance (Ord a, Read a) => Read (NubListR a) where readPrec = readNubList toNubListR
trskop/cabal
Cabal/Distribution/Utils/NubList.hs
bsd-3-clause
3,406
0
9
685
751
412
339
47
1
{-# LANGUAGE TemplateHaskell #-} module Skell.Buffer where import Control.Lens import Control.Monad.State import Data.Default --import Yi.Rope (YiString) --import qualified Yi.Rope as YS -- | TODO: data Buffer = Buffer { _filepath :: String , _content :: String , _cursor :: Int } deriving (Show) instance Default Buffer where def = Buffer "**none**" "" 0 makeLenses ''Buffer -- | Tipo intermedio para facilitar la ejecucion de varias operaciones sobre -- el buffer type BufferM a = State Buffer a insertStr :: String -> BufferM () insertStr str = modify $ insertStr_ str -- deleteChar :: BufferM () -- deleteChar = modify deleteChar_ moveLeft :: BufferM () moveLeft = modify moveLeft_ moveRight :: BufferM () moveRight = modify moveRight_ insertStr_ :: String -> Buffer -> Buffer insertStr_ new (Buffer n str pos) = Buffer n (concat [before, new,after]) (pos+length new) where (before,after) = splitAt pos str -- deleteChar_ :: Buffer -> Buffer -- deleteChar_ b@(Buffer _ _ 0) = b -- deleteChar_ (Buffer n str pos) = case init before of -- Just before' -> Buffer n (concat [before', after]) (pos-1) -- Nothing -> Buffer n (concat [before, after]) (pos-1) -- where (before,after) = splitAt pos str moveLeft_ :: Buffer -> Buffer moveLeft_ b@(Buffer n str pos) | pos==0 = b | otherwise = Buffer n str (pos-1) moveRight_ :: Buffer -> Buffer moveRight_ b@(Buffer n str pos) | pos==length str = b | otherwise = Buffer n str (pos+1)
damianfral/Skell
src/Skell/Buffer.hs
bsd-3-clause
1,623
0
9
433
388
208
180
31
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Application ( makeApplication , getApplicationDev , makeFoundation ) where import Import import Settings import Yesod.Auth import Yesod.Default.Config import Yesod.Default.Main import Yesod.Default.Handlers import Handler.Main import Handler.CRUD.Parts import Network.Wai.Middleware.RequestLogger import qualified Database.Persist import Database.Persist.Sql (runMigration) import Network.HTTP.Conduit (newManager, def) import Control.Monad.Logger (runLoggingT) import System.IO (stdout) import System.Log.FastLogger (mkLogger) -- Import all relevant handler modules here. -- Don't forget to add new modules to your cabal file! import Handler.Home -- This line actually creates our YesodDispatch instance. It is the second half -- of the call to mkYesodData which occurs in Foundation.hs. Please see the -- comments there for more details. mkYesodDispatch "App" resourcesApp -- This function allocates resources (such as a database connection pool), -- performs initialization and creates a WAI application. This is also the -- place to put your migrate statements to have automatic database -- migrations handled by Yesod. makeApplication :: AppConfig DefaultEnv Extra -> IO Application makeApplication conf = do foundation <- makeFoundation conf -- Initialize the logging middleware logWare <- mkRequestLogger def { outputFormat = if development then Detailed True else Apache FromSocket , destination = Logger $ appLogger foundation } -- Create the WAI application and apply middlewares app <- toWaiAppPlain foundation return $ logWare app -- | Loads up any necessary settings, creates your foundation datatype, and -- performs some initialization. makeFoundation :: AppConfig DefaultEnv Extra -> IO App makeFoundation conf = do manager <- newManager def s <- staticSite dbconf <- withYamlEnvironment "config/mysql.yml" (appEnv conf) Database.Persist.loadConfig >>= Database.Persist.applyEnv p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf) logger <- mkLogger True stdout let foundation = App conf s p manager dbconf logger -- Perform database migration using our application's logging settings. runLoggingT (Database.Persist.runPool dbconf (runMigration migrateAll) p) (messageLoggerSource foundation logger) return foundation -- for yesod devel getApplicationDev :: IO (Int, Application) getApplicationDev = defaultDevelApp loader makeApplication where loader = Yesod.Default.Config.loadConfig (configSettings Development) { csParseExtra = parseExtra }
smurphy8/backoffice
Application.hs
bsd-3-clause
2,750
0
12
539
474
258
216
-1
-1
import Root.B(foo) import Root.C(bar) main = do putStrLn "Hello Haskell World!" foo bar
codeboardio/mantra
test/test_resources/haskell/hs_several_files/Root/Main.hs
mit
96
0
7
21
38
19
19
6
1
{-# LANGUAGE DeriveGeneric #-} module Auto.G.D where import Control.DeepSeq import Data.Aeson import GHC.Generics (Generic) import Options data D a = Nullary | Unary Int | Product String Char a | Record { testOne :: Double , testTwo :: Bool , testThree :: D a } deriving (Show, Eq, Generic) instance NFData a => NFData (D a) where rnf Nullary = () rnf (Unary n) = rnf n rnf (Product s c x) = s `deepseq` c `deepseq` rnf x rnf (Record a b y) = a `deepseq` b `deepseq` rnf y instance ToJSON a => ToJSON (D a) where toJSON = genericToJSON opts toEncoding = genericToEncoding opts instance FromJSON a => FromJSON (D a) where parseJSON = genericParseJSON opts type T = D (D (D ())) d :: T d = Record { testOne = 1234.56789 , testTwo = True , testThree = Product "Hello World!" 'a' Record { testOne = 9876.54321 , testTwo = False , testThree = Product "Yeehaa!!!" '\n' Nullary } }
dmjio/aeson
benchmarks/bench/Auto/G/D.hs
bsd-3-clause
1,142
0
10
432
361
198
163
33
1
module ParseProgram where import HsModule import HsConstants(prelude_mod) import SrcLoc(loc0) --import HsName import NamesEntities import ParseMonad(parseFile) import Unlit(readHaskellFile) import ParserOptions import WorkModule(analyzeModules,WorkModuleI(..)) import PPModules import TypedIds(NameSpace(..),IdTy(..),namespace) import ReAssoc(getInfixes) import ReAssocModule --import ReAssocBaseStruct -- instance for HsModule import MUtils((@@),( # ), mapFst) import Lift -- Parse a program, analyze module dependencies and adjust infix -- applications in accordance with operator precedences: -- parseProgram :: ... => PM (HsModule ds) -> [FilePath] -> -- ([[HsModule ds]],[(Module,WorkModule)]) parseProgram files = parseProgram' flags0 files parseProgram' flags parseMod files = rewriteProgram # analyzeFiles' flags parseMod files analyzeFiles parseMod = analyzeFiles' flags0 parseMod analyzeFiles' flags parseMod = lift . analyzeModules'' (prel flags) @@ parseSourceFiles (cpp flags) parseMod analyzeModules' x = analyzeModules'' True x analyzeModules'' prel x = analyzeModules . map (optAddPrelude prel) $x parseSourceFiles cpp parseMod = mapM (parseSourceFile cpp parseMod) parseSourceFile cpp parseMod path = parseFile parseMod path =<< readHaskellFile cpp path rewriteProgram (modss,wms) = ((map.map) reAssocMod modss,wms) where origOps = (concatMap.map) infixDecls modss infixDecls mod = (hsModName mod,mapFst getQualified (getInfixes mod)) reAssocMod mod = reAssocModule wm origOps mod where Just wm = lookup (hsModName mod) wms
forste/haReFork
tools/base/ParseProgram.hs
bsd-3-clause
1,609
0
11
249
408
222
186
-1
-1
module Classes where class Foo f where bar :: f a -> f b -> f (a, b) baz :: f () baz = undefined class Quux q where (+++), (///) :: q -> q -> q (***), logBase :: q -> q -> q foo, quux :: q -> q -> q
Helkafen/haddock
hoogle-test/src/classes/Classes.hs
bsd-2-clause
230
0
10
84
116
66
50
-1
-1
{-# LANGUAGE PolyKinds, DataKinds, TypeFamilies, GADTs, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, ExistentialQuantification #-} module T6068 where import Prelude hiding (Maybe, Nothing) data Maybe :: * -> * where Nothing :: Maybe a data family Sing (a :: k) data instance Sing (a :: Maybe k) where SNothing :: Sing Nothing data KProxy (a :: *) = KProxy data Existential (p :: KProxy k) = forall (a :: k). Exists (Sing a) class HasSingleton a (kp :: KProxy k) | a -> kp where exists :: a -> Existential kp class Floop a b | a -> b instance forall a (mp :: KProxy (Maybe ak)). Floop a mp => HasSingleton (Maybe a) mp where exists Nothing = Exists SNothing -- instance forall (a ::*) (mp :: KProxy (Maybe ak)). HasSingleton (Maybe ak) (Maybe a) mp where -- exists Nothing = Exists SNothing
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/polykinds/T6068.hs
bsd-3-clause
868
0
10
176
235
134
101
-1
-1
-- !!! Importing Class with duplicate member module M where import Prelude(Eq((==),(/=),(==)))
siddhanathan/ghc
testsuite/tests/module/mod93.hs
bsd-3-clause
96
0
6
13
27
22
5
2
0
{-| A Flappy bird/ helicopter game clone -} module Flappy where import FRP.Helm import qualified FRP.Helm.Time as Time import qualified FRP.Helm.Text as Text import qualified FRP.Helm.Window as Window import qualified FRP.Helm.Keyboard as Keys import qualified FRP.Helm.Sample as S import Control.Concurrent import Control.Concurrent.STM import System.IO.Unsafe import Data.List -- MODEL data GameObject = Character { y :: Double, energy :: Double, active :: Bool} | Obstacle { x :: Double, y :: Double, which :: Int} | TextBox { i :: Int} -- | VolChan { c :: TVar Double, -- io :: ()}--should be an IO to execute somewhere else bird = Character 300 750 True obs1 = Obstacle 800 350 1 obs2 = Obstacle 1200 200 3 obs3 = Obstacle 1450 200 5 score = TextBox 0 allObs = [obs1,obs2,obs3] obsPositions = cycle $ concat $ permutations [130,433,300,210,540,500,200,450,333,100,400] -- UPDATE step :: (Time,[Bool]) -> [GameObject] -> [GameObject] step keys cs = map (update keys) cs update :: (Time,[Bool]) -> GameObject -> GameObject update (t,keys) (Character y e a) | a == False = Character y e a | y > 550 = Character (550) e True | y < 0 = Character (0) e True | e > 751 = Character (y+1.5) (750) True | e < 0 = Character (y+1.5) (0) True | keys!!0 == True = Character (y-3) (e-3) True | keys!!1 == True = Character (y+6) (e+1.5) True | keys!!0 == False = Character (y+1.5) (e+1.5) True update (t,keys) (Obstacle x y w) | x < 0 = Obstacle (800) (obsPositions!!w) (w+1) | x >= 0 = Obstacle (x-(fromIntegral w/5)-5) y w update (t,keys) (TextBox i) = TextBox $ i+1 --update (t,keys) (VolChan v ()) -- | keys!!0 == True = VolChan v (unsafePerformIO $ atomically $ writeTVar v 0) -- | keys!!1 == True = VolChan v (unsafePerformIO $ atomically $ writeTVar v 1) -- | keys!!0 == False = VolChan v (unsafePerformIO $ atomically $ writeTVar v 1) -- DISPLAY --need to scale to windows dimensions render :: [GameObject] -> (Int,Int) -> Element render cs (w,h) = collage w h $ concat (map my_collage cs) my_collage :: GameObject -> [Form] my_collage (Character y e a) = (healthBar e) ++ (player y) my_collage (Obstacle x y w) = obs x y w my_collage (TextBox i) = [move (300,9) $ toForm $ Text.text $ Text.color white $ Text.toText $ "Score: "++show i] --my_collage (VolChan _ _) = [] healthBar :: Double -> [Form] healthBar e = [rect ((*2) $ e) 35 |> filled green] player y = [move (400, y) $ toForm $ image 50 50 "player.png"] obs x y w = [move (x,y) $ filled red $ rect 25 100] -- INPUT runAt c s = let x = lift2 (,) c s in lift snd x getKeys= [(Keys.isDown Keys.SpaceKey), (Keys.isDown Keys.FKey)] input :: Signal (Time,[Bool]) input = Time.timestamp $ runAt (Time.fps 60) $ combine getKeys {-| Bootstrap the game. -} flap :: TVar Double -> IO () flap v = do run config $ render <~ stepper ~~ Window.dimensions where config = defaultConfig { windowTitle = "Helm - Flappy" } stepper = foldp step ([bird]++allObs++[score]) input --stepper = foldp step ([bird]++allObs++[score]++[VolChan v ()]) input flap' :: IO () flap' = do run config $ render <~ stepper ~~ Window.dimensions where config = defaultConfig { windowTitle = "Helm - Flappy" } stepper = foldp step ([bird]++allObs++[score]) input main :: IO() main = do v <- newTVarIO 0.2 flap v
santolucito/Euterpea_Projects
Parallel/flappy.hs
mit
3,561
1
13
906
1,361
734
627
70
1
{-# LANGUAGE RecordWildCards, TupleSections #-} -- | -- This module contains the graph-related checks of a proof, i.e. no cycles; -- local assumptions used properly. module ShapeChecks ( findCycles , findEscapedHypotheses , findUnconnectedGoals , findUsedConnections , calculateScopes ) where import qualified Data.IntMap as IM import qualified Data.Map as M import qualified Data.IntSet as IS import qualified Data.Set as S import Data.Map ((!)) import Data.Maybe -- import Debug.Trace import Types import ProofGraph findCycles :: Graph -> [Cycle] findCycles graph = [ mapMaybe (toConnKey graph) cycle | blockNode <- M.elems (blockNodes graph) , cycle <- calcCycle blockNode (localHypNodes graph) ] findEscapedHypotheses :: Context -> Proof -> Graph -> [Path] findEscapedHypotheses ctxt proof graph = [ mapMaybe (toConnKey graph) path | (blockKey, block) <- M.toList $ blocks proof , let rule = block2Rule ctxt block , (portKey, Port (PTLocalHyp consumedBy) _ _) <- M.toList (ports rule) , let startNodes = (blockNodes graph ! blockKey) : conclusionNodes graph , let targetNode = inPortNodes graph ! BlockPort blockKey consumedBy , let hypPortSpec = BlockPort blockKey portKey , let hypNode = outPortNodes graph ! hypPortSpec , nonScope <- [ calcNonScope startNode (localHypNodes graph) (IS.singleton (nodeUniq targetNode)) | startNode <- startNodes] , Just path <- return $ IM.lookup (nodeUniq hypNode) nonScope ] findUsedConnections :: Graph -> S.Set (Key Connection) findUsedConnections graph = S.fromList $ mapMaybe (toConnKey graph) $ backwardsSlice (conclusionNodes graph) findUnconnectedGoals :: Graph -> [PortSpec] findUnconnectedGoals graph = filter isUnconnected $ mapMaybe (toInPortKey graph) $ backwardsSlice (conclusionNodes graph) where -- An unconneced port might have predecessors (the a connection), but that -- would be dangling. See #63. isUnconnected pk = all (null . nodePred) (nodePred n) where n = inPortNodes graph ! pk type Scope = ([Key Block], PortSpec) calculateScopes :: Context -> Proof -> Graph -> [Scope] calculateScopes ctxt proof graph = [ (,ps) $ mapMaybe (toBlockNodeKey graph) $ IS.toList $ (`IS.difference` IM.keysSet (calcNonScope startNode (localHypNodes graph) (IS.singleton (nodeUniq targetNode)))) $ calcSCC startNode | (blockKey, block) <- M.toList (blocks proof) , let rule = block2Rule ctxt block , (portKey, Port {portType = PTAssumption, portScopes = _:_}) <- M.toList (ports rule) , let ps = BlockPort blockKey portKey , let targetNode = inPortNodes graph ! ps , let startNode = blockNodes graph ! blockKey ]
nomeata/incredible
logic/ShapeChecks.hs
mit
2,751
0
19
561
845
441
404
58
1
{-# htermination (readOctMyInt :: (List Char) -> (List (Tup2 MyInt (List Char)))) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Tup2 a b = Tup2 a b ; data Char = Char MyInt ; data Integer = Integer MyInt ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ordering = LT | EQ | GT ; fromIntMyInt :: MyInt -> MyInt fromIntMyInt x = x; asAs :: MyBool -> MyBool -> MyBool; asAs MyFalse x = MyFalse; asAs MyTrue x = x; primCmpNat :: Nat -> Nat -> Ordering; primCmpNat Zero Zero = EQ; primCmpNat Zero (Succ y) = LT; primCmpNat (Succ x) Zero = GT; primCmpNat (Succ x) (Succ y) = primCmpNat x y; primCmpInt :: MyInt -> MyInt -> Ordering; primCmpInt (Pos Zero) (Pos Zero) = EQ; primCmpInt (Pos Zero) (Neg Zero) = EQ; primCmpInt (Neg Zero) (Pos Zero) = EQ; primCmpInt (Neg Zero) (Neg Zero) = EQ; primCmpInt (Pos x) (Pos y) = primCmpNat x y; primCmpInt (Pos x) (Neg y) = GT; primCmpInt (Neg x) (Pos y) = LT; primCmpInt (Neg x) (Neg y) = primCmpNat y x; primCmpChar :: Char -> Char -> Ordering; primCmpChar (Char x) (Char y) = primCmpInt x y; compareChar :: Char -> Char -> Ordering compareChar = primCmpChar; esEsOrdering :: Ordering -> Ordering -> MyBool esEsOrdering LT LT = MyTrue; esEsOrdering LT EQ = MyFalse; esEsOrdering LT GT = MyFalse; esEsOrdering EQ LT = MyFalse; esEsOrdering EQ EQ = MyTrue; esEsOrdering EQ GT = MyFalse; esEsOrdering GT LT = MyFalse; esEsOrdering GT EQ = MyFalse; esEsOrdering GT GT = MyTrue; not :: MyBool -> MyBool; not MyTrue = MyFalse; not MyFalse = MyTrue; fsEsOrdering :: Ordering -> Ordering -> MyBool fsEsOrdering x y = not (esEsOrdering x y); gtEsChar :: Char -> Char -> MyBool gtEsChar x y = fsEsOrdering (compareChar x y) LT; ltEsChar :: Char -> Char -> MyBool ltEsChar x y = fsEsOrdering (compareChar x y) GT; isOctDigit c = asAs (gtEsChar c (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))))))))))))))))))))))))))))))))))))))))))))))) (ltEsChar c (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))))))))))))))))))))))))))))))))))))))))))))))))); foldr :: (b -> a -> a) -> a -> (List b) -> a; foldr f z Nil = z; foldr f z (Cons x xs) = f x (foldr f z xs); psPs :: (List a) -> (List a) -> (List a); psPs Nil ys = ys; psPs (Cons x xs) ys = Cons x (psPs xs ys); concat :: (List (List a)) -> (List a); concat = foldr psPs Nil; map :: (b -> a) -> (List b) -> (List a); map f Nil = Nil; map f (Cons x xs) = Cons (f x) (map f xs); pt :: (b -> a) -> (c -> b) -> c -> a; pt f g x = f (g x); concatMap :: (a -> (List b)) -> (List a) -> (List b); concatMap f = pt concat (map f); nonnull00 (Tup2 (Cons vy vz) t) = Cons (Tup2 (Cons vy vz) t) Nil; nonnull00 wu = Nil; nonnull0 vu68 = nonnull00 vu68; otherwise :: MyBool; otherwise = MyTrue; span2Span0 xx xy p wv ww MyTrue = Tup2 Nil (Cons wv ww); span2Vu43 xx xy = span xx xy; span2Ys0 xx xy (Tup2 ys wx) = ys; span2Ys xx xy = span2Ys0 xx xy (span2Vu43 xx xy); span2Zs0 xx xy (Tup2 wy zs) = zs; span2Zs xx xy = span2Zs0 xx xy (span2Vu43 xx xy); span2Span1 xx xy p wv ww MyTrue = Tup2 (Cons wv (span2Ys xx xy)) (span2Zs xx xy); span2Span1 xx xy p wv ww MyFalse = span2Span0 xx xy p wv ww otherwise; span2 p (Cons wv ww) = span2Span1 p ww p wv ww (p wv); span3 p Nil = Tup2 Nil Nil; span3 xv xw = span2 xv xw; span :: (a -> MyBool) -> (List a) -> Tup2 (List a) (List a); span p Nil = span3 p Nil; span p (Cons wv ww) = span2 p (Cons wv ww); nonnull :: (Char -> MyBool) -> (List Char) -> (List (Tup2 (List Char) (List Char))); nonnull p s = concatMap nonnull0 (Cons (span p s) Nil); foldl :: (b -> a -> b) -> b -> (List a) -> b; foldl f z Nil = z; foldl f z (Cons x xs) = foldl f (f z x) xs; foldl1 :: (a -> a -> a) -> (List a) -> a; foldl1 f (Cons x xs) = foldl f x xs; fromIntegerMyInt :: Integer -> MyInt fromIntegerMyInt (Integer x) = x; toIntegerMyInt :: MyInt -> Integer toIntegerMyInt x = Integer x; fromIntegral = pt fromIntegerMyInt toIntegerMyInt; primMinusNat :: Nat -> Nat -> MyInt; primMinusNat Zero Zero = Pos Zero; primMinusNat Zero (Succ y) = Neg (Succ y); primMinusNat (Succ x) Zero = Pos (Succ x); primMinusNat (Succ x) (Succ y) = primMinusNat x y; primPlusNat :: Nat -> Nat -> Nat; primPlusNat Zero Zero = Zero; primPlusNat Zero (Succ y) = Succ y; primPlusNat (Succ x) Zero = Succ x; primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y)); primPlusInt :: MyInt -> MyInt -> MyInt; primPlusInt (Pos x) (Neg y) = primMinusNat x y; primPlusInt (Neg x) (Pos y) = primMinusNat y x; primPlusInt (Neg x) (Neg y) = Neg (primPlusNat x y); primPlusInt (Pos x) (Pos y) = Pos (primPlusNat x y); psMyInt :: MyInt -> MyInt -> MyInt psMyInt = primPlusInt; primMulNat :: Nat -> Nat -> Nat; primMulNat Zero Zero = Zero; primMulNat Zero (Succ y) = Zero; primMulNat (Succ x) Zero = Zero; primMulNat (Succ x) (Succ y) = primPlusNat (primMulNat x (Succ y)) (Succ y); primMulInt :: MyInt -> MyInt -> MyInt; primMulInt (Pos x) (Pos y) = Pos (primMulNat x y); primMulInt (Pos x) (Neg y) = Neg (primMulNat x y); primMulInt (Neg x) (Pos y) = Neg (primMulNat x y); primMulInt (Neg x) (Neg y) = Pos (primMulNat x y); srMyInt :: MyInt -> MyInt -> MyInt srMyInt = primMulInt; readInt0 radix n d = psMyInt (srMyInt n radix) d; readInt10 radix digToInt (Tup2 ds r) = Cons (Tup2 (foldl1 (readInt0 radix) (map (pt fromIntegral digToInt) ds)) r) Nil; readInt10 radix digToInt vv = Nil; readInt1 radix digToInt vu77 = readInt10 radix digToInt vu77; readInt radix isDig digToInt s = concatMap (readInt1 radix digToInt) (nonnull isDig s); primCharToInt :: Char -> MyInt; primCharToInt (Char x) = x; fromEnumChar :: Char -> MyInt fromEnumChar = primCharToInt; fromEnum_0 :: MyInt; fromEnum_0 = fromEnumChar (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))))))))))))))))))))))))))))))))))))))))); primMinusInt :: MyInt -> MyInt -> MyInt; primMinusInt (Pos x) (Neg y) = Pos (primPlusNat x y); primMinusInt (Neg x) (Pos y) = Neg (primPlusNat x y); primMinusInt (Neg x) (Neg y) = primMinusNat y x; primMinusInt (Pos x) (Pos y) = primMinusNat x y; msMyInt :: MyInt -> MyInt -> MyInt msMyInt = primMinusInt; readOct0 d = msMyInt (fromEnumChar d) fromEnum_0; readOctMyInt :: (List Char) -> (List (Tup2 MyInt (List Char))) readOctMyInt = readInt (fromIntMyInt (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))) isOctDigit readOct0;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/readOct_1.hs
mit
7,323
0
121
1,552
4,027
2,087
1,940
148
1
module Data.Matrix ( matrix, Matrix ) where import Data.Matrix.Construct
robertzk/matrix.hs
src/Data/Matrix.hs
mit
77
0
4
13
20
13
7
3
0
module Rebase.Control.Monad.Trans.Class ( module Control.Monad.Trans.Class ) where import Control.Monad.Trans.Class
nikita-volkov/rebase
library/Rebase/Control/Monad/Trans/Class.hs
mit
119
0
5
12
26
19
7
4
0
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} -- | -- Provides the primitives necessary for building readers of -- 'BS.ByteString' or ['Word8'] data. -- A reader attempts to read from an input stream. The reader can succeed -- or fail depending on the input stream and what it is attempting to read. module BACnet.Reader.Core ( -- -- * Introduction -- $Introduction Reader, -- * The Runners run, runR, runS, -- * The Primitive Readers peek, byte, bytes, bytestring, sat, try, getInputStream, getInputState, -- * About the Instances -- $Instances ) where import qualified Data.ByteString.Lazy as BS import Data.Word import Control.Applicative import Control.Monad import Text.Parsec.Prim hiding (try) import qualified Text.Parsec.Prim as Pr import Text.Parsec.Error import Text.Parsec.Pos import Numeric newtype Bytes = Bytes { unbytes :: BS.ByteString } unpack :: Bytes -> [Word8] unpack = BS.unpack . unbytes cons :: Word8 -> Bytes -> Bytes cons b (Bytes bs) = Bytes $ BS.cons b bs uncons :: Bytes -> Maybe (Word8, Bytes) uncons (Bytes bs) = case BS.uncons bs of Nothing -> Nothing Just (v, vs) -> Just (v, Bytes vs) empty :: Bytes empty = Bytes BS.empty -- | @Reader a@ is a type of parser with return type of @a@. newtype Reader a = R { getParser :: Parsec Bytes () a } right :: Either ParseError b -> b right (Right x) = x right (Left err) = error $ show err -- | Runs the specified reader on the given input. If successful -- it returns the value that was read. If unsuccessful, an error -- is thrown giving the location of the error and the unexpected 'Word8' -- value run :: Reader a -> [Word8] -> a run r = right . runR r . BS.pack -- | Runs the specified reader on the given input. It returns the -- result in an @Either ParserError a@ runR :: Reader a -> BS.ByteString -> Either ParseError a runR (R p) = parse p "" . Bytes returnStream :: Parsec Bytes () a -> Parsec Bytes() (a, Bytes) returnStream p = do val <- p s <- getParserState return (val, stateInput s) -- | Like 'run' it runs the specified reader with the given list of bytes. -- If it succeeds it return the leftover input as part of the return value. runS :: Reader a -> [Word8] -> Either ParseError (a, [Word8]) runS (R p) inp = case runR (R (returnStream p)) (BS.pack inp) of Right (v, bs) -> Right (v, unpack bs) Left pe -> Left pe instance (Monad m) => Stream Bytes m Word8 where uncons = return . BACnet.Reader.Core.uncons updatePosWord8 :: SourcePos -> Word8 -> SourcePos updatePosWord8 pos _ = newPos (sourceName pos) (sourceLine pos) (sourceColumn pos + 1) -- | The reader @sat f@ succeeds for any byte for which the supplied function -- @f@ returns 'True'. Returns the byte that is actually read. sat :: (Word8 -> Bool) -> Reader Word8 sat p = R (tokenPrim showByte nextPos testByte) where showByte = ("0x"++) . flip showHex "" nextPos pos b _ = updatePosWord8 pos b testByte b = if p b then Just b else Nothing -- | This reader succeeds for any byte that is read. Returns the read byte. byte :: Reader Word8 byte = sat (const True) -- | @peek@ reads a byte and returns it without consuming any input. -- The following examples use 'runS' which if the reading is successful -- returns the remaing list of bytes as part of the result. -- -- >>> runS peek [0, 1, 2] -- Right (0,[0,1,2]) -- -- This differs from 'byte' which consumes input like so: -- -- >>> runS byte [0, 1, 2] -- Right (0,[1,2]) peek :: Reader Word8 peek = R . lookAhead $ getParser byte -- | @bytes n@ reads and consumes the next n bytes. Returns the bytes -- as a ['Word8']. bytes :: Word8 -> Reader [Word8] bytes 0 = return [] bytes n = (:) <$> byte <*> bytes (n-1) -- | @bytestring n@ reads and consumes the next n bytes. Returns the -- bytes in a 'BS.ByteString'. bytestring :: Word8 -> Reader BS.ByteString bytestring n = unbytes <$> bytestring' n bytestring' :: Word8 -> Reader Bytes bytestring' 0 = return BACnet.Reader.Core.empty bytestring' n = cons <$> byte <*> bytestring' (n-1) readerBind :: Reader a -> (a -> Reader b) -> Reader b readerBind ra f = R $ getParser ra >>= getParser . f -- | Attempts the specified reader. If the reader fails, then no input is consumed. -- Otherwise, it returns the read value as normal. try :: Reader a -> Reader a try = R . Pr.try . getParser -- | A reader that returns the remaing input stream. getInputStream :: Reader BS.ByteString getInputStream = unbytes <$> (R $ stateInput <$> getParserState) -- | A reader that returns the current state of the input stream. In other words, -- it returns the portion of the stream that has not yet been consumed. It -- is just like 'getInputStream' except it unpacks the 'BS.ByteString' returned -- by 'getInputStream'. -- -- >>>run getInputState [1,2,3,4] -- [1,2,3,4] -- -- >>>run (byte >> getInputState) [1,2,3,4] -- [2,3,4] getInputState :: Reader [Word8] getInputState = BS.unpack <$> getInputStream instance Monad Reader where fail = R . fail (>>=) = readerBind return = R . return instance Functor Reader where fmap = liftM instance Applicative Reader where pure = return (<*>) = ap instance Alternative Reader where empty = mzero (<|>) = mplus instance MonadPlus Reader where mzero = fail "mzero" (R p1) `mplus` (R p2) = R (p1 `mplus` p2) -- $Introduction -- This module defines the core primitives for a Reader. -- -- There are several functions -- that can be used to run a reader: 'run', 'runR', 'runS'. They differ -- in what input they take, and in how they handle failure. For example, -- 'runR' returns an @Either ParserError a@ so that it can return failure -- information or the result. The function 'run' expects the reader to -- succeed and throws an error if it fails. It's primarily meant for testing. -- -- The simplest -- readers are 'sat', 'byte', 'bytes', 'bytestring', 'peek'. -- -- Here are some examples that -- show how to run these readers. -- -- >>> import Data.ByteString.Lazy as BS -- >>> runR byte (BS.pack [0x23, 0x34]) -- Right 35 -- -- >>> runR (sat (==0)) (BS.pack [0x23, 0x34]) -- Left (line 1, column 1): -- unexpected 0x23 -- -- If you expect your readers to always succeed you can use 'run' instead -- of 'runR'. Recall, an error is thrown if the reading is not successful. -- The 'run' function also differs in how the input is given. It expects a -- ['Word8'] instead of a 'BS.ByteString' -- -- >>> run byte [10, 20] -- 10 -- -- >>> run (sat (==0)) [0x23] -- *** Exception: (line 1, column 1): -- unexpected 0x23 -- -- In some instances (testing, for example) it's nice to see how much of -- the input stream is left after running a 'Reader'. This can be done with -- 'runS'. In the following example 5 bytes are read and 5 are yet to be -- consumed. -- -- >>> runS (bytes 5) [0,1,2,3,4,5,6,7,8,9] -- Right ([0,1,2,3,4],[5,6,7,8,9]) -- -- -- $Instances -- The 'Reader' type is an instance of several classes: 'Monad', 'Functor', -- 'MonadPlus', 'Applicative' and 'Alternative'. -- -- The 'MonadPlus' instance will be described now. The function -- 'mzero' is defined to be a reader failure. -- -- >>> run mzero [0x01, 0x02] -- *** Exception: (line 1, column 1): -- mzero -- -- The function 'mplus' allows you to try reading input with two different -- readers. The first reader is run. If that succeeds then the value -- it read is returned. Only if it fails is the second reader run. If it -- succeeds then its value is returned. If the second reader also fails -- then the whole read fails. -- -- Note, the first reader may consume input even -- if the reading fails. If -- this is not desired, wrap the first reader with 'try'. This -- first example shows how even though the first reader fails, the second -- one succeeds. -- -- >>> runS (mzero `mplus` byte) [1, 2] -- Right (1,[2]) -- -- In the following example the second reader should succeed, except in trying -- the first reader all the input was consumed. Therefore, the second reader -- and the overall read represented by the @mplus@ also failed. -- -- >>> runS (bytes 3 `mplus` bytes 2) [1, 2] -- Left (line 1, column 3): -- unexpected end of input -- -- This can be resolved, if desired, by wrapping the first reader with try: -- -- >>> runS (try (bytes 3) `mplus` bytes 2) [1,2] -- Right ([1,2],[]) -- -- The 'Alternative' instance works just like the 'MonadPlus' instance -- with 'empty' equivalent to 'mzero' and 'Control.Applicative.<|>' equivalent to 'mplus'. -- -- The instances for 'Monad', 'Functor', and 'Applicative' all work as -- expected. Here are some examples: -- -- In this example we use '<$>' (an alias for 'fmap') to multiply the -- byte we read by 2. -- -- >>> run ((*2) <$> byte) [1] -- 2 -- -- This example shows the use of 'Applicative' -- -- >>> run ((*) <$> byte <*> byte) [3,7] -- 21 -- -- Finally, an example of 'Monad'. -- -- >>> run (byte >>= \b -> if b < 5 then bytes 2 else bytes 3) [0, 2, 4, 5] -- [2,4] -- -- >>> :{ -- let reader = -- do -- b <- peek -- bs <- bytes b -- return $ Prelude.map (*2) bs -- in run reader [3,2,1] -- :} -- [6,4,2]
michaelgwelch/bacnet
src/BACnet/Reader/Core.hs
mit
9,157
0
10
1,859
1,430
837
593
101
2
module Data.FixedWidth where import Control.Applicative import Control.Monad import Data.Attoparsec.Text as StrictText import Data.Attoparsec.Text.Lazy as LazyText import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.Text.Lazy.Encoding (decodeUtf8) fileToLazyText :: String -> IO TL.Text fileToLazyText filename = fmap decodeUtf8 $ BL.readFile filename strictLine :: Parser T.Text strictLine = (StrictText.takeTill isEndOfLine) <* endOfLine withFile :: String -> (Parser a) -> (a -> IO ()) -> IO () withFile filename parser action = do text <- fileToLazyText filename let loop rest = if (TL.null rest) then return () else case (LazyText.parse parser rest) of LazyText.Done rest' a -> (action a >> loop rest') _ -> error "failed parse" loop text lineIterator :: Parser a -> IO () -> (a -> IO ()) -> T.Text -> IO () lineIterator parser fail succeed text = case (parseOnly parser text) of Left _ -> fail Right a -> succeed a
avantcredit/fixedwidth-hs
Data/FixedWidth.hs
mit
1,118
0
16
267
378
198
180
27
3
{-# LANGUAGE TemplateHaskell #-} ------------------------------------------------------------------------------ -- | This module defines our application's state type and an alias for its -- handler monad. module Application where ------------------------------------------------------------------------------ import Api.Core import Control.Lens import Snap.Snaplet import Snap.Snaplet.Heist import Snap.Snaplet.Auth import Snap.Snaplet.Session ------------------------------------------------------------------------------ data App = App { _api :: Snaplet Api } makeLenses ''App ------------------------------------------------------------------------------ type AppHandler = Handler App App
cackharot/heub
app/Application.hs
mit
697
0
9
63
81
50
31
11
0
removeNonUppercase :: [Char] -> [Char] removeNonUppercase st = [c | c <- st, c `elem` ['A' .. 'Z']] addThree :: Int -> Int -> Int -> Int addThree x y z = x + y + z -- TYPES: -- Int: fixed size -- Integer: arbitrary size -- Float -- Double -- Bool -- Char -- TYPECLASSES: -- Eq: interface for equalities (ex: ==) -- Ord: " for ordering (ex: >) -- Show: " for representing stuff as strings (ex: show) -- Read: " for parsing strings as stuff (ex: read) -- Enum: " for sequentially ordered types -- Bounded: " for stuff with lower and upper bounds -- Num : " for stuff that behaves like numbers (Integrals + Floatings) (check: *) -- Integral: only integral numbers: Int, Integer -- Floating: only floating point numbers: Double, Float x1 = read "5" :: Int y1 = read "(5, 'a')" :: (Int, Char) -- fromIntegral: convert from Integral to Num
fabriceleal/learn-you-a-haskell
03/types_and_typeclasses.hs
mit
842
0
8
167
134
82
52
6
1
import Control.Monad.Trans.Reader import Control.Monad.Trans.State import Data.Functor.Identity rDec :: Num a => Reader a a rDec = ReaderT $ \a -> Identity (a - 1) -- point free rDec' :: Num a => Reader a a rDec' = ReaderT $ return . (subtract 1) rShow :: Show a => ReaderT a Identity String rShow = ReaderT $ \a -> Identity (show a) -- point free rShow' :: Show a => ReaderT a Identity String rShow' = ReaderT $ return . show rPrintAndInc :: (Num a, Show a) => ReaderT a IO a rPrintAndInc = ReaderT $ \a -> putStrLn ("Hi: " ++ (show a)) >> pure (a + 1) sPrintIncAccum :: (Num a, Show a) => StateT a IO String sPrintIncAccum = StateT $ \a -> putStrLn ("Hi: " ++ (show a)) >> return (show a, (a + 1))
mitochon/hexercise
src/haskellbook/ch26/ch26.end.hs
mit
769
0
12
207
325
171
154
17
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.WebGLCompressedTextureS3TC (pattern COMPRESSED_RGB_S3TC_DXT1_EXT, pattern COMPRESSED_RGBA_S3TC_DXT1_EXT, pattern COMPRESSED_RGBA_S3TC_DXT3_EXT, pattern COMPRESSED_RGBA_S3TC_DXT5_EXT, WebGLCompressedTextureS3TC(..), gTypeWebGLCompressedTextureS3TC) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums pattern COMPRESSED_RGB_S3TC_DXT1_EXT = 33776 pattern COMPRESSED_RGBA_S3TC_DXT1_EXT = 33777 pattern COMPRESSED_RGBA_S3TC_DXT3_EXT = 33778 pattern COMPRESSED_RGBA_S3TC_DXT5_EXT = 33779
ghcjs/jsaddle-dom
src/JSDOM/Generated/WebGLCompressedTextureS3TC.hs
mit
1,420
0
6
171
344
224
120
26
0
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE UnicodeSyntax #-} module Control.Monad.Trace.Class ( MonadTrace(..) ) where import Control.Monad.List import Control.Monad.Reader import Control.Monad.Trans.Except import Control.Monad.Trans.Identity import Control.Monad.Trans.Cont import Control.Monad.Trans.Maybe import qualified Control.Monad.RWS.Strict as Strict import qualified Control.Monad.RWS.Lazy as Lazy import qualified Control.Monad.Writer.Strict as Strict import qualified Control.Monad.Writer.Lazy as Lazy import qualified Control.Monad.State.Strict as Strict import qualified Control.Monad.State.Lazy as Lazy import Data.Sequence import Data.Monoid -- | A class for monads that have a scoped tracing effect class Monad m ⇒ MonadTrace t m | m → t where -- | Add a tag or breadcrumb to a scope traceScope ∷ t → m α → m α -- | Read back your own trace readTrace ∷ m (Seq t) instance MonadTrace t m ⇒ MonadTrace t (ReaderT r m) where traceScope t (ReaderT m) = ReaderT $ traceScope t . m readTrace = lift readTrace instance (Monoid w, MonadTrace t m) ⇒ MonadTrace t (Strict.WriterT w m) where traceScope t = Strict.WriterT . traceScope t . Strict.runWriterT readTrace = lift readTrace instance (Monoid w, MonadTrace t m) ⇒ MonadTrace t (Lazy.WriterT w m) where traceScope t = Lazy.WriterT . traceScope t . Lazy.runWriterT readTrace = lift readTrace instance MonadTrace t m ⇒ MonadTrace t (Strict.StateT w m) where traceScope t (Strict.StateT m) = Strict.StateT $ traceScope t . m readTrace = lift readTrace instance MonadTrace t m ⇒ MonadTrace t (Lazy.StateT w m) where traceScope t (Lazy.StateT m) = Lazy.StateT $ traceScope t . m readTrace = lift readTrace instance (Monoid w, MonadTrace t m) ⇒ MonadTrace t (Strict.RWST r w s m) where traceScope t (Strict.RWST m) = Strict.RWST $ \r → traceScope t . m r readTrace = lift readTrace instance (Monoid w, MonadTrace t m) ⇒ MonadTrace t (Lazy.RWST r w s m) where traceScope t (Lazy.RWST m) = Lazy.RWST $ \r → traceScope t . m r readTrace = lift readTrace instance MonadTrace t m ⇒ MonadTrace t (ExceptT e m) where traceScope t = ExceptT . traceScope t . runExceptT readTrace = lift readTrace instance MonadTrace t m ⇒ MonadTrace t (IdentityT m) where traceScope t = IdentityT . traceScope t . runIdentityT readTrace = lift readTrace instance MonadTrace t m ⇒ MonadTrace t (ContT r m) where traceScope t (ContT m) = ContT $ traceScope t . m readTrace = lift readTrace instance MonadTrace t m ⇒ MonadTrace t (ListT m) where traceScope t = ListT . traceScope t . runListT readTrace = lift readTrace instance MonadTrace t m ⇒ MonadTrace t (MaybeT m) where traceScope t = MaybeT . traceScope t . runMaybeT readTrace = lift readTrace
alephcloud/hs-trace
src/Control/Monad/Trace/Class.hs
mit
2,936
23
9
533
981
513
468
64
0
module Let where --Grammar for Let (concrete) -- int ::= Integer -- var ::= (Any variable name) -- exp ::= Int Integer Literal -- | exp `+` exp Addition -- | `let` var `=` exp `in` exp Variable declaration -- | var Variable Reference -- 1. Encode the above grammar as a set of Haskell Data Types type Var = String -- data NameOfType = Constructor TypeArgs -- | Constructor TypeArgs -- | Constructor TypeArgs -- | etc... data Exp = Lit Int | Add Exp Exp | Let Var Exp Exp --Let a var | Ref Var --reference to variable deriving(Eq, Show) -- 2. Write haskell values that represent some programs -- let x = 3 in (x + x) x1 :: Exp x1 = Let "x" (Lit 3) (Add (Ref "x") (Ref "x")) -- 4 + (Let y = 5 in (let z = 6 in (y + z))) x2 :: Exp x2 = Add (Lit 4) (Let "y" (Lit 5) (Let "z" (Lit 6) (Add (Ref "y") (Ref "z")))) -- 3. Write a program that returns all the variables declared in a -- Let program -- TODO: Apply this to Macro in the homework vars :: Exp -> [Var] vars (Let v e1 e2) = v : (vars e1 ++ vars e2) vars (Add e1 e2) = vars e1 ++ vars e2 vars (Lit _) = [] vars (Ref _) = []
siphayne/CS381
scratch/let.hs
mit
1,286
0
13
446
292
161
131
16
1
module LinkedList ( LinkedList , fromList, toList, reverseLinkedList , datum, next, isNil, nil, new) where data LinkedList a = Nil | Cons { datum :: a , next :: LinkedList a } deriving (Eq, Show) new :: a -> LinkedList a -> LinkedList a new = Cons nil :: LinkedList a nil = Nil fromList :: [a] -> LinkedList a fromList = foldr Cons Nil toList :: LinkedList a -> [a] toList Nil = [] toList (Cons x xs) = x : toList xs reverseLinkedList :: LinkedList a -> LinkedList a reverseLinkedList = go Nil where go acc Nil = acc go acc (Cons x xs) = (go $! Cons x acc) xs isNil :: LinkedList a -> Bool isNil Nil = True isNil _ = False
exercism/xhaskell
exercises/practice/simple-linked-list/.meta/examples/success-standard/src/LinkedList.hs
mit
721
0
10
225
278
148
130
23
2
-- Global.hs module GlobalLocal where topLevelFunction :: Integer -> Integer topLevelFunction x = x + woot + topLevelValue where woot :: Integer woot = 10 topLevelValue :: Integer topLevelValue = 5
Lyapunov/haskell-programming-from-first-principles
chapter_3/Global.hs
mit
212
0
6
45
52
30
22
7
1
-- | RealSimpleMusic API. -- Types and records PitchClass, Scale, Octave, Pitch, -- IndexedPitch, and etc. implement components aggregated -- by top-level Score type. -- Convenience functions to -- 1) generate scales: majorScale, -- naturalMinorScale, melodicMinorScale, and -- scaleFromEnhChromaticScale, 2) manipulate Pitch -- getPitch, -- 3) manipulate Note: -- indexedNoteToNote, indexedNoteToNotes, noteToRhythm. -- Workhorse functions to convert Score to Midi file or -- files: scoreToMidiFile, scoreToMidiFiles, and to -- convert Score to Lilypond file: scoreToLilypondFile module Music.RealSimpleMusic ( PitchClass(..) , pitchClassToEnhIdx , Scale , majorScale , chromaticScale , naturalMinorScale , melodicMinorScale , scaleFromEnhChromaticScale , scaleToAscendingPitchClasses , scaleToDescendingPitchClasses , Octave(..) , Pitch(..) , IndexedPitch(..) , Dynamic(..) , DiscreteDynamicValue(..) , Balance(..) , Pan(..) , PanVal(..) , Tempo(..) , TempoVal(..) , normalizeTempoVals , KeySignature(..) , TimeSignature(..) , Articulation(..) , Accent(..) , Rhythm , mkRhythm , getRhythm , RhythmDenom(..) , Instrument(..) , ScoreControls(..) , VoiceControl(..) , Note(..) , addControlToNote , IndexedNote(..) , ixPitchToPitch , indexedNoteToNote , indexedNotesToNotes , transposeIndexedPitch , transposeIndexedNote , Interval , Intervals , Chord(..) , Voice(..) , Title , Score(..) , scoreToMidiFile , scoreToMidiFiles , scoreToLilypondFile , scoreToByteString ) where import Music.RealSimpleMusic.Music.Data import Music.RealSimpleMusic.Music.Utils import Music.RealSimpleMusic.ScoreToMidi.Utils import Music.RealSimpleMusic.ScoreToLilypond.Utils
tomtitchener/RealSimpleMusic
src/Music/RealSimpleMusic.hs
cc0-1.0
1,888
0
5
422
296
211
85
55
0
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./CspCASL/Symbol.hs Description : semantic csp-casl symbols Copyright : (c) Christian Maeder, DFKI GmbH 2011 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable -} module CspCASL.Symbol where import CspCASL.AS_CspCASL_Process import CspCASL.CspCASL_Keywords import CspCASL.SignCSP import CspCASL.SymbItems import CASL.AS_Basic_CASL import CASL.Morphism import CASL.Sign import Common.Doc import Common.DocUtils import Common.Id import Common.Result import qualified Common.Lib.MapSet as MapSet import Data.Data import qualified Data.Map as Map import qualified Data.Set as Set import Control.Monad data CspSymbType = CaslSymbType SymbType | ProcAsItemType ProcProfile | ChanAsItemType Id -- the SORT deriving (Show, Eq, Ord, Typeable, Data) data CspSymbol = CspSymbol {cspSymName :: Id, cspSymbType :: CspSymbType} deriving (Show, Eq, Ord, Typeable, Data) data CspRawSymbol = ACspSymbol CspSymbol | CspKindedSymb CspSymbKind Id deriving (Show, Eq, Ord, Typeable, Data) rawId :: CspRawSymbol -> Id rawId r = case r of ACspSymbol s -> cspSymName s CspKindedSymb _ i -> i instance Pretty CspSymbol where pretty (CspSymbol i t) = case t of ProcAsItemType p -> keyword processS <+> pretty i <+> pretty p ChanAsItemType s -> keyword channelS <+> pretty i <+> colon <+> pretty s CaslSymbType c -> pretty $ Symbol i c instance GetRange CspSymbol where getRange (CspSymbol i _) = getRange i instance Pretty CspRawSymbol where pretty r = case r of ACspSymbol s -> pretty s CspKindedSymb k i -> pretty k <+> pretty i instance GetRange CspRawSymbol where getRange r = case r of ACspSymbol s -> getRange s CspKindedSymb _ i -> getRange i cspCheckSymbList :: [CspSymbMap] -> [Diagnosis] cspCheckSymbList l = case l of CspSymbMap (CspSymb a Nothing) Nothing : CspSymbMap (CspSymb b (Just t)) _ : r -> mkDiag Warning ("profile '" ++ showDoc t "' does not apply to '" ++ showId a "' but only to") b : cspCheckSymbList r _ : r -> cspCheckSymbList r [] -> [] toChanSymbol :: (CHANNEL_NAME, SORT) -> CspSymbol toChanSymbol (c, s) = CspSymbol c $ ChanAsItemType s toProcSymbol :: (PROCESS_NAME, ProcProfile) -> CspSymbol toProcSymbol (n, p) = CspSymbol n $ ProcAsItemType p idToCspRaw :: Id -> CspRawSymbol idToCspRaw = CspKindedSymb $ CaslKind Implicit sortToProcProfile :: SORT -> ProcProfile sortToProcProfile = ProcProfile [] . Set.singleton . CommTypeSort cspTypedSymbKindToRaw :: Bool -> CspCASLSign -> CspSymbKind -> Id -> CspType -> Result CspRawSymbol cspTypedSymbKindToRaw b sig k idt t = let csig = extendedInfo sig getSet = MapSet.lookup idt chs = getSet $ chans csig prs = getSet $ procSet csig reduce = reduceProcProfile $ sortRel sig err = plain_error (idToCspRaw idt) (showDoc idt " " ++ showDoc t " does not have kind " ++ showDoc k "") nullRange in case k of ProcessKind -> case t of ProcType p -> return $ ACspSymbol $ toProcSymbol (idt, reduce p) CaslType (A_type s) -> return $ ACspSymbol $ toProcSymbol (idt, reduce $ sortToProcProfile s) _ -> err ChannelKind -> case t of CaslType (A_type s) -> return $ ACspSymbol $ toChanSymbol (idt, s) _ -> err CaslKind ck -> case t of CaslType ct -> let caslAnno = fmap (\ r -> case r of ASymbol sy -> ACspSymbol $ CspSymbol idt $ CaslSymbType $ symbType sy _ -> CspKindedSymb k idt) $ typedSymbKindToRaw b sig ck idt ct in case ct of A_type s | b && ck == Implicit -> let hasChan = Set.member s chs cprs = Set.filter (\ (ProcProfile args al) -> null args && any (\ cs -> case cs of CommTypeSort r -> r == s || Set.member s (subsortsOf r sig) CommTypeChan (TypedChanName c _) -> c == s) (Set.toList al)) prs in case Set.toList cprs of [] -> if hasChan then do appendDiags [mkDiag Hint "matched channel" idt] return $ ACspSymbol $ toChanSymbol (idt, s) else caslAnno pr : rpr -> do when (hasChan || not (null rpr)) $ appendDiags [mkDiag Warning "ambiguous matches" idt] appendDiags [mkDiag Hint "matched process" idt] return $ ACspSymbol $ toProcSymbol (idt, pr) _ -> caslAnno ProcType p | ck == Implicit -> return $ ACspSymbol $ toProcSymbol (idt, reduce p) _ -> err cspSymbToRaw :: Bool -> CspCASLSign -> CspSymbKind -> CspSymb -> Result CspRawSymbol cspSymbToRaw b sig k (CspSymb idt mt) = case mt of Nothing -> return $ case k of CaslKind Sorts_kind -> ACspSymbol $ CspSymbol idt $ CaslSymbType SortAsItemType _ -> CspKindedSymb k idt Just t -> cspTypedSymbKindToRaw b sig k idt t cspStatSymbItems :: CspCASLSign -> [CspSymbItems] -> Result [CspRawSymbol] cspStatSymbItems sig sl = let st (CspSymbItems kind l) = do appendDiags $ cspCheckSymbList $ map (`CspSymbMap` Nothing) l mapM (cspSymbToRaw True sig kind) l in fmap concat (mapM st sl) maxKind :: CspSymbKind -> CspRawSymbol -> CspSymbKind maxKind k rs = case k of CaslKind Implicit -> case rs of ACspSymbol (CspSymbol _ ty) -> case ty of ProcAsItemType _ -> ProcessKind ChanAsItemType _ -> ChannelKind CaslSymbType cTy -> case cTy of OpAsItemType _ -> CaslKind Ops_kind PredAsItemType _ -> CaslKind Preds_kind _ -> CaslKind Sorts_kind _ -> k _ -> k cspSymbOrMapToRaw :: CspCASLSign -> Maybe CspCASLSign -> CspSymbKind -> CspSymbMap -> Result [(CspRawSymbol, CspRawSymbol)] cspSymbOrMapToRaw sig msig k (CspSymbMap s mt) = case mt of Nothing -> do v <- cspSymbToRaw True sig k s return [(v, v)] Just t -> do appendDiags $ case (s, t) of (CspSymb a Nothing, CspSymb b Nothing) | a == b -> [mkDiag Hint "unneeded identical mapping of" a] _ -> [] w <- cspSymbToRaw True sig k s let nk = maxKind k w x <- case msig of Nothing -> cspSymbToRaw False sig nk t Just tsig -> cspSymbToRaw True tsig nk t let mkS i = ACspSymbol $ CspSymbol i $ CaslSymbType SortAsItemType pairS s1 s2 = (mkS s1, mkS s2) case (w, x) of (ACspSymbol c1@(CspSymbol _ t1), ACspSymbol c2@(CspSymbol _ t2)) -> case (t1, t2) of (ChanAsItemType s1, ChanAsItemType s2) -> return [(w, x), (mkS s1, mkS s2)] (ProcAsItemType (ProcProfile args1 _), ProcAsItemType (ProcProfile args2 _)) | length args1 == length args2 -> return $ (w, x) : zipWith pairS args1 args2 (CaslSymbType (PredAsItemType (PredType args1)), CaslSymbType (PredAsItemType (PredType args2))) | length args1 == length args2 -> return $ (w, x) : zipWith pairS args1 args2 (CaslSymbType (OpAsItemType (OpType _ args1 res1)), CaslSymbType (OpAsItemType (OpType _ args2 res2))) | length args1 == length args2 -> return $ (w, x) : zipWith pairS (res1 : args1) (res2 : args2) (CaslSymbType SortAsItemType, CaslSymbType SortAsItemType) -> return [(w, x)] _ -> fail $ "profiles of '" ++ showDoc c1 "' and '" ++ showDoc c2 "' do not match" _ -> return [(w, x)] cspStatSymbMapItems :: CspCASLSign -> Maybe CspCASLSign -> [CspSymbMapItems] -> Result (Map.Map CspRawSymbol CspRawSymbol) cspStatSymbMapItems sig msig sl = do let st (CspSymbMapItems kind l) = do appendDiags $ cspCheckSymbList l fmap concat $ mapM (cspSymbOrMapToRaw sig msig kind) l getSort rsy = case rsy of ACspSymbol (CspSymbol i (CaslSymbType SortAsItemType)) -> Just i _ -> Nothing getImplicit rsy = case rsy of CspKindedSymb (CaslKind Implicit) i -> Just i _ -> Nothing mkSort i = ACspSymbol $ CspSymbol i $ CaslSymbType SortAsItemType mkImplicit = idToCspRaw ls <- mapM st sl foldM (insertRsys rawId getSort mkSort getImplicit mkImplicit) Map.empty (concat ls) toSymbolSet :: CspSign -> [Set.Set CspSymbol] toSymbolSet csig = map Set.fromList [ map toChanSymbol $ mapSetToList $ chans csig , map toProcSymbol $ mapSetToList $ procSet csig ] symSets :: CspCASLSign -> [Set.Set CspSymbol] symSets sig = map (Set.map caslToCspSymbol) (symOf sig) ++ toSymbolSet (extendedInfo sig) caslToCspSymbol :: Symbol -> CspSymbol caslToCspSymbol sy = CspSymbol (symName sy) $ CaslSymbType $ symbType sy -- | try to convert a csp raw symbol to a CASL raw symbol toRawSymbol :: CspRawSymbol -> Maybe RawSymbol toRawSymbol r = case r of ACspSymbol (CspSymbol i (CaslSymbType t)) -> Just (ASymbol $ Symbol i t) CspKindedSymb (CaslKind k) i -> Just (AKindedSymb k i) _ -> Nothing splitSymbolMap :: Map.Map CspRawSymbol CspRawSymbol -> (RawSymbolMap, Map.Map CspRawSymbol CspRawSymbol) splitSymbolMap = Map.foldWithKey (\ s t (cm, ccm) -> case (toRawSymbol s, toRawSymbol t) of (Just c, Just d) -> (Map.insert c d cm, ccm) _ -> (cm, Map.insert s t ccm)) (Map.empty, Map.empty) getCASLSymbols :: Set.Set CspSymbol -> Set.Set Symbol getCASLSymbols = Set.fold (\ (CspSymbol i ty) -> case ty of CaslSymbType t -> Set.insert $ Symbol i t _ -> id) Set.empty
gnn/Hets
CspCASL/Symbol.hs
gpl-2.0
9,772
135
23
2,707
3,167
1,622
1,545
222
13
module Main where import System.Environment(getArgs) import Data.List (sortBy, sort) import Data.Ord (comparing) sortNumbers :: [(Float, String)] -> [(Float, String)] sortNumbers = sort processLine :: String -> String processLine = unwords . map snd . sortNumbers . map (\s -> (read s, s)) . words main :: IO () main = do [inputFile] <- getArgs input <- readFile inputFile mapM_ putStrLn $ map processLine $ lines input
cryptica/CodeEval
Challenges/91_SimpleSorting/main.hs
gpl-3.0
437
0
11
83
177
96
81
13
1
module HFlint.Internal.Utils where import Control.Exception ( Exception , throw ) {-# INLINE throwBeforeIf #-} throwBeforeIf :: Exception e => e -> (a -> Bool) -> (a -> b) -> a -> b throwBeforeIf e cond f a = if cond a then throw e else f a {-# INLINE throwBeforeIf2 #-} throwBeforeIf2 :: Exception e => e -> (a -> b -> Bool) -> (a -> b -> c) -> a -> b -> c throwBeforeIf2 e cond f a b = if cond a b then throw e else f a b
martinra/hflint
src/HFlint/Internal/Utils.hs
gpl-3.0
541
0
11
210
186
98
88
15
2
{-# LANGUAGE CPP, ScopedTypeVariables #-} import Control.Applicative import Control.Arrow import Control.Concurrent (forkIO) import Control.Concurrent.Chan import Control.Concurrent.MVar import Control.Concurrent.Process import Control.Exception import Control.Monad import Control.Monad.Trans (MonadIO, liftIO) import Data.Bits import Data.Char (ord) import Data.Function (fix) import qualified Data.List as List import Data.Maybe import Data.Version (showVersion) import Mescaline (Time) import Mescaline.Application (AppT) import qualified Mescaline.Application as App import qualified Mescaline.Application.Desktop as App import qualified Mescaline.Application.Logger as Log import qualified Mescaline.Database as DB import qualified Mescaline.Database.Process as DatabaseP import qualified Mescaline.Pattern.Sequencer as Sequencer import qualified Mescaline.FeatureSpace.Model as FeatureSpace import qualified Mescaline.FeatureSpace.Process as FeatureSpaceP import qualified Mescaline.FeatureSpace.View as FeatureSpaceView import qualified Mescaline.Pattern as Pattern import qualified Mescaline.Pattern.Environment as Pattern import qualified Mescaline.Pattern.Event as Event import qualified Mescaline.Pattern.Patch as Patch import qualified Mescaline.Pattern.Process as PatternP import qualified Mescaline.Pattern.View as PatternView import qualified Mescaline.Synth.OSCServer as OSCServer import qualified Mescaline.Synth.Sampler.Process as SynthP import Mescaline.Util (findFiles) import qualified Paths_mescaline_app as Paths import qualified Sound.OpenSoundControl as OSC import qualified Sound.SC3.Server.State as State import qualified Sound.SC3.Server.Process as Server import qualified Sound.SC3.Server.Process.CommandLine as Server import System.Directory import qualified System.Environment as Env import System.Environment.FindBin (getProgPath) import System.FilePath import qualified System.Random as Random import qualified Qtc.Classes.Gui as Qt import qualified Qtc.Classes.Gui_h as Qt import qualified Qtc.Classes.Object as Qt import qualified Qtc.Classes.Qccs as Qt import qualified Qtc.Classes.Qccs_h as Qt import qualified Qtc.ClassTypes.Gui as Qt import qualified Qtc.ClassTypes.Tools as Qt import qualified Qtc.Core.Base as Qt import qualified Qtc.Core.QFile as Qt import qualified Qtc.Enums.Base as Qt import qualified Qtc.Enums.Classes.Core as Qt import qualified Qtc.Enums.Core.QIODevice as Qt import qualified Qtc.Enums.Core.Qt as Qt import qualified Qtc.Enums.Gui.QFileDialog as Qt import qualified Qtc.Enums.Gui.QPainter as Qt import qualified Qtc.Gui.Base as Qt import qualified Qtc.Gui.QApplication as Qt import qualified Qtc.Gui.QDialog as Qt import qualified Qtc.Gui.QFileDialog as Qt import qualified Qtc.Gui.QMessageBox as Qt import qualified Qtc.Enums.Gui.QGraphicsView as Qt import qualified Qtc.Gui.QGraphicsView as Qt import qualified Qtc.Gui.QGraphicsView as Qt import qualified Qtc.Gui.QGraphicsView_h as Qt import qualified Qtc.Gui.QKeySequence as Qt import qualified Qtc.Gui.QMainWindow as Qt import qualified Qtc.Gui.QMainWindow_h as Qt import qualified Qtc.Gui.QAction as Qt import qualified Qtc.Gui.QMenu as Qt import qualified Qtc.Gui.QMenuBar as Qt import qualified Qtc.Enums.Gui.QTextCursor as Qt import qualified Qtc.Gui.QTextCursor as Qt import qualified Qtc.Gui.QTextEdit as Qt import qualified Qtc.Gui.QFontMetrics as Qt import qualified Qtc.Gui.QWheelEvent as Qt import qualified Qtc.Gui.QWidget as Qt import qualified Qtc.Gui.QWidget_h as Qt import qualified Qtc.Tools.QUiLoader as Qt import qualified Qtc.Tools.QUiLoader_h as Qt -- sceneKeyPressEvent :: MVar Bool -> Chan (Sequencer a -> Sequencer a) -> Qt.QWidget () -> Qt.QKeyEvent () -> IO () -- sceneKeyPressEvent mute chan _ qkev = do -- key <- Qt.key qkev () -- if key == Qt.qEnum_toInt Qt.eKey_C -- then writeChan chan Sequencer.deleteAll -- else if key == Qt.qEnum_toInt Qt.eKey_M -- then modifyMVar_ mute (return . not) -- else return () type MainWindow = Qt.QMainWindowSc (CMainWindow) data CMainWindow = CMainWindow mainWindow :: Qt.QWidget () -> IO (MainWindow) mainWindow mw = do -- Qt.setHandler mw "keyPressEvent(QKeyEvent*)" $ windowKeyPressEvent -- Qt.setFocus mw Qt.eOtherFocusReason -- Qt.grabKeyboard mw () Qt.qSubClass $ Qt.qCast_QMainWindow mw windowKeyPressEvent :: Qt.QWidget () -> Qt.QKeyEvent () -> IO () windowKeyPressEvent this evt = putStrLn "yeah!" -- >> Qt.keyPressEvent_h this evt featureSpaceViewKeyPressEvent :: Qt.QGraphicsView () -> Qt.QKeyEvent () -> IO () featureSpaceViewKeyPressEvent view evt = do key <- Qt.key evt () if key == Qt.qEnum_toInt Qt.eKey_Control then Qt.setDragMode view Qt.eScrollHandDrag else Qt.keyPressEvent_h view evt featureSpaceViewKeyReleaseEvent :: Qt.QGraphicsView () -> Qt.QKeyEvent () -> IO () featureSpaceViewKeyReleaseEvent view evt = do key <- Qt.key evt () if key == Qt.qEnum_toInt Qt.eKey_Control then Qt.setDragMode view Qt.eNoDrag else Qt.keyPressEvent_h view evt -- featureSpaceViewWheelEvent :: Qt.QGraphicsView () -> Qt.QWheelEvent () -> IO () -- featureSpaceViewWheelEvent view evt = do -- mods <- Qt.modifiers evt () -- when (Qt.qFlags_toInt mods .&. Qt.qEnum_toInt Qt.eControlModifier == 0) $ do -- units <- Qt.delta evt () -- let deg = fromIntegral units / 8 -- scale0 = deg * 1.5 -- scale = if scale0 == 0 then 1 else if scale0 < 0 then 1/negate scale0 else scale0 -- scaleFeatureSpace scale view mkFeatureSpaceView :: Qt.QWidget a -> IO (Qt.QGraphicsView ()) mkFeatureSpaceView parent = do view <- Qt.qGraphicsView parent Qt.setRenderHints view (Qt.fAntialiasing :: Qt.RenderHints) Qt.setHandler view "keyPressEvent(QKeyEvent*)" featureSpaceViewKeyPressEvent Qt.setHandler view "keyReleaseEvent(QKeyEvent*)" featureSpaceViewKeyReleaseEvent -- Qt.fitInView graphicsView (Qt.rectF 0 0 1 1) Qt.setTransformationAnchor view Qt.eAnchorUnderMouse return view -- | Custom createWidget handler. -- -- This is needed because it is not possible to set event handlers on objects return from the UI loader (??). createWidget :: Qt.QUiLoader () -> String -> Qt.QWidget a -> String -> IO (Qt.QWidget ()) createWidget this className parent name = do if (className == "FeatureSpaceView") then do view <- mkFeatureSpaceView parent Qt.setObjectName view name return (Qt.objectCast view) else do Qt.createWidget_h this (className, parent, name) loadUI :: FilePath -> IO (MainWindow) loadUI path = do uiLoader <- Qt.qUiLoader () Qt.setHandler uiLoader "(QWidget*)createWidget(const QString&,QWidget*,const QString&)" createWidget uiFile <- Qt.qFile path Qt.open uiFile Qt.fReadOnly w <- Qt.load uiLoader uiFile Qt.close uiFile () mainWindow w pipe :: (a -> IO b) -> Chan a -> Chan b -> IO () pipe f ichan ochan = do a <- readChan ichan b <- f a writeChan ochan b pipe f ichan ochan -- ==================================================================== -- Menu definition utilities -- TODO: Factor this into a separate module. data ActionType = Trigger | Checkable deriving (Eq, Show) data MenuDefinition = Menu String String [MenuDefinition] | Action String String String ActionType (Maybe String) (Qt.QWidget () -> Qt.QAction () -> IO ()) | Separator actionCallback :: Qt.QAction () -> (Qt.QWidget () -> Qt.QAction () -> IO ()) -> Qt.QWidget () -> Bool -> IO () actionCallback a cb w _ = cb w a defineMenu :: [MenuDefinition] -> Qt.QMenuBar () -> Qt.QWidget () -> IO [(String, Qt.QAction ())] defineMenu defs menuBar widget = mapM (f (Left menuBar) []) defs >>= return . concat where f menu path (Menu name display defs) = do menu' <- either (flip Qt.addMenu display) (flip Qt.addMenu display) menu mapM (f (Right menu') (path ++ [name])) defs >>= return . concat f menu path (Action name display statusTip actionType shortcut callback) = do case menu of Left _ -> return [] Right menu -> do action <- Qt.qAction (display, widget) Qt.setStatusTip action statusTip when (actionType == Checkable) (Qt.setCheckable action True) maybe (return ()) (\s -> Qt.setShortcut action =<< Qt.qKeySequence s) shortcut let path' = path ++ [name] slot = List.intercalate "_" path' ++ "()" key = "/" ++ List.intercalate "/" path' Qt.connectSlot action "triggered()" widget slot (actionCallback action callback) Qt.addAction menu action return [(key, action)] f menu path Separator = do case menu of Left _ -> return () Right menu -> Qt.addSeparator menu () >> return () return [] defineWindowMenu :: [MenuDefinition] -> Qt.QMainWindow () -> IO [(String, Qt.QAction ())] defineWindowMenu defs window = do menuBar <- Qt.menuBar window () defineMenu defs menuBar (Qt.objectCast window) trigger :: String -> [(String, Qt.QAction ())] -> IO () trigger k = maybe (return ()) (flip Qt.trigger ()) . lookup k directoryMenu :: (FilePath -> Qt.QWidget () -> Qt.QAction () -> IO ()) -> [String] -> FilePath -> IO [MenuDefinition] directoryMenu callback exts dir = liftM (map mkAction) (findFiles exts [dir]) where mkAction path = Action (tr "/" '.' path) (makeRelative dir path) "" Trigger Nothing (callback path) tr s c = map (\x -> if elem x s then c else x) -- ==================================================================== -- Logging to text view chanLogger :: Log.Priority -> String -> Chan String -> IO () -> Log.GenericHandler (Chan String) chanLogger prio fmt chan action = Log.GenericHandler prio (Log.simpleLogFormatter fmt) chan (\chan msg -> writeChan chan msg >> action) (const (return ())) createLoggers :: MonadIO m => MainWindow -> AppT m () createLoggers logWindow = do -- components <- Log.getComponents logger <- liftIO $ do textEdit <- Qt.findChild logWindow ("<QTextEdit*>", "textEdit") :: IO (Qt.QTextEdit ()) chan <- newChan Qt.connectSlot logWindow "logMessage()" logWindow "logMessage()" $ logMessage chan textEdit let fmt = "[$prio][$loggername] $msg\n" action = Qt.emitSignal logWindow "logMessage()" () -- FIXME: The log levels have to be initialized first down in main, why? -- mapM_ (\(logger, prio) -> do -- Log.updateGlobalLogger -- logger -- (Log.setHandlers [chanLogger prio fmt chan action])) -- components return $ chanLogger Log.DEBUG fmt chan action App.updateLogger (Log.setHandlers [logger]) "" where logMessage :: Chan String -> Qt.QTextEdit () -> MainWindow -> IO () logMessage chan edit _ = do msg <- readChan chan c <- Qt.textCursor edit () Qt.insertText c msg _ <- Qt.movePosition c (Qt.eEnd :: Qt.MoveOperation) Qt.setTextCursor edit c clearLog :: MainWindow -> IO () clearLog logWindow = do edit <- Qt.findChild logWindow ("<QTextEdit*>", "textEdit") :: IO (Qt.QTextEdit ()) Qt.setPlainText edit "" -- ==================================================================== -- Actions action_about :: App.Version -> Qt.QWidget () -> Qt.QAction () -> IO () action_about version mw _ = Qt.qMessageBoxAbout ( mw , "About Mescaline" , unwords [ "<center><h2>Mescaline</h2></center>" , "<center><h4>Version " ++ showVersion version ++ "</h4></center>" , "<a href=\"http://mescaline.globero.es\">Mescaline</a>" , "is a data-driven sequencer and synthesizer." ] ) importDialog :: Qt.FileMode -> Qt.QWidget () -> IO [FilePath] importDialog fileMode w = do d <- Qt.qFileDialog w Qt.setFileMode d fileMode Qt.setViewMode d (Qt.eList :: Qt.QFileDialogViewMode) b <- Qt.exec d () if b > 0 then Qt.selectedFiles d () else return [] action_file_openFile :: PatternP.Handle -> Qt.QWidget () -> Qt.QAction () -> IO () action_file_openFile h w _ = do ps <- importDialog Qt.eExistingFile w case ps of [] -> return () (p:_) -> sendTo h $ PatternP.LoadPatch p action_file_saveFile :: PatternP.Handle -> Qt.QWidget () -> Qt.QAction () -> IO () action_file_saveFile h w _ = do ps <- importDialog Qt.eAnyFile w case ps of [] -> return () (p:_) -> sendTo h $ PatternP.StorePatch p action_file_importFile :: DatabaseP.Handle -> Qt.QWidget () -> Qt.QAction () -> IO () action_file_importFile db w _ = do ps <- importDialog Qt.eExistingFile w sendTo db $ DatabaseP.Import ps action_file_importDirectory :: DatabaseP.Handle -> Qt.QWidget () -> Qt.QAction () -> IO () action_file_importDirectory db w _ = do ps <- importDialog Qt.eDirectory w sendTo db $ DatabaseP.Import ps action_pattern_playPause :: PatternP.Handle -> Qt.QWidget () -> Qt.QAction () -> IO () action_pattern_playPause h _ a = do b <- Qt.isChecked a () sendTo h $ PatternP.Transport $ if b then PatternP.Start else PatternP.Pause action_pattern_reset :: PatternP.Handle -> Qt.QWidget () -> Qt.QAction () -> IO () action_pattern_reset h _ _ = sendTo h $ PatternP.Transport PatternP.Reset action_pattern_run :: PatternP.Handle -> Qt.QWidget () -> Qt.QAction () -> IO () action_pattern_run h _ _ = sendTo h PatternP.RunPatch action_pattern_mute :: Int -> PatternP.Handle -> Qt.QWidget () -> Qt.QAction () -> IO () action_pattern_mute i h _ a = do b <- Qt.isChecked a () sendTo h $ PatternP.Mute i b scaleFeatureSpace :: Double -> Qt.QGraphicsView () -> IO () scaleFeatureSpace s v = Qt.qscale v (s, s) setScaleFeatureSpace :: Double -> Qt.QGraphicsView () -> IO () setScaleFeatureSpace s v = do Qt.resetTransform v () Qt.qscale v (s, s) action_featureSpace_zoom_zoomIn :: Qt.QGraphicsView () -> Qt.QWidget () -> Qt.QAction () -> IO () action_featureSpace_zoom_zoomIn v _ _ = scaleFeatureSpace 2.0 v action_featureSpace_zoom_zoomOut :: Qt.QGraphicsView () -> Qt.QWidget () -> Qt.QAction () -> IO () action_featureSpace_zoom_zoomOut v _ _ = scaleFeatureSpace 0.5 v action_featureSpace_zoom_reset :: Qt.QGraphicsView () -> Qt.QWidget () -> Qt.QAction () -> IO () action_featureSpace_zoom_reset v _ _ = setScaleFeatureSpace 600 v action_closeActiveWindow :: Qt.QWidget () -> Qt.QAction () -> IO () action_closeActiveWindow _ _ = Qt.qApplicationActiveWindow () >>= flip Qt.close () >> return () action_showWindow :: MainWindow -> Qt.QWidget () -> Qt.QAction () -> IO () action_showWindow w _ _ = Qt.qshow w () >> Qt.activateWindow w () action_help_openUrl :: String -> Qt.QWidget () -> Qt.QAction () -> IO () action_help_openUrl url _ _ = App.openUrl url >> return () action_help_manual :: Qt.QWidget () -> Qt.QAction () -> IO () action_help_manual = action_help_openUrl "http://mescaline.globero.es/documentation/manual" action_help_patternRef :: Qt.QWidget () -> Qt.QAction () -> IO () action_help_patternRef = action_help_openUrl "http://mescaline.globero.es/doc/html/mescaline/Mescaline-Synth-Pattern-ASTLib.html" action_help_openExample :: PatternP.Handle -> FilePath -> Qt.QWidget () -> Qt.QAction () -> IO () action_help_openExample process path _ _ = sendTo process (PatternP.LoadPatch path) appMain :: AppT IO () appMain = do -- mapM_ (\(l,p) -> liftIO $ Log.updateGlobalLogger l (Log.setLevel p)) =<< Log.getComponents app <- liftIO $ Qt.qApplication () -- Parse arguments args <- App.getArgs dbFile <- case args of (f:_) -> return f _ -> App.getUserDataPath "mescaline.db" let pattern = case args of (_:p:_) -> p _ -> ".*" mainWindow <- liftIO . loadUI =<< App.getResourcePath "mescaline.ui" editorWindow <- liftIO . loadUI =<< App.getResourcePath "editor.ui" logWindow <- liftIO . loadUI =<< App.getResourcePath "messages.ui" -- createLoggers logWindow -- Qt.setHandler mainWindow "keyPressEvent(QKeyEvent*)" $ windowKeyPressEvent -- Synth process (synthP, synthQuit) <- SynthP.new -- Feature space process fspaceP <- liftIO FeatureSpaceP.new -- Feature space view (fspaceView, fspaceViewP) <- FeatureSpaceView.new fspaceP synthP -- Sequencer process defaultPatch <- Patch.defaultPatch patternP <- PatternP.new defaultPatch fspaceP (patternView, patternViewP) <- PatternView.new patternP (Qt.objectCast editorWindow) examplesDir <- App.getResourcePath "patches/examples" appVersion <- App.version liftIO $ do connect Left fspaceP fspaceViewP connect (\x -> case x of SynthP.UnitStarted _ u -> Right $ FeatureSpaceView.HighlightOn u SynthP.UnitStopped _ u -> Right $ FeatureSpaceView.HighlightOff u) synthP fspaceViewP fspace_graphicsView <- Qt.findChild mainWindow ("<QGraphicsView*>", "featureSpaceView") Qt.setScene fspace_graphicsView fspaceView patternViewP `listenTo` patternP -- Sequencer view seq_graphicsView <- Qt.findChild mainWindow ("<QGraphicsView*>", "sequencerView") Qt.setScene seq_graphicsView patternView -- Database process dbP <- DatabaseP.new connect (\(DatabaseP.Changed path pattern) -> FeatureSpaceP.LoadDatabase path pattern) dbP fspaceP sendTo dbP $ DatabaseP.Load dbFile pattern -- Pattern process patternToFSpaceP <- spawn $ fix $ \loop -> do x <- recv case x of PatternP.Event time event -> do Event.withSynth (return ()) (sendTo synthP . SynthP.PlayUnit time) event _ -> return () loop patternToFSpaceP `listenTo` patternP fspaceToPatternP <- spawn $ fix $ \loop -> do x <- recv case x of FeatureSpaceP.RegionChanged _ -> do fspace <- query fspaceP FeatureSpaceP.GetModel sendTo patternP $ PatternP.SetFeatureSpace fspace _ -> return () loop fspaceToPatternP `listenTo` fspaceP -- Pipe feature space view output to synth -- toSynthP <- spawn $ fix $ \loop -> do -- x <- recv -- case x of -- FeatureSpaceP.UnitActivated t u -> io $ writeChan synth_ichan (Left (t, (FeatureSpace.unit u))) -- _ -> return () -- loop -- toSynthP `listenTo` fspaceP -- Set up actions and menus examplesMenu <- directoryMenu (action_help_openExample patternP) ["msc"] examplesDir let aboutAction = Action "about" "About Mescaline" "Show about message box" Trigger Nothing (action_about appVersion) osMenu = case App.buildOS of App.OSX -> Just $ Menu "about" "about.Mescaline" [ aboutAction ] _ -> Nothing mkHelpMenu actions = case App.buildOS of App.OSX -> actions _ -> aboutAction:actions menuDef = maybeToList osMenu ++ [ Menu "file" "File" [ Action "openFile" "Open..." "Open file" Trigger (Just "Ctrl+o") (action_file_openFile patternP) , Action "saveFile" "Save" "Save file" Trigger (Just "Ctrl+s") (action_file_saveFile patternP) , Separator , Action "importFile" "Import File..." "Import a file" Trigger (Just "Ctrl+i") (action_file_importFile dbP) , Action "importDirectory" "Import Directory..." "Import a directory" Trigger (Just "Ctrl+Shift+I") (action_file_importDirectory dbP) ] , Menu "sequencer" "Sequencer" [ Action "play" "Play" "Start or pause the sequencer" Checkable (Just "SPACE") (action_pattern_playPause patternP) , Action "reset" "Reset" "Reset the sequencer" Trigger (Just "Ctrl+RETURN") (action_pattern_reset patternP) , Action "run" "Run Patch" "Run the current patch" Trigger (Just "Ctrl+r") (action_pattern_run patternP) , Menu "mute" "Mute" (flip map [0..7] $ \i -> Action ("mute" ++ show i) ("Mute track " ++ show (i + 1)) "" Checkable (Just ("Ctrl+" ++ show (i + 1))) (action_pattern_mute i patternP)) ] , Menu "featureSpace" "FeatureSpace" [ Menu "zoom" "Zoom" [ Action "zoomIn" "Zoom In" "Zoom into feature space" Trigger (Just "Ctrl++") (action_featureSpace_zoom_zoomIn fspace_graphicsView) , Action "zoomOut" "Zoom Out" "Zoom out of feature space" Trigger (Just "Ctrl+-") (action_featureSpace_zoom_zoomOut fspace_graphicsView) , Action "reset" "Reset" "Reset feature space zoom" Trigger (Just "Ctrl+0") (action_featureSpace_zoom_reset fspace_graphicsView) ] ] , Menu "window" "Window" [ Action "closeWindow" "Close" "Close window" Trigger (Just "Ctrl+w") action_closeActiveWindow , Separator , Action "mainWindow" "Main" "Show main window" Trigger (Just "Ctrl+Shift+w") (action_showWindow mainWindow) , Action "editorWindow" "Editor" "Show editor window" Trigger (Just "Ctrl+Shift+e") (action_showWindow editorWindow) , Separator , Action "logWindow" "Messages" "Show message window" Trigger (Just "Ctrl+Shift+m") (action_showWindow logWindow) , Action "clearLog" "Clear Messages" "Clear message window" Trigger (Just "Ctrl+Shift+c") (const (const (clearLog logWindow))) ] , Menu "help" "Help" $ mkHelpMenu [ Action "help" "Mescaline Help" "Open Mescaline manual in browser" Trigger Nothing action_help_manual , Action "help_patternRef" "Pattern Reference" "Open pattern reference in browser" Trigger Nothing action_help_patternRef , Separator , Menu "help_examples" "Examples" examplesMenu ] ] actions <- defineWindowMenu menuDef (Qt.objectCast mainWindow) trigger "/featureSpace/zoom/reset" actions defineWindowMenu menuDef (Qt.objectCast editorWindow) defineWindowMenu menuDef (Qt.objectCast logWindow) -- OSC server process oscServer <- OSCServer.new 2010 synthP fspaceP -- Start the application Qt.qshow mainWindow () Qt.activateWindow mainWindow () ok <- Qt.qApplicationExec () -- Signal synth thread and wait for it to exit. -- Otherwise stale scsynth processes will be lingering around. synthQuit putStrLn "Bye sucker." Qt.returnGC main :: IO () main = App.runAppT appMain =<< App.mkApp "Mescaline" Paths.version Paths.getBinDir Paths.getDataDir App.defaultConfigFiles
kaoskorobase/mescaline
app/main.hs
gpl-3.0
24,271
0
28
6,441
6,223
3,197
3,026
393
8
module Lib where import Utils.All import Assets import AssetUtils import LanguageDef.Data.LanguageDef import LanguageDef.ModuleLoader import LanguageDef.Data.Function import LanguageDef.Data.Expression import LanguageDef.Utils.LocationInfo import LanguageDef.Interpreter import LanguageDef.Prover import LanguageDef.API import LanguageDef.LangDefs import Repl (repl, trepl, replAsset) import Data.Map as M
pietervdvn/ALGT2
src/Lib.hs
gpl-3.0
418
0
5
48
85
55
30
15
0
{-# LANGUAGE DeriveGeneric, FlexibleInstances, OverloadedStrings, TypeFamilies #-} module Kraken.Request.Balance ( Balance(..) ) where import qualified Kraken.Result.Balance as R import Kraken.Request import Kraken.Tools.ToURLEncoded import GHC.Generics data Balance = Balance deriving Generic instance ToURLEncoded Balance instance Request Balance where type Result Balance = R.Balance urlPart _ = "Balance"
laugh-at-me/kraken-api
src/Kraken/Request/Balance.hs
gpl-3.0
441
1
8
78
87
52
35
13
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Calendar.Calendars.Clear -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Clears a primary calendar. This operation deletes all events associated -- with the primary calendar of an account. -- -- /See:/ <https://developers.google.com/google-apps/calendar/firstapp Calendar API Reference> for @calendar.calendars.clear@. module Network.Google.Resource.Calendar.Calendars.Clear ( -- * REST Resource CalendarsClearResource -- * Creating a Request , calendarsClear , CalendarsClear -- * Request Lenses , ccCalendarId ) where import Network.Google.AppsCalendar.Types import Network.Google.Prelude -- | A resource alias for @calendar.calendars.clear@ method which the -- 'CalendarsClear' request conforms to. type CalendarsClearResource = "calendar" :> "v3" :> "calendars" :> Capture "calendarId" Text :> "clear" :> QueryParam "alt" AltJSON :> Post '[JSON] () -- | Clears a primary calendar. This operation deletes all events associated -- with the primary calendar of an account. -- -- /See:/ 'calendarsClear' smart constructor. newtype CalendarsClear = CalendarsClear' { _ccCalendarId :: Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CalendarsClear' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccCalendarId' calendarsClear :: Text -- ^ 'ccCalendarId' -> CalendarsClear calendarsClear pCcCalendarId_ = CalendarsClear' {_ccCalendarId = pCcCalendarId_} -- | Calendar identifier. To retrieve calendar IDs call the calendarList.list -- method. If you want to access the primary calendar of the currently -- logged in user, use the \"primary\" keyword. ccCalendarId :: Lens' CalendarsClear Text ccCalendarId = lens _ccCalendarId (\ s a -> s{_ccCalendarId = a}) instance GoogleRequest CalendarsClear where type Rs CalendarsClear = () type Scopes CalendarsClear = '["https://www.googleapis.com/auth/calendar"] requestClient CalendarsClear'{..} = go _ccCalendarId (Just AltJSON) appsCalendarService where go = buildClient (Proxy :: Proxy CalendarsClearResource) mempty
brendanhay/gogol
gogol-apps-calendar/gen/Network/Google/Resource/Calendar/Calendars/Clear.hs
mpl-2.0
3,003
0
13
631
311
192
119
47
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.Logging.BillingAccounts.Operations.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the latest state of a long-running operation. Clients can use this -- method to poll the operation result at intervals as recommended by the -- API service. -- -- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.billingAccounts.operations.get@. module Network.Google.Resource.Logging.BillingAccounts.Operations.Get ( -- * REST Resource BillingAccountsOperationsGetResource -- * Creating a Request , billingAccountsOperationsGet , BillingAccountsOperationsGet -- * Request Lenses , baogXgafv , baogUploadProtocol , baogAccessToken , baogUploadType , baogName , baogCallback ) where import Network.Google.Logging.Types import Network.Google.Prelude -- | A resource alias for @logging.billingAccounts.operations.get@ method which the -- 'BillingAccountsOperationsGet' request conforms to. type BillingAccountsOperationsGetResource = "v2" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Operation -- | Gets the latest state of a long-running operation. Clients can use this -- method to poll the operation result at intervals as recommended by the -- API service. -- -- /See:/ 'billingAccountsOperationsGet' smart constructor. data BillingAccountsOperationsGet = BillingAccountsOperationsGet' { _baogXgafv :: !(Maybe Xgafv) , _baogUploadProtocol :: !(Maybe Text) , _baogAccessToken :: !(Maybe Text) , _baogUploadType :: !(Maybe Text) , _baogName :: !Text , _baogCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BillingAccountsOperationsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'baogXgafv' -- -- * 'baogUploadProtocol' -- -- * 'baogAccessToken' -- -- * 'baogUploadType' -- -- * 'baogName' -- -- * 'baogCallback' billingAccountsOperationsGet :: Text -- ^ 'baogName' -> BillingAccountsOperationsGet billingAccountsOperationsGet pBaogName_ = BillingAccountsOperationsGet' { _baogXgafv = Nothing , _baogUploadProtocol = Nothing , _baogAccessToken = Nothing , _baogUploadType = Nothing , _baogName = pBaogName_ , _baogCallback = Nothing } -- | V1 error format. baogXgafv :: Lens' BillingAccountsOperationsGet (Maybe Xgafv) baogXgafv = lens _baogXgafv (\ s a -> s{_baogXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). baogUploadProtocol :: Lens' BillingAccountsOperationsGet (Maybe Text) baogUploadProtocol = lens _baogUploadProtocol (\ s a -> s{_baogUploadProtocol = a}) -- | OAuth access token. baogAccessToken :: Lens' BillingAccountsOperationsGet (Maybe Text) baogAccessToken = lens _baogAccessToken (\ s a -> s{_baogAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). baogUploadType :: Lens' BillingAccountsOperationsGet (Maybe Text) baogUploadType = lens _baogUploadType (\ s a -> s{_baogUploadType = a}) -- | The name of the operation resource. baogName :: Lens' BillingAccountsOperationsGet Text baogName = lens _baogName (\ s a -> s{_baogName = a}) -- | JSONP baogCallback :: Lens' BillingAccountsOperationsGet (Maybe Text) baogCallback = lens _baogCallback (\ s a -> s{_baogCallback = a}) instance GoogleRequest BillingAccountsOperationsGet where type Rs BillingAccountsOperationsGet = Operation type Scopes BillingAccountsOperationsGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only", "https://www.googleapis.com/auth/logging.admin", "https://www.googleapis.com/auth/logging.read"] requestClient BillingAccountsOperationsGet'{..} = go _baogName _baogXgafv _baogUploadProtocol _baogAccessToken _baogUploadType _baogCallback (Just AltJSON) loggingService where go = buildClient (Proxy :: Proxy BillingAccountsOperationsGetResource) mempty
brendanhay/gogol
gogol-logging/gen/Network/Google/Resource/Logging/BillingAccounts/Operations/Get.hs
mpl-2.0
5,233
0
15
1,127
708
416
292
104
1
module Codewars.Kata.Addition where -- What should add's type be? add :: Num n => n -> n -> n add = (+)
ice1000/OI-codes
codewars/1-100/functional-addition.hs
agpl-3.0
105
0
7
23
35
21
14
3
1
-- Copyright 2016 TensorFlow authors. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. {-# LANGUAGE OverloadedStrings #-} module Main where import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.Word (Word8) import Data.Serialize (runGet, runPut) import Test.Framework (Test, defaultMain) import Test.Framework.Providers.QuickCheck2 (testProperty) import TensorFlow.Records (getTFRecord, putTFRecord) main :: IO () main = defaultMain tests tests :: [Test] tests = [ testProperty "Inverse" propEncodeDecodeInverse , testProperty "FixedRecord" propFixedRecord ] -- There's no (Arbitrary BL.ByteString), so pack it from a list of chunks. propEncodeDecodeInverse :: [[Word8]] -> Bool propEncodeDecodeInverse s = let bs = BL.fromChunks . fmap B.pack $ s in runGet getTFRecord (runPut (putTFRecord bs)) == Right bs propFixedRecord :: Bool propFixedRecord = ("\x42" == case runGet getTFRecord record of Left err -> error err -- Make the error appear in the test failure. Right x -> x) && (runPut (putTFRecord "\x42") == record) where record = "\x01\x00\x00\x00\x00\x00\x00\x00" <> "\x01\x75\xde\x41" <> "\x42" <> "\x52\xcf\xb8\x1e"
tensorflow/haskell
tensorflow-records/tests/Main.hs
apache-2.0
1,745
0
12
313
304
174
130
27
2
{-# LANGUAGE OverloadedStrings #-} module Spark.Core.InternalStd.Observable( asDouble, localPackBuilder) where import qualified Spark.Core.InternalStd.Column as C import Spark.Core.Internal.DatasetStructures import Spark.Core.Internal.FunctionsInternals import Spark.Core.Internal.TypesGenerics(SQLTypeable) import Spark.Core.Internal.NodeBuilder import Spark.Core.Internal.OpStructures import Spark.Core.Internal.TypesStructures(DataType) import Spark.Core.Internal.TypesFunctions(structTypeTuple') import Spark.Core.Internal.Utilities import Spark.Core.Try {-| Casts a local data as a double. -} asDouble :: (Num a, SQLTypeable a) => LocalData a -> LocalData Double asDouble = projectColFunction C.asDouble {-| Packs observables together into a single observable. This is required to apply transforms. -} localPackBuilder :: (HasCallStack) => NodeBuilder localPackBuilder = buildOpVariable "org.spark.LocalPack" $ \nss -> do -- Check that the inputs are not empty and all local. dts <- _checkLocal nss -- Make a tuple with all the inputs let dt = structTypeTuple' dts let no = NodeLocalOp $ StandardOperator "org.spark.LocalPack" dt emptyExtra let cni = coreNodeInfo dt Local no return cni _checkLocal :: (HasCallStack) => [NodeShape] -> Try (NonEmpty DataType) _checkLocal [] = tryError "localPackBuilder: no input provided" _checkLocal (h : t) = sequence $ f <$> (h :| t) where f ns | nsLocality ns == Distributed = tryError "localPackBuilder: parent node should be local" f ns = pure $ nsType ns
tjhunter/karps
haskell/src/Spark/Core/InternalStd/Observable.hs
apache-2.0
1,543
0
13
225
353
195
158
-1
-1
{-# LANGUAGE TemplateHaskell #-} module DistRemoteServer where import Control.Concurrent (threadDelay) import Control.Distributed.Process import Control.Distributed.Process.Node import Control.Distributed.Process.Closure import Control.Monad (forever) import Network.Transport.TCP (TCPParameters (..), createTransport, defaultTCPParameters) sampleTask :: (Int, String) -> Process () sampleTask (t, s) = liftIO (threadDelay (t * 1000 * 1000)) >> say s remotable ['sampleTask] myRemoteTable :: RemoteTable myRemoteTable = __remoteTable initRemoteTable main :: IO () main = do Right transport <- createTransport "127.0.0.1" "10501" defaultTCPParameters node <- newLocalNode transport myRemoteTable runProcess node $ do us <- getSelfNode _ <- spawnLocal $ sampleTask (1 :: Int, "using spawnLocal") pid <- spawn us $ $(mkClosure 'sampleTask) (1 :: Int, "using spawn") liftIO $ threadDelay (200 * 10000)
songpp/my-haskell-playground
src/DistRemoteServer.hs
apache-2.0
1,013
0
15
224
285
152
133
23
1
module Graphics.GL.Low.Texture ( -- | Textures are objects that contain image data that can be sampled by -- a shader. An obvious application of this is texture mapping, but there -- are many other uses for textures. The image data doesn't have to be an -- image at all, it can represent anything. -- -- Each sampler uniform in your shader points to a texture unit (zero by -- default). This texture unit is where it will read texture data from. To -- assign a texture to a texture unit, use 'setActiveTextureUnit' then bind -- a texture. This will not only bind it to the relevant texture binding target -- but also to the active texture unit. You can change which unit a sampler -- points to by setting it using the 'Graphics.GL.Low.Shader.setUniform1i' -- command. -- -- You can avoid dealing with active texture units if theres only one -- sampler because the default unit is zero. newTexture2D, newCubeMap, newEmptyTexture2D, newEmptyCubeMap, deleteTexture, bindTexture2D, bindTextureCubeMap, setActiveTextureUnit, setTex2DFiltering, setCubeMapFiltering, setTex2DWrapping, setCubeMapWrapping, Texture, ImageFormat(..), Filtering(..), Wrapping(..) -- * Example -- $example ) where import Prelude hiding (sequence) import Foreign.Ptr import Foreign.Marshal import Foreign.Storable import Data.Vector.Storable import Data.Word import Control.Applicative import Data.Traversable (sequence) import Graphics.GL import Graphics.GL.Low.Types import Graphics.GL.Low.Classes import Graphics.GL.Low.Cube import Graphics.GL.Low.Common getTex2DBinding :: IO GLint getTex2DBinding = alloca $ \ptr -> do glGetIntegerv GL_TEXTURE_BINDING_2D ptr peek ptr getCubemapBinding :: IO GLint getCubemapBinding = alloca $ \ptr -> do glGetIntegerv GL_TEXTURE_BINDING_CUBE_MAP ptr peek ptr -- | Create a new 2D texture from raw image data, its dimensions, and the -- assumed image format. The dimensions should be powers of 2. newTexture2D :: Storable a => Vector a -> (Int,Int) -> ImageFormat -> IO Texture newTexture2D src (w,h) format = do orig <- getTex2DBinding n <- alloca (\ptr -> glGenTextures 1 ptr >> peek ptr) glBindTexture GL_TEXTURE_2D n unsafeWith src $ \ptr -> glTexImage2D GL_TEXTURE_2D 0 (toGL format) (fromIntegral w) (fromIntegral h) 0 (toGL format) GL_UNSIGNED_BYTE (castPtr ptr) glGenerateMipmap GL_TEXTURE_2D glBindTexture GL_TEXTURE_2D (fromIntegral orig) return (Texture n format) -- | Create a new cubemap texture from six raw data sources. Each side will have -- the same format. newCubeMap :: Storable a => Cube (Vector a, (Int,Int)) -> ImageFormat -> IO Texture newCubeMap images format = do orig <- getCubemapBinding n <- alloca (\ptr -> glGenTextures 1 ptr >> peek ptr) glBindTexture GL_TEXTURE_CUBE_MAP n sequence_ (liftA2 (loadCubeMapSide format) images cubeSideCodes) glGenerateMipmap GL_TEXTURE_CUBE_MAP glBindTexture GL_TEXTURE_CUBE_MAP (fromIntegral orig) return (Texture n format) loadCubeMapSide :: Storable a => ImageFormat -> (Vector a, (Int,Int)) -> GLenum -> IO () loadCubeMapSide format (src, (w,h)) side = unsafeWith src $ \ptr -> glTexImage2D side 0 (toGL format) (fromIntegral w) (fromIntegral h) 0 (toGL format) GL_UNSIGNED_BYTE (castPtr ptr) -- | Create an empty texture with the specified dimensions and format. newEmptyTexture2D :: Int -> Int -> ImageFormat -> IO Texture newEmptyTexture2D w h format = do orig <- getTex2DBinding let w' = fromIntegral w let h' = fromIntegral h n <- alloca (\ptr -> glGenTextures 1 ptr >> peek ptr) glBindTexture GL_TEXTURE_2D n glTexImage2D GL_TEXTURE_2D 0 (toGL format) w' h' 0 (toGL format) GL_UNSIGNED_BYTE nullPtr glBindTexture GL_TEXTURE_2D (fromIntegral orig) return (Texture n format) -- | Create a cubemap texture where each of the six sides has the specified -- dimensions and format. newEmptyCubeMap :: Int -> Int -> ImageFormat -> IO Texture newEmptyCubeMap w h format = do orig <- getCubemapBinding let w' = fromIntegral w let h' = fromIntegral h n <- alloca (\ptr -> glGenTextures 1 ptr >> peek ptr) let fmt = toGL format let fmt' = toGL format glBindTexture GL_TEXTURE_CUBE_MAP n glTexImage2D GL_TEXTURE_CUBE_MAP_POSITIVE_X 0 fmt w' h' 0 fmt' GL_UNSIGNED_BYTE nullPtr glTexImage2D GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0 fmt w' h' 0 fmt' GL_UNSIGNED_BYTE nullPtr glTexImage2D GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0 fmt w' h' 0 fmt' GL_UNSIGNED_BYTE nullPtr glTexImage2D GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0 fmt w' h' 0 fmt' GL_UNSIGNED_BYTE nullPtr glTexImage2D GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0 fmt w' h' 0 fmt' GL_UNSIGNED_BYTE nullPtr glTexImage2D GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0 fmt w' h' 0 fmt' GL_UNSIGNED_BYTE nullPtr glBindTexture GL_TEXTURE_CUBE_MAP (fromIntegral orig) return (Texture n format) -- | Delete a texture. deleteTexture :: Texture -> IO () deleteTexture tex = withArray [texObjectName tex] (\ptr -> glDeleteTextures 1 ptr) -- | Bind a 2D texture to the 2D texture binding target and the currently -- active texture unit. bindTexture2D :: Texture -> IO () bindTexture2D = glBindTexture GL_TEXTURE_2D . texObjectName -- | Bind a cubemap texture to the cubemap texture binding target and -- the currently active texture unit. bindTextureCubeMap :: Texture -> IO () bindTextureCubeMap = glBindTexture GL_TEXTURE_CUBE_MAP . texObjectName -- | Set the active texture unit. The default is zero. setActiveTextureUnit :: Int -> IO () setActiveTextureUnit n = glActiveTexture (GL_TEXTURE0 + fromIntegral n) -- | Set the filtering for the 2D texture currently bound to the 2D texture -- binding target. setTex2DFiltering :: Filtering -> IO () setTex2DFiltering filt = do glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER (toGL filt) glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER (toGL filt) -- | Set the filtering for the cubemap texture currently bound to the cubemap -- texture binding target. setCubeMapFiltering :: Filtering -> IO () setCubeMapFiltering filt = do glTexParameteri GL_TEXTURE_CUBE_MAP GL_TEXTURE_MIN_FILTER (toGL filt) glTexParameteri GL_TEXTURE_CUBE_MAP GL_TEXTURE_MAG_FILTER (toGL filt) -- | Set the wrapping mode for the 2D texture currently bound to the 2D -- texture binding target. setTex2DWrapping :: Wrapping -> IO () setTex2DWrapping wrap = do glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_S (toGL wrap) glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_T (toGL wrap) -- | Set the wrapping mode for the cubemap texture currently bound to the -- cubemap texture binding target. Because no filtering occurs between cube -- faces you probably want ClampToEdge. setCubeMapWrapping :: Wrapping -> IO () setCubeMapWrapping wrap = do glTexParameteri GL_TEXTURE_CUBE_MAP GL_TEXTURE_WRAP_S (toGL wrap) glTexParameteri GL_TEXTURE_CUBE_MAP GL_TEXTURE_WRAP_T (toGL wrap) glTexParameteri GL_TEXTURE_CUBE_MAP GL_TEXTURE_WRAP_R (toGL wrap) -- | Texture filtering modes. data Filtering = Nearest | -- ^ No interpolation. Linear -- ^ Linear interpolation. deriving Show instance ToGL Filtering where toGL Nearest = GL_NEAREST toGL Linear = GL_LINEAR -- | Texture wrapping modes. data Wrapping = Repeat | -- ^ Tile the texture past the boundary. MirroredRepeat | -- ^ Tile the texture but mirror every other tile. ClampToEdge -- ^ Use the edge color for anything past the boundary. deriving Show instance ToGL Wrapping where toGL Repeat = GL_REPEAT toGL MirroredRepeat = GL_MIRRORED_REPEAT toGL ClampToEdge = GL_CLAMP_TO_EDGE -- $example -- -- <<texture.png Screenshot of Texture Example>> -- -- This example loads a PNG file with JuicyPixels and displays the image on a -- square. Since the window is not square and no aspect ratio transformation -- was applied, the picture is squished. -- -- @ -- module Main where -- -- import Control.Monad.Loops (whileM_) -- import qualified Data.Vector.Storable as V -- import Codec.Picture -- import Data.Word -- -- import qualified Graphics.UI.GLFW as GLFW -- import Linear -- import Graphics.GL.Low -- -- main = do -- GLFW.init -- GLFW.windowHint (GLFW.WindowHint'ContextVersionMajor 3) -- GLFW.windowHint (GLFW.WindowHint'ContextVersionMinor 2) -- GLFW.windowHint (GLFW.WindowHint'OpenGLForwardCompat True) -- GLFW.windowHint (GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core) -- mwin <- GLFW.createWindow 640 480 \"Texture\" Nothing Nothing -- case mwin of -- Nothing -> putStrLn "createWindow failed" -- Just win -> do -- GLFW.makeContextCurrent (Just win) -- GLFW.swapInterval 1 -- (vao, prog, texture) <- setup -- whileM_ (not \<$\> GLFW.windowShouldClose win) $ do -- GLFW.pollEvents -- draw vao prog texture -- GLFW.swapBuffers win -- -- setup = do -- -- establish a VAO -- vao <- newVAO -- bindVAO vao -- -- load the shader -- vsource <- readFile "texture.vert" -- fsource <- readFile "texture.frag" -- prog <- newProgram vsource fsource -- useProgram prog -- -- load the vertices -- let blob = V.fromList -- a quad has four vertices -- [ -0.5, -0.5, 0, 1 -- , -0.5, 0.5, 0, 0 -- , 0.5, -0.5, 1, 1 -- , 0.5, 0.5, 1, 0 ] :: V.Vector Float -- vbo <- newBufferObject blob StaticDraw -- bindVBO vbo -- setVertexLayout [ Attrib "position" 2 GLFloat -- , Attrib "texcoord" 2 GLFloat ] -- -- load the element array to draw a quad with two triangles -- indices <- newElementArray (V.fromList [0,1,2,3,2,1] :: V.Vector Word8) StaticDraw -- bindElementArray indices -- -- load the texture with JuicyPixels -- let fromRight (Right x) = x -- ImageRGBA8 (Image w h image) <- fromRight \<$\> readImage "logo.png" -- texture <- newTexture2D image (w,h) RGBA -- setTex2DFiltering Linear -- return (vao, prog, texture) -- -- draw vao prog texture = do -- clearColorBuffer (0.5, 0.5, 0.5) -- bindVAO vao -- useProgram prog -- bindTexture2D texture -- drawIndexedTriangles 6 UByteIndices -- @ -- -- The vertex shader for this example looks like -- -- @ -- #version 150 -- in vec2 position; -- in vec2 texcoord; -- out vec2 Texcoord; -- void main() -- { -- gl_Position = vec4(position, 0.0, 1.0); -- Texcoord = texcoord; -- } -- @ -- -- And the fragment shader looks like -- -- @ -- #version 150 -- in vec2 Texcoord; -- out vec4 outColor; -- uniform sampler2D tex; -- void main() -- { -- outColor = texture(tex, Texcoord); -- } -- @
evanrinehart/lowgl
Graphics/GL/Low/Texture.hs
bsd-2-clause
10,633
0
12
2,064
1,748
934
814
152
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} -- | A module responsible for identifying occurrences of the -- Walenty valency dictionary entries in the Skladnica treebank. module NLP.Skladnica.Walenty.Mapping ( -- * Types and Funs Edge , terminals , querify , markSklTree -- * Utilities , trunk , hasBase , hasTag , hasOrth ) where import Control.Applicative (empty, (<|>)) import Control.Monad (guard) import qualified Control.Monad.State.Strict as E import Control.Monad.Trans.Maybe (MaybeT (..), mapMaybeT) -- import Data.Foldable (foldMap) import Data.List (foldl') import qualified Data.Map.Strict as M import Data.Maybe (catMaybes, fromMaybe, isJust) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Tree as R -- import qualified Data.Text.Lazy as L import qualified NLP.Skladnica as S import qualified NLP.Walenty.Types as W import qualified NLP.Skladnica.Walenty.Search2 as Q import qualified NLP.Skladnica.Walenty.MweTree as MWE -- | `Edge` from Składnica (or rather, node with info about the ingoing edge). type Edge = S.Edge S.Node S.IsHead -- | Morphosyntactic attribute. type Attr = Text type AttrVal = Text -- | Retrieve terminal leaves of the given tree. terminals :: MWE.InTree -> [S.Term] terminals = let getTerm S.Node{..} = case label of Left _ -> [] Right t -> [t] in foldMap getTerm . S.simplify -- | Mark Składnica tree with MWEs. -- markSklTree :: [Q.Expr Edge 'Q.Tree] -> MWE.InTree -> MWE.OutTree markSklTree :: [(Q.Expr Edge 'Q.Tree, MWE.MweInfo)] -> MWE.InTree -> MWE.OutTree markSklTree = Q.markAll (S.nid . S.nodeLabel) -- markSklTree = -- let atts = MWE.MweInfo -- { MWE.origin = Just "walenty" -- , MWE.mweTyp = Nothing -- , MWE.reading = Nothing } -- in Q.markAll (S.nid . S.nodeLabel) . map (, atts) -- | Convert the given verbal entry from Walenty to a query. -- -- TODO: The following are ignored for the moment: -- -- * Negativity -- * Predicativity -- * ... -- querify :: W.Verb -> Q.Expr Edge Q.Tree querify verb = Q.andQ [ trunk . hasBase . W.base $ verb , frameQ (W.frame verb) ] -- | A query expression for a frame. -- -- TODO: At the moment it is not enfornced that each argument -- is realized by a different tree child node! frameQ :: W.Frame -> Q.Expr Edge Q.Tree -- frameQ frame = andQ $ map (Child . Child . argumentQ) frame frameQ frame = Q.andQ $ map (Q.anyChild . metaArgQ) frame -- | Pseudo-frame in which one or more of the arguments must be realized. -- Useful within the context of constraints on dependents, which are -- called "frames" but are not really. -- -- TODO: Difficult choice, sometimes it seems that all dependents specified -- in `RAtr` should be present, sometimes that only some of them... pseudoFrameQ :: W.Frame -> Q.Expr Edge Q.Tree -- pseudoFrameQ frame = orQ $ map (Child . metaArgQ) frame pseudoFrameQ = frameQ -- | Handle (and ignore) nodes explicitely marked -- with "fw", "fl", "ff". metaArgQ :: W.Argument -> Q.Expr Edge Q.Tree metaArgQ arg = Q.ifThenElse isMetaNode -- (skipAnyChild argument) (Q.anyChild argument) argument where argument = argumentQ arg isMetaNode = Q.Current . isNonTerm $ \S.NonTerm{..} -> cat `elem` ["fw", "fl", "ff"] -- | A query expression for an argument. -- TODO: function ignored. argumentQ :: W.Argument -> Q.Expr Edge Q.Tree argumentQ arg = let f = W.function arg in Q.orQ . map (phraseQ f) $ W.phraseAlt arg phraseQ :: Maybe W.Function -> W.Phrase -> Q.Expr Edge Q.Tree phraseQ f p = case p of W.Standard s -> stdPhraseQ f s W.Special s -> specPhraseQ f s stdPhraseQ :: Maybe W.Function -- ^ Subject, object -> W.StdPhrase -> Q.Expr Edge Q.Tree stdPhraseQ mayFun phrase = case phrase of W.NP{..} -> Q.andQ [ Q.Current $ Q.andQ [ hasCat "fno" , caseQ mayFun caseG , Q.maybeQ agrNumber agreeNumQ ] , Q.andQ [ lexicalQ lexicalHead , dependentsQ dependents ] ] W.PrepNP{..} -> Q.andQ [ Q.Current $ Q.andQ [ hasCat "fpm" , hasAttr przyimek $ preposition , hasAttr klasa "rzecz" , caseQ mayFun caseG ] -- we "skip" the child so that potential agreement works -- between the parent of PP and the NP (not sure if this -- is necessary) -- , skipAnyChild $ andQ , Q.anyChild $ Q.andQ [ Q.Current $ hasCat "fno" , Q.Current $ Q.maybeQ agrNumber agreeNumQ , lexicalQ lexicalHead , dependentsQ dependents ] ] -- Don't know how to handle this yet, and it is not handled -- by the default handler below (which referes to dependents) W.ComparP{} -> Q.B False -- By default we check if (a) lexical requirements are satisfied for the -- argument itself, directly, or (b) for one of its children, which makes -- sense for certain phrase types (e.g., `CP`) p -> let checkLex = Q.andQ [ lexicalQ (W.lexicalHead p) , dependentsQ (W.dependents p) ] -- in checkLex `Or` skipAnyChild checkLex in checkLex `Q.Or` Q.anyChild checkLex -- W.CP{..} -> andQ -- [ Current $ andQ -- [ hasCat "fzd" ] -- , anyChild $ andQ -- [ lexicalQ lexicalHead -- , dependentsQ dependents ] -- ] specPhraseQ :: Maybe W.Function -> W.SpecPhrase -> Q.Expr Edge Q.Tree specPhraseQ f p = case p of W.XP{..} -> Q.maybeQ xpVal (phraseQ f) -- TODO: not handled yet W.Fixed{} -> Q.B False _ -> Q.B True -- specPhraseQ _ = B True -- | Constraints on lexical heads. lexicalQ :: [Text] -> Q.Expr Edge Q.Tree lexicalQ xs = if null xs then Q.B True else trunk (hasBases xs) -- | Follow the trunk! trunk :: Q.Expr Edge Q.Node -> Q.Expr Edge Q.Tree trunk = Q.ancestor $ \x -> S.edgeLabel x == S.HeadYes -- | Constraints stemming from the requirements over the dependents. dependentsQ :: W.Attribute -> Q.Expr Edge Q.Tree dependentsQ deps = case deps of -- no modifiers allowed W.NAtr -> Q.NonBranching -- modifiers allowed but optional; TODO: we could check that all modifiers -- present are consistent with the given `Atr` list. W.Atr _ -> Q.B True -- TODO: not distinguished from `Atr` case. W.Atr1 _ -> Q.B True -- at least one of the attributes given in the list must be present W.RAtr xs -> pseudoFrameQ xs -- TODO: we should check that there is at most one modifier. W.RAtr1 xs -> pseudoFrameQ xs _ -> Q.B True -- | Skladnica case value based on the Walenty case value. caseQ :: Maybe W.Function -- ^ Subject, object -> W.Case -> Q.Expr Edge Q.Node caseQ mayFun c = case c of W.Structural -> case mayFun of Just W.Subject -> pr ["mian", "dop"] Just W.Object -> Q.ifThenElse (hasAttr "neg" "nie") (pr ["dop"]) (pr ["bier", "dop"]) Nothing -> pr ["mian", "dop", "bier"] -- W.Structural -> -- Q.ifThenElse -- (hasAttr "neg" "nie") -- (pr ["dop"]) $ -- case mayFun of -- Nothing -> pr ["mian", "bier"] -- Just W.Subject -> pr ["mian"] -- Just W.Object -> pr ["bier"] _ -> pr $ case c of W.Nominative -> sg "mian" W.Genitive -> sg "dop" W.Dative -> sg "cel" W.Accusative -> sg "bier" W.Instrumental -> sg "narz" W.Locative -> sg "miej" W.Partitive -> ["dop", "bier"] -- TODO: not sure if can be resolved at the compilation stage W.Agreement -> [] W.PostPrep -> sg "pop" -- TODO: not handled by Agata's specification W.Predicative -> [] -- -- TODO: structural case should depend on the function, can be -- -- precomputed at the compilation stage. -- W.Structural -> ["mian", "dop", "bier"] W.Structural -> error "caseQ: impossible happened" where sg x = [x] pr xs = if null xs then Q.B True else Q.orQ $ map (hasAttr przypadek) xs -- isNeg = Q.Current . hasAttr "neg" "nie" agreeNumQ :: W.Agree W.Number -> Q.Expr Edge Q.Node agreeNumQ agreeNum = case agreeNum of W.Value v -> hasAttr liczba $ liczbaSKL v -- W.Agree -> Satisfy2 $ \parent child -> isJust $ do -- x <- getAttr liczba parent -- y <- getAttr liczba child -- guard $ x == y _ -> Q.B True -- | Check if the node is a terminal node with the given base. hasBase :: Text -> Q.Expr Edge Q.Node hasBase x = hasBases [x] -- | Check if the node is a terminal node with one of the given orth values. hasOrth :: (Text -> Bool) -> Q.Expr Edge Q.Node hasOrth p0 = let p S.Term{..} = p0 orth in isTerm p `Q.And` Q.Mark -- | Check if the node is a terminal node with one of the given base values. hasBases :: [Text] -> Q.Expr Edge Q.Node hasBases xs = let p S.Term{..} = base `elem` xs in isTerm p `Q.And` Q.Mark -- | Check if the node is a terminal node with the given tag value. hasTag :: Text -> Q.Expr Edge Q.Node hasTag x = isTerm $ \S.Term{..} -> tag == x isNonTerm :: (S.NonTerm -> Bool) -> Q.Expr Edge Q.Node isNonTerm p = Q.SatisfyNode $ \S.Edge{..} -> isJust $ do nonTerm@S.NonTerm{..} <- takeLeft (S.label nodeLabel) guard $ p nonTerm isTerm :: (S.Term -> Bool) -> Q.Expr Edge Q.Node isTerm p = Q.SatisfyNode $ \S.Edge{..} -> isJust $ do term@S.Term{..} <- takeRight (S.label nodeLabel) guard $ p term -- | Check if the node is a non-terminal node with the given category. hasCat :: Text -> Q.Expr Edge Q.Node hasCat x = isNonTerm $ \S.NonTerm{..} -> x == cat -- | Check if the node is a non-terminal node with the given attribute -- and the corresponding value. hasAttr :: Attr -> AttrVal -> Q.Expr Edge Q.Node hasAttr x y = isNonTerm $ \S.NonTerm{..} -> isJust $ do y' <- M.lookup x morph guard $ y == y' getAttr :: Attr -> Edge -> Maybe AttrVal getAttr x S.Edge{..} = do S.NonTerm{..} <- takeLeft $ S.label nodeLabel M.lookup x morph -------------------------------------------------------------------------------- -- SKL conversion -------------------------------------------------------------------------------- liczbaSKL :: W.Number -> AttrVal liczbaSKL x = case x of W.Singular -> "poj" W.Plural -> "mno" -------------------------------------------------------------------------------- -- Utils -------------------------------------------------------------------------------- -- | Base form attribute. przypadek, przyimek, klasa, liczba :: Attr przypadek = "przypadek" przyimek = "przyim" klasa = "klasa" liczba = "liczba" takeLeft :: Either a b -> Maybe a takeLeft (Left x) = Just x takeLeft (Right _) = Nothing takeRight :: Either a b -> Maybe b takeRight (Left _) = Nothing takeRight (Right x) = Just x maybeT :: Monad m => Maybe a -> MaybeT m a maybeT = MaybeT . return
kawu/skladnica-with-walenty
src/NLP/Skladnica/Walenty/Mapping.hs
bsd-2-clause
11,122
0
17
2,767
2,688
1,427
1,261
200
15
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} -- ------------------------------------------------------------ {- | Module : Yuuko.Control.Arrow.IOStateListArrow Copyright : Copyright (C) 2005-8 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt (uwe\@fh-wedel.de) Stability : experimental Portability: portable Implementation of arrows with IO and a state -} -- ------------------------------------------------------------ module Yuuko.Control.Arrow.IOStateListArrow ( IOSLA(..) , liftSt , runSt ) where import Prelude hiding (id, (.)) import Control.Category import Control.Arrow import Yuuko.Control.Arrow.ArrowIf import Yuuko.Control.Arrow.ArrowIO import Yuuko.Control.Arrow.ArrowList import Yuuko.Control.Arrow.ArrowNF import Yuuko.Control.Arrow.ArrowTree import Yuuko.Control.Arrow.ArrowState import Control.DeepSeq -- ------------------------------------------------------------ -- | list arrow combined with a state and the IO monad newtype IOSLA s a b = IOSLA { runIOSLA :: s -> a -> IO (s, [b]) } instance Category (IOSLA s) where id = IOSLA $ \ s x -> return (s, [x]) -- don't defined id = arr id, this gives loops during optimization IOSLA g . IOSLA f = IOSLA $ \ s x -> do (s1, ys) <- f s x sequence' s1 ys where sequence' s' [] = return (s', []) sequence' s' (x':xs') = do (s1', ys') <- g s' x' (s2', zs') <- sequence' s1' xs' return (s2', ys' ++ zs') instance Arrow (IOSLA s) where arr f = IOSLA $ \ s x -> return (s, [f x]) first (IOSLA f) = IOSLA $ \ s (x1, x2) -> do (s', ys1) <- f s x1 return (s', [ (y1, x2) | y1 <- ys1 ]) -- just for efficiency second (IOSLA g) = IOSLA $ \ s (x1, x2) -> do (s', ys2) <- g s x2 return (s', [ (x1, y2) | y2 <- ys2 ]) -- just for efficiency IOSLA f *** IOSLA g = IOSLA $ \ s (x1, x2) -> do (s1, ys1) <- f s x1 (s2, ys2) <- g s1 x2 return (s2, [ (y1, y2) | y1 <- ys1, y2 <- ys2 ]) -- just for efficiency IOSLA f &&& IOSLA g = IOSLA $ \ s x -> do (s1, ys1) <- f s x (s2, ys2) <- g s1 x return (s2, [ (y1, y2) | y1 <- ys1, y2 <- ys2 ]) instance ArrowZero (IOSLA s) where zeroArrow = IOSLA $ \ s -> const (return (s, [])) instance ArrowPlus (IOSLA s) where IOSLA f <+> IOSLA g = IOSLA $ \ s x -> do (s1, rs1) <- f s x (s2, rs2) <- g s1 x return (s2, rs1 ++ rs2) instance ArrowChoice (IOSLA s) where left (IOSLA f) = IOSLA $ \ s -> either (\ x -> do (s1, y) <- f s x return (s1, map Left y) ) (\ x -> return (s, [Right x])) right (IOSLA f) = IOSLA $ \ s -> either (\ x -> return (s, [Left x])) (\ x -> do (s1, y) <- f s x return (s1, map Right y) ) instance ArrowApply (IOSLA s) where app = IOSLA $ \ s (IOSLA f, x) -> f s x instance ArrowList (IOSLA s) where arrL f = IOSLA $ \ s x -> return (s, (f x)) arr2A f = IOSLA $ \ s (x, y) -> runIOSLA (f x) s y constA c = IOSLA $ \ s -> const (return (s, [c])) isA p = IOSLA $ \ s x -> return (s, if p x then [x] else []) IOSLA f >>. g = IOSLA $ \ s x -> do (s1, ys) <- f s x return (s1, g ys) -- just for efficency perform (IOSLA f) = IOSLA $ \ s x -> do (s1, _ys) <- f s x return (s1, [x]) instance ArrowIf (IOSLA s) where ifA (IOSLA p) ta ea = IOSLA $ \ s x -> do (s1, res) <- p s x runIOSLA ( if null res then ea else ta ) s1 x (IOSLA f) `orElse` g = IOSLA $ \ s x -> do r@(s1, res) <- f s x if null res then runIOSLA g s1 x else return r instance ArrowIO (IOSLA s) where arrIO cmd = IOSLA $ \ s x -> do res <- cmd x return (s, [res]) instance ArrowIOIf (IOSLA s) where isIOA p = IOSLA $ \ s x -> do res <- p x return (s, if res then [x] else []) instance ArrowState s (IOSLA s) where changeState cf = IOSLA $ \ s x -> let s' = cf s x in return (seq s' s', [x]) accessState af = IOSLA $ \ s x -> return (s, [af s x]) -- ------------------------------------------------------------ -- | -- lift the state of an IOSLA arrow to a state with an additional component. -- -- This is uesful, when running predefined IO arrows, e.g. for document input, -- in a context with a more complex state component. liftSt :: IOSLA s1 b c -> IOSLA (s1, s2) b c liftSt (IOSLA f) = IOSLA $ \ (s1, s2) x -> do (s1', ys) <- f s1 x return ((s1', s2), ys) -- | -- run an arrow with augmented state in the context of a simple state arrow. -- An initial value for the new state component is needed. -- -- This is useful, when running an arrow with an extra environment component, e.g. -- for namespace handling in XML. runSt :: s2 -> IOSLA (s1, s2) b c -> IOSLA s1 b c runSt s2 (IOSLA f) = IOSLA $ \ s1 x -> do ((s1', _s2'), ys) <- f (s1, s2) x return (s1', ys) -- ------------------------------------------------------------ instance ArrowTree (IOSLA s) instance (NFData s) => ArrowNF (IOSLA s) where rnfA (IOSLA f) = IOSLA $ \ s x -> do res <- f s x deepseq res $ return res -- ------------------------------------------------------------
nfjinjing/yuuko
src/Yuuko/Control/Arrow/IOStateListArrow.hs
bsd-3-clause
5,702
75
15
1,936
2,165
1,149
1,016
112
1
module Diagrams.SVG.Fonts.WriteFont where import Numeric ( showHex ) import Data.String ( fromString ) import Data.Char ( ord ) import Data.List ( intercalate ) import qualified Data.Set as Set import qualified Data.Map as M import Control.Monad ( forM_ ) import Text.Blaze.Svg11 ((!), toValue) import qualified Text.Blaze.Internal as B import qualified Text.Blaze.Svg11 as S import qualified Text.Blaze.Svg11.Attributes as A import Diagrams.SVG.Fonts.ReadFont makeSvgFont :: (Show n, S.ToValue n) => PreparedFont n -> Set.Set String -> S.Svg makeSvgFont (fd, _) gs = font ! A.horizAdvX horizAdvX $ do -- Font meta information S.fontFace ! A.fontFamily fontFamily ! A.fontStyle fontStyle ! A.fontWeight fontWeight ! A.fontStretch fontStretch ! A.fontVariant fontVariant # maybeMaybe A.fontSize fontDataSize ! A.unitsPerEm unitsPerEm # maybeString A.panose1 fontDataPanose # maybeMaybe A.slope fontDataSlope ! A.ascent ascent ! A.descent descent ! A.xHeight xHeight ! A.capHeight capHeight # maybeMaybe A.accentHeight fontDataAccentHeight ! A.bbox bbox ! A.underlineThickness underlineT ! A.underlinePosition underlineP ! A.unicodeRange unicodeRange # maybeMaybe A.widths fontDataWidths # maybeMaybe A.stemv fontDataHorizontalStem # maybeMaybe A.stemh fontDataVerticalStem # maybeMaybe A.ideographic fontDataIdeographicBaseline # maybeMaybe A.alphabetic fontDataAlphabeticBaseline # maybeMaybe A.mathematical fontDataMathematicalBaseline # maybeMaybe A.hanging fontDataHangingBaseline # maybeMaybe A.vIdeographic fontDataVIdeographicBaseline # maybeMaybe A.vAlphabetic fontDataVAlphabeticBaseline # maybeMaybe A.vMathematical fontDataVMathematicalBaseline # maybeMaybe A.vHanging fontDataVHangingBaseline # maybeMaybe A.overlinePosition fontDataOverlinePos # maybeMaybe A.overlineThickness fontDataOverlineThickness # maybeMaybe A.strikethroughPosition fontDataStrikethroughPos # maybeMaybe A.strikethroughThickness fontDataStrikethroughThickness -- Insert the 'missing-glyph' case M.lookup ".notdef" (fontDataGlyphs fd) of Nothing -> return () Just (_, _, gPath) -> S.missingGlyph ! A.d (toValue gPath) $ return () -- Insert all other glyphs forM_ (Set.toList gs') $ \g -> case M.lookup g (fontDataGlyphs fd) of Nothing -> return () Just (gName, gHAdv, gPath) -> S.glyph ! A.glyphName (toValue gName) ! A.horizAdvX (toValue gHAdv) ! A.d (toValue gPath) # maybeUnicode g $ return () forM_ (fontDataRawKernings fd) $ \(k, g1, g2, u1, u2) -> do let g1' = filter isGlyph g1 g2' = filter isGlyph g2 u1' = filter isGlyph u1 u2' = filter isGlyph u2 case (not (null g1') && not (null g2')) || (not (null u1') && not (null u2')) of True -> S.hkern ! A.k (toValue k) # maybeString A.g1 (const $ intercalate "," g1') # maybeString A.g2 (const $ intercalate "," g2') # maybeString A.u1 (const $ intercalate "," u1') # maybeString A.u2 (const $ intercalate "," u2') False -> return () where (#) :: (B.Attributable h) => h -> Maybe S.Attribute -> h (#) x Nothing = x (#) x (Just a) = x ! a unicodeBlacklist :: Set.Set String unicodeBlacklist = Set.fromList [ ".notdef" , ".null" ] maybeUnicode :: String -> Maybe S.Attribute maybeUnicode [] = Nothing maybeUnicode s | s `Set.member` unicodeBlacklist || length s >= 10 = Nothing maybeUnicode s = Just $ A.unicode $ toValue $ concatMap encodeUnicode s encodeUnicode :: Char -> String encodeUnicode c = let cOrd = ord c in if cOrd >= 32 && cOrd <= 126 then [c] else "&#x" ++ showHex cOrd "" -- maybeMaybe :: (S.ToValue a) -- => (S.AttributeValue -> S.Attribute) -> (FontData n -> Maybe a) -- -> Maybe S.Attribute maybeMaybe toF fromF = (toF . toValue) `fmap` fromF fd -- maybeString :: (S.AttributeValue -> S.Attribute) -> (FontData n -> String) -- -> Maybe S.Attribute maybeString toF fromF = case fromF fd of "" -> Nothing s -> Just $ toF $ toValue $ s font :: S.Svg -> S.Svg font m = B.Parent (fromString "font") (fromString "<font") (fromString "</font>") m isGlyph :: String -> Bool isGlyph g = g `Set.member` gs' gs' = Set.insert ".notdef" gs horizAdvX = toValue $ fontDataHorizontalAdvance fd fontFamily = toValue $ fontDataFamily fd fontStyle = toValue $ fontDataStyle fd fontWeight = toValue $ fontDataWeight fd fontStretch = toValue $ fontDataStretch fd fontVariant = toValue $ fontDataVariant fd unitsPerEm = toValue $ fontDataUnitsPerEm fd ascent = toValue $ fontDataAscent fd descent = toValue $ fontDataDescent fd xHeight = toValue $ fontDataXHeight fd capHeight = toValue $ fontDataCapHeight fd bbox = toValue $ intercalate " " $ fmap show $ fontDataBoundingBox fd underlineT = toValue $ fontDataUnderlineThickness fd underlineP = toValue $ fontDataUnderlinePos fd unicodeRange = toValue $ fontDataUnicodeRange fd
diagrams/diagrams-input
src/Diagrams/SVG/Fonts/WriteFont.hs
bsd-3-clause
5,800
0
42
1,805
1,602
809
793
115
9
{- - Main.hs - By Steven Smith -} module Main where import System.Environment import SpirV.Builder (buildModule) import SpirV.PrettyPrint import Program1 import Program2 main :: IO () main = do args <- getArgs let program = case args of ["1"] -> program1 ["2"] -> program2 _ -> program1 printModule (buildModule program)
stevely/hspirv
test/src/Main.hs
bsd-3-clause
377
0
13
106
102
55
47
14
3
module Scheme.DataType.Error where import Scheme.DataType.Error.Eval (EvalError) import Scheme.DataType.Error.Try (TryError) import Scheme.DataType.Misc import DeepControl.Monad.Except -------------------------------------------------- -- Data -------------------------------------------------- data ScmError = EXITErr | EVALErr MSP EvalError | TRYErr TryError | OTHER String instance Error ScmError where strMsg s = OTHER s -------------------------------------------------- -- Show -------------------------------------------------- instance Show ScmError where show EXITErr = "Exited." show (EVALErr (Just sp) err) = "Eval error: " ++ (showSourcePos sp) ++ "\n" ++ show err show (EVALErr Nothing err) = "Eval error: " ++ show err show (TRYErr err) = show err show (OTHER s) = "Scheme error: " ++ s
ocean0yohsuke/Scheme
src/Scheme/DataType/Error.hs
bsd-3-clause
919
0
10
213
209
115
94
17
0
{- Arr.hs, the Array representation used in Obsidian. Joel Svensson -} module Obsidian.ArrowObsidian.Arr where import Obsidian.ArrowObsidian.Exp -------------------------------------------------------------------------------- data Arr a = Arr (IndexE -> a) Int -- Dynamic content, Static length instance Show a => Show (Arr a) where show (Arr f n) = "(Arr" ++ show2 f ++ show n ++ ")" where show2 f = show [f i| i <- [0..1]] instance Functor Arr where fmap f arr = mkArr (\ix -> f (arr ! ix)) (len arr) instance Eq a => Eq (Arr a) where (==) a1 a2 = len a1 == len a2 && (a1 ! variable "X") == (a2 ! variable "X") (!) (Arr f _) ix = f ix len (Arr _ n) = n mkArr f n = Arr f n singleton = rep 1 rep n x = Arr (\ix -> x) n --------------------------------------------------------------------------------
svenssonjoel/ArrowObsidian
Obsidian/ArrowObsidian/Arr.hs
bsd-3-clause
950
0
12
291
326
168
158
17
1
{-# LANGUAGE OverloadedStrings #-} module HLiquid.Parser where import Control.Monad (void) import Text.Megaparsec import Text.Megaparsec.Text import Data.Text (pack) import Data.Maybe (maybeToList) import HLiquid.Lexer import HLiquid.Syntax import HLiquid.Parser.Variable import HLiquid.Parser.Expression fullFile = many liquid <* eof liquid :: Parser Statement liquid = choice [ assignTag, bodyText, breakTag, captureTag liquid, caseTag , commentTag, continueTag, cycleTag, decrementTag, formTag , forTag, ifTag, incrementTag, layoutTag, includeTag, sectionTag , paginateTag, tablerowTag, unlessTag, schemaTag, rawTag, expressionTag ] placeHolderTag :: Parser Statement placeHolderTag = braces $ placeHolder *> (pure Break) -- type TagParser a = (String, Parser (a -> Statement), (a -> Statement) -> Parser Statement) -- can be made into just a `Parser a` --------------------^ ifTag :: Parser Statement ifTag = do b1 <- branch "if" branches <- many $ branch "elsif" e <- optional . try $ do braces $ symbol "else" b <- many liquid return $ Else b simpleTag "endif" (pure ()) return . If $ b1 : (branches ++ maybeToList e) unlessTag :: Parser Statement unlessTag = do b1 <- branch "unless" branches <- many $ branch "elsif" e <- optional . try $ do braces $ symbol "else" b <- many liquid return $ Else b simpleTag "endunless" (pure ()) return . If $ b1 : (branches ++ maybeToList e) branch :: String -> Parser Branch branch nm = do cond <- simpleTag nm filteredExpression body <- many $ liquid return $ Branch cond body caseTag :: Parser Statement caseTag = tag "case" (Case <$> filteredExpression) $ \f -> do body <- some $ do w <- simpleTag "when" (When <$> filteredExpression) w <$> many liquid e <- optional . try $ do braces $ symbol "else" b <- many liquid return $ Else b simpleTag "endcase" (pure ()) return $ f body forTag :: Parser Statement forTag = tag "for" head body where head = placeHolder *> (pure . uncurry $ For) body f = do b <- many $ liquid e <- optional . try $ do braces $ symbol "else" b <- many liquid return $ Else b braces $ symbol "endfor" return $ (curry f) Break b tablerowTag :: Parser Statement tablerowTag = simpleBlockTag "tablerow" head (many liquid) where head = Tablerow <$> placeHolder breakTag :: Parser Statement breakTag = simpleTag "break" (pure Break) continueTag :: Parser Statement continueTag = simpleTag "continue" (pure Continue) cycleTag :: Parser Statement cycleTag = simpleTag "cycle" (placeHolder *> (pure $ Cycle [])) layoutTag :: Parser Statement layoutTag = simpleTag "layout" (Layout <$> filteredExpression) includeTag :: Parser Statement includeTag = simpleTag "include" body where body = do e <- filteredExpression o <- optional $ do symbol "with" choice [namedArg `sepBy1` (symbol ","), pure <$> filteredExpression] w <- many $ (symbol "," *> namedArg) return $ Include e namedArg = (try $ identifier *> symbol ":") *> filteredExpression sectionTag :: Parser Statement sectionTag = simpleTag "section" (Section <$> filteredExpression) formTag :: Parser Statement formTag = simpleBlockTag "form" head (many liquid) where head = Form <$> filteredExpression <*> startBy expression (symbol ",") startBy p sep = (sep *> sepBy p sep) <|> pure [] paginateTag :: Parser Statement paginateTag = simpleBlockTag "paginate" head (many liquid) where head = Paginate <$> placeHolder -- | Comment should not parse inner liquid commentTag :: Parser Statement commentTag = simpleBlockTag "comment" head (body) where head = pure $ Comment body = do notFollowedBy (string "{% endcomment") someTill anyChar $ lookAhead (string "{% endcomment") schemaTag :: Parser Statement schemaTag = simpleBlockTag "schema" head (many liquid) where head = pure $ Schema rawTag :: Parser Statement rawTag = simpleBlockTag "raw" head (body) where head = pure Raw body = do notFollowedBy (string "{%") someTill anyChar $ lookAhead (string "{%") expressionTag :: Parser Statement expressionTag = try . braces' $ do e <- filteredExpression return $ Expression e bodyText :: Parser Statement bodyText = LitString . pack <$> do notFollowedBy openB someTill anyChar $ lookAhead openB where openB = ((void $ string "{{") <|> (void $ string "{%") <|> eof)
xldenis/hliquid
src/HLiquid/Parser.hs
bsd-3-clause
4,543
0
17
1,026
1,492
737
755
123
1
{-# LANGUAGE DeriveDataTypeable #-} {- Main hrolldice executable -} import System.Console.CmdArgs import RollDice.Roller import Data.List data HRollDice = RollStatements {rolls :: [String]} deriving (Show, Data, Typeable) rollstatements = RollStatements {rolls = def &= args &= typ "dice_string" } &= summary "hrolldice, a dice rolling application modeled after 'rolldice' by Stevie Strickland." outputResult :: Either String [Int] -> IO () outputResult (Left e) = fail e outputResult (Right nums) = do putStrLn $ intercalate " " $ map show nums main :: IO () main = do argrs <- cmdArgs rollstatements let statements = rolls argrs rollResults <- mapM runRoll statements mapM_ outputResult rollResults
tarmstrong/hrolldice
RollDice.hs
bsd-3-clause
721
0
10
123
212
106
106
17
1
{-# LANGUAGE FlexibleContexts, FlexibleInstances, GADTs #-} -- | The @esqueleto@ EDSL (embedded domain specific language). -- This module replaces @Database.Persist@, so instead of -- importing that module you should just import this one: -- -- @ -- -- For a module using just esqueleto. -- import Database.Esqueleto -- @ -- -- If you need to use @persistent@'s default support for queries -- as well, either import it qualified: -- -- @ -- -- For a module that mostly uses esqueleto. -- import Database.Esqueleto -- import qualified Database.Persistent as P -- @ -- -- or import @esqueleto@ itself qualified: -- -- @ -- -- For a module uses esqueleto just on some queries. -- import Database.Persistent -- import qualified Database.Esqueleto as E -- @ -- -- Other than identifier name clashes, @esqueleto@ does not -- conflict with @persistent@ in any way. module Database.Esqueleto ( -- * Setup -- $setup -- * Introduction -- $introduction -- * Getting started -- $gettingstarted -- * @esqueleto@'s Language Esqueleto( where_, on, groupBy, orderBy, asc, desc, limit, offset, having , sub_select, sub_selectDistinct, (^.), (?.) , val, isNothing, just, nothing, joinV, countRows, count, not_ , (==.), (>=.), (>.), (<=.), (<.), (!=.), (&&.), (||.) , (+.), (-.), (/.), (*.) , random_, round_, ceiling_, floor_ , min_, max_, sum_, avg_ , like, (%), concat_, (++.) , subList_select, subList_selectDistinct, valList , in_, notIn, exists, notExists , set, (=.), (+=.), (-=.), (*=.), (/=.) ) , from , Value(..) , ValueList(..) , OrderBy -- ** Joins , InnerJoin(..) , CrossJoin(..) , LeftOuterJoin(..) , RightOuterJoin(..) , FullOuterJoin(..) , OnClauseWithoutMatchingJoinException(..) -- * SQL backend , SqlQuery , SqlExpr , SqlEntity , select , selectDistinct , selectSource , selectDistinctSource , delete , deleteCount , update , updateCount , insertSelect , insertSelectDistinct , (<#) , (<&>) -- * Helpers , valkey -- * Re-exports -- $reexports , deleteKey , module Database.Esqueleto.Internal.PersistentImport ) where import Data.Int (Int64) import Database.Esqueleto.Internal.Language import Database.Esqueleto.Internal.Sql import Database.Esqueleto.Internal.PersistentImport import qualified Database.Persist -- $setup -- -- If you're already using @persistent@, then you're ready to use -- @esqueleto@, no further setup is needed. If you're just -- starting a new project and would like to use @esqueleto@, take -- a look at @persistent@'s book first -- (<http://www.yesodweb.com/book/persistent>) to learn how to -- define your schema. ---------------------------------------------------------------------- -- $introduction -- -- The main goals of @esqueleto@ are to: -- -- * Be easily translatable to SQL. When you take a look at a -- @esqueleto@ query, you should be able to know exactly how -- the SQL query will end up. (As opposed to being a -- relational algebra EDSL such as HaskellDB, which is -- non-trivial to translate into SQL.) -- -- * Support the mostly used SQL features. We'd like you to be -- able to use @esqueleto@ for all of your queries, no -- exceptions. Send a pull request or open an issue on our -- project page (<https://github.com/meteficha/esqueleto>) if -- there's anything missing that you'd like to see. -- -- * Be as type-safe as possible. We strive to provide as many -- type checks as possible. If you get bitten by some invalid -- code that type-checks, please open an issue on our project -- page so we can take a look. -- -- However, it is /not/ a goal to be able to write portable SQL. -- We do not try to hide the differences between DBMSs from you, -- and @esqueleto@ code that works for one database may not work -- on another. This is a compromise we have to make in order to -- give you as much control over the raw SQL as possible without -- losing too much convenience. This also means that you may -- type-check a query that doesn't work on your DBMS. ---------------------------------------------------------------------- -- $gettingstarted -- -- We like clean, easy-to-read EDSLs. However, in order to -- achieve this goal we've used a lot of type hackery, leading to -- some hard-to-read type signatures. On this section, we'll try -- to build some intuition about the syntax. -- -- For the following examples, we'll use this example schema: -- -- @ -- share [mkPersist sqlSettings, mkMigrate \"migrateAll\"] [persist| -- Person -- name String -- age Int Maybe -- deriving Eq Show -- BlogPost -- title String -- authorId PersonId -- deriving Eq Show -- Follow -- follower PersonId -- followed PersonId -- deriving Eq Show -- |] -- @ -- -- Most of @esqueleto@ was created with @SELECT@ statements in -- mind, not only because they're the most common but also -- because they're the most complex kind of statement. The most -- simple kind of @SELECT@ would be: -- -- @ -- SELECT * -- FROM Person -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- do people <- 'select' $ -- 'from' $ \\person -> do -- return person -- liftIO $ mapM_ (putStrLn . personName . entityVal) people -- @ -- -- The expression above has type @SqlPersist m ()@, while -- @people@ has type @[Entity Person]@. The query above will be -- translated into exactly the same query we wrote manually, but -- instead of @SELECT *@ it will list all entity fields (using -- @*@ is not robust). Note that @esqueleto@ knows that we want -- an @Entity Person@ just because of the @personName@ that we're -- printing later. -- -- However, most of the time we need to filter our queries using -- @WHERE@. For example: -- -- @ -- SELECT * -- FROM Person -- WHERE Person.name = \"John\" -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\p -> do -- 'where_' (p '^.' PersonName '==.' 'val' \"John\") -- return p -- @ -- -- Although @esqueleto@'s code is a bit more noisy, it's has -- almost the same structure (save from the @return@). The -- @('^.')@ operator is used to project a field from an entity. -- The field name is the same one generated by @persistent@'s -- Template Haskell functions. We use 'val' to lift a constant -- Haskell value into the SQL query. -- -- Another example would be: -- -- @ -- SELECT * -- FROM Person -- WHERE Person.age >= 18 -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\p -> do -- where_ (p ^. PersonAge '>=.' 'just' (val 18)) -- return p -- @ -- -- Since @age@ is an optional @Person@ field, we use 'just' lift -- @val 18 :: SqlExpr (Value Int)@ into @just (val 18) :: -- SqlExpr (Value (Just Int))@. -- -- Implicit joins are represented by tuples. For example, to get -- the list of all blog posts and their authors, we could write: -- -- @ -- SELECT BlogPost.*, Person.* -- FROM BlogPost, Person -- WHERE BlogPost.authorId = Person.id -- ORDER BY BlogPost.title ASC -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\(b, p) -> do -- where_ (b ^. BlogPostAuthorId ==. p ^. PersonId) -- 'orderBy' ['asc' (b ^. BlogPostTitle)] -- return (b, p) -- @ -- -- However, we may want your results to include people who don't -- have any blog posts as well using a @LEFT OUTER JOIN@: -- -- @ -- SELECT Person.*, BlogPost.* -- FROM Person LEFT OUTER JOIN BlogPost -- ON Person.id = BlogPost.authorId -- ORDER BY Person.name ASC, BlogPost.title ASC -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\(p ``LeftOuterJoin`` mb) -> do -- 'on' (just (p ^. PersonId) ==. mb '?.' BlogPostAuthorId) -- orderBy [asc (p ^. PersonName), asc (mb '?.' BlogPostTitle)] -- return (p, mb) -- @ -- -- On a @LEFT OUTER JOIN@ the entity on the right hand side may -- not exist (i.e. there may be a @Person@ without any -- @BlogPost@s), so while @p :: SqlExpr (Entity Person)@, we have -- @mb :: SqlExpr (Maybe (Entity BlogPost))@. The whole -- expression above has type @SqlPersist m [(Entity Person, Maybe -- (Entity BlogPost))]@. Instead of using @(^.)@, we used -- @('?.')@ to project a field from a @Maybe (Entity a)@. -- -- We are by no means limited to joins of two tables, nor by -- joins of different tables. For example, we may want a list -- the @Follow@ entity: -- -- @ -- SELECT P1.*, Follow.*, P2.* -- FROM Person AS P1 -- INNER JOIN Follow ON P1.id = Follow.follower -- INNER JOIN P2 ON P2.id = Follow.followed -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- select $ -- from $ \\(p1 ``InnerJoin`` f ``InnerJoin`` p2) -> do -- on (p2 ^. PersonId ==. f ^. FollowFollowed) -- on (p1 ^. PersonId ==. f ^. FollowFollower) -- return (p1, f, p2) -- @ -- -- /Note carefully that the order of the ON clauses is/ -- /reversed!/ You're required to write your 'on's in reverse -- order because that helps composability (see the documentation -- of 'on' for more details). -- -- We also currently support @UPDATE@ and @DELETE@ statements. -- For example: -- -- @ -- do 'update' $ \\p -> do -- 'set' p [ PersonName '=.' val \"João\" ] -- where_ (p ^. PersonName ==. val \"Joao\") -- 'delete' $ -- from $ \\p -> do -- where_ (p ^. PersonAge <. just (val 14)) -- @ -- -- The results of queries can also be used for insertions. -- In @SQL@, we might write the following, inserting a new blog -- post for every user: -- -- @ -- INSERT INTO BlogPost -- SELECT ('Group Blog Post', id) -- FROM Person -- @ -- -- In @esqueleto@, we may write the same query above as: -- -- @ -- insertSelect $ from $ \p-> -- return $ BlogPost \<# \"Group Blog Post\" \<&\> (p ^. PersonId) -- @ -- -- Individual insertions can be performed through Persistent's -- 'insert' function, reexported for convenience. ---------------------------------------------------------------------- -- $reexports -- -- We re-export many symbols from @persistent@ for convenince: -- -- * \"Store functions\" from "Database.Persist". -- -- * Everything from "Database.Persist.Class" except for -- @PersistQuery@ and @delete@ (use 'deleteKey' instead). -- -- * Everything from "Database.Persist.Types" except for -- @Update@, @SelectOpt@, @BackendSpecificFilter@ and @Filter@. -- -- * Everything from "Database.Persist.Sql" except for -- @deleteWhereCount@ and @updateWhereCount@. ---------------------------------------------------------------------- -- | @valkey i = val (Key (PersistInt64 i))@ -- (<https://github.com/meteficha/esqueleto/issues/9>). valkey :: Esqueleto query expr backend => Int64 -> expr (Value (Key entity)) valkey = val . Key . PersistInt64 ---------------------------------------------------------------------- -- | Synonym for 'Database.Persist.Store.delete' that does not -- clash with @esqueleto@'s 'delete'. deleteKey :: ( PersistStore m , PersistMonadBackend m ~ PersistEntityBackend val , PersistEntity val ) => Key val -> m () deleteKey = Database.Persist.delete
begriffs/esqueleto
src/Database/Esqueleto.hs
bsd-3-clause
11,272
0
11
2,301
739
634
105
58
1
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveGeneric #-} module Models where import Data.Aeson import Data.Maybe (mapMaybe) import GHC.Generics (Generic) import Database.Persist.Sqlite import Database.Persist.TH import Control.Monad.IO.Class share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User json firstName String lastName String age Int email String deriving Show |] type SqlResult a = forall (m :: * -> *). MonadIO m => SqlPersistT m a setupDB :: SqlResult () setupDB = do runMigration migrateAll insertMany [ User "Joe" "Schmoe" 25 "joeschmoe99@gmail.com" , User "Jeff" "Brown" 12 "jb12345@yahoo.com" ] return ()
sgeop/micro
src/Models.hs
bsd-3-clause
1,238
0
9
321
179
104
75
30
1
-- ----------------------------------------------------------------------------- -- -- NFA.hs, part of Alex -- -- (c) Chris Dornan 1995-2000, Simon Marlow 2003 -- -- The `scanner2nfa' takes a `Scanner' (see the `RExp' module) and -- generates its equivelent nondeterministic finite automaton. NFAs -- are turned into DFAs in the DFA module. -- -- See the chapter on `Finite Automata and Lexical Analysis' in the -- dragon book for an excellent overview of the algorithms in this -- module. -- -- ----------------------------------------------------------------------------} module NFA where import AbsSyn import CharSet import DFS ( t_close, out ) import Map ( Map ) import qualified Map hiding ( Map ) import Util ( str, space ) import Control.Applicative ( Applicative(..) ) import Control.Monad ( forM_, zipWithM, zipWithM_, when, liftM, ap ) import Data.Array ( Array, (!), array, listArray, assocs, bounds ) -- Each state of a nondeterministic automaton contains a list of `Accept' -- values, a list of epsilon transitions (an epsilon transition represents a -- transition to another state that can be made without reading a character) -- and a list of transitions qualified with a character predicate (the -- transition can only be made to the given state on input of a character -- permitted by the predicate). Although a list of `Accept' values is provided -- for, in actual fact each state will have zero or one of them (the `Maybe' -- type is not used because the flexibility offered by the list representation -- is useful). type NFA = Array SNum NState data NState = NSt { nst_accs :: [Accept Code], nst_cl :: [SNum], nst_outs :: [(ByteSet,SNum)] } -- Debug stuff instance Show NState where showsPrec _ (NSt accs cl outs) = str "NSt " . shows accs . space . shows cl . space . shows [ (c, s) | (c,s) <- outs ] {- From the Scan Module -- The `Accept' structure contains the priority of the token being accepted -- (lower numbers => higher priorities), the name of the token, a place holder -- that can be used for storing the `action' function, a list of start codes -- (listing the start codes that the scanner must be in for the token to be -- accepted; empty => no restriction), the leading and trailing context (both -- `Nothing' if there is none). -- -- The leading context consists simply of a character predicate that will -- return true if the last character read is acceptable. The trailing context -- consists of an alternative starting state within the DFA; if this `sub-dfa' -- turns up any accepting state when applied to the residual input then the -- trailing context is acceptable. -} -- `scanner2nfa' takes a scanner (see the AbsSyn module) and converts it to an -- NFA, using the NFA creation monad (see below). -- -- We generate a start state for each startcode, with the same number -- as that startcode, and epsilon transitions from this state to each -- of the sub-NFAs for each of the tokens acceptable in that startcode. scanner2nfa:: Encoding -> Scanner -> [StartCode] -> NFA scanner2nfa enc Scanner{scannerTokens = toks} startcodes = runNFA enc $ do -- make a start state for each start code (these will be -- numbered from zero). start_states <- sequence (replicate (length startcodes) newState) -- construct the NFA for each token tok_states <- zipWithM do_token toks [0..] -- make an epsilon edge from each state state to each -- token that is acceptable in that state zipWithM_ (tok_transitions (zip toks tok_states)) startcodes start_states where do_token (RECtx _scs lctx re rctx code) prio = do b <- newState e <- newState rexp2nfa b e re rctx_e <- case rctx of NoRightContext -> return NoRightContext RightContextCode code' -> return (RightContextCode code') RightContextRExp re' -> do r_b <- newState r_e <- newState rexp2nfa r_b r_e re' accept r_e rctxt_accept return (RightContextRExp r_b) let lctx' = case lctx of Nothing -> Nothing Just st -> Just st accept e (Acc prio code lctx' rctx_e) return b tok_transitions toks_with_states start_code start_state = do let states = [ s | (RECtx scs _ _ _ _, s) <- toks_with_states, null scs || start_code `elem` map snd scs ] mapM_ (epsilonEdge start_state) states -- ----------------------------------------------------------------------------- -- NFA creation from a regular expression -- rexp2nfa B E R generates an NFA that begins in state B, recognises -- R, and ends in state E only if R has been recognised. rexp2nfa :: SNum -> SNum -> RExp -> NFAM () rexp2nfa b e Eps = epsilonEdge b e rexp2nfa b e (Ch p) = charEdge b p e rexp2nfa b e (re1 :%% re2) = do s <- newState rexp2nfa b s re1 rexp2nfa s e re2 rexp2nfa b e (re1 :| re2) = do rexp2nfa b e re1 rexp2nfa b e re2 rexp2nfa b e (Star re) = do s <- newState epsilonEdge b s rexp2nfa s s re epsilonEdge s e rexp2nfa b e (Plus re) = do s1 <- newState s2 <- newState rexp2nfa s1 s2 re epsilonEdge b s1 epsilonEdge s2 s1 epsilonEdge s2 e rexp2nfa b e (Ques re) = do rexp2nfa b e re epsilonEdge b e -- ----------------------------------------------------------------------------- -- NFA creation monad. -- Partial credit to Thomas Hallgren for this code, as I adapted it from -- his "Lexing Haskell in Haskell" lexer generator. type MapNFA = Map SNum NState newtype NFAM a = N {unN :: SNum -> MapNFA -> Encoding -> (SNum, MapNFA, a)} instance Functor NFAM where fmap = liftM instance Applicative NFAM where pure = return (<*>) = ap instance Monad NFAM where return a = N $ \s n _ -> (s,n,a) m >>= k = N $ \s n e -> case unN m s n e of (s', n', a) -> unN (k a) s' n' e runNFA :: Encoding -> NFAM () -> NFA runNFA e m = case unN m 0 Map.empty e of (s, nfa_map, ()) -> -- trace ("runNfa.." ++ show (Map.toAscList nfa_map)) $ e_close (array (0,s-1) (Map.toAscList nfa_map)) e_close:: Array Int NState -> NFA e_close ar = listArray bds [NSt accs (out gr v) outs|(v,NSt accs _ outs)<-assocs ar] where gr = t_close (hi+1,\v->nst_cl (ar!v)) bds@(_,hi) = bounds ar newState :: NFAM SNum newState = N $ \s n _ -> (s+1,n,s) getEncoding :: NFAM Encoding getEncoding = N $ \s n e -> (s,n,e) anyBytes :: SNum -> Int -> SNum -> NFAM () anyBytes from 0 to = epsilonEdge from to anyBytes from n to = do s <- newState byteEdge from (byteSetRange 0 0xff) s anyBytes s (n-1) to bytesEdge :: SNum -> [Byte] -> [Byte] -> SNum -> NFAM () bytesEdge from [] [] to = epsilonEdge from to bytesEdge from [x] [y] to = byteEdge from (byteSetRange x y) to -- (OPTIMISATION) bytesEdge from (x:xs) (y:ys) to | x == y = do s <- newState byteEdge from (byteSetSingleton x) s bytesEdge s xs ys to | x < y = do do s <- newState byteEdge from (byteSetSingleton x) s bytesEdge s xs (fmap (const 0xff) ys) to do t <- newState byteEdge from (byteSetSingleton y) t bytesEdge t (fmap (const 0x00) xs) ys to when ((x+1) <= (y-1)) $ do u <- newState byteEdge from (byteSetRange (x+1) (y-1)) u anyBytes u (length xs) to bytesEdge _ _ _ _ = undefined -- hide compiler warning charEdge :: SNum -> CharSet -> SNum -> NFAM () charEdge from charset to = do -- trace ("charEdge: " ++ (show $ charset) ++ " => " ++ show (byteRanges charset)) $ e <- getEncoding forM_ (byteRanges e charset) $ \(xs,ys) -> do bytesEdge from xs ys to byteEdge :: SNum -> ByteSet -> SNum -> NFAM () byteEdge from charset to = N $ \s n _ -> (s, addEdge n, ()) where addEdge n = case Map.lookup from n of Nothing -> Map.insert from (NSt [] [] [(charset,to)]) n Just (NSt acc eps trans) -> Map.insert from (NSt acc eps ((charset,to):trans)) n epsilonEdge :: SNum -> SNum -> NFAM () epsilonEdge from to | from == to = return () | otherwise = N $ \s n _ -> (s, addEdge n, ()) where addEdge n = case Map.lookup from n of Nothing -> Map.insert from (NSt [] [to] []) n Just (NSt acc eps trans) -> Map.insert from (NSt acc (to:eps) trans) n accept :: SNum -> Accept Code -> NFAM () accept state new_acc = N $ \s n _ -> (s, addAccept n, ()) where addAccept n = case Map.lookup state n of Nothing -> Map.insert state (NSt [new_acc] [] []) n Just (NSt acc eps trans) -> Map.insert state (NSt (new_acc:acc) eps trans) n rctxt_accept :: Accept Code rctxt_accept = Acc 0 Nothing Nothing NoRightContext
kumasento/alex
src/NFA.hs
bsd-3-clause
8,675
31
21
2,071
2,577
1,318
1,259
157
4
{-| Module : Raytracer Description : Core Copyright : (c) Konrad Dobroś, 2017 License : GPL-3 Maintainer : dobros.konrad@gmail.com Stability : experimental Portability : POSIX This is an entry point to internals of Raytrace. -} {-# LANGUAGE BangPatterns #-} module Raytracer (raytrace, roots) where import Data.Vect.Double import Control.Monad.State.Strict import Control.Monad.Reader import Control.Monad.Random import Data.List (foldl1') import Types import Predefined -------------------------------------------------------------------------------- -- Intersection calculations type Time = Double positionFromT :: Ray -> Time -> Vec3 positionFromT Ray{base = b, direction = dir} t = b &+ (&*) (fromNormal dir) t -- Collision precision to prevent any rays that start inside shape -- (due to rounding errors) from colliding epsilon :: Double epsilon = 0.0001 lightEpsilon :: Double lightEpsilon = 0.0001 -- Calculate the roots of the equation a * x^2 + b * x + c = 0 roots :: Double -> Double -> Double -> [Double] roots a b c = let discriminant = b*b - 4*a*c in if discriminant < 0.0 then [] else [ 0.5 * (-b + sqrt discriminant), 0.5 * (-b - sqrt discriminant)] intersect :: Ray -> Shape -> [(Time, Intersection)] intersect ray@Ray{base = base, direction = dir} (Sphere center rad materialfn) = let a = lensqr dir b = 2 * ( fromNormal dir &. (base &- center)) c = lensqr (base &- center) - rad^2 times = filter (> epsilon) (roots a b c) normal_at_time t = mkNormal (positionFromT ray t &- center) intersection_at_time t = Intersection (normal_at_time t) (positionFromT ray t) ray (materialfn (positionFromT ray t)) in map (\t -> (t,intersection_at_time t)) times intersect ray@Ray{base = base, direction = dir} (Plane normal d materialfn) = let vd = normal &. dir v0 = (d - (fromNormal normal &. base)) in if vd == 0 then [] else let t = v0 / vd hitpoint = positionFromT ray t in [ (t, Intersection (if vd > 0 then mkNormal.neg.fromNormal$normal else normal) hitpoint ray (materialfn hitpoint)) | t > epsilon] -- Extract the closest intersection from a list closest :: [ (Time,Intersection) ] -> Intersection closest xs = let select_nearest (t1,i1) (t2,i2) = if t1<t2 then (t1,i1) else (t2,i2) in snd (foldl1' select_nearest xs) -------------------------------------------------------------------------------- -- Local lighting model lightsource :: BRDF -> Bool lightsource (Emmisive c) = True lightsource _ = False -- Is the light directly visible from point? pointIsLit :: Point3 -> Light -> Reader World Bool pointIsLit point lightpos = do s <- asks scene let path = lightpos &- point let time_at_light = len path let ray = Ray point (mkNormal path) let hits = concatMap (intersect ray) (shapes s) let first = closest hits return (any lightsource.snd.unzip.brdfs.material$first) -- -------------------------------------------------------------------------------- -- -- Main path tracing functions -- overallLighting :: Double -> Int -> Intersection -> ReaderT World (Rand StdGen) Color overallLighting importance depth hit = do s <- asks scene let brs = brdfs (material hit) let calcColor (x,y) = fmap (&* x) (calculateBRDF y (importance*x) depth hit) -- colors <- mapM calcColor brs let color = foldr addMix black colors return $! clamp color -- | Send a ray and return its color. raytrace :: Double -- ^ Importance of ray -- (when importance is sufficently low raytracing stops and returns black). -- Should be started at 1.0. -> Int -- ^ Depth to trace, that is raytracing stops when depth reaches 0. -> Ray -- ^ Ray to send. -> ReaderT World (Rand StdGen) Color -- ^ Color of this ray. raytrace _ 0 _ = return black raytrace importance depth ray = if importance < lightEpsilon then return black else do s <- asks scene let hits = concatMap (intersect ray) (shapes s) if null hits then return (backgroundColor s) else overallLighting importance depth (closest hits) -------------------------------------------------------------------------------- -- BRDF functions -- Random double from range (0.0, 1.0) evalRoll :: Rand StdGen Double evalRoll = getRandomR (0.0,1.0) -- Helper to calculate Schlicks approximation of Fresnels equation schlick :: Double -> Double -> Normal3 -> Normal3 -> Double schlick ind1 ind2 normal viewdir = r_0 + (1.0 - r_0)*(1 - abs (normal &. viewdir))^5 where r_0 = (ind1 - ind2)^2/ (ind1 + ind2)^2 -- Helper to calculate the diffuse light at the surface normal, given -- the light direction (from light source to surface) diffuseCoeff :: Normal3 -> Normal3 -> Double diffuseCoeff lightDir normal = max 0.0 (lightDir &. normal) -- Helper to rotate coordinates from z to normal rotateWorld :: Normal3 -> Normal3 -> Normal3 rotateWorld z norm = case fromNormal norm of (Vec3 0.0 1.0 0.0) -> z (Vec3 0.0 (-1.0) 0.0) -> flipNormal z a -> mkNormal.flip rmul matrix.fromNormal$z where matrix = Mat3 constantV (fromNormal norm) produced constantV = normalize$crossprod (Vec3 0.0 1.0 0.0) a produced = crossprod a constantV calculateBRDF :: BRDF -> Double -> Int -> Intersection -> ReaderT World (Rand StdGen) Color -- Lambertian BRDF calculateBRDF (Lambert c) importance depth intersection = do -- Calculate point light sources l <- asks $lights.scene w <- ask let lits = runReader (filterM (pointIsLit.point$intersection) l) w let lightDirs = map (\x -> mkNormal (x &- point intersection)) lits colors <- mapM (raytrace importance 1.Ray (point intersection)) lightDirs let coefficients = map (diffuseCoeff (normalI intersection)) lightDirs let colorL = foldr addMix black $ zipWith (&*) colors coefficients -- Calculate monte carlo diffusion r_1 <- lift evalRoll r_2 <- lift evalRoll let phi = 2*r_1 - 1 let x = phi * cos (2*pi*r_2) let y = cos (asin phi) let z = phi * sin (2*pi*r_2) let normalHit = if (normalI intersection &. (direction.ray$intersection)) > 0 then flipNormal.normalI$intersection else normalI intersection let randomDir = mkNormal (Vec3 x y z) let outRayDir = rotateWorld randomDir normalHit -- (normalI$intersection) let outRay = Ray (point intersection) outRayDir let coeff = diffuseCoeff outRayDir normalHit -- (normalI intersection) let count = length coefficients + 1 -- We need to get weighted average, so sum of coefficients doesn`t exceed 1 pathColor <- raytrace (importance*coeff) (depth-1) outRay return $ c `prodMix` ((pathColor &+ colorL)&* (1.0/fromIntegral count)) -- Perfect reflection BRDF calculateBRDF (Reflection inRI outRI c) importance depth intersection = let inRayDir = flipNormal.direction.ray$intersection outRayDir = reflect' (normalI intersection) inRayDir outRay = Ray (point intersection) (normalI intersection) fresnel = schlick inRI outRI (normalI intersection) inRayDir in fmap (pointwise (c &* fresnel)) (raytrace (fresnel*importance) (depth-1) outRay) -- Perfect refraction BRDF calculateBRDF (Refraction inRI outRI c) importance depth intersection = let inRayDir = flipNormal.direction.ray$intersection normal = normalI intersection normal2 = (if normal &. inRayDir <= 0 then flipNormal else id) normal eta = if normal &. inRayDir > 0 then outRI/inRI else inRI/outRI outRayDir = refract' eta normal2 inRayDir outRay = Ray (point intersection) outRayDir fresnelT = 1.0 - schlick inRI outRI (normalI intersection) inRayDir in fmap (pointwise (c &* fresnelT)) (raytrace (fresnelT*importance) (depth-1) outRay) -- Emmisive BRDF (uniform) calculateBRDF (Emmisive c) importance depth intersection = return c
kd226/Raytrace
src/Raytracer.hs
bsd-3-clause
7,847
1
17
1,593
2,455
1,254
1,201
137
4
-- Copyright (c) 2014 Eric McCorkle. 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. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS -- 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 Tests.Data.Enumeration.Traversal(tests) where import Data.Enumeration import Data.Enumeration.Traversal import Test.HUnitPlus.Base import qualified Data.ArithEncode as ArithEncode firstEncoding :: ArithEncode.Encoding [Int] firstEncoding = ArithEncode.fromHashableList [[0], [1], [2], [3]] stepFunc :: Path -> [Int] -> Enumeration [Int] stepFunc path val @ (0 : _) = fromEncodingWithPrefix path (ArithEncode.singleton (reverse val)) stepFunc path val @ (n : _) = let nextEncoding :: ArithEncode.Encoding [Int] nextEncoding = ArithEncode.wrap (Just . head) (Just . (: val)) (ArithEncode.interval 0 (n - 1)) in stepWithPrefix path nextEncoding stepFunc tail enum :: Enumeration [Int] enum = step firstEncoding stepFunc tail depthFirstVals = [ ([0], [0,0]), ([1,0], [1,0,0]), ([2,0], [2,0,0]), ([2,1,0], [2,1,0,0]), ([3,0], [3,0,0]), ([3,1,0], [3,1,0,0]), ([3,2,0], [3,2,0,0]), ([3,2,1,0], [3,2,1,0,0]) ] breadthFirstVals = [ ([0], [0,0]), ([1,0], [1,0,0]), ([2,0], [2,0,0]), ([3,0], [3,0,0]), ([2,1,0], [2,1,0,0]), ([3,1,0], [3,1,0,0]), ([3,2,0], [3,2,0,0]), ([3,2,1,0], [3,2,1,0,0]) ] prioritizedVals = [ ([3,2,1,0], [3,2,1,0,0]), ([3,2,0], [3,2,0,0]), ([3,1,0], [3,1,0,0]), ([3,0], [3,0,0]), ([2,1,0], [2,1,0,0]), ([2,0], [2,0,0]), ([1,0], [1,0,0]), ([0], [0,0]) ] infOne :: ArithEncode.Encoding Integer infOne = ArithEncode.integral finTwo :: Path -> Integer -> Enumeration (Integer, Integer) finTwo path n = fromEncodingWithPrefix path (ArithEncode.wrap (Just . snd) (\m -> Just (n, m)) (ArithEncode.interval 0 3)) finOne :: ArithEncode.Encoding Integer finOne = ArithEncode.interval 0 3 infTwo :: Path -> Integer -> Enumeration (Integer, Integer) infTwo path n = fromEncodingWithPrefix path (ArithEncode.wrap (Just . snd) (\m -> Just (n, m)) ArithEncode.integral) infiniteFinite :: Enumeration (Integer, Integer) infiniteFinite = step infOne finTwo fst finiteInfinite :: Enumeration (Integer, Integer) finiteInfinite = step finOne infTwo fst infiniteInfinite :: Enumeration (Integer, Integer) infiniteInfinite = step infOne infTwo fst breadthFirstInfFinVals = [ ((0,0), [0,0]), ((0,1), [0,1]), ((0,2), [0,2]), ((0,3), [0,3]), ((-1,0), [1,0]), ((-1,1), [1,1]), ((-1,2), [1,2]), ((-1,3), [1,3]) ] breadthFirstFinInfVals = [ ((0,0), [0,0]), ((1,0), [1,0]), ((2,0), [2,0]), ((3,0), [3,0]), ((0,-1), [0,1]), ((1,-1), [1,1]), ((2,-1), [2,1]), ((3,-1), [3,1]) ] breadthFirstInfInfVals = [ ((0,0), [0,0]), ((0,-1), [0,1]), ((-1,0), [1,0]), ((0,1), [0,2]), ((-1,-1), [1,1]), ((1,0), [2,0]), ((0,-2), [0,3]), ((-1,1), [1,2]) ] depthFirstFinInfVals = [ ((0,0), [0,0]), ((0,-1), [0,1]), ((0,1), [0,2]), ((0,-2), [0,3]), ((0,2), [0,4]), ((0,-3), [0,5]), ((0,3), [0,6]), ((0,-4), [0,7]) ] depthFirstFinite :: DepthFirst [Int] depthFirstFinite = mkTraversal enum breadthFirstFinite :: BreadthFirst [Int] breadthFirstFinite = mkTraversal enum breadthFirstInfiniteFinite :: BreadthFirst (Integer, Integer) breadthFirstInfiniteFinite = mkTraversal infiniteFinite breadthFirstFiniteInfinite :: BreadthFirst (Integer, Integer) breadthFirstFiniteInfinite = mkTraversal finiteInfinite breadthFirstInfiniteInfinite :: BreadthFirst (Integer, Integer) breadthFirstInfiniteInfinite = mkTraversal infiniteInfinite depthFirstFiniteInfinite :: DepthFirst (Integer, Integer) depthFirstFiniteInfinite = mkTraversal finiteInfinite scorefunc (enum, curr) = fromIntegral (curr + sum (prefix enum)) prioritizedFinite :: Prioritized [Int] prioritizedFinite = mkPrioritizedTraversal scorefunc enum prioritizedDefaultVals = [ ([1,0], [1,0,0]), ([0], [0,0]), ([3,0], [3,0,0]), ([2,0], [2,0,0]), ([2,1,0], [2,1,0,0]), ([3,1,0], [3,1,0,0]), ([3,2,0], [3,2,0,0]), ([3,2,1,0], [3,2,1,0,0]) ] prioritizedFiniteDefault :: Prioritized [Int] prioritizedFiniteDefault = mkTraversal enum depthFirstTests = [ "finite" ~: getAll depthFirstFinite @?= depthFirstVals, "finiteInfinite" ~: take 8 (getAll depthFirstFiniteInfinite) @?= depthFirstFinInfVals ] breadthFirstTests = [ "finite" ~: getAll breadthFirstFinite @?= breadthFirstVals, "infiniteFinite" ~: take 8 (getAll breadthFirstInfiniteFinite) @?= breadthFirstInfFinVals, "finiteInfinite" ~: take 8 (getAll breadthFirstFiniteInfinite) @?= breadthFirstFinInfVals, "infiniteInfinite" ~: take 8 (getAll breadthFirstInfiniteInfinite) @?= breadthFirstInfInfVals ] prioritizedTests = [ "finite" ~: getAll prioritizedFinite @?= prioritizedVals, "default_finite" ~: getAll prioritizedFiniteDefault @?= prioritizedDefaultVals ] testlist :: [Test] testlist = [ "depthFirst" ~: depthFirstTests, "breadthFirst" ~: breadthFirstTests, "prioritized" ~: prioritizedTests ] tests :: Test tests = "Traversal" ~: testlist
emc2/enumeration
test/Tests/Data/Enumeration/Traversal.hs
bsd-3-clause
6,807
2
14
1,423
2,593
1,605
988
148
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts, FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Control.Monad.Classes.Log where import Control.Monad.Classes import Control.Monad.Log hiding (MonadLog(..), logMessage, mapLogMessage, mapLogMessageM, logDebug, logInfo, logNotice, logWarning, logError, logCritical, logAlert, logEmergency) import qualified Control.Monad.Log as Log import Control.Monad.Trans.Class (MonadTrans(..)) import GHC.Prim (proxy#, Proxy#) data EffLog (w :: *) type instance CanDo (LoggingT msg m) eff = LoggingCanDo msg eff type instance CanDo (PureLoggingT msg m) eff = LoggingCanDo msg eff type instance CanDo (DiscardLoggingT msg m) eff = LoggingCanDo msg eff type family LoggingCanDo msg eff where LoggingCanDo msg (EffLog msg) = 'True LoggingCanDo msg (EffWriter msg) = 'True LoggingCanDo msg eff = 'False #ifdef USE_FEUERBACH class Monad m => MonadLogN (k :: Nat) message m where #else class Monad m => MonadLogN (k :: Peano) message m where #endif logMessageFreeN :: Proxy# k -> (forall n. Monoid n => (message -> n) -> n) -> m () type MonadLog msg m = MonadLogN (Find (EffLog msg) m) msg m instance Monad m => MonadLogN 'Zero msg (LoggingT msg m) where logMessageFreeN _ = Log.logMessageFree {-# INLINABLE logMessageFreeN #-} instance (Monad m, Monoid msg) => MonadLogN 'Zero msg (PureLoggingT msg m) where logMessageFreeN _ = Log.logMessageFree {-# INLINABLE logMessageFreeN #-} instance Monad m => MonadLogN 'Zero msg (DiscardLoggingT msg m) where logMessageFreeN _ = Log.logMessageFree {-# INLINABLE logMessageFreeN #-} #ifdef USE_FEUERBACH instance (MonadTrans t, MonadLogN k msg m, Monad (t m)) => MonadLogN ('Suc k) msg (t m) where #else instance (MonadTrans t, MonadLogN k msg m, Monad (t m)) => MonadLogN ('Succ k) msg (t m) where #endif logMessageFreeN _ f = lift $ logMessageFreeN (proxy# :: Proxy# k) f {-# INLINABLE logMessageFreeN #-} logMessageFree :: forall msg m. MonadLog msg m => (forall n. Monoid n => (msg -> n) -> n) -> m () logMessageFree = logMessageFreeN (proxy# :: Proxy# (Find (EffLog msg) m)) {-# INLINABLE logMessageFree #-} logMessage :: MonadLog msg m => msg -> m () logMessage m = logMessageFree (\inject -> inject m) {-# INLINABLE logMessage #-} mapLogMessage :: MonadLog msg' m => (msg -> msg') -> LoggingT msg m a -> m a mapLogMessage f m = runLoggingT m (logMessage . f) {-# INLINABLE mapLogMessage #-} mapLogMessageM :: MonadLog msg' m => (msg -> m msg') -> LoggingT msg m a -> m a mapLogMessageM f m = runLoggingT m ((>>= logMessage) . f) {-# INLINABLE mapLogMessageM #-} logDebug :: MonadLog (WithSeverity a) m => a -> m () logDebug = logMessage . WithSeverity Debug {-# INLINEABLE logDebug #-} logInfo :: MonadLog (WithSeverity a) m => a -> m () logInfo = logMessage . WithSeverity Informational {-# INLINEABLE logInfo #-} logNotice :: MonadLog (WithSeverity a) m => a -> m () logNotice = logMessage . WithSeverity Notice {-# INLINEABLE logNotice #-} logWarning :: MonadLog (WithSeverity a) m => a -> m () logWarning = logMessage . WithSeverity Warning {-# INLINEABLE logWarning #-} logError :: MonadLog (WithSeverity a) m => a -> m () logError = logMessage . WithSeverity Error {-# INLINEABLE logError #-} logCritical :: MonadLog (WithSeverity a) m => a -> m () logCritical = logMessage . WithSeverity Critical {-# INLINEABLE logCritical #-} logAlert :: MonadLog (WithSeverity a) m => a -> m () logAlert = logMessage . WithSeverity Alert {-# INLINEABLE logAlert #-} logEmergency :: MonadLog (WithSeverity a) m => a -> m () logEmergency = logMessage . WithSeverity Emergency {-# INLINEABLE logEmergency #-} -- MonadWriter instances instance Monad m => MonadWriterN 'Zero msg (LoggingT msg m) where tellN _ msg = logMessage msg instance (Monad m, Monoid msg) => MonadWriterN 'Zero msg (PureLoggingT msg m) where tellN _ msg = logMessage msg instance Monad m => MonadWriterN 'Zero msg (DiscardLoggingT msg m) where tellN _ msg = logMessage msg
edwardgeorge/monad-classes-logging
src/Control/Monad/Classes/Log.hs
bsd-3-clause
4,652
0
14
1,118
1,310
693
617
-1
-1
----------------------------------------------------------------------------- -- -- Pretty-printing of Cmm as C, suitable for feeding gcc -- -- (c) The University of Glasgow 2004-2006 -- -- Print Cmm as real C, for -fvia-C -- -- See wiki:Commentary/Compiler/Backends/PprC -- -- This is simpler than the old PprAbsC, because Cmm is "macro-expanded" -- relative to the old AbstractC, and many oddities/decorations have -- disappeared from the data type. -- -- This code generator is only supported in unregisterised mode. -- ----------------------------------------------------------------------------- module PprC ( writeCs, pprStringInCStyle ) where #include "HsVersions.h" -- Cmm stuff import BlockId import CLabel import ForeignCall import OldCmm import OldPprCmm () -- Utils import Constants import CPrim import DynFlags import FastString import Outputable import Platform import UniqSet import Unique import Util -- The rest import Control.Monad.ST import Data.Bits import Data.Char import Data.List import Data.Map (Map) import Data.Word import System.IO import qualified Data.Map as Map #if __GLASGOW_HASKELL__ >= 703 import Data.Array.Unsafe ( castSTUArray ) import Data.Array.ST hiding ( castSTUArray ) #else import Data.Array.ST #endif -- -------------------------------------------------------------------------- -- Top level pprCs :: DynFlags -> [RawCmmGroup] -> SDoc pprCs dflags cmms = pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC (targetPlatform dflags) c) cmms) where split_marker | dopt Opt_SplitObjs dflags = ptext (sLit "__STG_SPLIT_MARKER") | otherwise = empty writeCs :: DynFlags -> Handle -> [RawCmmGroup] -> IO () writeCs dflags handle cmms = printForC handle (pprCs dflags cmms) -- -------------------------------------------------------------------------- -- Now do some real work -- -- for fun, we could call cmmToCmm over the tops... -- pprC :: Platform -> RawCmmGroup -> SDoc pprC platform tops = vcat $ intersperse blankLine $ map (pprTop platform) tops -- -- top level procs -- pprTop :: Platform -> RawCmmDecl -> SDoc pprTop platform (CmmProc mb_info clbl (ListGraph blocks)) = (case mb_info of Nothing -> empty Just (Statics info_clbl info_dat) -> pprDataExterns platform info_dat $$ pprWordArray platform info_clbl info_dat) $$ (vcat [ blankLine, extern_decls, (if (externallyVisibleCLabel clbl) then mkFN_ else mkIF_) (pprCLabel platform clbl) <+> lbrace, nest 8 temp_decls, nest 8 mkFB_, case blocks of [] -> empty -- the first block doesn't get a label: (BasicBlock _ stmts : rest) -> nest 8 (vcat (map (pprStmt platform) stmts)) $$ vcat (map (pprBBlock platform) rest), nest 8 mkFE_, rbrace ] ) where (temp_decls, extern_decls) = pprTempAndExternDecls platform blocks -- Chunks of static data. -- We only handle (a) arrays of word-sized things and (b) strings. pprTop platform (CmmData _section (Statics lbl [CmmString str])) = hcat [ pprLocalness lbl, ptext (sLit "char "), pprCLabel platform lbl, ptext (sLit "[] = "), pprStringInCStyle str, semi ] pprTop platform (CmmData _section (Statics lbl [CmmUninitialised size])) = hcat [ pprLocalness lbl, ptext (sLit "char "), pprCLabel platform lbl, brackets (int size), semi ] pprTop platform (CmmData _section (Statics lbl lits)) = pprDataExterns platform lits $$ pprWordArray platform lbl lits -- -------------------------------------------------------------------------- -- BasicBlocks are self-contained entities: they always end in a jump. -- -- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn -- as many jumps as possible into fall throughs. -- pprBBlock :: Platform -> CmmBasicBlock -> SDoc pprBBlock platform (BasicBlock lbl stmts) = if null stmts then pprTrace "pprC.pprBBlock: curious empty code block for" (pprBlockId lbl) empty else nest 4 (pprBlockId lbl <> colon) $$ nest 8 (vcat (map (pprStmt platform) stmts)) -- -------------------------------------------------------------------------- -- Info tables. Just arrays of words. -- See codeGen/ClosureInfo, and nativeGen/PprMach pprWordArray :: Platform -> CLabel -> [CmmStatic] -> SDoc pprWordArray platform lbl ds = hcat [ pprLocalness lbl, ptext (sLit "StgWord") , space, pprCLabel platform lbl, ptext (sLit "[] = {") ] $$ nest 8 (commafy (pprStatics platform ds)) $$ ptext (sLit "};") -- -- has to be static, if it isn't globally visible -- pprLocalness :: CLabel -> SDoc pprLocalness lbl | not $ externallyVisibleCLabel lbl = ptext (sLit "static ") | otherwise = empty -- -------------------------------------------------------------------------- -- Statements. -- pprStmt :: Platform -> CmmStmt -> SDoc pprStmt platform stmt = case stmt of CmmReturn _ -> panic "pprStmt: return statement should have been cps'd away" CmmNop -> empty CmmComment _ -> empty -- (hang (ptext (sLit "/*")) 3 (ftext s)) $$ ptext (sLit "*/") -- XXX if the string contains "*/", we need to fix it -- XXX we probably want to emit these comments when -- some debugging option is on. They can get quite -- large. CmmAssign dest src -> pprAssign platform dest src CmmStore dest src | typeWidth rep == W64 && wordWidth /= W64 -> (if isFloatType rep then ptext (sLit "ASSIGN_DBL") else ptext (sLit ("ASSIGN_Word64"))) <> parens (mkP_ <> pprExpr1 platform dest <> comma <> pprExpr platform src) <> semi | otherwise -> hsep [ pprExpr platform (CmmLoad dest rep), equals, pprExpr platform src <> semi ] where rep = cmmExprType src CmmCall (CmmCallee fn cconv) results args ret -> maybe_proto $$ fnCall where cast_fn = parens (cCast platform (pprCFunType (char '*') cconv results args) fn) real_fun_proto lbl = char ';' <> pprCFunType (pprCLabel platform lbl) cconv results args <> noreturn_attr <> semi noreturn_attr = case ret of CmmNeverReturns -> text "__attribute__ ((noreturn))" CmmMayReturn -> empty -- See wiki:Commentary/Compiler/Backends/PprC#Prototypes (maybe_proto, fnCall) = case fn of CmmLit (CmmLabel lbl) | StdCallConv <- cconv -> let myCall = pprCall platform (pprCLabel platform lbl) cconv results args in (real_fun_proto lbl, myCall) -- stdcall functions must be declared with -- a function type, otherwise the C compiler -- doesn't add the @n suffix to the label. We -- can't add the @n suffix ourselves, because -- it isn't valid C. | CmmNeverReturns <- ret -> let myCall = pprCall platform (pprCLabel platform lbl) cconv results args in (real_fun_proto lbl, myCall) | not (isMathFun lbl) -> pprForeignCall platform (pprCLabel platform lbl) cconv results args _ -> (empty {- no proto -}, pprCall platform cast_fn cconv results args <> semi) -- for a dynamic call, no declaration is necessary. CmmCall (CmmPrim op) results args _ret -> proto $$ fn_call where cconv = CCallConv fn = pprCallishMachOp_for_C op (proto, fn_call) -- The mem primops carry an extra alignment arg, must drop it. -- We could maybe emit an alignment directive using this info. -- We also need to cast mem primops to prevent conflicts with GCC -- builtins (see bug #5967). | op `elem` [MO_Memcpy, MO_Memset, MO_Memmove] = pprForeignCall platform fn cconv results (init args) | otherwise = (empty, pprCall platform fn cconv results args) CmmBranch ident -> pprBranch ident CmmCondBranch expr ident -> pprCondBranch platform expr ident CmmJump lbl _params -> mkJMP_(pprExpr platform lbl) <> semi CmmSwitch arg ids -> pprSwitch platform arg ids pprForeignCall :: Platform -> SDoc -> CCallConv -> [HintedCmmFormal] -> [HintedCmmActual] -> (SDoc, SDoc) pprForeignCall platform fn cconv results args = (proto, fn_call) where fn_call = braces ( pprCFunType (char '*' <> text "ghcFunPtr") cconv results args <> semi $$ text "ghcFunPtr" <+> equals <+> cast_fn <> semi $$ pprCall platform (text "ghcFunPtr") cconv results args <> semi ) cast_fn = parens (parens (pprCFunType (char '*') cconv results args) <> fn) proto = ptext (sLit ";EF_(") <> fn <> char ')' <> semi pprCFunType :: SDoc -> CCallConv -> [HintedCmmFormal] -> [HintedCmmActual] -> SDoc pprCFunType ppr_fn cconv ress args = res_type ress <+> parens (ccallConvAttribute cconv <> ppr_fn) <> parens (commafy (map arg_type args)) where res_type [] = ptext (sLit "void") res_type [CmmHinted one hint] = machRepHintCType (localRegType one) hint res_type _ = panic "pprCFunType: only void or 1 return value supported" arg_type (CmmHinted expr hint) = machRepHintCType (cmmExprType expr) hint -- --------------------------------------------------------------------- -- unconditional branches pprBranch :: BlockId -> SDoc pprBranch ident = ptext (sLit "goto") <+> pprBlockId ident <> semi -- --------------------------------------------------------------------- -- conditional branches to local labels pprCondBranch :: Platform -> CmmExpr -> BlockId -> SDoc pprCondBranch platform expr ident = hsep [ ptext (sLit "if") , parens(pprExpr platform expr) , ptext (sLit "goto") , (pprBlockId ident) <> semi ] -- --------------------------------------------------------------------- -- a local table branch -- -- we find the fall-through cases -- -- N.B. we remove Nothing's from the list of branches, as they are -- 'undefined'. However, they may be defined one day, so we better -- document this behaviour. -- pprSwitch :: Platform -> CmmExpr -> [ Maybe BlockId ] -> SDoc pprSwitch platform e maybe_ids = let pairs = [ (ix, ident) | (ix,Just ident) <- zip [0..] maybe_ids ] pairs2 = [ (map fst as, snd (head as)) | as <- groupBy sndEq pairs ] in (hang (ptext (sLit "switch") <+> parens ( pprExpr platform e ) <+> lbrace) 4 (vcat ( map caseify pairs2 ))) $$ rbrace where sndEq (_,x) (_,y) = x == y -- fall through case caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix where do_fallthrough ix = hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon , ptext (sLit "/* fall through */") ] final_branch ix = hsep [ ptext (sLit "case") , pprHexVal ix wordWidth <> colon , ptext (sLit "goto") , (pprBlockId ident) <> semi ] caseify (_ , _ ) = panic "pprSwtich: swtich with no cases!" -- --------------------------------------------------------------------- -- Expressions. -- -- C Types: the invariant is that the C expression generated by -- -- pprExpr e -- -- has a type in C which is also given by -- -- machRepCType (cmmExprType e) -- -- (similar invariants apply to the rest of the pretty printer). pprExpr :: Platform -> CmmExpr -> SDoc pprExpr platform e = case e of CmmLit lit -> pprLit platform lit CmmLoad e ty -> pprLoad platform e ty CmmReg reg -> pprCastReg reg CmmRegOff reg 0 -> pprCastReg reg CmmRegOff reg i | i > 0 -> pprRegOff (char '+') i | otherwise -> pprRegOff (char '-') (-i) where pprRegOff op i' = pprCastReg reg <> op <> int i' CmmMachOp mop args -> pprMachOpApp platform mop args CmmStackSlot _ _ -> panic "pprExpr: CmmStackSlot not supported!" pprLoad :: Platform -> CmmExpr -> CmmType -> SDoc pprLoad platform e ty | width == W64, wordWidth /= W64 = (if isFloatType ty then ptext (sLit "PK_DBL") else ptext (sLit "PK_Word64")) <> parens (mkP_ <> pprExpr1 platform e) | otherwise = case e of CmmReg r | isPtrReg r && width == wordWidth && not (isFloatType ty) -> char '*' <> pprAsPtrReg r CmmRegOff r 0 | isPtrReg r && width == wordWidth && not (isFloatType ty) -> char '*' <> pprAsPtrReg r CmmRegOff r off | isPtrReg r && width == wordWidth , off `rem` wORD_SIZE == 0 && not (isFloatType ty) -- ToDo: check that the offset is a word multiple? -- (For tagging to work, I had to avoid unaligned loads. --ARY) -> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift)) _other -> cLoad platform e ty where width = typeWidth ty pprExpr1 :: Platform -> CmmExpr -> SDoc pprExpr1 platform (CmmLit lit) = pprLit1 platform lit pprExpr1 platform e@(CmmReg _reg) = pprExpr platform e pprExpr1 platform other = parens (pprExpr platform other) -- -------------------------------------------------------------------------- -- MachOp applications pprMachOpApp :: Platform -> MachOp -> [CmmExpr] -> SDoc pprMachOpApp platform op args | isMulMayOfloOp op = ptext (sLit "mulIntMayOflo") <> parens (commafy (map (pprExpr platform) args)) where isMulMayOfloOp (MO_U_MulMayOflo _) = True isMulMayOfloOp (MO_S_MulMayOflo _) = True isMulMayOfloOp _ = False pprMachOpApp platform mop args | Just ty <- machOpNeedsCast mop = ty <> parens (pprMachOpApp' platform mop args) | otherwise = pprMachOpApp' platform mop args -- Comparisons in C have type 'int', but we want type W_ (this is what -- resultRepOfMachOp says). The other C operations inherit their type -- from their operands, so no casting is required. machOpNeedsCast :: MachOp -> Maybe SDoc machOpNeedsCast mop | isComparisonMachOp mop = Just mkW_ | otherwise = Nothing pprMachOpApp' :: Platform -> MachOp -> [CmmExpr] -> SDoc pprMachOpApp' platform mop args = case args of -- dyadic [x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y -- unary [x] -> pprMachOp_for_C mop <> parens (pprArg x) _ -> panic "PprC.pprMachOp : machop with wrong number of args" where -- Cast needed for signed integer ops pprArg e | signedOp mop = cCast platform (machRep_S_CType (typeWidth (cmmExprType e))) e | needsFCasts mop = cCast platform (machRep_F_CType (typeWidth (cmmExprType e))) e | otherwise = pprExpr1 platform e needsFCasts (MO_F_Eq _) = False needsFCasts (MO_F_Ne _) = False needsFCasts (MO_F_Neg _) = True needsFCasts (MO_F_Quot _) = True needsFCasts mop = floatComparison mop -- -------------------------------------------------------------------------- -- Literals pprLit :: Platform -> CmmLit -> SDoc pprLit platform lit = case lit of CmmInt i rep -> pprHexVal i rep CmmFloat f w -> parens (machRep_F_CType w) <> str where d = fromRational f :: Double str | isInfinite d && d < 0 = ptext (sLit "-INFINITY") | isInfinite d = ptext (sLit "INFINITY") | isNaN d = ptext (sLit "NAN") | otherwise = text (show d) -- these constants come from <math.h> -- see #1861 CmmBlock bid -> mkW_ <> pprCLabelAddr (infoTblLbl bid) CmmHighStackMark -> panic "PprC printing high stack mark" CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i CmmLabelDiffOff clbl1 _ i -- WARNING: -- * the lit must occur in the info table clbl2 -- * clbl1 must be an SRT, a slow entry point or a large bitmap -> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i where pprCLabelAddr lbl = char '&' <> pprCLabel platform lbl pprLit1 :: Platform -> CmmLit -> SDoc pprLit1 platform lit@(CmmLabelOff _ _) = parens (pprLit platform lit) pprLit1 platform lit@(CmmLabelDiffOff _ _ _) = parens (pprLit platform lit) pprLit1 platform lit@(CmmFloat _ _) = parens (pprLit platform lit) pprLit1 platform other = pprLit platform other -- --------------------------------------------------------------------------- -- Static data pprStatics :: Platform -> [CmmStatic] -> [SDoc] pprStatics _ [] = [] pprStatics platform (CmmStaticLit (CmmFloat f W32) : rest) -- floats are padded to a word, see #1852 | wORD_SIZE == 8, CmmStaticLit (CmmInt 0 W32) : rest' <- rest = pprLit1 platform (floatToWord f) : pprStatics platform rest' | wORD_SIZE == 4 = pprLit1 platform (floatToWord f) : pprStatics platform rest | otherwise = pprPanic "pprStatics: float" (vcat (map ppr' rest)) where ppr' (CmmStaticLit l) = ppr (cmmLitType l) ppr' _other = ptext (sLit "bad static!") pprStatics platform (CmmStaticLit (CmmFloat f W64) : rest) = map (pprLit1 platform) (doubleToWords f) ++ pprStatics platform rest pprStatics platform (CmmStaticLit (CmmInt i W64) : rest) | wordWidth == W32 #ifdef WORDS_BIGENDIAN = pprStatics platform (CmmStaticLit (CmmInt q W32) : CmmStaticLit (CmmInt r W32) : rest) #else = pprStatics platform (CmmStaticLit (CmmInt r W32) : CmmStaticLit (CmmInt q W32) : rest) #endif where r = i .&. 0xffffffff q = i `shiftR` 32 pprStatics _ (CmmStaticLit (CmmInt _ w) : _) | w /= wordWidth = panic "pprStatics: cannot emit a non-word-sized static literal" pprStatics platform (CmmStaticLit lit : rest) = pprLit1 platform lit : pprStatics platform rest pprStatics platform (other : _) = pprPanic "pprWord" (pprStatic platform other) pprStatic :: Platform -> CmmStatic -> SDoc pprStatic platform s = case s of CmmStaticLit lit -> nest 4 (pprLit platform lit) CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i)) -- these should be inlined, like the old .hc CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s')) -- --------------------------------------------------------------------------- -- Block Ids pprBlockId :: BlockId -> SDoc pprBlockId b = char '_' <> ppr (getUnique b) -- -------------------------------------------------------------------------- -- Print a MachOp in a way suitable for emitting via C. -- pprMachOp_for_C :: MachOp -> SDoc pprMachOp_for_C mop = case mop of -- Integer operations MO_Add _ -> char '+' MO_Sub _ -> char '-' MO_Eq _ -> ptext (sLit "==") MO_Ne _ -> ptext (sLit "!=") MO_Mul _ -> char '*' MO_S_Quot _ -> char '/' MO_S_Rem _ -> char '%' MO_S_Neg _ -> char '-' MO_U_Quot _ -> char '/' MO_U_Rem _ -> char '%' -- & Floating-point operations MO_F_Add _ -> char '+' MO_F_Sub _ -> char '-' MO_F_Neg _ -> char '-' MO_F_Mul _ -> char '*' MO_F_Quot _ -> char '/' -- Signed comparisons MO_S_Ge _ -> ptext (sLit ">=") MO_S_Le _ -> ptext (sLit "<=") MO_S_Gt _ -> char '>' MO_S_Lt _ -> char '<' -- & Unsigned comparisons MO_U_Ge _ -> ptext (sLit ">=") MO_U_Le _ -> ptext (sLit "<=") MO_U_Gt _ -> char '>' MO_U_Lt _ -> char '<' -- & Floating-point comparisons MO_F_Eq _ -> ptext (sLit "==") MO_F_Ne _ -> ptext (sLit "!=") MO_F_Ge _ -> ptext (sLit ">=") MO_F_Le _ -> ptext (sLit "<=") MO_F_Gt _ -> char '>' MO_F_Lt _ -> char '<' -- Bitwise operations. Not all of these may be supported at all -- sizes, and only integral MachReps are valid. MO_And _ -> char '&' MO_Or _ -> char '|' MO_Xor _ -> char '^' MO_Not _ -> char '~' MO_Shl _ -> ptext (sLit "<<") MO_U_Shr _ -> ptext (sLit ">>") -- unsigned shift right MO_S_Shr _ -> ptext (sLit ">>") -- signed shift right -- Conversions. Some of these will be NOPs, but never those that convert -- between ints and floats. -- Floating-point conversions use the signed variant. -- We won't know to generate (void*) casts here, but maybe from -- context elsewhere -- noop casts MO_UU_Conv from to | from == to -> empty MO_UU_Conv _from to -> parens (machRep_U_CType to) MO_SS_Conv from to | from == to -> empty MO_SS_Conv _from to -> parens (machRep_S_CType to) MO_FF_Conv from to | from == to -> empty MO_FF_Conv _from to -> parens (machRep_F_CType to) MO_SF_Conv _from to -> parens (machRep_F_CType to) MO_FS_Conv _from to -> parens (machRep_S_CType to) MO_S_MulMayOflo _ -> pprTrace "offending mop:" (ptext $ sLit "MO_S_MulMayOflo") (panic $ "PprC.pprMachOp_for_C: MO_S_MulMayOflo" ++ " should have been handled earlier!") MO_U_MulMayOflo _ -> pprTrace "offending mop:" (ptext $ sLit "MO_U_MulMayOflo") (panic $ "PprC.pprMachOp_for_C: MO_U_MulMayOflo" ++ " should have been handled earlier!") signedOp :: MachOp -> Bool -- Argument type(s) are signed ints signedOp (MO_S_Quot _) = True signedOp (MO_S_Rem _) = True signedOp (MO_S_Neg _) = True signedOp (MO_S_Ge _) = True signedOp (MO_S_Le _) = True signedOp (MO_S_Gt _) = True signedOp (MO_S_Lt _) = True signedOp (MO_S_Shr _) = True signedOp (MO_SS_Conv _ _) = True signedOp (MO_SF_Conv _ _) = True signedOp _ = False floatComparison :: MachOp -> Bool -- comparison between float args floatComparison (MO_F_Eq _) = True floatComparison (MO_F_Ne _) = True floatComparison (MO_F_Ge _) = True floatComparison (MO_F_Le _) = True floatComparison (MO_F_Gt _) = True floatComparison (MO_F_Lt _) = True floatComparison _ = False -- --------------------------------------------------------------------- -- tend to be implemented by foreign calls pprCallishMachOp_for_C :: CallishMachOp -> SDoc pprCallishMachOp_for_C mop = case mop of MO_F64_Pwr -> ptext (sLit "pow") MO_F64_Sin -> ptext (sLit "sin") MO_F64_Cos -> ptext (sLit "cos") MO_F64_Tan -> ptext (sLit "tan") MO_F64_Sinh -> ptext (sLit "sinh") MO_F64_Cosh -> ptext (sLit "cosh") MO_F64_Tanh -> ptext (sLit "tanh") MO_F64_Asin -> ptext (sLit "asin") MO_F64_Acos -> ptext (sLit "acos") MO_F64_Atan -> ptext (sLit "atan") MO_F64_Log -> ptext (sLit "log") MO_F64_Exp -> ptext (sLit "exp") MO_F64_Sqrt -> ptext (sLit "sqrt") MO_F32_Pwr -> ptext (sLit "powf") MO_F32_Sin -> ptext (sLit "sinf") MO_F32_Cos -> ptext (sLit "cosf") MO_F32_Tan -> ptext (sLit "tanf") MO_F32_Sinh -> ptext (sLit "sinhf") MO_F32_Cosh -> ptext (sLit "coshf") MO_F32_Tanh -> ptext (sLit "tanhf") MO_F32_Asin -> ptext (sLit "asinf") MO_F32_Acos -> ptext (sLit "acosf") MO_F32_Atan -> ptext (sLit "atanf") MO_F32_Log -> ptext (sLit "logf") MO_F32_Exp -> ptext (sLit "expf") MO_F32_Sqrt -> ptext (sLit "sqrtf") MO_WriteBarrier -> ptext (sLit "write_barrier") MO_Memcpy -> ptext (sLit "memcpy") MO_Memset -> ptext (sLit "memset") MO_Memmove -> ptext (sLit "memmove") (MO_PopCnt w) -> ptext (sLit $ popCntLabel w) MO_Touch -> panic $ "pprCallishMachOp_for_C: MO_Touch not supported!" -- --------------------------------------------------------------------- -- Useful #defines -- mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc mkJMP_ i = ptext (sLit "JMP_") <> parens i mkFN_ i = ptext (sLit "FN_") <> parens i -- externally visible function mkIF_ i = ptext (sLit "IF_") <> parens i -- locally visible mkFB_, mkFE_ :: SDoc mkFB_ = ptext (sLit "FB_") -- function code begin mkFE_ = ptext (sLit "FE_") -- function code end -- from includes/Stg.h -- mkC_,mkW_,mkP_ :: SDoc mkC_ = ptext (sLit "(C_)") -- StgChar mkW_ = ptext (sLit "(W_)") -- StgWord mkP_ = ptext (sLit "(P_)") -- StgWord* -- --------------------------------------------------------------------- -- -- Assignments -- -- Generating assignments is what we're all about, here -- pprAssign :: Platform -> CmmReg -> CmmExpr -> SDoc -- dest is a reg, rhs is a reg pprAssign _ r1 (CmmReg r2) | isPtrReg r1 && isPtrReg r2 = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ] -- dest is a reg, rhs is a CmmRegOff pprAssign _ r1 (CmmRegOff r2 off) | isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE == 0) = hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ] where off1 = off `shiftR` wordShift (op,off') | off >= 0 = (char '+', off1) | otherwise = (char '-', -off1) -- dest is a reg, rhs is anything. -- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting -- the lvalue elicits a warning from new GCC versions (3.4+). pprAssign platform r1 r2 | isFixedPtrReg r1 = mkAssign (mkP_ <> pprExpr1 platform r2) | Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 platform r2) | otherwise = mkAssign (pprExpr platform r2) where mkAssign x = if r1 == CmmGlobal BaseReg then ptext (sLit "ASSIGN_BaseReg") <> parens x <> semi else pprReg r1 <> ptext (sLit " = ") <> x <> semi -- --------------------------------------------------------------------- -- Registers pprCastReg :: CmmReg -> SDoc pprCastReg reg | isStrangeTypeReg reg = mkW_ <> pprReg reg | otherwise = pprReg reg -- True if (pprReg reg) will give an expression with type StgPtr. We -- need to take care with pointer arithmetic on registers with type -- StgPtr. isFixedPtrReg :: CmmReg -> Bool isFixedPtrReg (CmmLocal _) = False isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r -- True if (pprAsPtrReg reg) will give an expression with type StgPtr -- JD: THIS IS HORRIBLE AND SHOULD BE RENAMED, AT THE VERY LEAST. -- THE GARBAGE WITH THE VNonGcPtr HELPS MATCH THE OLD CODE GENERATOR'S OUTPUT; -- I'M NOT SURE IF IT SHOULD REALLY STAY THAT WAY. isPtrReg :: CmmReg -> Bool isPtrReg (CmmLocal _) = False isPtrReg (CmmGlobal (VanillaReg _ VGcPtr)) = True -- if we print via pprAsPtrReg isPtrReg (CmmGlobal (VanillaReg _ VNonGcPtr)) = False -- if we print via pprAsPtrReg isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg -- True if this global reg has type StgPtr isFixedPtrGlobalReg :: GlobalReg -> Bool isFixedPtrGlobalReg Sp = True isFixedPtrGlobalReg Hp = True isFixedPtrGlobalReg HpLim = True isFixedPtrGlobalReg SpLim = True isFixedPtrGlobalReg _ = False -- True if in C this register doesn't have the type given by -- (machRepCType (cmmRegType reg)), so it has to be cast. isStrangeTypeReg :: CmmReg -> Bool isStrangeTypeReg (CmmLocal _) = False isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g isStrangeTypeGlobal :: GlobalReg -> Bool isStrangeTypeGlobal CCCS = True isStrangeTypeGlobal CurrentTSO = True isStrangeTypeGlobal CurrentNursery = True isStrangeTypeGlobal BaseReg = True isStrangeTypeGlobal r = isFixedPtrGlobalReg r strangeRegType :: CmmReg -> Maybe SDoc strangeRegType (CmmGlobal CCCS) = Just (ptext (sLit "struct CostCentreStack_ *")) strangeRegType (CmmGlobal CurrentTSO) = Just (ptext (sLit "struct StgTSO_ *")) strangeRegType (CmmGlobal CurrentNursery) = Just (ptext (sLit "struct bdescr_ *")) strangeRegType (CmmGlobal BaseReg) = Just (ptext (sLit "struct StgRegTable_ *")) strangeRegType _ = Nothing -- pprReg just prints the register name. -- pprReg :: CmmReg -> SDoc pprReg r = case r of CmmLocal local -> pprLocalReg local CmmGlobal global -> pprGlobalReg global pprAsPtrReg :: CmmReg -> SDoc pprAsPtrReg (CmmGlobal (VanillaReg n gcp)) = WARN( gcp /= VGcPtr, ppr n ) char 'R' <> int n <> ptext (sLit ".p") pprAsPtrReg other_reg = pprReg other_reg pprGlobalReg :: GlobalReg -> SDoc pprGlobalReg gr = case gr of VanillaReg n _ -> char 'R' <> int n <> ptext (sLit ".w") -- pprGlobalReg prints a VanillaReg as a .w regardless -- Example: R1.w = R1.w & (-0x8UL); -- JMP_(*R1.p); FloatReg n -> char 'F' <> int n DoubleReg n -> char 'D' <> int n LongReg n -> char 'L' <> int n Sp -> ptext (sLit "Sp") SpLim -> ptext (sLit "SpLim") Hp -> ptext (sLit "Hp") HpLim -> ptext (sLit "HpLim") CCCS -> ptext (sLit "CCCS") CurrentTSO -> ptext (sLit "CurrentTSO") CurrentNursery -> ptext (sLit "CurrentNursery") HpAlloc -> ptext (sLit "HpAlloc") BaseReg -> ptext (sLit "BaseReg") EagerBlackholeInfo -> ptext (sLit "stg_EAGER_BLACKHOLE_info") GCEnter1 -> ptext (sLit "stg_gc_enter_1") GCFun -> ptext (sLit "stg_gc_fun") other -> panic $ "pprGlobalReg: Unsupported register: " ++ show other pprLocalReg :: LocalReg -> SDoc pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq -- ----------------------------------------------------------------------------- -- Foreign Calls pprCall :: Platform -> SDoc -> CCallConv -> [HintedCmmFormal] -> [HintedCmmActual] -> SDoc pprCall platform ppr_fn cconv results args | not (is_cishCC cconv) = panic $ "pprCall: unknown calling convention" | otherwise = ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi where ppr_assign [] rhs = rhs ppr_assign [CmmHinted one hint] rhs = pprLocalReg one <> ptext (sLit " = ") <> pprUnHint hint (localRegType one) <> rhs ppr_assign _other _rhs = panic "pprCall: multiple results" pprArg (CmmHinted expr AddrHint) = cCast platform (ptext (sLit "void *")) expr -- see comment by machRepHintCType below pprArg (CmmHinted expr SignedHint) = cCast platform (machRep_S_CType $ typeWidth $ cmmExprType expr) expr pprArg (CmmHinted expr _other) = pprExpr platform expr pprUnHint AddrHint rep = parens (machRepCType rep) pprUnHint SignedHint rep = parens (machRepCType rep) pprUnHint _ _ = empty -- Currently we only have these two calling conventions, but this might -- change in the future... is_cishCC :: CCallConv -> Bool is_cishCC CCallConv = True is_cishCC CApiConv = True is_cishCC StdCallConv = True is_cishCC CmmCallConv = False is_cishCC PrimCallConv = False -- --------------------------------------------------------------------- -- Find and print local and external declarations for a list of -- Cmm statements. -- pprTempAndExternDecls :: Platform -> [CmmBasicBlock] -> (SDoc{-temps-}, SDoc{-externs-}) pprTempAndExternDecls platform stmts = (vcat (map pprTempDecl (uniqSetToList temps)), vcat (map (pprExternDecl platform False{-ToDo-}) (Map.keys lbls))) where (temps, lbls) = runTE (mapM_ te_BB stmts) pprDataExterns :: Platform -> [CmmStatic] -> SDoc pprDataExterns platform statics = vcat (map (pprExternDecl platform False{-ToDo-}) (Map.keys lbls)) where (_, lbls) = runTE (mapM_ te_Static statics) pprTempDecl :: LocalReg -> SDoc pprTempDecl l@(LocalReg _ rep) = hcat [ machRepCType rep, space, pprLocalReg l, semi ] pprExternDecl :: Platform -> Bool -> CLabel -> SDoc pprExternDecl platform _in_srt lbl -- do not print anything for "known external" things | not (needsCDecl lbl) = empty | Just sz <- foreignLabelStdcallInfo lbl = stdcall_decl sz | otherwise = hcat [ visibility, label_type lbl, lparen, pprCLabel platform lbl, text ");" ] where label_type lbl | isCFunctionLabel lbl = ptext (sLit "F_") | otherwise = ptext (sLit "I_") visibility | externallyVisibleCLabel lbl = char 'E' | otherwise = char 'I' -- If the label we want to refer to is a stdcall function (on Windows) then -- we must generate an appropriate prototype for it, so that the C compiler will -- add the @n suffix to the label (#2276) stdcall_decl sz = ptext (sLit "extern __attribute__((stdcall)) void ") <> pprCLabel platform lbl <> parens (commafy (replicate (sz `quot` wORD_SIZE) (machRep_U_CType wordWidth))) <> semi type TEState = (UniqSet LocalReg, Map CLabel ()) newtype TE a = TE { unTE :: TEState -> (a, TEState) } instance Monad TE where TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s' return a = TE $ \s -> (a, s) te_lbl :: CLabel -> TE () te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, Map.insert lbl () lbls)) te_temp :: LocalReg -> TE () te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls)) runTE :: TE () -> TEState runTE (TE m) = snd (m (emptyUniqSet, Map.empty)) te_Static :: CmmStatic -> TE () te_Static (CmmStaticLit lit) = te_Lit lit te_Static _ = return () te_BB :: CmmBasicBlock -> TE () te_BB (BasicBlock _ ss) = mapM_ te_Stmt ss te_Lit :: CmmLit -> TE () te_Lit (CmmLabel l) = te_lbl l te_Lit (CmmLabelOff l _) = te_lbl l te_Lit (CmmLabelDiffOff l1 _ _) = te_lbl l1 te_Lit _ = return () te_Stmt :: CmmStmt -> TE () te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r te_Stmt (CmmCall _ rs es _) = mapM_ (te_temp.hintlessCmm) rs >> mapM_ (te_Expr.hintlessCmm) es te_Stmt (CmmCondBranch e _) = te_Expr e te_Stmt (CmmSwitch e _) = te_Expr e te_Stmt (CmmJump e _) = te_Expr e te_Stmt _ = return () te_Expr :: CmmExpr -> TE () te_Expr (CmmLit lit) = te_Lit lit te_Expr (CmmLoad e _) = te_Expr e te_Expr (CmmReg r) = te_Reg r te_Expr (CmmMachOp _ es) = mapM_ te_Expr es te_Expr (CmmRegOff r _) = te_Reg r te_Expr (CmmStackSlot _ _) = panic "te_Expr: CmmStackSlot not supported!" te_Reg :: CmmReg -> TE () te_Reg (CmmLocal l) = te_temp l te_Reg _ = return () -- --------------------------------------------------------------------- -- C types for MachReps cCast :: Platform -> SDoc -> CmmExpr -> SDoc cCast platform ty expr = parens ty <> pprExpr1 platform expr cLoad :: Platform -> CmmExpr -> CmmType -> SDoc cLoad platform expr rep | bewareLoadStoreAlignment (platformArch platform) = let decl = machRepCType rep <+> ptext (sLit "x") <> semi struct = ptext (sLit "struct") <+> braces (decl) packed_attr = ptext (sLit "__attribute__((packed))") cast = parens (struct <+> packed_attr <> char '*') in parens (cast <+> pprExpr1 platform expr) <> ptext (sLit "->x") | otherwise = char '*' <> parens (cCast platform (machRepPtrCType rep) expr) where -- On these platforms, unaligned loads are known to cause problems bewareLoadStoreAlignment (ArchARM {}) = True bewareLoadStoreAlignment _ = False isCmmWordType :: CmmType -> Bool -- True of GcPtrReg/NonGcReg of native word size isCmmWordType ty = not (isFloatType ty) && typeWidth ty == wordWidth -- This is for finding the types of foreign call arguments. For a pointer -- argument, we always cast the argument to (void *), to avoid warnings from -- the C compiler. machRepHintCType :: CmmType -> ForeignHint -> SDoc machRepHintCType _ AddrHint = ptext (sLit "void *") machRepHintCType rep SignedHint = machRep_S_CType (typeWidth rep) machRepHintCType rep _other = machRepCType rep machRepPtrCType :: CmmType -> SDoc machRepPtrCType r | isCmmWordType r = ptext (sLit "P_") | otherwise = machRepCType r <> char '*' machRepCType :: CmmType -> SDoc machRepCType ty | isFloatType ty = machRep_F_CType w | otherwise = machRep_U_CType w where w = typeWidth ty machRep_F_CType :: Width -> SDoc machRep_F_CType W32 = ptext (sLit "StgFloat") -- ToDo: correct? machRep_F_CType W64 = ptext (sLit "StgDouble") machRep_F_CType _ = panic "machRep_F_CType" machRep_U_CType :: Width -> SDoc machRep_U_CType w | w == wordWidth = ptext (sLit "W_") machRep_U_CType W8 = ptext (sLit "StgWord8") machRep_U_CType W16 = ptext (sLit "StgWord16") machRep_U_CType W32 = ptext (sLit "StgWord32") machRep_U_CType W64 = ptext (sLit "StgWord64") machRep_U_CType _ = panic "machRep_U_CType" machRep_S_CType :: Width -> SDoc machRep_S_CType w | w == wordWidth = ptext (sLit "I_") machRep_S_CType W8 = ptext (sLit "StgInt8") machRep_S_CType W16 = ptext (sLit "StgInt16") machRep_S_CType W32 = ptext (sLit "StgInt32") machRep_S_CType W64 = ptext (sLit "StgInt64") machRep_S_CType _ = panic "machRep_S_CType" -- --------------------------------------------------------------------- -- print strings as valid C strings pprStringInCStyle :: [Word8] -> SDoc pprStringInCStyle s = doubleQuotes (text (concatMap charToC s)) -- --------------------------------------------------------------------------- -- Initialising static objects with floating-point numbers. We can't -- just emit the floating point number, because C will cast it to an int -- by rounding it. We want the actual bit-representation of the float. -- This is a hack to turn the floating point numbers into ints that we -- can safely initialise to static locations. big_doubles :: Bool big_doubles | widthInBytes W64 == 2 * wORD_SIZE = True | widthInBytes W64 == wORD_SIZE = False | otherwise = panic "big_doubles" castFloatToIntArray :: STUArray s Int Float -> ST s (STUArray s Int Int) castFloatToIntArray = castSTUArray castDoubleToIntArray :: STUArray s Int Double -> ST s (STUArray s Int Int) castDoubleToIntArray = castSTUArray -- floats are always 1 word floatToWord :: Rational -> CmmLit floatToWord r = runST (do arr <- newArray_ ((0::Int),0) writeArray arr 0 (fromRational r) arr' <- castFloatToIntArray arr i <- readArray arr' 0 return (CmmInt (toInteger i) wordWidth) ) doubleToWords :: Rational -> [CmmLit] doubleToWords r | big_doubles -- doubles are 2 words = runST (do arr <- newArray_ ((0::Int),1) writeArray arr 0 (fromRational r) arr' <- castDoubleToIntArray arr i1 <- readArray arr' 0 i2 <- readArray arr' 1 return [ CmmInt (toInteger i1) wordWidth , CmmInt (toInteger i2) wordWidth ] ) | otherwise -- doubles are 1 word = runST (do arr <- newArray_ ((0::Int),0) writeArray arr 0 (fromRational r) arr' <- castDoubleToIntArray arr i <- readArray arr' 0 return [ CmmInt (toInteger i) wordWidth ] ) -- --------------------------------------------------------------------------- -- Utils wordShift :: Int wordShift = widthInLog wordWidth commafy :: [SDoc] -> SDoc commafy xs = hsep $ punctuate comma xs -- Print in C hex format: 0x13fa pprHexVal :: Integer -> Width -> SDoc pprHexVal 0 _ = ptext (sLit "0x0") pprHexVal w rep | w < 0 = parens (char '-' <> ptext (sLit "0x") <> go (-w) <> repsuffix rep) | otherwise = ptext (sLit "0x") <> go w <> repsuffix rep where -- type suffix for literals: -- Integer literals are unsigned in Cmm/C. We explicitly cast to -- signed values for doing signed operations, but at all other -- times values are unsigned. This also helps eliminate occasional -- warnings about integer overflow from gcc. -- on 32-bit platforms, add "ULL" to 64-bit literals repsuffix W64 | wORD_SIZE == 4 = ptext (sLit "ULL") -- on 64-bit platforms with 32-bit int, add "L" to 64-bit literals repsuffix W64 | cINT_SIZE == 4 = ptext (sLit "UL") repsuffix _ = char 'U' go 0 = empty go w' = go q <> dig where (q,r) = w' `quotRem` 16 dig | r < 10 = char (chr (fromInteger r + ord '0')) | otherwise = char (chr (fromInteger r - 10 + ord 'a'))
ilyasergey/GHC-XAppFix
compiler/cmm/PprC.hs
bsd-3-clause
41,510
677
21
11,353
10,306
5,424
4,882
688
46
{- Copyright 2013-2019 Mario Blazevic License: BSD3 (see BSD3-LICENSE.txt file) -} -- | This module defines the 'Semigroup' => 'Factorial' => 'StableFactorial' classes and some of their instances. -- {-# LANGUAGE Haskell2010, FlexibleInstances, Trustworthy #-} module Data.Semigroup.Factorial ( -- * Classes Factorial(..), StableFactorial, -- * Monad function equivalents mapM, mapM_ ) where import qualified Control.Monad as Monad import Data.Semigroup -- (Semigroup (..), Dual(..), Sum(..), Product(..), Endo(Endo, appEndo)) import qualified Data.Foldable as Foldable import qualified Data.List as List import qualified Data.ByteString as ByteString import qualified Data.ByteString.Lazy as LazyByteString import qualified Data.Text as Text import qualified Data.Text.Lazy as LazyText import qualified Data.IntMap as IntMap import qualified Data.IntSet as IntSet import qualified Data.Map as Map import qualified Data.Sequence as Sequence import qualified Data.Set as Set import qualified Data.Vector as Vector import Data.List.NonEmpty (nonEmpty) import Data.Numbers.Primes (primeFactors) import Numeric.Natural (Natural) import Data.Monoid.Null (MonoidNull(null)) import Prelude hiding (break, drop, dropWhile, foldl, foldr, last, length, map, mapM, mapM_, null, reverse) -- | Class of semigroups that can be split into irreducible (/i.e./, atomic or prime) 'factors' in a unique way. Factors of -- a 'Product' are literally its prime factors: -- -- prop> factors (Product 12) == [Product 2, Product 2, Product 3] -- -- Factors of a list are /not/ its elements but all its single-item sublists: -- -- prop> factors "abc" == ["a", "b", "c"] -- -- The methods of this class satisfy the following laws: -- -- > maybe id sconcat . nonEmpty . factors == id -- > List.all (\prime-> factors prime == [prime]) . factors -- > primePrefix s == foldr const s s -- > foldl f a == List.foldl f a . factors -- > foldl' f a == List.foldl' f a . factors -- > foldr f a == List.foldr f a . factors -- -- A minimal instance definition must implement 'factors' or 'foldr'. Other methods can and should be implemented only -- for performance reasons. class Semigroup m => Factorial m where -- | Returns a list of all prime factors; inverse of mconcat. factors :: m -> [m] -- | The prime prefix; @primePrefix mempty == mempty@ for monoids. primePrefix :: m -> m -- | The prime suffix; @primeSuffix mempty == mempty@ for monoids. primeSuffix :: m -> m -- | Like 'List.foldl' from "Data.List" on the list of prime 'factors'. foldl :: (a -> m -> a) -> a -> m -> a -- | Like 'List.foldl'' from "Data.List" on the list of prime 'factors'. foldl' :: (a -> m -> a) -> a -> m -> a -- | Like 'List.foldr' from "Data.List" on the list of prime 'factors'. foldr :: (m -> a -> a) -> a -> m -> a -- | The 'length' of the list of prime 'factors'. length :: m -> Int -- | Generalizes 'Foldable.foldMap' from "Data.Foldable", except the function arguments are prime 'factors' rather -- than the structure elements. foldMap :: Monoid n => (m -> n) -> m -> n -- | Equivalent to 'List.reverse' from "Data.List". reverse :: m -> m factors = foldr (:) [] primePrefix s = foldr const s s primeSuffix s = foldl (const id) s s foldl f f0 = List.foldl f f0 . factors foldl' f f0 = List.foldl' f f0 . factors foldr f f0 = List.foldr f f0 . factors length = foldl' (const . succ) 0 foldMap f = foldr (mappend . f) mempty reverse s = maybe s sconcat (nonEmpty $ List.reverse $ factors s) {-# MINIMAL factors | foldr #-} -- | A subclass of 'Factorial' whose instances satisfy the following additional laws: -- -- > factors (a <> b) == factors a <> factors b -- > factors . reverse == List.reverse . factors -- > primeSuffix s == primePrefix (reverse s) class Factorial m => StableFactorial m instance Factorial () where factors () = [] primePrefix () = () primeSuffix () = () length () = 0 reverse = id instance Factorial a => Factorial (Dual a) where factors (Dual a) = fmap Dual (reverse $ factors a) length (Dual a) = length a primePrefix (Dual a) = Dual (primeSuffix a) primeSuffix (Dual a) = Dual (primePrefix a) reverse (Dual a) = Dual (reverse a) instance (Integral a, Eq a) => Factorial (Sum a) where primePrefix (Sum a) = Sum (signum a ) primeSuffix = primePrefix factors (Sum n) = replicate (fromIntegral $ abs n) (Sum $ signum n) length (Sum a) = abs (fromIntegral a) reverse = id instance Integral a => Factorial (Product a) where factors (Product a) = List.map Product (primeFactors a) reverse = id instance Factorial a => Factorial (Maybe a) where factors Nothing = [] factors (Just a) = case factors a of [] -> [Just a] as -> List.map Just as length Nothing = 0 length (Just a) = max 1 (length a) reverse = fmap reverse instance (Factorial a, Factorial b, MonoidNull a, MonoidNull b) => Factorial (a, b) where factors (a, b) = List.map (\a1-> (a1, mempty)) (factors a) ++ List.map ((,) mempty) (factors b) primePrefix (a, b) | null a = (a, primePrefix b) | otherwise = (primePrefix a, mempty) primeSuffix (a, b) | null b = (primeSuffix a, b) | otherwise = (mempty, primeSuffix b) foldl f a0 (x, y) = foldl f2 (foldl f1 a0 x) y where f1 a = f a . fromFst f2 a = f a . fromSnd foldl' f a0 (x, y) = a' `seq` foldl' f2 a' y where f1 a = f a . fromFst f2 a = f a . fromSnd a' = foldl' f1 a0 x foldr f a (x, y) = foldr (f . fromFst) (foldr (f . fromSnd) a y) x foldMap f (x, y) = Data.Semigroup.Factorial.foldMap (f . fromFst) x `mappend` Data.Semigroup.Factorial.foldMap (f . fromSnd) y length (a, b) = length a + length b reverse (a, b) = (reverse a, reverse b) {-# INLINE fromFst #-} fromFst :: Monoid b => a -> (a, b) fromFst a = (a, mempty) {-# INLINE fromSnd #-} fromSnd :: Monoid a => b -> (a, b) fromSnd b = (mempty, b) instance (Factorial a, Factorial b, Factorial c, MonoidNull a, MonoidNull b, MonoidNull c) => Factorial (a, b, c) where factors (a, b, c) = List.map (\a1-> (a1, mempty, mempty)) (factors a) ++ List.map (\b1-> (mempty, b1, mempty)) (factors b) ++ List.map (\c1-> (mempty, mempty, c1)) (factors c) primePrefix (a, b, c) | not (null a) = (primePrefix a, mempty, mempty) | not (null b) = (mempty, primePrefix b, mempty) | otherwise = (mempty, mempty, primePrefix c) primeSuffix (a, b, c) | not (null c) = (mempty, mempty, primeSuffix c) | not (null b) = (mempty, primeSuffix b, mempty) | otherwise = (primeSuffix a, mempty, mempty) foldl f s0 (a, b, c) = foldl f3 (foldl f2 (foldl f1 s0 a) b) c where f1 x = f x . fromFstOf3 f2 x = f x . fromSndOf3 f3 x = f x . fromThdOf3 foldl' f s0 (a, b, c) = a' `seq` b' `seq` foldl' f3 b' c where f1 x = f x . fromFstOf3 f2 x = f x . fromSndOf3 f3 x = f x . fromThdOf3 a' = foldl' f1 s0 a b' = foldl' f2 a' b foldr f s (a, b, c) = foldr (f . fromFstOf3) (foldr (f . fromSndOf3) (foldr (f . fromThdOf3) s c) b) a foldMap f (a, b, c) = Data.Semigroup.Factorial.foldMap (f . fromFstOf3) a `mappend` Data.Semigroup.Factorial.foldMap (f . fromSndOf3) b `mappend` Data.Semigroup.Factorial.foldMap (f . fromThdOf3) c length (a, b, c) = length a + length b + length c reverse (a, b, c) = (reverse a, reverse b, reverse c) {-# INLINE fromFstOf3 #-} fromFstOf3 :: (Monoid b, Monoid c) => a -> (a, b, c) fromFstOf3 a = (a, mempty, mempty) {-# INLINE fromSndOf3 #-} fromSndOf3 :: (Monoid a, Monoid c) => b -> (a, b, c) fromSndOf3 b = (mempty, b, mempty) {-# INLINE fromThdOf3 #-} fromThdOf3 :: (Monoid a, Monoid b) => c -> (a, b, c) fromThdOf3 c = (mempty, mempty, c) instance (Factorial a, Factorial b, Factorial c, Factorial d, MonoidNull a, MonoidNull b, MonoidNull c, MonoidNull d) => Factorial (a, b, c, d) where factors (a, b, c, d) = List.map (\a1-> (a1, mempty, mempty, mempty)) (factors a) ++ List.map (\b1-> (mempty, b1, mempty, mempty)) (factors b) ++ List.map (\c1-> (mempty, mempty, c1, mempty)) (factors c) ++ List.map (\d1-> (mempty, mempty, mempty, d1)) (factors d) primePrefix (a, b, c, d) | not (null a) = (primePrefix a, mempty, mempty, mempty) | not (null b) = (mempty, primePrefix b, mempty, mempty) | not (null c) = (mempty, mempty, primePrefix c, mempty) | otherwise = (mempty, mempty, mempty, primePrefix d) primeSuffix (a, b, c, d) | not (null d) = (mempty, mempty, mempty, primeSuffix d) | not (null c) = (mempty, mempty, primeSuffix c, mempty) | not (null b) = (mempty, primeSuffix b, mempty, mempty) | otherwise = (primeSuffix a, mempty, mempty, mempty) foldl f s0 (a, b, c, d) = foldl f4 (foldl f3 (foldl f2 (foldl f1 s0 a) b) c) d where f1 x = f x . fromFstOf4 f2 x = f x . fromSndOf4 f3 x = f x . fromThdOf4 f4 x = f x . fromFthOf4 foldl' f s0 (a, b, c, d) = a' `seq` b' `seq` c' `seq` foldl' f4 c' d where f1 x = f x . fromFstOf4 f2 x = f x . fromSndOf4 f3 x = f x . fromThdOf4 f4 x = f x . fromFthOf4 a' = foldl' f1 s0 a b' = foldl' f2 a' b c' = foldl' f3 b' c foldr f s (a, b, c, d) = foldr (f . fromFstOf4) (foldr (f . fromSndOf4) (foldr (f . fromThdOf4) (foldr (f . fromFthOf4) s d) c) b) a foldMap f (a, b, c, d) = Data.Semigroup.Factorial.foldMap (f . fromFstOf4) a `mappend` Data.Semigroup.Factorial.foldMap (f . fromSndOf4) b `mappend` Data.Semigroup.Factorial.foldMap (f . fromThdOf4) c `mappend` Data.Semigroup.Factorial.foldMap (f . fromFthOf4) d length (a, b, c, d) = length a + length b + length c + length d reverse (a, b, c, d) = (reverse a, reverse b, reverse c, reverse d) {-# INLINE fromFstOf4 #-} fromFstOf4 :: (Monoid b, Monoid c, Monoid d) => a -> (a, b, c, d) fromFstOf4 a = (a, mempty, mempty, mempty) {-# INLINE fromSndOf4 #-} fromSndOf4 :: (Monoid a, Monoid c, Monoid d) => b -> (a, b, c, d) fromSndOf4 b = (mempty, b, mempty, mempty) {-# INLINE fromThdOf4 #-} fromThdOf4 :: (Monoid a, Monoid b, Monoid d) => c -> (a, b, c, d) fromThdOf4 c = (mempty, mempty, c, mempty) {-# INLINE fromFthOf4 #-} fromFthOf4 :: (Monoid a, Monoid b, Monoid c) => d -> (a, b, c, d) fromFthOf4 d = (mempty, mempty, mempty, d) instance Factorial [x] where factors xs = List.map (:[]) xs primePrefix [] = [] primePrefix (x:_) = [x] primeSuffix [] = [] primeSuffix xs = [List.last xs] foldl _ a [] = a foldl f a (x:xs) = foldl f (f a [x]) xs foldl' _ a [] = a foldl' f a (x:xs) = let a' = f a [x] in a' `seq` foldl' f a' xs foldr _ f0 [] = f0 foldr f f0 (x:xs) = f [x] (foldr f f0 xs) length = List.length foldMap f = mconcat . List.map (f . (:[])) reverse = List.reverse instance Factorial ByteString.ByteString where factors x = factorize (ByteString.length x) x where factorize 0 _ = [] factorize n xs = xs1 : factorize (pred n) xs' where (xs1, xs') = ByteString.splitAt 1 xs primePrefix = ByteString.take 1 primeSuffix x = ByteString.drop (ByteString.length x - 1) x foldl f = ByteString.foldl f' where f' a byte = f a (ByteString.singleton byte) foldl' f = ByteString.foldl' f' where f' a byte = f a (ByteString.singleton byte) foldr f = ByteString.foldr (f . ByteString.singleton) length = ByteString.length reverse = ByteString.reverse instance Factorial LazyByteString.ByteString where factors x = factorize (LazyByteString.length x) x where factorize 0 _ = [] factorize n xs = xs1 : factorize (pred n) xs' where (xs1, xs') = LazyByteString.splitAt 1 xs primePrefix = LazyByteString.take 1 primeSuffix x = LazyByteString.drop (LazyByteString.length x - 1) x length = fromIntegral . LazyByteString.length reverse = LazyByteString.reverse instance Factorial Text.Text where factors = Text.chunksOf 1 primePrefix = Text.take 1 primeSuffix x = if Text.null x then Text.empty else Text.singleton (Text.last x) foldl f = Text.foldl f' where f' a char = f a (Text.singleton char) foldl' f = Text.foldl' f' where f' a char = f a (Text.singleton char) foldr f = Text.foldr f' where f' char a = f (Text.singleton char) a length = Text.length reverse = Text.reverse instance Factorial LazyText.Text where factors = LazyText.chunksOf 1 primePrefix = LazyText.take 1 primeSuffix x = if LazyText.null x then LazyText.empty else LazyText.singleton (LazyText.last x) foldl f = LazyText.foldl f' where f' a char = f a (LazyText.singleton char) foldl' f = LazyText.foldl' f' where f' a char = f a (LazyText.singleton char) foldr f = LazyText.foldr f' where f' char a = f (LazyText.singleton char) a length = fromIntegral . LazyText.length reverse = LazyText.reverse instance Ord k => Factorial (Map.Map k v) where factors = List.map (uncurry Map.singleton) . Map.toAscList primePrefix map | Map.null map = map | otherwise = uncurry Map.singleton $ Map.findMin map primeSuffix map | Map.null map = map | otherwise = uncurry Map.singleton $ Map.findMax map foldl f = Map.foldlWithKey f' where f' a k v = f a (Map.singleton k v) foldl' f = Map.foldlWithKey' f' where f' a k v = f a (Map.singleton k v) foldr f = Map.foldrWithKey f' where f' k v a = f (Map.singleton k v) a length = Map.size reverse = id instance Factorial (IntMap.IntMap a) where factors = List.map (uncurry IntMap.singleton) . IntMap.toAscList primePrefix map | IntMap.null map = map | otherwise = uncurry IntMap.singleton $ IntMap.findMin map primeSuffix map | IntMap.null map = map | otherwise = uncurry IntMap.singleton $ IntMap.findMax map foldl f = IntMap.foldlWithKey f' where f' a k v = f a (IntMap.singleton k v) foldl' f = IntMap.foldlWithKey' f' where f' a k v = f a (IntMap.singleton k v) foldr f = IntMap.foldrWithKey f' where f' k v a = f (IntMap.singleton k v) a length = IntMap.size reverse = id instance Factorial IntSet.IntSet where factors = List.map IntSet.singleton . IntSet.toAscList primePrefix set | IntSet.null set = set | otherwise = IntSet.singleton $ IntSet.findMin set primeSuffix set | IntSet.null set = set | otherwise = IntSet.singleton $ IntSet.findMax set foldl f = IntSet.foldl f' where f' a b = f a (IntSet.singleton b) foldl' f = IntSet.foldl' f' where f' a b = f a (IntSet.singleton b) foldr f = IntSet.foldr f' where f' a b = f (IntSet.singleton a) b length = IntSet.size reverse = id instance Factorial (Sequence.Seq a) where factors = List.map Sequence.singleton . Foldable.toList primePrefix = Sequence.take 1 primeSuffix q = Sequence.drop (Sequence.length q - 1) q foldl f = Foldable.foldl f' where f' a b = f a (Sequence.singleton b) foldl' f = Foldable.foldl' f' where f' a b = f a (Sequence.singleton b) foldr f = Foldable.foldr f' where f' a b = f (Sequence.singleton a) b length = Sequence.length reverse = Sequence.reverse instance Ord a => Factorial (Set.Set a) where factors = List.map Set.singleton . Set.toAscList primePrefix set | Set.null set = set | otherwise = Set.singleton $ Set.findMin set primeSuffix set | Set.null set = set | otherwise = Set.singleton $ Set.findMax set foldl f = Foldable.foldl f' where f' a b = f a (Set.singleton b) foldl' f = Foldable.foldl' f' where f' a b = f a (Set.singleton b) foldr f = Foldable.foldr f' where f' a b = f (Set.singleton a) b length = Set.size reverse = id instance Factorial (Vector.Vector a) where factors x = factorize (Vector.length x) x where factorize 0 _ = [] factorize n xs = xs1 : factorize (pred n) xs' where (xs1, xs') = Vector.splitAt 1 xs primePrefix = Vector.take 1 primeSuffix x = Vector.drop (Vector.length x - 1) x foldl f = Vector.foldl f' where f' a byte = f a (Vector.singleton byte) foldl' f = Vector.foldl' f' where f' a byte = f a (Vector.singleton byte) foldr f = Vector.foldr f' where f' byte a = f (Vector.singleton byte) a length = Vector.length reverse = Vector.reverse instance StableFactorial () instance StableFactorial a => StableFactorial (Dual a) instance StableFactorial [x] instance StableFactorial ByteString.ByteString instance StableFactorial LazyByteString.ByteString instance StableFactorial Text.Text instance StableFactorial LazyText.Text instance StableFactorial (Sequence.Seq a) instance StableFactorial (Vector.Vector a) instance StableFactorial (Sum Natural) -- | A 'Monad.mapM' equivalent. mapM :: (Factorial a, Semigroup b, Monoid b, Monad m) => (a -> m b) -> a -> m b mapM f = ($ return mempty) . appEndo . Data.Semigroup.Factorial.foldMap (Endo . Monad.liftM2 mappend . f) -- | A 'Monad.mapM_' equivalent. mapM_ :: (Factorial a, Applicative m) => (a -> m b) -> a -> m () mapM_ f = foldr ((*>) . f) (pure ())
blamario/monoid-subclasses
src/Data/Semigroup/Factorial.hs
bsd-3-clause
17,869
0
14
4,753
6,806
3,544
3,262
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module PeerTrader.Investment.Database where import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Time.Clock (UTCTime, getCurrentTime) import Database.Groundhog import Database.Groundhog.TH import Prosper (InvestResponse (..), InvestMessage (..), InvestStatus (..)) import PeerTrader.StrategyType import PeerTrader.Types (UserLogin) data Investment = Investment { owner :: !UserLogin , timeStamp :: !UTCTime , strategyType :: !StrategyType , investment :: !InvestResponse } deriving Show mkPersist defaultCodegenConfig [groundhog| definitions: - primitive: InvestMessage - primitive: InvestStatus - embedded: InvestResponse - entity: Investment constructors: - name: Investment fields: - name: owner type: text reference: table: snap_auth_user columns: [login] - name: timeStamp type: timestamptz default: now() |] insertResponse :: (PersistBackend m, MonadIO m, Functor m) => UserLogin -> StrategyType -> InvestResponse -> m () insertResponse n t investResp = do now <- liftIO getCurrentTime insert_ $ Investment n now t investResp userResponses :: (PersistBackend m, MonadIO m) => UserLogin -> m [Investment] userResponses n = select $ OwnerField ==. n
WraithM/peertrader-backend
src/PeerTrader/Investment/Database.hs
bsd-3-clause
1,730
0
10
548
273
157
116
42
1
module CppUtils where import Data.List import Control.Monad.State import qualified Data.Set as S import HeaderData import Utils isType :: String -> Bool isType "virtual" = False isType "enum" = False isType "mutable" = False isType "struct" = False isType "union" = False isType "inline" = False isType _ = True combChars :: String -> [String] -> [String] combChars st = map (combChar st) combChar :: String -> String -> String combChar st (x:y:xs) | x == ' ' && y == ' ' = combChar st xs | x == ' ' && y `elem` st = y : combChar st xs | otherwise = x : combChar st (y:xs) combChar _ " " = "" combChar _ l = l -- separate pointer * and ref & from other chars. -- remove keywords such as virtual, static, etc. correctType :: String -> String correctType t = let ns = words t in case ns of [] -> "" ms -> combChar "*&" $ intercalate " " $ filter isType ms isStatic :: String -> Bool isStatic n = take 7 n == "static " isConst :: String -> Bool isConst n = take 6 n == "const " stripStatic :: String -> String stripStatic n | isStatic n = drop 7 n | otherwise = n stripExtra :: String -> String stripExtra = stripConst . stripRef . stripPtr stripChar :: Char -> String -> String stripChar c = stripWhitespace . takeWhile (/= c) -- stripPtr " char * " = "char" stripPtr :: String -> String stripPtr = stripChar '*' stripRef :: String -> String stripRef = stripChar '&' stripConst :: String -> String stripConst n | isConst n = stripWhitespace $ drop 5 n | otherwise = n getAllTypes :: [Object] -> S.Set String getAllTypes = S.fromList . map (stripConst . stripPtr) . concatMap getUsedFunTypes getAllTypesWithPtr :: [Object] -> S.Set String getAllTypesWithPtr = S.fromList . map (correctType . stripConst) . concatMap getUsedFunTypes -- "aaa < bbb, ddd> fff" = " bbb, ddd" betweenAngBrackets :: String -> String betweenAngBrackets = fst . foldr go ("", Nothing) where go _ (accs, Just True) = (accs, Just True) -- done go '>' (accs, Nothing) = (accs, Just False) -- start go '<' (accs, Just False) = (accs, Just True) -- finish go c (accs, Just False) = (c:accs, Just False) -- collect go _ (accs, Nothing) = (accs, Nothing) -- continue isTemplate :: String -> Bool isTemplate = not . null . betweenAngBrackets isPtr :: String -> Int isPtr = length . filter (=='*') . dropWhile (/= '*') isStdType "float" = True isStdType "double" = True isStdType "char" = True isStdType "int" = True isStdType "unsigned int" = True isStdType "signed int" = True isStdType "long" = True isStdType "unsigned long" = True isStdType "signed long" = True isStdType "bool" = True isStdType "short" = True isStdType "unsigned short" = True isStdType "signed short" = True isStdType "unsigned" = True isStdType "long long" = True isStdType "unsigned long long" = True isStdType "int8_t" = True isStdType "uint8_t" = True isStdType "int16_t" = True isStdType "uint16_t" = True isStdType "int32_t" = True isStdType "uint32_t" = True isStdType "int64_t" = True isStdType "uint64_t" = True isStdType "size_t" = True isStdType "uint8" = True isStdType "uint16" = True isStdType "uint32" = True isStdType "uint64" = True isStdType _ = False getEnumValues :: [EnumVal] -> [(String, Int)] getEnumValues es = evalState go 0 where go :: State Int [(String, Int)] go = mapM f es f :: EnumVal -> State Int (String, Int) f (EnumVal en ev) = do oldval <- get let thisval = case ev of Nothing -> oldval Just m -> case reads m of [(v, _)] -> v _ -> oldval put $ thisval + 1 return (en, thisval) enumReadable :: [EnumVal] -> Bool enumReadable = all valid . map enumvalue where valid Nothing = True valid (Just n) = case (reads :: String -> [(Int, String)]) n of [(_, [])] -> True _ -> False publicClass :: Object -> Bool publicClass (ClassDecl _ _ nest _ _) = all (== Public) $ map fst nest publicClass _ = False abstractClass :: Object -> Bool abstractClass (ClassDecl _ _ _ _ objs) = any isAbstractFun (map snd objs) abstractClass _ = False removeNamespace :: String -> String removeNamespace = map (\c -> if c == ':' then '_' else c) stripNamespace :: String -> String stripNamespace = last . takeWhile (not . null) . iterate (dropWhile (==':') . snd . break (== ':')) fixNamespace :: [String] -> String -> String fixNamespace enums n = (if (stripNamespace n) `elem` enums then stripNamespace else removeNamespace) n
anttisalonen/cgen
src/CppUtils.hs
bsd-3-clause
4,770
0
19
1,267
1,662
866
796
126
5
module Day21 where import Control.Monad import Data.Maybe import Safe type HitPoints = Int type Damage = Int type Armor = Int type Gold = Int data Attacker = Attacker HitPoints Damage Armor data Item = Item String Gold Damage Armor data Battle = Battle Role Attacker Attacker data Role = Player | Boss deriving (Eq) mostExpensiveLoss :: Attacker -> Gold mostExpensiveLoss = maximum . map fst . filter ((== Boss) . snd) . allOutcomes cheapestWin :: Attacker -> Gold cheapestWin = minimum . map fst . filter ((== Player) . snd) . allOutcomes allOutcomes :: Attacker -> [(Gold, Role)] allOutcomes b = (outcome <$>) <$> players where outcome = simulateBattle . Battle Player b players = createPlayer 100 <$> itemSets simulateBattle :: Battle -> Role simulateBattle b@(Battle _ (Attacker bhp _ _) (Attacker php _ _)) | php <= 0 = Boss | bhp <= 0 = Player | otherwise = simulateBattle $ advanceBattle b advanceBattle :: Battle -> Battle advanceBattle = \case Battle Player (Attacker hp bd a) p@(Attacker _ d _) -> Battle Boss (Attacker (hp - d + a) bd a) p Battle Boss b@(Attacker _ d _) (Attacker php pd pa) -> Battle Player b (Attacker (php - d + pa) pd pa) createPlayer :: HitPoints -> [Item] -> (Gold, Attacker) createPlayer h = foldr equipItem (0, Attacker h 0 0) where equipItem (Item _ g d a) (cost, Attacker hp pd pa) = (cost + g, Attacker hp (pd + d) (pa + a)) itemSets :: [[Item]] itemSets = do w <- weapons rs <- subsetsOfMaxSize 2 rings as <- subsetsOfMaxSize 1 armor return $ [w] ++ rs ++ as subsetsOfMaxSize :: Int -> [a] -> [[a]] subsetsOfMaxSize n = filter ((<=n) . length) . filterM (const [True, False]) parseAttacker :: String -> Attacker parseAttacker s = Attacker hp d a where [hp, d, a] = catMaybes $ readMay <$> words s weapons :: [Item] weapons = [ Item "Dagger" 8 4 0 , Item "Shortsword" 10 5 0 , Item "Warhammer" 25 6 0 , Item "Longsword" 40 7 0 , Item "Greataxe" 74 8 0 ] armor :: [Item] armor = [ Item "Leather" 13 0 1 , Item "Chainmail" 31 0 2 , Item "Splintmail" 53 0 3 , Item "Bandedmail" 75 0 4 , Item "Platemail" 102 0 5 ] rings :: [Item] rings = [ Item "Damage +1" 25 1 0 , Item "Damage +2" 50 2 0 , Item "Damage +3" 100 3 0 , Item "Defense +1" 20 0 1 , Item "Defense +2" 40 0 2 , Item "Defense +3" 80 0 3 ]
patrickherrmann/advent
src/Day21.hs
bsd-3-clause
2,359
0
13
560
1,007
531
476
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Views where import Prelude hiding (head, div, id) import Text.Blaze.Html5 hiding (map, details) import Text.Blaze.Html5.Attributes hiding (name, title) import Data.String (fromString) import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import Data.Text.Format import Data.Text.Format.Params (Params) import Control.Monad (forM_) import Data.Monoid ((<>)) import Models -- Text.Format.format but producing Blaze HTML instead formatHtml :: Params ps => Format -> ps -> Html formatHtml fmt = toHtml . format fmt formatAttr :: Params ps => Format -> ps -> AttributeValue formatAttr fmt = fromString . T.unpack . format fmt -- A useful class for quickly converting data to HTML class Displayable a where display :: a -> Html instance Displayable Text where display = toHtml instance Displayable Integer where display = formatHtml "{}" . Only instance Displayable Int where display = formatHtml "{}" . Only instance Displayable Double where display = formatHtml "{}" . Only . fixed 2 instance Displayable Playtime where display pt | h > 0 = formatHtml "{} hours" (Only (fixed 1 hf)) | otherwise = formatHtml "{}:{}" (m, left 2 '0' s) where s = fromPlaytime pt `mod` 60 m = (fromPlaytime pt `quot` 60) `mod` 60 h = (fromPlaytime pt `quot` 3600) hf = fromInteger (fromPlaytime pt) / 3600 :: Double maybeDisplay :: Displayable a => Maybe a -> Html maybeDisplay (Just x) = display x maybeDisplay Nothing = display ("--" :: Text) scoreboard :: [Player] -> Html scoreboard players = do tr $ mapM_ th ["Player", "Efficacy", "Kills", "Deaths", "KDR", "Time played"] forM_ players $ \player -> tr $ do let playerUrl = formatAttr "/player/{}" (Only (name player)) td $ a ! href playerUrl $ display (name player) td $ display (efficacy player) td $ display (killCount player) td $ display (deathCount player) td $ display (kdr player) td $ display (playtime player) playerView :: Player -> Html playerView player = do h2 $ formatHtml "Player {}" (Only (name player)) table $ do tr $ th "Efficacy: " >> td (display (efficacy player)) tr $ th "Kills: " >> td (display (killCount player)) tr $ th "Headshots: " >> td (maybeDisplay (fmap hsCount (details player))) tr $ th "Melee kills: " >> td (maybeDisplay (fmap meleeKills (details player))) tr $ th "Deaths: " >> td (display (deathCount player)) tr $ th "KDR: " >> td (display (kdr player)) tr $ th "Time played: " >> td (display (playtime player)) tr $ th "Favourite weapon: " >> td (maybeDisplay (fmap favWeapon (details player))) playerListView :: [Player] -> Html playerListView players = do h2 "Top 10 players" table $ scoreboard players roundView :: Round -> Html roundView round = do h2 $ formatHtml "Round {} on {} ({} players)" (round_id round, mapName round, length (players round)) table $ scoreboard (players round) roundListView :: [Round] -> Html roundListView rounds = do h2 "Last 10 rounds played" table $ do tr $ mapM_ th ["Round #", "Map", "Players"] forM_ rounds $ \round -> tr $ do let roundUrl = formatAttr "/round/{}" (Only (round_id round)) td $ a ! href roundUrl $ display (round_id round) td $ display (mapName round) td $ display (length (players round)) errorView :: Text -> Html errorView err = docTypeHtml $ do p $ toHtml (format "Error: {}" (Only err)) site :: Html -> Html site contents = docTypeHtml $ do head $ do title "cod2stats" link ! rel "stylesheet" ! href "/css" meta ! httpEquiv "Content-Type" ! content "text/html; charset=utf-8" body $ do header $ do h1 $ a ! href "/" $ "cod2stats" nav $ do ul $ do li $ a ! href "/players" $ "Players" li $ a ! href "/rounds" $ "Rounds" div ! id "main" $ contents footer $ p $ do "2014 © kqr, " a ! href "https://github.com/kqr/cod2stats" ! target "_BLANK" $ "source"
kqr/cod2stats
Views.hs
bsd-3-clause
4,392
0
22
1,284
1,521
746
775
94
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module Database.Curry.Storage ( saveThread, createNotifyer, saveToFile, loadFromFile, ) where import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.Async import Control.Concurrent.STM import qualified Control.Exception as E import Control.Lens import Control.Monad.Logger import Control.Monad.State.Strict import Data.Binary import Data.Monoid import qualified Data.Text as T import Data.Time import Database.Curry.HashMap as HM import Database.Curry.Types saveThread :: (Functor m, MonadIO m, Binary v) => TVar Bool -> STM () -> DBMT v m () saveThread saveReq reset = forever $ do liftIO $ atomically $ do req <- readTVar saveReq when (not req) retry writeTVar saveReq False reset saveToFile createNotifyer :: [SaveStrategy] -> IO (STM (), STM (), TVar Bool) createNotifyer strats = do timer <- createTimer saveReq <- newTVarIO False let notify (SaveByFrequency {..})= do upd <- newTVarIO 0 _ <- forkIO $ forever $ do start <- readTVarIO timer atomically $ do cur <- readTVar timer when (cur `diffUTCTime` start < fromIntegral freqSecond) retry num <- readTVar upd writeTVar upd 0 when (num >= freqUpdates) $ writeTVar saveReq True return upd upds <- mapM notify strats let upd = mapM_ (\tv -> modifyTVar' tv (+1)) upds reset = mapM_ (\tv -> writeTVar tv 0) upds return (upd, reset, saveReq) createTimer :: IO (TVar UTCTime) createTimer = do curV <- newTVarIO =<< getCurrentTime _ <- async $ forever $ do threadDelay $ 10 ^ (6 :: Int) time <- getCurrentTime atomically $ writeTVar curV time return curV saveToFile :: (MonadIO m, Binary v) => DBMT v m () saveToFile = do Config {..} <- use dbmConfig case configPath of Nothing -> return () Just path -> do $logInfo "save to file..." err <- liftIO . E.try . HM.save path =<< use dbmTable case err of Right _ -> return () Left ioerr -> $logError $ "save error: " <> (T.pack $ show $ (ioerr :: IOError)) loadFromFile :: (MonadIO m, Binary v) => DBMT v m () loadFromFile = do Config {..} <- use dbmConfig case configPath of Nothing -> return () Just path -> do $logInfo "load from file..." tbl <- use dbmTable res <- liftIO . E.try . HM.load path =<< use dbmTable case res of Right () -> return () Left err -> do $logInfo $ "fail to load " <> ": " <> (T.pack $ show (err :: E.SomeException))
tanakh/CurryDB
Database/Curry/Storage.hs
bsd-3-clause
2,837
0
22
864
962
472
490
83
3
{-# LANGUAGE RecordWildCards #-} -- | Main Toss logic. module Pos.Chain.Ssc.Toss.Logic ( verifyAndApplySscPayload , applyGenesisBlock , rollbackSsc , normalizeToss , refreshToss ) where import Universum hiding (id) import Control.Lens (at) import Control.Monad.Except (MonadError, runExceptT, throwError) import Crypto.Random (MonadRandom) import qualified Data.HashMap.Strict as HM import Pos.Chain.Block.IsHeader (IsMainHeader, headerSlotL) import Pos.Chain.Genesis as Genesis (Config (..), configSlotSecurityParam) import Pos.Chain.Ssc.Commitment (SignedCommitment) import Pos.Chain.Ssc.CommitmentsMap (CommitmentsMap (..), getCommitmentsMap, mkCommitmentsMapUnsafe) import Pos.Chain.Ssc.Error (SscVerifyError (..)) import Pos.Chain.Ssc.Functions (verifySscPayload) import Pos.Chain.Ssc.Opening (Opening) import Pos.Chain.Ssc.Payload (SscPayload (..), checkSscPayload, spVss) import Pos.Chain.Ssc.SharesMap (InnerSharesMap) import Pos.Chain.Ssc.Toss.Base (checkPayload) import Pos.Chain.Ssc.Toss.Class (MonadToss (..), MonadTossEnv (..)) import Pos.Chain.Ssc.Toss.Types (TossModifier (..)) import Pos.Chain.Ssc.VssCertificate (VssCertificate) import Pos.Chain.Ssc.VssCertificatesMap (getVssCertificatesMap, mkVssCertificatesMapSingleton) import Pos.Core (EpochIndex, EpochOrSlot (..), LocalSlotIndex, SlotCount, SlotId (siSlot), StakeholderId, epochIndexL, epochOrSlot, epochOrSlotPred, epochOrSlotToEnum, getEpochOrSlot, getSlotIndex, mkCoin) import Pos.Core.Chrono (NewestFirst (..)) import Pos.Util.AssertMode (inAssertMode) import Pos.Util.Some (Some) import Pos.Util.Util (sortWithMDesc) import Pos.Util.Wlog (logError) -- | Verify 'SscPayload' with respect to data provided by -- MonadToss. If data is valid it is also applied. Otherwise -- SscVerifyError is thrown using 'MonadError' type class. verifyAndApplySscPayload :: ( MonadToss m , MonadTossEnv m , MonadError SscVerifyError m , MonadRandom m ) => Genesis.Config -> Either EpochIndex (Some IsMainHeader) -> SscPayload -> m () verifyAndApplySscPayload genesisConfig eoh payload = do -- Check the payload for internal consistency. either (throwError . SscInvalidPayload) pure (checkSscPayload (configProtocolMagic genesisConfig) payload) -- We can't trust payload from mempool, so we must call -- @verifySscPayload@. whenLeft eoh $ const $ verifySscPayload genesisConfig eoh payload -- We perform @verifySscPayload@ for block when we construct it -- (in the 'recreateGenericBlock'). So this check is just in case. -- NOTE: in block verification `verifySscPayload` on `MainBlock` is run -- by `Pos.Block.BHelper.verifyMainBlock` inAssertMode $ whenRight eoh $ const $ verifySscPayload genesisConfig eoh payload let blockCerts = spVss payload let curEpoch = either identity (^. epochIndexL) eoh checkPayload genesisConfig curEpoch payload -- Apply case eoh of Left _ -> pass Right header -> do let eos = EpochOrSlot $ Right $ header ^. headerSlotL setEpochOrSlot eos -- We can freely clear shares after 'slotSecurityParam' because -- it's guaranteed that rollback on more than 'slotSecurityParam' -- can't happen let indexToCount :: LocalSlotIndex -> SlotCount indexToCount = fromIntegral . getSlotIndex let slot = epochOrSlot (const 0) (indexToCount . siSlot) eos slotSecurityParam = configSlotSecurityParam genesisConfig when (slotSecurityParam <= slot && slot < 2 * slotSecurityParam) $ resetShares mapM_ putCertificate blockCerts case payload of CommitmentsPayload comms _ -> mapM_ putCommitment $ toList $ getCommitmentsMap comms OpeningsPayload opens _ -> mapM_ (uncurry putOpening) $ HM.toList opens SharesPayload shares _ -> mapM_ (uncurry putShares) $ HM.toList shares CertificatesPayload _ -> pass -- | Apply genesis block for given epoch to 'Toss' state. applyGenesisBlock :: MonadToss m => EpochIndex -> m () applyGenesisBlock epoch = do setEpochOrSlot $ getEpochOrSlot epoch -- We don't clear shares on genesis block because -- there aren't 'slotSecurityParam' slots after shares phase, -- so we won't have shares after rollback -- We store shares until 'slotSecurityParam' slots of next epoch passed -- and clear their after that resetCO -- | Rollback application of 'SscPayload's in 'Toss'. First argument is -- 'EpochOrSlot' of oldest block which is subject to rollback. rollbackSsc :: MonadToss m => SlotCount -> EpochOrSlot -> NewestFirst [] SscPayload -> m () rollbackSsc epochSlots oldestEOS (NewestFirst payloads) | oldestEOS == epochOrSlotToEnum epochSlots 0 = do logError "rollbackSsc: most genesis block is passed to rollback" setEpochOrSlot oldestEOS resetCO resetShares | otherwise = do setEpochOrSlot (epochOrSlotPred epochSlots oldestEOS) mapM_ rollbackSscDo payloads where rollbackSscDo (CommitmentsPayload comms _) = mapM_ delCommitment $ HM.keys $ getCommitmentsMap comms rollbackSscDo (OpeningsPayload opens _) = mapM_ delOpening $ HM.keys opens rollbackSscDo (SharesPayload shares _) = mapM_ delShares $ HM.keys shares rollbackSscDo (CertificatesPayload _) = pass -- | Apply as much data from given 'TossModifier' as possible. normalizeToss :: (MonadToss m, MonadTossEnv m, MonadRandom m) => Genesis.Config -> EpochIndex -> TossModifier -> m () normalizeToss genesisConfig epoch TossModifier {..} = normalizeTossDo genesisConfig epoch ( HM.toList (getCommitmentsMap _tmCommitments) , HM.toList _tmOpenings , HM.toList _tmShares , HM.toList (getVssCertificatesMap _tmCertificates)) -- | Apply the most valuable from given 'TossModifier' and drop the -- rest. This function can be used if mempool is exhausted. refreshToss :: (MonadToss m, MonadTossEnv m, MonadRandom m) => Genesis.Config -> EpochIndex -> TossModifier -> m () refreshToss genesisConfig epoch TossModifier {..} = do comms <- takeMostValuable epoch (HM.toList (getCommitmentsMap _tmCommitments)) opens <- takeMostValuable epoch (HM.toList _tmOpenings) shares <- takeMostValuable epoch (HM.toList _tmShares) certs <- takeMostValuable epoch (HM.toList (getVssCertificatesMap _tmCertificates)) normalizeTossDo genesisConfig epoch (comms, opens, shares, certs) takeMostValuable :: (MonadToss m, MonadTossEnv m) => EpochIndex -> [(StakeholderId, x)] -> m [(StakeholderId, x)] takeMostValuable epoch items = take toTake <$> sortWithMDesc resolver items where toTake = 2 * length items `div` 3 resolver (id, _) = fromMaybe (mkCoin 0) . (view (at id)) . fromMaybe mempty <$> getRichmen epoch type TossModifierLists = ( [(StakeholderId, SignedCommitment)] , [(StakeholderId, Opening)] , [(StakeholderId, InnerSharesMap)] , [(StakeholderId, VssCertificate)]) normalizeTossDo :: forall m . (MonadToss m, MonadTossEnv m, MonadRandom m) => Genesis.Config -> EpochIndex -> TossModifierLists -> m () normalizeTossDo genesisConfig epoch (comms, opens, shares, certs) = do putsUseful $ map (flip CommitmentsPayload mempty . mkCommitmentsMapUnsafe . one) $ comms putsUseful $ map (flip OpeningsPayload mempty . one) opens putsUseful $ map (flip SharesPayload mempty . one) shares putsUseful $ map (CertificatesPayload . mkVssCertificatesMapSingleton . snd) certs where putsUseful :: [SscPayload] -> m () putsUseful entries = do let verifyAndApply = runExceptT . verifyAndApplySscPayload genesisConfig (Left epoch) mapM_ verifyAndApply entries
input-output-hk/pos-haskell-prototype
chain/src/Pos/Chain/Ssc/Toss/Logic.hs
mit
8,489
0
18
2,196
1,874
1,001
873
-1
-1
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} module Carnap.Languages.ModalPropositional.Parser (modalPropFormulaParser,worldTheoryPropFormulaParser, absoluteModalPropFormulaParser, relativeModalPropFormulaParser, absoluteModalPropFormulaPreParser) where import Carnap.Core.Data.Types (Term, Form, FixLang) import Carnap.Languages.ModalPropositional.Syntax import Carnap.Languages.Util.LanguageClasses (PrismBooleanConnLex, PrismModality, BooleanLanguage, BooleanConstLanguage, ModalLanguage, IndexedPropLanguage, IndexingLang(..), IndexConsLang(..), IndexedSchemePropLanguage) import Carnap.Languages.ClassicalSequent.Parser import Carnap.Languages.Util.GenericParsers import Text.Parsec import Text.Parsec.Expr import Control.Monad.Identity (Identity) import Carnap.Core.Unification.Unification data ModalPropositionalParserOptions lex u m = ModalPropositionalParserOptions { atomicSentenceParser :: ParsecT String u m (FixLang lex (Form (World -> Bool))) , quantifiedSentenceParser' :: Maybe (ParsecT String u m (FixLang lex (Term World)) -> ParsecT String u m (FixLang lex (Form (World -> Bool))) -> ParsecT String u m (FixLang lex (Form (World -> Bool)))) , freeVarParser :: Maybe (ParsecT String u m (FixLang lex (Term World))) , hasBooleanConstants :: Bool } --subformulas are either coreSubformulaParser :: ( BooleanLanguage (FixLang lex (Form (World -> Bool))) , BooleanConstLanguage (FixLang lex (Form (World -> Bool))) , ModalLanguage (FixLang lex (Form (World -> Bool))) , IndexedPropLanguage (FixLang lex (Form (World -> Bool))) , IndexedSchemePropLanguage (FixLang lex (Form (World -> Bool)))) => Parsec String u (FixLang lex (Form (World -> Bool))) -> ModalPropositionalParserOptions lex u Identity -> Parsec String u (FixLang lex (Form (World -> Bool))) coreSubformulaParser fp opts = --formulas wrapped in parentheses (parenParser fp <* spaces) --negations of subformulas <|> unaryOpParser [parseNeg, parsePos, parseNec] (coreSubformulaParser fp opts <* spaces) -- maybe quantified sentences <|> case (quantifiedSentenceParser' opts,freeVarParser opts) of (Just qparse, Just vparse) -> try $ qparse vparse (coreSubformulaParser fp opts) _ -> parserZero --or atoms <|> try (sentenceLetterParser "PQRSTUVW" <* spaces) <|> if hasBooleanConstants opts then try (booleanConstParser <* spaces) else parserZero <|> (schemevarParser <* spaces) simpleModalOptions :: ( BooleanLanguage (FixLang lex (Form (World -> Bool))) , BooleanConstLanguage (FixLang lex (Form (World -> Bool))) , ModalLanguage (FixLang lex (Form (World -> Bool))) , IndexedPropLanguage (FixLang lex (Form (World -> Bool))) , IndexedSchemePropLanguage (FixLang lex (Form (World -> Bool)))) => ModalPropositionalParserOptions lex u Identity simpleModalOptions = ModalPropositionalParserOptions { atomicSentenceParser = sentenceLetterParser "PQRSTUVW" , quantifiedSentenceParser' = Nothing , freeVarParser = Nothing , hasBooleanConstants = False } modalPropFormulaParser :: Parsec String u ModalForm modalPropFormulaParser = buildExpressionParser opTable subFormulaParser where subFormulaParser = coreSubformulaParser modalPropFormulaParser simpleModalOptions absoluteModalPropFormulaParser :: Parsec String u AbsoluteModalForm absoluteModalPropFormulaParser = absoluteModalPropFormulaPreParser >>= indexIt where indexIt :: AbsoluteModalPreForm -> Parsec String u AbsoluteModalForm indexIt f = do char '/' w <- parseWorld return (f `atWorld` w) relativeModalPropFormulaParser :: Parsec String u AbsoluteModalForm relativeModalPropFormulaParser = absoluteModalPropFormulaPreParser >>= indexIt where indexIt :: AbsoluteModalPreForm -> Parsec String u AbsoluteModalForm indexIt f = do char '/' (w:ws)<- sepBy1 parseWorld (char '-') let idx = foldl indexcons w ws return (f `atWorld` idx) absoluteModalPropFormulaPreParser :: Parsec String u AbsoluteModalPreForm absoluteModalPropFormulaPreParser = formulaParser where formulaParser = buildExpressionParser opTable subFormulaParser subFormulaParser = coreSubformulaParser formulaParser simpleModalOptions{hasBooleanConstants = True} instance ParsableLex (Form Bool) AbsoluteModalPropLexicon where langParser = absoluteModalPropFormulaParser instance ParsableLex (Form (World -> Bool)) AbsoluteModalPropLexicon where langParser = absoluteModalPropFormulaPreParser worldTheoryOptions :: ModalPropositionalParserOptions WorldTheoryPropLexicon u Identity worldTheoryOptions = simpleModalOptions { quantifiedSentenceParser' = Just quantifiedSentenceParser , freeVarParser = Just (parseWorldVar "ijklmn") , hasBooleanConstants = True } worldTheoryPropFormulaParser :: Parsec String u WorldTheoryForm worldTheoryPropFormulaParser = buildExpressionParser (worldTheoryOpTable worldTheoryOptions) subFormulaParser where subFormulaParser = coreSubformulaParser worldTheoryPropFormulaParser worldTheoryOptions instance ParsableLex (Form (World -> Bool)) WorldTheoryPropLexicon where langParser = worldTheoryPropFormulaParser opTable :: ( PrismBooleanConnLex (ModalPropLexiconWith a) (World -> Bool), Monad m , PrismModality (ModalPropLexiconWith a) (World -> Bool) ) => [[Operator String u m (ModalPropLanguageWith a (Form (World -> Bool)))]] opTable = [ [Prefix (try parseNeg), Prefix (try parseNec), Prefix (try parsePos)] , [ Infix (try parseOr) AssocLeft, Infix (try parseAnd) AssocLeft] , [ Infix (try parseIf) AssocNone, Infix (try parseIff) AssocNone] ] worldTheoryOpTable :: Monad m => ModalPropositionalParserOptions WorldTheoryPropLexicon u m -> [[Operator String u m WorldTheoryForm]] worldTheoryOpTable opts = [ [Prefix (try parseNeg), Prefix (try parseNec), Prefix (try parsePos)] , [Infix (try parseOr) AssocLeft, Infix (try parseAnd) AssocLeft] , [Infix (try parseIf) AssocNone, Infix (try parseIff) AssocNone] , [Postfix (try $ parseWorldIndexer opts)] ] parseWorldIndexer :: Monad m => ModalPropositionalParserOptions WorldTheoryPropLexicon u m -> ParsecT String u m (WorldTheoryForm -> WorldTheoryForm) parseWorldIndexer opts = do char '/' term <- parseWorld <|> vparse return (\x -> x `atWorld` term) where vparse = case freeVarParser opts of Just vp -> vp _ -> parserZero parseWorldVar :: Monad m => String -> ParsecT String u m (WorldTheoryPropLanguage (Term World)) parseWorldVar s = choice [try $ do _ <- string "i_" dig <- many1 digit return $ worldVar $ "i_" ++ dig , do c <- oneOf s return $ worldVar [c] ] parseWorld :: (IndexingLang lex (Term World) (Form c) (Form b), Monad m) => ParsecT String u m (FixLang lex (Term World)) parseWorld = do digits <- many1 digit return $ world (read digits)
opentower/carnap
Carnap/src/Carnap/Languages/ModalPropositional/Parser.hs
gpl-3.0
8,349
0
19
2,545
2,019
1,058
961
117
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.ECS.DescribeContainerInstances -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Describes Amazon EC2 Container Service container instances. Returns -- metadata about registered and remaining resources on each container -- instance requested. -- -- /See:/ <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeContainerInstances.html AWS API Reference> for DescribeContainerInstances. module Network.AWS.ECS.DescribeContainerInstances ( -- * Creating a Request describeContainerInstances , DescribeContainerInstances -- * Request Lenses , dciCluster , dciContainerInstances -- * Destructuring the Response , describeContainerInstancesResponse , DescribeContainerInstancesResponse -- * Response Lenses , dcisrsFailures , dcisrsContainerInstances , dcisrsResponseStatus ) where import Network.AWS.ECS.Types import Network.AWS.ECS.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'describeContainerInstances' smart constructor. data DescribeContainerInstances = DescribeContainerInstances' { _dciCluster :: !(Maybe Text) , _dciContainerInstances :: ![Text] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeContainerInstances' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dciCluster' -- -- * 'dciContainerInstances' describeContainerInstances :: DescribeContainerInstances describeContainerInstances = DescribeContainerInstances' { _dciCluster = Nothing , _dciContainerInstances = mempty } -- | The short name or full Amazon Resource Name (ARN) of the cluster that -- hosts the container instances you want to describe. If you do not -- specify a cluster, the default cluster is assumed. dciCluster :: Lens' DescribeContainerInstances (Maybe Text) dciCluster = lens _dciCluster (\ s a -> s{_dciCluster = a}); -- | A space-separated list of container instance UUIDs or full Amazon -- Resource Name (ARN) entries. dciContainerInstances :: Lens' DescribeContainerInstances [Text] dciContainerInstances = lens _dciContainerInstances (\ s a -> s{_dciContainerInstances = a}) . _Coerce; instance AWSRequest DescribeContainerInstances where type Rs DescribeContainerInstances = DescribeContainerInstancesResponse request = postJSON eCS response = receiveJSON (\ s h x -> DescribeContainerInstancesResponse' <$> (x .?> "failures" .!@ mempty) <*> (x .?> "containerInstances" .!@ mempty) <*> (pure (fromEnum s))) instance ToHeaders DescribeContainerInstances where toHeaders = const (mconcat ["X-Amz-Target" =# ("AmazonEC2ContainerServiceV20141113.DescribeContainerInstances" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON DescribeContainerInstances where toJSON DescribeContainerInstances'{..} = object (catMaybes [("cluster" .=) <$> _dciCluster, Just ("containerInstances" .= _dciContainerInstances)]) instance ToPath DescribeContainerInstances where toPath = const "/" instance ToQuery DescribeContainerInstances where toQuery = const mempty -- | /See:/ 'describeContainerInstancesResponse' smart constructor. data DescribeContainerInstancesResponse = DescribeContainerInstancesResponse' { _dcisrsFailures :: !(Maybe [Failure]) , _dcisrsContainerInstances :: !(Maybe [ContainerInstance]) , _dcisrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DescribeContainerInstancesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcisrsFailures' -- -- * 'dcisrsContainerInstances' -- -- * 'dcisrsResponseStatus' describeContainerInstancesResponse :: Int -- ^ 'dcisrsResponseStatus' -> DescribeContainerInstancesResponse describeContainerInstancesResponse pResponseStatus_ = DescribeContainerInstancesResponse' { _dcisrsFailures = Nothing , _dcisrsContainerInstances = Nothing , _dcisrsResponseStatus = pResponseStatus_ } -- | Undocumented member. dcisrsFailures :: Lens' DescribeContainerInstancesResponse [Failure] dcisrsFailures = lens _dcisrsFailures (\ s a -> s{_dcisrsFailures = a}) . _Default . _Coerce; -- | The list of container instances. dcisrsContainerInstances :: Lens' DescribeContainerInstancesResponse [ContainerInstance] dcisrsContainerInstances = lens _dcisrsContainerInstances (\ s a -> s{_dcisrsContainerInstances = a}) . _Default . _Coerce; -- | The response status code. dcisrsResponseStatus :: Lens' DescribeContainerInstancesResponse Int dcisrsResponseStatus = lens _dcisrsResponseStatus (\ s a -> s{_dcisrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ecs/gen/Network/AWS/ECS/DescribeContainerInstances.hs
mpl-2.0
5,824
0
14
1,216
774
460
314
98
1
{-# LANGUAGE QuasiQuotes, OverloadedStrings, TemplateHaskell #-} {-# LANGUAGE CPP #-} module Handler.Admin ( postAdminR , postUnadminR , postRealR , postUnrealR , postRealPicR , postUnrealPicR , postBlockR , postUnblockR , getMessagesR , postCloseMessageR , getAdminUsersR , requireAdmin ) where import Import import Control.Monad (unless) import Handler.User (adminControls) -- FIXME includes style too many times import Handler.Root (gravatar) import Yesod.Form.Jquery (urlJqueryJs) requireAdmin :: Handler () requireAdmin = do Entity _ admin <- requireAuth unless (userAdmin admin) $ permissionDenied "You are not an admin" adminHelper :: EntityField User Bool -> Bool -> Html -> UserId -> Handler () adminHelper constr bool msg uid = do requireAdmin u <- runDB $ get404 uid runDB $ update uid [constr =. bool] setMessage msg redirect $ userR ((uid, u), Nothing) postAdminR :: UserId -> Handler () postAdminR = adminHelper UserAdmin True "User is now an admin" postUnadminR :: UserId -> Handler () postUnadminR = adminHelper UserAdmin False "User is no longer an admin" postRealR :: UserId -> Handler () postRealR = adminHelper UserReal True "User now has verified user status" postUnrealR :: UserId -> Handler () postUnrealR = adminHelper UserReal False "User no longer has verified user status" postRealPicR :: UserId -> Handler () postRealPicR = adminHelper UserRealPic True "User now has real picture status" postUnrealPicR :: UserId -> Handler () postUnrealPicR = adminHelper UserRealPic False "User no longer has real picture status" postBlockR :: UserId -> Handler () postBlockR = adminHelper UserBlocked True "User has been blocked" postUnblockR :: UserId -> Handler () postUnblockR = adminHelper UserBlocked False "User has been unblocked" getMessagesR :: Handler RepHtml getMessagesR = do requireAdmin messages <- runDB $ selectList [MessageClosed ==. False] [Asc MessageWhen] >>= mapM (\(Entity mid m) -> do let go uid = do u <- get404 uid return $ Just (uid, u) from <- maybe (return Nothing) go $ messageFrom m regarding <- maybe (return Nothing) go $ messageRegarding m return ((mid, m), (from, regarding)) ) defaultLayout $ do setTitle "Admin Messages" $(widgetFile "messages") postCloseMessageR :: MessageId -> Handler () postCloseMessageR mid = do requireAdmin runDB $ update mid [MessageClosed =. True] setMessage "Message has been closed" redirect MessagesR getAdminUsersR :: Handler RepHtml getAdminUsersR = do users <- runDB $ selectList [UserVerifiedEmail ==. True] [Asc UserFullName] y <- getYesod defaultLayout $ do setTitle "Admin list of users" addScriptEither $ urlJqueryJs y $(widgetFile "admin-users")
danse/haskellers
tests/Handler/Admin.hs
bsd-2-clause
2,880
0
21
633
795
394
401
74
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleContexts #-} module Arbitrary ( InversibleGeotransform(..) , positivePair , (~==) ) where import Control.Applicative ((<$>), (<*>), pure) import Data.Fixed (Fixed, E3) import Test.QuickCheck hiding (Fixed) import GDAL (Pair(..), Geotransform(Geotransform)) import OGR (Envelope(Envelope)) instance Arbitrary a => Arbitrary (Pair a) where arbitrary = (:+:) <$> arbitrary <*> arbitrary newtype InversibleGeotransform = InversibleGeotransform { getInversible :: Geotransform } deriving (Eq, Show) instance Arbitrary InversibleGeotransform where arbitrary = InversibleGeotransform <$> (Geotransform <$> fmap fixed arbitrary <*> fmap fixedNonZero arbitrary <*> pure 0 <*> fmap fixed arbitrary <*> pure 0 <*> fmap fixedNonZero arbitrary) where fixed :: Fixed E3 -> Double fixed = realToFrac fixedNonZero = fixed . getNonZero infix 4 ~== (~==) :: (Fractional a, Ord a) => a -> a -> Bool a ~== b = abs(a-b)<epsilon where epsilon = 1e-2 instance Arbitrary Geotransform where arbitrary = Geotransform <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary positivePair :: (Num a, Ord a, Arbitrary a) => Gen (Pair a) positivePair = fmap (fmap getPositive) arbitrary instance (Num a, Arbitrary a, Ord a) => Arbitrary (Envelope a) where arbitrary = do eMin <- arbitrary sz <- positivePair return (Envelope eMin (eMin+sz))
meteogrid/bindings-gdal
tests/Arbitrary.hs
bsd-3-clause
1,668
0
14
434
487
268
219
49
1
{-# OPTIONS_GHC -cpp #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.GHC -- Copyright : Isaac Jones 2003-2006 -- -- Maintainer : Isaac Jones <ijones@syntaxpolice.org> -- Stability : alpha -- Portability : portable -- {- Copyright (c) 2003-2005, Isaac Jones All rights reserved. Redistribution and use in source and binary forms, with or without modiication, 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 Isaac Jones nor the names of other 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 OWNER 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 Distribution.Simple.GHC ( build, installLib, installExe ) where import Distribution.PackageDescription ( PackageDescription(..), BuildInfo(..), withLib, setupMessage, Executable(..), withExe, Library(..), libModules, hcOptions ) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..), autogenModulesDir, mkLibDir, mkIncludeDir ) import Distribution.Simple.Utils( rawSystemExit, rawSystemPath, rawSystemVerbose, maybeExit, xargs, die, dirOf, moduleToFilePath, smartCopySources, findFile, copyFileVerbose, mkLibName, mkProfLibName, dotToSep ) import Distribution.Package ( PackageIdentifier(..), showPackageId ) import Distribution.Program ( rawSystemProgram, ranlibProgram, Program(..), ProgramConfiguration(..), ProgramLocation(..), lookupProgram, arProgram ) import Distribution.Compiler ( Compiler(..), CompilerFlavor(..), extensionsToGHCFlag ) import Distribution.Version ( Version(..) ) import Distribution.Compat.FilePath ( joinFileName, exeExtension, joinFileExt, splitFilePath, objExtension, joinPaths, isAbsolutePath, splitFileExt ) import Distribution.Compat.Directory ( createDirectoryIfMissing ) import qualified Distribution.Simple.GHCPackageConfig as GHC ( localPackageConfig, canReadLocalPackageConfig ) import Language.Haskell.Extension (Extension(..)) import Control.Monad ( unless, when ) import Data.List ( isSuffixOf, nub ) import System.Directory ( removeFile, renameFile, getDirectoryContents, doesFileExist ) import System.Exit (ExitCode(..)) #ifdef mingw32_HOST_OS import Distribution.Compat.FilePath ( splitFileName ) #endif #ifndef __NHC__ import Control.Exception (try) #else import IO (try) #endif -- ----------------------------------------------------------------------------- -- Building -- |Building for GHC. If .ghc-packages exists and is readable, add -- it to the command-line. build :: PackageDescription -> LocalBuildInfo -> Int -> IO () build pkg_descr lbi verbose = do let pref = buildDir lbi let ghcPath = compilerPath (compiler lbi) ifVanillaLib forceVanilla = when (forceVanilla || withVanillaLib lbi) ifProfLib = when (withProfLib lbi) ifGHCiLib = when (withGHCiLib lbi) -- GHC versions prior to 6.4 didn't have the user package database, -- so we fake it. TODO: This can go away in due course. pkg_conf <- if versionBranch (compilerVersion (compiler lbi)) >= [6,4] then return [] else do pkgConf <- GHC.localPackageConfig pkgConfReadable <- GHC.canReadLocalPackageConfig if pkgConfReadable then return ["-package-conf", pkgConf] else return [] -- Build lib withLib pkg_descr () $ \lib -> do when (verbose > 3) (putStrLn "Building library...") let libBi = libBuildInfo lib libTargetDir = pref forceVanillaLib = TemplateHaskell `elem` extensions libBi -- TH always needs vanilla libs, even when building for profiling createDirectoryIfMissing True libTargetDir -- put hi-boot files into place for mutually recurive modules smartCopySources verbose (hsSourceDirs libBi) libTargetDir (libModules pkg_descr) ["hi-boot"] False False let ghcArgs = pkg_conf ++ ["-package-name", showPackageId (package pkg_descr) ] ++ (if splitObjs lbi then ["-split-objs"] else []) ++ constructGHCCmdLine lbi libBi libTargetDir verbose ++ (libModules pkg_descr) ghcArgsProf = ghcArgs ++ ["-prof", "-hisuf", "p_hi", "-osuf", "p_o" ] ++ ghcProfOptions libBi unless (null (libModules pkg_descr)) $ do ifVanillaLib forceVanillaLib (rawSystemExit verbose ghcPath ghcArgs) ifProfLib (rawSystemExit verbose ghcPath ghcArgsProf) -- build any C sources unless (null (cSources libBi)) $ do when (verbose > 3) (putStrLn "Building C Sources...") -- FIX: similar 'versionBranch' logic duplicated below. refactor for code sharing sequence_ [do let ghc_vers = compilerVersion (compiler lbi) odir | versionBranch ghc_vers >= [6,4,1] = pref | otherwise = pref `joinFileName` dirOf c -- ghc 6.4.1 fixed a bug in -odir handling -- for C compilations. createDirectoryIfMissing True odir let cArgs = ["-I" ++ dir | dir <- includeDirs libBi] ++ ["-optc" ++ opt | opt <- ccOptions libBi] ++ ["-odir", odir, "-hidir", pref, "-c"] ++ (if verbose > 4 then ["-v"] else []) rawSystemExit verbose ghcPath (cArgs ++ [c]) | c <- cSources libBi] -- link: when (verbose > 3) (putStrLn "cabal-linking...") let cObjs = [ path `joinFileName` file `joinFileExt` objExtension | (path, file, _) <- (map splitFilePath (cSources libBi)) ] libName = mkLibName pref (showPackageId (package pkg_descr)) profLibName = mkProfLibName pref (showPackageId (package pkg_descr)) ghciLibName = mkGHCiLibName pref (showPackageId (package pkg_descr)) stubObjs <- sequence [moduleToFilePath [libTargetDir] (x ++"_stub") [objExtension] | x <- libModules pkg_descr ] >>= return . concat stubProfObjs <- sequence [moduleToFilePath [libTargetDir] (x ++"_stub") ["p_" ++ objExtension] | x <- libModules pkg_descr ] >>= return . concat hObjs <- getHaskellObjects pkg_descr libBi lbi pref objExtension hProfObjs <- if (withProfLib lbi) then getHaskellObjects pkg_descr libBi lbi pref ("p_" ++ objExtension) else return [] unless (null hObjs && null cObjs && null stubObjs) $ do try (removeFile libName) -- first remove library if it exists try (removeFile profLibName) -- first remove library if it exists try (removeFile ghciLibName) -- first remove library if it exists let arArgs = ["q"++ (if verbose > 4 then "v" else "")] ++ [libName] arObjArgs = hObjs ++ map (pref `joinFileName`) cObjs ++ stubObjs arProfArgs = ["q"++ (if verbose > 4 then "v" else "")] ++ [profLibName] arProfObjArgs = hProfObjs ++ map (pref `joinFileName`) cObjs ++ stubProfObjs ldArgs = ["-r"] ++ ["-x"] -- FIXME: only some systems's ld support the "-x" flag ++ ["-o", ghciLibName `joinFileExt` "tmp"] ldObjArgs = hObjs ++ map (pref `joinFileName`) cObjs ++ stubObjs #if defined(mingw32_TARGET_OS) || defined(mingw32_HOST_OS) (compilerDir, _) = splitFileName $ compilerPath (compiler lbi) (baseDir, _) = splitFileName compilerDir ld = baseDir `joinFileName` "gcc-lib\\ld.exe" rawSystemLd = rawSystemVerbose maxCommandLineSize = 30 * 1024 #else ld = "ld" rawSystemLd = rawSystemPath --TODO: discover this at configure time on unix maxCommandLineSize = 30 * 1024 #endif runLd ld args = do exists <- doesFileExist ghciLibName status <- rawSystemLd verbose ld (args ++ if exists then [ghciLibName] else []) when (status == ExitSuccess) (renameFile (ghciLibName `joinFileExt` "tmp") ghciLibName) return status ifVanillaLib False $ maybeExit $ xargs maxCommandLineSize (rawSystemPath verbose) "ar" arArgs arObjArgs ifProfLib $ maybeExit $ xargs maxCommandLineSize (rawSystemPath verbose) "ar" arProfArgs arProfObjArgs ifGHCiLib $ maybeExit $ xargs maxCommandLineSize runLd ld ldArgs ldObjArgs -- build any executables withExe pkg_descr $ \ (Executable exeName' modPath exeBi) -> do when (verbose > 3) (putStrLn $ "Building executable: " ++ exeName' ++ "...") -- exeNameReal, the name that GHC really uses (with .exe on Windows) let exeNameReal = exeName' `joinFileExt` (if null $ snd $ splitFileExt exeName' then exeExtension else "") let targetDir = pref `joinFileName` exeName' let exeDir = joinPaths targetDir (exeName' ++ "-tmp") createDirectoryIfMissing True targetDir createDirectoryIfMissing True exeDir -- put hi-boot files into place for mutually recursive modules -- FIX: what about exeName.hi-boot? smartCopySources verbose (hsSourceDirs exeBi) exeDir (otherModules exeBi) ["hi-boot"] False False -- build executables unless (null (cSources exeBi)) $ do when (verbose > 3) (putStrLn "Building C Sources.") sequence_ [do let cSrcODir |versionBranch (compilerVersion (compiler lbi)) >= [6,4,1] = exeDir | otherwise = exeDir `joinFileName` (dirOf c) createDirectoryIfMissing True cSrcODir let cArgs = ["-I" ++ dir | dir <- includeDirs exeBi] ++ ["-optc" ++ opt | opt <- ccOptions exeBi] ++ ["-odir", cSrcODir, "-hidir", pref, "-c"] ++ (if verbose > 4 then ["-v"] else []) rawSystemExit verbose ghcPath (cArgs ++ [c]) | c <- cSources exeBi] srcMainFile <- findFile (hsSourceDirs exeBi) modPath let cObjs = [ path `joinFileName` file `joinFileExt` objExtension | (path, file, _) <- (map splitFilePath (cSources exeBi)) ] let binArgs linkExe profExe = pkg_conf ++ ["-I"++pref] ++ (if linkExe then ["-o", targetDir `joinFileName` exeNameReal] else ["-c"]) ++ constructGHCCmdLine lbi exeBi exeDir verbose ++ [exeDir `joinFileName` x | x <- cObjs] ++ [srcMainFile] ++ ldOptions exeBi ++ ["-l"++lib | lib <- extraLibs exeBi] ++ ["-L"++libDir | libDir <- extraLibDirs exeBi] ++ if profExe then "-prof":ghcProfOptions exeBi else [] -- For building exe's for profiling that use TH we actually -- have to build twice, once without profiling and the again -- with profiling. This is because the code that TH needs to -- run at compile time needs to be the vanilla ABI so it can -- be loaded up and run by the compiler. when (withProfExe lbi && TemplateHaskell `elem` extensions exeBi) (rawSystemExit verbose ghcPath (binArgs False False)) rawSystemExit verbose ghcPath (binArgs True (withProfExe lbi)) -- when using -split-objs, we need to search for object files in the -- Module_split directory for each module. getHaskellObjects :: PackageDescription -> BuildInfo -> LocalBuildInfo -> FilePath -> String -> IO [FilePath] getHaskellObjects pkg_descr libBi lbi pref obj_ext | splitObjs lbi = do let dirs = [ pref `joinFileName` (dotToSep x ++ "_split") | x <- libModules pkg_descr ] objss <- mapM getDirectoryContents dirs let objs = [ dir `joinFileName` obj | (objs,dir) <- zip objss dirs, obj <- objs, obj_ext `isSuffixOf` obj ] return objs | otherwise = return [ pref `joinFileName` (dotToSep x) `joinFileExt` obj_ext | x <- libModules pkg_descr ] constructGHCCmdLine :: LocalBuildInfo -> BuildInfo -> FilePath -> Int -- verbosity level -> [String] constructGHCCmdLine lbi bi odir verbose = ["--make"] ++ (if verbose > 4 then ["-v"] else []) -- Unsupported extensions have already been checked by configure ++ (if compilerVersion (compiler lbi) > Version [6,4] [] then ["-hide-all-packages"] else []) ++ ["-i"] ++ ["-i" ++ autogenModulesDir lbi] ++ ["-i" ++ l | l <- nub (hsSourceDirs bi)] ++ ["-I" ++ dir | dir <- includeDirs bi] ++ ["-optc" ++ opt | opt <- ccOptions bi] ++ [ "-#include \"" ++ inc ++ "\"" | inc <- includes bi ++ installIncludes bi ] ++ [ "-odir", odir, "-hidir", odir ] ++ (concat [ ["-package", showPackageId pkg] | pkg <- packageDeps lbi ]) ++ hcOptions GHC (options bi) ++ snd (extensionsToGHCFlag (extensions bi)) mkGHCiLibName :: FilePath -- ^file Prefix -> String -- ^library name. -> String mkGHCiLibName pref lib = pref `joinFileName` ("HS" ++ lib ++ ".o") -- ----------------------------------------------------------------------------- -- Installing -- |Install executables for GHC. installExe :: Int -- ^verbose -> FilePath -- ^install location -> FilePath -- ^Build location -> PackageDescription -> IO () installExe verbose pref buildPref pkg_descr = do createDirectoryIfMissing True pref withExe pkg_descr $ \ (Executable e _ b) -> do let exeName = e `joinFileExt` exeExtension copyFileVerbose verbose (buildPref `joinFileName` e `joinFileName` exeName) (pref `joinFileName` exeName) -- |Install for ghc, .hi, .a and, if --with-ghci given, .o installLib :: Int -- ^verbose -> ProgramConfiguration -> Bool -- ^has vanilla library -> Bool -- ^has profiling library -> Bool -- ^has GHCi libs -> FilePath -- ^install location -> FilePath -- ^Build location -> PackageDescription -> IO () installLib verbose programConf hasVanilla hasProf hasGHCi pref buildPref pd@PackageDescription{library=Just l, package=p} = do ifVanilla $ smartCopySources verbose [buildPref] pref (libModules pd) ["hi"] True False ifProf $ smartCopySources verbose [buildPref] pref (libModules pd) ["p_hi"] True False let libTargetLoc = mkLibName pref (showPackageId p) profLibTargetLoc = mkProfLibName pref (showPackageId p) libGHCiTargetLoc = mkGHCiLibName pref (showPackageId p) ifVanilla $ copyFileVerbose verbose (mkLibName buildPref (showPackageId p)) libTargetLoc ifProf $ copyFileVerbose verbose (mkProfLibName buildPref (showPackageId p)) profLibTargetLoc ifGHCi $ copyFileVerbose verbose (mkGHCiLibName buildPref (showPackageId p)) libGHCiTargetLoc installIncludeFiles verbose pd pref -- use ranlib or ar -s to build an index. this is necessary -- on some systems like MacOS X. If we can't find those, -- don't worry too much about it. let progName = programName $ ranlibProgram mProg <- lookupProgram progName programConf case foundProg mProg of Just rl -> do ifVanilla $ rawSystemProgram verbose rl [libTargetLoc] ifProf $ rawSystemProgram verbose rl [profLibTargetLoc] Nothing -> do let progName = programName $ arProgram mProg <- lookupProgram progName programConf case mProg of Just ar -> do ifVanilla $ rawSystemProgram verbose ar ["-s", libTargetLoc] ifProf $ rawSystemProgram verbose ar ["-s", profLibTargetLoc] Nothing -> setupMessage "Warning: Unable to generate index for library (missing ranlib and ar)" pd return () where ifVanilla action = when hasVanilla (action >> return ()) ifProf action = when hasProf (action >> return ()) ifGHCi action = when hasGHCi (action >> return ()) installLib _ _ _ _ _ _ _ PackageDescription{library=Nothing} = die $ "Internal Error. installLibGHC called with no library." -- | Install the files listed in install-includes installIncludeFiles :: Int -> PackageDescription -> FilePath -> IO () installIncludeFiles verbose pkg_descr@PackageDescription{library=Just l} libdir = do createDirectoryIfMissing True incdir incs <- mapM (findInc relincdirs) (installIncludes lbi) sequence_ [ copyFileVerbose verbose path (incdir `joinFileName` f) | (f,path) <- incs ] where relincdirs = filter (not.isAbsolutePath) (includeDirs lbi) lbi = libBuildInfo l incdir = mkIncludeDir libdir findInc [] f = die ("can't find include file " ++ f) findInc (d:ds) f = do let path = (d `joinFileName` f) b <- doesFileExist path if b then return (f,path) else findInc ds f -- Also checks whether the program was actually found. foundProg :: Maybe Program -> Maybe Program foundProg Nothing = Nothing foundProg (Just Program{programLocation=EmptyLocation}) = Nothing foundProg x = x
alekar/hugs
packages/Cabal/Distribution/Simple/GHC.hs
bsd-3-clause
19,178
272
25
5,560
4,020
2,219
1,801
294
13
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.IAM.ListPolicyVersions -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- 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 <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Lists information about the versions of the specified managed policy, -- including the version that is set as the policy's default version. -- -- For more information about managed policies, refer to <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies andInline Policies> in the /Using IAM/ guide. -- -- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_ListPolicyVersions.html> module Network.AWS.IAM.ListPolicyVersions ( -- * Request ListPolicyVersions -- ** Request constructor , listPolicyVersions -- ** Request lenses , lpvMarker , lpvMaxItems , lpvPolicyArn -- * Response , ListPolicyVersionsResponse -- ** Response constructor , listPolicyVersionsResponse -- ** Response lenses , lpvrIsTruncated , lpvrMarker , lpvrVersions ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.IAM.Types import qualified GHC.Exts data ListPolicyVersions = ListPolicyVersions { _lpvMarker :: Maybe Text , _lpvMaxItems :: Maybe Nat , _lpvPolicyArn :: Text } deriving (Eq, Ord, Read, Show) -- | 'ListPolicyVersions' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lpvMarker' @::@ 'Maybe' 'Text' -- -- * 'lpvMaxItems' @::@ 'Maybe' 'Natural' -- -- * 'lpvPolicyArn' @::@ 'Text' -- listPolicyVersions :: Text -- ^ 'lpvPolicyArn' -> ListPolicyVersions listPolicyVersions p1 = ListPolicyVersions { _lpvPolicyArn = p1 , _lpvMarker = Nothing , _lpvMaxItems = Nothing } -- | Use this parameter only when paginating results, and only in a subsequent -- request after you've received a response where the results are truncated. Set -- it to the value of the 'Marker' element in the response you just received. lpvMarker :: Lens' ListPolicyVersions (Maybe Text) lpvMarker = lens _lpvMarker (\s a -> s { _lpvMarker = a }) -- | Use this parameter only when paginating results to indicate the maximum -- number of policy versions you want in the response. If there are additional -- policy versions beyond the maximum you specify, the 'IsTruncated' response -- element is 'true'. This parameter is optional. If you do not include it, it -- defaults to 100. lpvMaxItems :: Lens' ListPolicyVersions (Maybe Natural) lpvMaxItems = lens _lpvMaxItems (\s a -> s { _lpvMaxItems = a }) . mapping _Nat lpvPolicyArn :: Lens' ListPolicyVersions Text lpvPolicyArn = lens _lpvPolicyArn (\s a -> s { _lpvPolicyArn = a }) data ListPolicyVersionsResponse = ListPolicyVersionsResponse { _lpvrIsTruncated :: Maybe Bool , _lpvrMarker :: Maybe Text , _lpvrVersions :: List "member" PolicyVersion } deriving (Eq, Read, Show) -- | 'ListPolicyVersionsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lpvrIsTruncated' @::@ 'Maybe' 'Bool' -- -- * 'lpvrMarker' @::@ 'Maybe' 'Text' -- -- * 'lpvrVersions' @::@ ['PolicyVersion'] -- listPolicyVersionsResponse :: ListPolicyVersionsResponse listPolicyVersionsResponse = ListPolicyVersionsResponse { _lpvrVersions = mempty , _lpvrIsTruncated = Nothing , _lpvrMarker = Nothing } -- | A flag that indicates whether there are more policy versions to list. If your -- results were truncated, you can make a subsequent pagination request using -- the 'Marker' request parameter to retrieve more policy versions in the list. lpvrIsTruncated :: Lens' ListPolicyVersionsResponse (Maybe Bool) lpvrIsTruncated = lens _lpvrIsTruncated (\s a -> s { _lpvrIsTruncated = a }) -- | If 'IsTruncated' is 'true', this element is present and contains the value to use -- for the 'Marker' parameter in a subsequent pagination request. lpvrMarker :: Lens' ListPolicyVersionsResponse (Maybe Text) lpvrMarker = lens _lpvrMarker (\s a -> s { _lpvrMarker = a }) -- | A list of policy versions. -- -- For more information about managed policy versions, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html Versioning forManaged Policies> in the /Using IAM/ guide. lpvrVersions :: Lens' ListPolicyVersionsResponse [PolicyVersion] lpvrVersions = lens _lpvrVersions (\s a -> s { _lpvrVersions = a }) . _List instance ToPath ListPolicyVersions where toPath = const "/" instance ToQuery ListPolicyVersions where toQuery ListPolicyVersions{..} = mconcat [ "Marker" =? _lpvMarker , "MaxItems" =? _lpvMaxItems , "PolicyArn" =? _lpvPolicyArn ] instance ToHeaders ListPolicyVersions instance AWSRequest ListPolicyVersions where type Sv ListPolicyVersions = IAM type Rs ListPolicyVersions = ListPolicyVersionsResponse request = post "ListPolicyVersions" response = xmlResponse instance FromXML ListPolicyVersionsResponse where parseXML = withElement "ListPolicyVersionsResult" $ \x -> ListPolicyVersionsResponse <$> x .@? "IsTruncated" <*> x .@? "Marker" <*> x .@? "Versions" .!@ mempty
romanb/amazonka
amazonka-iam/gen/Network/AWS/IAM/ListPolicyVersions.hs
mpl-2.0
6,066
0
14
1,225
735
442
293
77
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Desugaring arrow commands -} module ETA.DeSugar.DsArrows ( dsProcExpr ) where import ETA.DeSugar.Match import ETA.DeSugar.DsUtils import ETA.DeSugar.DsMonad import ETA.HsSyn.HsSyn hiding (collectPatBinders, collectPatsBinders, collectLStmtsBinders, collectLStmtBinders, collectStmtBinders ) import ETA.TypeCheck.TcHsSyn -- NB: The desugarer, which straddles the source and Core worlds, sometimes -- needs to see source types (newtypes etc), and sometimes not -- So WATCH OUT; check each use of split*Ty functions. -- Sigh. This is a pain. import {-# SOURCE #-} ETA.DeSugar.DsExpr ( dsExpr, dsLExpr, dsLocalBinds ) import ETA.TypeCheck.TcType import ETA.TypeCheck.TcEvidence import ETA.Core.CoreSyn import ETA.Core.CoreFVs import ETA.Core.CoreUtils import ETA.Core.MkCore import ETA.DeSugar.DsBinds (dsHsWrapper) import ETA.BasicTypes.Name import ETA.BasicTypes.Var import ETA.BasicTypes.Id import ETA.BasicTypes.DataCon import ETA.Prelude.TysWiredIn import ETA.BasicTypes.BasicTypes import ETA.Prelude.PrelNames import ETA.Utils.Outputable import ETA.Utils.Bag import ETA.BasicTypes.VarSet import ETA.BasicTypes.SrcLoc import ETA.Utils.ListSetOps( assocDefault ) import ETA.Utils.FastString import Data.List data DsCmdEnv = DsCmdEnv { arr_id, compose_id, first_id, app_id, choice_id, loop_id :: CoreExpr } mkCmdEnv :: CmdSyntaxTable Id -> DsM ([CoreBind], DsCmdEnv) -- See Note [CmdSyntaxTable] in HsExpr mkCmdEnv tc_meths = do { (meth_binds, prs) <- mapAndUnzipM mk_bind tc_meths ; return (meth_binds, DsCmdEnv { arr_id = Var (find_meth prs arrAName), compose_id = Var (find_meth prs composeAName), first_id = Var (find_meth prs firstAName), app_id = Var (find_meth prs appAName), choice_id = Var (find_meth prs choiceAName), loop_id = Var (find_meth prs loopAName) }) } where mk_bind (std_name, expr) = do { rhs <- dsExpr expr ; id <- newSysLocalDs (exprType rhs) ; return (NonRec id rhs, (std_name, id)) } find_meth prs std_name = assocDefault (mk_panic std_name) prs std_name mk_panic std_name = pprPanic "mkCmdEnv" (ptext (sLit "Not found:") <+> ppr std_name) -- arr :: forall b c. (b -> c) -> a b c do_arr :: DsCmdEnv -> Type -> Type -> CoreExpr -> CoreExpr do_arr ids b_ty c_ty f = mkApps (arr_id ids) [Type b_ty, Type c_ty, f] -- (>>>) :: forall b c d. a b c -> a c d -> a b d do_compose :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr -> CoreExpr do_compose ids b_ty c_ty d_ty f g = mkApps (compose_id ids) [Type b_ty, Type c_ty, Type d_ty, f, g] -- first :: forall b c d. a b c -> a (b,d) (c,d) do_first :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr do_first ids b_ty c_ty d_ty f = mkApps (first_id ids) [Type b_ty, Type c_ty, Type d_ty, f] -- app :: forall b c. a (a b c, b) c do_app :: DsCmdEnv -> Type -> Type -> CoreExpr do_app ids b_ty c_ty = mkApps (app_id ids) [Type b_ty, Type c_ty] -- (|||) :: forall b d c. a b d -> a c d -> a (Either b c) d -- note the swapping of d and c do_choice :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr -> CoreExpr do_choice ids b_ty c_ty d_ty f g = mkApps (choice_id ids) [Type b_ty, Type d_ty, Type c_ty, f, g] -- loop :: forall b d c. a (b,d) (c,d) -> a b c -- note the swapping of d and c do_loop :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr do_loop ids b_ty c_ty d_ty f = mkApps (loop_id ids) [Type b_ty, Type d_ty, Type c_ty, f] -- premap :: forall b c d. (b -> c) -> a c d -> a b d -- premap f g = arr f >>> g do_premap :: DsCmdEnv -> Type -> Type -> Type -> CoreExpr -> CoreExpr -> CoreExpr do_premap ids b_ty c_ty d_ty f g = do_compose ids b_ty c_ty d_ty (do_arr ids b_ty c_ty f) g mkFailExpr :: HsMatchContext Id -> Type -> DsM CoreExpr mkFailExpr ctxt ty = mkErrorAppDs pAT_ERROR_ID ty (matchContextErrString ctxt) -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> a mkFstExpr :: Type -> Type -> DsM CoreExpr mkFstExpr a_ty b_ty = do a_var <- newSysLocalDs a_ty b_var <- newSysLocalDs b_ty pair_var <- newSysLocalDs (mkCorePairTy a_ty b_ty) return (Lam pair_var (coreCasePair pair_var a_var b_var (Var a_var))) -- construct CoreExpr for \ (a :: a_ty, b :: b_ty) -> b mkSndExpr :: Type -> Type -> DsM CoreExpr mkSndExpr a_ty b_ty = do a_var <- newSysLocalDs a_ty b_var <- newSysLocalDs b_ty pair_var <- newSysLocalDs (mkCorePairTy a_ty b_ty) return (Lam pair_var (coreCasePair pair_var a_var b_var (Var b_var))) {- Build case analysis of a tuple. This cannot be done in the DsM monad, because the list of variables is typically not yet defined. -} -- coreCaseTuple [u1..] v [x1..xn] body -- = case v of v { (x1, .., xn) -> body } -- But the matching may be nested if the tuple is very big coreCaseTuple :: UniqSupply -> Id -> [Id] -> CoreExpr -> CoreExpr coreCaseTuple uniqs scrut_var vars body = mkTupleCase uniqs vars body scrut_var (Var scrut_var) coreCasePair :: Id -> Id -> Id -> CoreExpr -> CoreExpr coreCasePair scrut_var var1 var2 body = Case (Var scrut_var) scrut_var (exprType body) [(DataAlt (tupleCon BoxedTuple 2), [var1, var2], body)] mkCorePairTy :: Type -> Type -> Type mkCorePairTy t1 t2 = mkBoxedTupleTy [t1, t2] mkCorePairExpr :: CoreExpr -> CoreExpr -> CoreExpr mkCorePairExpr e1 e2 = mkCoreTup [e1, e2] mkCoreUnitExpr :: CoreExpr mkCoreUnitExpr = mkCoreTup [] {- The input is divided into a local environment, which is a flat tuple (unless it's too big), and a stack, which is a right-nested pair. In general, the input has the form ((x1,...,xn), (s1,...(sk,())...)) where xi are the environment values, and si the ones on the stack, with s1 being the "top", the first one to be matched with a lambda. -} envStackType :: [Id] -> Type -> Type envStackType ids stack_ty = mkCorePairTy (mkBigCoreVarTupTy ids) stack_ty -- splitTypeAt n (t1,... (tn,t)...) = ([t1, ..., tn], t) splitTypeAt :: Int -> Type -> ([Type], Type) splitTypeAt n ty | n == 0 = ([], ty) | otherwise = case tcTyConAppArgs ty of [t, ty'] -> let (ts, ty_r) = splitTypeAt (n-1) ty' in (t:ts, ty_r) _ -> pprPanic "splitTypeAt" (ppr ty) ---------------------------------------------- -- buildEnvStack -- -- ((x1,...,xn),stk) buildEnvStack :: [Id] -> Id -> CoreExpr buildEnvStack env_ids stack_id = mkCorePairExpr (mkBigCoreVarTup env_ids) (Var stack_id) ---------------------------------------------- -- matchEnvStack -- -- \ ((x1,...,xn),stk) -> body -- => -- \ pair -> -- case pair of (tup,stk) -> -- case tup of (x1,...,xn) -> -- body matchEnvStack :: [Id] -- x1..xn -> Id -- stk -> CoreExpr -- e -> DsM CoreExpr matchEnvStack env_ids stack_id body = do uniqs <- newUniqueSupply tup_var <- newSysLocalDs (mkBigCoreVarTupTy env_ids) let match_env = coreCaseTuple uniqs tup_var env_ids body pair_id <- newSysLocalDs (mkCorePairTy (idType tup_var) (idType stack_id)) return (Lam pair_id (coreCasePair pair_id tup_var stack_id match_env)) ---------------------------------------------- -- matchEnv -- -- \ (x1,...,xn) -> body -- => -- \ tup -> -- case tup of (x1,...,xn) -> -- body matchEnv :: [Id] -- x1..xn -> CoreExpr -- e -> DsM CoreExpr matchEnv env_ids body = do uniqs <- newUniqueSupply tup_id <- newSysLocalDs (mkBigCoreVarTupTy env_ids) return (Lam tup_id (coreCaseTuple uniqs tup_id env_ids body)) ---------------------------------------------- -- matchVarStack -- -- case (x1, ...(xn, s)...) -> e -- => -- case z0 of (x1,z1) -> -- case zn-1 of (xn,s) -> -- e matchVarStack :: [Id] -> Id -> CoreExpr -> DsM (Id, CoreExpr) matchVarStack [] stack_id body = return (stack_id, body) matchVarStack (param_id:param_ids) stack_id body = do (tail_id, tail_code) <- matchVarStack param_ids stack_id body pair_id <- newSysLocalDs (mkCorePairTy (idType param_id) (idType tail_id)) return (pair_id, coreCasePair pair_id param_id tail_id tail_code) mkHsEnvStackExpr :: [Id] -> Id -> LHsExpr Id mkHsEnvStackExpr env_ids stack_id = mkLHsTupleExpr [mkLHsVarTuple env_ids, nlHsVar stack_id] -- Translation of arrow abstraction -- D; xs |-a c : () --> t' ---> c' -- -------------------------- -- D |- proc p -> c :: a t t' ---> premap (\ p -> ((xs),())) c' -- -- where (xs) is the tuple of variables bound by p dsProcExpr :: LPat Id -> LHsCmdTop Id -> DsM CoreExpr dsProcExpr pat (L _ (HsCmdTop cmd _unitTy cmd_ty ids)) = do (meth_binds, meth_ids) <- mkCmdEnv ids let locals = mkVarSet (collectPatBinders pat) (core_cmd, _free_vars, env_ids) <- dsfixCmd meth_ids locals unitTy cmd_ty cmd let env_ty = mkBigCoreVarTupTy env_ids let env_stk_ty = mkCorePairTy env_ty unitTy let env_stk_expr = mkCorePairExpr (mkBigCoreVarTup env_ids) mkCoreUnitExpr fail_expr <- mkFailExpr ProcExpr env_stk_ty var <- selectSimpleMatchVarL pat match_code <- matchSimply (Var var) ProcExpr pat env_stk_expr fail_expr let pat_ty = hsLPatType pat proc_code = do_premap meth_ids pat_ty env_stk_ty cmd_ty (Lam var match_code) core_cmd return (mkLets meth_binds proc_code) {- Translation of a command judgement of the form D; xs |-a c : stk --> t to an expression e such that D |- e :: a (xs, stk) t -} dsLCmd :: DsCmdEnv -> IdSet -> Type -> Type -> LHsCmd Id -> [Id] -> DsM (CoreExpr, IdSet) dsLCmd ids local_vars stk_ty res_ty cmd env_ids = dsCmd ids local_vars stk_ty res_ty (unLoc cmd) env_ids dsCmd :: DsCmdEnv -- arrow combinators -> IdSet -- set of local vars available to this command -> Type -- type of the stack (right-nested tuple) -> Type -- return type of the command -> HsCmd Id -- command to desugar -> [Id] -- list of vars in the input to this command -- This is typically fed back, -- so don't pull on it too early -> DsM (CoreExpr, -- desugared expression IdSet) -- subset of local vars that occur free -- D |- fun :: a t1 t2 -- D, xs |- arg :: t1 -- ----------------------------- -- D; xs |-a fun -< arg : stk --> t2 -- -- ---> premap (\ ((xs), _stk) -> arg) fun dsCmd ids local_vars stack_ty res_ty (HsCmdArrApp arrow arg arrow_ty HsFirstOrderApp _) env_ids = do let (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty core_arrow <- dsLExpr arrow core_arg <- dsLExpr arg stack_id <- newSysLocalDs stack_ty core_make_arg <- matchEnvStack env_ids stack_id core_arg return (do_premap ids (envStackType env_ids stack_ty) arg_ty res_ty core_make_arg core_arrow, exprFreeIds core_arg `intersectVarSet` local_vars) -- D, xs |- fun :: a t1 t2 -- D, xs |- arg :: t1 -- ------------------------------ -- D; xs |-a fun -<< arg : stk --> t2 -- -- ---> premap (\ ((xs), _stk) -> (fun, arg)) app dsCmd ids local_vars stack_ty res_ty (HsCmdArrApp arrow arg arrow_ty HsHigherOrderApp _) env_ids = do let (a_arg_ty, _res_ty') = tcSplitAppTy arrow_ty (_a_ty, arg_ty) = tcSplitAppTy a_arg_ty core_arrow <- dsLExpr arrow core_arg <- dsLExpr arg stack_id <- newSysLocalDs stack_ty core_make_pair <- matchEnvStack env_ids stack_id (mkCorePairExpr core_arrow core_arg) return (do_premap ids (envStackType env_ids stack_ty) (mkCorePairTy arrow_ty arg_ty) res_ty core_make_pair (do_app ids arg_ty res_ty), (exprFreeIds core_arrow `unionVarSet` exprFreeIds core_arg) `intersectVarSet` local_vars) -- D; ys |-a cmd : (t,stk) --> t' -- D, xs |- exp :: t -- ------------------------ -- D; xs |-a cmd exp : stk --> t' -- -- ---> premap (\ ((xs),stk) -> ((ys),(e,stk))) cmd dsCmd ids local_vars stack_ty res_ty (HsCmdApp cmd arg) env_ids = do core_arg <- dsLExpr arg let arg_ty = exprType core_arg stack_ty' = mkCorePairTy arg_ty stack_ty (core_cmd, free_vars, env_ids') <- dsfixCmd ids local_vars stack_ty' res_ty cmd stack_id <- newSysLocalDs stack_ty arg_id <- newSysLocalDs arg_ty -- push the argument expression onto the stack let stack' = mkCorePairExpr (Var arg_id) (Var stack_id) core_body = bindNonRec arg_id core_arg (mkCorePairExpr (mkBigCoreVarTup env_ids') stack') -- match the environment and stack against the input core_map <- matchEnvStack env_ids stack_id core_body return (do_premap ids (envStackType env_ids stack_ty) (envStackType env_ids' stack_ty') res_ty core_map core_cmd, free_vars `unionVarSet` (exprFreeIds core_arg `intersectVarSet` local_vars)) -- D; ys |-a cmd : stk t' -- ----------------------------------------------- -- D; xs |-a \ p1 ... pk -> cmd : (t1,...(tk,stk)...) t' -- -- ---> premap (\ ((xs), (p1, ... (pk,stk)...)) -> ((ys),stk)) cmd dsCmd ids local_vars stack_ty res_ty (HsCmdLam (MG { mg_alts = [L _ (Match _ pats _ (GRHSs [L _ (GRHS [] body)] _ ))] })) env_ids = do let pat_vars = mkVarSet (collectPatsBinders pats) local_vars' = pat_vars `unionVarSet` local_vars (pat_tys, stack_ty') = splitTypeAt (length pats) stack_ty (core_body, free_vars, env_ids') <- dsfixCmd ids local_vars' stack_ty' res_ty body param_ids <- mapM newSysLocalDs pat_tys stack_id' <- newSysLocalDs stack_ty' -- the expression is built from the inside out, so the actions -- are presented in reverse order let -- build a new environment, plus what's left of the stack core_expr = buildEnvStack env_ids' stack_id' in_ty = envStackType env_ids stack_ty in_ty' = envStackType env_ids' stack_ty' fail_expr <- mkFailExpr LambdaExpr in_ty' -- match the patterns against the parameters match_code <- matchSimplys (map Var param_ids) LambdaExpr pats core_expr fail_expr -- match the parameters against the top of the old stack (stack_id, param_code) <- matchVarStack param_ids stack_id' match_code -- match the old environment and stack against the input select_code <- matchEnvStack env_ids stack_id param_code return (do_premap ids in_ty in_ty' res_ty select_code core_body, free_vars `minusVarSet` pat_vars) dsCmd ids local_vars stack_ty res_ty (HsCmdPar cmd) env_ids = dsLCmd ids local_vars stack_ty res_ty cmd env_ids -- D, xs |- e :: Bool -- D; xs1 |-a c1 : stk --> t -- D; xs2 |-a c2 : stk --> t -- ---------------------------------------- -- D; xs |-a if e then c1 else c2 : stk --> t -- -- ---> premap (\ ((xs),stk) -> -- if e then Left ((xs1),stk) else Right ((xs2),stk)) -- (c1 ||| c2) dsCmd ids local_vars stack_ty res_ty (HsCmdIf mb_fun cond then_cmd else_cmd) env_ids = do core_cond <- dsLExpr cond (core_then, fvs_then, then_ids) <- dsfixCmd ids local_vars stack_ty res_ty then_cmd (core_else, fvs_else, else_ids) <- dsfixCmd ids local_vars stack_ty res_ty else_cmd stack_id <- newSysLocalDs stack_ty either_con <- dsLookupTyCon eitherTyConName left_con <- dsLookupDataCon leftDataConName right_con <- dsLookupDataCon rightDataConName let mk_left_expr ty1 ty2 e = mkCoreConApps left_con [Type ty1, Type ty2, e] mk_right_expr ty1 ty2 e = mkCoreConApps right_con [Type ty1, Type ty2, e] in_ty = envStackType env_ids stack_ty then_ty = envStackType then_ids stack_ty else_ty = envStackType else_ids stack_ty sum_ty = mkTyConApp either_con [then_ty, else_ty] fvs_cond = exprFreeIds core_cond `intersectVarSet` local_vars core_left = mk_left_expr then_ty else_ty (buildEnvStack then_ids stack_id) core_right = mk_right_expr then_ty else_ty (buildEnvStack else_ids stack_id) core_if <- case mb_fun of Just fun -> do { core_fun <- dsExpr fun ; matchEnvStack env_ids stack_id $ mkCoreApps core_fun [core_cond, core_left, core_right] } Nothing -> matchEnvStack env_ids stack_id $ mkIfThenElse core_cond core_left core_right return (do_premap ids in_ty sum_ty res_ty core_if (do_choice ids then_ty else_ty res_ty core_then core_else), fvs_cond `unionVarSet` fvs_then `unionVarSet` fvs_else) {- Case commands are treated in much the same way as if commands (see above) except that there are more alternatives. For example case e of { p1 -> c1; p2 -> c2; p3 -> c3 } is translated to premap (\ ((xs)*ts) -> case e of p1 -> (Left (Left (xs1)*ts)) p2 -> Left ((Right (xs2)*ts)) p3 -> Right ((xs3)*ts)) ((c1 ||| c2) ||| c3) The idea is to extract the commands from the case, build a balanced tree of choices, and replace the commands with expressions that build tagged tuples, obtaining a case expression that can be desugared normally. To build all this, we use triples describing segments of the list of case bodies, containing the following fields: * a list of expressions of the form (Left|Right)* ((xs)*ts), to be put into the case replacing the commands * a sum type that is the common type of these expressions, and also the input type of the arrow * a CoreExpr for an arrow built by combining the translated command bodies with |||. -} dsCmd ids local_vars stack_ty res_ty (HsCmdCase exp (MG { mg_alts = matches, mg_arg_tys = arg_tys, mg_origin = origin })) env_ids = do stack_id <- newSysLocalDs stack_ty -- Extract and desugar the leaf commands in the case, building tuple -- expressions that will (after tagging) replace these leaves let leaves = concatMap leavesMatch matches make_branch (leaf, bound_vars) = do (core_leaf, _fvs, leaf_ids) <- dsfixCmd ids (bound_vars `unionVarSet` local_vars) stack_ty res_ty leaf return ([mkHsEnvStackExpr leaf_ids stack_id], envStackType leaf_ids stack_ty, core_leaf) branches <- mapM make_branch leaves either_con <- dsLookupTyCon eitherTyConName left_con <- dsLookupDataCon leftDataConName right_con <- dsLookupDataCon rightDataConName let left_id = HsVar (dataConWrapId left_con) right_id = HsVar (dataConWrapId right_con) left_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ HsWrap (mkWpTyApps [ty1, ty2]) left_id ) e right_expr ty1 ty2 e = noLoc $ HsApp (noLoc $ HsWrap (mkWpTyApps [ty1, ty2]) right_id) e -- Prefix each tuple with a distinct series of Left's and Right's, -- in a balanced way, keeping track of the types. merge_branches (builds1, in_ty1, core_exp1) (builds2, in_ty2, core_exp2) = (map (left_expr in_ty1 in_ty2) builds1 ++ map (right_expr in_ty1 in_ty2) builds2, mkTyConApp either_con [in_ty1, in_ty2], do_choice ids in_ty1 in_ty2 res_ty core_exp1 core_exp2) (leaves', sum_ty, core_choices) = foldb merge_branches branches -- Replace the commands in the case with these tagged tuples, -- yielding a HsExpr Id we can feed to dsExpr. (_, matches') = mapAccumL (replaceLeavesMatch res_ty) leaves' matches in_ty = envStackType env_ids stack_ty core_body <- dsExpr (HsCase exp (MG { mg_alts = matches', mg_arg_tys = arg_tys , mg_res_ty = sum_ty, mg_origin = origin })) -- Note that we replace the HsCase result type by sum_ty, -- which is the type of matches' core_matches <- matchEnvStack env_ids stack_id core_body return (do_premap ids in_ty sum_ty res_ty core_matches core_choices, exprFreeIds core_body `intersectVarSet` local_vars) -- D; ys |-a cmd : stk --> t -- ---------------------------------- -- D; xs |-a let binds in cmd : stk --> t -- -- ---> premap (\ ((xs),stk) -> let binds in ((ys),stk)) c dsCmd ids local_vars stack_ty res_ty (HsCmdLet binds body) env_ids = do let defined_vars = mkVarSet (collectLocalBinders binds) local_vars' = defined_vars `unionVarSet` local_vars (core_body, _free_vars, env_ids') <- dsfixCmd ids local_vars' stack_ty res_ty body stack_id <- newSysLocalDs stack_ty -- build a new environment, plus the stack, using the let bindings core_binds <- dsLocalBinds binds (buildEnvStack env_ids' stack_id) -- match the old environment and stack against the input core_map <- matchEnvStack env_ids stack_id core_binds return (do_premap ids (envStackType env_ids stack_ty) (envStackType env_ids' stack_ty) res_ty core_map core_body, exprFreeIds core_binds `intersectVarSet` local_vars) -- D; xs |-a ss : t -- ---------------------------------- -- D; xs |-a do { ss } : () --> t -- -- ---> premap (\ (env,stk) -> env) c dsCmd ids local_vars stack_ty res_ty (HsCmdDo stmts _) env_ids = do (core_stmts, env_ids') <- dsCmdDo ids local_vars res_ty stmts env_ids let env_ty = mkBigCoreVarTupTy env_ids core_fst <- mkFstExpr env_ty stack_ty return (do_premap ids (mkCorePairTy env_ty stack_ty) env_ty res_ty core_fst core_stmts, env_ids') -- D |- e :: forall e. a1 (e,stk1) t1 -> ... an (e,stkn) tn -> a (e,stk) t -- D; xs |-a ci :: stki --> ti -- ----------------------------------- -- D; xs |-a (|e c1 ... cn|) :: stk --> t ---> e [t_xs] c1 ... cn dsCmd _ids local_vars _stack_ty _res_ty (HsCmdArrForm op _ args) env_ids = do let env_ty = mkBigCoreVarTupTy env_ids core_op <- dsLExpr op (core_args, fv_sets) <- mapAndUnzipM (dsTrimCmdArg local_vars env_ids) args return (mkApps (App core_op (Type env_ty)) core_args, unionVarSets fv_sets) dsCmd ids local_vars stack_ty res_ty (HsCmdCast coercion cmd) env_ids = do (core_cmd, env_ids') <- dsCmd ids local_vars stack_ty res_ty cmd env_ids wrapped_cmd <- dsHsWrapper (mkWpCast coercion) core_cmd return (wrapped_cmd, env_ids') dsCmd _ _ _ _ _ c = pprPanic "dsCmd" (ppr c) -- D; ys |-a c : stk --> t (ys <= xs) -- --------------------- -- D; xs |-a c : stk --> t ---> premap (\ ((xs),stk) -> ((ys),stk)) c dsTrimCmdArg :: IdSet -- set of local vars available to this command -> [Id] -- list of vars in the input to this command -> LHsCmdTop Id -- command argument to desugar -> DsM (CoreExpr, -- desugared expression IdSet) -- subset of local vars that occur free dsTrimCmdArg local_vars env_ids (L _ (HsCmdTop cmd stack_ty cmd_ty ids)) = do (meth_binds, meth_ids) <- mkCmdEnv ids (core_cmd, free_vars, env_ids') <- dsfixCmd meth_ids local_vars stack_ty cmd_ty cmd stack_id <- newSysLocalDs stack_ty trim_code <- matchEnvStack env_ids stack_id (buildEnvStack env_ids' stack_id) let in_ty = envStackType env_ids stack_ty in_ty' = envStackType env_ids' stack_ty arg_code = if env_ids' == env_ids then core_cmd else do_premap meth_ids in_ty in_ty' cmd_ty trim_code core_cmd return (mkLets meth_binds arg_code, free_vars) -- Given D; xs |-a c : stk --> t, builds c with xs fed back. -- Typically needs to be prefixed with arr (\(p, stk) -> ((xs),stk)) dsfixCmd :: DsCmdEnv -- arrow combinators -> IdSet -- set of local vars available to this command -> Type -- type of the stack (right-nested tuple) -> Type -- return type of the command -> LHsCmd Id -- command to desugar -> DsM (CoreExpr, -- desugared expression IdSet, -- subset of local vars that occur free [Id]) -- the same local vars as a list, fed back dsfixCmd ids local_vars stk_ty cmd_ty cmd = trimInput (dsLCmd ids local_vars stk_ty cmd_ty cmd) -- Feed back the list of local variables actually used a command, -- for use as the input tuple of the generated arrow. trimInput :: ([Id] -> DsM (CoreExpr, IdSet)) -> DsM (CoreExpr, -- desugared expression IdSet, -- subset of local vars that occur free [Id]) -- same local vars as a list, fed back to -- the inner function to form the tuple of -- inputs to the arrow. trimInput build_arrow = fixDs (\ ~(_,_,env_ids) -> do (core_cmd, free_vars) <- build_arrow env_ids return (core_cmd, free_vars, varSetElems free_vars)) {- Translation of command judgements of the form D |-a do { ss } : t -} dsCmdDo :: DsCmdEnv -- arrow combinators -> IdSet -- set of local vars available to this statement -> Type -- return type of the statement -> [CmdLStmt Id] -- statements to desugar -> [Id] -- list of vars in the input to this statement -- This is typically fed back, -- so don't pull on it too early -> DsM (CoreExpr, -- desugared expression IdSet) -- subset of local vars that occur free dsCmdDo _ _ _ [] _ = panic "dsCmdDo" -- D; xs |-a c : () --> t -- -------------------------- -- D; xs |-a do { c } : t -- -- ---> premap (\ (xs) -> ((xs), ())) c dsCmdDo ids local_vars res_ty [L _ (LastStmt body _)] env_ids = do (core_body, env_ids') <- dsLCmd ids local_vars unitTy res_ty body env_ids let env_ty = mkBigCoreVarTupTy env_ids env_var <- newSysLocalDs env_ty let core_map = Lam env_var (mkCorePairExpr (Var env_var) mkCoreUnitExpr) return (do_premap ids env_ty (mkCorePairTy env_ty unitTy) res_ty core_map core_body, env_ids') dsCmdDo ids local_vars res_ty (stmt:stmts) env_ids = do let bound_vars = mkVarSet (collectLStmtBinders stmt) local_vars' = bound_vars `unionVarSet` local_vars (core_stmts, _, env_ids') <- trimInput (dsCmdDo ids local_vars' res_ty stmts) (core_stmt, fv_stmt) <- dsCmdLStmt ids local_vars env_ids' stmt env_ids return (do_compose ids (mkBigCoreVarTupTy env_ids) (mkBigCoreVarTupTy env_ids') res_ty core_stmt core_stmts, fv_stmt) {- A statement maps one local environment to another, and is represented as an arrow from one tuple type to another. A statement sequence is translated to a composition of such arrows. -} dsCmdLStmt :: DsCmdEnv -> IdSet -> [Id] -> CmdLStmt Id -> [Id] -> DsM (CoreExpr, IdSet) dsCmdLStmt ids local_vars out_ids cmd env_ids = dsCmdStmt ids local_vars out_ids (unLoc cmd) env_ids dsCmdStmt :: DsCmdEnv -- arrow combinators -> IdSet -- set of local vars available to this statement -> [Id] -- list of vars in the output of this statement -> CmdStmt Id -- statement to desugar -> [Id] -- list of vars in the input to this statement -- This is typically fed back, -- so don't pull on it too early -> DsM (CoreExpr, -- desugared expression IdSet) -- subset of local vars that occur free -- D; xs1 |-a c : () --> t -- D; xs' |-a do { ss } : t' -- ------------------------------ -- D; xs |-a do { c; ss } : t' -- -- ---> premap (\ ((xs)) -> (((xs1),()),(xs'))) -- (first c >>> arr snd) >>> ss dsCmdStmt ids local_vars out_ids (BodyStmt cmd _ _ c_ty) env_ids = do (core_cmd, fv_cmd, env_ids1) <- dsfixCmd ids local_vars unitTy c_ty cmd core_mux <- matchEnv env_ids (mkCorePairExpr (mkCorePairExpr (mkBigCoreVarTup env_ids1) mkCoreUnitExpr) (mkBigCoreVarTup out_ids)) let in_ty = mkBigCoreVarTupTy env_ids in_ty1 = mkCorePairTy (mkBigCoreVarTupTy env_ids1) unitTy out_ty = mkBigCoreVarTupTy out_ids before_c_ty = mkCorePairTy in_ty1 out_ty after_c_ty = mkCorePairTy c_ty out_ty snd_fn <- mkSndExpr c_ty out_ty return (do_premap ids in_ty before_c_ty out_ty core_mux $ do_compose ids before_c_ty after_c_ty out_ty (do_first ids in_ty1 c_ty out_ty core_cmd) $ do_arr ids after_c_ty out_ty snd_fn, extendVarSetList fv_cmd out_ids) -- D; xs1 |-a c : () --> t -- D; xs' |-a do { ss } : t' xs2 = xs' - defs(p) -- ----------------------------------- -- D; xs |-a do { p <- c; ss } : t' -- -- ---> premap (\ (xs) -> (((xs1),()),(xs2))) -- (first c >>> arr (\ (p, (xs2)) -> (xs'))) >>> ss -- -- It would be simpler and more consistent to do this using second, -- but that's likely to be defined in terms of first. dsCmdStmt ids local_vars out_ids (BindStmt pat cmd _ _) env_ids = do (core_cmd, fv_cmd, env_ids1) <- dsfixCmd ids local_vars unitTy (hsLPatType pat) cmd let pat_ty = hsLPatType pat pat_vars = mkVarSet (collectPatBinders pat) env_ids2 = varSetElems (mkVarSet out_ids `minusVarSet` pat_vars) env_ty2 = mkBigCoreVarTupTy env_ids2 -- multiplexing function -- \ (xs) -> (((xs1),()),(xs2)) core_mux <- matchEnv env_ids (mkCorePairExpr (mkCorePairExpr (mkBigCoreVarTup env_ids1) mkCoreUnitExpr) (mkBigCoreVarTup env_ids2)) -- projection function -- \ (p, (xs2)) -> (zs) env_id <- newSysLocalDs env_ty2 uniqs <- newUniqueSupply let after_c_ty = mkCorePairTy pat_ty env_ty2 out_ty = mkBigCoreVarTupTy out_ids body_expr = coreCaseTuple uniqs env_id env_ids2 (mkBigCoreVarTup out_ids) fail_expr <- mkFailExpr (StmtCtxt DoExpr) out_ty pat_id <- selectSimpleMatchVarL pat match_code <- matchSimply (Var pat_id) (StmtCtxt DoExpr) pat body_expr fail_expr pair_id <- newSysLocalDs after_c_ty let proj_expr = Lam pair_id (coreCasePair pair_id pat_id env_id match_code) -- put it all together let in_ty = mkBigCoreVarTupTy env_ids in_ty1 = mkCorePairTy (mkBigCoreVarTupTy env_ids1) unitTy in_ty2 = mkBigCoreVarTupTy env_ids2 before_c_ty = mkCorePairTy in_ty1 in_ty2 return (do_premap ids in_ty before_c_ty out_ty core_mux $ do_compose ids before_c_ty after_c_ty out_ty (do_first ids in_ty1 pat_ty in_ty2 core_cmd) $ do_arr ids after_c_ty out_ty proj_expr, fv_cmd `unionVarSet` (mkVarSet out_ids `minusVarSet` pat_vars)) -- D; xs' |-a do { ss } : t -- -------------------------------------- -- D; xs |-a do { let binds; ss } : t -- -- ---> arr (\ (xs) -> let binds in (xs')) >>> ss dsCmdStmt ids local_vars out_ids (LetStmt binds) env_ids = do -- build a new environment using the let bindings core_binds <- dsLocalBinds binds (mkBigCoreVarTup out_ids) -- match the old environment against the input core_map <- matchEnv env_ids core_binds return (do_arr ids (mkBigCoreVarTupTy env_ids) (mkBigCoreVarTupTy out_ids) core_map, exprFreeIds core_binds `intersectVarSet` local_vars) -- D; ys |-a do { ss; returnA -< ((xs1), (ys2)) } : ... -- D; xs' |-a do { ss' } : t -- ------------------------------------ -- D; xs |-a do { rec ss; ss' } : t -- -- xs1 = xs' /\ defs(ss) -- xs2 = xs' - defs(ss) -- ys1 = ys - defs(ss) -- ys2 = ys /\ defs(ss) -- -- ---> arr (\(xs) -> ((ys1),(xs2))) >>> -- first (loop (arr (\((ys1),~(ys2)) -> (ys)) >>> ss)) >>> -- arr (\((xs1),(xs2)) -> (xs')) >>> ss' dsCmdStmt ids local_vars out_ids (RecStmt { recS_stmts = stmts , recS_later_ids = later_ids, recS_rec_ids = rec_ids , recS_later_rets = later_rets, recS_rec_rets = rec_rets }) env_ids = do let env2_id_set = mkVarSet out_ids `minusVarSet` mkVarSet later_ids env2_ids = varSetElems env2_id_set env2_ty = mkBigCoreVarTupTy env2_ids -- post_loop_fn = \((later_ids),(env2_ids)) -> (out_ids) uniqs <- newUniqueSupply env2_id <- newSysLocalDs env2_ty let later_ty = mkBigCoreVarTupTy later_ids post_pair_ty = mkCorePairTy later_ty env2_ty post_loop_body = coreCaseTuple uniqs env2_id env2_ids (mkBigCoreVarTup out_ids) post_loop_fn <- matchEnvStack later_ids env2_id post_loop_body --- loop (...) (core_loop, env1_id_set, env1_ids) <- dsRecCmd ids local_vars stmts later_ids later_rets rec_ids rec_rets -- pre_loop_fn = \(env_ids) -> ((env1_ids),(env2_ids)) let env1_ty = mkBigCoreVarTupTy env1_ids pre_pair_ty = mkCorePairTy env1_ty env2_ty pre_loop_body = mkCorePairExpr (mkBigCoreVarTup env1_ids) (mkBigCoreVarTup env2_ids) pre_loop_fn <- matchEnv env_ids pre_loop_body -- arr pre_loop_fn >>> first (loop (...)) >>> arr post_loop_fn let env_ty = mkBigCoreVarTupTy env_ids out_ty = mkBigCoreVarTupTy out_ids core_body = do_premap ids env_ty pre_pair_ty out_ty pre_loop_fn (do_compose ids pre_pair_ty post_pair_ty out_ty (do_first ids env1_ty later_ty env2_ty core_loop) (do_arr ids post_pair_ty out_ty post_loop_fn)) return (core_body, env1_id_set `unionVarSet` env2_id_set) dsCmdStmt _ _ _ _ s = pprPanic "dsCmdStmt" (ppr s) -- loop (premap (\ ((env1_ids), ~(rec_ids)) -> (env_ids)) -- (ss >>> arr (\ (out_ids) -> ((later_rets),(rec_rets))))) >>> dsRecCmd :: DsCmdEnv -- arrow combinators -> IdSet -- set of local vars available to this statement -> [CmdLStmt Id] -- list of statements inside the RecCmd -> [Id] -- list of vars defined here and used later -> [HsExpr Id] -- expressions corresponding to later_ids -> [Id] -- list of vars fed back through the loop -> [HsExpr Id] -- expressions corresponding to rec_ids -> DsM (CoreExpr, -- desugared statement IdSet, -- subset of local vars that occur free [Id]) -- same local vars as a list dsRecCmd ids local_vars stmts later_ids later_rets rec_ids rec_rets = do let later_id_set = mkVarSet later_ids rec_id_set = mkVarSet rec_ids local_vars' = rec_id_set `unionVarSet` later_id_set `unionVarSet` local_vars -- mk_pair_fn = \ (out_ids) -> ((later_rets),(rec_rets)) core_later_rets <- mapM dsExpr later_rets core_rec_rets <- mapM dsExpr rec_rets let -- possibly polymorphic version of vars of later_ids and rec_ids out_ids = varSetElems (unionVarSets (map exprFreeIds (core_later_rets ++ core_rec_rets))) out_ty = mkBigCoreVarTupTy out_ids later_tuple = mkBigCoreTup core_later_rets later_ty = mkBigCoreVarTupTy later_ids rec_tuple = mkBigCoreTup core_rec_rets rec_ty = mkBigCoreVarTupTy rec_ids out_pair = mkCorePairExpr later_tuple rec_tuple out_pair_ty = mkCorePairTy later_ty rec_ty mk_pair_fn <- matchEnv out_ids out_pair -- ss (core_stmts, fv_stmts, env_ids) <- dsfixCmdStmts ids local_vars' out_ids stmts -- squash_pair_fn = \ ((env1_ids), ~(rec_ids)) -> (env_ids) rec_id <- newSysLocalDs rec_ty let env1_id_set = fv_stmts `minusVarSet` rec_id_set env1_ids = varSetElems env1_id_set env1_ty = mkBigCoreVarTupTy env1_ids in_pair_ty = mkCorePairTy env1_ty rec_ty core_body = mkBigCoreTup (map selectVar env_ids) where selectVar v | v `elemVarSet` rec_id_set = mkTupleSelector rec_ids v rec_id (Var rec_id) | otherwise = Var v squash_pair_fn <- matchEnvStack env1_ids rec_id core_body -- loop (premap squash_pair_fn (ss >>> arr mk_pair_fn)) let env_ty = mkBigCoreVarTupTy env_ids core_loop = do_loop ids env1_ty later_ty rec_ty (do_premap ids in_pair_ty env_ty out_pair_ty squash_pair_fn (do_compose ids env_ty out_ty out_pair_ty core_stmts (do_arr ids out_ty out_pair_ty mk_pair_fn))) return (core_loop, env1_id_set, env1_ids) {- A sequence of statements (as in a rec) is desugared to an arrow between two environments (no stack) -} dsfixCmdStmts :: DsCmdEnv -- arrow combinators -> IdSet -- set of local vars available to this statement -> [Id] -- output vars of these statements -> [CmdLStmt Id] -- statements to desugar -> DsM (CoreExpr, -- desugared expression IdSet, -- subset of local vars that occur free [Id]) -- same local vars as a list dsfixCmdStmts ids local_vars out_ids stmts = trimInput (dsCmdStmts ids local_vars out_ids stmts) dsCmdStmts :: DsCmdEnv -- arrow combinators -> IdSet -- set of local vars available to this statement -> [Id] -- output vars of these statements -> [CmdLStmt Id] -- statements to desugar -> [Id] -- list of vars in the input to these statements -> DsM (CoreExpr, -- desugared expression IdSet) -- subset of local vars that occur free dsCmdStmts ids local_vars out_ids [stmt] env_ids = dsCmdLStmt ids local_vars out_ids stmt env_ids dsCmdStmts ids local_vars out_ids (stmt:stmts) env_ids = do let bound_vars = mkVarSet (collectLStmtBinders stmt) local_vars' = bound_vars `unionVarSet` local_vars (core_stmts, _fv_stmts, env_ids') <- dsfixCmdStmts ids local_vars' out_ids stmts (core_stmt, fv_stmt) <- dsCmdLStmt ids local_vars env_ids' stmt env_ids return (do_compose ids (mkBigCoreVarTupTy env_ids) (mkBigCoreVarTupTy env_ids') (mkBigCoreVarTupTy out_ids) core_stmt core_stmts, fv_stmt) dsCmdStmts _ _ _ [] _ = panic "dsCmdStmts []" -- Match a list of expressions against a list of patterns, left-to-right. matchSimplys :: [CoreExpr] -- Scrutinees -> HsMatchContext Name -- Match kind -> [LPat Id] -- Patterns they should match -> CoreExpr -- Return this if they all match -> CoreExpr -- Return this if they don't -> DsM CoreExpr matchSimplys [] _ctxt [] result_expr _fail_expr = return result_expr matchSimplys (exp:exps) ctxt (pat:pats) result_expr fail_expr = do match_code <- matchSimplys exps ctxt pats result_expr fail_expr matchSimply exp ctxt pat match_code fail_expr matchSimplys _ _ _ _ _ = panic "matchSimplys" -- List of leaf expressions, with set of variables bound in each leavesMatch :: LMatch Id (Located (body Id)) -> [(Located (body Id), IdSet)] leavesMatch (L _ (Match _ pats _ (GRHSs grhss binds))) = let defined_vars = mkVarSet (collectPatsBinders pats) `unionVarSet` mkVarSet (collectLocalBinders binds) in [(body, mkVarSet (collectLStmtsBinders stmts) `unionVarSet` defined_vars) | L _ (GRHS stmts body) <- grhss] -- Replace the leaf commands in a match replaceLeavesMatch :: Type -- new result type -> [Located (body' Id)] -- replacement leaf expressions of that type -> LMatch Id (Located (body Id)) -- the matches of a case command -> ([Located (body' Id)], -- remaining leaf expressions LMatch Id (Located (body' Id))) -- updated match replaceLeavesMatch _res_ty leaves (L loc (Match mf pat mt (GRHSs grhss binds))) = let (leaves', grhss') = mapAccumL replaceLeavesGRHS leaves grhss in (leaves', L loc (Match mf pat mt (GRHSs grhss' binds))) replaceLeavesGRHS :: [Located (body' Id)] -- replacement leaf expressions of that type -> LGRHS Id (Located (body Id)) -- rhss of a case command -> ([Located (body' Id)], -- remaining leaf expressions LGRHS Id (Located (body' Id))) -- updated GRHS replaceLeavesGRHS (leaf:leaves) (L loc (GRHS stmts _)) = (leaves, L loc (GRHS stmts leaf)) replaceLeavesGRHS [] _ = panic "replaceLeavesGRHS []" -- Balanced fold of a non-empty list. foldb :: (a -> a -> a) -> [a] -> a foldb _ [] = error "foldb of empty list" foldb _ [x] = x foldb f xs = foldb f (fold_pairs xs) where fold_pairs [] = [] fold_pairs [x] = [x] fold_pairs (x1:x2:xs) = f x1 x2:fold_pairs xs {- Note [Dictionary binders in ConPatOut] See also same Note in HsUtils ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following functions to collect value variables from patterns are copied from HsUtils, with one change: we also collect the dictionary bindings (pat_binds) from ConPatOut. We need them for cases like h :: Arrow a => Int -> a (Int,Int) Int h x = proc (y,z) -> case compare x y of GT -> returnA -< z+x The type checker turns the case into case compare x y of GT { p77 = plusInt } -> returnA -< p77 z x Here p77 is a local binding for the (+) operation. See comments in HsUtils for why the other version does not include these bindings. -} collectPatBinders :: LPat Id -> [Id] collectPatBinders pat = collectl pat [] collectPatsBinders :: [LPat Id] -> [Id] collectPatsBinders pats = foldr collectl [] pats --------------------- collectl :: LPat Id -> [Id] -> [Id] -- See Note [Dictionary binders in ConPatOut] collectl (L _ pat) bndrs = go pat where go (VarPat var) = var : bndrs go (WildPat _) = bndrs go (LazyPat pat) = collectl pat bndrs go (BangPat pat) = collectl pat bndrs go (AsPat (L _ a) pat) = a : collectl pat bndrs go (ParPat pat) = collectl pat bndrs go (ListPat pats _ _) = foldr collectl bndrs pats go (PArrPat pats _) = foldr collectl bndrs pats go (TuplePat pats _ _) = foldr collectl bndrs pats go (ConPatIn _ ps) = foldr collectl bndrs (hsConPatArgs ps) go (ConPatOut {pat_args=ps, pat_binds=ds}) = collectEvBinders ds ++ foldr collectl bndrs (hsConPatArgs ps) go (LitPat _) = bndrs go (NPat _ _ _) = bndrs go (NPlusKPat (L _ n) _ _ _) = n : bndrs go (SigPatIn pat _) = collectl pat bndrs go (SigPatOut pat _) = collectl pat bndrs go (CoPat _ pat _) = collectl (noLoc pat) bndrs go (ViewPat _ pat _) = collectl pat bndrs go p@(SplicePat {}) = pprPanic "collectl/go" (ppr p) go p@(QuasiQuotePat {}) = pprPanic "collectl/go" (ppr p) collectEvBinders :: TcEvBinds -> [Id] collectEvBinders (EvBinds bs) = foldrBag add_ev_bndr [] bs collectEvBinders (TcEvBinds {}) = panic "ToDo: collectEvBinders" add_ev_bndr :: EvBind -> [Id] -> [Id] add_ev_bndr (EvBind b _) bs | isId b = b:bs | otherwise = bs -- A worry: what about coercion variable binders?? collectLStmtsBinders :: [LStmt Id body] -> [Id] collectLStmtsBinders = concatMap collectLStmtBinders collectLStmtBinders :: LStmt Id body -> [Id] collectLStmtBinders = collectStmtBinders . unLoc collectStmtBinders :: Stmt Id body -> [Id] collectStmtBinders (BindStmt pat _ _ _) = collectPatBinders pat collectStmtBinders (LetStmt binds) = collectLocalBinders binds collectStmtBinders (BodyStmt {}) = [] collectStmtBinders (LastStmt {}) = [] collectStmtBinders (ParStmt xs _ _) = collectLStmtsBinders $ [ s | ParStmtBlock ss _ _ <- xs, s <- ss] collectStmtBinders (TransStmt { trS_stmts = stmts }) = collectLStmtsBinders stmts collectStmtBinders (RecStmt { recS_later_ids = later_ids }) = later_ids
alexander-at-github/eta
compiler/ETA/DeSugar/DsArrows.hs
bsd-3-clause
46,307
2
22
13,576
9,690
5,006
4,684
703
20
-- -- Patricia Fasel -- Los Alamos National Laboratory -- 1990 August -- module PushParticle (pushParticle) where import PicType import Consts import Data.Array--1.3 -- Phase IV: Particle push -- Each particle has an initial velocity determined by its motion during the -- previous timestep and is accelerated by the field induced by the -- collection of particles -- -- Compute the acceleration of each particle -- Find the maximum acceleration in x and y directions -- Determine a safe delta t, such that no particle will move a -- distance greater than the cell -- Compute new position and velocity of each particle pushParticle :: ParticleHeap -> Electric -> Value -> Value -> Value -> (Value, Value, ParticleHeap) pushParticle ([], []) xyElec dt maxAcc maxVel = (maxAcc, maxVel, ([], [])) pushParticle (((xPos,yPos):xyPos), ((xVel,yVel):xyVel)) (xElec, yElec) dt maxAcc maxVel = (maxAcc'', maxVel'', (((xPos',yPos'):xyPos'), ((xVel',yVel'):xyVel'))) where i = truncate xPos j = truncate yPos i1 = (i+1) `rem` nCell j1 = (j+1) `rem` nCell dx = xPos - fromIntegral i dy = yPos - fromIntegral j xAcc = (charge/mass) * (xElec!(i,j)*(1-dy) + xElec!(i,j1)*dy) yAcc = (charge/mass) * (yElec!(i,j)*(1-dx) + yElec!(i1,j)*dx) xTV = xAcc*dt + xVel yTV = yAcc*dt + yVel xT = xTV*dt + xPos yT = yTV*dt + yPos maxAcc' = max maxAcc (max (abs xAcc) (abs yAcc)) maxVel' = max maxVel (max (abs xTV) (abs yTV)) (xVel',yVel') = (xTV, yTV) xPos' = if (xT >= fromIntegral nCell) then xT - fromIntegral nCell else if (xT < 0.0) then xT + fromIntegral nCell else xT yPos' = if (yT >= fromIntegral nCell) then yT - fromIntegral nCell else if (yT < 0.0) then yT + fromIntegral nCell else yT (maxAcc'', maxVel'', (xyPos', xyVel')) = pushParticle (xyPos, xyVel) (xElec, yElec) dt maxAcc' maxVel'
PaulBone/mercury
benchmarks/progs/pic/haskell/PushParticle.hs
gpl-2.0
1,940
28
14
458
710
406
304
37
5
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ko-KR"> <title>Online Menu | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/onlineMenu/src/main/javahelp/org/zaproxy/zap/extension/onlineMenu/resources/help_ko_KR/helpset_ko_KR.hs
apache-2.0
972
78
66
159
413
209
204
-1
-1
import Test.Cabal.Prelude main = cabalTest $ do osx <- isOSX -- On Travis OSX, Cabal shipped with GHC 7.8 does not work -- with error "setup: /usr/bin/ar: permission denied"; see -- also https://github.com/haskell/cabal/issues/3938 -- This is a hack to make the test not run in this case. when osx $ skipUnless =<< ghcVersionIs (>= mkVersion [7,10]) withSandbox $ do cabal_sandbox "add-source" ["custom"] cabal_sandbox "add-source" ["client"] -- NB: This test relies critically on the Setup script being -- built against GHC's bundled Cabal. This means that the -- output we see may vary between tests, so we don't record this. recordMode DoNotRecord $ cabal "install" ["client"]
mydaum/cabal
cabal-testsuite/PackageTests/CustomDep/sandbox.test.hs
bsd-3-clause
769
0
13
194
107
55
52
9
1
module MyDoc2Latex(latex) where import MyDoc import Pretty beg t = text "\\begin{" <> text t <> char '}' end t = text "\\end{" <> text t <> char '}' cmd x t = beg x $$ t $$ end x latex = Style { ppHeading = heading , ppDecStr = txt , ppCode = code , ppList = list , ppItem = item , ppParagraph = par , ppText = id , ppFinalize = fin } fin x = text "\\documentclass{article}" $$ cmd "document" x heading (n,t) = text lvl <> curlies (text t) where lvl = case n of 0 -> "\\section" 1 -> "\\subsection" 2 -> "\\subsubsection" _ -> error "*** section level > 3" txt (dec,t) = let t' = text t in case dec of Plain -> t' Emph -> text "\\emph" <> curlies t' Code -> text "\\verb#" <> t' <> char '#' Math -> char '$' <> t' <> char '$' list = cmd "itemize" . vcat item i = text "\\item" <+> i par t = text "\n" $$ t code = cmd "verbatim" . vcat . map text
forste/haReFork
tools/hs2html/MyDoc2Latex.hs
bsd-3-clause
1,019
0
12
359
387
195
192
32
4
import Control.Concurrent.STM (STM, TVar, newTVar, readTVar, writeTVar, retry, atomically) -- <<TChan data TChan a = TChan (TVar (TVarList a)) (TVar (TVarList a)) type TVarList a = TVar (TList a) data TList a = TNil | TCons a (TVarList a) newTChan :: STM (TChan a) newTChan = do hole <- newTVar TNil read <- newTVar hole write <- newTVar hole return (TChan read write) readTChan :: TChan a -> STM a readTChan (TChan readVar _) = do listHead <- readTVar readVar head <- readTVar listHead case head of TNil -> retry TCons val tail -> do writeTVar readVar tail return val writeTChan :: TChan a -> a -> STM () writeTChan (TChan _ writeVar) a = do newListEnd <- newTVar TNil listEnd <- readTVar writeVar writeTVar writeVar newListEnd writeTVar listEnd (TCons a newListEnd) -- >> -- <<dupTChan dupTChan :: TChan a -> STM (TChan a) dupTChan (TChan _ writeVar) = do hole <- readTVar writeVar newReadVar <- newTVar hole return (TChan newReadVar writeVar) -- >> -- <<unGetTChan unGetTChan :: TChan a -> a -> STM () unGetTChan (TChan readVar _) a = do listHead <- readTVar readVar newHead <- newTVar (TCons a listHead) writeTVar readVar newHead -- >> -- <<isEmptyTChan isEmptyTChan :: TChan a -> STM Bool isEmptyTChan (TChan read _write) = do listhead <- readTVar read head <- readTVar listhead case head of TNil -> return True TCons _ _ -> return False -- >> main = do c <- atomically $ newTChan atomically $ writeTChan c 'a' atomically (readTChan c) >>= print atomically (isEmptyTChan c) >>= print atomically $ unGetTChan c 'a' atomically (isEmptyTChan c) >>= print atomically (readTChan c) >>= print c2 <- atomically $ dupTChan c atomically $ writeTChan c 'b' atomically (readTChan c) >>= print atomically (readTChan c2) >>= print
prt2121/haskell-practice
parconc/TChan.hs
apache-2.0
1,850
0
12
421
735
344
391
55
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE BangPatterns, NoImplicitPrelude #-} -- Copyright (c) 2008, Ralf Hinze -- 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. -- -- * The names of the contributors may not 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 OWNER 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. -- | A /priority search queue/ (henceforth /queue/) efficiently -- supports the operations of both a search tree and a priority queue. -- An 'Elem'ent is a product of a key, a priority, and a -- value. Elements can be inserted, deleted, modified and queried in -- logarithmic time, and the element with the least priority can be -- retrieved in constant time. A queue can be built from a list of -- elements, sorted by keys, in linear time. -- -- This implementation is due to Ralf Hinze with some modifications by -- Scott Dillard and Johan Tibell. -- -- * Hinze, R., /A Simple Implementation Technique for Priority Search -- Queues/, ICFP 2001, pp. 110-121 -- -- <http://citeseer.ist.psu.edu/hinze01simple.html> module GHC.Event.PSQ ( -- * Binding Type Elem(..) , Key , Prio -- * Priority Search Queue Type , PSQ -- * Query , size , null , lookup -- * Construction , empty , singleton -- * Insertion , insert -- * Delete/Update , delete , adjust -- * Conversion , toList , toAscList , toDescList , fromList -- * Min , findMin , deleteMin , minView , atMost ) where import GHC.Base hiding (empty) import GHC.Num (Num(..)) import GHC.Show (Show(showsPrec)) import GHC.Event.Unique (Unique) -- | @E k p@ binds the key @k@ with the priority @p@. data Elem a = E { key :: {-# UNPACK #-} !Key , prio :: {-# UNPACK #-} !Prio , value :: a } deriving (Eq, Show) ------------------------------------------------------------------------ -- | A mapping from keys @k@ to priorites @p@. type Prio = Double type Key = Unique data PSQ a = Void | Winner {-# UNPACK #-} !(Elem a) !(LTree a) {-# UNPACK #-} !Key -- max key deriving (Eq, Show) -- | /O(1)/ The number of elements in a queue. size :: PSQ a -> Int size Void = 0 size (Winner _ lt _) = 1 + size' lt -- | /O(1)/ True if the queue is empty. null :: PSQ a -> Bool null Void = True null (Winner _ _ _) = False -- | /O(log n)/ The priority and value of a given key, or Nothing if -- the key is not bound. lookup :: Key -> PSQ a -> Maybe (Prio, a) lookup k q = case tourView q of Null -> Nothing Single (E k' p v) | k == k' -> Just (p, v) | otherwise -> Nothing tl `Play` tr | k <= maxKey tl -> lookup k tl | otherwise -> lookup k tr ------------------------------------------------------------------------ -- Construction empty :: PSQ a empty = Void -- | /O(1)/ Build a queue with one element. singleton :: Key -> Prio -> a -> PSQ a singleton k p v = Winner (E k p v) Start k ------------------------------------------------------------------------ -- Insertion -- | /O(log n)/ Insert a new key, priority and value in the queue. If -- the key is already present in the queue, the associated priority -- and value are replaced with the supplied priority and value. insert :: Key -> Prio -> a -> PSQ a -> PSQ a insert k p v q = case q of Void -> singleton k p v Winner (E k' p' v') Start _ -> case compare k k' of LT -> singleton k p v `play` singleton k' p' v' EQ -> singleton k p v GT -> singleton k' p' v' `play` singleton k p v Winner e (RLoser _ e' tl m tr) m' | k <= m -> insert k p v (Winner e tl m) `play` (Winner e' tr m') | otherwise -> (Winner e tl m) `play` insert k p v (Winner e' tr m') Winner e (LLoser _ e' tl m tr) m' | k <= m -> insert k p v (Winner e' tl m) `play` (Winner e tr m') | otherwise -> (Winner e' tl m) `play` insert k p v (Winner e tr m') ------------------------------------------------------------------------ -- Delete/Update -- | /O(log n)/ Delete a key and its priority and value from the -- queue. When the key is not a member of the queue, the original -- queue is returned. delete :: Key -> PSQ a -> PSQ a delete k q = case q of Void -> empty Winner (E k' p v) Start _ | k == k' -> empty | otherwise -> singleton k' p v Winner e (RLoser _ e' tl m tr) m' | k <= m -> delete k (Winner e tl m) `play` (Winner e' tr m') | otherwise -> (Winner e tl m) `play` delete k (Winner e' tr m') Winner e (LLoser _ e' tl m tr) m' | k <= m -> delete k (Winner e' tl m) `play` (Winner e tr m') | otherwise -> (Winner e' tl m) `play` delete k (Winner e tr m') -- | /O(log n)/ Update a priority at a specific key with the result -- of the provided function. When the key is not a member of the -- queue, the original queue is returned. adjust :: (Prio -> Prio) -> Key -> PSQ a -> PSQ a adjust f k q0 = go q0 where go q = case q of Void -> empty Winner (E k' p v) Start _ | k == k' -> singleton k' (f p) v | otherwise -> singleton k' p v Winner e (RLoser _ e' tl m tr) m' | k <= m -> go (Winner e tl m) `unsafePlay` (Winner e' tr m') | otherwise -> (Winner e tl m) `unsafePlay` go (Winner e' tr m') Winner e (LLoser _ e' tl m tr) m' | k <= m -> go (Winner e' tl m) `unsafePlay` (Winner e tr m') | otherwise -> (Winner e' tl m) `unsafePlay` go (Winner e tr m') {-# INLINE adjust #-} ------------------------------------------------------------------------ -- Conversion -- | /O(n*log n)/ Build a queue from a list of key/priority/value -- tuples. If the list contains more than one priority and value for -- the same key, the last priority and value for the key is retained. fromList :: [Elem a] -> PSQ a fromList = foldr (\(E k p v) q -> insert k p v q) empty -- | /O(n)/ Convert to a list of key/priority/value tuples. toList :: PSQ a -> [Elem a] toList = toAscList -- | /O(n)/ Convert to an ascending list. toAscList :: PSQ a -> [Elem a] toAscList q = seqToList (toAscLists q) toAscLists :: PSQ a -> Sequ (Elem a) toAscLists q = case tourView q of Null -> emptySequ Single e -> singleSequ e tl `Play` tr -> toAscLists tl <> toAscLists tr -- | /O(n)/ Convert to a descending list. toDescList :: PSQ a -> [ Elem a ] toDescList q = seqToList (toDescLists q) toDescLists :: PSQ a -> Sequ (Elem a) toDescLists q = case tourView q of Null -> emptySequ Single e -> singleSequ e tl `Play` tr -> toDescLists tr <> toDescLists tl ------------------------------------------------------------------------ -- Min -- | /O(1)/ The element with the lowest priority. findMin :: PSQ a -> Maybe (Elem a) findMin Void = Nothing findMin (Winner e _ _) = Just e -- | /O(log n)/ Delete the element with the lowest priority. Returns -- an empty queue if the queue is empty. deleteMin :: PSQ a -> PSQ a deleteMin Void = Void deleteMin (Winner _ t m) = secondBest t m -- | /O(log n)/ Retrieve the binding with the least priority, and the -- rest of the queue stripped of that binding. minView :: PSQ a -> Maybe (Elem a, PSQ a) minView Void = Nothing minView (Winner e t m) = Just (e, secondBest t m) secondBest :: LTree a -> Key -> PSQ a secondBest Start _ = Void secondBest (LLoser _ e tl m tr) m' = Winner e tl m `play` secondBest tr m' secondBest (RLoser _ e tl m tr) m' = secondBest tl m `play` Winner e tr m' -- | /O(r*(log n - log r))/ Return a list of elements ordered by -- key whose priorities are at most @pt@. atMost :: Prio -> PSQ a -> ([Elem a], PSQ a) atMost pt q = let (sequ, q') = atMosts pt q in (seqToList sequ, q') atMosts :: Prio -> PSQ a -> (Sequ (Elem a), PSQ a) atMosts !pt q = case q of (Winner e _ _) | prio e > pt -> (emptySequ, q) Void -> (emptySequ, Void) Winner e Start _ -> (singleSequ e, Void) Winner e (RLoser _ e' tl m tr) m' -> let (sequ, q') = atMosts pt (Winner e tl m) (sequ', q'') = atMosts pt (Winner e' tr m') in (sequ <> sequ', q' `play` q'') Winner e (LLoser _ e' tl m tr) m' -> let (sequ, q') = atMosts pt (Winner e' tl m) (sequ', q'') = atMosts pt (Winner e tr m') in (sequ <> sequ', q' `play` q'') ------------------------------------------------------------------------ -- Loser tree type Size = Int data LTree a = Start | LLoser {-# UNPACK #-} !Size {-# UNPACK #-} !(Elem a) !(LTree a) {-# UNPACK #-} !Key -- split key !(LTree a) | RLoser {-# UNPACK #-} !Size {-# UNPACK #-} !(Elem a) !(LTree a) {-# UNPACK #-} !Key -- split key !(LTree a) deriving (Eq, Show) size' :: LTree a -> Size size' Start = 0 size' (LLoser s _ _ _ _) = s size' (RLoser s _ _ _ _) = s left, right :: LTree a -> LTree a left Start = moduleError "left" "empty loser tree" left (LLoser _ _ tl _ _ ) = tl left (RLoser _ _ tl _ _ ) = tl right Start = moduleError "right" "empty loser tree" right (LLoser _ _ _ _ tr) = tr right (RLoser _ _ _ _ tr) = tr maxKey :: PSQ a -> Key maxKey Void = moduleError "maxKey" "empty queue" maxKey (Winner _ _ m) = m lloser, rloser :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lloser k p v tl m tr = LLoser (1 + size' tl + size' tr) (E k p v) tl m tr rloser k p v tl m tr = RLoser (1 + size' tl + size' tr) (E k p v) tl m tr ------------------------------------------------------------------------ -- Balancing -- | Balance factor omega :: Int omega = 4 lbalance, rbalance :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lbalance k p v l m r | size' l + size' r < 2 = lloser k p v l m r | size' r > omega * size' l = lbalanceLeft k p v l m r | size' l > omega * size' r = lbalanceRight k p v l m r | otherwise = lloser k p v l m r rbalance k p v l m r | size' l + size' r < 2 = rloser k p v l m r | size' r > omega * size' l = rbalanceLeft k p v l m r | size' l > omega * size' r = rbalanceRight k p v l m r | otherwise = rloser k p v l m r lbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lbalanceLeft k p v l m r | size' (left r) < size' (right r) = lsingleLeft k p v l m r | otherwise = ldoubleLeft k p v l m r lbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lbalanceRight k p v l m r | size' (left l) > size' (right l) = lsingleRight k p v l m r | otherwise = ldoubleRight k p v l m r rbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rbalanceLeft k p v l m r | size' (left r) < size' (right r) = rsingleLeft k p v l m r | otherwise = rdoubleLeft k p v l m r rbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rbalanceRight k p v l m r | size' (left l) > size' (right l) = rsingleRight k p v l m r | otherwise = rdoubleRight k p v l m r lsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) | p1 <= p2 = lloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3 | otherwise = lloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3 lsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) = rloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3 lsingleLeft _ _ _ _ _ _ = moduleError "lsingleLeft" "malformed tree" rsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) = rloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3 rsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) = rloser k2 p2 v2 (rloser k1 p1 v1 t1 m1 t2) m2 t3 rsingleLeft _ _ _ _ _ _ = moduleError "rsingleLeft" "malformed tree" lsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a lsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lloser k2 p2 v2 t1 m1 (lloser k1 p1 v1 t2 m2 t3) lsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3) lsingleRight _ _ _ _ _ _ = moduleError "lsingleRight" "malformed tree" rsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3) rsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 | p1 <= p2 = rloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3) | otherwise = rloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3) rsingleRight _ _ _ _ _ _ = moduleError "rsingleRight" "malformed tree" ldoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a ldoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) = lsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3) ldoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) = lsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3) ldoubleLeft _ _ _ _ _ _ = moduleError "ldoubleLeft" "malformed tree" ldoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a ldoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3 ldoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = lsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3 ldoubleRight _ _ _ _ _ _ = moduleError "ldoubleRight" "malformed tree" rdoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rdoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) = rsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3) rdoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) = rsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3) rdoubleLeft _ _ _ _ _ _ = moduleError "rdoubleLeft" "malformed tree" rdoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a rdoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = rsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3 rdoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 = rsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3 rdoubleRight _ _ _ _ _ _ = moduleError "rdoubleRight" "malformed tree" -- | Take two pennants and returns a new pennant that is the union of -- the two with the precondition that the keys in the first tree are -- strictly smaller than the keys in the second tree. play :: PSQ a -> PSQ a -> PSQ a Void `play` t' = t' t `play` Void = t Winner e@(E k p v) t m `play` Winner e'@(E k' p' v') t' m' | p <= p' = Winner e (rbalance k' p' v' t m t') m' | otherwise = Winner e' (lbalance k p v t m t') m' {-# INLINE play #-} -- | A version of 'play' that can be used if the shape of the tree has -- not changed or if the tree is known to be balanced. unsafePlay :: PSQ a -> PSQ a -> PSQ a Void `unsafePlay` t' = t' t `unsafePlay` Void = t Winner e@(E k p v) t m `unsafePlay` Winner e'@(E k' p' v') t' m' | p <= p' = Winner e (rloser k' p' v' t m t') m' | otherwise = Winner e' (lloser k p v t m t') m' {-# INLINE unsafePlay #-} data TourView a = Null | Single {-# UNPACK #-} !(Elem a) | (PSQ a) `Play` (PSQ a) tourView :: PSQ a -> TourView a tourView Void = Null tourView (Winner e Start _) = Single e tourView (Winner e (RLoser _ e' tl m tr) m') = Winner e tl m `Play` Winner e' tr m' tourView (Winner e (LLoser _ e' tl m tr) m') = Winner e' tl m `Play` Winner e tr m' ------------------------------------------------------------------------ -- Utility functions moduleError :: String -> String -> a moduleError fun msg = error ("GHC.Event.PSQ." ++ fun ++ ':' : ' ' : msg) {-# NOINLINE moduleError #-} ------------------------------------------------------------------------ -- Hughes's efficient sequence type newtype Sequ a = Sequ ([a] -> [a]) emptySequ :: Sequ a emptySequ = Sequ (\as -> as) singleSequ :: a -> Sequ a singleSequ a = Sequ (\as -> a : as) (<>) :: Sequ a -> Sequ a -> Sequ a Sequ x1 <> Sequ x2 = Sequ (\as -> x1 (x2 as)) infixr 5 <> seqToList :: Sequ a -> [a] seqToList (Sequ x) = x [] instance Show a => Show (Sequ a) where showsPrec d a = showsPrec d (seqToList a)
beni55/haste-compiler
libraries/ghc-7.10/base/GHC/Event/PSQ.hs
bsd-3-clause
18,076
0
14
5,064
6,445
3,230
3,215
304
6
module A070 where
siddhanathan/ghc
testsuite/tests/driver/A070.hs
bsd-3-clause
18
0
2
3
4
3
1
1
0
{-# LANGUAGE DataKinds, MultiParamTypeClasses, FunctionalDependencies, TypeOperators, PolyKinds, TypeFamilies, FlexibleInstances, ScopedTypeVariables, UndecidableInstances, DefaultSignatures, FlexibleContexts, InstanceSigs #-} {-# OPTIONS_HADDOCK prune #-} module Data.MFoldable where import Data.MGeneric import Data.Unapply import Data.HList import Data.Proxy import Data.Nat import Unsafe.Coerce import Data.Monoid -- | > MonoidMap as m ~ Map (\a -> (a -> m)) as type family MonoidMap as m where MonoidMap '[] m = '[] MonoidMap (a ': as) m = (a -> m) ': MonoidMap as m -- | `MFoldable` type class, generalisation of `Data.Foldable.Foldable`, `Data.Bifoldable.Bifoldable`, etc. -- -- >>> instance MFoldable (,,) '[a, b, c] -- >>> mfoldMap (Sum `HCons` (Sum . length) `HCons` const mempty `HCons` HNil) (1, "foobar", 5) = 7 class MFoldable (f :: k) (as :: [*]) | as -> k where -- | see `mfoldMap` mfoldMapP :: Monoid m => Proxy f -> Proxy as -> HList (MonoidMap as m) -> f :$: as -> m default mfoldMapP :: (MGeneric (f :$: as), as ~ Pars (f :$: as), GMFoldable (Rep (f :$: as)) as, Monoid m ) => Proxy f -> Proxy as -> HList (MonoidMap as m) -> f :$: as -> m mfoldMapP _ _ fs = mfoldMapG fs . from -- | Map elements of each parameter type of a structure to a monoid, and combine the results. -- -- Proxy-less version of `mfoldMapP` -- -- > mfoldMap :: HList '[a1 -> m, ..., an -> m] -> f :$: '[a1, ..., an] -> m mfoldMap :: forall m a f as. ( Monoid m, Unapply a f as, MFoldable f as ) => HList (MonoidMap as m) -> a -> m mfoldMap = mfoldMapP (Proxy :: Proxy f) (Proxy :: Proxy as) class Repeat m as where repeatId :: Proxy m -> Proxy as -> HList (MonoidMap as m) instance Repeat m '[] where repeatId _ _ = HNil instance Repeat m as => Repeat m (m ': as) where repeatId pm _ = HCons id (repeatId pm (Proxy :: Proxy as)) -- | Combine the elements of a structure when all its parameters are the same monoid. mfold :: forall m f as a. ( Monoid m, Repeat m as, MFoldable f as, Unapply a f as ) => a -> m mfold = mfoldMap (repeatId (Proxy :: Proxy m) (Proxy :: Proxy as)) -- Generics class GMFoldable (f :: Un *) (as :: [*]) where mfoldMapG :: Monoid m => HList (MonoidMap as m) -> In f as -> m instance GMFoldable UV fs where mfoldMapG _ _ = undefined instance GMFoldable UT fs where mfoldMapG _ InT = mempty instance (GMFoldable u as, GMFoldable v as) => GMFoldable (u :++: v) as where mfoldMapG fs (InL u) = mfoldMapG fs u mfoldMapG fs (InR v) = mfoldMapG fs v instance (GMFoldable u as, GMFoldable v as) => GMFoldable (u :**: v) as where mfoldMapG fs (u :*: v) = mfoldMapG fs u `mappend` mfoldMapG fs v instance GFMFoldable f as => GMFoldable (UF f) as where mfoldMapG fs (InF f) = mfoldMapGF fs f class GFMFoldable (f :: Field *) (as :: [*]) where mfoldMapGF :: Monoid m => HList (MonoidMap as m) -> InField f as -> m instance GFMFoldable (FK a) as where mfoldMapGF fs (InK _) = mempty instance GFPMFoldable n as => GFMFoldable (FP n) as where mfoldMapGF fs (InP a) = mfoldMapGFP (Proxy :: Proxy n) (Proxy :: Proxy as) fs a class GFPMFoldable n as where mfoldMapGFP :: Monoid m => Proxy n -> Proxy as -> HList (MonoidMap as m) -> as :!: n -> m instance GFPMFoldable NZ (a ': as) where mfoldMapGFP _ _ (HCons f _) = f instance GFPMFoldable n as => GFPMFoldable (NS n) (a ': as) where mfoldMapGFP _ p (HCons _ fs) = mfoldMapGFP (Proxy :: Proxy n) (Proxy :: Proxy as) fs class AdaptFieldMonoid (f :: [Field *]) (as :: [*]) where adaptFieldMonoid :: Monoid m => Proxy f -> Proxy as -> Proxy m -> HList (MonoidMap as m) -> HList (MonoidMap (ExpandFields f as) m) instance AdaptFieldMonoid '[] fs where adaptFieldMonoid _ _ _ fs = HNil instance AdaptFieldMonoid as fs => AdaptFieldMonoid (FK a ': as) fs where adaptFieldMonoid _ pf pm fs = HCons (const mempty) (adaptFieldMonoid (Proxy :: Proxy as) pf pm fs) instance (GFPMFoldable n fs, AdaptFieldMonoid as fs) => AdaptFieldMonoid (FP n ': as) fs where adaptFieldMonoid _ pf pm fs = HCons (mfoldMapGFP (Proxy :: Proxy n) (Proxy :: Proxy fs) fs) (adaptFieldMonoid (Proxy :: Proxy as) pf pm fs) instance (MFoldable f (ExpandFields bs fs), AdaptFieldMonoid bs fs, AdaptFieldMonoid as fs) => AdaptFieldMonoid ((f :@: bs) ': as) fs where adaptFieldMonoid _ pf pm fs = HCons (mfoldMapP (Proxy :: Proxy f) (Proxy :: Proxy (ExpandFields bs fs)) (adaptFieldMonoid (Proxy :: Proxy bs) pf pm fs)) (adaptFieldMonoid (Proxy :: Proxy as) pf pm fs) instance (MFoldable f (ExpandFields as bs), AdaptFieldMonoid as bs) => GFMFoldable (f :@: as) bs where mfoldMapGF :: forall m. Monoid m => HList (MonoidMap bs m) -> InField (f :@: as) bs -> m mfoldMapGF fs (InA a) = mfoldMapP (Proxy :: Proxy f) (Proxy :: Proxy (ExpandFields as bs)) (adaptFieldMonoid (Proxy :: Proxy as) (Proxy :: Proxy bs) (Proxy :: Proxy m) fs) (unsafeCoerce a)
RafaelBocquet/haskell-mgeneric
src/Data/MFoldable.hs
mit
5,165
0
16
1,280
1,922
990
932
80
1
module VirtualMachine where import Data.Char (chr) import Data.List (findIndices) import MachineCode -- Machine Internals type MemValue = Int data Machine = Machine { prog :: ([Instruction], [Instruction]), stack :: [MemValue], st :: Int, lb :: Int } deriving Show -- Instruction Execution Functions nextInst :: Machine -> (Maybe Instruction, Machine) nextInst (Machine {prog = (ps, []), stack = s, st = st, lb = lb}) = (Nothing, Machine {prog = (ps, []), stack = s, st = st, lb = lb}) nextInst (Machine {prog = (ps, i:ns), stack = s, st = st, lb = lb}) = (Just i, (Machine {prog = (i:ps, ns), stack = s, st = st, lb = lb})) pushValueToStack :: Int -> Machine -> Machine pushValueToStack n (Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) = Machine {prog = (ps, ns), stack = n:s, st = (st+1), lb = lb} pushAddressToStack :: Register -> Int -> Machine -> Machine pushAddressToStack r i m@(Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) = Machine {prog = (ps, ns), stack = (calculateAddress r i m):s, st = (st+1), lb = lb} retrieveValueAtAddress :: Register -> Int -> Machine -> Machine retrieveValueAtAddress r i (Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) = case r of SB -> (Machine {prog = (ps, ns), stack = (getStackElement s i):s, st = (st+1), lb = lb}) LB -> (Machine {prog = (ps, ns), stack = (getStackElement s (i+lb)):s, st = (st+1), lb = lb}) ST -> (Machine {prog = (ps, ns), stack = (getStackElement s (i+st)):s, st = (st+1), lb = lb}) getStackElement :: [MemValue] -> Int -> MemValue getStackElement [] i = error "Error: There is nothing in memory to retrieve" getStackElement s i | i < 0 = error "Error: Memory address evaluates to a negative number" getStackElement s i | (length s - 1) < i = error $ "Error: There is no element at " ++ (show i) getStackElement s i = s !! ((length s) - i - 1) storeValueToAddress :: Register -> Int -> Machine -> Machine storeValueToAddress r i (Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) = case r of SB -> (Machine {prog = (ps, ns), stack = (storeValueAt s i), st = (st-1), lb = lb}) LB -> (Machine {prog = (ps, ns), stack = (storeValueAt s (i+lb)), st = (st-1), lb = lb}) ST -> (Machine {prog = (ps, ns), stack = (storeValueAt s (i+st)), st = (st-1), lb = lb}) where storeValueAt :: [MemValue] -> Int -> [MemValue] storeValueAt [] _ = error "Error: There is no value to pop from the stack" storeValueAt s i | i < 0 = error "Error: Memory address evaluates to a negative number" storeValueAt ss i | (length ss - 1) < i = error $ "Error: There is no element at " ++ (show i) storeValueAt (s:ss) i = let (s1, _:s2) = splitAt ((length ss) - i - 1) ss in s1 ++ (s:s2) performBinaryOperation :: (Int -> Int -> Int) -> Machine -> Machine performBinaryOperation op (Machine {stack = []}) = error "Error: Stack is empty, cannot perform operation" performBinaryOperation op (Machine {stack = s:[]}) = error "Error: Not enough items on the stack, cannot perform operation" performBinaryOperation op (Machine {prog = (ps, ns), stack = s1:s2:ss, st = st, lb = lb}) = Machine {prog = (ps, ns), stack = (s1 `op` s2):ss, st = (st - 1), lb = lb} popFromStack :: Int -> Int -> Machine -> Machine popFromStack i j (Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) | length s < i + j = error "Error: POP operation would run off the bottom of the stack" | length s >= i + j = Machine {prog = (ps, ns), stack = s', st = st - j, lb = lb} where s' = let (fs, ss) = splitAt i s in fs ++ (drop j ss) jumpTo :: Label -> Machine -> Machine jumpTo l m@(Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) | numberMatches l m < 1 = error $ "Error: There is no label called " ++ l | numberMatches l m > 1 = error $ "Error: There is more than one label called " ++ l | numberMatches l m == 1 = (Machine {prog = (resetAtLabel l ((reverse ps) ++ ns)), stack = s, st = st, lb = lb}) where numberMatches :: Label -> Machine -> Int numberMatches l (Machine {prog = (ps, ns)}) = length $ findIndices (labelMatch l) (ps ++ ns) maybeJump :: Bool -> Label -> Machine -> Machine maybeJump onzero l m@(Machine {stack = s}) = case s of [] -> error "Error: Stack is empty, cannot perform conditional jump" s:ss -> if onzero == (s == 0) then jumpTo l m else m callFunction :: Label -> Machine -> Machine callFunction l m@(Machine {prog = (ps, ns), st = st, lb = lb}) = let (Machine {prog = (ps', ns'), stack = s}) = jumpTo l m in Machine {prog = (ps', ns'), stack = (ra:dl:s), st = st + 2, lb = st + 1} where ra = length ps dl = lb returnFromFunction :: Int -> Int -> Machine -> Machine returnFromFunction r a m@(Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) | length s < 2+r+a = error $ "Error: Not enough values on the stack to complete the RETURN" | length s >= 2+r+a = let dl = getStackElement s lb in let ra = getStackElement s (lb+1) in Machine { prog = resetAtRA ra (ps, ns), stack = removeArgs r a lb s, st = lb - a + r - 1, lb = dl } resetAtRA :: Int -> ([Instruction], [Instruction]) -> ([Instruction], [Instruction]) resetAtRA ra (ps, ns) = let (ps', ns') = splitAt ra ((reverse ps) ++ ns) in (reverse ps', ns') removeArgs :: Int -> Int -> Int -> [MemValue] -> [MemValue] removeArgs returns args lb s = let (record, rest) = splitAt ((length s) - lb) s in ((take returns record) ++ (drop args rest)) -- Control Flow Functions runCode :: Bool -> [Instruction] -> IO () runCode t is = let m = initialiseMachine is in do putStrLn "Executing Compiled Code:" runMachine t m runMachine :: Bool -> Machine -> IO () runMachine t m@(Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) = let (i, m') = nextInst m in do maybePrint t $ "Current Stack: " ++ (show s) ++ ", ST: " ++ (show st) ++ ", LB: " ++ (show lb) ++ "\n" case i of Nothing -> putStrLn "Execution Complete" Just HALT -> putStrLn "Execution Terminated by HALT" Just (LABEL l) -> do maybePrint t $ "Label \"" ++ l ++ "\": (No Action)" runMachine t m' Just i' -> do maybePrint t $ "Next Instruction: " ++ (show i') executeInstruction t i' m' executeInstruction :: Bool -> Instruction -> Machine -> IO () executeInstruction t (LOADL v) m = let m' = pushValueToStack v m in runMachine t m' executeInstruction t (LOADA r i) m = let m' = pushAddressToStack r i m in runMachine t m' executeInstruction t (LOAD r i) m = let m' = retrieveValueAtAddress r i m in runMachine t m' executeInstruction t (STORE r i) m = let m' = storeValueToAddress r i m in runMachine t m' executeInstruction t ADD m = let m' = performBinaryOperation (+) m in runMachine t m' executeInstruction t SUB m = let m' = performBinaryOperation (-) m in runMachine t m' executeInstruction t MULT m = let m' = performBinaryOperation (*) m in runMachine t m' executeInstruction t DIV m = let m' = performBinaryOperation div m in runMachine t m' executeInstruction t MOD m = let m' = performBinaryOperation mod m in runMachine t m' executeInstruction t EQUALS m = let m' = performBinaryOperation numericEQ m in runMachine t m' executeInstruction t NOT_EQ m = let m' = performBinaryOperation mod m in runMachine t m' executeInstruction t OR m = let m' = performBinaryOperation (numericLogical (||)) m in runMachine t m' executeInstruction t AND m = let m' = performBinaryOperation (numericLogical (&&)) m in runMachine t m' executeInstruction t LESS_THAN m = let m' = performBinaryOperation numericLT m in runMachine t m' executeInstruction t GREATER_THAN m = let m' = performBinaryOperation numericGT m in runMachine t m' executeInstruction t LT_OR_EQ m = let m' = performBinaryOperation numericLTE m in runMachine t m' executeInstruction t GT_OR_EQ m = let m' = performBinaryOperation numericGTE m in runMachine t m' executeInstruction t (POP i j) m = let m' = popFromStack i j m in runMachine t m' executeInstruction t (JUMP l) m = let m' = jumpTo l m in runMachine t m' executeInstruction t (JUMPIFZ l) m = let m' = maybeJump True l m in runMachine t m' executeInstruction t (JUMPIFNZ l) m = let m' = maybeJump False l m in runMachine t m' executeInstruction t (CALL l) m = let m' = callFunction l m in runMachine t m' executeInstruction t (RETURN i j) m = let m' = returnFromFunction i j m in runMachine t m' executeInstruction t PRINTC (Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) = case s of [] -> error "Error: Stack is empty, nothing to print" i:ss -> do putStr [chr i] runMachine t (Machine {prog = (ps, ns), stack = ss, st = st - 1, lb = lb}) executeInstruction t PRINTI (Machine {prog = (ps, ns), stack = s, st = st, lb = lb}) = case s of [] -> error "Error: Stack is empty, nothing to print" i:ss -> do putStr $ show i runMachine t (Machine {prog = (ps, ns), stack = ss, st = st - 1, lb = lb}) -- Misc Helper Functions initialiseMachine :: [Instruction] -> Machine initialiseMachine is = (Machine {prog = ([], is), stack = [], st = -1, lb = 0}) maybePrint :: Bool -> String -> IO () maybePrint t s = if t then putStrLn s else return () calculateAddress :: Register -> Int -> Machine -> Int calculateAddress r i m = case r of SB -> i; LB -> (st m) + i; ST -> (st m) + i labelMatch :: Label -> Instruction -> Bool labelMatch l (LABEL s) = s == l labelMatch _ _ = False resetAtLabel :: Label -> [Instruction] -> ([Instruction], [Instruction]) resetAtLabel l is = let (ps, ns) = break (labelMatch l) is in (reverse ps, ns) numericEQ :: Int -> Int -> Int numericEQ x y = if x == y then 1 else 0 numericNEQ :: Int -> Int -> Int numericNEQ x y = if x /= y then 1 else 0 numericLogical :: (Bool -> Bool -> Bool) -> Int -> Int -> Int numericLogical o x y = if (x /= 0) `o` (y /= 0) then 1 else 0 numericGT :: Int -> Int -> Int numericGT x y = if x > y then 1 else 0 numericLT :: Int -> Int -> Int numericLT x y = if x < y then 1 else 0 numericGTE :: Int -> Int -> Int numericGTE x y = if x >= y then 1 else 0 numericLTE :: Int -> Int -> Int numericLTE x y = if x <= y then 1 else 0
tombusby/dissertation
src/VirtualMachine.hs
mit
10,059
142
17
2,219
4,785
2,565
2,220
209
6
module Tokens.Tokens ( Token(..), TokenType(..), FileLoc(..), TokenLoc(..), print_tokens ) where import qualified Debug.Debug as Debug import qualified Tools.Formatting as Formatting data FileLoc = FileLoc Int Int data TokenLoc = TokenLoc FileLoc FileLoc instance Debug.DebugShow TokenLoc where debug_show (TokenLoc (FileLoc start_line start_char) (FileLoc end_line end_char)) = "line: " ++ Formatting.prefix_spaces (show start_line) 3 ++ " char: " ++ Formatting.prefix_spaces (show start_char) 3 ++ " to line: " ++ Formatting.prefix_spaces (show end_line) 3 ++ " char: " ++ Formatting.prefix_spaces (show end_char) 3 instance Show TokenLoc where show (TokenLoc (FileLoc start_line start_char) (FileLoc end_line end_char)) = "(" ++ (show start_line) ++ ":" ++ (show start_char) ++ ") - (" ++ (show end_line) ++ ":" ++ (show end_char) ++ ")" data Token = Token TokenType String TokenLoc data TokenType = IntLiteral | BoolLiteral | NullLiteral | IfLiteral | LambdaLiteral | MemberLiteral | VarLiteral | FunctionLiteral | TypeLiteral | StructLiteral | PackageLiteral | String_ | Type | Colon | LParen | RParen | LBracket | RBracket deriving (Show, Eq) print_tokens :: [Token] -> String print_tokens tokens = case tokens of [] -> "" (current: rest) -> (Debug.debug_show current) ++ "\n" ++ print_tokens rest instance Debug.DebugShow Token where debug_show (Token token_type string file_info) = Formatting.postfix_spaces string 15 ++ " (" ++ Formatting.postfix_spaces (show token_type ++ ")") 20 ++ " at " ++ Debug.debug_show file_info instance Show Token where show (Token token_type string file_info) = Formatting.postfix_spaces string 15 ++ " (" ++ Formatting.postfix_spaces (show token_type ++ ")") 20 ++ " at " ++ show file_info
quintenpalmer/fresh
haskell/src/Tokens/Tokens.hs
mit
1,987
0
15
506
583
310
273
58
2
module Graphics.Urho3D.Graphics.Internal.Drawable( Drawable , PODVectorDrawablePtr , VectorSourceBatch , vectorSourceBatchCntx , SourceBatch(..) , HasDistance(..) , HasGeometry(..) , HasMaterial(..) , HasWorldTransform(..) , HasNumWorldTransforms(..) , HasGeometryType(..) , FrameInfo(..) , HasFrameNumber(..) , HasTimeStep(..) , HasViewSize(..) , HasCamera(..) , drawableCntx ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import GHC.Generics import Control.Lens import Control.DeepSeq import qualified Data.Map as Map import Foreign import Graphics.Urho3D.Container.Vector import Graphics.Urho3D.Container.Ptr import Graphics.Urho3D.Math.Internal.Vector2 import Graphics.Urho3D.Math.Internal.Matrix3x4 import Graphics.Urho3D.Graphics.Internal.Camera import Graphics.Urho3D.Graphics.Internal.Geometry import Graphics.Urho3D.Graphics.Internal.Material import Graphics.Urho3D.Graphics.Defs -- | Base class for visible components. data Drawable data PODVectorDrawablePtr -- | Source data for a 3D geometry draw call. data SourceBatch = SourceBatch { _sourceBatchDistance :: {-# UNPACK #-} !Float -- ^ Distance from camera , _sourceBatchGeometry :: {-# UNPACK #-} !(Ptr Geometry) -- ^ Geometry , _sourceBatchMaterial :: {-# UNPACK #-} !(SharedPtr Material) -- ^ Material , _sourceBatchWorldTransform :: {-# UNPACK #-} !(Ptr Matrix3x4) -- ^ World transform(s). For a skinned model, these are the bone transforms. , _sourceBatchNumWorldTransforms :: {-# UNPACK #-} !Word -- ^ Number of world transforms. , _sourceBatchGeometryType :: !GeometryType -- ^ Geometry type. } deriving Generic -- | Rendering frame update parameters. data FrameInfo = FrameInfo { _frameInfoFrameNumber :: {-# UNPACK #-} !Word -- ^ frame number , _frameInfoTimeStep :: {-# UNPACK #-} !Float -- ^ Time elapsed since last frame , _frameInfoViewSize :: {-# UNPACK #-} !IntVector2 -- ^ Viewport size , _frameInfoCamera :: {-# UNPACK #-} !(Ptr Camera) -- ^ Camera being used. } deriving Generic makeFields ''SourceBatch makeFields ''FrameInfo instance NFData SourceBatch where rnf SourceBatch{..} = _sourceBatchDistance `deepseq` _sourceBatchGeometry `seq` _sourceBatchMaterial `seq` _sourceBatchWorldTransform `seq` _sourceBatchNumWorldTransforms `deepseq` _sourceBatchGeometryType `deepseq` () instance NFData FrameInfo where rnf FrameInfo{..} = _frameInfoFrameNumber `deepseq` _frameInfoTimeStep `deepseq` _frameInfoViewSize `deepseq` _frameInfoCamera `seq` () drawableCntx :: C.Context drawableCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "Drawable", [t| Drawable |]) , (C.TypeName "SourceBatch", [t| SourceBatch |]) , (C.TypeName "FrameInfo", [t| FrameInfo |]) , (C.TypeName "PODVectorDrawablePtr", [t| PODVectorDrawablePtr |]) ] } simpleVectorImpl "SourceBatch"
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Graphics/Internal/Drawable.hs
mit
2,962
0
11
450
600
389
211
-1
-1
module Y2016.M07.D20.Solution where import Control.Monad (join, (<=<)) import Data.Graph import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (maybeToList, fromJust) import Control.Logic.Frege ((<<-)) import qualified Data.MultiMap as MM import Y2016.M07.D19.Exercise (Point2d) import qualified Y2016.M07.D19.Exercise as Incomplete type Figure = Graph type FigureC = (Figure, Vertex -> (Point2d, Char, String), Char -> Maybe Vertex) lineSegments :: [(Char, Char)] -- these are the edges missing from yesterday lineSegments = zip "aaabbbggggcccddfffhhhhttjkmn" "bjfjkgkmncnpdptjkhkmntnpkmnp" -- first of all we want to convert the multimapping ('a','b'), ('a','j') to -- the mapping ('a', "bj"), etc ... multimap will help here. enqueue :: Ord a => [(a,a)] -> Map a [a] enqueue = MM.store . MM.fromList pure {-- *Y2016.M07.D20.Solution> enqueue lineSegments ~> fromList [('a',"bjf"),('b',"jkg"),('c',"npd"),('d',"pt"),('f',"jkh"), ('g',"kmnc"),('h',"kmnt"),('j',"k"),('k',"m"),('m',"n"), ('n',"p"),('t',"np")] --} -- Okay, we need to put the old-figure map and the above map into GFF. -- GFF: graph-friendly format gff :: Map Char String -> Incomplete.Figure -> [(Point2d, Char, String)] gff tree = map (\(key, pt) -> (pt, key, find key tree)) . Map.toList where find = catShift <<- Map.lookup catShift :: Maybe [a] -> [a] catShift = join . maybeToList {-- *Y2016.M07.D20.Solution> gff (enqueue lineSegments) Incomplete.figure2 ~> [((0.0,0.0),'a',"bjf"),((15.0,10.0),'b',"jkg"),((35.0,10.0),'c',"npd"), ((50.0,0.0),'d',"pt"),((15.0,-10.0),'f',"jkh"),((25.0,10.0),'g',"kmnc"), ((25.0,-10.0),'h',"kmnt"),((15.0,0.0),'j',"k"),((20.0,0.0),'k',"m"), ((25.0,0.0),'m',"n"),((30.0,0.0),'n',"p"),((35.0,0.0),'p',""), ((35.0,-10.0),'t',"np")] --} -- with this structure we can realize the graph from the vertices and edges graphit :: Incomplete.Figure -> [(Char, Char)] -> FigureC graphit fig2 = graphFromEdges . (`gff` fig2) . enqueue {-- *Y2016.M07.D20.Solution> let (fig, lookupPtf, lookupVertM) = graphit Incomplete.figure2 lineSegments *Y2016.M07.D20.Solution> fig ~> array (0,12) [(0,[1,7,4]),(1,[7,8,5]),(2,[10,11,3]),(3,[11,12]),(4,[7,8,6]), (5,[8,9,10,2]),(6,[8,9,10,12]),(7,[8]),(8,[9]),(9,[10]),(10,[11]), (11,[]),(12,[10,11])] *Y2016.M07.D20.Solution> lookupPtf 0 ~> ((0.0,0.0),'a',"bjf") --} -- Given a vertex-as-character, return all the vertices it's directly connected -- to, that is: its immediate neighbors. This is a trick(y) question as a -- connection for b is both b -> g but also a -> b, so check thoroughly! neighbors :: FigureC -> Char -> String neighbors = catShift . fmap (\(_,_,s) -> s) <<- getC getC :: FigureC -> Char -> Maybe (Point2d, Char, String) getC (_, lkPtf, lkVm) = fmap lkPtf . lkVm -- 1. What are the neighbors of 'a'? Should be "bjf" or a permutation of that. -- *Y2016.M07.D20.Solution> neighbors figc 'a' ~> "bjf" -- Did you encode your points fully? loc :: FigureC -> Char -> (Char, Point2d) loc = fromJust . fmap (\(pt, ch, _) -> (ch, pt)) <<- getC -- 2. What is the location of pt a? Should be (0,0) What is the location of b? {-- *Y2016.M07.D20.Solution> loc fig 'a' ~> ('a',(0.0,0.0)) *Y2016.M07.D20.Solution> loc fig 'b' ~> ('b',(15.0,10.0)) --} -- connections: All the points in this figure are (somehow) connected. But how? connection :: Figure -> Char -> Char -> String connection fig from to = undefined -- so breath-first-search on the forest rooted at 'a'? (forest-of-one-tree)? -- maybe a problem for tomorrow? Yeah, sounds right. -- There are many paths from, e.g. 'a' to 'c' ... pick one of them. Shortest -- would be nice but not necessary. Should be "abgc"-ish {-- And we have something like a definition to connection with: *Y2016.M07.D20.Solution> let (g,pf,vf) = fig *Y2016.M07.D20.Solution> vf 'a' ~> Just 0 *Y2016.M07.D20.Solution> dfs g [0] ~> [N _0_ [N _1_ [N 7 [N 8 [N 9 [N 10 [N 11 []]]]], N _5_ [N _2_ [N 3 [N 12 []]]]], N 4 [N 6 []]]] and we see that *Y2016.M07.D20.Solution> pf 1 ~> ((15.0,10.0),'b',"jkg") *Y2016.M07.D20.Solution> pf 5 ~> ((25.0,10.0),'g',"kmnc") *Y2016.M07.D20.Solution> pf 2 ~> ((35.0,10.0),'c',"npd") So we have a path (underscored) of "abgc" ... now extracting that path ... mm! --}
geophf/1HaskellADay
exercises/HAD/Y2016/M07/D20/Solution.hs
mit
4,326
0
10
714
584
352
232
-1
-1
-- Generated by protobuf-simple. DO NOT EDIT! module Types.Int64ListPacked where import Control.Applicative ((<$>)) import Prelude () import qualified Data.ProtoBufInt as PB newtype Int64ListPacked = Int64ListPacked { value :: PB.Seq PB.Int64 } deriving (PB.Show, PB.Eq, PB.Ord) instance PB.Default Int64ListPacked where defaultVal = Int64ListPacked { value = PB.defaultVal } instance PB.Mergeable Int64ListPacked where merge a b = Int64ListPacked { value = PB.merge (value a) (value b) } instance PB.Required Int64ListPacked where reqTags _ = PB.fromList [] instance PB.WireMessage Int64ListPacked where fieldToValue (PB.WireTag 1 PB.LenDelim) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getInt64Packed fieldToValue (PB.WireTag 1 PB.VarInt) self = (\v -> self{value = PB.append (value self) v}) <$> PB.getInt64 fieldToValue tag self = PB.getUnknown tag self messageToFields self = do PB.putInt64Packed (PB.WireTag 1 PB.LenDelim) (value self)
sru-systems/protobuf-simple
test/Types/Int64ListPacked.hs
mit
1,006
0
13
174
348
186
162
21
0
module Faker.LoremSpec where import Faker.Lorem import Helper import Prelude hiding (words) import Test.Hspec spec :: Spec spec = do describe "word" $ deterministicOutput word describe "words" $ deterministicOutput $ words 2 describe "character" $ deterministicOutput character describe "characters" $ deterministicOutput $ characters 2 describe "sentence" $ deterministicOutput sentence describe "sentences" $ deterministicOutput $ sentences 2 describe "paragraph" $ deterministicOutput paragraph describe "paragraphs" $ deterministicOutput $ paragraphs 2
gazay/faker
test/Faker/LoremSpec.hs
mit
653
0
9
163
158
72
86
22
1
-- Logistic regression model from Anglican -- (https://bitbucket.org/probprog/anglican-white-paper) module LogReg where import Control.Monad (replicateM) import Numeric.Log import Control.Monad.Bayes.Class xs :: [Double] xs = [-10, -5, 2, 6, 10] labels :: [Bool] labels = [False, False, True, True, True] logisticRegression :: (MonadInfer m) => [(Double, Bool)] -> m Double logisticRegression dat = do m <- normal 0 1 b <- normal 0 1 sigma <- gamma 1 1 let y x = normal (m * x + b) sigma sigmoid x = y x >>= \t -> return $ 1 / (1 + exp (- t)) obs x label = do p <- sigmoid x factor $ (Exp . log) $ if label then p else 1 - p mapM_ (uncurry obs) dat sigmoid 8 syntheticData :: MonadSample m => Int -> m [(Double, Bool)] syntheticData n = replicateM n syntheticPoint where syntheticPoint = do x <- uniform (-1) 1 label <- bernoulli 0.5 return (x,label)
adscib/monad-bayes
models/LogReg.hs
mit
920
0
17
224
390
204
186
26
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} import Data.Array import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as IO import Text.Parsec import Text.Parsec.Text newtype Light = Brightness Int deriving (Eq, Num, Show) type Lights = Array Coordinates Light data Instruction = Instruction Command Coordinates Coordinates deriving (Eq, Show) data Command = TurnOn | TurnOff | Toggle deriving (Eq, Show) type Coordinates = (Int, Int) lightsBounds :: (Coordinates, Coordinates) lightsBounds = ((0, 0), (999, 999)) main = do instructions <- map parseInput <$> Text.lines <$> IO.getContents let finalState = foldl (flip apply) initialState instructions let count = sum $ elems finalState print count parseInput :: Text -> Instruction parseInput text = either (error . show) id $ parse parser "" text where parser = do command <- instructionCommand space startX <- number char ',' startY <- number string " through " endX <- number char ',' endY <- number return $ Instruction command (startX, startY) (endX, endY) instructionCommand = (try (string "turn on") >> return TurnOn) <|> (try (string "turn off") >> return TurnOff) <|> (try (string "toggle") >> return Toggle) number = read <$> many1 digit initialState :: Lights initialState = listArray lightsBounds (repeat $ Brightness 0) apply :: Instruction -> Lights -> Lights apply (Instruction command start end) lights = accum (flip ($)) lights $ map (\i -> (i, decode command)) (range (start, end)) decode :: Command -> (Light -> Light) decode TurnOn (Brightness n) = Brightness $ n + 1 decode TurnOff (Brightness n) = Brightness $ max 0 (n - 1) decode Toggle (Brightness n) = Brightness $ n + 2
SamirTalwar/advent-of-code
2015/AOC_06_2.hs
mit
1,804
0
13
388
660
345
315
49
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Vaultaire.Collector.Ceilometer.Process ( processSample , process , retrieveMessage , runCollector , initState , cleanup , ackLast , module Process ) where import Control.Applicative import Control.Monad import Control.Monad.Reader import Control.Monad.State import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as L import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Data.Word import Options.Applicative hiding (Success) import System.Log.Logger import System.ZMQ4 import Marquise.Client import Vaultaire.Collector.Common.Process hiding (runCollector) import qualified Vaultaire.Collector.Common.Process as V (runCollector) import Vaultaire.Collector.Common.Types hiding (Collector) import qualified Vaultaire.Collector.Common.Types as V (Collector) import Vaultaire.Collector.Ceilometer.Process.Common as Process import Vaultaire.Collector.Ceilometer.Process.Image as Process import Vaultaire.Collector.Ceilometer.Process.Instance as Process import Vaultaire.Collector.Ceilometer.Process.IP as Process import Vaultaire.Collector.Ceilometer.Process.Snapshot as Process import Vaultaire.Collector.Ceilometer.Process.Volume as Process import Vaultaire.Collector.Ceilometer.Types parseOptions :: Parser CeilometerOptions parseOptions = CeilometerOptions <$> strOption (long "publisher-host" <> short 'H' <> metavar "HOSTNAME" <> help "ceilometer-publisher-zeromq host") <*> option auto (long "publisher-port" <> short 'p' <> value 8282 <> metavar "PORT" <> help "ceilometer-publisher-zeromq port") -- | Initialise ZMQ socket and context initState :: CollectorOpts CeilometerOptions -> IO CeilometerState initState (_, CeilometerOptions{..}) = do c <- context sock <- socket c Rep let connString = "tcp://" <> zmqHost <> ":" <> show zmqPort bind sock connString infoM "Ceilometer.Process.initState" $ "Listening to publishers at " <> connString return $ CeilometerState sock c -- | Cleans up ZMQ socket and context cleanup :: Collector () cleanup = do (_, CeilometerState{..}) <- get liftIO $ close zmqSocket liftIO $ term zmqContext -- | Core entry point for Ceilometer.Process -- Processes JSON objects from the configured publisher and -- writes out SimplePoints and SourceDicts to spool files runCollector :: IO () runCollector = V.runCollector parseOptions initState cleanup publishSamples where publishSamples = forever $ retrieveMessage >>= processSample >>= mapM_ collectData >> ackLast collectData (addr, sd, ts, p) = do collectSource addr sd collectSimple (SimplePoint addr ts p) -- | Blocking read from ceilometer-publisher-zeromq retrieveMessage :: Collector L.ByteString retrieveMessage = do (_, CeilometerState{..}) <- get liftIO $ L.fromStrict <$> receive zmqSocket -- | Ack last message received from ceilometer-publisher-zeromq ackLast :: Collector () ackLast = do (_, CeilometerState{..}) <- get liftIO $ send zmqSocket [] "" -- | Takes in a JSON Object and processes it into a list of -- (Address, SourceDict, TimeStamp, Payload) tuples processSample :: MonadIO m => L.ByteString -> V.Collector o s m [(Address, SourceDict, TimeStamp, Word64)] processSample bs = case eitherDecode bs of Left e -> do liftIO $ alertM "Ceilometer.Process.processSample" $ "Failed to parse: " <> L.unpack bs <> " Error: " <> e return [] Right m -> process m -- | Primary processing function, converts a parsed Ceilometer metric -- into a list of vaultaire SimplePoint and SourceDict data process :: MonadIO m => Metric -> V.Collector o s m [(Address, SourceDict, TimeStamp, Word64)] process m = process' (metricName m) (isEvent m) where -- Supported metrics -- We process both instance pollsters and events process' :: MonadIO m => Text -> Bool -> V.Collector o s m [(Address, SourceDict, TimeStamp, Word64)] process' "instance" False = processInstancePollster m process' "instance" True = processInstanceEvent m process' "cpu" False = processBasePollster m process' "disk.write.bytes" False = processBasePollster m process' "disk.read.bytes" False = processBasePollster m process' "network.incoming.bytes" False = processBasePollster m process' "network.outgoing.bytes" False = processBasePollster m process' "volume.size" True = processVolumeEvent m -- We process both image.size pollsters and events process' "image.size" False = processBasePollster m process' "image.size" True = processImageSizeEvent m process' "snapshot.size" True = processSnapshotSizeEvent m -- Ignored metrics -- Tracking both disk.r/w and disk.device.r/w will most likely double count process' x@"disk.device.write.bytes" y = ignore x y process' x@"disk.device.read.bytes" y = ignore x y -- We meter on bytes not requests process' x@"disk.write.requests" y = ignore x y process' x@"disk.read.requests" y = ignore x y process' x@"disk.device.write.requests" y = ignore x y process' x@"disk.device.read.requests" y = ignore x y -- We derive these from instance pollsters process' x@"disk.ephemeral.size" y@True = ignore x y process' x@"disk.root.size" y@True = ignore x y process' x@"volume" y = ignore x y process' x@"vcpus" y = ignore x y process' x@"memory" y = ignore x y -- We meter on bytes not packets process' x@"network.incoming.packets" y = ignore x y process' x@"network.outgoing.packets" y = ignore x y -- ip-allocations are currently unsupported process' x@"ip.floating" y = ignore x y process' x@"ip.floating.create" y = ignore x y process' x@"ip.floating.update" y = ignore x y process' x@"ip.floating.delete" y = ignore x y -- These seem to be linked to constructing the stack, and are not common -- We potentially care about the network/disk I/O of these ops process' x@"image" y = ignore x y process' x@"image.update" y@True = ignore x y process' x@"image.download" y@True = ignore x y process' x@"image.serve" y@True = ignore x y process' x@"image.upload" y@True = ignore x y process' x@"image.delete" y@True = ignore x y -- We care about ip allocations, these metrics are superfluous process' x@"port" y = ignore x y process' x@"port.create" y = ignore x y process' x@"port.update" y = ignore x y process' x@"port.delete" y = ignore x y process' x@"network" y = ignore x y process' x@"network.create" y = ignore x y process' x@"network.update" y = ignore x y process' x@"network.delete" y = ignore x y process' x@"subnet" y = ignore x y process' x@"subnet.create" y = ignore x y process' x@"subnet.update" y = ignore x y process' x@"subnet.delete" y = ignore x y process' x@"router" y = ignore x y process' x@"router.create" y = ignore x y process' x@"router.update" y = ignore x y process' x@"router.delete" y = ignore x y process' x@"snapshot" y = ignore x y process' x@"network.services.firewall.policy" y = ignore x y process' x y | "instance:" `T.isPrefixOf` x = ignore x y | otherwise = alert x y ignore x y = do liftIO $ infoM "Ceilometer.Process.processSample" $ "Ignored metric: " <> show x <> " event: " <> show y return [] alert x y = do liftIO $ alertM "Ceilometer.Process.processSample" $ "Unexpected metric: " <> show x <> " event: " <> show y <> "\n" <> show m return []
anchor/vaultaire-collector-ceilometer
lib/Vaultaire/Collector/Ceilometer/Process.hs
mit
9,242
0
16
3,148
2,017
1,054
963
154
53
module Language.Haskell.GHC.HappyParser ( fullStatement , fullImport , fullDeclaration , fullExpression , fullTypeSignature , fullModule ) where import Parser import SrcLoc -- compiler/hsSyn import HsSyn -- compiler/utils import OrdList -- compiler/parser import Lexer fullStatement :: P (Maybe (LStmt GhcPs (LHsExpr GhcPs))) fullStatement = parseStmt fullImport :: P (LImportDecl GhcPs) fullImport = parseImport fullDeclaration :: P (OrdList (LHsDecl GhcPs)) fullDeclaration = fmap unitOL parseDeclaration fullExpression :: P (LHsExpr GhcPs) fullExpression = parseExpression fullTypeSignature :: P (Located (OrdList (LHsDecl GhcPs))) fullTypeSignature = fmap (noLoc . unitOL) parseTypeSignature fullModule :: P (Located (HsModule GhcPs)) fullModule = parseModule
gibiansky/IHaskell
ghc-parser/src-8.4/Language/Haskell/GHC/HappyParser.hs
mit
802
0
11
131
215
119
96
24
1
module D20.Internal.Character.TalentLevel where data TalentLevel = Normal | Improved | Advanced deriving (Show,Enum)
elkorn/d20
src/D20/Internal/Character/TalentLevel.hs
mit
126
0
6
22
32
20
12
6
0
{-# LANGUAGE OverloadedStrings #-} module TitleForLink ( titleForLink ) where import Network.HTTP.Conduit import Data.Maybe import qualified Data.Text as T import qualified Data.ByteString.Lazy as B import qualified Data.ByteString.Lazy.Char8 as C import Text.HTML.TagSoup import qualified Text.Regex as R isLink :: T.Text -> Bool isLink t = isJust $ R.matchRegex urlRegex $ T.unpack t urlRegex :: R.Regex urlRegex = R.mkRegex "((https?):((//)|(\\\\\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)" titleForLink :: T.Text -> IO (Maybe T.Text) titleForLink "" = return Nothing titleForLink t = if isLink t then loadTitle t else return Nothing where loadTitle :: T.Text -> IO (Maybe T.Text) loadTitle u = do request <- simpleHttp $ T.unpack u return $ extractTitle request extractTitle :: B.ByteString -> Maybe T.Text extractTitle bs = do let tags = canonicalizeTags $ parseTags bs case takeWhile (not . isTagCloseName "title") $ dropWhile (not . isTagOpenName "title") tags of [] -> Nothing t -> Just $ T.pack $ C.unpack $ innerText t
HackerspaceBielefeld/wheatley
src/TitleForLink.hs
mit
1,235
0
13
355
344
180
164
26
2
{-# LANGUAGE DeriveTraversable, FlexibleInstances, MultiParamTypeClasses, RankNTypes, RecordWildCards #-} module Games.Ambition where import Control.Lens import Control.Monad (join) import Control.Monad.State.Strict import qualified Data.List as L import Data.Monoid (Sum(..), getSum) import Data.Maybe (fromJust) import Jatek.Interact import Jatek.Mechanic import Util.PlayingCards data PlayerId = Random | Player Int deriving (Eq, Ord, Show) pointValue :: Card -> Int pointValue (Card r s) = case s of Club -> if r == king then 18 else 0 Heart -> if r == 2 then 10 else if r > 10 then 3 else 1 Spade -> if r > 10 then 6 else 2 Diamond -> if r > 10 then 3 else 1 firstTrickValue :: Int firstTrickValue = 10 nextPos :: Int -> Int nextPos n = (n + 1 `mod` 4) -- TODO: investigate using Nat from GHC.TypeLits to get what I want for sized vectors. newtype Tup4 a = Tup4 {fromTup4 :: (a, a, a, a)} deriving (Eq, Ord, Show, Functor, Foldable, Traversable) tup4Lens :: Lens (Tup4 a) (Tup4 a) (a, a, a, a) (a, a, a, a) tup4Lens = lens fromTup4 (\_ x -> Tup4 x) instance Field1 (Tup4 a) (Tup4 a) a a where _1 = tup4Lens . _1 instance Field2 (Tup4 a) (Tup4 a) a a where _2 = tup4Lens . _2 instance Field3 (Tup4 a) (Tup4 a) a a where _3 = tup4Lens . _3 instance Field4 (Tup4 a) (Tup4 a) a a where _4 = tup4Lens . _4 data TrickState = TrickState {tsTrickNum :: Int, tsLeadPos :: Int, tsHands :: Tup4 [Card], tsTable :: Tup4 (Maybe Card)} deriving (Eq, Show) hands :: Lens' TrickState (Tup4 [Card]) hands = lens tsHands (\x v-> x {tsHands = v}) data TrickView = TrickView {tvTrickNum :: Int, tvLeadPos :: Int, tvHand :: [Card], tvTable :: Tup4 (Maybe Card)} deriving (Eq, Show) tup4 :: Int -> Lens' (Tup4 a) a tup4 n = case (n `mod` 4) of 0 -> _1 1 -> _2 2 -> _3 3 -> _4 _ -> undefined class HasTrickView a where trickNum :: Lens' a Int leadPos :: Lens' a Int table :: Lens' a (Tup4 (Maybe Card)) instance HasTrickView TrickState where trickNum = lens tsTrickNum (\x y -> x {tsTrickNum = y}) leadPos = lens tsLeadPos (\x y -> x {tsLeadPos = y}) table = lens tsTable (\x y -> x {tsTable = y}) instance HasTrickView TrickView where trickNum = lens tvTrickNum (\x y -> x {tvTrickNum = y}) leadPos = lens tvLeadPos (\x y -> x {tvLeadPos = y}) table = lens tvTable (\x y -> x {tvTable = y}) tablePos :: (HasTrickView a) => Int -> Lens' a (Maybe Card) tablePos pos = table . (tup4 pos) ledSuit :: (HasTrickView a) => a -> Maybe Suit ledSuit obj = if obj ^. trickNum == 1 then Just Diamond else fmap suit $ obj ^. (tablePos $ obj ^. leadPos) -- Find the first player who hasn't played to the trick. trickActive :: TrickState -> [PlayerId] trickActive ts = case filter check (rotateL theLeadPos [0..3]) of [] -> [] (x:_) -> [Player x] where check n = ts ^. (tablePos n) == Nothing theLeadPos = ts ^. leadPos rotateL n list = (drop n list) ++ (take n list) hasSuit :: [Card] -> Suit -> Bool hasSuit cards s = any ((== s) . suit) cards trickLegal :: TrickView -> PlayerId -> Card -> Bool trickLegal tv (Player _) card = card `elem` hand && followingSuit where hand = tvHand tv followingSuit = case ledSuit tv of Just ls -> (suit card) == ls || not (hasSuit hand ls) Nothing -> True data TrickResult = TrickResult {cardsPlayed :: Tup4 Card, whoWon :: Int, points :: Int} deriving (Eq, Show) trickMakeView :: TrickState -> PlayerId -> TrickView trickMakeView ts@TrickState {..} (Player n) = TrickView {tvTrickNum = tsTrickNum, tvTable = tsTable, tvLeadPos = tsLeadPos, tvHand = tsHands ^. (tup4 n)} trickMakeView _ _ = error "Random player uses no views" trickUpdate' :: TrickState -> Int -> Card -> TrickState trickUpdate' ts pos card = ts & table . (tup4 pos) .~ (Just card) & hands . (tup4 pos) %~ (L.delete card) trickUpdate :: TrickState -> [PlayerId] -> [Card] -> TrickState trickUpdate ts [(Player pos)] [card] = trickUpdate' ts pos card trickUpdate _ _ _ = error "trick play is strictly one-at-a-time" -- TODO: implement a zipTraversable and bypass the list conversion. maxIndex :: (Ord b, Traversable t) => (a -> b) -> t a -> Int maxIndex f xs = snd $ maximum $ zip (map f (foldr (:) [] xs)) [0..] winnerOfTrick :: Suit -> Tup4 Card -> Int winnerOfTrick ledSuit cards = maxIndex score cards where honor = any (\(Card r s) -> r >= jack && s == ledSuit) cards score c = if (suit c) == ledSuit then if honor && (rank c) == 2 then 100 else unRank (rank c) else -100 pointValueOfTrick :: Bool -> Tup4 Card -> Int pointValueOfTrick isFirst cards = (if isFirst then firstTrickValue else 0) + base where base = getSum $ foldMap (Sum . pointValue) cards trickTerminal :: TrickState -> Maybe TrickResult trickTerminal ts = if all (/= Nothing) (ts ^. table) then let cards = fmap fromJust $ ts ^. table (Just theLedSuit) = ledSuit ts in Just $ TrickResult {cardsPlayed = cards, whoWon = winnerOfTrick theLedSuit cards, points = pointValueOfTrick (ts ^. trickNum == 1) cards} else Nothing trick :: Mechanic PlayerId TrickState Card TrickView TrickResult trick = Mechanic {players = const (map Player [0..3]), makeView = trickMakeView, active = trickActive, legal = trickLegal, update = trickUpdate, terminal = trickTerminal} data RoundResult = RoundResult {rrTrickHistory :: TrickResult, rrPointsTaken :: Tup4 Int, rrPointsScored :: Tup4 Int, rrStrikes :: Tup4 Int} data RoundState = BeforePass {rsRoundNum :: Int, rsHands :: Tup4 [Card]} | PlayingTricks {rsRoundNum :: Int, trickState :: TrickState, trickHistory :: [TrickResult], rsPointsTaken :: Tup4 Int} | RoundFinished RoundResult data RoundView = RVBeforePass {rvRoundNum :: Int, rvHand :: [Card]} | RVPlayingTricks {rvRoundNum :: Int, trickView :: TrickView, lastTrick :: TrickResult, rvPointsTaken :: Tup4 Int} | RVRoundFinished RoundResult data RoundAction = PlayCard Card | PassCards (Card, Card, Card) round :: Game PlayerId RoundState RoundAction RoundView RoundResult round = undefined
michaelochurch/jatek
Games/Ambition.hs
mit
6,979
0
14
2,178
2,367
1,296
1,071
-1
-1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ViewPatterns #-} module Kashmir.Github.Api (getUserDetails, getUserOrganizations, getUserRepositories,getRepositoryHooks ,requestAccess,createRepositoryHook,deleteRepositoryHook,toUrl,Sitemap(..),RepositorySitemap(..),GithubError(..),GithubErrorMessage(..)) where import Control.Category ((.)) import Control.Exception (try) import Control.Lens import Control.Monad.IO.Class import Control.Monad.Reader import Data.Aeson import Data.Bifunctor import Data.ByteString hiding (pack, putStrLn, unpack) import Data.ByteString.Lazy (fromStrict) import qualified Data.CaseInsensitive as CI import Data.Map (Map) import Data.Maybe import Data.Monoid import Data.Text import Data.Text.Encoding import Kashmir.Github.Types import Kashmir.Github.Types.Common import Kashmir.Github.Types.Hook (Hook) import Kashmir.Unfold import Kashmir.Web (mimeTypeJson) import Network.HTTP.Client (HttpException (..)) import Network.HTTP.Types.Status (statusCode) import Network.Wreq hiding (statusCode) import Prelude hiding ((.)) import Text.Boomerang.HStack import Text.Boomerang.TH import Text.Printf import Web.Routes hiding (URL) import Web.Routes.Boomerang hiding ((.~)) data RepositorySitemap = RepositoryDetails | RepositoryHooks | RepositoryHook Int deriving (Eq,Ord,Read,Show) data Sitemap = UserDetails | UserOrganizations | UserRepositories | Repositories Text Text RepositorySitemap deriving (Eq,Ord,Read,Show) makeBoomerangs ''RepositorySitemap makeBoomerangs ''Sitemap sitemap :: Router () (Sitemap :- ()) sitemap = mconcat ["user" . users ,"repos" . rRepositories </> anyText </> anyText . repos] where users = mconcat [rUserDetails ,rUserOrganizations </> "orgs" ,rUserRepositories </> "repos"] repos = mconcat [rRepositoryDetails ,rRepositoryHooks </> "hooks" ,rRepositoryHook </> "hooks" </> int] toUrl :: Sitemap -> Text toUrl s = fromMaybe (error (printf "Cannot convert to URL: %s" (show s))) (toPathInfo <$> unparseTexts sitemap s) server :: Text server = "https://api.github.com" makeGithubUrl :: Sitemap -> Text makeGithubUrl uri = server <> toUrl uri getRaw :: FromJSON a => URL -> ReaderT AccessToken IO (Response a) getRaw aUrl = do (AccessToken t) <- ask liftIO $ do raw <- getWith (defaults & param "access_token" .~ [t]) (unpack aUrl) asJSON raw postRaw :: (ToJSON a,FromJSON b) => URL -> a -> ReaderT AccessToken IO b postRaw aUrl payload = do (AccessToken t) <- ask liftIO $ do response <- postWith (defaults & param "access_token" .~ [t]) (unpack aUrl) (toJSON payload) view responseBody <$> asJSON response deleteRaw :: Text -> ReaderT AccessToken IO () deleteRaw aUrl = do (AccessToken t) <- ask void . liftIO $ deleteWith (defaults & param "access_token" .~ [t]) (unpack aUrl) postGithub :: (ToJSON a,FromJSON b) => Sitemap -> a -> ReaderT AccessToken IO b postGithub uri = postRaw (makeGithubUrl uri) deleteGithub :: Sitemap -> ReaderT AccessToken IO () deleteGithub uri = deleteRaw (makeGithubUrl uri) githubGetPage :: FromJSON a => Maybe URL -> ReaderT AccessToken IO (Maybe ([a],Maybe URL)) githubGetPage maybeUrl = case maybeUrl of Nothing -> return Nothing Just uri -> do r <- getRaw uri return $ Just (r ^. responseBody ,decodeUtf8 <$> (r ^? responseLink "rel" "next" . linkURL)) githubGet :: FromJSON a => Sitemap -> ReaderT AccessToken IO a githubGet uri = view responseBody <$> getRaw (makeGithubUrl uri) githubGetPages :: FromJSON a => Sitemap -> ReaderT AccessToken IO [a] githubGetPages uri = unfoldrM githubGetPage (Just (makeGithubUrl uri)) getUserDetails :: ReaderT AccessToken IO GithubUser getUserDetails = githubGet UserDetails getUserOrganizations :: ReaderT AccessToken IO [GithubOrganization] getUserOrganizations = githubGetPages UserOrganizations getUserRepositories :: ReaderT AccessToken IO [GithubRepository] getUserRepositories = githubGetPages UserRepositories data GithubErrorMessage = GithubErrorMessage {message :: Text ,errors :: [Map Text Text]} deriving (Show,Generic,FromJSON) data GithubError = GithubError GithubErrorMessage | UnhandledGithubError HttpException deriving (Show,Generic) handleGithubError :: HttpException -> GithubError handleGithubError err@(StatusCodeException (statusCode -> 422) headerList _) = let rawMessage :: Maybe GithubErrorMessage = lookup (CI.mk "X-Response-Body-Start") headerList >>= decode . fromStrict in case rawMessage of Nothing -> UnhandledGithubError err Just message -> GithubError message handleGithubError err = UnhandledGithubError err tryGithub :: IO a -> IO (Either GithubError a) tryGithub block = first handleGithubError <$> try block getRepositoryHooks :: Text -> Text -> ReaderT AccessToken IO (Either GithubError [GithubRepositoryHook]) getRepositoryHooks ownerLogin repoName = mapReaderT tryGithub $ do rawHooks <- githubGetPages (Repositories ownerLogin repoName RepositoryHooks) return (fromRaw ownerLogin repoName <$> rawHooks) -- TODO This doesn't handle a response of: -- responseBody = "{\"error\":\"bad_verification_code\",\"error_description\":\"The code passed is incorrect or expired.\",\"error_uri\":\"https://developer.github.com/v3/oauth/#bad-verification-code\"}" requestAccess :: Config -> ByteString -> IO AccessTokenResponse requestAccess config code = do response <- postWith (defaults & header "Accept" .~ [mimeTypeJson]) (view accessUrl config) ["code" := code ,"client_id" := view clientId config ,"client_secret" := view clientSecret config] view responseBody <$> asJSON response createRepositoryHook :: Text -> Text -> Hook -> ReaderT AccessToken IO (Either GithubError GithubRepositoryHook) createRepositoryHook ownerLogin repoName hook = mapReaderT tryGithub $ do (rawHook :: RawRepositoryHook) <- postGithub (Repositories ownerLogin repoName RepositoryHooks) hook return (fromRaw ownerLogin repoName rawHook) deleteRepositoryHook :: Text -> Text -> Int -> ReaderT AccessToken IO (Either GithubError ()) deleteRepositoryHook ownerLogin repoName hook = mapReaderT tryGithub $ deleteGithub (Repositories ownerLogin repoName (RepositoryHook hook))
krisajenkins/kashmir
src/Kashmir/Github/Api.hs
epl-1.0
7,358
0
17
1,860
1,868
981
887
-1
-1
module ProjectData(ProjectData, projectName, projectDir, projectCommits, projectFileMods, buildProjectData) where import Data.List as L import Data.Map as M import Git data ProjectData = ProjectData { projectName :: String, projectDir :: String, projectCommits :: [Commit], projectFileMods :: [[String]] } deriving (Eq, Ord, Show) buildProjectData :: String -> String -> [Commit] -> [[String]] -> ProjectData buildProjectData name dir commits mods = ProjectData name dir commits mods
dillonhuff/GitVisualizer
src/ProjectData.hs
gpl-2.0
551
0
10
129
151
91
60
16
1
module Amoeba.Middleware.Math.Geometry where -- Inspired by https://github.com/ocharles/netwire-classics/blob/master/asteroids/Asteroids.hs import qualified Linear as L import qualified Control.Arrow as Arr import Data.Maybe (fromJust) import Data.Tuple (swap) class Bounded i where bounds :: i -> Point -> Bound class ToVector i where toVector :: i -> Point -- TODO: extract shapes data types (Rectangle, Circle, etc.) from Bound. data Bound = Circled { circleCenter :: Point , circleRadius :: Radius } | Rectangled { rectedLU :: Point , rectedRD :: Point } | Pointed { pointPosition :: Point } | NoBound deriving (Show, Read, Eq) type Bounds = [Bound] type Radius = Double type Point = L.V3 Int type Points = [Point] type Path = Points data Direction = DirLeft | DirRight | DirUp | DirDown | DirLeftUp | DirRightDown | DirLeftDown | DirRightUp deriving (Show, Read, Eq) type Directions = [Direction] type Shift = Point -> Point type Shifts = [Shift] type TargetPoint = Point type Distance = Int type NeighboursFunc = Point -> Points toDoubleV3 :: L.V3 Int -> L.V3 Double toDoubleV3 (L.V3 x1 x2 x3) = L.V3 (fromIntegral x1) (fromIntegral x2) (fromIntegral x3) normIntV3 :: Point -> Double normIntV3 = L.norm . toDoubleV3 distanceIntV3 :: Point -> Point -> Double distanceIntV3 p1 p2 = L.distance (toDoubleV3 p1) (toDoubleV3 p2) inSegment :: (Int, Int) -> Int -> Bool inSegment (x, y) z = (z <= max x y) && (z >= min x y) minMax (L.V3 x1 y1 _) (L.V3 x2 y2 _) = point (min x1 x2) (max y1 y2) 0 maxMin (L.V3 x1 y1 _) (L.V3 x2 y2 _) = point (max x1 x2) (min y1 y2) 0 minMin (L.V3 x1 y1 _) (L.V3 x2 y2 _) = point (min x1 x2) (min y1 y2) 0 maxMax (L.V3 x1 y1 _) (L.V3 x2 y2 _) = point (max x1 x2) (max y1 y2) 0 rectBound :: Point -> Point -> Bound rectBound p1 p2 = Rectangled (minMin p1 p2) (maxMax p1 p2) pointBound :: Point -> Bound pointBound (L.V3 x y z) = Pointed (point x y z) circleBound :: Point -> Radius -> Bound circleBound = Circled noBound = NoBound updateRectBound :: Point -> Bound -> Bound updateRectBound p (Rectangled p1 p2) = Rectangled (minMin p1 p) (maxMax p2 p) updateRectBound p NoBound = Rectangled p p updateRectBound p b = error $ "Rectangled bound expected, but got: " ++ show b ++ " for point " ++ show p inRect r1 r2 = leftUpIn && rightDownIn where leftUpIn = uncurry (withCoords (>=)) ((Arr.***) rectedLU rectedLU (r1, r2)) rightDownIn = uncurry (withCoords (<=)) ((Arr.***) rectedRD rectedRD (r1, r2)) withCoords f (L.V3 x1 y1 _) (L.V3 x2 y2 _) = f x1 x2 && f y1 y2 occupiedArea :: Points -> Bound occupiedArea [] = NoBound occupiedArea (p:ps) = foldr updateRectBound (rectBound p p) ps intersecting :: Bound -> Bound -> Bool intersecting (Circled c1 r1) (Circled c2 r2) = normIntV3 (c1 - c2) < (r1 + r2) intersecting c@(Circled _ _) (Pointed p) = intersecting c (Circled p 0) intersecting p@(Pointed _) c@(Circled _ _) = intersecting c p intersecting (Pointed p1) (Pointed p2) = p1 == p2 intersecting (Rectangled lu@(L.V3 x1 x2 _) rd@(L.V3 y1 y2 _)) (Pointed p@(L.V3 p1 p2 _)) = inSegment (x1, y1) p1 && inSegment (x2, y2) p2 intersecting p@(Pointed {}) r@(Rectangled {}) = intersecting r p intersecting NoBound _ = True intersecting _ NoBound = True intersecting b1 b2 = error $ "Intersecting not implemented for " ++ show b1 ++ " and " ++ show b2 inBounds :: Point -> Bounds -> Bool inBounds p = any (intersecting (Pointed p)) point :: Int -> Int -> Int -> L.V3 Int point = L.V3 zeroPoint = L.V3 0 0 0 :: L.V3 Int -- Directions leftUp = DirLeftUp leftDown = DirLeftDown rightUp = DirRightUp rightDown = DirRightDown left = DirLeft right = DirRight up = DirUp down = DirDown sideDirections = [ left, right, up, down ] cornerDirections = [ leftUp, rightDown, leftDown, rightUp ] directions = sideDirections ++ cornerDirections oppositeDirections1 = [ (leftUp, rightDown) , (leftDown, rightUp) , (left, right) , (up, down) ] oppositeDirections2 = map swap oppositeDirections1 oppositeDirections = oppositeDirections1 ++ oppositeDirections2 opposite dir = fromJust $ lookup dir oppositeDirections instance ToVector Direction where toVector DirLeft = leftP toVector DirRight = rightP toVector DirUp = upP toVector DirDown = downP toVector DirLeftUp = leftUpP toVector DirRightDown = rightDownP toVector DirLeftDown = leftDownP toVector DirRightUp = rightUpP leftUpP = L.V3 (-1) (-1) 0 :: L.V3 Int leftDownP = L.V3 (-1) 1 0 :: L.V3 Int rightUpP = L.V3 1 (-1) 0 :: L.V3 Int rightDownP = L.V3 1 1 0 :: L.V3 Int leftP = L.V3 (-1) 0 0 :: L.V3 Int rightP = L.V3 1 0 0 :: L.V3 Int upP = L.V3 0 (-1) 0 :: L.V3 Int downP = L.V3 0 1 0 :: L.V3 Int relativeCorners = [ leftUpP, leftDownP, rightUpP, rightDownP ] relativeSides = [ leftP, rightP, upP, downP ] neighbours :: NeighboursFunc neighbours p = map (p L.^+^) $ relativeCorners ++ relativeSides sideNeighbours p = map (p L.^+^) relativeSides cornerNeighbours p = map (p L.^+^) relativeCorners areNeighbours p1 p2 = p1 `elem` neighbours p2 pointX (L.V3 x _ _) = x pointY (L.V3 _ y _) = y pointZ (L.V3 _ _ z) = z addPoint = (L.^+^) :: Point -> Point -> Point -- Moving moveStraight :: Distance -> Point -> Direction -> Point moveStraight 0 p dir = p moveStraight dist p dir = let oppDir = opposite dir absDist = abs dist in (L.^+^) p (if dist < 0 then toVector oppDir L.^* absDist else toVector dir L.^* dist) advance :: Point -> Direction -> Point advance = moveStraight 1
graninas/The-Amoeba-World
src/Amoeba/Middleware/Math/Geometry.hs
gpl-3.0
5,666
0
11
1,273
2,300
1,225
1,075
132
2
{-# LANGUAGE FlexibleInstances #-} --hdbc and hdbc-odbc must be installed (from hackage) module Database.Design.Ampersand.Prototype.Apps.RAP (fillAtlas,picturesForAtlas,atlas2context,atlas2populations) where import Database.Design.Ampersand.Prototype.CoreImporter import Database.Design.Ampersand.Prototype.AutoInstaller (odbcinstall) import Database.HDBC.ODBC import Database.HDBC import Database.Design.Ampersand.FSpec.SQL -- fatal :: Int -> String -> a -- fatal = fatalMsg "Ampersand.Prototype.Apps.RAP" ------ dsnatlas::String dsnatlas = "DSN=RAPv1" ---------------------------------------------------- fillAtlas :: FSpec -> IO() fillAtlas fSpec = odbcinstall fSpec dsnatlas picturesForAtlas :: FSpec -> [Picture] picturesForAtlas fSpec = map (makePicture fSpec) ( [PTRelsUsedInPat pat | pat <- vpatterns fSpec] ++ [PTSingleRule userRule | userRule <- vrules fSpec]++ [PTConcept cpt | cpt <- concs fSpec] ) ---------------------------------------------------- --select population of concepts or reldeclsDefdInations from the atlas of this user --REMARK quickQuery' is strict and needed to keep results for use after disconnecting type AtomVal = String type RelTbl = [(AtomVal,AtomVal)] selectdecl :: (IConnection conn) => conn -> FSpec -> String -- ^The name of the declaration -> IO RelTbl selectdecl conn fSpec dclName = do rows <- quickQuery' conn stmt [] return [(fromSql x,fromSql y) |[x,y]<-rows] where stmt = prettySQLQuery fSpec 0 dcl dcl = therel dclName "" "" therel ::String -> String -> String -> Declaration therel relname relsource reltarget = theonly [ d | d<-vrels fSpec ,relname==name d ,null relsource || relsource==name(source d) ,null reltarget || reltarget==name(target d)] ("when searching for the relation x with searchpattern (name,source,target)" ++ show (relname,relsource,reltarget)) theonly :: [t] -> String -> t theonly xs err | length xs==1 = head xs | null xs = error ("no x: " ++ err) | otherwise = error ("more than one x: " ++ err) geta :: [(String,b)] -> String -> b -> b geta f x notfound = (\xs-> if null xs then notfound else head xs) [y | (x',y)<-f,x==x'] atlas2populations :: FSpec -> IO String atlas2populations fSpec = do verboseLn (getOpts fSpec) "Connecting to atlas..." conn<-connectODBC dsnatlas verboseLn (getOpts fSpec) "Connected." ----------- --select (strict) everything you need, then disconnect, then assemble it into a context with populations only --Context-- r_ctxnm <- selectdecl conn fSpec "ctxnm" --ctxnm ::Context->Conid --Concept-- r_cptnm <- selectdecl conn fSpec "cptnm" --cptnm :: Concept->Conid r_cptos <- selectdecl conn fSpec "cptos" --cptos :: Concept*AtomID r_atomvalue <- selectdecl conn fSpec "atomvalue" --atomvalue::AtomID->Atom --Relation-- r_decnm <- selectdecl conn fSpec "decnm" --decnm ::Declaration->Varid r_decsgn <- selectdecl conn fSpec "decsgn" --decsgn ::Declaration->Sign r_src <- selectdecl conn fSpec "src" --src::Sign->Concept r_trg <- selectdecl conn fSpec "trg" --trg::Sign->Concept --P_Population-- r_decpopu <- selectdecl conn fSpec "decpopu" --decpopu ::Declaration*PairID r_left <- selectdecl conn fSpec "left" --left::Pair->AtomID r_right <- selectdecl conn fSpec "right" --right::Pair->AtomID ----------- disconnect conn verboseLn (getOpts fSpec) "Disconnected." makepops r_ctxnm r_decnm r_decsgn r_src r_trg r_cptnm r_decpopu r_left r_right r_cptos r_atomvalue makepops :: RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> IO String makepops r_ctxnm r_decnm r_decsgn r_src r_trg r_cptnm r_decpopu r_left r_right r_cptos r_atomvalue = return ("CONTEXT "++cxnm++" IN DUTCH\n"++concatMap showADL pops++"\nENDCONTEXT") -- SJ: The " IN DUTCH\n" part is wrong, surely. But how to fix this? In any case, it doesn't block the parser anymore. where cxnm = snd(theonly r_ctxnm "no context found in Atlas DB") pops = atlas2pops r_decnm r_decsgn r_src r_trg r_cptnm r_decpopu r_left r_right r_cptos r_atomvalue atlas2context :: Options -> FSpec -> IO A_Context atlas2context opts fSpec = do --tbls <- readAtlas fSpec verboseLn (getOpts fSpec) "Connecting to atlas..." conn<-connectODBC dsnatlas verboseLn (getOpts fSpec) "Connected." ----------- --select (strict) everything you need, then disconnect, then assemble it into a context and patterns and stuff --Context-- r_ctxnm <- selectdecl conn fSpec "ctxnm" --ctxnm ::Context->Conid --not needed because there is only one context --ctxpats :: Context*Pattern --ctxcs :: Context*Concept --Pattern-- r_ptnm <- selectdecl conn fSpec "ptnm" --ptnm :: Pattern->Conid r_ptrls <- selectdecl conn fSpec "ptrls" --ptrls :: Pattern*Rule r_ptdcs <- selectdecl conn fSpec "ptdcs" --ptdcs :: Pattern*Declaration r_ptgns <- selectdecl conn fSpec "ptgns" --ptgns :: Pattern*Isa r_ptxps <- selectdecl conn fSpec "ptxps" --ptxps :: Pattern*Blob --Isa-- r_gengen <- selectdecl conn fSpec "gengen" --gengen :: Isa->Concept r_genspc <- selectdecl conn fSpec "genspc" --genspc :: Isa->Concept r_genrhs <- selectdecl conn fSpec "genrhs" --genrhs :: Isa*Concept --Concept-- r_cptnm <- selectdecl conn fSpec "cptnm" --cptnm :: Concept->Conid r_cptpurpose <- selectdecl conn fSpec "cptpurpose" --cptpurpose:: Concept*Blob -- r_cptdf <- selectdecl conn fSpec "cptdf" --cptdf :: Concept*Blob r_cptos <- selectdecl conn fSpec "cptos" --cptos :: Concept*AtomID r_atomvalue <- selectdecl conn fSpec "atomvalue" --atomvalue::AtomID->Atom --Relation-- r_decnm <- selectdecl conn fSpec "decnm" --decnm :: Declaration->Varid r_decsgn <- selectdecl conn fSpec "decsgn" --decsgn :: Declaration->Sign r_src <- selectdecl conn fSpec "src" --src::Sign->Concept r_trg <- selectdecl conn fSpec "trg" --trg::Sign->Concept r_decprps <- selectdecl conn fSpec "decprps" --decprps::Declaration*PropertyRule r_declaredthrough <- selectdecl conn fSpec "declaredthrough" --declaredthrough :: PropertyRule*Property r_decprL <- selectdecl conn fSpec "decprL" --decprL :: Declaration*String r_decprM <- selectdecl conn fSpec "decprM" --decprM :: Declaration*String r_decprR <- selectdecl conn fSpec "decprR" --decprR :: Declaration*String r_decmean <- selectdecl conn fSpec "decmean" --decmean :: Declaration * Blob r_decpurpose <- selectdecl conn fSpec "decpurpose" --decpurpose :: Declaration * Blob --P_Population-- r_decpopu <- selectdecl conn fSpec "decpopu" --decpopu :: Declaration*PairID r_left <- selectdecl conn fSpec "left" --left :: PairID->AtomID r_right <- selectdecl conn fSpec "right" --right :: PairID->AtomID --Rule-- r_rrnm <- selectdecl conn fSpec "rrnm" --rrnm :: Rule -> ADLid r_rrexp <- selectdecl conn fSpec "rrexp" --rrexp :: Rule -> ExpressionID r_rrmean <- selectdecl conn fSpec "rrmean" --rrmean :: Rule * Blob r_rrpurpose <- selectdecl conn fSpec "rrpurpose" --rrpurpose :: Rule * Blob --Expression-- r_exprvalue' <- selectdecl conn fSpec "exprvalue" --exprvalue :: ExpressionID->Expression --not needed --rels :: ExpressionID*Relation --relnm :: Relation -> Varid --reldcl :: Relation -> Declaration ----------- disconnect conn verboseLn (getOpts fSpec) "Disconnected." let r_exprvalue = parseexprs r_exprvalue' --parsing is the safest way to get the Term --verboseLn (getOpts fSpec) (show(map showADL (atlas2pops relcontent relname relsc reltg pairleft pairright atomsyntax))) actx <- makectx opts r_ctxnm (fsLang fSpec) r_ptnm r_ptrls r_ptdcs r_ptgns r_ptxps r_gengen r_genspc r_genrhs r_cptnm r_cptpurpose {- r_cptdf -} r_cptos r_atomvalue r_decnm r_decsgn r_src r_trg r_decprps r_declaredthrough r_decprL r_decprM r_decprR r_decmean r_decpurpose r_decpopu r_left r_right r_rrnm r_rrexp r_rrmean r_rrpurpose r_exprvalue case actx of (Errors x) -> error (show x) (Checked x) -> return x where parseexprs :: RelTbl -> [(AtomVal, Term TermPrim)] parseexprs = map f where f :: (AtomVal,AtomVal) -> (AtomVal, Term TermPrim) f (str, expr) = (str , case parseADL1pExpr expr "Atlas(Rule)" of Left err -> error err Right term -> term ) makectx :: Options -> RelTbl -> Lang -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> {- RelTbl -> -} RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> [(AtomVal,(Term TermPrim))] -> IO (Guarded A_Context) makectx opts r_ctxnm lang r_ptnm r_ptrls r_ptdcs r_ptgns r_ptxps r_gengen r_genspc r_genrhs r_cptnm r_cptpurpose {- r_cptdf -} r_cptos r_atomvalue r_decnm r_decsgn r_src r_trg r_decprps r_declaredthrough r_decprL r_decprM r_decprR r_decmean r_decpurpose r_decpopu r_left r_right r_rrnm r_rrexp r_rrmean r_rrpurpose r_exprvalue = return a_context where (a_context) = pCtx2aCtx opts rawctx rawctx = PCtx { ctx_nm = snd(theonly r_ctxnm "not one context in Atlas DB") , ctx_pos = [DBLoc "Atlas(Context)"] , ctx_lang = lang , ctx_markup= Just LaTeX --ADLImportable writes LaTeX , ctx_thms = [] , ctx_pats = [atlas2pattern p lang r_ptrls r_ptdcs r_ptgns r_gengen r_genspc r_genrhs r_cptnm r_decnm r_decsgn r_src r_trg r_decprps r_declaredthrough r_decprL r_decprM r_decprR r_decmean r_decpurpose r_rrnm r_rrexp r_rrmean r_rrpurpose r_exprvalue |p<-r_ptnm] , ctx_rs = [] --in pattern:(atlas2rules fSpec tbls) , ctx_ds = [] --in pattern:(atlas2decls fSpec tbls) , ctx_cs = [{- TODO: Han, please fix this: Cd { cdpos = DBLoc "Atlas(A_ConceptDef)" , cdcpt = cnm , cdplug = False , cddef = cdf , cdtyp = "Text" , cdref = [] , cdfrom = "" } | (cid,cdf)<-r_cptdf, not(null cdf) , let cnm = geta r_cptnm cid (error "while geta r_cptnm for cdf.") -} ] , ctx_ks = [] , ctx_rrules = [] , ctx_rrels = [] , ctx_vs = [] , ctx_gs = [] , ctx_ifcs = [] , ctx_ps = [PRef2 (DBLoc "Atlas(PatPurpose)") (PRef2Pattern pnm) (P_Markup Nothing Nothing ppurp) [] | (pid,ppurp)<-r_ptxps, not(null ppurp) , let pnm = geta r_ptnm pid (error "while geta r_ptnm for ppurp.")] ++ [PRef2 (DBLoc "Atlas(CptPurpose)") (PRef2ConceptDef cnm) (P_Markup Nothing Nothing cpurp) [] | (cid,cpurp)<-r_cptpurpose, not(null cpurp) , let cnm = geta r_cptnm cid (error "while geta r_cptnm for cpurp.")] , ctx_pops = atlas2pops r_decnm r_decsgn r_src r_trg r_cptnm r_decpopu r_left r_right r_cptos r_atomvalue , ctx_sql = [] , ctx_php = [] , ctx_metas = [] } atlas2pattern :: (AtomVal,AtomVal) -> Lang -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> [(AtomVal,(Term TermPrim))] -> P_Pattern atlas2pattern (pid,pnm) lang r_ptrls r_ptdcs r_ptgns r_gengen r_genspc _ {- r_genrhs -} r_cptnm r_decnm r_decsgn r_src r_trg r_decprps r_declaredthrough r_decprL r_decprM r_decprR r_decmean r_decpurpose r_rrnm r_rrexp r_rrmean r_rrpurpose r_exprvalue = P_Pat { pt_pos = DBLoc "Atlas(Pattern)" , pt_nm = pnm , pt_rls = [atlas2rule rid lang r_rrnm r_rrexp r_rrmean r_exprvalue | (pid',rid)<-r_ptrls, pid==pid', rid `notElem` map fst r_declaredthrough] , pt_gns = [PGen{ gen_fp = DBLoc "Atlas(Isa)" ,gen_gen= PCpt gnm,gen_spc=(PCpt snm)} -- TODO: Han, would you please look after the CLASSIFY IS statements? | (pid',genid)<-r_ptgns, pid'==pid , let gid = geta r_gengen genid (error "while geta r_gengen.") , let sid = geta r_genspc genid (error "while geta r_genspc.") , let gnm = geta r_cptnm gid (error "while geta r_cptnm for gen.") , let snm = geta r_cptnm sid (error "while geta r_cptnm for spc.")] , pt_dcs = [atlas2decl rid i lang r_decnm r_decsgn r_src r_trg r_cptnm r_decprps r_declaredthrough r_decprL r_decprM r_decprR r_decmean |(i,(pid',rid))<-zip [1..] r_ptdcs, pid==pid'] , pt_RRuls = [] , pt_RRels = [] , pt_cds = [] , pt_ids = [] , pt_vds = [] , pt_xps = [PRef2 (DBLoc "Atlas(RulPurpose)") (PRef2Rule rnm) (P_Markup Nothing Nothing rpurp) [] | (pid',rid)<-r_ptrls, pid==pid' , (rid',rpurp)<-r_rrpurpose, rid==rid', not(null rpurp) , let rnm = geta r_rrnm rid (error "while geta r_rrnm for rpurp.")] ++ [PRef2 (DBLoc "Atlas(RelPurpose)") (PRef2Declaration (PNamedRel OriginUnknown rnm (Just $ atlas2sign rid r_decsgn r_src r_trg r_cptnm))) (P_Markup Nothing Nothing rpurp) [] | (pid',rid)<-r_ptdcs, pid==pid' , (rid',rpurp)<-r_decpurpose, rid==rid', not(null rpurp) , let rnm = geta r_decnm rid (error "while geta r_decnm for rpurp.")] , pt_pop = [] , pt_end = DBLoc "Atlas(Pattern)" } atlas2rule :: AtomVal -> Lang -> RelTbl -> RelTbl -> RelTbl -> [(AtomVal,Term TermPrim)] -> (P_Rule TermPrim) atlas2rule rid lang r_rrnm r_rrexp r_rrmean r_exprvalue = P_Ru { rr_fps = DBLoc "Atlas(Rule)" , rr_nm = geta r_rrnm rid (error "while geta r_rrnm.") , rr_exp = geta r_exprvalue eid (error "while geta r_exprvalue.") , rr_mean = [PMeaning (P_Markup (Just lang) Nothing (geta r_rrmean rid ""))] , rr_msg = [] , rr_viol = Nothing } where eid = geta r_rrexp rid (error "while geta r_rrexp.") atlas2sign :: AtomVal -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> P_Sign atlas2sign rid r_decsgn r_src r_trg r_cptnm = P_Sign (PCpt srcnm) (PCpt trgnm) where sid = geta r_decsgn rid (error "while geta r_decsgn.") srcid = geta r_src sid (error ("while geta r_src."++sid++show r_src)) trgid = geta r_trg sid (error "while geta r_trg.") srcnm = geta r_cptnm srcid (error "while geta r_cptnm of srcid.") trgnm = geta r_cptnm trgid (error "while geta r_cptnm of trgid.") atlas2pops :: RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> [P_Population] atlas2pops r_decnm r_decsgn r_src r_trg r_cptnm r_decpopu r_left r_right r_cptos r_atomvalue = [ P_TRelPop { p_rnme = rnm , p_orig = OriginUnknown , p_type = rsgn , p_popps = rpop } | (rid,rnm)<-r_decnm , let rsgn = atlas2sign rid r_decsgn r_src r_trg r_cptnm , let rpop = [makepair pid | (rid',pid)<-r_decpopu, rid==rid'] ] ++ [P_CptPopu { p_cnme=geta r_cptnm (fst(head cl)) (error "while geta r_cptnm for CptPopu.") , p_orig = OriginUnknown , p_popas=[a | (_,aid)<-cl, let a=geta r_atomvalue aid (error "while geta r_atomvalue of aid.")] } | cl<-eqCl fst r_cptos, not (null cl)] where makepair pid = mkPair src trg where lid = geta r_left pid (error "while geta r_left.") rid = geta r_right pid (error "while geta r_right.") src = geta r_atomvalue lid (error "while geta r_atomvalue of lid.") trg = geta r_atomvalue rid (error "while geta r_atomvalue of rid.") atlas2decl :: AtomVal -> Int -> Lang -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> RelTbl -> P_Declaration atlas2decl rid i lang r_decnm r_decsgn r_src r_trg r_cptnm r_decprps r_declaredthrough r_decprL r_decprM r_decprR r_decmean = P_Sgn { dec_nm = geta r_decnm rid (error "while geta r_decnm.") , dec_sign = atlas2sign rid r_decsgn r_src r_trg r_cptnm , dec_prps = [case geta r_declaredthrough prp (error "while geta r_declaredthrough.") of "UNI"->Uni "TOT"->Tot "INJ"->Inj "SUR"->Sur "RFX"->Rfx "IRF"->Irf "TRN"->Trn "SYM"->Sym "ASY"->Asy _ -> error "unknown prop in atlas" | (rid',prp)<-r_decprps, rid'==rid] , dec_pragma = [geta r_decprL rid "", geta r_decprM rid "", geta r_decprR rid ""] , dec_Mean = [PMeaning (P_Markup (Just lang) Nothing (geta r_decmean rid ""))] , dec_popu = [] , dec_fpos = DBLoc$"Atlas(Declaration)"++show i , dec_plug = False }
DanielSchiavini/ampersand
src/Database/Design/Ampersand/Prototype/Apps/RAP.hs
gpl-3.0
19,041
0
42
6,025
4,499
2,324
2,175
270
10
module Main where { import qualified Server; main = Server.main}
ckaestne/CIDE
CIDE_Language_Haskell/test/WSP/Webserver/Main.hs
gpl-3.0
67
0
5
12
18
13
5
3
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.ServiceBroker -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- The Google Cloud Platform Service Broker API provides Google hosted -- implementation of the Open Service Broker API -- (https:\/\/www.openservicebrokerapi.org\/). -- -- /See:/ <https://cloud.google.com/kubernetes-engine/docs/concepts/add-on/service-broker Service Broker API Reference> module Network.Google.ServiceBroker ( -- * Service Configuration serviceBrokerService -- * OAuth Scopes , cloudPlatformScope -- * API Declaration , ServiceBrokerAPI -- * Resources -- ** servicebroker.getIamPolicy , module Network.Google.Resource.ServiceBroker.GetIAMPolicy -- ** servicebroker.setIamPolicy , module Network.Google.Resource.ServiceBroker.SetIAMPolicy -- ** servicebroker.testIamPermissions , module Network.Google.Resource.ServiceBroker.TestIAMPermissions -- * Types -- ** GoogleIAMV1__Policy , GoogleIAMV1__Policy , googleIAMV1__Policy , givpEtag , givpVersion , givpBindings -- ** GoogleIAMV1__TestIAMPermissionsResponse , GoogleIAMV1__TestIAMPermissionsResponse , googleIAMV1__TestIAMPermissionsResponse , givtiprPermissions -- ** GoogleType__Expr , GoogleType__Expr , googleType__Expr , gteLocation , gteExpression , gteTitle , gteDescription -- ** Xgafv , Xgafv (..) -- ** GoogleIAMV1__Binding , GoogleIAMV1__Binding , googleIAMV1__Binding , givbMembers , givbRole , givbCondition -- ** GoogleIAMV1__SetIAMPolicyRequest , GoogleIAMV1__SetIAMPolicyRequest , googleIAMV1__SetIAMPolicyRequest , givsiprPolicy -- ** GoogleIAMV1__TestIAMPermissionsRequest , GoogleIAMV1__TestIAMPermissionsRequest , googleIAMV1__TestIAMPermissionsRequest , giamvtiamprPermissions ) where import Network.Google.Prelude import Network.Google.Resource.ServiceBroker.GetIAMPolicy import Network.Google.Resource.ServiceBroker.SetIAMPolicy import Network.Google.Resource.ServiceBroker.TestIAMPermissions import Network.Google.ServiceBroker.Types {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Service Broker API service. type ServiceBrokerAPI = GetIAMPolicyResource :<|> SetIAMPolicyResource :<|> TestIAMPermissionsResource
brendanhay/gogol
gogol-servicebroker/gen/Network/Google/ServiceBroker.hs
mpl-2.0
2,767
0
6
504
213
158
55
47
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Admin.Customers.Chrome.Printers.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a printer under given Organization Unit. -- -- /See:/ <https://developers.google.com/admin-sdk/ Admin SDK API Reference> for @admin.customers.chrome.printers.create@. module Network.Google.Resource.Admin.Customers.Chrome.Printers.Create ( -- * REST Resource CustomersChromePrintersCreateResource -- * Creating a Request , customersChromePrintersCreate , CustomersChromePrintersCreate -- * Request Lenses , ccpcParent , ccpcXgafv , ccpcUploadProtocol , ccpcAccessToken , ccpcUploadType , ccpcPayload , ccpcCallback ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @admin.customers.chrome.printers.create@ method which the -- 'CustomersChromePrintersCreate' request conforms to. type CustomersChromePrintersCreateResource = "admin" :> "directory" :> "v1" :> Capture "parent" Text :> "chrome" :> "printers" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Printer :> Post '[JSON] Printer -- | Creates a printer under given Organization Unit. -- -- /See:/ 'customersChromePrintersCreate' smart constructor. data CustomersChromePrintersCreate = CustomersChromePrintersCreate' { _ccpcParent :: !Text , _ccpcXgafv :: !(Maybe Xgafv) , _ccpcUploadProtocol :: !(Maybe Text) , _ccpcAccessToken :: !(Maybe Text) , _ccpcUploadType :: !(Maybe Text) , _ccpcPayload :: !Printer , _ccpcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CustomersChromePrintersCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccpcParent' -- -- * 'ccpcXgafv' -- -- * 'ccpcUploadProtocol' -- -- * 'ccpcAccessToken' -- -- * 'ccpcUploadType' -- -- * 'ccpcPayload' -- -- * 'ccpcCallback' customersChromePrintersCreate :: Text -- ^ 'ccpcParent' -> Printer -- ^ 'ccpcPayload' -> CustomersChromePrintersCreate customersChromePrintersCreate pCcpcParent_ pCcpcPayload_ = CustomersChromePrintersCreate' { _ccpcParent = pCcpcParent_ , _ccpcXgafv = Nothing , _ccpcUploadProtocol = Nothing , _ccpcAccessToken = Nothing , _ccpcUploadType = Nothing , _ccpcPayload = pCcpcPayload_ , _ccpcCallback = Nothing } -- | Required. The name of the customer. Format: customers\/{customer_id} ccpcParent :: Lens' CustomersChromePrintersCreate Text ccpcParent = lens _ccpcParent (\ s a -> s{_ccpcParent = a}) -- | V1 error format. ccpcXgafv :: Lens' CustomersChromePrintersCreate (Maybe Xgafv) ccpcXgafv = lens _ccpcXgafv (\ s a -> s{_ccpcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ccpcUploadProtocol :: Lens' CustomersChromePrintersCreate (Maybe Text) ccpcUploadProtocol = lens _ccpcUploadProtocol (\ s a -> s{_ccpcUploadProtocol = a}) -- | OAuth access token. ccpcAccessToken :: Lens' CustomersChromePrintersCreate (Maybe Text) ccpcAccessToken = lens _ccpcAccessToken (\ s a -> s{_ccpcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ccpcUploadType :: Lens' CustomersChromePrintersCreate (Maybe Text) ccpcUploadType = lens _ccpcUploadType (\ s a -> s{_ccpcUploadType = a}) -- | Multipart request metadata. ccpcPayload :: Lens' CustomersChromePrintersCreate Printer ccpcPayload = lens _ccpcPayload (\ s a -> s{_ccpcPayload = a}) -- | JSONP ccpcCallback :: Lens' CustomersChromePrintersCreate (Maybe Text) ccpcCallback = lens _ccpcCallback (\ s a -> s{_ccpcCallback = a}) instance GoogleRequest CustomersChromePrintersCreate where type Rs CustomersChromePrintersCreate = Printer type Scopes CustomersChromePrintersCreate = '["https://www.googleapis.com/auth/admin.chrome.printers"] requestClient CustomersChromePrintersCreate'{..} = go _ccpcParent _ccpcXgafv _ccpcUploadProtocol _ccpcAccessToken _ccpcUploadType _ccpcCallback (Just AltJSON) _ccpcPayload directoryService where go = buildClient (Proxy :: Proxy CustomersChromePrintersCreateResource) mempty
brendanhay/gogol
gogol-admin-directory/gen/Network/Google/Resource/Admin/Customers/Chrome/Printers/Create.hs
mpl-2.0
5,464
0
20
1,278
792
461
331
118
1