code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE ScopedTypeVariables #-} import System.Environment import Control.Applicative ((<$>)) import Control.Monad (void) import qualified Kwil.Parser as KwilP import qualified Kwil.Compiler as KwilC import qualified Text.Parsec as P import Text.Parsec.Error (ParseError) import qualified Text.Parsec.Prim as Pr import Text.ParserCombinators.Parsec import Kwil.Lexer main = do args <- getArgs programInput <- readFile (if not (null args) then head args else error "Missing file argument") let tokens = parseFile programInput (head args) in case P.runParser KwilP.program () "example.kwil" tokens of (Left pe) -> do putStrLn "Programming Parsing Failed" print pe (Right p) -> if length args >= 2 && (args !! 1 == "compile") then do preludeInput <- readFile "Kwil/Kwil.js" putStrLn preludeInput putStrLn "\n" putStrLn $ KwilC.compileProgram p else putStrLn "No More Evaluator" filenameToJS filename = do programInput <- readFile filename let tokens = parseFile programInput filename in case P.runParser KwilP.program () filename tokens of (Right p) -> print $ KwilC.compileProgram p
rtpg/kwil
Main.hs
bsd-3-clause
1,365
1
17
427
359
181
178
33
4
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} #ifdef TRUSTWORTHY {-# LANGUAGE Trustworthy #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Internal.Bazaar -- Copyright : (C) 2012-2014 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable -- ---------------------------------------------------------------------------- module Control.Lens.Internal.Bazaar ( Bizarre(..) , Bazaar(..), Bazaar' , BazaarT(..), BazaarT' , Bizarre1(..) , Bazaar1(..), Bazaar1' , BazaarT1(..), BazaarT1' ) where import Control.Applicative import Control.Arrow as Arrow import Control.Category import Control.Comonad import Control.Lens.Internal.Context import Control.Lens.Internal.Indexed import Data.Functor.Apply import Data.Functor.Compose import Data.Functor.Contravariant import Data.Functor.Identity import Data.Semigroup import Data.Profunctor import Data.Profunctor.Rep import Data.Profunctor.Unsafe import Prelude hiding ((.),id) ------------------------------------------------------------------------------ -- Bizarre ------------------------------------------------------------------------------ -- | This class is used to run the various 'Bazaar' variants used in this -- library. class Profunctor p => Bizarre p w | w -> p where bazaar :: Applicative f => p a (f b) -> w a b t -> f t ------------------------------------------------------------------------------ -- Bazaar ------------------------------------------------------------------------------ -- | This is used to characterize a 'Control.Lens.Traversal.Traversal'. -- -- a.k.a. indexed Cartesian store comonad, indexed Kleene store comonad, or an indexed 'FunList'. -- -- <http://twanvl.nl/blog/haskell/non-regular1> -- -- A 'Bazaar' is like a 'Control.Lens.Traversal.Traversal' that has already been applied to some structure. -- -- Where a @'Context' a b t@ holds an @a@ and a function from @b@ to -- @t@, a @'Bazaar' a b t@ holds @N@ @a@s and a function from @N@ -- @b@s to @t@, (where @N@ might be infinite). -- -- Mnemonically, a 'Bazaar' holds many stores and you can easily add more. -- -- This is a final encoding of 'Bazaar'. newtype Bazaar p a b t = Bazaar { runBazaar :: forall f. Applicative f => p a (f b) -> f t } -- | This alias is helpful when it comes to reducing repetition in type signatures. -- -- @ -- type 'Bazaar'' p a t = 'Bazaar' p a a t -- @ type Bazaar' p a = Bazaar p a a instance IndexedFunctor (Bazaar p) where ifmap f (Bazaar k) = Bazaar (fmap f . k) {-# INLINE ifmap #-} instance Conjoined p => IndexedComonad (Bazaar p) where iextract (Bazaar m) = runIdentity $ m (arr Identity) {-# INLINE iextract #-} iduplicate (Bazaar m) = getCompose $ m (Compose #. distrib sell . sell) {-# INLINE iduplicate #-} instance Corepresentable p => Sellable p (Bazaar p) where sell = cotabulate $ \ w -> Bazaar $ tabulate $ \k -> pure (corep k w) {-# INLINE sell #-} instance Profunctor p => Bizarre p (Bazaar p) where bazaar g (Bazaar f) = f g {-# INLINE bazaar #-} instance Functor (Bazaar p a b) where fmap = ifmap {-# INLINE fmap #-} instance Apply (Bazaar p a b) where Bazaar mf <.> Bazaar ma = Bazaar $ \ pafb -> mf pafb <*> ma pafb {-# INLINE (<.>) #-} instance Applicative (Bazaar p a b) where pure a = Bazaar $ \_ -> pure a {-# INLINE pure #-} Bazaar mf <*> Bazaar ma = Bazaar $ \ pafb -> mf pafb <*> ma pafb {-# INLINE (<*>) #-} instance (a ~ b, Conjoined p) => Comonad (Bazaar p a b) where extract = iextract {-# INLINE extract #-} duplicate = iduplicate {-# INLINE duplicate #-} instance (a ~ b, Conjoined p) => ComonadApply (Bazaar p a b) where (<@>) = (<*>) {-# INLINE (<@>) #-} ------------------------------------------------------------------------------ -- BazaarT ------------------------------------------------------------------------------ -- | 'BazaarT' is like 'Bazaar', except that it provides a questionable 'Contravariant' instance -- To protect this instance it relies on the soundness of another 'Contravariant' type, and usage conventions. -- -- For example. This lets us write a suitably polymorphic and lazy 'Control.Lens.Traversal.taking', but there -- must be a better way! newtype BazaarT p (g :: * -> *) a b t = BazaarT { runBazaarT :: forall f. Applicative f => p a (f b) -> f t } -- | This alias is helpful when it comes to reducing repetition in type signatures. -- -- @ -- type 'BazaarT'' p g a t = 'BazaarT' p g a a t -- @ type BazaarT' p g a = BazaarT p g a a instance IndexedFunctor (BazaarT p g) where ifmap f (BazaarT k) = BazaarT (fmap f . k) {-# INLINE ifmap #-} instance Conjoined p => IndexedComonad (BazaarT p g) where iextract (BazaarT m) = runIdentity $ m (arr Identity) {-# INLINE iextract #-} iduplicate (BazaarT m) = getCompose $ m (Compose #. distrib sell . sell) {-# INLINE iduplicate #-} instance Corepresentable p => Sellable p (BazaarT p g) where sell = cotabulate $ \ w -> BazaarT (`corep` w) {-# INLINE sell #-} instance Profunctor p => Bizarre p (BazaarT p g) where bazaar g (BazaarT f) = f g {-# INLINE bazaar #-} instance Functor (BazaarT p g a b) where fmap = ifmap {-# INLINE fmap #-} instance Apply (BazaarT p g a b) where BazaarT mf <.> BazaarT ma = BazaarT $ \ pafb -> mf pafb <*> ma pafb {-# INLINE (<.>) #-} instance Applicative (BazaarT p g a b) where pure a = BazaarT $ tabulate $ \_ -> pure (pure a) {-# INLINE pure #-} BazaarT mf <*> BazaarT ma = BazaarT $ \ pafb -> mf pafb <*> ma pafb {-# INLINE (<*>) #-} instance (a ~ b, Conjoined p) => Comonad (BazaarT p g a b) where extract = iextract {-# INLINE extract #-} duplicate = iduplicate {-# INLINE duplicate #-} instance (a ~ b, Conjoined p) => ComonadApply (BazaarT p g a b) where (<@>) = (<*>) {-# INLINE (<@>) #-} instance (Profunctor p, Contravariant g) => Contravariant (BazaarT p g a b) where contramap _ = (<$) (error "contramap: BazaarT") {-# INLINE contramap #-} instance Contravariant g => Semigroup (BazaarT p g a b t) where BazaarT a <> BazaarT b = BazaarT $ \f -> a f <* b f {-# INLINE (<>) #-} instance Contravariant g => Monoid (BazaarT p g a b t) where mempty = BazaarT $ \_ -> pure (error "mempty: BazaarT") {-# INLINE mempty #-} BazaarT a `mappend` BazaarT b = BazaarT $ \f -> a f <* b f {-# INLINE mappend #-} ------------------------------------------------------------------------------ -- Bizarre1 ------------------------------------------------------------------------------ class Profunctor p => Bizarre1 p w | w -> p where bazaar1 :: Apply f => p a (f b) -> w a b t -> f t ------------------------------------------------------------------------------ -- Bazaar1 ------------------------------------------------------------------------------ -- | This is used to characterize a 'Control.Lens.Traversal.Traversal'. -- -- a.k.a. indexed Cartesian store comonad, indexed Kleene store comonad, or an indexed 'FunList'. -- -- <http://twanvl.nl/blog/haskell/non-regular1> -- -- A 'Bazaar1' is like a 'Control.Lens.Traversal.Traversal' that has already been applied to some structure. -- -- Where a @'Context' a b t@ holds an @a@ and a function from @b@ to -- @t@, a @'Bazaar1' a b t@ holds @N@ @a@s and a function from @N@ -- @b@s to @t@, (where @N@ might be infinite). -- -- Mnemonically, a 'Bazaar1' holds many stores and you can easily add more. -- -- This is a final encoding of 'Bazaar1'. newtype Bazaar1 p a b t = Bazaar1 { runBazaar1 :: forall f. Apply f => p a (f b) -> f t } -- | This alias is helpful when it comes to reducing repetition in type signatures. -- -- @ -- type 'Bazaar1'' p a t = 'Bazaar1' p a a t -- @ type Bazaar1' p a = Bazaar1 p a a instance IndexedFunctor (Bazaar1 p) where ifmap f (Bazaar1 k) = Bazaar1 (fmap f . k) {-# INLINE ifmap #-} instance Conjoined p => IndexedComonad (Bazaar1 p) where iextract (Bazaar1 m) = runIdentity $ m (arr Identity) {-# INLINE iextract #-} iduplicate (Bazaar1 m) = getCompose $ m (Compose #. distrib sell . sell) {-# INLINE iduplicate #-} instance Corepresentable p => Sellable p (Bazaar1 p) where sell = cotabulate $ \ w -> Bazaar1 $ tabulate $ \k -> pure (corep k w) {-# INLINE sell #-} instance Profunctor p => Bizarre1 p (Bazaar1 p) where bazaar1 g (Bazaar1 f) = f g {-# INLINE bazaar1 #-} instance Functor (Bazaar1 p a b) where fmap = ifmap {-# INLINE fmap #-} instance Apply (Bazaar1 p a b) where Bazaar1 mf <.> Bazaar1 ma = Bazaar1 $ \ pafb -> mf pafb <.> ma pafb {-# INLINE (<.>) #-} instance (a ~ b, Conjoined p) => Comonad (Bazaar1 p a b) where extract = iextract {-# INLINE extract #-} duplicate = iduplicate {-# INLINE duplicate #-} instance (a ~ b, Conjoined p) => ComonadApply (Bazaar1 p a b) where Bazaar1 mf <@> Bazaar1 ma = Bazaar1 $ \ pafb -> mf pafb <.> ma pafb {-# INLINE (<@>) #-} ------------------------------------------------------------------------------ -- BazaarT1 ------------------------------------------------------------------------------ -- | 'BazaarT1' is like 'Bazaar1', except that it provides a questionable 'Contravariant' instance -- To protect this instance it relies on the soundness of another 'Contravariant' type, and usage conventions. -- -- For example. This lets us write a suitably polymorphic and lazy 'Control.Lens.Traversal.taking', but there -- must be a better way! newtype BazaarT1 p (g :: * -> *) a b t = BazaarT1 { runBazaarT1 :: forall f. Apply f => p a (f b) -> f t } -- | This alias is helpful when it comes to reducing repetition in type signatures. -- -- @ -- type 'BazaarT1'' p g a t = 'BazaarT1' p g a a t -- @ type BazaarT1' p g a = BazaarT1 p g a a instance IndexedFunctor (BazaarT1 p g) where ifmap f (BazaarT1 k) = BazaarT1 (fmap f . k) {-# INLINE ifmap #-} instance Conjoined p => IndexedComonad (BazaarT1 p g) where iextract (BazaarT1 m) = runIdentity $ m (arr Identity) {-# INLINE iextract #-} iduplicate (BazaarT1 m) = getCompose $ m (Compose #. distrib sell . sell) {-# INLINE iduplicate #-} instance Corepresentable p => Sellable p (BazaarT1 p g) where sell = cotabulate $ \ w -> BazaarT1 (`corep` w) {-# INLINE sell #-} instance Profunctor p => Bizarre1 p (BazaarT1 p g) where bazaar1 g (BazaarT1 f) = f g {-# INLINE bazaar1 #-} instance Functor (BazaarT1 p g a b) where fmap = ifmap {-# INLINE fmap #-} instance Apply (BazaarT1 p g a b) where BazaarT1 mf <.> BazaarT1 ma = BazaarT1 $ \ pafb -> mf pafb <.> ma pafb {-# INLINE (<.>) #-} instance (a ~ b, Conjoined p) => Comonad (BazaarT1 p g a b) where extract = iextract {-# INLINE extract #-} duplicate = iduplicate {-# INLINE duplicate #-} instance (a ~ b, Conjoined p) => ComonadApply (BazaarT1 p g a b) where BazaarT1 mf <@> BazaarT1 ma = BazaarT1 $ \ pafb -> mf pafb <.> ma pafb {-# INLINE (<@>) #-} instance (Profunctor p, Contravariant g) => Contravariant (BazaarT1 p g a b) where contramap _ = (<$) (error "contramap: BazaarT1") {-# INLINE contramap #-} instance Contravariant g => Semigroup (BazaarT1 p g a b t) where BazaarT1 a <> BazaarT1 b = BazaarT1 $ \f -> a f <. b f {-# INLINE (<>) #-}
hvr/lens
src/Control/Lens/Internal/Bazaar.hs
bsd-3-clause
11,422
0
12
2,162
2,839
1,532
1,307
-1
-1
module Fibon.Run.CommandLine ( Opt(..) , UsageError , parseCommandLine , ReuseDir , RunMode(..) ) where import Data.Maybe import Data.List import Fibon.Run.Actions import Fibon.Run.Config import Fibon.Run.Manifest import System.Console.GetOpt type UsageError = String type ReuseDir = Maybe FilePath -- path to directory of already built benchmarks data RunMode = Sequential | Parallel data Opt = Opt { optConfig :: ConfigId , optHelpMsg :: Maybe String , optBenchmarks :: Maybe [BenchmarkRunSelection] , optTuneSetting :: Maybe TuneSetting , optSizeSetting :: Maybe InputSize , optIterations :: Maybe Int , optAction :: Action , optReuseDir :: ReuseDir , optRunMode :: RunMode , optIniConfig :: Bool } defaultOpts :: Opt defaultOpts = Opt { optConfig = "default" , optBenchmarks = Nothing , optHelpMsg = Nothing , optTuneSetting = Nothing , optSizeSetting = Nothing , optIterations = Nothing , optAction = Run , optReuseDir = Nothing , optRunMode = Sequential , optIniConfig = False } parseCommandLine :: [String] -> Either UsageError Opt parseCommandLine args = case getOpt Permute options args of (o, bms, []) -> let (oErrs, opts) = parseOpts o (bErrs, bs) = parseBenchs bms in case (oErrs, bErrs) of (Just oe, Just be) -> Left $ oe ++ be (Just oe, Nothing) -> Left $ oe (Nothing, Just be) -> Left $ be (Nothing, Nothing) -> Right $ opts {optBenchmarks = bs} (_,_,errs) -> Left (concat errs ++ usage) parseOpts :: [OptionParser] -> (Maybe UsageError, Opt) parseOpts = foldl (flip id) (Nothing, defaultOpts) parseBenchs :: [String] -> (Maybe UsageError, Maybe [BenchmarkRunSelection]) parseBenchs bms = (errors, benchs) where bmParses = map mbParse bms :: [Maybe FibonBenchmark] grParses = map mbParse bms :: [Maybe FibonGroup] parses = zipWith oneOrTheOther bmParses grParses errors = foldl collectErrors Nothing (zip bms parses) benchs = case catMaybes parses of [] -> Nothing; bs -> Just bs oneOrTheOther (Just b) _ = Just $ RunSingle b oneOrTheOther _ (Just g) = Just $ RunGroup g oneOrTheOther _ _ = Nothing collectErrors errs (bm, parse) = mbAddError errs parse ("Unknown benchmark: "++bm) type OptionParser = ((Maybe UsageError, Opt) -> (Maybe UsageError, Opt)) options :: [OptDescr OptionParser] options = [ Option ['h'] ["help"] (NoArg (\(e, opt) -> (e, opt {optHelpMsg = Just usage}))) "print a help message" , Option ['c'] ["config"] (ReqArg (\c (e, opt) -> (e, opt {optConfig = c})) "ConfigId") "default config settings" , Option ['t'] ["tune"] (ReqArg (\t (e, opt) -> let tune = mbParse t errs = mbAddError e tune ("Unknown tune setting: "++t) in (errs, opt {optTuneSetting = tune})) "TuneSetting" ) "override tune setting" , Option ['s'] ["size"] (ReqArg (\s (e, opt) -> let size = mbParse s errs = mbAddError e size ("Unknown size setting: "++s) in (errs, opt {optSizeSetting = size})) "InputSize" ) "override size setting" , Option ['i'] ["iters"] (ReqArg (\i (e, opt) -> let iter = mbParse i errs = mbAddError e iter ("Invalid iter setting: "++i) in (errs, opt {optIterations = iter})) "Int" ) "override number of iterations" , Option ['m'] ["manifest"] (NoArg (\(e, opt) -> (e, opt {optHelpMsg = Just manifest}))) "print manifest of configs and benchmarks" , Option ['a'] ["action"] (ReqArg (\a (e, opt) -> let act = mbParse a errs = mbAddError e act ("Invalid action setting: "++a) in (errs, opt {optAction = fromMaybe (optAction opt) act})) "Action" ) "override default action" , Option ['r'] ["reuse"] (ReqArg (\dir (e, opt) -> (e, opt {optReuseDir = Just dir})) "DIR") "reuse build results from directory" , Option ['p'] ["parallel"] (NoArg (\(e, opt) -> (e, opt {optRunMode = Parallel}))) "run benchmarks in parallel (for testing)" , Option [] ["dump-config"] (NoArg (\(e, opt) -> (e, opt {optIniConfig = True}))) "dump config to stdout in ini format" ] usage :: String usage = usageInfo header options where header = "Usage: fibon-run [OPTION...] [BENCHMARKS...]" mbAddError :: Maybe UsageError -> Maybe a -> UsageError -> Maybe UsageError mbAddError e p msg = case p of Just _success -> e Nothing -> case e of Just errs -> Just (errs ++ "\n" ++ msg) Nothing -> Just msg mbParse :: (Read a) => String -> Maybe a mbParse s = case reads s of [(a, "")] -> Just a _ -> Nothing manifest :: String manifest = "Configurations(" ++ nConfigs ++ ")\n " ++ configs ++ "\n" ++ "Benchmarks(" ++ nBenchs ++ ")\n " ++ bms ++ "\n" ++ "Groups(" ++ nGroups ++ ")\n " ++ grps where nConfigs = formatN configManifest nBenchs = formatN benchmarkManifest nGroups = formatN groupManifest configs = format configId configManifest bms = format show benchmarkManifest grps = format show groupManifest format f = concat . intersperse "\n " . map f formatN = show . length
dmpots/fibon
tools/fibon-run/Fibon/Run/CommandLine.hs
bsd-3-clause
5,513
0
18
1,603
1,804
997
807
137
5
{-# LANGUAGE OverloadedStrings #-} -- | Visualize a sparse adjacency matrix. module Web.Lightning.Plots.Adjacency ( AdjacencyPlot(..) , Visualization (..) , adjacencyPlot ) where -------------------------------------------------------------------------------- import Control.Monad.Reader import Data.Aeson import Data.Default.Class import qualified Data.Text as T import qualified Web.Lightning.Routes as R import Web.Lightning.Types.Lightning import Web.Lightning.Types.Visualization (Visualization (..)) import Web.Lightning.Utilities -------------------------------------------------------------------------------- -- | Adjacency plot parameters data AdjacencyPlot = AdjacencyPlot { apConn :: [[Double]] -- ^ Matrix that defines the connectivity of the plot. The -- dimensions of the matrix can be (n, n), (n, 2) or (n, 3). -- Matrix can be binary or continuous valued. Links should -- contain either 2 elements per link (source, target) or -- 3 elements (source, target, value). , apLabels :: Maybe [T.Text] -- ^ Text labels for each item (will label rows and columns). , apGroup :: Maybe [Int] -- ^ List to set colors via groups. , apSort :: Maybe T.Text -- ^ What to sort by; options are "group" or "degree." , apNumbers :: Maybe Bool -- ^ Whether or not to show numbers on cells. , apSymmetric :: Maybe Bool -- ^ Whether or not to make links symetrical. } deriving (Show, Eq) instance Default AdjacencyPlot where def = AdjacencyPlot [[]] Nothing Nothing (Just "group") (Just False) (Just True) instance ToJSON AdjacencyPlot where toJSON (AdjacencyPlot conn lbs grps srt nbrs sym) = omitNulls [ "links" .= getLinks conn , "nodes" .= getNodes conn , "labels" .= lbs , "group" .= grps , "numbers" .= nbrs , "symmetric" .= sym , "srt" .= srt ] instance ValidatablePlot AdjacencyPlot where validatePlot (AdjacencyPlot conn lbls grp srt nbrs sym) = do conn' <- validateConn conn return $ AdjacencyPlot conn' lbls grp srt nbrs sym -- | Submits a request to the specified lightning-viz server to create -- a sparse adjacency matrix visualiazation. -- -- <http://lightning-viz.org/visualizations/adjacency/ Adjacency Visualization> adjacencyPlot :: Monad m => AdjacencyPlot -- ^ Adjacency plot to create. -> LightningT m Visualization -- ^ Transformer stack with created visualization. adjacencyPlot adjPlt = do url <- ask viz <- sendPlot "adjacency" adjPlt R.plot return $ viz { vizBaseUrl = Just url }
cmoresid/lightning-haskell
src/Web/Lightning/Plots/Adjacency.hs
bsd-3-clause
3,047
0
11
992
469
268
201
43
1
module CNC.GInterpreter where import CNC.FanucMacro import CNC.Geometry import CNC.GParser import Control.Monad.Writer import Control.Monad.Trans import Data.Int import Data.IORef import Data.Maybe import qualified Data.Map as M import System.IO import Text.Printf import Debug.Trace -- Describes result of executing current frame data FrameResult = FR_Stop | FR_Move Move -- Describes move operation in declarative form data Move = M_FastLinear { m_p1 :: Pos, m_p2 :: Pos } | M_Linear { m_p1 :: Pos, m_p2 :: Pos, m_feed::RealT, m_tool :: Tool } | M_CircleCenter { m_p1 :: Pos, m_p2 :: Pos, m_center :: Pos, m_dir :: CircleDirection, m_feed::RealT, m_tool :: Tool } | M_CircleRadius { m_p1 :: Pos, m_p2 :: Pos, m_radius :: RealT, m_dir :: CircleDirection, m_feed::RealT, m_tool :: Tool } | M_ToolChange { m_tool :: Tool } deriving Show data CircleDirection = Clockwise | CounterClockwise deriving Show -- Type of move, mapped from G codes, so no actuial arguments data MoveType = MT_Fast | MT_Linear | MT_CW | MT_CCW -- Miscellaneous operations data OperationType = OT_NonOptionalStop | OT_ToolChange | OT_EndProgram deriving Show newtype Tool = Tool Int deriving (Show, Eq, Ord) type GTrace = [Move] fastSpeed = 20000 :: RealT toolChangeTime = 10 / 60 :: RealT -- in minutes resetToLinear = True -- Should we switch to Linear interpolation after circle or not gcodeToMoves :: GProgram -> IO GTrace gcodeToMoves (GProgram name frames) = do cur_frame_ref <- newIORef undefined -- for tracing purposes [x_ref,y_ref,z_ref] <- sequence $ replicate 3 $ newIORef 0 [i_ref,j_ref,k_ref] <- sequence $ replicate 3 $ newIORef Nothing r_ref <- newIORef Nothing move_type_ref <- newIORef MT_Fast op_type_ref <- newIORef Nothing feed_ref <- newIORef 0 tool_ref <- newIORef $ Tool 0 tool_changer_ref <- newIORef $ Tool 0 let -- processes entire frame, returns Move together with instructions what to do next run_frame (GFrame codes) = do moves <- proc_frame codes (return ()) mop <- readIORef op_type_ref op_effs <- proc_operation move_effs <- read_effect moves return $ op_effs ++ move_effs run_frame (GComment _) = return [] -- Accumulates effects of a frame proc_frame [] act = return act proc_frame (GInstrF axe val : rest) act | axe == 'X' = proc_move x_ref val rest act | axe == 'Y' = proc_move y_ref val rest act | axe == 'Z' = proc_move z_ref val rest act | axe == 'I' = proc_geom_setting i_ref val rest act | axe == 'J' = proc_geom_setting j_ref val rest act | axe == 'K' = proc_geom_setting k_ref val rest act | axe == 'R' = proc_geom_setting r_ref val rest act proc_frame (GInstrF 'F' val : rest) act = writeIORef feed_ref val >> proc_frame rest act proc_frame (GInstrI 'T' val : rest) act = writeIORef tool_changer_ref (Tool val) >> proc_frame rest act proc_frame (GInstrI 'G' val : rest) act = proc_gcode val rest act proc_frame (GInstrI 'M' val : rest) act = proc_mcode val rest act proc_frame (GInstrI 'N' _ : rest) act = proc_frame rest act proc_frame (instr:rest) act = do warn $ "skipping instruction " ++ show instr proc_frame rest act -- Stores encountered G instruction proc_gcode val rest act = do case val of 0 -> writeIORef move_type_ref MT_Fast 1 -> writeIORef move_type_ref MT_Linear 2 -> writeIORef move_type_ref MT_CW 3 -> writeIORef move_type_ref MT_CCW n -> warn $ "Ignoring gcode " ++ show n proc_frame rest act -- Stores encountered G instruction proc_mcode val rest act = do m <- readIORef op_type_ref case m of Nothing -> do case val of 0 -> writeIORef op_type_ref $ Just OT_NonOptionalStop 6 -> writeIORef op_type_ref $ Just OT_ToolChange 30 -> writeIORef op_type_ref $ Just OT_EndProgram n -> warn $ "Ignoring mcode " ++ show n proc_frame rest act Just mcode -> fail $ "got second Mcode in single frame in addition to " ++ show mcode -- Stores instruction specifying target coordinates, like X Y Z proc_move :: IORef RealT -> RealT -> [GInstr] -> IO () -> IO (IO ()) proc_move axe val rest act = proc_frame rest $ do act writeIORef axe val -- Stores instruction specifying target coordinates, like X Y Z proc_geom_setting :: IORef (Maybe RealT) -> RealT -> [GInstr] -> IO () -> IO (IO ()) proc_geom_setting axe val rest act = do val0 <- readIORef axe case val0 of Nothing -> writeIORef axe $ Just val Just _ -> warn $ printf "can't set value %s, already specified code in that frame" (show val) proc_frame rest act proc_operation = do mop <- readIORef op_type_ref writeIORef op_type_ref Nothing case mop of Nothing -> return [] Just OT_ToolChange -> do t <- readIORef tool_changer_ref writeIORef tool_ref t return [FR_Move $ M_ToolChange { m_tool = t }] Just OT_EndProgram -> return [FR_Stop] Just OT_NonOptionalStop -> return [FR_Stop] read_effect moves = do frame <- readIORef cur_frame_ref p1 <- read_pos moves p2 <- read_pos mt <- readIORef move_type_ref f <- readIORef feed_ref t <- readIORef tool_ref [r, i, j, k] <- mapM (\ref -> readIORef ref >>= \res -> writeIORef ref Nothing >> return res) [r_ref, i_ref,j_ref,k_ref] let radius_specified = isJust r center_specified = any isJust [i, j, k] circle_move dir | radius_specified = M_CircleRadius p1 p2 (fromJust r) dir f t | center_specified = M_CircleCenter p1 p2 (Pos (read_pos i) (read_pos j) (read_pos k)) dir f t | otherwise = error $ "circle interpolation was set, but neither center nor radius were specified in frame" ++ show frame read_pos = fromMaybe 0 case mt of MT_CW -> writeIORef move_type_ref MT_Linear MT_CCW -> writeIORef move_type_ref MT_Linear _ -> return () return $ (\x -> [x]) $ FR_Move $ case mt of MT_Fast -> M_FastLinear p1 p2 MT_Linear -> M_Linear p1 p2 f t MT_CW -> circle_move Clockwise MT_CCW -> circle_move CounterClockwise read_pos = do [xx,yy,zz] <- mapM readIORef [x_ref,y_ref,z_ref] return $ Pos xx yy zz iterateFrames [] [] = return [] iterateFrames (f:fs) [] = do writeIORef cur_frame_ref f res <- run_frame f iterateFrames fs res iterateFrames fs (r:rs) = case r of FR_Stop -> return [] FR_Move m -> do next <- iterateFrames fs rs return $ m : next iterateFrames frames [] data ProgramStatistics = ProgramStatistics { ps_time :: RealT, ps_fast_move_dist :: RealT, ps_tool_carve_stats :: M.Map Tool RealT } deriving (Show) gcode_stats = gcode_stats' 0 0 M.empty gcode_stats' time fast_move_dist tool_dists [] = ProgramStatistics { ps_time = time , ps_fast_move_dist = fast_move_dist , ps_tool_carve_stats = tool_dists } gcode_stats' time fast_move_dist tool_dists (cur_mov : moves) = case cur_mov of M_FastLinear p1 p2 -> let dst = dist p1 p2 in upd_stats dst Nothing tool_dists M_Linear p1 p2 _ _ -> let dst = dist p1 p2 in upd_work_stats dst M_CircleRadius p1 p2 r _ _ _ -> let dst = ark_dst p1 p2 r in trace (show (p1,p2, r, dst)) $ upd_work_stats dst M_CircleCenter p1 p2 c _ _ _ -> let r1 = dist p1 c r2 = dist p2 c dst = ark_dst p1 p2 r1 in if abs (r1 - r2) < eps then upd_work_stats dst else error $ "uneven distance between center and start and end points: " ++ show (c, p1,p2) M_ToolChange _ -> gcode_stats' (time + toolChangeTime) fast_move_dist tool_dists moves where upd_work_stats dst = upd_stats dst (Just $ m_feed cur_mov) (upd_tools (m_tool cur_mov) dst) upd_stats dst mfeed tools' = case mfeed of Just feed -> gcode_stats' (time + dt dst feed) fast_move_dist tools' moves Nothing -> gcode_stats' (time + dt dst fastSpeed) (fast_move_dist + dst) tools' moves upd_tools tool dst = M.insertWith (+) tool dst tool_dists dt dst feed = if dst < eps then 0 else dst / feed warn msg = hPutStrLn stderr msg
akamaus/gcodec
src/CNC/GInterpreter.hs
bsd-3-clause
9,294
0
21
3,111
2,675
1,326
1,349
163
29
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs, OverloadedStrings #-} module Main where import Language.LSP.Server import qualified Language.LSP.Test as Test import Language.LSP.Types import Control.Monad.IO.Class import Control.Monad import System.Process import System.Environment import System.Time.Extra import Control.Concurrent import Data.IORef handlers :: Handlers (LspM ()) handlers = mconcat [ requestHandler STextDocumentHover $ \req responder -> do let RequestMessage _ _ _ (HoverParams _doc pos _workDone) = req Position _l _c' = pos rsp = Hover ms (Just range) ms = HoverContents $ markedUpContent "lsp-demo-simple-server" "Hello world" range = Range pos pos responder (Right $ Just rsp) , requestHandler STextDocumentDefinition $ \req responder -> do let RequestMessage _ _ _ (DefinitionParams (TextDocumentIdentifier doc) pos _ _) = req responder (Right $ InL $ Location doc $ Range pos pos) ] server :: ServerDefinition () server = ServerDefinition { onConfigurationChange = const $ const $ Right () , defaultConfig = () , doInitialize = \env _req -> pure $ Right env , staticHandlers = handlers , interpretHandler = \env -> Iso (runLspT env) liftIO , options = defaultOptions } main :: IO () main = do (hinRead, hinWrite) <- createPipe (houtRead, houtWrite) <- createPipe n <- read . head <$> getArgs forkIO $ void $ runServerWithHandles hinRead houtWrite server liftIO $ putStrLn $ "Starting " <> show n <> " rounds" i <- newIORef 0 Test.runSessionWithHandles hinWrite houtRead Test.defaultConfig Test.fullCaps "." $ do start <- liftIO offsetTime replicateM_ n $ do n <- liftIO $ readIORef i liftIO $ when (n `mod` 1000 == 0) $ putStrLn $ show n ResponseMessage{_result=Right (Just _)} <- Test.request STextDocumentHover $ HoverParams (TextDocumentIdentifier $ Uri "test") (Position 1 100) Nothing ResponseMessage{_result=Right (InL _)} <- Test.request STextDocumentDefinition $ DefinitionParams (TextDocumentIdentifier $ Uri "test") (Position 1000 100) Nothing Nothing liftIO $ modifyIORef' i (+1) pure () end <- liftIO start liftIO $ putStrLn $ "Completed " <> show n <> " rounds in " <> showDuration end
alanz/haskell-lsp
lsp-test/bench/SimpleBench.hs
mit
2,410
0
19
598
764
382
382
54
1
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-} module GeneratorTestUtil where import Control.Applicative import Control.Monad (when) import Data.List (sortBy) import Language.Haskell.TH import Test.HUnit import Yesod.EmbeddedStatic.Types as Y import qualified Data.ByteString.Lazy as BL import RIO (HasCallStack) -- We test the generators by executing them at compile time -- and sticking the result into the GenTestResult. We then -- test the GenTestResult at runtime. But to test the ebDevelReload -- we must run the action at runtime so that is also embedded. -- Because of template haskell stage restrictions, this code -- needs to be in a separate module. data GenTestResult = GenError String | GenSuccessWithDevel (IO BL.ByteString) -- | Creates a GenTestResult at compile time by testing the entry. testEntry :: Maybe String -> Y.Location -> IO BL.ByteString -> Entry -> ExpQ testEntry name _ _ e | ebHaskellName e /= (mkName Control.Applicative.<$> name) = [| GenError ("haskell name " ++ $(litE $ stringL $ show $ ebHaskellName e) ++ " /= " ++ $(litE $ stringL $ show name)) |] testEntry _ loc _ e | ebLocation e /= loc = [| GenError ("location " ++ $(litE $ stringL $ show $ ebLocation e)) |] testEntry _ _ act e = do expected <- fmap stripCR $ runIO act actual <- fmap stripCR $ runIO $ ebProductionContent e if expected == actual then [| GenSuccessWithDevel $(ebDevelReload e) |] else [| GenError $ "production content: " ++ $(litE $ stringL $ show (expected, actual)) |] -- | Remove all carriage returns, for Windows testing stripCR :: BL.ByteString -> BL.ByteString stripCR = BL.filter (/= 13) testOneEntry :: Maybe String -> Y.Location -> IO BL.ByteString -> [Entry] -> ExpQ testOneEntry name loc ct [e] = testEntry name loc ct e testOneEntry _ _ _ _ = [| GenError "not exactly one entry" |] -- | Tests a list of entries testEntries :: [(Maybe String, Y.Location, IO BL.ByteString)] -> [Entry] -> ExpQ testEntries a b | length a /= length b = [| [GenError "lengths differ"] |] testEntries a b = listE $ zipWith f a' b' where a' = sortBy (\(_,l1,_) (_,l2,_) -> compare l1 l2) a b' = sortBy (\e1 e2 -> ebLocation e1 `compare` ebLocation e2) b f (name, loc, ct) e = testEntry name loc ct e -- | Use this at runtime to assert the 'GenTestResult' is OK assertGenResult :: HasCallStack => (IO BL.ByteString) -- ^ expected development content -> GenTestResult -- ^ test result created at compile time -> Assertion assertGenResult _ (GenError e) = assertFailure ("invalid " ++ e) assertGenResult mexpected (GenSuccessWithDevel mactual) = do expected <- fmap stripCR mexpected actual <- fmap stripCR mactual when (expected /= actual) $ assertFailure $ "invalid devel content: " ++ show (expected, actual)
geraldus/yesod
yesod-static/test/GeneratorTestUtil.hs
mit
2,957
0
12
679
697
375
322
-1
-1
{-# LANGUAGE DeriveGeneric, ViewPatterns #-} -- | Functionality for display of binary data. Seeing a visual representation of quantum random -- data lets a user visually verify that it is indeed random. -- -- Usually to be imported via the "Quantum.Random" module. module Quantum.Random.Display ( DisplayStyle (..), parseStyle, display ) where import GHC.Generics (Generic) import Data.Aeson (FromJSON,ToJSON) import System.Console.ANSI (Color (..), ColorIntensity (..)) import System.Console.Ansigraph (AnsiColor (AnsiColor), colorStr, fromFG) import System.Console.Terminal.Size (size,width) import Data.Word (Word8) import Data.Bits (testBit) import Data.Char (toLower) import Numeric (showHex) -- | Represents the supported methods for displaying binary data. -- All styles show data separated by byte except for 'Hex'. data DisplayStyle = Colors | Spins | Bits | Hex | ColorSpins | ColorBits | ColorHex deriving (Generic,Show,Eq) instance FromJSON DisplayStyle instance ToJSON DisplayStyle -- | Parse a string to one of the supported display styles. parseStyle :: String -> Maybe DisplayStyle parseStyle (map toLower -> "colors") = Just Colors parseStyle (map toLower -> "spins") = Just Spins parseStyle (map toLower -> "bits") = Just Bits parseStyle (map toLower -> "binary") = Just Bits parseStyle (map toLower -> "hex") = Just Hex parseStyle (map toLower -> "hexidecimal") = Just Hex parseStyle (map toLower -> "colorspins") = Just ColorSpins parseStyle (map toLower -> "colorbits") = Just ColorBits parseStyle (map toLower -> "colorbinary") = Just ColorBits parseStyle (map toLower -> "colorhex") = Just ColorHex parseStyle _ = Nothing ---- Interpreting as colors ---- -- 'Bits' type class indexes bits from least to most significant, thus the reverse w8bools :: Word8 -> [Bool] w8bools w = reverse $ testBit w <$> [0..7] type EightBits = (Bool,Bool,Bool,Bool,Bool,Bool,Bool,Bool) type FourBits = (Bool,Bool,Bool,Bool) byteBits :: Word8 -> EightBits byteBits (w8bools -> [a,b,c,d,e,f,g,h]) = (a,b,c,d,e,f,g,h) byteBits _ = error "byteBits: Impossible case: w8bools produces length-8 list" sepByte :: Word8 -> (FourBits, FourBits) sepByte (byteBits -> (a,b,c,d,e,f,g,h)) = ((a,b,c,d), (e,f,g,h)) color :: FourBits -> AnsiColor color (False,False,False,False) = AnsiColor Dull Black color (False,False,False,True) = AnsiColor Vivid Black color (False,False,True,False) = AnsiColor Dull Red color (False,False,True,True) = AnsiColor Vivid Red color (False,True,False,False) = AnsiColor Dull Green color (False,True,False,True) = AnsiColor Vivid Green color (False,True,True,False) = AnsiColor Dull Yellow color (False,True,True,True) = AnsiColor Vivid Yellow color (True,False,False,False) = AnsiColor Dull Blue color (True,False,False,True) = AnsiColor Vivid Blue color (True,False,True,False) = AnsiColor Dull Magenta color (True,False,True,True) = AnsiColor Vivid Magenta color (True,True,False,False) = AnsiColor Dull Cyan color (True,True,False,True) = AnsiColor Vivid Cyan color (True,True,True,False) = AnsiColor Dull White color (True,True,True,True) = AnsiColor Vivid White colorBlock :: AnsiColor -> IO () colorBlock c = colorStr (fromFG c) "█" ---- Interpreting as strings ---- binChar :: Bool -> Char binChar False = '0' binChar True = '1' spinChar :: Bool -> Char spinChar False = '↑' spinChar True = '↓' binStr :: FourBits -> String binStr (a,b,c,d) = [binChar a, binChar b, binChar c, binChar d] spinStr :: FourBits -> String spinStr (a,b,c,d) = [spinChar a, spinChar b, spinChar c, spinChar d] hexStr :: Word8 -> String hexStr w = let hx = showHex w "" in if length hx < 2 then '0' : hx else hx ---- Byte display functions ---- binDisplay :: Word8 -> IO () binDisplay (sepByte -> (x,y)) = do putStr $ (binStr x) ++ " " ++ (binStr y) ++ " " spinDisplay :: Word8 -> IO () spinDisplay (sepByte -> (x,y)) = do putStr $ (spinStr x) ++ " " ++ (spinStr y) ++ " " hexDisplay :: Word8 -> IO () hexDisplay = putStr . hexStr binColorDisplay :: Word8 -> IO () binColorDisplay (sepByte -> (x,y)) = do colorBlock (color x) colorBlock (color y) putStr $ " " ++ (binStr x) ++ " " ++ (binStr y) ++ " " spinColorDisplay :: Word8 -> IO () spinColorDisplay (sepByte -> (x,y)) = do colorBlock (color x) colorBlock (color y) putStr $ " " ++ (spinStr x) ++ " " ++ (spinStr y) ++ " " hexColorDisplay :: Word8 -> IO () hexColorDisplay w = do let (x,y) = sepByte w colorBlock (color x) colorBlock (color y) putStr $ " " ++ hexStr w ++ " " colorDisplay :: Word8 -> IO () colorDisplay (sepByte -> (x,y)) = do colorBlock (color x) colorBlock (color y) ---- Interpreting as display IO actions ---- displayByte :: DisplayStyle -> Word8 -> IO () displayByte Colors = colorDisplay displayByte Spins = spinDisplay displayByte Bits = binDisplay displayByte ColorSpins = spinColorDisplay displayByte ColorBits = binColorDisplay displayByte Hex = hexDisplay displayByte ColorHex = hexColorDisplay -- How many characters each display style uses per byte byteSize :: DisplayStyle -> Int byteSize ColorHex = 6 byteSize ColorBits = 13 byteSize ColorSpins = 13 byteSize Bits = 11 byteSize Spins = 11 byteSize Hex = 2 byteSize Colors = 1 insertEvery :: Int -> a -> [a] -> [a] insertEvery n x l = take n l ++ nl where nl = if length (drop n l) > 0 then (x : insertEvery n x (drop n l)) else [] -- Obtain the character-width of the terminal. On failure assume a conservative default. termWidth :: IO Int termWidth = do mw <- fmap width <$> size case mw of Just w -> pure w Nothing -> pure 80 -- Display data, such that no byte is broken by a new line. displayBytes :: DisplayStyle -> [Word8] -> IO () displayBytes sty ws = do w <- termWidth let bw = w `div` byteSize sty sequence_ $ insertEvery bw (putStrLn "") $ displayByte sty <$> ws -- | Display a given list of bytes with the specified display style. display :: DisplayStyle -> [Word8] -> IO () display Hex l = putStrLn $ concatMap hexStr l display s l = displayBytes s l *> putStrLn ""
BlackBrane/quantum-random-numbers
src-lib/Quantum/Random/Display.hs
mit
6,515
0
12
1,534
2,267
1,213
1,054
139
2
<?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="sl-SI"> <title>Python Scripting</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>
veggiespam/zap-extensions
addOns/jython/src/main/javahelp/org/zaproxy/zap/extension/jython/resources/help_sl_SI/helpset_sl_SI.hs
apache-2.0
962
91
29
157
391
210
181
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Qth.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:01:40 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qth ( module Qth.Core ) where import Qth.Core
keera-studios/hsQt
Qth.hs
bsd-2-clause
467
0
5
91
21
15
6
4
0
{-# LANGUAGE CPP, DataKinds, TypeOperators, TypeApplications, TypeFamilies #-} #if __GLASGOW_HASKELL__ >= 805 {-# LANGUAGE NoStarIsType #-} #endif {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Extra.Solver #-} import Data.List (isInfixOf) import Data.Proxy import Data.Type.Bool import Control.Exception import Test.Tasty import Test.Tasty.HUnit import ErrorTests import GHC.TypeLits import GHC.TypeLits.Extra test1 :: Proxy (GCD 6 8) -> Proxy 2 test1 = id test2 :: Proxy ((GCD 6 8) + x) -> Proxy (x + (GCD 10 8)) test2 = id test3 :: Proxy (CLog 3 10) -> Proxy 3 test3 = id test4 :: Proxy ((CLog 3 10) + x) -> Proxy (x + (CLog 2 7)) test4 = id test5 :: Proxy (CLog x (x^y)) -> Proxy y test5 = id test6 :: Integer test6 = natVal (Proxy :: Proxy (CLog 6 8)) test7 :: Integer test7 = natVal (Proxy :: Proxy (CLog 3 10)) test8 :: Integer test8 = natVal (Proxy :: Proxy ((CLog 2 4) * (3 ^ (CLog 2 4)))) test9 :: Integer test9 = natVal (Proxy :: Proxy (Max (CLog 2 4) (CLog 4 20))) test10 :: Proxy (Div 9 3) -> Proxy 3 test10 = id test11 :: Proxy (Div 9 4) -> Proxy 2 test11 = id test12 :: Proxy (Mod 9 3) -> Proxy 0 test12 = id test13 :: Proxy (Mod 9 4) -> Proxy 1 test13 = id test14 :: Integer test14 = natVal (Proxy :: Proxy (Div 9 3)) test15 :: Integer test15 = natVal (Proxy :: Proxy (Mod 9 4)) test16 :: Proxy (LCM 18 7) -> Proxy 126 test16 = id test17 :: Integer test17 = natVal (Proxy :: Proxy (LCM 18 7)) test18 :: Proxy ((LCM 6 4) + x) -> Proxy (x + (LCM 3 4)) test18 = id test19 :: Integer test19 = natVal (Proxy :: Proxy (FLog 3 1)) test20 :: Proxy (FLog 3 1) -> Proxy 0 test20 = id test21 :: Integer test21 = natVal (Proxy :: Proxy (CLog 3 1)) test22 :: Proxy (CLog 3 1) -> Proxy 0 test22 = id test23 :: Integer test23 = natVal (Proxy :: Proxy (Log 3 1)) test24 :: Integer test24 = natVal (Proxy :: Proxy (Log 3 9)) test25 :: Proxy (Log 3 9) -> Proxy 2 test25 = id test26 :: Proxy (b ^ (Log b y)) -> Proxy y test26 = id test27 :: Proxy (Max n n) -> Proxy n test27 = id test28 :: Proxy (Min n n) -> Proxy n test28 = id test29 :: Proxy (Max n n + 1) -> Proxy (1 + n) test29 = id test30 :: Proxy n -> Proxy (1 + Max n n) -> Proxy (Min n n + 1) test30 _ = id test31 :: Proxy (Min n (n + 1)) -> Proxy n test31 = id test32 :: Proxy (Min (n + 1) n) -> Proxy n test32 = id test33 :: Proxy (Max n (n + 1)) -> Proxy (n+1) test33 = id test34 :: Proxy (Max (n + 1) n) -> Proxy (n+1) test34 = id test35 :: Proxy n -> Proxy (1 + Max n (1 + n)) -> Proxy (n + 2) test35 _ = id test36 :: Proxy n -> Proxy (1 + Min n (1 + n)) -> Proxy (n + 1) test36 _ = id test37 :: (1 <= Div l r) => Proxy l -> Proxy r -> () test37 _ _ = () test38 :: Proxy (Min (0-1) 0) -> Proxy (0-1) test38 = id test39 :: Proxy (Max (0-1) 0) -> Proxy (0-1) test39 = id test40 :: Proxy x -> Proxy y -> Proxy (Max x y) -> Proxy (Max y x) test40 _ _ = id test41 :: Proxy x -> Proxy y -> Proxy (Min x y) -> Proxy (Min y x) test41 _ _ = id test42 :: Proxy x -> Proxy y -> Proxy (GCD x y) -> Proxy (GCD y x) test42 _ _ = id test43 :: Proxy x -> Proxy y -> Proxy (LCM x y) -> Proxy (LCM y x) test43 _ _ = id test44 :: Proxy x -> Proxy y -> Proxy (x <=? (Max x y)) -> Proxy True test44 _ _ = id test45 :: Proxy x -> Proxy y -> Proxy (y <=? (Max x y)) -> Proxy True test45 _ _ = id test46 :: n ~ (Max x y) => Proxy x -> Proxy y -> Proxy (x <=? n) -> Proxy True test46 _ _ = id test47 :: n ~ (Max x y) => Proxy x -> Proxy y -> Proxy (y <=? n) -> Proxy True test47 _ _ = id test48 :: Proxy n -> Proxy (Max (1+n) 1) -> Proxy (n+1) test48 _ = id test49 :: Proxy n -> Proxy (Max (n+1) 1) -> Proxy (1+n) test49 _ = id test50 :: Proxy n -> Proxy (Max (n+2) 1) -> Proxy (Max (2+n) 2) test50 _ = id test51 :: Proxy n -> Proxy (Max (((2 ^ n) + 1) + ((2 ^ n) + 1)) 1) -> Proxy (2+((2^n)*2)) test51 _ = id type family BitPack a :: Nat test52 :: Proxy a -> Proxy (1 + BitPack a) -> Proxy (Max 0 (BitPack a) + CLog 2 2) test52 _ = id test53 :: Proxy n -> Proxy (1 <=? Max (n + 1) 1) -> Proxy True test53 _ = id test54 :: Proxy n -> Proxy (n <=? Max (n + 1) 1) -> Proxy True test54 _ = id test55 :: Proxy n -> Proxy (n + 1 <=? Max (n + 1) 1) -> Proxy True test55 _ = id test56 :: Proxy n -> Proxy p -> Proxy (n <=? Max (n + p) p) -> Proxy True test56 _ _ = id test57 :: Proxy n -> Proxy p -> Proxy (n + 1 <=? Max (n + p + 1) p) -> Proxy True test57 _ _ = id main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "ghc-typelits-natnormalise" [ testGroup "Basic functionality" [ testCase "GCD 6 8 ~ 2" $ show (test1 Proxy) @?= "Proxy" , testCase "forall x . GCD 6 8 + x ~ x + GCD 10 8" $ show (test2 Proxy) @?= "Proxy" , testCase "CLog 3 10 ~ 3" $ show (test3 Proxy) @?= "Proxy" , testCase "forall x . CLog 3 10 + x ~ x + CLog 2 7" $ show (test4 Proxy) @?= "Proxy" , testCase "forall x>1 . CLog x (x^y) ~ y" $ show (test5 Proxy) @?= "Proxy" , testCase "KnownNat (CLog 6 8) ~ 2" $ show test6 @?= "2" , testCase "KnownNat (CLog 3 10) ~ 3" $ show test7 @?= "3" , testCase "KnownNat ((CLog 2 4) * (3 ^ (CLog 2 4)))) ~ 18" $ show test8 @?= "18" , testCase "KnownNat (Max (CLog 2 4) (CLog 4 20)) ~ 3" $ show test9 @?= "3" , testCase "Div 9 3 ~ 3" $ show (test10 Proxy) @?= "Proxy" , testCase "Div 9 4 ~ 2" $ show (test11 Proxy) @?= "Proxy" , testCase "Mod 9 3 ~ 0" $ show (test12 Proxy) @?= "Proxy" , testCase "Mod 9 4 ~ 1" $ show (test13 Proxy) @?= "Proxy" , testCase "KnownNat (Div 9 3) ~ 3" $ show test14 @?= "3" , testCase "KnownNat (Mod 9 4) ~ 1" $ show test15 @?= "1" , testCase "LCM 18 7 ~ 126" $ show (test16 Proxy) @?= "Proxy" , testCase "KnownNat (LCM 18 7) ~ 126" $ show test17 @?= "126" , testCase "forall x . LCM 3 4 + x ~ x + LCM 6 4" $ show (test18 Proxy) @?= "Proxy" , testCase "KnownNat (FLog 3 1) ~ 0" $ show test19 @?= "0" , testCase "FLog 3 1 ~ 0" $ show (test20 Proxy) @?= "Proxy" , testCase "KnownNat (CLog 3 1) ~ 0" $ show test21 @?= "0" , testCase "CLog 3 1 ~ 0" $ show (test22 Proxy) @?= "Proxy" , testCase "KnownNat (Log 3 1) ~ 0" $ show test23 @?= "0" , testCase "KnownNat (Log 3 9) ~ 2" $ show test24 @?= "2" , testCase "Log 3 9 ~ 2" $ show (test25 Proxy) @?= "Proxy" , testCase "forall x>1 . x ^ (Log x y) ~ y" $ show (test26 Proxy) @?= "Proxy" , testCase "forall x . Max x x ~ x" $ show (test27 Proxy) @?= "Proxy" , testCase "forall x . Min x x ~ x" $ show (test28 Proxy) @?= "Proxy" , testCase "forall x . (Max x x + 1) ~ (1 + x)" $ show (test29 Proxy) @?= "Proxy" , testCase "forall x . (Min x x + 1) ~ (1 + Max x x)" $ show (test30 Proxy Proxy) @?= "Proxy" , testCase "forall x . Min x (x+1) ~ x" $ show (test31 Proxy) @?= "Proxy" , testCase "forall x . Min (x+1) x ~ x" $ show (test32 Proxy) @?= "Proxy" , testCase "forall x . Max x (x+1) ~ (x+1)" $ show (test33 Proxy) @?= "Proxy" , testCase "forall x . Max (x+1) x ~ (x+1)" $ show (test34 Proxy) @?= "Proxy" , testCase "forall x . (1 + Max n (1+n)) ~ (2 + x)" $ show (test35 Proxy Proxy) @?= "Proxy" , testCase "forall x . (1 + Min n (1+n)) ~ (1 + x)" $ show (test36 Proxy Proxy) @?= "Proxy" , testCase "1 <= Div 18 3" $ show (test37 (Proxy @18) (Proxy @3)) @?= "()" , testCase "Min (0-1) 0 ~ (0-1)" $ show (test38 Proxy) @?= "Proxy" , testCase "Max (0-1) 0 ~ (0-1)" $ show (test39 Proxy) @?= "Proxy" , testCase "forall x y . Max x y ~ Max y x" $ show (test40 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall x y . Min x y ~ Min y x" $ show (test41 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall x y . GCD x y ~ GCD y x" $ show (test42 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall x y . LCM x y ~ LCM y x" $ show (test43 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall x y . x <=? Max x y ~ True" $ show (test44 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall x y . y <=? Max x y ~ True" $ show (test45 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall x y n . n ~ Max x y => x <=? n ~ True" $ show (test46 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall x y n . n ~ Max x y => y <=? n ~ True" $ show (test47 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall n . Max (n+1) 1 ~ 1+n" $ show (test48 Proxy Proxy) @?= "Proxy" , testCase "forall n . Max (1+n) 1 ~ n+1" $ show (test49 Proxy Proxy) @?= "Proxy" , testCase "forall n . Max (n+2) 1 ~ Max (2+n) 2" $ show (test50 Proxy Proxy) @?= "Proxy" , testCase "forall n . Max (((2 ^ n) + 1) + ((2 ^ n) + 1)) 1 ~ 2 + ((2 ^ n) * 2)" $ show (test51 Proxy Proxy) @?= "Proxy" , testCase "forall a . (1 + BitPack a) ~ (Max 0 (BitPack a) + CLog 2 2" $ show (test52 Proxy Proxy) @?= "Proxy" , testCase "forall n . 1 <= Max (n + 1) 1" $ show (test53 Proxy Proxy) @?= "Proxy" , testCase "forall n . n <= Max (n + 1) 1" $ show (test54 Proxy Proxy) @?= "Proxy" , testCase "forall n . n + 1 <= Max (n + 1) 1" $ show (test55 Proxy Proxy) @?= "Proxy" , testCase "forall n p . n <= Max (n + p) p" $ show (test56 Proxy Proxy Proxy) @?= "Proxy" , testCase "forall n p . n + 1 <= Max (n + p + 1) p" $ show (test57 Proxy Proxy Proxy) @?= "Proxy" ] , testGroup "errors" [ testCase "GCD 6 8 /~ 4" $ testFail1 `throws` testFail1Errors , testCase "GCD 6 8 + x /~ x + GCD 9 6" $ testFail2 `throws` testFail2Errors , testCase "CLog 3 10 /~ 2" $ testFail3 `throws` testFail3Errors , testCase "CLog 3 10 + x /~ x + CLog 2 9" $ testFail4 `throws` testFail4Errors , testCase "CLog 0 4 /~ 100" $ testFail5 `throws` testFail5Errors , testCase "CLog 1 4 /~ 100" $ testFail5 `throws` testFail5Errors , testCase "CLog 4 0 /~ 0" $ testFail7 `throws` testFail7Errors , testCase "CLog 1 (1^y) /~ y" $ testFail8 `throws` testFail8Errors , testCase "CLog 0 (0^y) /~ y" $ testFail9 `throws` testFail9Errors , testCase "No instance (KnownNat (CLog 1 4))" $ testFail10 `throws` testFail10Errors , testCase "No instance (KnownNat (CLog 4 4 - CLog 2 4))" $ testFail11 `throws` testFail11Errors , testCase "Div 4 0 /~ 4" $ testFail12 `throws` testFail12Errors , testCase "Mod 4 0 /~ 4" $ testFail13 `throws` testFail13Errors , testCase "FLog 0 4 /~ 100" $ testFail14 `throws` testFail14Errors , testCase "FLog 1 4 /~ 100" $ testFail15 `throws` testFail15Errors , testCase "FLog 4 0 /~ 0" $ testFail16 `throws` testFail16Errors , testCase "GCD 6 8 /~ 4" $ testFail17 `throws` testFail17Errors , testCase "GCD 6 8 + x /~ x + GCD 9 6" $ testFail18 `throws` testFail18Errors , testCase "No instance (KnownNat (Log 3 0))" $ testFail19 `throws` testFail19Errors , testCase "No instance (KnownNat (Log 3 10))" $ testFail20 `throws` testFail20Errors , testCase "Min a (a*b) /~ a" $ testFail21 `throws` testFail21Errors , testCase "Max a (a*b) /~ (a*b)" $ testFail22 `throws` testFail22Errors , testCase "(1 <=? Div 18 6) ~ False" $ testFail23 `throws` testFail23Errors , testCase "(z <=? Max x y) /~ True" $ testFail24 `throws` testFail24Errors , testCase "(x+1 <=? Max x y) /~ True" $ testFail25 `throws` testFail25Errors , testCase "(x <= n) /=> (Max x y) ~ n" $ testFail26 `throws` testFail26Errors , testCase "n + 2 <=? Max (n + 1) 1 /~ True" $ testFail27 `throws` testFail27Errors ] ] -- | Assert that evaluation of the first argument (to WHNF) will throw -- an exception whose string representation contains the given -- substrings. throws :: a -> [String] -> Assertion throws v xs = do result <- try (evaluate v) case result of Right _ -> assertFailure "No exception!" Left (TypeError msg) -> if all (`isInfixOf` (removeProblemChars msg)) $ map removeProblemChars xs then return () else assertFailure msg -- The kind and amount of quotes in GHC error messages changes depending on -- whether or not our locale supports unicode. -- Remove the problematic characters to enable comparison of errors. removeProblemChars = filter (`notElem` problemChars) where problemChars = "‘’`'"
christiaanb/ghc-typelits-extra
tests/Main.hs
bsd-2-clause
12,832
1
16
3,678
4,775
2,322
2,453
-1
-1
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE CPP #-} module Foundation.Check.Arbitrary ( Arbitrary(..) , frequency , oneof , elements , between ) where import Basement.Imports import Foundation.Primitive import Basement.Nat import Basement.Cast (cast) import Basement.IntegralConv import Basement.Bounded import Basement.Types.OffsetSize import qualified Basement.Types.Char7 as Char7 import Basement.Types.Word128 (Word128(..)) import Basement.Types.Word256 (Word256(..)) #if __GLASGOW_HASKELL__ >= 710 import qualified Basement.Sized.List as ListN #endif import Foundation.Check.Gen import Foundation.Random import Foundation.Bits import Foundation.Collection import Foundation.Numerical import Control.Monad (replicateM) -- | How to generate an arbitrary value for 'a' class Arbitrary a where arbitrary :: Gen a instance Arbitrary Integer where arbitrary = arbitraryInteger instance Arbitrary Natural where arbitrary = arbitraryNatural instance (NatWithinBound Word64 n, KnownNat n) => Arbitrary (Zn64 n) where arbitrary = zn64 <$> arbitrary instance KnownNat n => Arbitrary (Zn n) where arbitrary = zn <$> arbitraryNatural -- prim types instance Arbitrary Int where arbitrary = int64ToInt <$> arbitraryInt64 instance Arbitrary Word where arbitrary = word64ToWord <$> arbitraryWord64 instance Arbitrary Word256 where arbitrary = Word256 <$> arbitraryWord64 <*> arbitraryWord64 <*> arbitraryWord64 <*> arbitraryWord64 instance Arbitrary Word128 where arbitrary = Word128 <$> arbitraryWord64 <*> arbitraryWord64 instance Arbitrary Word64 where arbitrary = arbitraryWord64 instance Arbitrary Word32 where arbitrary = integralDownsize <$> arbitraryWord64 instance Arbitrary Word16 where arbitrary = integralDownsize <$> arbitraryWord64 instance Arbitrary Word8 where arbitrary = integralDownsize <$> arbitraryWord64 instance Arbitrary Int64 where arbitrary = arbitraryInt64 instance Arbitrary Int32 where arbitrary = integralDownsize <$> arbitraryInt64 instance Arbitrary Int16 where arbitrary = integralDownsize <$> arbitraryInt64 instance Arbitrary Int8 where arbitrary = integralDownsize <$> arbitraryInt64 instance Arbitrary Char where arbitrary = arbitraryChar instance Arbitrary Char7 where arbitrary = Char7.fromByteMask . integralDownsize <$> arbitraryWord64 instance Arbitrary (CountOf ty) where arbitrary = CountOf <$> arbitrary instance Arbitrary Bool where arbitrary = flip testBit 0 <$> arbitraryWord64 instance Arbitrary String where arbitrary = genWithParams $ \params -> fromList <$> (genMax (genMaxSizeString params) >>= \i -> replicateM (cast i) arbitrary) instance Arbitrary AsciiString where arbitrary = genWithParams $ \params -> fromList <$> (genMax (genMaxSizeString params) >>= \i -> replicateM (cast i) arbitrary) instance Arbitrary Float where arbitrary = arbitraryF32 instance Arbitrary Double where arbitrary = arbitraryF64 instance Arbitrary a => Arbitrary (Maybe a) where arbitrary = frequency $ nonEmpty_ [ (1, pure Nothing), (4, Just <$> arbitrary) ] instance (Arbitrary l, Arbitrary r) => Arbitrary (Either l r) where arbitrary = oneof $ nonEmpty_ [ Left <$> arbitrary, Right <$> arbitrary ] instance (Arbitrary a, Arbitrary b) => Arbitrary (a,b) where arbitrary = (,) <$> arbitrary <*> arbitrary instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (a,b,c) where arbitrary = (,,) <$> arbitrary <*> arbitrary <*> arbitrary instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Arbitrary (a,b,c,d) where arbitrary = (,,,) <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e) => Arbitrary (a,b,c,d,e) where arbitrary = (,,,,) <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e, Arbitrary f) => Arbitrary (a,b,c,d,e,f) where arbitrary = (,,,,,) <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary a => Arbitrary [a] where arbitrary = genWithParams $ \params -> fromList <$> (genMax (genMaxSizeArray params) >>= \i -> replicateM (cast i) arbitrary) #if __GLASGOW_HASKELL__ >= 710 instance (Arbitrary a, KnownNat n, NatWithinBound Int n) => Arbitrary (ListN.ListN n a) where arbitrary = ListN.replicateM arbitrary #endif arbitraryInteger :: Gen Integer arbitraryInteger = -- TODO use the sized parameter frequency $ nonEmpty_ [ (4, integerOfSize True 2) , (4, integerOfSize False 2) , (4, integerOfSize True 4) , (4, integerOfSize False 4) , (2, integerOfSize True 8) , (2, integerOfSize False 8) , (1, integerOfSize True 16) , (1, integerOfSize False 16) ] where integerOfSize :: Bool -> Word -> Gen Integer integerOfSize toSign n = ((if toSign then negate else id) . foldl' (\x y -> x + integralUpsize y) 0 . toList) <$> (arbitraryUArrayOf n :: Gen (UArray Word8)) arbitraryNatural :: Gen Natural arbitraryNatural = integralDownsize . abs <$> arbitraryInteger arbitraryChar :: Gen Char arbitraryChar = frequency $ nonEmpty_ [ (6, wordToChar <$> genMax 128) , (1, wordToChar <$> genMax 0x10ffff) ] arbitraryWord64 :: Gen Word64 arbitraryWord64 = genWithRng getRandomWord64 arbitraryInt64 :: Gen Int64 arbitraryInt64 = cast <$> arbitraryWord64 arbitraryF64 :: Gen Double arbitraryF64 = genWithRng getRandomF64 arbitraryF32 :: Gen Float arbitraryF32 = genWithRng getRandomF32 arbitraryUArrayOf :: (PrimType ty, Arbitrary ty) => Word -> Gen (UArray ty) arbitraryUArrayOf size = between (0, size) >>= \sz -> fromList <$> replicateM (cast sz) arbitrary -- | Call one of the generator weighted frequency :: NonEmpty [(Word, Gen a)] -> Gen a frequency (getNonEmpty -> l) = between (0, sum) >>= pickOne l where sum :: Word !sum = foldl' (+) 0 $ fmap fst l pickOne ((k,x):xs) n | n <= k = x | otherwise = pickOne xs (n-k) pickOne _ _ = error "frequency" oneof :: NonEmpty [Gen a] -> Gen a oneof ne = frequency (nonEmptyFmap (\x -> (1, x)) ne) elements :: NonEmpty [a] -> Gen a elements l = frequency (nonEmptyFmap (\x -> (1, pure x)) l) between :: (Word, Word) -> Gen Word between (x,y) | range == 0 = pure x | otherwise = (+) x <$> genMax range where range = y - x genMax :: Word -> Gen Word genMax m = flip mod m <$> arbitrary
vincenthz/hs-foundation
foundation/Foundation/Check/Arbitrary.hs
bsd-3-clause
6,855
0
15
1,458
2,120
1,146
974
-1
-1
{- (c) The AQUA Project, Glasgow University, 1993-1998 \section{Common subexpression} -} {-# LANGUAGE CPP #-} module CSE (cseProgram) where #include "HsVersions.h" import CoreSubst import Var ( Var ) import Id ( Id, idType, idInlineActivation, zapIdOccInfo ) import CoreUtils ( mkAltExpr , exprIsTrivial , stripTicksE, stripTicksT, stripTicksTopE, mkTick, mkTicks ) import Type ( tyConAppArgs ) import CoreSyn import Outputable import BasicTypes ( isAlwaysActive ) import TrieMap import Data.List {- Simple common sub-expression ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we see x1 = C a b x2 = C x1 b we build up a reverse mapping: C a b -> x1 C x1 b -> x2 and apply that to the rest of the program. When we then see y1 = C a b y2 = C y1 b we replace the C a b with x1. But then we *dont* want to add x1 -> y1 to the mapping. Rather, we want the reverse, y1 -> x1 so that a subsequent binding y2 = C y1 b will get transformed to C x1 b, and then to x2. So we carry an extra var->var substitution which we apply *before* looking up in the reverse mapping. Note [Shadowing] ~~~~~~~~~~~~~~~~ We have to be careful about shadowing. For example, consider f = \x -> let y = x+x in h = \x -> x+x in ... Here we must *not* do CSE on the inner x+x! The simplifier used to guarantee no shadowing, but it doesn't any more (it proved too hard), so we clone as we go. We can simply add clones to the substitution already described. Note [Case binders 1] ~~~~~~~~~~~~~~~~~~~~~~ Consider f = \x -> case x of wild { (a:as) -> case a of wild1 { (p,q) -> ...(wild1:as)... Here, (wild1:as) is morally the same as (a:as) and hence equal to wild. But that's not quite obvious. In general we want to keep it as (wild1:as), but for CSE purpose that's a bad idea. So we add the binding (wild1 -> a) to the extra var->var mapping. Notice this is exactly backwards to what the simplifier does, which is to try to replaces uses of 'a' with uses of 'wild1' Note [Case binders 2] ~~~~~~~~~~~~~~~~~~~~~~ Consider case (h x) of y -> ...(h x)... We'd like to replace (h x) in the alternative, by y. But because of the preceding [Note: case binders 1], we only want to add the mapping scrutinee -> case binder to the reverse CSE mapping if the scrutinee is a non-trivial expression. (If the scrutinee is a simple variable we want to add the mapping case binder -> scrutinee to the substitution Note [CSE for INLINE and NOINLINE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are some subtle interactions of CSE with functions that the user has marked as INLINE or NOINLINE. (Examples from Roman Leshchinskiy.) Consider yes :: Int {-# NOINLINE yes #-} yes = undefined no :: Int {-# NOINLINE no #-} no = undefined foo :: Int -> Int -> Int {-# NOINLINE foo #-} foo m n = n {-# RULES "foo/no" foo no = id #-} bar :: Int -> Int bar = foo yes We do not expect the rule to fire. But if we do CSE, then we risk getting yes=no, and the rule does fire. Actually, it won't because NOINLINE means that 'yes' will never be inlined, not even if we have yes=no. So that's fine (now; perhaps in the olden days, yes=no would have substituted even if 'yes' was NOINLINE. But we do need to take care. Consider {-# NOINLINE bar #-} bar = <rhs> -- Same rhs as foo foo = <rhs> If CSE produces foo = bar then foo will never be inlined to <rhs> (when it should be, if <rhs> is small). The conclusion here is this: We should not add <rhs> :-> bar to the CSEnv if 'bar' has any constraints on when it can inline; that is, if its 'activation' not always active. Otherwise we might replace <rhs> by 'bar', and then later be unable to see that it really was <rhs>. Note that we do not (currently) do CSE on the unfolding stored inside an Id, even if is a 'stable' unfolding. That means that when an unfolding happens, it is always faithful to what the stable unfolding originally was. Note [CSE for case expressions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider case f x of y { pat -> ...let y = f x in ... } Then we can CSE the inner (f x) to y. In fact 'case' is like a strict let-binding, and we can use cseRhs for dealing with the scrutinee. ************************************************************************ * * \section{Common subexpression} * * ************************************************************************ -} cseProgram :: CoreProgram -> CoreProgram cseProgram binds = snd (mapAccumL cseBind emptyCSEnv binds) cseBind :: CSEnv -> CoreBind -> (CSEnv, CoreBind) cseBind env (NonRec b e) = (env2, NonRec b' e') where (env1, b') = addBinder env b (env2, e') = cseRhs env1 (b',e) cseBind env (Rec pairs) = (env2, Rec (bs' `zip` es')) where (bs,es) = unzip pairs (env1, bs') = addRecBinders env bs (env2, es') = mapAccumL cseRhs env1 (bs' `zip` es) cseRhs :: CSEnv -> (OutBndr, InExpr) -> (CSEnv, OutExpr) cseRhs env (id',rhs) = case lookupCSEnv env rhs'' of Nothing | always_active -> (extendCSEnv env rhs' id', rhs') | otherwise -> (env, rhs') Just id | always_active -> (extendCSSubst env id' id, mkTicks ticks $ Var id) | otherwise -> (env, mkTicks ticks $ Var id) -- In the Just case, we have -- x = rhs -- ... -- x' = rhs -- We are replacing the second binding with x'=x -- and so must record that in the substitution so -- that subsequent uses of x' are replaced with x, -- See Trac #5996 where rhs' = cseExpr env rhs ticks = stripTicksT tickishFloatable rhs' rhs'' = stripTicksE tickishFloatable rhs' -- We don't want to lose the source notes when a common sub -- expression gets eliminated. Hence we push all (!) of them on -- top of the replaced sub-expression. This is probably not too -- useful in practice, but upholds our semantics. always_active = isAlwaysActive (idInlineActivation id') -- See Note [CSE for INLINE and NOINLINE] tryForCSE :: CSEnv -> InExpr -> OutExpr tryForCSE env expr | exprIsTrivial expr' = expr' -- No point | Just smaller <- lookupCSEnv env expr'' = foldr mkTick (Var smaller) ticks | otherwise = expr' where expr' = cseExpr env expr expr'' = stripTicksE tickishFloatable expr' ticks = stripTicksT tickishFloatable expr' cseExpr :: CSEnv -> InExpr -> OutExpr cseExpr env (Type t) = Type (substTy (csEnvSubst env) t) cseExpr env (Coercion c) = Coercion (substCo (csEnvSubst env) c) cseExpr _ (Lit lit) = Lit lit cseExpr env (Var v) = lookupSubst env v cseExpr env (App f a) = App (cseExpr env f) (tryForCSE env a) cseExpr env (Tick t e) = Tick t (cseExpr env e) cseExpr env (Cast e co) = Cast (cseExpr env e) (substCo (csEnvSubst env) co) cseExpr env (Lam b e) = let (env', b') = addBinder env b in Lam b' (cseExpr env' e) cseExpr env (Let bind e) = let (env', bind') = cseBind env bind in Let bind' (cseExpr env' e) cseExpr env (Case scrut bndr ty alts) = Case scrut' bndr'' ty alts' where alts' = cseAlts env2 scrut' bndr bndr'' alts (env1, bndr') = addBinder env bndr bndr'' = zapIdOccInfo bndr' -- The swizzling from Note [Case binders 2] may -- cause a dead case binder to be alive, so we -- play safe here and bring them all to life (env2, scrut') = cseRhs env1 (bndr'', scrut) -- Note [CSE for case expressions] cseAlts :: CSEnv -> OutExpr -> InBndr -> InBndr -> [InAlt] -> [OutAlt] cseAlts env scrut' bndr bndr' alts = map cse_alt alts where scrut'' = stripTicksTopE tickishFloatable scrut' (con_target, alt_env) = case scrut'' of Var v' -> (v', extendCSSubst env bndr v') -- See Note [Case binders 1] -- map: bndr -> v' _ -> (bndr', extendCSEnv env scrut' bndr') -- See Note [Case binders 2] -- map: scrut' -> bndr' arg_tys = tyConAppArgs (idType bndr) cse_alt (DataAlt con, args, rhs) | not (null args) -- Don't try CSE if there are no args; it just increases the number -- of live vars. E.g. -- case x of { True -> ....True.... } -- Don't replace True by x! -- Hence the 'null args', which also deal with literals and DEFAULT = (DataAlt con, args', tryForCSE new_env rhs) where (env', args') = addBinders alt_env args new_env = extendCSEnv env' con_expr con_target con_expr = mkAltExpr (DataAlt con) args' arg_tys cse_alt (con, args, rhs) = (con, args', tryForCSE env' rhs) where (env', args') = addBinders alt_env args {- ************************************************************************ * * \section{The CSE envt} * * ************************************************************************ -} type InExpr = CoreExpr -- Pre-cloning type InBndr = CoreBndr type InAlt = CoreAlt type OutExpr = CoreExpr -- Post-cloning type OutBndr = CoreBndr type OutAlt = CoreAlt data CSEnv = CS { cs_map :: CoreMap (OutExpr, Id) -- Key, value , cs_subst :: Subst } emptyCSEnv :: CSEnv emptyCSEnv = CS { cs_map = emptyCoreMap, cs_subst = emptySubst } lookupCSEnv :: CSEnv -> OutExpr -> Maybe Id lookupCSEnv (CS { cs_map = csmap }) expr = case lookupCoreMap csmap expr of Just (_,e) -> Just e Nothing -> Nothing extendCSEnv :: CSEnv -> OutExpr -> Id -> CSEnv extendCSEnv cse expr id = cse { cs_map = extendCoreMap (cs_map cse) sexpr (sexpr,id) } where sexpr = stripTicksE tickishFloatable expr csEnvSubst :: CSEnv -> Subst csEnvSubst = cs_subst lookupSubst :: CSEnv -> Id -> OutExpr lookupSubst (CS { cs_subst = sub}) x = lookupIdSubst (text "CSE.lookupSubst") sub x extendCSSubst :: CSEnv -> Id -> Id -> CSEnv extendCSSubst cse x y = cse { cs_subst = extendIdSubst (cs_subst cse) x (Var y) } addBinder :: CSEnv -> Var -> (CSEnv, Var) addBinder cse v = (cse { cs_subst = sub' }, v') where (sub', v') = substBndr (cs_subst cse) v addBinders :: CSEnv -> [Var] -> (CSEnv, [Var]) addBinders cse vs = (cse { cs_subst = sub' }, vs') where (sub', vs') = substBndrs (cs_subst cse) vs addRecBinders :: CSEnv -> [Id] -> (CSEnv, [Id]) addRecBinders cse vs = (cse { cs_subst = sub' }, vs') where (sub', vs') = substRecBndrs (cs_subst cse) vs
DavidAlphaFox/ghc
compiler/simplCore/CSE.hs
bsd-3-clause
11,820
0
12
3,921
1,938
1,040
898
116
3
{-# LANGUAGE OverloadedStrings, RecordWildCards #-} module Main (main) where import Prelude hiding (interact) import Blaze.ByteString.Builder import Blaze.ByteString.Builder.Char8 import Control.Applicative import Control.Monad import Data.Aeson import Data.ByteString.Char8 (unpack) import Data.ByteString.Lazy.Char8 (ByteString, interact) import Data.Char import Data.Foldable (asum) import Data.Function (on) import qualified Data.HashMap.Lazy as HM (toList) import Data.List (intercalate, sortBy, groupBy, intersperse) import Data.Maybe import Data.Monoid import Data.Ord (comparing) import Data.Text.Encoding (encodeUtf8) -------------------------------------------------------------------------------- -- README -- -- * New groups have to be listed in cmdGroups below. -- * The command blacklist allows to specify the name of a manual -- implementation. -- |Whitelist for the command groups groupCmds :: Cmds -> Cmds groupCmds (Cmds cmds) = Cmds [cmd | cmd <- cmds, group <- groups, cmdGroup cmd == group] where groups = [ "generic" , "string" , "list" , "set" , "sorted_set" , "hash" -- , "pubsub" commands implemented in Database.Redis.PubSub -- , "transactions" implemented in Database.Redis.Transactions , "connection" , "server" , "scripting" ] -- |Blacklisted commands, optionally paired with the name of their -- implementation in the "Database.Redis.ManualCommands" module. blacklist :: [(String, Maybe ([String],[String]))] blacklist = [ manual "AUTH" ["auth"] , manual "SELECT" ["select"] , manual "OBJECT" ["objectRefcount","objectEncoding","objectIdletime"] , manualWithType "TYPE" ["getType"] ["RedisType(..)"] , manual "EVAL" ["eval"] , manual "EVALSHA" ["evalsha"] , manualWithType "SORT" ["sort","sortStore"] ["SortOpts(..)","defaultSortOpts","SortOrder(..)"] , manual "BITCOUNT" ["bitcount", "bitcountRange"] , manual "BITOP" ["bitopAnd", "bitopOr", "bitopXor", "bitopNot"] , manual "LINSERT" ["linsertBefore", "linsertAfter"] , manualWithType "SLOWLOG" ["slowlogGet", "slowlogLen", "slowlogReset"] ["Slowlog(..)"] , manualWithType "ZINTERSTORE" ["zinterstore","zinterstoreWeights"] ["Aggregate(..)"] , manual "ZRANGE" ["zrange", "zrangeWithscores"] , manual "ZRANGEBYSCORE" ["zrangebyscore", "zrangebyscoreWithscores" ,"zrangebyscoreLimit", "zrangebyscoreWithscoresLimit"] , manual "ZREVRANGE" ["zrevrange", "zrevrangeWithscores"] , manual "ZREVRANGEBYSCORE" ["zrevrangebyscore", "zrevrangebyscoreWithscores" ,"zrevrangebyscoreLimit", "zrevrangebyscoreWithscoresLimit"] , manual "ZUNIONSTORE" ["zunionstore","zunionstoreWeights"] , unimplemented "MONITOR" -- debugging command , unimplemented "SYNC" -- internal command , unimplemented "SHUTDOWN" -- kills server, throws exception , unimplemented "DEBUG SEGFAULT" -- crashes the server ] where unimplemented cmd = (cmd, Nothing) manual cmd aliases = (cmd, Just (aliases, [])) manualWithType cmd aliases types = (cmd, Just (aliases, types)) -- Read JSON from STDIN, write Haskell module source to STDOUT. main :: IO () main = interact generateCommands generateCommands :: ByteString -> ByteString generateCommands json = toLazyByteString . hsFile . groupCmds . fromJust $ decode' json -- Types to represent Commands. They are parsed from the JSON input. data Cmd = Cmd { cmdName, cmdGroup :: String , cmdRetType :: Maybe String , cmdArgs :: [Arg] , cmdSummary :: String } deriving (Show) newtype Cmds = Cmds [Cmd] instance Show Cmds where show (Cmds cmds) = intercalate "\n" (map show cmds) data Arg = Arg { argName, argType :: String } | Pair Arg Arg | Multiple Arg | Command String | Enum [String] deriving (Show) instance FromJSON Cmds where parseJSON (Object cmds) = do Cmds <$> forM (HM.toList cmds) (\(name,Object cmd) -> do let cmdName = unpack $ encodeUtf8 name cmdGroup <- cmd .: "group" cmdRetType <- cmd .:? "returns" cmdSummary <- cmd .: "summary" cmdArgs <- cmd .:? "arguments" .!= [] <|> error ("failed to parse args: " ++ cmdName) return Cmd{..}) instance FromJSON Arg where parseJSON (Object arg) = asum [ parseEnum, parseCommand, parseMultiple , parsePair, parseSingle, parseSingleList ] <|> error ("failed to parse arg: " ++ show arg) where parseSingle = do argName <- arg .: "name" argType <- arg .: "type" return Arg{..} -- "multiple": "true" parseMultiple = do True <- arg .: "multiple" Multiple <$> (parsePair <|> parseSingle) -- example: SUBSCRIBE parseSingleList = do [argName] <- arg .: "name" [argType] <- arg .: "type" return Arg{..} -- example: MSETNX parsePair = do [name1,name2] <- arg .: "name" [typ1,typ2] <- arg .: "type" return $ Pair Arg{ argName = name1, argType = typ1 } Arg{ argName = name2, argType = typ2 } -- example: ZREVRANGEBYSCORE parseCommand = do s <- arg .: "command" return $ Command s -- example: LINSERT parseEnum = do enum <- arg .: "enum" return $ Enum enum -- Generate source code for Haskell module exporting the given commands. hsFile :: Cmds -> Builder hsFile (Cmds cmds) = mconcat [ fromString "-- Generated by GenCmds.hs. DO NOT EDIT.\n\n\ \{-# LANGUAGE OverloadedStrings, FlexibleContexts #-}\n\n\ \module Database.Redis.Commands (\n" , exportList cmds , newline , unimplementedCmds , fromString ") where\n\n" , imprts, newline , mconcat (map fromCmd cmds) , newline , newline ] unimplementedCmds :: Builder unimplementedCmds = fromString "-- * Unimplemented Commands\n\ \-- |These commands are not implemented, as of now. Library\n\ \-- users can implement these or other commands from\n\ \-- experimental Redis versions by using the 'sendRequest'\n\ \-- function.\n" `mappend` mconcat (map unimplementedCmd unimplemented) where unimplemented = map fst . filter (isNothing . snd) $ blacklist unimplementedCmd cmd = mconcat [ fromString "--\n" , fromString "-- * " , fromString cmd, fromString " (" , cmdDescriptionLink cmd , fromString ")\n" , fromString "--\n" ] exportList :: [Cmd] -> Builder exportList cmds = mconcat . map exportGroup . groupBy ((==) `on` cmdGroup) $ sortBy (comparing cmdGroup) cmds where exportGroup group = mconcat [ newline , fromString "-- ** ", fromString $ translateGroup (head group) , newline , mconcat . map exportCmd $ sortBy (comparing cmdName) group ] exportCmd cmd@Cmd{..} | implemented cmd = exportCmdNames cmd | otherwise = mempty implemented Cmd{..} = case lookup cmdName blacklist of Nothing -> True Just (Just _) -> True Just Nothing -> False translateGroup Cmd{..} = case cmdGroup of "generic" -> "Keys" "string" -> "Strings" "list" -> "Lists" "set" -> "Sets" "sorted_set" -> "Sorted Sets" "hash" -> "Hashes" -- "pubsub" -> -- "transactions" -> "Transactions" "connection" -> "Connection" "server" -> "Server" "scripting" -> "Scripting" _ -> error $ "untranslated group: " ++ cmdGroup exportCmdNames :: Cmd -> Builder exportCmdNames Cmd{..} = types `mappend` functions where types = mconcat $ flip map typeNames (\name -> mconcat [fromString name, fromString ",\n"]) functions = mconcat $ flip map funNames (\name -> mconcat [fromString name, fromString ", ", haddock, newline]) funNames = case lookup cmdName blacklist of Nothing -> [camelCase cmdName] Just (Just (xs,_)) -> xs Just Nothing -> error "unhandled" typeNames = case lookup cmdName blacklist of Nothing -> [] Just (Just (_,ts)) -> ts Just Nothing -> error "unhandled" haddock = mconcat [ fromString "-- |", fromString cmdSummary , fromString " (" , cmdDescriptionLink cmdName , fromString ")." , if length funNames > 1 then mconcat [ fromString " The Redis command @" , fromString cmdName , fromString "@ is split up into '" , mconcat . map fromString $ intersperse "', '" funNames , fromString "'." ] else mempty ] cmdDescriptionLink :: String -> Builder cmdDescriptionLink cmd = mconcat $ map fromString [ "<http://redis.io/commands/" , map (\c -> if isSpace c then '-' else toLower c) cmd , ">" ] newline :: Builder newline = fromChar '\n' imprts :: Builder imprts = mconcat $ flip map moduls (\modul -> fromString "import " `mappend` fromString modul `mappend`newline) where moduls = [ "Prelude hiding (min,max)" -- name shadowing warnings. , "Data.ByteString (ByteString)" , "Database.Redis.ManualCommands" , "Database.Redis.Types" , "Database.Redis.Core" ] blackListed :: Cmd -> Bool blackListed Cmd{..} = isJust $ lookup cmdName blacklist fromCmd :: Cmd -> Builder fromCmd cmd@Cmd{..} | blackListed cmd = mempty | otherwise = mconcat [sig, newline, fun, newline, newline] where sig = mconcat [ fromString name , fromString "\n :: (RedisCtx m f)" , fromString "\n => " , mconcat $ map argumentType cmdArgs , fromString "m (f ", retType cmd, fromString ")" ] fun = mconcat [ fromString name, fromString " " , mconcat $ intersperse (fromString " ") (map argumentName cmdArgs) , fromString " = " , fromString "sendRequest ([\"" , mconcat $ map fromString $ intersperse "\",\"" $ words cmdName , fromString "\"]" , mconcat $ map argumentList cmdArgs , fromString " )" ] name = camelCase cmdName retType :: Cmd -> Builder retType Cmd{..} = maybe err translate cmdRetType where err = error $ "Command without return type: " ++ cmdName translate t = fromString $ case t of "status" -> "Status" "bool" -> "Bool" "integer" -> "Integer" "maybe-integer"-> "(Maybe Integer)" "key" -> "ByteString" "maybe-key" -> "(Maybe ByteString)" "string" -> "ByteString" "maybe-string" -> "(Maybe ByteString)" "list-string" -> "[ByteString]" "list-maybe" -> "[Maybe ByteString]" "list-bool" -> "[Bool]" "hash" -> "[(ByteString,ByteString)]" "set" -> "[ByteString]" "maybe-pair" -> "(Maybe (ByteString,ByteString))" "double" -> "Double" "maybe-double" -> "(Maybe Double)" "reply" -> "Reply" "time" -> "(Integer,Integer)" _ -> error $ "untranslated return type: " ++ t argumentList :: Arg -> Builder argumentList a = fromString " ++ " `mappend` go a where go (Multiple p@(Pair _a _a')) = mconcat [ fromString "concatMap (\\(x,y) -> [encode x,encode y])" , argumentName p ] go (Multiple a) = fromString "map encode " `mappend` argumentName a go a@Arg{..} = mconcat [ fromString "[encode ", argumentName a, fromString "]" ] argumentName :: Arg -> Builder argumentName a = go a where go (Multiple a) = go a go (Pair a a') = fromString . camelCase $ argName a ++ " " ++ argName a' go a@Arg{..} = name a name Arg{..} = fromString (camelCase argName) argumentType :: Arg -> Builder argumentType a = mconcat [ go a , fromString " -- ^ ", argumentName a , fromString "\n -> " ] where go (Multiple a) = mconcat [fromString "[", go a, fromString "]"] go (Pair a a') = mconcat [fromString "(", go a, fromString ",", go a', fromString ")"] go a@Arg{..} = translateArgType a translateArgType Arg{..} = fromString $ case argType of "integer" -> "Integer" "string" -> "ByteString" "key" -> "ByteString" "pattern" -> "ByteString" "posix time" -> "Integer" "double" -> "Double" _ -> error $ "untranslated arg type: " ++ argType -------------------------------------------------------------------------------- -- HELPERS -- -- |Convert all-uppercase string to camelCase camelCase :: String -> String camelCase s = case split (map toLower s) of [] -> "" w:ws -> concat $ w : map upcaseFirst ws where upcaseFirst [] = "" upcaseFirst (c:cs) = toUpper c : cs -- modified version of Data.List.words split s = case dropWhile (not . isAlphaNum) s of "" -> [] s' -> w:split s'' where (w,s'') = break (not . isAlphaNum) s'
gyfarkas/hedis
codegen/GenCmds.hs
bsd-3-clause
14,262
0
18
4,690
3,395
1,794
1,601
302
19
module Main (main) where -- See Trac #149 -- Curently (with GHC 7.0) the CSE works, just, -- but it's delicate. import System.CPUTime main :: IO () main = print $ playerMostOccur2 [1..m] m :: Int m = 22 playerMostOccur2 :: [Int] -> Int playerMostOccur2 [a] = a playerMostOccur2 (x:xs) | numOccur x (x:xs) > numOccur pmo xs = x | otherwise = pmo where pmo = playerMostOccur2 xs numOccur :: Int -> [Int] -> Int numOccur i is = length $ filter (i ==) is
lukexi/ghc-7.8-arm64
testsuite/tests/perf/should_run/T149_B.hs
bsd-3-clause
466
0
11
101
177
95
82
14
1
module WASHOut where -- output monad data Out a = Out a ShowS instance Monad Out where return a = Out a id m >>= f = case m of Out x shw1 -> case f x of Out y shw2 -> Out y (shw1 . shw2) runOut :: Out a -> ShowS runOut (Out a shw) = shw wrapper = (Out () .) outString :: String -> Out () outString = wrapper showString outChar :: Char -> Out () outChar = wrapper showChar outs :: Show a => a -> Out () outs = wrapper shows outShowS :: ShowS -> Out () outShowS = Out ()
nh2/WashNGo
washparser/hs/WASHOut.hs
bsd-3-clause
520
4
13
158
237
119
118
20
1
{-# LANGUAGE DeriveDataTypeable #-} module HsExpStruct where import SrcLoc1 import HsIdent import HsLiteral import HsGuardsStruct(HsAlt) import HsFieldsStruct import Data.Generics -------- Expressions -------------------------------------------------------- data EI i e p ds t c = HsId (HsIdentI i) -- collapsing HsVar and HsCon | HsLit SrcLoc HsLiteral | HsInfixApp e (HsIdentI i) e | HsApp e e | HsNegApp SrcLoc e | HsLambda [p] e | HsLet ds e | HsIf e e e | HsCase e [HsAlt e p ds] | HsDo (HsStmt e p ds) | HsTuple [e] | HsList [e] | HsParen e | HsLeftSection e (HsIdentI i) | HsRightSection (HsIdentI i) e | HsRecConstr SrcLoc i (HsFieldsI i e) -- qcon { fbind1, ..., fbindn } | HsRecUpdate SrcLoc e (HsFieldsI i e) -- exp_<qcon> { fbind1, ..., fbindn } | HsEnumFrom e | HsEnumFromTo e e | HsEnumFromThen e e | HsEnumFromThenTo e e e | HsListComp (HsStmt e p ds) | HsExpTypeSig SrcLoc e c t -------------------------------- | HsAsPat i e -- pattern only | HsWildCard -- ditto | HsIrrPat e -- ditto deriving (Read, Show, Data, Typeable, Ord) instance (Eq i, Eq e, Eq p, Eq ds, Eq t , Eq c) => Eq (EI i e p ds t c) where HsId i == HsId i1 = i == i1 HsLit _ l == HsLit _ l1 = l == l1 HsInfixApp x op z == HsInfixApp x1 op1 z1 = x==x1 && op == op1 && z == z1 HsApp x y == HsApp x1 y1 = x == x1 && y == y1 HsNegApp _ x == HsNegApp _ x1 = x == x1 HsLambda ps e == HsLambda ps1 e1 = ps ==ps1 && e == e1 HsLet ds e == HsLet ds1 e1 = ds == ds1 && e == e1 HsIf x y z == HsIf x1 y1 z1 = x==x1 && y==y1 && z==z1 HsCase e alts == HsCase e1 alts1 = e == e1 && alts == alts1 HsDo stmts == HsDo stmts1 = stmts == stmts1 HsTuple xs == HsTuple xs1 = xs == xs1 HsList xs == HsList xs1 = xs == xs1 HsParen x == HsParen x1 = x == x1 HsLeftSection x op == HsLeftSection x1 op1 = x == x1 && op == op1 HsRightSection op y == HsRightSection op1 y1 = op == op1 && y == y1 HsRecConstr _ n upds == HsRecConstr _ n1 upds1 = n == n1 && upds == upds1 HsRecUpdate _ e upds == HsRecUpdate _ e1 upds1 = e == e1 && upds == upds1 HsEnumFrom x == HsEnumFrom x1 = x == x1 HsEnumFromTo x y == HsEnumFromTo x1 y1 = x == x1 && y==y1 HsEnumFromThen x y == HsEnumFromThen x1 y1 = x == x1 && y==y1 HsEnumFromThenTo x y z== HsEnumFromThenTo x1 y1 z1 = x == x1 && y==y1 && z==z1 HsListComp stmts == HsListComp stmts1 = stmts == stmts1 HsExpTypeSig _ e c t == HsExpTypeSig _ e1 c1 t1 = e == e1 && c == c1 && t == t1 HsAsPat n e == HsAsPat n1 e1 = n == n1 && e == e1 HsWildCard == HsWildCard = True HsIrrPat e == HsIrrPat e1 = e == e1 _ == _ = False data HsStmt e p ds = HsGenerator SrcLoc p e (HsStmt e p ds) | HsQualifier e (HsStmt e p ds) | HsLetStmt ds (HsStmt e p ds) | HsLast e deriving (Ord,Read, Eq, Show, Data, Typeable)
kmate/HaRe
old/tools/base/AST/HsExpStruct.hs
bsd-3-clause
3,441
0
10
1,338
1,278
632
646
70
0
{-# OPTIONS -cpp #-} ------------------------------------------------------------------ -- A primop-table mangling program -- ------------------------------------------------------------------ module Main where import Parser import Syntax import Data.Char import Data.List import Data.Maybe ( catMaybes ) import System.Environment ( getArgs ) vecOptions :: Entry -> [(String,String,Int)] vecOptions i = concat [vecs | OptionVector vecs <- opts i] desugarVectorSpec :: Entry -> [Entry] desugarVectorSpec i@(Section {}) = [i] desugarVectorSpec i = case vecOptions i of [] -> [i] vos -> map genVecEntry vos where genVecEntry :: (String,String,Int) -> Entry genVecEntry (con,repCon,n) = case i of PrimOpSpec {} -> PrimVecOpSpec { cons = "(" ++ concat (intersperse " " [cons i, vecCat, show n, vecWidth]) ++ ")" , name = name' , prefix = pfx , veclen = n , elemrep = con ++ "ElemRep" , ty = desugarTy (ty i) , cat = cat i , desc = desc i , opts = opts i } PrimTypeSpec {} -> PrimVecTypeSpec { ty = desugarTy (ty i) , prefix = pfx , veclen = n , elemrep = con ++ "ElemRep" , desc = desc i , opts = opts i } _ -> error "vector options can only be given for primops and primtypes" where vecCons = con++"X"++show n++"#" vecCat = conCat con vecWidth = conWidth con pfx = lowerHead con++"X"++show n vecTyName = pfx++"PrimTy" name' | Just pre <- splitSuffix (name i) "Array#" = pre++vec++"Array#" | Just pre <- splitSuffix (name i) "OffAddr#" = pre++vec++"OffAddr#" | Just pre <- splitSuffix (name i) "ArrayAs#" = pre++con++"ArrayAs"++vec++"#" | Just pre <- splitSuffix (name i) "OffAddrAs#" = pre++con++"OffAddrAs"++vec++"#" | otherwise = init (name i)++vec ++"#" where vec = con++"X"++show n splitSuffix :: Eq a => [a] -> [a] -> Maybe [a] splitSuffix s suf | drop len s == suf = Just (take len s) | otherwise = Nothing where len = length s - length suf lowerHead s = toLower (head s) : tail s desugarTy :: Ty -> Ty desugarTy (TyF s d) = TyF (desugarTy s) (desugarTy d) desugarTy (TyC s d) = TyC (desugarTy s) (desugarTy d) desugarTy (TyApp SCALAR []) = TyApp (TyCon repCon) [] desugarTy (TyApp VECTOR []) = TyApp (VecTyCon vecCons vecTyName) [] desugarTy (TyApp VECTUPLE []) = TyUTup (replicate n (TyApp (TyCon repCon) [])) desugarTy (TyApp tycon ts) = TyApp tycon (map desugarTy ts) desugarTy t@(TyVar {}) = t desugarTy (TyUTup ts) = TyUTup (map desugarTy ts) conCat :: String -> String conCat "Int8" = "IntVec" conCat "Int16" = "IntVec" conCat "Int32" = "IntVec" conCat "Int64" = "IntVec" conCat "Word8" = "WordVec" conCat "Word16" = "WordVec" conCat "Word32" = "WordVec" conCat "Word64" = "WordVec" conCat "Float" = "FloatVec" conCat "Double" = "FloatVec" conCat con = error $ "conCat: unknown type constructor " ++ con ++ "\n" conWidth :: String -> String conWidth "Int8" = "W8" conWidth "Int16" = "W16" conWidth "Int32" = "W32" conWidth "Int64" = "W64" conWidth "Word8" = "W8" conWidth "Word16" = "W16" conWidth "Word32" = "W32" conWidth "Word64" = "W64" conWidth "Float" = "W32" conWidth "Double" = "W64" conWidth con = error $ "conWidth: unknown type constructor " ++ con ++ "\n" main :: IO () main = getArgs >>= \args -> if length args /= 1 || head args `notElem` known_args then error ("usage: genprimopcode command < primops.txt > ...\n" ++ " where command is one of\n" ++ unlines (map (" "++) known_args) ) else do s <- getContents case parse s of Left err -> error ("parse error at " ++ (show err)) Right p_o_specs@(Info _ _) -> seq (sanityTop p_o_specs) ( case head args of "--data-decl" -> putStr (gen_data_decl p_o_specs) "--has-side-effects" -> putStr (gen_switch_from_attribs "has_side_effects" "primOpHasSideEffects" p_o_specs) "--out-of-line" -> putStr (gen_switch_from_attribs "out_of_line" "primOpOutOfLine" p_o_specs) "--commutable" -> putStr (gen_switch_from_attribs "commutable" "commutableOp" p_o_specs) "--code-size" -> putStr (gen_switch_from_attribs "code_size" "primOpCodeSize" p_o_specs) "--can-fail" -> putStr (gen_switch_from_attribs "can_fail" "primOpCanFail" p_o_specs) "--strictness" -> putStr (gen_switch_from_attribs "strictness" "primOpStrictness" p_o_specs) "--fixity" -> putStr (gen_switch_from_attribs "fixity" "primOpFixity" p_o_specs) "--primop-primop-info" -> putStr (gen_primop_info p_o_specs) "--primop-tag" -> putStr (gen_primop_tag p_o_specs) "--primop-list" -> putStr (gen_primop_list p_o_specs) "--primop-vector-uniques" -> putStr (gen_primop_vector_uniques p_o_specs) "--primop-vector-tys" -> putStr (gen_primop_vector_tys p_o_specs) "--primop-vector-tys-exports" -> putStr (gen_primop_vector_tys_exports p_o_specs) "--primop-vector-tycons" -> putStr (gen_primop_vector_tycons p_o_specs) "--make-haskell-wrappers" -> putStr (gen_wrappers p_o_specs) "--make-haskell-source" -> putStr (gen_hs_source p_o_specs) "--make-latex-doc" -> putStr (gen_latex_doc p_o_specs) _ -> error "Should not happen, known_args out of sync?" ) known_args :: [String] known_args = [ "--data-decl", "--has-side-effects", "--out-of-line", "--commutable", "--code-size", "--can-fail", "--strictness", "--fixity", "--primop-primop-info", "--primop-tag", "--primop-list", "--primop-vector-uniques", "--primop-vector-tys", "--primop-vector-tys-exports", "--primop-vector-tycons", "--make-haskell-wrappers", "--make-haskell-source", "--make-latex-doc" ] ------------------------------------------------------------------ -- Code generators ----------------------------------------------- ------------------------------------------------------------------ gen_hs_source :: Info -> String gen_hs_source (Info defaults entries) = "{-\n" ++ "This is a generated file (generated by genprimopcode).\n" ++ "It is not code to actually be used. Its only purpose is to be\n" ++ "consumed by haddock.\n" ++ "-}\n" ++ "\n" ++ (replicate 77 '-' ++ "\n") -- For 80-col cleanliness ++ "-- |\n" ++ "-- Module : GHC.Prim\n" ++ "-- \n" ++ "-- Maintainer : ghc-devs@haskell.org\n" ++ "-- Stability : internal\n" ++ "-- Portability : non-portable (GHC extensions)\n" ++ "--\n" ++ "-- GHC\'s primitive types and operations.\n" ++ "-- Use GHC.Exts from the base package instead of importing this\n" ++ "-- module directly.\n" ++ "--\n" ++ (replicate 77 '-' ++ "\n") -- For 80-col cleanliness ++ "{-# LANGUAGE Unsafe #-}\n" ++ "{-# LANGUAGE MagicHash #-}\n" ++ "{-# LANGUAGE MultiParamTypeClasses #-}\n" ++ "{-# LANGUAGE NoImplicitPrelude #-}\n" ++ "{-# LANGUAGE UnboxedTuples #-}\n" ++ "module GHC.Prim (\n" ++ unlines (map ((" " ++) . hdr) entries') ++ ") where\n" ++ "\n" ++ "{-\n" ++ unlines (map opt defaults) ++ "-}\n" ++ "import GHC.Types (Coercible)\n" ++ unlines (concatMap ent entries') ++ "\n\n\n" where entries' = concatMap desugarVectorSpec entries opt (OptionFalse n) = n ++ " = False" opt (OptionTrue n) = n ++ " = True" opt (OptionString n v) = n ++ " = { " ++ v ++ "}" opt (OptionInteger n v) = n ++ " = " ++ show v opt (OptionVector _) = "" opt (OptionFixity mf) = "fixity" ++ " = " ++ show mf hdr s@(Section {}) = sec s hdr (PrimOpSpec { name = n }) = wrapOp n ++ "," hdr (PrimVecOpSpec { name = n }) = wrapOp n ++ "," hdr (PseudoOpSpec { name = n }) = wrapOp n ++ "," hdr (PrimTypeSpec { ty = TyApp (TyCon n) _ }) = wrapTy n ++ "," hdr (PrimTypeSpec {}) = error $ "Illegal type spec" hdr (PrimVecTypeSpec { ty = TyApp (VecTyCon n _) _ }) = wrapTy n ++ "," hdr (PrimVecTypeSpec {}) = error $ "Illegal type spec" ent (Section {}) = [] ent o@(PrimOpSpec {}) = spec o ent o@(PrimVecOpSpec {}) = spec o ent o@(PrimTypeSpec {}) = spec o ent o@(PrimVecTypeSpec {}) = spec o ent o@(PseudoOpSpec {}) = spec o sec s = "\n-- * " ++ escape (title s) ++ "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ desc s) ++ "\n" spec o = comm : decls where decls = case o of PrimOpSpec { name = n, ty = t, opts = options } -> [ pprFixity fixity n | OptionFixity (Just fixity) <- options ] ++ [ wrapOp n ++ " :: " ++ pprTy t, wrapOp n ++ " = let x = x in x" ] PrimVecOpSpec { name = n, ty = t, opts = options } -> [ pprFixity fixity n | OptionFixity (Just fixity) <- options ] ++ [ wrapOp n ++ " :: " ++ pprTy t, wrapOp n ++ " = let x = x in x" ] PseudoOpSpec { name = n, ty = t } -> [ wrapOp n ++ " :: " ++ pprTy t, wrapOp n ++ " = let x = x in x" ] PrimTypeSpec { ty = t } -> [ "data " ++ pprTy t ] PrimVecTypeSpec { ty = t } -> [ "data " ++ pprTy t ] Section { } -> [] comm = case (desc o) of [] -> "" d -> "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ d) wrapOp nm | isAlpha (head nm) = nm | otherwise = "(" ++ nm ++ ")" wrapTy nm | isAlpha (head nm) = nm | otherwise = "(" ++ nm ++ ")" unlatex s = case s of '\\':'t':'e':'x':'t':'t':'t':'{':cs -> markup "@" "@" cs '{':'\\':'t':'t':cs -> markup "@" "@" cs '{':'\\':'i':'t':cs -> markup "/" "/" cs c : cs -> c : unlatex cs [] -> [] markup s t xs = s ++ mk (dropWhile isSpace xs) where mk "" = t mk ('\n':cs) = ' ' : mk cs mk ('}':cs) = t ++ unlatex cs mk (c:cs) = c : mk cs escape = concatMap (\c -> if c `elem` special then '\\':c:[] else c:[]) where special = "/'`\"@<" pprFixity (Fixity i d) n = pprFixityDir d ++ " " ++ show i ++ " " ++ n pprTy :: Ty -> String pprTy = pty where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = show tc ++ concat (map (' ' :) (map paty ts)) pbty (TyUTup ts) = "(# " ++ concat (intersperse "," (map pty ts)) ++ " #)" pbty t = paty t paty (TyVar tv) = tv paty t = "(" ++ pty t ++ ")" -- -- Generates the type environment that the stand-alone External Core tools use. gen_ext_core_source :: [Entry] -> String gen_ext_core_source entries = "-----------------------------------------------------------------------\n" ++ "-- This module is automatically generated by the GHC utility\n" ++ "-- \"genprimopcode\". Do not edit!\n" ++ "-----------------------------------------------------------------------\n" ++ "module Language.Core.PrimEnv(primTcs, primVals, intLitTypes, ratLitTypes," ++ "\n charLitTypes, stringLitTypes) where\nimport Language.Core.Core" ++ "\nimport Language.Core.Encoding\n\n" ++ "primTcs :: [(Tcon, Kind)]\n" ++ "primTcs = [\n" ++ printList tcEnt entries ++ " ]\n" ++ "primVals :: [(Var, Ty)]\n" ++ "primVals = [\n" ++ printList valEnt entries ++ "]\n" ++ "intLitTypes :: [Ty]\n" ++ "intLitTypes = [\n" ++ printList tyEnt (intLitTys entries) ++ "]\n" ++ "ratLitTypes :: [Ty]\n" ++ "ratLitTypes = [\n" ++ printList tyEnt (ratLitTys entries) ++ "]\n" ++ "charLitTypes :: [Ty]\n" ++ "charLitTypes = [\n" ++ printList tyEnt (charLitTys entries) ++ "]\n" ++ "stringLitTypes :: [Ty]\n" ++ "stringLitTypes = [\n" ++ printList tyEnt (stringLitTys entries) ++ "]\n\n" where printList f = concat . intersperse ",\n" . filter (not . null) . map f tcEnt (PrimTypeSpec {ty=t}) = case t of TyApp tc args -> parens (show tc) (tcKind tc args) _ -> error ("tcEnt: type in PrimTypeSpec is not a type" ++ " constructor: " ++ show t) tcEnt _ = "" -- hack alert! -- The primops.txt.pp format doesn't have enough information in it to -- print out some of the information that ext-core needs (like kinds, -- and later on in this code, module names) so we special-case. An -- alternative would be to refer to things indirectly and hard-wire -- certain things (e.g., the kind of the Any constructor, here) into -- ext-core's Prims module again. tcKind (TyCon "Any") _ = "Klifted" tcKind tc [] | last (show tc) == '#' = "Kunlifted" tcKind _ [] | otherwise = "Klifted" -- assumes that all type arguments are lifted (are they?) tcKind tc (_v:as) = "(Karrow Klifted " ++ tcKind tc as ++ ")" valEnt (PseudoOpSpec {name=n, ty=t}) = valEntry n t valEnt (PrimOpSpec {name=n, ty=t}) = valEntry n t valEnt _ = "" valEntry name' ty' = parens name' (mkForallTy (freeTvars ty') (pty ty')) where pty (TyF t1 t2) = mkFunTy (pty t1) (pty t2) pty (TyC t1 t2) = mkFunTy (pty t1) (pty t2) pty (TyApp tc ts) = mkTconApp (mkTcon tc) (map pty ts) pty (TyUTup ts) = mkUtupleTy (map pty ts) pty (TyVar tv) = paren $ "Tvar \"" ++ tv ++ "\"" mkFunTy s1 s2 = "Tapp " ++ (paren ("Tapp (Tcon tcArrow)" ++ " " ++ paren s1)) ++ " " ++ paren s2 mkTconApp tc args = foldl tapp tc args mkTcon tc = paren $ "Tcon " ++ paren (qualify True (show tc)) mkUtupleTy args = foldl tapp (tcUTuple (length args)) args mkForallTy [] t = t mkForallTy vs t = foldr (\ v s -> "Tforall " ++ (paren (quote v ++ ", " ++ vKind v)) ++ " " ++ paren s) t vs -- hack alert! vKind "o" = "Kopen" vKind _ = "Klifted" freeTvars (TyF t1 t2) = freeTvars t1 `union` freeTvars t2 freeTvars (TyC t1 t2) = freeTvars t1 `union` freeTvars t2 freeTvars (TyApp _ tys) = freeTvarss tys freeTvars (TyVar v) = [v] freeTvars (TyUTup tys) = freeTvarss tys freeTvarss = nub . concatMap freeTvars tapp s nextArg = paren $ "Tapp " ++ s ++ " " ++ paren nextArg tcUTuple n = paren $ "Tcon " ++ paren (qualify False $ "Z" ++ show n ++ "H") tyEnt (PrimTypeSpec {ty=(TyApp tc _args)}) = " " ++ paren ("Tcon " ++ (paren (qualify True (show tc)))) tyEnt _ = "" -- more hacks. might be better to do this on the ext-core side, -- as per earlier comment qualify _ tc | tc == "Bool" = "Just boolMname" ++ ", " ++ ze True tc qualify _ tc | tc == "()" = "Just baseMname" ++ ", " ++ ze True tc qualify enc tc = "Just primMname" ++ ", " ++ (ze enc tc) ze enc tc = (if enc then "zEncodeString " else "") ++ "\"" ++ tc ++ "\"" intLitTys = prefixes ["Int", "Word", "Addr", "Char"] ratLitTys = prefixes ["Float", "Double"] charLitTys = prefixes ["Char"] stringLitTys = prefixes ["Addr"] prefixes ps = filter (\ t -> case t of (PrimTypeSpec {ty=(TyApp tc _args)}) -> any (\ p -> p `isPrefixOf` show tc) ps _ -> False) parens n ty' = " (zEncodeString \"" ++ n ++ "\", " ++ ty' ++ ")" paren s = "(" ++ s ++ ")" quote s = "\"" ++ s ++ "\"" gen_latex_doc :: Info -> String gen_latex_doc (Info defaults entries) = "\\primopdefaults{" ++ mk_options defaults ++ "}\n" ++ (concat (map mk_entry entries)) where mk_entry (PrimOpSpec {cons=constr,name=n,ty=t,cat=c,desc=d,opts=o}) = "\\primopdesc{" ++ latex_encode constr ++ "}{" ++ latex_encode n ++ "}{" ++ latex_encode (zencode n) ++ "}{" ++ latex_encode (show c) ++ "}{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_entry (PrimVecOpSpec {}) = "" mk_entry (Section {title=ti,desc=d}) = "\\primopsection{" ++ latex_encode ti ++ "}{" ++ d ++ "}\n" mk_entry (PrimTypeSpec {ty=t,desc=d,opts=o}) = "\\primtypespec{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_entry (PrimVecTypeSpec {}) = "" mk_entry (PseudoOpSpec {name=n,ty=t,desc=d,opts=o}) = "\\pseudoopspec{" ++ latex_encode (zencode n) ++ "}{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_source_ty typ = pty typ where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = show tc ++ (concat (map (' ':) (map paty ts))) pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)" pbty t = paty t paty (TyVar tv) = tv paty t = "(" ++ pty t ++ ")" mk_core_ty typ = foralls ++ (pty typ) where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = (zencode (show tc)) ++ (concat (map (' ':) (map paty ts))) pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts)))) pbty t = paty t paty (TyVar tv) = zencode tv paty (TyApp tc []) = zencode (show tc) paty t = "(" ++ pty t ++ ")" utuplenm 1 = "(# #)" utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)" foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars) tvars = tvars_of typ tbinds [] = ". " tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs) tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs) tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2 tvars_of (TyC t1 t2) = tvars_of t1 `union` tvars_of t2 tvars_of (TyApp _ ts) = foldl union [] (map tvars_of ts) tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts) tvars_of (TyVar tv) = [tv] mk_options o = "\\primoptions{" ++ mk_has_side_effects o ++ "}{" ++ mk_out_of_line o ++ "}{" ++ mk_commutable o ++ "}{" ++ mk_needs_wrapper o ++ "}{" ++ mk_can_fail o ++ "}{" ++ mk_fixity o ++ "}{" ++ latex_encode (mk_strictness o) ++ "}{" ++ "}" mk_has_side_effects o = mk_bool_opt o "has_side_effects" "Has side effects." "Has no side effects." mk_out_of_line o = mk_bool_opt o "out_of_line" "Implemented out of line." "Implemented in line." mk_commutable o = mk_bool_opt o "commutable" "Commutable." "Not commutable." mk_needs_wrapper o = mk_bool_opt o "needs_wrapper" "Needs wrapper." "Needs no wrapper." mk_can_fail o = mk_bool_opt o "can_fail" "Can fail." "Cannot fail." mk_bool_opt o opt_name if_true if_false = case lookup_attrib opt_name o of Just (OptionTrue _) -> if_true Just (OptionFalse _) -> if_false Just (OptionString _ _) -> error "String value for boolean option" Just (OptionInteger _ _) -> error "Integer value for boolean option" Just (OptionFixity _) -> error "Fixity value for boolean option" Just (OptionVector _) -> error "vector template for boolean option" Nothing -> "" mk_strictness o = case lookup_attrib "strictness" o of Just (OptionString _ s) -> s -- for now Just _ -> error "Wrong value for strictness" Nothing -> "" mk_fixity o = case lookup_attrib "fixity" o of Just (OptionFixity (Just (Fixity i d))) -> pprFixityDir d ++ " " ++ show i _ -> "" zencode xs = case maybe_tuple xs of Just n -> n -- Tuples go to Z2T etc Nothing -> concat (map encode_ch xs) where maybe_tuple "(# #)" = Just("Z1H") maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H") _ -> Nothing maybe_tuple "()" = Just("Z0T") maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of (n, ')' : _) -> Just ('Z' : shows (n+1) "T") _ -> Nothing maybe_tuple _ = Nothing count_commas :: Int -> String -> (Int, String) count_commas n (',' : cs) = count_commas (n+1) cs count_commas n cs = (n,cs) unencodedChar :: Char -> Bool -- True for chars that don't need encoding unencodedChar 'Z' = False unencodedChar 'z' = False unencodedChar c = isAlphaNum c encode_ch :: Char -> String encode_ch c | unencodedChar c = [c] -- Common case first -- Constructors encode_ch '(' = "ZL" -- Needed for things like (,), and (->) encode_ch ')' = "ZR" -- For symmetry with ( encode_ch '[' = "ZM" encode_ch ']' = "ZN" encode_ch ':' = "ZC" encode_ch 'Z' = "ZZ" -- Variables encode_ch 'z' = "zz" encode_ch '&' = "za" encode_ch '|' = "zb" encode_ch '^' = "zc" encode_ch '$' = "zd" encode_ch '=' = "ze" encode_ch '>' = "zg" encode_ch '#' = "zh" encode_ch '.' = "zi" encode_ch '<' = "zl" encode_ch '-' = "zm" encode_ch '!' = "zn" encode_ch '+' = "zp" encode_ch '\'' = "zq" encode_ch '\\' = "zr" encode_ch '/' = "zs" encode_ch '*' = "zt" encode_ch '_' = "zu" encode_ch '%' = "zv" encode_ch c = 'z' : shows (ord c) "U" latex_encode [] = [] latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs) latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs) latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs) latex_encode (c:cs) = c:(latex_encode cs) gen_wrappers :: Info -> String gen_wrappers (Info _ entries) = "{-# LANGUAGE MagicHash, NoImplicitPrelude, UnboxedTuples #-}\n" -- Dependencies on Prelude must be explicit in libraries/base, but we -- don't need the Prelude here so we add NoImplicitPrelude. ++ "module GHC.PrimopWrappers where\n" ++ "import qualified GHC.Prim\n" ++ "import GHC.Tuple ()\n" ++ "import GHC.Prim (" ++ types ++ ")\n" ++ unlines (concatMap f specs) where specs = filter (not.dodgy) $ filter (not.is_llvm_only) $ filter is_primop entries tycons = foldr union [] $ map (tyconsIn . ty) specs tycons' = filter (`notElem` [TyCon "()", TyCon "Bool"]) tycons types = concat $ intersperse ", " $ map show tycons' f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)] src_name = wrap (name spec) lhs = src_name ++ " " ++ unwords args rhs = "(GHC.Prim." ++ name spec ++ ") " ++ unwords args in ["{-# NOINLINE " ++ src_name ++ " #-}", src_name ++ " :: " ++ pprTy (ty spec), lhs ++ " = " ++ rhs] wrap nm | isLower (head nm) = nm | otherwise = "(" ++ nm ++ ")" dodgy spec = name spec `elem` [-- C code generator can't handle these "seq#", "tagToEnum#", -- not interested in parallel support "par#", "parGlobal#", "parLocal#", "parAt#", "parAtAbs#", "parAtRel#", "parAtForNow#" ] is_llvm_only :: Entry -> Bool is_llvm_only entry = case lookup_attrib "llvm_only" (opts entry) of Just (OptionTrue _) -> True _ -> False gen_primop_list :: Info -> String gen_primop_list (Info _ entries) = unlines ( [ " [" ++ cons first ] ++ map (\p -> " , " ++ cons p) rest ++ [ " ]" ] ) where (first:rest) = concatMap desugarVectorSpec (filter is_primop entries) mIN_VECTOR_UNIQUE :: Int mIN_VECTOR_UNIQUE = 300 gen_primop_vector_uniques :: Info -> String gen_primop_vector_uniques (Info _ entries) = unlines $ concatMap mkVecUnique (specs `zip` [mIN_VECTOR_UNIQUE..]) where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecUnique :: (Entry, Int) -> [String] mkVecUnique (i, unique) = [ key_id ++ " :: Unique" , key_id ++ " = mkPreludeTyConUnique " ++ show unique ] where key_id = prefix i ++ "PrimTyConKey" gen_primop_vector_tys :: Info -> String gen_primop_vector_tys (Info _ entries) = unlines $ concatMap mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> [String] mkVecTypes i = [ name_id ++ " :: Name" , name_id ++ " = mkPrimTc (fsLit \"" ++ pprTy (ty i) ++ "\") " ++ key_id ++ " " ++ tycon_id , ty_id ++ " :: Type" , ty_id ++ " = mkTyConTy " ++ tycon_id , tycon_id ++ " :: TyCon" , tycon_id ++ " = pcPrimTyCon0 " ++ name_id ++ " (VecRep " ++ show (veclen i) ++ " " ++ elemrep i ++ ")" ] where key_id = prefix i ++ "PrimTyConKey" name_id = prefix i ++ "PrimTyConName" ty_id = prefix i ++ "PrimTy" tycon_id = prefix i ++ "PrimTyCon" gen_primop_vector_tys_exports :: Info -> String gen_primop_vector_tys_exports (Info _ entries) = unlines $ map mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> String mkVecTypes i = " " ++ ty_id ++ ", " ++ tycon_id ++ "," where ty_id = prefix i ++ "PrimTy" tycon_id = prefix i ++ "PrimTyCon" gen_primop_vector_tycons :: Info -> String gen_primop_vector_tycons (Info _ entries) = unlines $ map mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> String mkVecTypes i = " , " ++ tycon_id where tycon_id = prefix i ++ "PrimTyCon" gen_primop_tag :: Info -> String gen_primop_tag (Info _ entries) = unlines (max_def_type : max_def : tagOf_type : zipWith f primop_entries [1 :: Int ..]) where primop_entries = concatMap desugarVectorSpec $ filter is_primop entries tagOf_type = "tagOf_PrimOp :: PrimOp -> FastInt" f i n = "tagOf_PrimOp " ++ cons i ++ " = _ILIT(" ++ show n ++ ")" max_def_type = "maxPrimOpTag :: Int" max_def = "maxPrimOpTag = " ++ show (length primop_entries) gen_data_decl :: Info -> String gen_data_decl (Info _ entries) = "data PrimOp\n = " ++ head conss ++ "\n" ++ unlines (map (" | "++) (tail conss)) where conss = map genCons (filter is_primop entries) genCons :: Entry -> String genCons entry = case vecOptions entry of [] -> cons entry _ -> cons entry ++ " PrimOpVecCat Length Width" gen_switch_from_attribs :: String -> String -> Info -> String gen_switch_from_attribs attrib_name fn_name (Info defaults entries) = let defv = lookup_attrib attrib_name defaults alternatives = catMaybes (map mkAlt (filter is_primop entries)) getAltRhs (OptionFalse _) = "False" getAltRhs (OptionTrue _) = "True" getAltRhs (OptionInteger _ i) = show i getAltRhs (OptionString _ s) = s getAltRhs (OptionVector _) = "True" getAltRhs (OptionFixity mf) = show mf mkAlt po = case lookup_attrib attrib_name (opts po) of Nothing -> Nothing Just xx -> case vecOptions po of [] -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx) _ -> Just (fn_name ++ " (" ++ cons po ++ " _ _ _) = " ++ getAltRhs xx) in case defv of Nothing -> error ("gen_switch_from: " ++ attrib_name) Just xx -> unlines alternatives ++ fn_name ++ " _ = " ++ getAltRhs xx ++ "\n" ------------------------------------------------------------------ -- Create PrimOpInfo text from PrimOpSpecs ----------------------- ------------------------------------------------------------------ gen_primop_info :: Info -> String gen_primop_info (Info _ entries) = unlines (map mkPOItext (concatMap desugarVectorSpec (filter is_primop entries))) mkPOItext :: Entry -> String mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i mkPOI_LHS_text :: Entry -> String mkPOI_LHS_text i = "primOpInfo " ++ cons i ++ " = " mkPOI_RHS_text :: Entry -> String mkPOI_RHS_text i = case cat i of Compare -> case ty i of TyF t1 (TyF _ _) -> "mkCompare " ++ sl_name i ++ ppType t1 _ -> error "Type error in comparison op" Monadic -> case ty i of TyF t1 _ -> "mkMonadic " ++ sl_name i ++ ppType t1 _ -> error "Type error in monadic op" Dyadic -> case ty i of TyF t1 (TyF _ _) -> "mkDyadic " ++ sl_name i ++ ppType t1 _ -> error "Type error in dyadic op" GenPrimOp -> let (argTys, resTy) = flatTys (ty i) tvs = nub (tvsIn (ty i)) in "mkGenPrimOp " ++ sl_name i ++ " " ++ listify (map ppTyVar tvs) ++ " " ++ listify (map ppType argTys) ++ " " ++ "(" ++ ppType resTy ++ ")" sl_name :: Entry -> String sl_name i = "(fsLit \"" ++ name i ++ "\") " ppTyVar :: String -> String ppTyVar "a" = "alphaTyVar" ppTyVar "b" = "betaTyVar" ppTyVar "c" = "gammaTyVar" ppTyVar "s" = "deltaTyVar" ppTyVar "o" = "openAlphaTyVar" ppTyVar _ = error "Unknown type var" ppType :: Ty -> String ppType (TyApp (TyCon "Any") []) = "anyTy" ppType (TyApp (TyCon "Bool") []) = "boolTy" ppType (TyApp (TyCon "Int#") []) = "intPrimTy" ppType (TyApp (TyCon "Int32#") []) = "int32PrimTy" ppType (TyApp (TyCon "Int64#") []) = "int64PrimTy" ppType (TyApp (TyCon "Char#") []) = "charPrimTy" ppType (TyApp (TyCon "Word#") []) = "wordPrimTy" ppType (TyApp (TyCon "Word32#") []) = "word32PrimTy" ppType (TyApp (TyCon "Word64#") []) = "word64PrimTy" ppType (TyApp (TyCon "Addr#") []) = "addrPrimTy" ppType (TyApp (TyCon "Float#") []) = "floatPrimTy" ppType (TyApp (TyCon "Double#") []) = "doublePrimTy" ppType (TyApp (TyCon "ByteArray#") []) = "byteArrayPrimTy" ppType (TyApp (TyCon "RealWorld") []) = "realWorldTy" ppType (TyApp (TyCon "ThreadId#") []) = "threadIdPrimTy" ppType (TyApp (TyCon "ForeignObj#") []) = "foreignObjPrimTy" ppType (TyApp (TyCon "BCO#") []) = "bcoPrimTy" ppType (TyApp (TyCon "()") []) = "unitTy" -- unitTy is TysWiredIn's name for () ppType (TyVar "a") = "alphaTy" ppType (TyVar "b") = "betaTy" ppType (TyVar "c") = "gammaTy" ppType (TyVar "s") = "deltaTy" ppType (TyVar "o") = "openAlphaTy" ppType (TyApp (TyCon "State#") [x]) = "mkStatePrimTy " ++ ppType x ppType (TyApp (TyCon "MutVar#") [x,y]) = "mkMutVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableArray#") [x,y]) = "mkMutableArrayPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableArrayArray#") [x]) = "mkMutableArrayArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "SmallMutableArray#") [x,y]) = "mkSmallMutableArrayPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableByteArray#") [x]) = "mkMutableByteArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "Array#") [x]) = "mkArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "ArrayArray#") []) = "mkArrayArrayPrimTy" ppType (TyApp (TyCon "SmallArray#") [x]) = "mkSmallArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "Weak#") [x]) = "mkWeakPrimTy " ++ ppType x ppType (TyApp (TyCon "StablePtr#") [x]) = "mkStablePtrPrimTy " ++ ppType x ppType (TyApp (TyCon "StableName#") [x]) = "mkStableNamePrimTy " ++ ppType x ppType (TyApp (TyCon "MVar#") [x,y]) = "mkMVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "TVar#") [x,y]) = "mkTVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (VecTyCon _ pptc) []) = pptc ppType (TyUTup ts) = "(mkTupleTy UnboxedTuple " ++ listify (map ppType ts) ++ ")" ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))" ppType (TyC s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))" ppType other = error ("ppType: can't handle: " ++ show other ++ "\n") pprFixityDir :: FixityDirection -> String pprFixityDir InfixN = "infix" pprFixityDir InfixL = "infixl" pprFixityDir InfixR = "infixr" listify :: [String] -> String listify ss = "[" ++ concat (intersperse ", " ss) ++ "]" flatTys :: Ty -> ([Ty],Ty) flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t) flatTys (TyC t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t) flatTys other = ([],other) tvsIn :: Ty -> [TyVar] tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2 tvsIn (TyC t1 t2) = tvsIn t1 ++ tvsIn t2 tvsIn (TyApp _ tys) = concatMap tvsIn tys tvsIn (TyVar tv) = [tv] tvsIn (TyUTup tys) = concatMap tvsIn tys tyconsIn :: Ty -> [TyCon] tyconsIn (TyF t1 t2) = tyconsIn t1 `union` tyconsIn t2 tyconsIn (TyC t1 t2) = tyconsIn t1 `union` tyconsIn t2 tyconsIn (TyApp tc tys) = foldr union [tc] $ map tyconsIn tys tyconsIn (TyVar _) = [] tyconsIn (TyUTup tys) = foldr union [] $ map tyconsIn tys arity :: Ty -> Int arity = length . fst . flatTys
forked-upstream-packages-for-ghcjs/ghc
utils/genprimopcode/Main.hs
bsd-3-clause
40,625
0
37
16,412
11,388
5,727
5,661
787
74
{-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeOperators #-} module T12594 where import GHC.Generics data Action = Action class ToField a where toField :: a -> Action instance ToField Int where -- Not the actual instance, but good enough for testing purposes toField _ = Action class ToRow a where toRow :: a -> [Action] default toRow :: (Generic a, GToRow (Rep a)) => a -> [Action] toRow = gtoRow . from class GToRow f where gtoRow :: f p -> [Action] instance GToRow f => GToRow (M1 c i f) where gtoRow (M1 x) = gtoRow x instance (GToRow f, GToRow g) => GToRow (f :*: g) where gtoRow (f :*: g) = gtoRow f ++ gtoRow g instance (ToField a) => GToRow (K1 R a) where gtoRow (K1 a) = [toField a] instance GToRow U1 where gtoRow _ = [] data Foo = Foo { bar :: Int } deriving (Generic, ToRow)
shlevy/ghc
testsuite/tests/deriving/should_compile/T12594.hs
bsd-3-clause
975
0
11
220
332
176
156
29
0
{- | Module : Language.Egison.Match Licence : MIT This module defines some data types Egison pattern matching. -} module Language.Egison.Match ( Match , MatchingTree (..) , MatchingState (..) , PatternBinding , LoopPatContext (..) , SeqPatContext (..) , nullMState , MatchM , matchFail ) where import Control.Monad.Trans.Maybe import Language.Egison.Data import Language.Egison.IExpr -- -- Pattern Matching -- type Match = [Binding] data MatchingState = MState { mStateEnv :: Env , loopPatCtx :: [LoopPatContext] , seqPatCtx :: [SeqPatContext] , mStateBindings :: [Binding] , mTrees :: [MatchingTree] } instance Show MatchingState where show ms = "(MState " ++ unwords ["_", "_", "_", show (mStateBindings ms), show (mTrees ms)] ++ ")" data MatchingTree = MAtom IPattern WHNFData Matcher | MNode [PatternBinding] MatchingState deriving Show type PatternBinding = (String, IPattern) data LoopPatContext = LoopPatContext (String, ObjectRef) ObjectRef IPattern IPattern IPattern data SeqPatContext = SeqPatContext [MatchingTree] IPattern [Matcher] [WHNFData] | ForallPatContext [Matcher] [WHNFData] nullMState :: MatchingState -> Bool nullMState MState{ mTrees = [] } = True nullMState MState{ mTrees = MNode _ state : _ } = nullMState state nullMState _ = False -- -- Monads -- type MatchM = MaybeT EvalM matchFail :: MatchM a matchFail = MaybeT $ return Nothing
egison/egison
hs-src/Language/Egison/Match.hs
mit
1,597
0
12
431
390
232
158
38
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE Rank2Types #-} -- | A postgresql backend for persistent. module Database.Persist.Postgresql ( withPostgresqlPool , withPostgresqlConn , createPostgresqlPool , createPostgresqlPoolModified , module Database.Persist.Sql , ConnectionString , PostgresConf (..) , openSimpleConn , tableName , fieldName ) where import Database.Persist.Sql import Data.Fixed (Pico) import qualified Database.PostgreSQL.Simple as PG import qualified Database.PostgreSQL.Simple.TypeInfo as PG import qualified Database.PostgreSQL.Simple.TypeInfo.Static as PS import qualified Database.PostgreSQL.Simple.Internal as PG import qualified Database.PostgreSQL.Simple.ToField as PGTF import qualified Database.PostgreSQL.Simple.FromField as PGFF import qualified Database.PostgreSQL.Simple.Types as PG import Database.PostgreSQL.Simple.Ok (Ok (..)) import qualified Database.PostgreSQL.LibPQ as LibPQ import Control.Monad.Trans.Resource import Control.Exception (throw) import Control.Monad.IO.Class (MonadIO (..)) import Data.Typeable import Data.IORef import qualified Data.Map as Map import Data.Maybe import Data.Either (partitionEithers) import Control.Arrow import Data.List (find, sort, groupBy) import Data.Function (on) import Data.Conduit import qualified Data.Conduit.List as CL import Control.Monad.Logger (MonadLogger, runNoLoggingT) import qualified Data.IntMap as I import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B8 import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Blaze.ByteString.Builder.Char8 as BBB import qualified Blaze.ByteString.Builder as BB import Data.Text (Text) import Data.Aeson import Control.Monad (forM, mzero) import Data.Acquire (Acquire, mkAcquire, with) import System.Environment (getEnvironment) import Data.Int (Int64) import Data.Monoid ((<>)) import Data.Time (utc, localTimeToUTC) -- | A @libpq@ connection string. A simple example of connection -- string would be @\"host=localhost port=5432 user=test -- dbname=test password=test\"@. Please read libpq's -- documentation at -- <http://www.postgresql.org/docs/9.1/static/libpq-connect.html> -- for more details on how to create such strings. type ConnectionString = ByteString -- | Create a PostgreSQL connection pool and run the given -- action. The pool is properly released after the action -- finishes using it. Note that you should not use the given -- 'ConnectionPool' outside the action since it may be already -- been released. withPostgresqlPool :: (MonadBaseControl IO m, MonadLogger m, MonadIO m) => ConnectionString -- ^ Connection string to the database. -> Int -- ^ Number of connections to be kept open in -- the pool. -> (ConnectionPool -> m a) -- ^ Action to be executed that uses the -- connection pool. -> m a withPostgresqlPool ci = withSqlPool $ open' (const $ return ()) ci -- | Create a PostgreSQL connection pool. Note that it's your -- responsibility to properly close the connection pool when -- unneeded. Use 'withPostgresqlPool' for an automatic resource -- control. createPostgresqlPool :: (MonadIO m, MonadBaseControl IO m, MonadLogger m) => ConnectionString -- ^ Connection string to the database. -> Int -- ^ Number of connections to be kept open -- in the pool. -> m ConnectionPool createPostgresqlPool = createPostgresqlPoolModified (const $ return ()) -- | Same as 'createPostgresqlPool', but additionally takes a callback function -- for some connection-specific tweaking to be performed after connection -- creation. This could be used, for example, to change the schema. For more -- information, see: -- -- <https://groups.google.com/d/msg/yesodweb/qUXrEN_swEo/O0pFwqwQIdcJ> -- -- Since 2.1.3 createPostgresqlPoolModified :: (MonadIO m, MonadBaseControl IO m, MonadLogger m) => (PG.Connection -> IO ()) -- ^ action to perform after connection is created -> ConnectionString -- ^ Connection string to the database. -> Int -- ^ Number of connections to be kept open in the pool. -> m ConnectionPool createPostgresqlPoolModified modConn ci = createSqlPool $ open' modConn ci -- | Same as 'withPostgresqlPool', but instead of opening a pool -- of connections, only one connection is opened. withPostgresqlConn :: (MonadIO m, MonadBaseControl IO m, MonadLogger m) => ConnectionString -> (SqlBackend -> m a) -> m a withPostgresqlConn = withSqlConn . open' (const $ return ()) open' :: (PG.Connection -> IO ()) -> ConnectionString -> LogFunc -> IO SqlBackend open' modConn cstr logFunc = do conn <- PG.connectPostgreSQL cstr modConn conn openSimpleConn logFunc conn -- | Generate a 'Connection' from a 'PG.Connection' openSimpleConn :: LogFunc -> PG.Connection -> IO SqlBackend openSimpleConn logFunc conn = do smap <- newIORef $ Map.empty return SqlBackend { connPrepare = prepare' conn , connStmtMap = smap , connInsertSql = insertSql' , connClose = PG.close conn , connMigrateSql = migrate' , connBegin = const $ PG.begin conn , connCommit = const $ PG.commit conn , connRollback = const $ PG.rollback conn , connEscapeName = escape , connNoLimit = "LIMIT ALL" , connRDBMS = "postgresql" , connLimitOffset = decorateSQLWithLimitOffset "LIMIT ALL" , connLogFunc = logFunc } prepare' :: PG.Connection -> Text -> IO Statement prepare' conn sql = do let query = PG.Query (T.encodeUtf8 sql) return Statement { stmtFinalize = return () , stmtReset = return () , stmtExecute = execute' conn query , stmtQuery = withStmt' conn query } insertSql' :: EntityDef -> [PersistValue] -> InsertSqlResult insertSql' ent vals = let sql = T.concat [ "INSERT INTO " , escape $ entityDB ent , if null (entityFields ent) then " DEFAULT VALUES" else T.concat [ "(" , T.intercalate "," $ map (escape . fieldDB) $ entityFields ent , ") VALUES(" , T.intercalate "," (map (const "?") $ entityFields ent) , ")" ] ] in case entityPrimary ent of Just _pdef -> ISRManyKeys sql vals Nothing -> ISRSingle (sql <> " RETURNING " <> escape (fieldDB (entityId ent))) execute' :: PG.Connection -> PG.Query -> [PersistValue] -> IO Int64 execute' conn query vals = PG.execute conn query (map P vals) withStmt' :: MonadIO m => PG.Connection -> PG.Query -> [PersistValue] -> Acquire (Source m [PersistValue]) withStmt' conn query vals = pull `fmap` mkAcquire openS closeS where openS = do -- Construct raw query rawquery <- PG.formatQuery conn query (map P vals) -- Take raw connection (rt, rr, rc, ids) <- PG.withConnection conn $ \rawconn -> do -- Execute query mret <- LibPQ.exec rawconn rawquery case mret of Nothing -> do merr <- LibPQ.errorMessage rawconn fail $ case merr of Nothing -> "Postgresql.withStmt': unknown error" Just e -> "Postgresql.withStmt': " ++ B8.unpack e Just ret -> do -- Check result status status <- LibPQ.resultStatus ret case status of LibPQ.TuplesOk -> return () _ -> do msg <- LibPQ.resStatus status mmsg <- LibPQ.resultErrorMessage ret fail $ "Postgresql.withStmt': bad result status " ++ show status ++ " (" ++ maybe (show msg) (show . (,) msg) mmsg ++ ")" -- Get number and type of columns cols <- LibPQ.nfields ret oids <- forM [0..cols-1] $ \col -> fmap ((,) col) (LibPQ.ftype ret col) -- Ready to go! rowRef <- newIORef (LibPQ.Row 0) rowCount <- LibPQ.ntuples ret return (ret, rowRef, rowCount, oids) let getters = map (\(col, oid) -> getGetter conn oid $ PG.Field rt col oid) ids return (rt, rr, rc, getters) closeS (ret, _, _, _) = LibPQ.unsafeFreeResult ret pull x = do y <- liftIO $ pullS x case y of Nothing -> return () Just z -> yield z >> pull x pullS (ret, rowRef, rowCount, getters) = do row <- atomicModifyIORef rowRef (\r -> (r+1, r)) if row == rowCount then return Nothing else fmap Just $ forM (zip getters [0..]) $ \(getter, col) -> do mbs <- LibPQ.getvalue' ret row col case mbs of Nothing -> return PersistNull Just bs -> do ok <- PGFF.runConversion (getter mbs) conn bs `seq` case ok of Errors (exc:_) -> throw exc Errors [] -> error "Got an Errors, but no exceptions" Ok v -> return v -- | Avoid orphan instances. newtype P = P PersistValue instance PGTF.ToField P where toField (P (PersistText t)) = PGTF.toField t toField (P (PersistByteString bs)) = PGTF.toField (PG.Binary bs) toField (P (PersistInt64 i)) = PGTF.toField i toField (P (PersistDouble d)) = PGTF.toField d toField (P (PersistRational r)) = PGTF.Plain $ BBB.fromString $ show (fromRational r :: Pico) -- FIXME: Too Ambigous, can not select precision without information about field toField (P (PersistBool b)) = PGTF.toField b toField (P (PersistDay d)) = PGTF.toField d toField (P (PersistTimeOfDay t)) = PGTF.toField t toField (P (PersistUTCTime t)) = PGTF.toField t toField (P PersistNull) = PGTF.toField PG.Null toField (P (PersistList l)) = PGTF.toField $ listToJSON l toField (P (PersistMap m)) = PGTF.toField $ mapToJSON m toField (P (PersistDbSpecific s)) = PGTF.toField (Unknown s) toField (P (PersistObjectId _)) = error "Refusing to serialize a PersistObjectId to a PostgreSQL value" newtype Unknown = Unknown { unUnknown :: ByteString } deriving (Eq, Show, Read, Ord, Typeable) instance PGFF.FromField Unknown where fromField f mdata = case mdata of Nothing -> PGFF.returnError PGFF.UnexpectedNull f "" Just dat -> return (Unknown dat) instance PGTF.ToField Unknown where -- TODO adapt type to handle the (unsafe) non-escaped possibility -- -- toField (Unknown a) = PGTF.Escape a toField (Unknown a) = PGTF.Plain (BB.fromByteString a) type Getter a = PGFF.FieldParser a convertPV :: PGFF.FromField a => (a -> b) -> Getter b convertPV f = (fmap f .) . PGFF.fromField builtinGetters :: I.IntMap (Getter PersistValue) builtinGetters = I.fromList [ (k PS.bool, convertPV PersistBool) , (k PS.bytea, convertPV (PersistByteString . unBinary)) , (k PS.char, convertPV PersistText) , (k PS.name, convertPV PersistText) , (k PS.int8, convertPV PersistInt64) , (k PS.int2, convertPV PersistInt64) , (k PS.int4, convertPV PersistInt64) , (k PS.text, convertPV PersistText) , (k PS.xml, convertPV PersistText) , (k PS.float4, convertPV PersistDouble) , (k PS.float8, convertPV PersistDouble) , (k PS.abstime, convertPV PersistUTCTime) , (k PS.reltime, convertPV PersistUTCTime) , (k PS.money, convertPV PersistRational) , (k PS.bpchar, convertPV PersistText) , (k PS.varchar, convertPV PersistText) , (k PS.date, convertPV PersistDay) , (k PS.time, convertPV PersistTimeOfDay) , (k PS.timestamp, convertPV (PersistUTCTime. localTimeToUTC utc)) , (k PS.timestamptz, convertPV PersistUTCTime) , (k PS.bit, convertPV PersistInt64) , (k PS.varbit, convertPV PersistInt64) , (k PS.numeric, convertPV PersistRational) , (k PS.void, \_ _ -> return PersistNull) , (k PS.json, convertPV (PersistByteString . unUnknown)) , (k PS.jsonb, convertPV (PersistByteString . unUnknown)) , (k PS.unknown, convertPV (PersistByteString . unUnknown)) , (k PS.point, convertPV (PersistByteString . unUnknown)) , (k PS.polygon, convertPV (PersistByteString . unUnknown)) , (k PS.lseg, convertPV (PersistByteString . unUnknown)) , (k PS.box, convertPV (PersistByteString . unUnknown)) , (k PS.circle, convertPV (PersistByteString . unUnknown)) -- array types: same order as above , (1000, listOf PersistBool) , (1001, listOf (PersistByteString . unBinary)) , (1002, listOf PersistText) , (1003, listOf PersistText) , (1016, listOf PersistInt64) , (1005, listOf PersistInt64) , (1007, listOf PersistInt64) , (1009, listOf PersistText) , (143, listOf PersistText) , (1021, listOf PersistDouble) , (1022, listOf PersistDouble) , (1023, listOf PersistUTCTime) , (1024, listOf PersistUTCTime) , (791, listOf PersistRational) , (1014, listOf PersistText) , (1015, listOf PersistText) , (1182, listOf PersistDay) , (1183, listOf PersistTimeOfDay) , (1115, listOf PersistUTCTime) , (1185, listOf PersistUTCTime) , (1561, listOf PersistInt64) , (1563, listOf PersistInt64) , (1231, listOf PersistRational) -- no array(void) type , (2951, listOf (PersistDbSpecific . unUnknown)) , (199, listOf (PersistByteString . unUnknown)) , (3807, listOf (PersistByteString . unUnknown)) -- no array(unknown) either ] where k (PGFF.typoid -> i) = PG.oid2int i listOf f = convertPV (PersistList . map f . PG.fromPGArray) getGetter :: PG.Connection -> PG.Oid -> Getter PersistValue getGetter conn oid = fromMaybe defaultGetter $ I.lookup (PG.oid2int oid) builtinGetters where defaultGetter = convertPV (PersistDbSpecific . unUnknown) unBinary :: PG.Binary a -> a unBinary (PG.Binary x) = x doesTableExist :: (Text -> IO Statement) -> DBName -- ^ table name -> IO Bool doesTableExist getter (DBName name) = do stmt <- getter sql with (stmtQuery stmt vals) ($$ start) where sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_name=?" vals = [PersistText name] start = await >>= maybe (error "No results when checking doesTableExist") start' start' [PersistInt64 0] = finish False start' [PersistInt64 1] = finish True start' res = error $ "doesTableExist returned unexpected result: " ++ show res finish x = await >>= maybe (return x) (error "Too many rows returned in doesTableExist") migrate' :: [EntityDef] -> (Text -> IO Statement) -> EntityDef -> IO (Either [Text] [(Bool, Text)]) migrate' allDefs getter val = fmap (fmap $ map showAlterDb) $ do let name = entityDB val old <- getColumns getter val case partitionEithers old of ([], old'') -> do let old' = partitionEithers old'' let (newcols', udefs, fdefs) = mkColumns allDefs val let newcols = filter (not . safeToRemove val . cName) newcols' let udspair = map udToPair udefs -- Check for table existence if there are no columns, workaround -- for https://github.com/yesodweb/persistent/issues/152 exists <- if null old then doesTableExist getter name else return True if not exists then do let idtxt = case entityPrimary val of Just pdef -> T.concat [" PRIMARY KEY (", T.intercalate "," $ map (escape . fieldDB) $ compositeFields pdef, ")"] Nothing -> T.concat [escape $ fieldDB (entityId val) , " SERIAL PRIMARY KEY UNIQUE"] let addTable = AddTable $ T.concat -- Lower case e: see Database.Persist.Sql.Migration [ "CREATe TABLE " -- DO NOT FIX THE CAPITALIZATION! , escape name , "(" , idtxt , if null newcols then "" else "," , T.intercalate "," $ map showColumn newcols , ")" ] let uniques = flip concatMap udspair $ \(uname, ucols) -> [AlterTable name $ AddUniqueConstraint uname ucols] references = mapMaybe (\c@Column { cName=cname, cReference=Just (refTblName, _) } -> getAddReference allDefs name refTblName cname (cReference c)) $ filter (isJust . cReference) newcols foreignsAlt = map (\fdef -> let (childfields, parentfields) = unzip (map (\((_,b),(_,d)) -> (b,d)) (foreignFields fdef)) in AlterColumn name (foreignRefTableDBName fdef, AddReference (foreignConstraintNameDBName fdef) childfields parentfields)) fdefs return $ Right $ addTable : uniques ++ references ++ foreignsAlt else do let (acs, ats) = getAlters allDefs val (newcols, udspair) old' let acs' = map (AlterColumn name) acs let ats' = map (AlterTable name) ats return $ Right $ acs' ++ ats' (errs, _) -> return $ Left errs type SafeToRemove = Bool data AlterColumn = Type SqlType Text | IsNull | NotNull | Add' Column | Drop SafeToRemove | Default Text | NoDefault | Update' Text | AddReference DBName [DBName] [DBName] | DropReference DBName type AlterColumn' = (DBName, AlterColumn) data AlterTable = AddUniqueConstraint DBName [DBName] | DropConstraint DBName data AlterDB = AddTable Text | AlterColumn DBName AlterColumn' | AlterTable DBName AlterTable -- | Returns all of the columns in the given table currently in the database. getColumns :: (Text -> IO Statement) -> EntityDef -> IO [Either Text (Either Column (DBName, [DBName]))] getColumns getter def = do let sqlv=T.concat ["SELECT " ,"column_name " ,",is_nullable " ,",udt_name " ,",column_default " ,",numeric_precision " ,",numeric_scale " ,"FROM information_schema.columns " ,"WHERE table_catalog=current_database() " ,"AND table_schema=current_schema() " ,"AND table_name=? " ,"AND column_name <> ?"] stmt <- getter sqlv let vals = [ PersistText $ unDBName $ entityDB def , PersistText $ unDBName $ fieldDB (entityId def) ] cs <- with (stmtQuery stmt vals) ($$ helper) let sqlc = T.concat ["SELECT " ,"c.constraint_name, " ,"c.column_name " ,"FROM information_schema.key_column_usage c, " ,"information_schema.table_constraints k " ,"WHERE c.table_catalog=current_database() " ,"AND c.table_catalog=k.table_catalog " ,"AND c.table_schema=current_schema() " ,"AND c.table_schema=k.table_schema " ,"AND c.table_name=? " ,"AND c.table_name=k.table_name " ,"AND c.column_name <> ? " ,"AND c.constraint_name=k.constraint_name " ,"AND NOT k.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY') " ,"ORDER BY c.constraint_name, c.column_name"] stmt' <- getter sqlc us <- with (stmtQuery stmt' vals) ($$ helperU) return $ cs ++ us where getAll front = do x <- CL.head case x of Nothing -> return $ front [] Just [PersistText con, PersistText col] -> getAll (front . (:) (con, col)) Just [PersistByteString con, PersistByteString col] -> getAll (front . (:) (T.decodeUtf8 con, T.decodeUtf8 col)) Just o -> error $ "unexpected datatype returned for postgres o="++show o helperU = do rows <- getAll id return $ map (Right . Right . (DBName . fst . head &&& map (DBName . snd))) $ groupBy ((==) `on` fst) rows helper = do x <- CL.head case x of Nothing -> return [] Just x' -> do col <- liftIO $ getColumn getter (entityDB def) x' let col' = case col of Left e -> Left e Right c -> Right $ Left c cols <- helper return $ col' : cols -- | Check if a column name is listed as the "safe to remove" in the entity -- list. safeToRemove :: EntityDef -> DBName -> Bool safeToRemove def (DBName colName) = any (elem "SafeToRemove" . fieldAttrs) $ filter ((== DBName colName) . fieldDB) $ entityFields def getAlters :: [EntityDef] -> EntityDef -> ([Column], [(DBName, [DBName])]) -> ([Column], [(DBName, [DBName])]) -> ([AlterColumn'], [AlterTable]) getAlters defs def (c1, u1) (c2, u2) = (getAltersC c1 c2, getAltersU u1 u2) where getAltersC [] old = map (\x -> (cName x, Drop $ safeToRemove def $ cName x)) old getAltersC (new:news) old = let (alters, old') = findAlters defs (entityDB def) new old in alters ++ getAltersC news old' getAltersU :: [(DBName, [DBName])] -> [(DBName, [DBName])] -> [AlterTable] getAltersU [] old = map DropConstraint $ filter (not . isManual) $ map fst old getAltersU ((name, cols):news) old = case lookup name old of Nothing -> AddUniqueConstraint name cols : getAltersU news old Just ocols -> let old' = filter (\(x, _) -> x /= name) old in if sort cols == sort ocols then getAltersU news old' else DropConstraint name : AddUniqueConstraint name cols : getAltersU news old' -- Don't drop constraints which were manually added. isManual (DBName x) = "__manual_" `T.isPrefixOf` x getColumn :: (Text -> IO Statement) -> DBName -> [PersistValue] -> IO (Either Text Column) getColumn getter tname [PersistText x, PersistText y, PersistText z, d, npre, nscl] = case d' of Left s -> return $ Left s Right d'' -> case getType z of Left s -> return $ Left s Right t -> do let cname = DBName x ref <- getRef cname return $ Right Column { cName = cname , cNull = y == "YES" , cSqlType = t , cDefault = fmap stripSuffixes d'' , cDefaultConstraintName = Nothing , cMaxLen = Nothing , cReference = ref } where stripSuffixes t = loop' [ "::character varying" , "::text" ] where loop' [] = t loop' (p:ps) = case T.stripSuffix p t of Nothing -> loop' ps Just t' -> t' getRef cname = do let sql = T.concat [ "SELECT COUNT(*) FROM " , "information_schema.table_constraints " , "WHERE table_catalog=current_database() " , "AND table_schema=current_schema() " , "AND table_name=? " , "AND constraint_type='FOREIGN KEY' " , "AND constraint_name=?" ] let ref = refName tname cname stmt <- getter sql with (stmtQuery stmt [ PersistText $ unDBName tname , PersistText $ unDBName ref ]) ($$ do Just [PersistInt64 i] <- CL.head return $ if i == 0 then Nothing else Just (DBName "", ref)) d' = case d of PersistNull -> Right Nothing PersistText t -> Right $ Just t _ -> Left $ T.pack $ "Invalid default column: " ++ show d getType "int4" = Right SqlInt32 getType "int8" = Right SqlInt64 getType "varchar" = Right SqlString getType "date" = Right SqlDay getType "bool" = Right SqlBool getType "timestamptz" = Right SqlDayTime getType "float4" = Right SqlReal getType "float8" = Right SqlReal getType "bytea" = Right SqlBlob getType "time" = Right SqlTime getType "numeric" = getNumeric npre nscl getType a = Right $ SqlOther a getNumeric (PersistInt64 a) (PersistInt64 b) = Right $ SqlNumeric (fromIntegral a) (fromIntegral b) getNumeric a b = Left $ T.pack $ "Can not get numeric field precision, got: " ++ show a ++ " and " ++ show b ++ " as precision and scale" getColumn _ _ x = return $ Left $ T.pack $ "Invalid result from information_schema: " ++ show x -- | Intelligent comparison of SQL types, to account for SqlInt32 vs SqlOther integer sqlTypeEq :: SqlType -> SqlType -> Bool sqlTypeEq x y = T.toCaseFold (showSqlType x) == T.toCaseFold (showSqlType y) findAlters :: [EntityDef] -> DBName -> Column -> [Column] -> ([AlterColumn'], [Column]) findAlters defs _tablename col@(Column name isNull sqltype def _defConstraintName _maxLen ref) cols = case filter (\c -> cName c == name) cols of [] -> ([(name, Add' col)], cols) Column _ isNull' sqltype' def' _defConstraintName' _maxLen' ref':_ -> let refDrop Nothing = [] refDrop (Just (_, cname)) = [(name, DropReference cname)] refAdd Nothing = [] refAdd (Just (tname, a)) = case find ((==tname) . entityDB) defs of Just refdef -> [(tname, AddReference a [name] [fieldDB (entityId refdef)])] Nothing -> error $ "could not find the entityDef for reftable[" ++ show tname ++ "]" modRef = if fmap snd ref == fmap snd ref' then [] else refDrop ref' ++ refAdd ref modNull = case (isNull, isNull') of (True, False) -> [(name, IsNull)] (False, True) -> let up = case def of Nothing -> id Just s -> (:) (name, Update' s) in up [(name, NotNull)] _ -> [] modType | sqlTypeEq sqltype sqltype' = [] -- When converting from Persistent pre-2.0 databases, we -- need to make sure that TIMESTAMP WITHOUT TIME ZONE is -- treated as UTC. | sqltype == SqlDayTime && sqltype' == SqlOther "timestamp" = [(name, Type sqltype $ T.concat [ " USING " , escape name , " AT TIME ZONE 'UTC'" ])] | otherwise = [(name, Type sqltype "")] modDef = if def == def' then [] else case def of Nothing -> [(name, NoDefault)] Just s -> [(name, Default s)] in (modRef ++ modDef ++ modNull ++ modType, filter (\c -> cName c /= name) cols) -- | Get the references to be added to a table for the given column. getAddReference :: [EntityDef] -> DBName -> DBName -> DBName -> Maybe (DBName, DBName) -> Maybe AlterDB getAddReference allDefs table reftable cname ref = case ref of Nothing -> Nothing Just (s, _) -> Just $ AlterColumn table (s, AddReference (refName table cname) [cname] [id_]) where id_ = fromMaybe (error $ "Could not find ID of entity " ++ show reftable) $ do entDef <- find ((== reftable) . entityDB) allDefs return (fieldDB (entityId entDef)) showColumn :: Column -> Text showColumn (Column n nu sqlType' def _defConstraintName _maxLen _ref) = T.concat [ escape n , " " , showSqlType sqlType' , " " , if nu then "NULL" else "NOT NULL" , case def of Nothing -> "" Just s -> " DEFAULT " <> s ] showSqlType :: SqlType -> Text showSqlType SqlString = "VARCHAR" showSqlType SqlInt32 = "INT4" showSqlType SqlInt64 = "INT8" showSqlType SqlReal = "DOUBLE PRECISION" showSqlType (SqlNumeric s prec) = T.concat [ "NUMERIC(", T.pack (show s), ",", T.pack (show prec), ")" ] showSqlType SqlDay = "DATE" showSqlType SqlTime = "TIME" showSqlType SqlDayTime = "TIMESTAMP WITH TIME ZONE" showSqlType SqlBlob = "BYTEA" showSqlType SqlBool = "BOOLEAN" -- Added for aliasing issues re: https://github.com/yesodweb/yesod/issues/682 showSqlType (SqlOther (T.toLower -> "integer")) = "INT4" showSqlType (SqlOther t) = t showAlterDb :: AlterDB -> (Bool, Text) showAlterDb (AddTable s) = (False, s) showAlterDb (AlterColumn t (c, ac)) = (isUnsafe ac, showAlter t (c, ac)) where isUnsafe (Drop safeRemove) = not safeRemove isUnsafe _ = False showAlterDb (AlterTable t at) = (False, showAlterTable t at) showAlterTable :: DBName -> AlterTable -> Text showAlterTable table (AddUniqueConstraint cname cols) = T.concat [ "ALTER TABLE " , escape table , " ADD CONSTRAINT " , escape cname , " UNIQUE(" , T.intercalate "," $ map escape cols , ")" ] showAlterTable table (DropConstraint cname) = T.concat [ "ALTER TABLE " , escape table , " DROP CONSTRAINT " , escape cname ] showAlter :: DBName -> AlterColumn' -> Text showAlter table (n, Type t extra) = T.concat [ "ALTER TABLE " , escape table , " ALTER COLUMN " , escape n , " TYPE " , showSqlType t , extra ] showAlter table (n, IsNull) = T.concat [ "ALTER TABLE " , escape table , " ALTER COLUMN " , escape n , " DROP NOT NULL" ] showAlter table (n, NotNull) = T.concat [ "ALTER TABLE " , escape table , " ALTER COLUMN " , escape n , " SET NOT NULL" ] showAlter table (_, Add' col) = T.concat [ "ALTER TABLE " , escape table , " ADD COLUMN " , showColumn col ] showAlter table (n, Drop _) = T.concat [ "ALTER TABLE " , escape table , " DROP COLUMN " , escape n ] showAlter table (n, Default s) = T.concat [ "ALTER TABLE " , escape table , " ALTER COLUMN " , escape n , " SET DEFAULT " , s ] showAlter table (n, NoDefault) = T.concat [ "ALTER TABLE " , escape table , " ALTER COLUMN " , escape n , " DROP DEFAULT" ] showAlter table (n, Update' s) = T.concat [ "UPDATE " , escape table , " SET " , escape n , "=" , s , " WHERE " , escape n , " IS NULL" ] showAlter table (reftable, AddReference fkeyname t2 id2) = T.concat [ "ALTER TABLE " , escape table , " ADD CONSTRAINT " , escape fkeyname , " FOREIGN KEY(" , T.intercalate "," $ map escape t2 , ") REFERENCES " , escape reftable , "(" , T.intercalate "," $ map escape id2 , ")" ] showAlter table (_, DropReference cname) = T.concat [ "ALTER TABLE " , escape table , " DROP CONSTRAINT " , escape cname ] -- | get the SQL string for the table that a PeristEntity represents -- Useful for raw SQL queries tableName :: forall record. ( PersistEntity record , PersistEntityBackend record ~ SqlBackend ) => record -> Text tableName = escape . tableDBName -- | get the SQL string for the field that an EntityField represents -- Useful for raw SQL queries fieldName :: forall record typ. ( PersistEntity record , PersistEntityBackend record ~ SqlBackend ) => EntityField record typ -> Text fieldName = escape . fieldDBName escape :: DBName -> Text escape (DBName s) = T.pack $ '"' : go (T.unpack s) ++ "\"" where go "" = "" go ('"':xs) = "\"\"" ++ go xs go (x:xs) = x : go xs -- | Information required to connect to a PostgreSQL database -- using @persistent@'s generic facilities. These values are the -- same that are given to 'withPostgresqlPool'. data PostgresConf = PostgresConf { pgConnStr :: ConnectionString -- ^ The connection string. , pgPoolSize :: Int -- ^ How many connections should be held on the connection pool. } deriving Show instance FromJSON PostgresConf where parseJSON = withObject "PostgresConf" $ \o -> do database <- o .: "database" host <- o .: "host" port <- o .:? "port" .!= 5432 user <- o .: "user" password <- o .: "password" pool <- o .: "poolsize" let ci = PG.ConnectInfo { PG.connectHost = host , PG.connectPort = port , PG.connectUser = user , PG.connectPassword = password , PG.connectDatabase = database } cstr = PG.postgreSQLConnectionString ci return $ PostgresConf cstr pool instance PersistConfig PostgresConf where type PersistConfigBackend PostgresConf = SqlPersistT type PersistConfigPool PostgresConf = ConnectionPool createPoolConfig (PostgresConf cs size) = runNoLoggingT $ createPostgresqlPool cs size -- FIXME runPool _ = runSqlPool loadConfig = parseJSON applyEnv c0 = do env <- getEnvironment return $ addUser env $ addPass env $ addDatabase env $ addPort env $ addHost env c0 where addParam param val c = c { pgConnStr = B8.concat [pgConnStr c, " ", param, "='", pgescape val, "'"] } pgescape = B8.pack . go where go ('\'':rest) = '\\' : '\'' : go rest go ('\\':rest) = '\\' : '\\' : go rest go ( x :rest) = x : go rest go [] = [] maybeAddParam param envvar env = maybe id (addParam param) $ lookup envvar env addHost = maybeAddParam "host" "PGHOST" addPort = maybeAddParam "port" "PGPORT" addUser = maybeAddParam "user" "PGUSER" addPass = maybeAddParam "password" "PGPASS" addDatabase = maybeAddParam "dbname" "PGDATABASE" refName :: DBName -> DBName -> DBName refName (DBName table) (DBName column) = DBName $ T.concat [table, "_", column, "_fkey"] udToPair :: UniqueDef -> (DBName, [DBName]) udToPair ud = (uniqueDBName ud, map snd $ uniqueFields ud)
creichert/persistent-postgresql
Database/Persist/Postgresql.hs
mit
37,336
0
32
13,152
9,778
5,136
4,642
-1
-1
module Main(main) where import Control.Exception (SomeException, handle) import System.IO (IOMode (..), hClose, hFileSize, openFile) handler :: SomeException -> IO (Maybe Integer) handler _ = return Nothing simpleFileSize :: FilePath -> IO (Maybe Integer) simpleFileSize path = handle handler $ do h <- openFile path ReadMode size <- hFileSize h hClose h return (Just size) main = do putStrLn "Input file name:" path <- getLine size <- simpleFileSize path print size
rockdragon/julia-programming
code/haskell/BetterIO.hs
mit
515
0
10
118
181
89
92
16
1
module LAEMain where import HaskellCourse.LAE.LAE import HaskellCourse.Util -- | Run an AE program from a file passed in via the command line. -- Print the results back to stdout. main :: IO () main = runCode (show . runLAE)
joshcough/HaskellCourse
executables/LAEMain.hs
mit
228
0
7
42
42
25
17
5
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BC import Data.FileEmbed (embedFile) import Data.List (sortOn) testData :: ByteString testData = $(embedFile "test.txt") input :: ByteString input = $(embedFile "input.txt") type SortedChars = [ByteString] type Selector = SortedChars -> Char prepare :: ByteString -> [SortedChars] prepare = map (sortOn BC.length . BC.group . BC.sort) . BC.transpose . BC.lines degarble :: Selector -> ByteString -> String degarble s = map s . prepare mostCommon :: Selector mostCommon = BC.head . last test1 :: Bool test1 = "easter" == degarble mostCommon testData part1 :: String part1 = degarble mostCommon input leastCommon :: Selector leastCommon = BC.head . head test2 :: Bool test2 = "advent" == degarble leastCommon testData part2 :: String part2 = degarble leastCommon input main :: IO () main = do print test1 putStrLn part1 print test2 putStrLn part2
genos/online_problems
advent_of_code_2016/day6/src/Main.hs
mit
1,031
0
12
170
317
171
146
35
1
import Data.Char myFormMaybe :: a -> Maybe a -> a myFormMaybe _ (Just x) = x myFormMaybe d Nothing = d
threetreeslight/learning-haskell
practice/polymorphic.hs
mit
104
0
7
22
48
24
24
4
1
{-# LANGUAGE OverloadedStrings #-} module FuseOps where import FS import Stat import BufferedStream import System.Fuse.ByteString hiding (EntryType) import System.Posix.Types import Data.ByteString (ByteString) import Data.Maybe myGetFileStat :: FS -> ByteString -> IO (Either Errno FileStat) myGetFileStat fs p = do ctx <- getFuseContext if p == "/" || p == "." || p == ".." then return (Right $ dirStat ctx 0) else Right . entryToFileStat ctx <$> getEntry fs Nothing p myOpen :: FS -> ByteString -> OpenMode -> OpenFileFlags -> IO (Either Errno BufferedStream) myOpen fs p m _ = case m of ReadOnly -> do bf <- getFileContent' fs p return $ Right bf _ -> return $ Left ePERM myRead :: FS -> ByteString -> BufferedStream -> ByteCount -> FileOffset -> IO (Either Errno ByteString) myRead _ _ bf bc fo = Right <$> readBufferedStream bf bc fo myRelease :: ByteString -> BufferedStream -> IO () myRelease _ = closeBufferedStream myOpenDirectory :: FS -> ByteString -> IO Errno myOpenDirectory _ _ = return eOK defaultStats :: FuseContext -> [(ByteString, FileStat)] defaultStats ctx = [(".", dirStat ctx 0), ("..", dirStat ctx 0)] myReadDirectory :: FS -> ByteString -> IO (Either Errno [(ByteString, FileStat)]) myReadDirectory fs f = do ctx <- getFuseContext Right . (\l -> defaultStats ctx ++ map (fmap $ entryTypeToFileStat ctx) l) <$> getDirectoryEntries fs f getFileSystemStats :: ByteString -> IO (Either Errno FileSystemStats) getFileSystemStats _ = return $ Right FileSystemStats { fsStatBlockSize = 512 , fsStatBlockCount = 1 , fsStatBlocksFree = 1 , fsStatBlocksAvailable = 1 , fsStatFileCount = 5 -- IS THIS CORRECT? , fsStatFilesFree = 10 -- WHAT IS THIS? , fsStatMaxNameLength = 255 -- SEEMS SMALL? } myFuseOperations :: FS -> FuseOperations BufferedStream myFuseOperations o = defaultFuseOps { fuseGetFileStat = myGetFileStat o , fuseOpen = myOpen o , fuseRead = myRead o , fuseRelease = myRelease , fuseOpenDirectory = myOpenDirectory o , fuseReadDirectory = myReadDirectory o , fuseGetFileSystemStats = getFileSystemStats } entryToFileStat :: FuseContext -> Entry -> FileStat entryToFileStat ctx = go where go Dir = dirStat ctx 0 go (File stats) = fStat stats fStat (FileStats s t) = fileStat ctx (fromMaybe 0 t) (fromMaybe 0 s) entryTypeToFileStat :: FuseContext -> EntryType -> FileStat entryTypeToFileStat ctx = entryToFileStat ctx . trans where trans DirType = Dir trans FileType = File (FileStats Nothing Nothing)
ffwng/httpfs
src/FuseOps.hs
mit
2,704
0
15
654
821
428
393
63
2
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Serials.Model.Source where import Prelude hiding (id) import Control.Applicative import Data.Text (Text, unpack) import Data.Aeson (ToJSON(..), FromJSON, Value(..), toJSON) import Data.Pool import Data.Time import Data.List (sort, group, sortBy) import qualified Data.HashMap.Strict as HashMap import Data.HashMap.Strict (HashMap) import GHC.Generics import qualified Database.RethinkDB as R import Database.RethinkDB.NoClash hiding (table, status, toJSON, Change, Object, Null, group) import Serials.Model.Lib.Crud import Serials.Model.Chapter (Chapter(..)) import Serials.Model.Scan (Scan(..)) import Serials.Link.Import (ImportSettings) import Serials.Types instance FromJSON ImportSettings instance ToJSON ImportSettings data Status = Complete | Active | Disabled | Abandoned | Proposed deriving (Show, Eq, Generic) instance FromJSON Status instance ToJSON Status type Tag = Text data TagCount = TagCount { tagName :: Text, tagCount :: Int } deriving (Eq, Show, Generic) instance ToJSON TagCount data Source = Source { id :: Text, url :: Text, name :: Text, author :: Text, authorUrl :: Text, hidden :: Bool, tags :: [Tag], changeId :: Maybe Text, status :: Status, imageUrl :: Text, imageMissingTitle :: Bool, imageArtist :: Maybe Text, imageArtistUrl :: Maybe Text, imageArtistAboutUrl :: Maybe Text, importSettings :: ImportSettings, lastScan :: Maybe Scan, chapters :: [Chapter] } deriving (Show, Generic, Eq) instance FromJSON Source instance ToJSON Source instance FromDatum Source instance ToDatum Source -- when they are displayed in a list newtype SourceThumbnail = SourceThumbnail Source deriving (Show, Generic) instance FromJSON SourceThumbnail instance ToJSON SourceThumbnail where toJSON (SourceThumbnail source) = Object $ foldr HashMap.delete obj ["chapters", "lastScan", "importSettings"] where (Object obj) = toJSON source table = R.table "sources" tagIndexName = "tags" tagIndex = Index tagIndexName -- could I pass in both the table and the database connection? -- sure... why not? -- then I could do the magic sauce... -- runr $ table # orderBy [asc "id"] -- well, just start with the database connection list :: App [Source] list = docsList table find :: Text -> App (Maybe Source) find = docsFind table findByTag :: Tag -> App [Source] findByTag tag = runDb $ table # getAll tagIndex [expr tag] -- either way this is slow right? So just get all the tags and tally it yourself allTags :: App [TagCount] allTags = do tss <- runDb $ table # R.map (!"tags") :: App [[Tag]] let grouped = group $ sort $ concat tss counts = map (\ts -> TagCount (head ts) (length ts)) grouped return $ sortBy (\a b -> compare (tagCount b) (tagCount a)) counts insert :: Source -> App Text insert = docsInsert table save :: Text -> Source -> App (Either RethinkDBError ()) save id s = do er <- runDb $ table # get (expr id) # replace (const (toDatum s)) :: App (Either RethinkDBError WriteResponse) return $ fmap (return ()) er delete :: Text -> App () delete = docsRemove table init :: App () init = do initDb $ runDb $ tableCreate table initDb $ runDb $ table # ex indexCreate ["multi" := True] (tagIndexName) (!expr tagIndexName) isActive :: Source -> Bool isActive = (== Active) . status deleteChapters :: Pool RethinkDBHandle -> Text -> IO () deleteChapters h sourceId = runPool h $ table # get (expr sourceId) # update (const ["chapters" := (toDatum empty)]) where empty :: [Chapter] empty = []
seanhess/serials
server/Serials/Model/Source.hs
mit
3,612
0
15
666
1,182
650
532
94
1
module Types where type Id = Integer type Latitude = Float type Longitude = Float type Tags = [ImportTag] type Version = Integer type Timestamp = Integer type Changeset = Integer type UID = Integer type SID = String type User = String type Members = Tags type Key = String type Value = String type Nodes = [Integer] data ImportTag = ImportTag Key Value deriving (Show) data ImportNode = ImportNode Id Latitude Longitude Tags Version Timestamp Changeset UID SID deriving Show data ImportWay = ImportWay Id Tags Version Timestamp Changeset UID User Nodes deriving Show data ImportRelation = ImportRelation Id Tags Version Timestamp Changeset User Members deriving Show
ederoyd46/OSMImport
src/Types.hs
mit
951
0
6
393
190
115
75
19
0
{-# LANGUAGE NoMonomorphismRestriction #-} module DetermineType where x = 5 y = x + 5 w :: Num a => a w = y * 10 x2 = 5 y2 = x2 + 5 z :: Num a => a -> a z y2 = y2 * 10 x3 = 5 y3 = x3 + 5 f :: Fractional a => a f = 4 / y3 x4 = "Julie" y4 = "<3" z4 = "Haskell" f2 :: [Char] f2 = x4 ++ y4 ++ z4
Numberartificial/workflow
haskell-first-principles/haskell-from-first-principles-master/05/05.08.02-derermine-the-types.hs
mit
296
0
6
90
153
85
68
19
1
module Example where import AST import TypeCheck import Compiler {- $((\(s : Int -> TyQ) -> (s 1)) (\(i: Int) -> [| $i + $i |])) -- should be (1 + 1) after stage 1 -- and evaluate to 2 -} tm1 :: Term tm1 = TmSplice $ TmApp (TmAbs "s" (TyArrow TyInt TyQ) (TmApp (TmVar "s") (TmInt 1))) (TmAbs "i" TyInt (TmBracket $ TmApp (TmApp (TmVar "plus") (TmSplice $ TmVar "i")) (TmSplice $ TmVar "i"))) {- $((\(s : String) -> TmAbs s TyInt (TyVar s)) genstr) -- should be (_x0) -} tm2 :: Term tm2 = TmSplice $ TmApp (TmAbs "s" TyString $ TmApp (TmApp (TmApp (TmVar "TmAbs") (TmVar "s")) (TmVar "TyInt")) (TmApp (TmVar "TmVar") (TmVar "s"))) (TmVar "genstr")
izgzhen/template
src/Example.hs
mit
884
0
16
357
224
116
108
20
1
{-# OPTIONS_HADDOCK hide, prune #-} module Handler.Home.UIButtons ( uiButtons ) where import Import import Text.Julius -- | Rotating circular progress bar. -- Exposes: -- * #helpbutton -- * #fullscreenbutton -- * #submitbutton -- * #toolboxbutton -- * #clearbutton -- * #evaluatebutton uiButtons :: Maybe (ScenarioProblemId, UserId) -> Handler (Widget, Widget) uiButtons mscpuid = do popupSubmitId <- newIdent popupShareId <- newIdent sfGeometry <- newIdent sfPreview <- newIdent submitForm <- newIdent previewcontainer <- newIdent textAreaDesc <- newIdent let popupSubmit = do toWidgetBody [hamlet| <script> (function() { if (document.getElementById("facebook-jssdk")) return; var fbdiv = document.createElement("div"); fbdiv.id = "fb-root"; document.body.insertBefore(fbdiv, document.body.firstChild); var js = document.createElement("script"); js.id = "facebook-jssdk"; js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.8&appId=1837721753181850"; document.body.insertBefore(js, document.body.firstChild);}()); <div style="display: none;" aria-hidden="true" class="modal modal-va-middle fade" ##{popupSubmitId} role="dialog" tabindex="-1"> <div class="modal-dialog modal-xs"> <div class="modal-content"> <div class="modal-heading"> <p class="modal-title"> Submit your design <div class="modal-inner"> <div ##{previewcontainer}> <form ##{submitForm} method="post"> <input type="hidden" ##{sfGeometry} name="geometry"> <input type="hidden" ##{sfPreview} name="preview"> <div class="form-group form-group-label"> <label.floating-label for="#{textAreaDesc}">Share your ideas <textarea.form-control.textarea-autosize form="#{submitForm}" id="#{textAreaDesc}" rows="1" name="description"> <div class="modal-footer"> <p class="text-right"> <a.btn.btn-flat.btn-brand-accent.waves-attach.waves-effect data-dismiss="modal"> Cancel <a.btn.btn-flat.btn-brand-accent.waves-attach.waves-effect data-dismiss="modal" onclick="$('##{submitForm}').submit();"> Save $case mscpuid $of Nothing $of Just (pId, uId) <div style="display: none;" aria-hidden="true" class="modal modal-va-middle fade" ##{popupShareId} role="dialog" tabindex="-1"> <div class="modal-dialog modal-xs"> <div class="modal-content"> <div class="modal-heading"> <p class="modal-title"> Share this design with others <div class="modal-inner"> <p class="text"> You can share the following link that refers to the last saved version of this design: <code> @{SubmissionViewerR pId uId} <p class="text"> Alternatively, use your favourite button: <div style="text-align:center"> <a.shareButton onclick="FB.ui({method: 'share',mobile_iframe: true, href: '@{SubmissionViewerR pId uId}'}, function(response){});"> <img src="@{StaticR img_fbIcon_png}" style="width:40px;height:40px;" title="Share on Facebook" alt="Share on Facebook"> <a.shareButton href="http://vk.com/share.php?url=@{SubmissionViewerR pId uId}" onclick="javascript:window.open(this.href, 'popUpWindow', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=700,width=500,left=20,top=10');return false;"> <img src="@{StaticR img_vkIcon_png}" style="width:40px;height:40px;" title="Share on Vkontakte" alt="Share on Vkontakte"> <a.shareButton onclick="window.open('https://twitter.com/intent/tweet?url=' + encodeURIComponent('@{SubmissionViewerR pId uId}') + '&text=' + encodeURIComponent('Check out this design on #quakit!') + '&hashtags=mooc,edx,ethz,chairia,urbandesign', 'popUpWindow', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=700,width=500,left=20,top=10');return false;"> <img src="@{StaticR img_twitterIcon_png}" style="width:40px;height:40px;" title="Tweet the link" alt="Tweet the link"> <a.shareButton href="https://plus.google.com/share?url=@{SubmissionViewerR pId uId}" onclick="javascript:window.open(this.href, 'popUpWindow', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=700,width=500,left=20,top=10');return false;"> <img src="@{StaticR img_gIcon_png}" style="width:40px;height:40px;" title="Share on Google" alt="Share on Google"> <div class="modal-footer"> <p class="text-right"> <a.btn.btn-flat.btn-brand-accent.waves-attach.waves-effect data-dismiss="modal"> Close |] uiButtonsG = do uiButton <- newIdent guiElement <- newIdent guiplaceholder <- newIdent idleplaceholder <- newIdent activeplaceholder <- newIdent btn <- newIdent serviceClear <- newIdent serviceRun <- newIdent submitbutton <- newIdent toWidgetHead [cassius| /* GUI icons */ .#{guiElement} fill: #FF8A65 /* #FFAB91 */ stroke: #FFFFFF stroke-width: 0.0 .#{uiButton}:hover cursor: pointer .#{uiButton}:hover .#{guiElement} fill: #FF5722 .#{uiButton}:active .#{guiElement} fill: #FF5722 .#{uiButton} position: relative padding: 0 margin: 0 z-index: 10 overflow: hidden width: 64px height: 64px rect.#{btn} stroke: #FFFFFF fill: #FFFFFF fill-opacity: 0 stroke-opacity: 0 ##{guiplaceholder} position: absolute bottom: 0 padding: 0 margin: 0 z-index: 4 overflow: visible /* height: 256px */ width: 64px -webkit-transition: width 300ms ease-in-out, left 300ms ease-in-out -moz-transition: width 300ms ease-in-out, left 300ms ease-in-out -o-transition: width 300ms ease-in-out, left 300ms ease-in-out transition: width 300ms ease-in-out, left 300ms ease-in-out .#{activeplaceholder} left: -32px .#{idleplaceholder} left: -64px .shareButton display: inline-block width: 40px height: 40px cursor: pointer cursor: hand -webkit-filter: drop-shadow(0px 1px 3px rgba(0,0,0,.3)) filter: drop-shadow(0px 1px 3px rgba(0,0,0,.3)) -ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=0, OffY=1, Color='#444')" filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=0, OffY=1, Color='#444')" |] -- sfGeometry <- newIdent -- sfPreview <- newIdent -- submitButton <- newIdent -- previewcontainer <- newIdent toWidgetHead [julius| "use strict" /** Registers one callback; comes from Handler.Home.UIButtons. * onClick :: (submitUrl -> FeatureCollection -> Image -> IO ()) -> IO () * return :: IO () */ function registerSubmit(onClick) { document.getElementById('#{rawJS submitbutton}').style.display = "block" document.getElementById('#{rawJS submitbutton}').addEventListener("click", function() { onClick( function(submitUrl, fc, img) { document.getElementById('#{rawJS sfGeometry}').value = JSON.stringify(fc); document.getElementById('#{rawJS sfPreview}').value = img; var eimg = document.createElement("img"); eimg.src = img; eimg.style.width = "100%"; document.getElementById('#{rawJS previewcontainer}').innerHTML = ""; document.getElementById('#{rawJS previewcontainer}').appendChild(eimg); document.getElementById('#{rawJS submitForm}').action = submitUrl; $('##{rawJS popupSubmitId}').modal('show'); }); }); } /** Registers one callback; comes from Handler.Home.UIButtons. * onClick :: IO () * return :: IO () */ function registerResetCamera(onClick) { document.getElementById('resetposbutton').addEventListener("click", onClick); } /** Registers one callback; comes from Handler.Home.UIButtons. * onClick :: IO () * return :: IO () */ function registerServiceClear(onClick) { document.getElementById('#{rawJS serviceClear}').addEventListener("click", onClick); } /** Registers one callback; comes from Handler.Home.UIButtons. * onClick :: IO () * return :: IO () */ function registerServiceRun(onClick) { document.getElementById('#{rawJS serviceRun}').style.display = "block" document.getElementById('#{rawJS serviceRun}').addEventListener("click", onClick); } /** Shows or hides button "clear"; comes from Handler.Home.UIButtons. * state :: Bool * return :: IO () */ function toggleServiceClear(state) { document.getElementById('#{rawJS serviceClear}').style.display = state ? "block" : "none"; document.getElementById('#{rawJS serviceRun}').style.display = state ? "none" : "block"; } // Toggle fullscreen and change the fullscreen button shape function toggleFullScreen() { if (!document['fullscreenElement'] && !document['mozFullScreenElement'] && !document['webkitFullscreenElement'] && !document['msFullscreenElement'] && !document['fullScreen']) { if (document.documentElement['requestFullscreen']) { document.documentElement.requestFullscreen(); } else if (document.documentElement['msRequestFullscreen']) { document.documentElement.msRequestFullscreen(); } else if (document.documentElement['mozRequestFullScreen']) { document.documentElement.mozRequestFullScreen(); } else if (document.documentElement['webkitRequestFullscreen']) { document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT); } } else { if (document['exitFullscreen']) { document.exitFullscreen(); } else if (document['msExitFullscreen']) { document.msExitFullscreen(); } else if (document['mozCancelFullScreen']) { document.mozCancelFullScreen(); } else if (document['webkitExitFullscreen']) { document.webkitExitFullscreen(); } else { document.cancelFullScreen(); document.exitFullscreen(); } } }; // change fullscreen button function checkfullscreen() { if (document['fullscreenElement'] || document['webkitFullscreenElement'] || document['mozFullScreenElement']) { document.getElementById('fullscreenbicon').innerText = "fullscreen_exit"; } else { document.getElementById('fullscreenbicon').innerText = "fullscreen"; } }; document.addEventListener('webkitfullscreenchange', function(e) {checkfullscreen();}, false); document.addEventListener('mozfullscreenchange', function(e) {checkfullscreen();}, false); document.addEventListener('msfullscreenchange', function(e) {checkfullscreen();}, false); document.addEventListener('fullscreenchange', function(e) {checkfullscreen();}, false); // Toggle GUI panel on the right side of window function toggleGUIPanel(){ var panel = document.getElementById('guipanel'); if (panel.className == 'idleguipanel') { panel.className = 'activeguipanel'; document.getElementById('#{rawJS guiplaceholder}').className = '#{rawJS activeplaceholder}'; } else { panel.className = 'idleguipanel'; document.getElementById('#{rawJS guiplaceholder}').className = '#{rawJS idleplaceholder}'; } }; |] toWidgetBody [hamlet| <div .#{idleplaceholder} ##{guiplaceholder}> <div class="fbtn-inner open"> <a aria-expanded="true" class="fbtn fbtn-lg fbtn-red waves-attach waves-circle waves-light waves-effect" onclick="$(this).parent().toggleClass('open');"> <span class="fbtn-text fbtn-text-left">Tools <span class="fbtn-ori icon">apps <span class="fbtn-sub icon">close <div class="fbtn-dropup"> $case mscpuid $of Just (_, _) <a class="fbtn fbtn-brand waves-attach waves-circle waves-effect" onclick="$('##{popupShareId}').modal('show');"> <span class="fbtn-text fbtn-text-left">Share <span class="icon icon-lg">share $of Nothing <a class="fbtn waves-attach waves-circle waves-effect fbtn-brand-accent" #resetposbutton> <span class="fbtn-text fbtn-text-left">Reset camera position <span class="icon icon-lg" style="font-size: 2em;margin-left:-8px;vertical-align:-32%;margin-top:-3px;">fullscreen <span class="icon icon" style="margin-left: -24px;font-size: 1em;line-height: 1em;">videocam <a class="fbtn waves-attach waves-circle waves-effect" #helpbutton onclick="$('#popuphelp').modal('show')"> <span class="fbtn-text fbtn-text-left">How-to: mouse & finger controls <span class="icon icon-lg">help_outline <a class="fbtn waves-attach waves-circle waves-effect" #fullscreenbutton onclick="toggleFullScreen()"> <span class="fbtn-text fbtn-text-left">Toggle fullscreen <span class="icon icon-lg" #fullscreenbicon>fullscreen <a class="fbtn waves-attach waves-circle waves-effect" #toolboxbutton onclick="toggleGUIPanel()"> <span class="fbtn-text fbtn-text-left">Control panel <span class="icon icon-lg">settings <a class="fbtn fbtn-brand waves-attach waves-circle waves-effect" style="display: none;" ##{submitbutton}> <span class="fbtn-text fbtn-text-left">Submit proposal <span class="icon icon-lg">save <a class="fbtn fbtn-brand-accent waves-attach waves-circle waves-light waves-effect" style="display: none;" ##{serviceClear}> <span class="fbtn-text fbtn-text-left">Clear service results <span class="icon icon-lg">visibility_off <a class="fbtn fbtn-green waves-attach waves-circle waves-effect" style="display: none;" ##{serviceRun}> <span class="fbtn-text fbtn-text-left">Run evaluation service <span class="icon icon-lg">play_arrow |] return (uiButtonsG, popupSubmit)
mb21/qua-kit
apps/hs/qua-server/src/Handler/Home/UIButtons.hs
mit
17,003
0
12
5,809
246
130
116
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeApplications #-} module Data.HeapSpec (spec) where import Test.Hspec import Data.Foldable (toList) import Data.Heap import Data.MyPrelude import Data.Nat.Binary (Bin) import Data.Nat.Peano (Peano) import Data.Utils.Random (shuffleR) spec :: Spec spec = do peanoSpec binSpec peanoSpec :: Spec peanoSpec = describe "Peano" $ do it "should sort a short list" $ do let xs = [(2, 'a'), (5, 'e'), (1, 'H'), (4, 'k'), (7, 'l'), (6, 'l'), (3, 's')] toList (toHeap @Peano xs) `shouldBe` "Haskell" it "should sort a 2000-element list" $ do let n = 2000 xs = [(x, x) | x <- shuffle n] toList (toHeap @Peano xs) `shouldBe` [1 .. n] binSpec :: Spec binSpec = describe "Bin" $ do it "should sort a short list" $ do let xs = [(2, 'a'), (5, 'e'), (1, 'H'), (4, 'k'), (7, 'l'), (6, 'l'), (3, 's')] toList (toHeap @Bin xs) `shouldBe` "Haskell" it "should sort a 2000-element list" $ do let n = 2000 xs = [(x, x) | x <- shuffle n] toList (toHeap @Bin xs) `shouldBe` [1 .. n] it "should sort a 10000-element list" $ do let n = 10000 xs = [(x, x) | x <- shuffle n] toList (toHeap @Bin xs) `shouldBe` [1 .. n] it "should sort a 50000-element list" $ do let n = 50000 xs = [(x, x) | x <- shuffle n] toList (toHeap @Bin xs) `shouldBe` [1 .. n] shuffle :: Natural -> [Natural] shuffle n = evalRand (shuffleR [1 .. n]) $ mkStdGen 1234567
brunjlar/heap
test/Data/HeapSpec.hs
mit
1,563
0
17
457
659
363
296
42
1
module Main where import Types import System.Random import Control.Monad.State choose :: [(Float, Move)] -> Move -> State StdGen Move choose xs d = (choose' xs d) `fmap` (state (randomR (0.0,1.0))) where choose' :: [(Float, a)] -> a -> Float -> a choose' [] d p = d choose' ((pa,a):ps) d p | p < pa = a | otherwise = choose' ps d (p - pa) f ((_,Betray):(Betray,_):(_,Cooperate):rs) = return Cooperate f ((_,Betray):rs) = return Betray f ((_,Cooperate):rs) = choose [(0.95, Cooperate)] Betray f _ = return Cooperate strat = S ("remorsefulprober 0.05", f) --main = testStrat strat [(Cooperate, Cooperate)] main = dilemmaMain strat
barkmadley/etd-retreat-2014-hteam
src/RemosefulProber/Main.hs
mit
693
0
10
168
324
178
146
18
2
{- This is my xmonad configuration file. There are many like it, but this one is mine. If you want to customize this file, the easiest workflow goes something like this: 1. Make a small change. 2. Hit "super-q", which recompiles and restarts xmonad 3. If there is an error, undo your change and hit "super-q" again to get to a stable place again. 4. Repeat Author: David Brewer Repository: https://github.com/davidbrewer/xmonad-ubuntu-conf -} import XMonad import XMonad.Config.Azerty import XMonad.Hooks.SetWMName import XMonad.Layout.Grid import XMonad.Layout.ResizableTile import XMonad.Layout.IM import XMonad.Layout.ThreeColumns import XMonad.Layout.NoBorders import XMonad.Layout.PerWorkspace (onWorkspace) import XMonad.Layout.Fullscreen import XMonad.Layout.Reflect import XMonad.Layout.MouseResizableTile import XMonad.Layout.Maximize import XMonad.Layout.Tabbed import XMonad.Util.EZConfig import XMonad.Util.Run import XMonad.Hooks.DynamicLog import XMonad.Actions.Plane import XMonad.Hooks.ManageDocks import XMonad.Hooks.UrgencyHook import qualified XMonad.StackSet as W import qualified Data.Map as M import Data.Ratio ((%)) {- Xmonad configuration variables. These settings control some of the simpler parts of xmonad's behavior and are straightforward to tweak. -} myModMask = mod4Mask -- changes the mod key to "super" myFocusedBorderColor = "#ff0000" -- color of focused border myNormalBorderColor = "#000000" -- color of inactive border myBorderWidth = 2 -- width of border around windows myTerminal = "gnome-terminal" -- which terminal software to use myIMRosterTitle = "Liste de contacts" -- title of roster on IM workspace -- use "Buddy List" for Pidgin, but -- "Contact List" for Empathy {- Xmobar configuration variables. These settings control the appearance of text which xmonad is sending to xmobar via the DynamicLog hook. -} myTitleColor = "#eeeeee" -- color of window title myTitleLength = 80 -- truncate window title to this length myCurrentWSColor = "#e6744c" -- color of active workspace myVisibleWSColor = "#c185a7" -- color of inactive workspace myUrgentWSColor = "#cc0000" -- color of workspace with 'urgent' window myCurrentWSLeft = "[" -- wrap active workspace with these myCurrentWSRight = "]" myVisibleWSLeft = "(" -- wrap inactive workspace with these myVisibleWSRight = ")" myUrgentWSLeft = "{" -- wrap urgent workspace with these myUrgentWSRight = "}" {- Workspace configuration. Here you can change the names of your workspaces. Note that they are organized in a grid corresponding to the layout of the number pad. I would recommend sticking with relatively brief workspace names because they are displayed in the xmobar status bar, where space can get tight. Also, the workspace labels are referred to elsewhere in the configuration file, so when you change a label you will have to find places which refer to it and make a change there as well. This central organizational concept of this configuration is that the workspaces correspond to keys on the number pad, and that they are organized in a grid which also matches the layout of the number pad. So, I don't recommend changing the number of workspaces unless you are prepared to delve into the workspace navigation keybindings section as well. -} myWorkspaces = [ "7:Chat", "8:Dbg", "9:Pix", "4:Docs", "5:Dev", "6:Web", "1:Term", "2:Hub", "3:Mail", "0:VM", "Extr1", "Extr2" ] startupWorkspace = "5:Dev" -- which workspace do you want to be on after launch? {- Layout configuration. In this section we identify which xmonad layouts we want to use. I have defined a list of default layouts which are applied on every workspace, as well as special layouts which get applied to specific workspaces. Note that all layouts are wrapped within "avoidStruts". What this does is make the layouts avoid the status bar area at the top of the screen. Without this, they would overlap the bar. You can toggle this behavior by hitting "super-b" (bound to ToggleStruts in the keyboard bindings in the next section). -} -- Define group of default layouts used on most screens, in the -- order they will appear. -- "smartBorders" modifier makes it so the borders on windows only -- appear if there is more than one visible window. -- "avoidStruts" modifier makes it so that the layout provides -- space for the status bar at the top of the screen. defaultLayouts = smartBorders(avoidStruts( -- ResizableTall layout has a large master window on the left, -- and remaining windows tile on the right. By default each area -- takes up half the screen, but you can resize using "super-h" and -- "super-l". maximize (mouseResizableTile) -- Mirrored variation of ResizableTall. In this layout, the large -- master window is at the top, and remaining windows tile at the -- bottom of the screen. Can be resized as described above. ||| maximize (Mirror (mouseResizableTile)) -- Full layout makes every window full screen. When you toggle the -- active window, it will bring the active window to the front. -- ||| noBorders Full -- ThreeColMid layout puts the large master window in the center -- of the screen. As configured below, by default it takes of 3/4 of -- the available space. Remaining windows tile to both the left and -- right of the master window. You can resize using "super-h" and -- "super-l". -- ||| ThreeColMid 1 (3/100) (3/4) -- Circle layout places the master window in the center of the screen. -- Remaining windows appear in a circle around it -- ||| Circle -- Grid layout tries to equally distribute windows in the available -- space, increasing the number of columns and rows as necessary. -- Master window is at top left. -- ||| Grid ||| noBorders simpleTabbed )) -- Here we define some layouts which will be assigned to specific -- workspaces based on the functionality of that workspace. -- The chat layout uses the "IM" layout. We have a roster which takes -- up 1/8 of the screen vertically, and the remaining space contains -- chat windows which are tiled using the grid layout. The roster is -- identified using the myIMRosterTitle variable, and by default is -- configured for Pidgin, so if you're using something else you -- will want to modify that variable. chatLayout = reflectHoriz $ avoidStruts(withIM (1%6) (Title myIMRosterTitle) Grid) -- The GIMP layout uses the ThreeColMid layout. The traditional GIMP -- floating panels approach is a bit of a challenge to handle with xmonad; -- I find the best solution is to make the image you are working on the -- master area, and then use this ThreeColMid layout to make the panels -- tile to the left and right of the image. If you use GIMP 2.8, you -- can use single-window mode and avoid this issue. gimpLayout = smartBorders(avoidStruts(ThreeColMid 1 (3/100) (3/4))) -- Here we combine our default layouts with our specific, workspace-locked -- layouts. myLayouts = onWorkspace "7:Chat" chatLayout $ onWorkspace "9:Pix" gimpLayout $ defaultLayouts {- Custom keybindings. In this section we define a list of relatively straightforward keybindings. This would be the clearest place to add your own keybindings, or change the keys we have defined for certain functions. It can be difficult to find a good list of keycodes for use in xmonad. I have found this page useful -- just look for entries beginning with "xK": http://xmonad.org/xmonad-docs/xmonad/doc-index-X.html Note that in the example below, the last three entries refer to nonstandard keys which do not have names assigned by xmonad. That's because they are the volume and mute keys on my laptop, a Lenovo W520. If you have special keys on your keyboard which you want to bind to specific actions, you can use the "xev" command-line tool to determine the code for a specific key. Launch the command, then type the key in question and watch the output. -} myKeyBindings = [ ((myModMask, xK_b), sendMessage ToggleStruts) , ((myModMask, xK_a), sendMessage MirrorShrink) , ((myModMask, xK_z), sendMessage MirrorExpand) , ((myModMask, xK_p), spawn "synapse") , ((myModMask, xK_u), focusUrgent) , ((myModMask, xK_m), withFocused (sendMessage . maximizeRestore)) , ((0, 0x1008FF12), spawn "amixer -q set Master toggle") , ((0, 0x1008FF11), spawn "amixer -q set Master 10%-") , ((0, 0x1008FF13), spawn "amixer -q set Master 10%+") ] {- Management hooks. You can use management hooks to enforce certain behaviors when specific programs or windows are launched. This is useful if you want certain windows to not be managed by xmonad, or sent to a specific workspace, or otherwise handled in a special way. Each entry within the list of hooks defines a way to identify a window (before the arrow), and then how that window should be treated (after the arrow). To figure out to identify your window, you will need to use a command-line tool called "xprop". When you run xprop, your cursor will temporarily change to crosshairs; click on the window you want to identify. In the output that is printed in your terminal, look for a couple of things: - WM_CLASS(STRING): values in this list of strings can be compared to "className" to match windows. - WM_NAME(STRING): this value can be compared to "resource" to match windows. The className values tend to be generic, and might match any window or dialog owned by a particular program. The resource values tend to be more specific, and will be different for every dialog. Sometimes you might want to compare both className and resource, to make sure you are matching only a particular window which belongs to a specific program. Once you've pinpointed the window you want to manipulate, here are a few examples of things you might do with that window: - doIgnore: this tells xmonad to completely ignore the window. It will not be tiled or floated. Useful for things like launchers and trays. - doFloat: this tells xmonad to float the window rather than tiling it. Handy for things that pop up, take some input, and then go away, such as dialogs, calculators, and so on. - doF (W.shift "Workspace"): this tells xmonad that when this program is launched it should be sent to a specific workspace. Useful for keeping specific tasks on specific workspaces. In the example below I have specific workspaces for chat, development, and editing images. -} myManagementHooks :: [ManageHook] myManagementHooks = [ resource =? "synapse" --> doIgnore , resource =? "stalonetray" --> doIgnore , className =? "rdesktop" --> doFloat , (className =? "Pidgin") --> doF (W.shift "7:Chat") , (className =? "Gimp-2.8") --> doF (W.shift "9:Pix") ] {- Workspace navigation keybindings. This is probably the part of the configuration I have spent the most time messing with, but understand the least. Be very careful if messing with this section. -} -- We define two lists of keycodes for use in the rest of the -- keyboard configuration. The first is the list of numpad keys, -- in the order they occur on the keyboard (left to right and -- top to bottom). The second is the list of number keys, in an -- order corresponding to the numpad. We will use these to -- make workspace navigation commands work the same whether you -- use the numpad or the top-row number keys. And, we also -- use them to figure out where to go when the user -- uses the arrow keys. numPadKeys = [ xK_KP_Home, xK_KP_Up, xK_KP_Page_Up , xK_KP_Left, xK_KP_Begin,xK_KP_Right , xK_KP_End, xK_KP_Down, xK_KP_Page_Down , xK_KP_Insert, xK_KP_Delete, xK_KP_Enter ] numKeys = [ xK_7, xK_8, xK_9 , xK_4, xK_5, xK_6 , xK_1, xK_2, xK_3 , xK_0, xK_minus, xK_equal ] -- Here, some magic occurs that I once grokked but has since -- fallen out of my head. Essentially what is happening is -- that we are telling xmonad how to navigate workspaces, -- how to send windows to different workspaces, -- and what keys to use to change which monitor is focused. myKeys = myKeyBindings ++ [ ((m .|. myModMask, k), windows $ f i) | (i, k) <- zip myWorkspaces numPadKeys , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)] ] ++ [ ((m .|. myModMask, k), windows $ f i) | (i, k) <- zip myWorkspaces numKeys , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)] ] ++ M.toList (planeKeys myModMask (Lines 4) Finite) ++ [ ((m .|. myModMask, key), screenWorkspace sc >>= flip whenJust (windows . f)) | (key, sc) <- zip [xK_w, xK_e, xK_r] [1,0,2] , (f, m) <- [(W.view, 0), (W.shift, shiftMask)] ] {- Here we actually stitch together all the configuration settings and run xmonad. We also spawn an instance of xmobar and pipe content into it via the logHook.. -} main = do xmproc <- spawnPipe "xmobar ~/.xmonad/xmobarrc" xmonad $ withUrgencyHook NoUrgencyHook $ azertyConfig { focusedBorderColor = myFocusedBorderColor , normalBorderColor = myNormalBorderColor , terminal = myTerminal , borderWidth = myBorderWidth , layoutHook = myLayouts , workspaces = myWorkspaces , modMask = myModMask , handleEventHook = fullscreenEventHook , startupHook = do setWMName "LG3D" windows $ W.greedyView startupWorkspace spawn "~/.xmonad/startup-hook" , manageHook = manageHook defaultConfig <+> composeAll myManagementHooks <+> manageDocks , logHook = dynamicLogWithPP $ xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor myTitleColor "" . shorten myTitleLength , ppCurrent = xmobarColor myCurrentWSColor "" . wrap myCurrentWSLeft myCurrentWSRight , ppVisible = xmobarColor myVisibleWSColor "" . wrap myVisibleWSLeft myVisibleWSRight , ppUrgent = xmobarColor myUrgentWSColor "" . wrap myUrgentWSLeft myUrgentWSRight } } `additionalKeys` myKeys
Adirelle/xmonad-ubuntu-conf
xmonad.hs
mit
14,290
8
15
3,003
1,411
854
557
132
1
module Main (main) where import qualified Data.Map as M import Control.Monad import Control.Monad.IO.Class import Data.IORef import Data.List (unzip4) import Data.StateVar as SV import System.Exit import Graphics.UI.GLFW import Graphics.Rendering.OpenGL.GL.CoordTrans import Graphics.Rendering.OpenGL as GL import qualified Physics.Hipmunk as H type Time = Double ------------------------------------------------------------ -- Some constants and utils ------------------------------------------------------------ -- | Desired (and maximum) frames per second. desiredFPS :: Int desiredFPS = 60 -- | How much seconds a frame lasts. framePeriod :: Time framePeriod = 1 / toEnum desiredFPS -- | How many steps should be done per frame. frameSteps :: Double frameSteps = 6 -- | Maximum number of steps per frame (e.g. if lots of frames get -- dropped because the window was minimized) maxSteps :: Int maxSteps = 20 -- | How much time should pass in each step. frameDelta :: H.Time frameDelta = 3.33e-3 -- | How much slower should the slow mode be. slowdown :: Double slowdown = 10 -- | 0 :: GLfloat zero :: GLfloat zero = 0 -- | Asserts that an @IO@ action returns @True@, otherwise -- fails with the given message. assertTrue :: IO Bool -> String -> IO () assertTrue act msg = do {b <- act; when (not b) (fail msg)} -- | Constructs a Vector. (+:) :: H.CpFloat -> H.CpFloat -> H.Vector (+:) = H.Vector infix 4 +: ------------------------------------------------------------ -- State ------------------------------------------------------------ -- | Our current program state that will be passed around. data State = State { stSpace :: H.Space, stCarState :: CarState, stControls :: CarControls, stShapes :: M.Map H.Shape (IO () {- Drawing -} ,IO () {- Removal -}), stCollisionsVar :: IORef [H.Position] } data CarState = Stopped | GoingLeft | GoingRight deriving (Eq, Ord, Enum) type Object = (H.Shape, (IO (), IO ())) type CarControls = (CarState -> IO ()) -- | Our initial state. initialState :: IO State initialState = do -- The (empty) space space <- H.newSpace H.gravity space SV.$= 0 +: -230 -- Default objects seesaw <- buildSeesaw space ground <- buildGround space (car,c) <- buildCar space -- Add a callback to Hipmunk to draw collisions collisionsVar <- newIORef [] let handler = do ps <- H.points liftIO $ modifyIORef collisionsVar (ps ++) H.setDefaultCollisionHandler space $ H.Handler {H.beginHandler = Nothing ,H.preSolveHandler = Nothing ,H.postSolveHandler = Just handler ,H.separateHandler = Nothing} -- Our state return $ State {stSpace = space ,stCarState = Stopped ,stControls = c ,stShapes = M.fromList [seesaw, ground, car] ,stCollisionsVar = collisionsVar} -- | Builds the ground buildGround :: H.Space -> IO Object buildGround space = do static <- H.newBody H.infinity H.infinity H.position static SV.$= -330 +: 0 let seg1type = H.LineSegment (50 +: -230) (610 +: -230) 1 seg1 <- H.newShape static seg1type 0 H.friction seg1 SV.$= 1.0 H.elasticity seg1 SV.$= 0.6 H.spaceAdd space (H.Static seg1) return (seg1, (drawMyShape seg1 seg1type, return ())) -- | Builds the seesaw. buildSeesaw :: H.Space -> IO Object buildSeesaw space = do ---- Support let supportV = [-15 +: -20, -5 +: 20, 5 +: 20, 15 +: -20] supportT = H.Polygon supportV supportM = 500 supportI = H.momentForPoly supportM supportV 0 supportB <- H.newBody supportM supportI H.position supportB SV.$= 0 +: 20-230 supportS <- H.newShape supportB supportT 0 H.friction supportS SV.$= 2.0 H.elasticity supportS SV.$= 0.1 H.spaceAdd space supportB H.spaceAdd space supportS ----- Board let boardV = [-100 +: 1, 100 +: 1, 100 +: -1, -100 +: -1] boardT = H.Polygon boardV boardM = 10 boardI = H.momentForPoly boardM boardV 0 boardB <- H.newBody boardM boardI H.position boardB SV.$= 0 +: 40-230 boardS <- H.newShape boardB boardT 0 let setBoardProps shape = do H.friction shape SV.$= 2.0 H.elasticity shape SV.$= 0.1 setBoardProps boardS H.spaceAdd space boardB H.spaceAdd space boardS boardS2 <- forM (zip boardV $ tail $ cycle boardV) $ \(v1,v2) -> do seg <- H.newShape boardB (H.LineSegment v1 v2 0.1) 0 setBoardProps seg H.spaceAdd space seg return seg ----- Constraint seesawJoint <- H.newConstraint supportB boardB (H.Pin (0 +: 20) 0) H.spaceAdd space seesawJoint ----- Avoiding self-collisions forM_ (supportS : boardS : boardS2) $ \s -> do H.group s SV.$= 1 ----- Removing and drawing let drawSeeSaw = do drawMyShape supportS supportT drawMyShape boardS boardT let removeSeeSaw = do H.spaceRemove space supportB H.spaceRemove space supportS H.spaceRemove space boardB H.spaceRemove space boardS forM_ boardS2 (H.spaceRemove space) H.spaceRemove space seesawJoint return (supportS, (drawSeeSaw, removeSeeSaw)) -- | Build a small car. buildCar :: H.Space -> IO (Object, CarControls) buildCar space = do ---- Bodywork let bodyworkV = [-25 +: -9, -17 +: 10, 17 +: 10, 25 +: -9] bodyworkT = H.Polygon bodyworkV bodyworkP = (-150 +: -90) bodyworkM = 40 bodyworkI = H.momentForPoly bodyworkM bodyworkV 0 bodyworkB <- H.newBody bodyworkM bodyworkI H.position bodyworkB SV.$= bodyworkP bodyworkS <- H.newShape bodyworkB bodyworkT 0 H.friction bodyworkS SV.$= 1.5 H.elasticity bodyworkS SV.$= 0.1 H.spaceAdd space bodyworkB H.spaceAdd space bodyworkS ---- Wheels let wheelR = 12 -- radius wheelM = 200 -- mass wheelT = H.Circle wheelR wheelI = H.momentForCircle wheelM (0, wheelR) 0 wheelJ1 x = H.DampedSpring (x +: 0) (0 +: 0) 23 0 10 -- spring wheelJ2 x = H.Groove (x +: -23.5, x +: -27) (0 +: 0) -- groove (wheelBs, wheelSs, wheelCs, wheelMs) <- fmap unzip4 $ forM [-25, 25] $ \x -> do -- Basic wheelB <- H.newBody wheelM wheelI H.position wheelB SV.$= (x +: -24) + bodyworkP wheelS <- H.newShape wheelB wheelT 0 H.friction wheelS SV.$= 2.0 H.elasticity wheelS SV.$= 0.25 -- Constraints wheelC1 <- H.newConstraint bodyworkB wheelB (wheelJ1 x) wheelC2 <- H.newConstraint bodyworkB wheelB (wheelJ2 x) H.spaceAdd space wheelB H.spaceAdd space wheelS H.spaceAdd space wheelC1 H.spaceAdd space wheelC2 -- Motor motor <- H.newConstraint bodyworkB wheelB (H.SimpleMotor 0) H.spaceAdd space motor let motorControls = map turn [0, -1, 1] turn = H.redefineC motor . H.SimpleMotor . (*4) -- Return let constrs = [H.forgetC wheelC1, H.forgetC wheelC2, H.forgetC motor] return (wheelB, wheelS, constrs, motorControls) ---- Removing and drawing let drawCar = do drawMyShape bodyworkS bodyworkT mapM_ (flip drawMyShape wheelT) wheelSs let removeCar = do mapM_ (H.spaceRemove space) (bodyworkB : wheelBs) mapM_ (H.spaceRemove space) (bodyworkS : wheelSs) mapM_ (H.spaceRemove space) (concat wheelCs) ---- Motor controls let control w = mapM_ (!!n) wheelMs where n = fromEnum w return ((bodyworkS, (drawCar, removeCar)), control) -- | Destroy a state. destroyState :: State -> IO () destroyState (State {stSpace = space}) = do H.freeSpace space ------------------------------------------------------------ -- Main function and main loop ------------------------------------------------------------ -- | Entry point. main :: IO () main = do -- Initialize Chipmunk, GLFW and our state H.initChipmunk assertTrue initialize "Failed to init GLFW" stateVar <- initialState >>= newIORef -- Create a window assertTrue (openWindow (GL.Size 1200 900) [] Window) "Failed to open a window" windowTitle GL.$= "Hipmunk Playground" -- Define some GL parameters for the whole program clearColor GL.$= Color4 1 1 1 1 pointSmooth GL.$= Enabled pointSize GL.$= 3 lineSmooth GL.$= Enabled lineWidth GL.$= 2.5 blend GL.$= Enabled blendFunc GL.$= (SrcAlpha, OneMinusSrcAlpha) matrixMode GL.$= Projection loadIdentity ortho (-320) 320 (-240) 240 (-1) 1 translate (Vector3 0.5 0.5 zero) -- Add some callbacks to GLFW windowCloseCallback GL.$= exitWith ExitSuccess windowSizeCallback GL.$= (\size -> viewport GL.$= (Position 0 0, size)) mouseButtonCallback GL.$= processMouseInput stateVar -- Let's go! now <- GL.get time loop stateVar now -- | The simulation loop. loop :: IORef State -> Time -> IO () loop stateVar oldTime = do -- Some key states slowKey <- getKey (SpecialKey ENTER) quitKey <- getKey (SpecialKey ESC) clearKey <- getKey (SpecialKey DEL) leftKey <- getKey (SpecialKey LEFT) rightKey <- getKey (SpecialKey RIGHT) -- Quit? when (quitKey == Press) (terminate >> exitWith ExitSuccess) -- Clear? when (clearKey == Press) $ do destroyState =<< readIORef stateVar H.resetShapeCounter initialState >>= writeIORef stateVar -- Update display and time updateCar stateVar leftKey rightKey updateDisplay stateVar slowKey newTime <- advanceTime stateVar oldTime slowKey loop stateVar newTime -- | Updates the car state updateCar :: IORef State -> KeyButtonState -> KeyButtonState -> IO () updateCar stateVar leftKey rightKey = do let wantsToBe = case (leftKey, rightKey) of (Press, _) -> GoingLeft (_, Press) -> GoingRight _ -> Stopped state <- readIORef stateVar when (stCarState state /= wantsToBe) $ do stControls state wantsToBe writeIORef stateVar (state {stCarState = wantsToBe}) -- | Advances the time. advanceTime :: IORef State -> Time -> KeyButtonState -> IO Time advanceTime stateVar oldTime slowKey = do newTime <- GL.get time -- Advance simulation let slower = if slowKey == Press then slowdown else 1 mult = frameSteps / (framePeriod * slower) framesPassed = truncate $ mult * (newTime - oldTime) simulNewTime = oldTime + toEnum framesPassed / mult advanceSimulTime stateVar $ min maxSteps framesPassed -- Correlate with reality newTime' <- GL.get time let diff = newTime' - simulNewTime sleepTime = ((framePeriod * slower) - diff) / slower when (sleepTime > 0) $ sleep sleepTime return simulNewTime ------------------------------------------------------------ -- Display related functions ------------------------------------------------------------ -- | Renders the current state. updateDisplay :: IORef State -> KeyButtonState -> IO () updateDisplay stateVar slowKey = do state <- SV.get stateVar clear [ColorBuffer] drawInstructions when (slowKey == Press) drawSlowMotion forM_ (M.assocs $ stShapes state) (fst . snd) -- Draw each one readIORef (stCollisionsVar state) >>= mapM_ (drawPoint CollisionPoint) swapBuffers drawInstructions :: IO () drawInstructions = preservingMatrix $ do translate (Vector3 (-320) 240 zero) scale 0.75 0.75 (1 `asTypeOf` zero) let render str = do translate (Vector3 zero (-16) zero) renderString Fixed8x16 str color $ Color3 zero zero 1 render "Press the left mouse button to create a ball." render "Press the right mouse button to create a square." render "Press the middle mouse button to create a triangle on a pendulum." color $ Color3 1 zero zero render "Hold LEFT SHIFT to create counterclockwise rotating objects." render "Hold RIGHT SHIFT to create clockwise rotating objects." render "Hold LEFT or RIGHT to move the car." render "Hold ENTER to see in slow motion." color $ Color3 zero zero zero render "Press DEL to clear the screen." drawSlowMotion :: IO () drawSlowMotion = preservingMatrix $ do scale 2 2 (1 `asTypeOf` zero) translate (Vector3 (-40) zero zero) color $ Color3 zero 1 zero renderString Fixed8x16 "Slowwww..." -- | Draws a shape (assuming zero offset) drawMyShape :: H.Shape -> H.ShapeType -> IO () drawMyShape shape (H.Circle radius) = do H.Vector px py <- SV.get $ H.position $ H.body shape angle <- SV.get $ H.angle $ H.body shape color $ Color3 zero zero zero renderPrimitive LineStrip $ do let segs = 20; coef = 2*pi/toEnum segs forM_ [0..segs] $ \i -> do let r = toEnum i * coef x = radius * cos (r + angle) + px y = radius * sin (r + angle) + py vertex' x y vertex' px py drawPoint PositionPoint (px +: py) drawMyShape shape (H.LineSegment p1 p2 _) = do let v (H.Vector x y) = vertex' x y pos <- SV.get $ H.position $ H.body shape color $ Color3 zero zero zero renderPrimitive Lines $ v (p1 + pos) >> v (p2 + pos) drawPoint PositionPoint pos drawMyShape shape (H.Polygon verts) = do pos <- SV.get $ H.position $ H.body shape angle <- SV.get $ H.angle $ H.body shape let rot = H.rotate $ H.fromAngle angle verts' = map ((+pos) . rot) verts color $ Color3 zero zero zero renderPrimitive LineStrip $ do forM_ (verts' ++ [head verts']) $ \(H.Vector x y) -> do vertex' x y drawPoint PositionPoint pos -- | Draws a red point. drawPoint :: PointType -> H.Vector -> IO () drawPoint pt (H.Vector px py) = do color $ case pt of PositionPoint -> Color3 zero zero 1 CollisionPoint -> Color3 1 zero zero renderPrimitive Points $ do vertex' px py data PointType = PositionPoint | CollisionPoint deriving (Eq, Ord, Show, Enum) ------------------------------------------------------------ -- Input processing ------------------------------------------------------------ -- | Returns the current mouse position in our space's coordinates. getMousePos :: IO H.Position getMousePos = do Position cx cy <- GL.get mousePos Size _ h <- GL.get $ windowSize model <- GL.get $ matrix (Just $ Modelview 0) proj <- GL.get $ matrix (Just Projection) view <- GL.get $ viewport let src = Vertex3 (fromIntegral cx) (fromIntegral h - fromIntegral cy) 0 Vertex3 mx my _ <- unProject src (model :: GLmatrix GLdouble) proj view return (realToFrac mx +: realToFrac my) -- | Process a user mouse button press. processMouseInput :: IORef State -> MouseButton -> KeyButtonState -> IO () processMouseInput _ _ Press = return () processMouseInput stateVar btn Release = do rotateKeyCCW <- getKey (SpecialKey LSHIFT) rotateKeyCW <- getKey (SpecialKey RSHIFT) let angVel = case (rotateKeyCCW, rotateKeyCW) of (Press, Release) -> 50 (Release, Press) -> (-50) _ -> 0 (shape,add,draw,remove) <- (case btn of ButtonLeft -> createCircle ButtonRight -> createSquare _ -> createTriPendulum) angVel state <- SV.get stateVar let space = stSpace state add space >> stateVar SV.$= state { stShapes = M.insert shape (draw, remove space) $ stShapes state} ------------------------------------------------------------ -- Object creation ------------------------------------------------------------ -- | The return of functions that create objects. type Creation = (H.Shape, -- ^ A representative shape H.Space -> IO (), -- ^ Function that add the entities IO (), -- ^ Function that draws the entity H.Space -> IO () -- ^ Function that removes the entities ) -- | The type of the functions that create objects. type Creator = H.CpFloat -> IO Creation createCircle :: Creator createCircle angVel = do let mass = 20 radius = 20 t = H.Circle radius b <- H.newBody mass $ H.momentForCircle mass (0, radius) 0 s <- H.newShape b t 0 (H.position b SV.$=) =<< getMousePos H.angVel b SV.$= angVel H.friction s SV.$= 0.5 H.elasticity s SV.$= 0.9 let add space = do H.spaceAdd space b H.spaceAdd space s let draw = do drawMyShape s t let remove space = do H.spaceRemove space b H.spaceRemove space s return (s,add,draw,remove) createSquare :: Creator createSquare angVel = do let mass = 18 verts = [-15 +: -15, -15 +: 15, 15 +: 15, 15 +: -15] t = H.Polygon verts b <- H.newBody mass $ H.momentForPoly mass verts 0 s <- H.newShape b t 0 (H.position b SV.$=) =<< getMousePos H.angVel b SV.$= angVel H.friction s SV.$= 0.5 H.elasticity s SV.$= 0.6 let add space = do H.spaceAdd space b H.spaceAdd space s let draw = do drawMyShape s t let remove space = do H.spaceRemove space b H.spaceRemove space s return (s,add,draw,remove) createTriPendulum :: Creator createTriPendulum angVel = do let mass = 100 verts = [-30 +: -30, 0 +: 37, 30 +: -30] t = H.Polygon verts b <- H.newBody mass $ H.momentForPoly mass verts 0 s <- H.newShape b t 0 (H.position b SV.$=) =<< getMousePos H.angVel b SV.$= angVel H.friction s SV.$= 0.8 H.elasticity s SV.$= 0.3 let staticPos = 0 +: 240 static <- H.newBody H.infinity H.infinity H.position static SV.$= staticPos j <- H.newConstraint static b (H.Pin 0 0) let add space = do H.spaceAdd space b H.spaceAdd space s H.spaceAdd space j let remove space = do H.spaceRemove space b H.spaceRemove space s H.spaceRemove space j let draw = do H.Vector x1 y1 <- SV.get $ H.position b let H.Vector x2 y2 = staticPos color $ Color3 (0.7 `asTypeOf` zero) 0.7 0.7 renderPrimitive LineStrip $ do let vertex' x1 y1 vertex' x2 y2 drawMyShape s t return (s,add,draw,remove) vertex' :: Double -> Double -> IO () vertex' x y = let f p = realToFrac p :: GLdouble in vertex (Vertex2 (f x) (f y)) ------------------------------------------------------------ -- Simulation bookkeeping ------------------------------------------------------------ -- | Advances the time in a certain number of steps. advanceSimulTime :: IORef State -> Int -> IO () advanceSimulTime _ 0 = return () advanceSimulTime stateVar steps = do removeOutOfSight stateVar state <- SV.get stateVar -- Do (steps-1) steps that clear the collisions variable. let clearCollisions = writeIORef (stCollisionsVar state) [] step = H.step (stSpace state) frameDelta replicateM_ (steps-1) $ step >> clearCollisions -- Do a final step that will leave the collisions variable filled. step -- | Removes all shapes that may be out of sight forever. removeOutOfSight :: IORef State -> IO () removeOutOfSight stateVar = do state <- SV.get stateVar shapes' <- foldM f (stShapes state) $ M.assocs (stShapes state) stateVar SV.$= state {stShapes = shapes'} where f shapes (shape, (_,remove)) = do H.Vector x y <- SV.get $ H.position $ H.body shape if y < (-350) || abs x > 800 then remove >> return (M.delete shape shapes) else return shapes
meteficha/HipmunkPlayground
Playground.hs
mit
19,177
0
21
4,625
6,318
3,075
3,243
-1
-1
-- Concatenate a list of lists. concat :: [[a]] -> [a] concat = foldr (++) []
iharh/fp-by-example
tex/src/concat_hof.hs
mit
77
0
7
15
34
20
14
2
1
module Messaging ( Job (..) , JobType (..) , createTopicExchange , createProductsQueue ) where import qualified Network.AMQP.Config as Config import qualified Network.AMQP.MessageBus as MB import Data.Aeson as Aeson import GHC.Generics (Generic) data Job a = Job { getJobType :: JobType , getPayload :: a } deriving (Show, Generic) instance ToJSON a => ToJSON (Job a) instance FromJSON a => FromJSON (Job a) data JobType = ProductCreated deriving (Show, Read, Eq, Generic) instance ToJSON JobType instance FromJSON JobType createTopicExchange :: Config.RabbitMQConfig -> MB.WithConn () createTopicExchange cfg = let exch = MB.Exchange (Config.getExchangeNameConfig cfg) "topic" True in MB.createExchange exch createProductsQueue :: MB.WithConn MB.QueueStatus createProductsQueue = let queue = MB.Queue "products" False True in MB.createQueue queue
gust/feature-creature
feature-creature/backend/src/Messaging.hs
mit
882
0
12
147
275
149
126
27
1
-- | Type and functions for first-order predicate logic. module Faun.Parser.FOL where import qualified Data.Text as T import Text.Parsec import Text.Parsec.String (Parser) import qualified Text.Parsec.Expr as Ex import Faun.Formula import Faun.FOL import Faun.Parser.LogicOps import Faun.Parser.Core import Faun.Parser.Numbers import Faun.Parser.Term as Term import Faun.Predicate import Faun.QuanT -- | Parser for weighted first-order logic. Parses a double following by -- a formula (or a formula followed by a double). -- -- The /smoking/ example for Markov logic: -- -- @ -- parseWFOL \"∀x∀y∀z Friend(x, y) ∧ Friend(y, z) ⇒ Friend(x, z) 0.7\" -- parseWFOL \"∀x Smoking(x) ⇒ Cancer(x) 1.5\" -- parseWFOL \"1.1 ∀x∀y Friend(x, y) ∧ Smoking(x) ⇒ Smoking(y)\" -- @ parseWFOL :: String -> Either ParseError (FOL, Double) parseWFOL = parse (contents parseWeighted) "<stdin>" -- | Parser for first-order logic. The parser will read a string and output -- an either type with (hopefully) the formula on the right. -- -- This parser makes the assumption that variables start with a lowercase -- character, while constants start with an uppercase character. -- -- Some examples of valid strings for the parser: -- -- @ -- parseFOL \"ForAll x, y PositiveInteger(y) => GreaterThan(Add(x, y), x)\" -- parseFOL \"A.x,y: Integer(x) and PositiveInteger(y) => GreaterThan(Add(x, y), x)\" -- parseFOL \"∀ x Add(x, 0) = x\" -- @ parseFOL :: String -> Either ParseError FOL parseFOL = parse (contents parseFOLAll) "<stdin>" parseFOLAll, parseSentence, parseTop, parseBot, parseAtoms, parsePred, parsePredLike, parseIdentity, parseNIdentity, parseQuan, parseNQuan, parseNegation :: Parser FOL parseFOLAll = try parseNQuan<|> try parseQuan <|> parseSentence parseSentence = Ex.buildExpressionParser logicTbl parseAtoms parseTop = reservedOps ["True", "TRUE", "true", "T", "⊤"] >> return top parseBot = reservedOps ["False", "FALSE", "false", "F", "⊥"] >> return bot parseNQuan = do nots <- many1 parseNot (q, vs, a) <- parseQuanForm return $ foldr (\_ acc -> Not acc) (foldr (Quantifier q) a vs) nots parseQuan = do (q, vs, a) <- parseQuanForm return $ foldr (Quantifier q) a vs parseNegation = do n <- parseNot a <- parseAtoms return $ n a parsePredLike = try parseIdentity <|> try parseNIdentity <|> parsePred parseAtoms = try parsePredLike <|> parseNegation <|> parseTop <|> parseBot <|> parens parseFOLAll parsePred = do args <- Term.parseFunForm return $ Atom $ uncurry Predicate args parseIdentity = do left <- Term.parseTerm reservedOps ["=", "=="] right <- Term.parseTerm return $ Atom $ Predicate "Identity" [left, right] parseNIdentity = do left <- Term.parseTerm reservedOps ["!=", "/=", "\\neq"] right <- Term.parseTerm return $ Not $ Atom $ Predicate "Identity" [left, right] parseNot :: Parser (FOL -> FOL) parseNot = reservedOps ["Not", "NOT", "not", "~", "!", "¬"] >> return Not parseExists, parseForAll :: Parser QuanT parseExists = reservedOps ["E.", "Exists", "exists", "∃"] >> return Exists parseForAll = reservedOps ["A.", "ForAll", "Forall", "forall", "∀"] >> return ForAll -- Parse a weight and then a first-order logic formula parseLeftW :: Parser (FOL, Double) parseLeftW = do n <- getDouble f <- parseFOLAll return (f, n) -- Parse a first-order logic formula and then a weight parseRightW :: Parser (FOL, Double) parseRightW = do f <- parseFOLAll n <- getDouble return (f, n) parseWeighted :: Parser (FOL, Double) parseWeighted = try parseLeftW <|> parseRightW parseQuanForm :: Parser (QuanT, [T.Text], FOL) parseQuanForm = do q <- parseExists <|> parseForAll -- many1 v <- commaSep identifier optional $ reservedOp ":" a <- parseFOLAll return (q, map T.pack v, a)
PhDP/Sphinx-AI
Faun/Parser/FOL.hs
mit
3,817
0
12
662
959
529
430
77
1
-- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. {-# LANGUAGE QuasiQuotes, OverloadedStrings, RecordWildCards #-} module Language.Bond.Codegen.Cpp.Reflection_h (reflection_h) where import System.FilePath import Data.Monoid import Prelude import Data.Text.Lazy (Text) import qualified Data.Foldable as F import Text.Shakespeare.Text import Language.Bond.Syntax.Types import Language.Bond.Codegen.TypeMapping import Language.Bond.Codegen.Util import qualified Language.Bond.Codegen.Cpp.Util as CPP -- | Codegen template for generating /base_name/_reflection.h containing schema -- metadata definitions. reflection_h :: MappingContext -> String -> [Import] -> [Declaration] -> (String, Text) reflection_h cpp file imports declarations = ("_reflection.h", [lt| #pragma once #include "#{file}_types.h" #include <bond/core/reflection.h> #{newlineSepEnd 0 include imports} #{CPP.openNamespace cpp} #{doubleLineSepEnd 1 schema declarations} #{CPP.closeNamespace cpp} |]) where idlNamespace = getIdlQualifiedName $ getIdlNamespace cpp -- C++ type cppType = getTypeName cpp -- template for generating #include statement from import include (Import path) = [lt|#include "#{dropExtension path}_reflection.h"|] -- template for generating struct schema schema s@Struct {..} = [lt|// // #{declName} // #{CPP.template s}struct #{structName}::Schema { typedef #{baseType structBase} base; static const bond::Metadata metadata; #{newlineBeginSep 2 fieldMetadata structFields} public: struct var {#{fieldTemplates structFields}}; private: typedef boost::mpl::list<> fields0; #{newlineSep 2 pushField indexedFields} public: typedef #{typename}fields#{length structFields}::type fields; #{constructor} static bond::Metadata GetMetadata() { return bond::reflection::MetadataInit#{metadataInitArgs}("#{declName}", "#{idlNamespace}.#{declName}", #{CPP.attributeInit declAttributes} ); } }; #{onlyTemplate $ CPP.schemaMetadata cpp s}|] where structParams = CPP.structParams s structName = CPP.structName s onlyTemplate x = if null declParams then mempty else x metadataInitArgs = onlyTemplate [lt|<boost::mpl::list#{structParams} >|] typename = onlyTemplate [lt|typename |] -- constructor, generated only for struct templates constructor = onlyTemplate [lt| Schema() { // Force instantiation of template statics (void)metadata; #{newlineSep 3 static structFields} }|] where static Field {..} = [lt|(void)s_#{fieldName}_metadata;|] -- reversed list of field names zipped with indexes indexedFields :: [(String, Int)] indexedFields = zipWith ((,) . fieldName) (reverse structFields) [0..] baseType (Just base) = cppType base baseType Nothing = "bond::no_base" pushField (field, i) = [lt|private: typedef #{typename}boost::mpl::push_front<fields#{i}, #{typename}var::#{field}>::type fields#{i + 1};|] fieldMetadata Field {..} = [lt|private: static const bond::Metadata s_#{fieldName}_metadata;|] fieldTemplates = F.foldMap $ \ f@Field {..} -> [lt| // #{fieldName} typedef bond::reflection::FieldTemplate< #{fieldOrdinal}, #{CPP.modifierTag f}, #{structName}, #{cppType fieldType}, &#{structName}::#{fieldName}, &s_#{fieldName}_metadata > #{fieldName}; |] -- nothing to generate for enums schema _ = mempty
upsoft/bond
compiler/src/Language/Bond/Codegen/Cpp/Reflection_h.hs
mit
3,895
0
13
968
453
279
174
35
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-viewercertificate.html module Stratosphere.ResourceProperties.CloudFrontDistributionViewerCertificate where import Stratosphere.ResourceImports -- | Full data type definition for CloudFrontDistributionViewerCertificate. -- See 'cloudFrontDistributionViewerCertificate' for a more convenient -- constructor. data CloudFrontDistributionViewerCertificate = CloudFrontDistributionViewerCertificate { _cloudFrontDistributionViewerCertificateAcmCertificateArn :: Maybe (Val Text) , _cloudFrontDistributionViewerCertificateCloudFrontDefaultCertificate :: Maybe (Val Bool) , _cloudFrontDistributionViewerCertificateIamCertificateId :: Maybe (Val Text) , _cloudFrontDistributionViewerCertificateMinimumProtocolVersion :: Maybe (Val Text) , _cloudFrontDistributionViewerCertificateSslSupportMethod :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON CloudFrontDistributionViewerCertificate where toJSON CloudFrontDistributionViewerCertificate{..} = object $ catMaybes [ fmap (("AcmCertificateArn",) . toJSON) _cloudFrontDistributionViewerCertificateAcmCertificateArn , fmap (("CloudFrontDefaultCertificate",) . toJSON) _cloudFrontDistributionViewerCertificateCloudFrontDefaultCertificate , fmap (("IamCertificateId",) . toJSON) _cloudFrontDistributionViewerCertificateIamCertificateId , fmap (("MinimumProtocolVersion",) . toJSON) _cloudFrontDistributionViewerCertificateMinimumProtocolVersion , fmap (("SslSupportMethod",) . toJSON) _cloudFrontDistributionViewerCertificateSslSupportMethod ] -- | Constructor for 'CloudFrontDistributionViewerCertificate' containing -- required fields as arguments. cloudFrontDistributionViewerCertificate :: CloudFrontDistributionViewerCertificate cloudFrontDistributionViewerCertificate = CloudFrontDistributionViewerCertificate { _cloudFrontDistributionViewerCertificateAcmCertificateArn = Nothing , _cloudFrontDistributionViewerCertificateCloudFrontDefaultCertificate = Nothing , _cloudFrontDistributionViewerCertificateIamCertificateId = Nothing , _cloudFrontDistributionViewerCertificateMinimumProtocolVersion = Nothing , _cloudFrontDistributionViewerCertificateSslSupportMethod = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-viewercertificate.html#cfn-cloudfront-distribution-viewercertificate-acmcertificatearn cfdvcAcmCertificateArn :: Lens' CloudFrontDistributionViewerCertificate (Maybe (Val Text)) cfdvcAcmCertificateArn = lens _cloudFrontDistributionViewerCertificateAcmCertificateArn (\s a -> s { _cloudFrontDistributionViewerCertificateAcmCertificateArn = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-viewercertificate.html#cfn-cloudfront-distribution-viewercertificate-cloudfrontdefaultcertificate cfdvcCloudFrontDefaultCertificate :: Lens' CloudFrontDistributionViewerCertificate (Maybe (Val Bool)) cfdvcCloudFrontDefaultCertificate = lens _cloudFrontDistributionViewerCertificateCloudFrontDefaultCertificate (\s a -> s { _cloudFrontDistributionViewerCertificateCloudFrontDefaultCertificate = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-viewercertificate.html#cfn-cloudfront-distribution-viewercertificate-iamcertificateid cfdvcIamCertificateId :: Lens' CloudFrontDistributionViewerCertificate (Maybe (Val Text)) cfdvcIamCertificateId = lens _cloudFrontDistributionViewerCertificateIamCertificateId (\s a -> s { _cloudFrontDistributionViewerCertificateIamCertificateId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-viewercertificate.html#cfn-cloudfront-distribution-viewercertificate-minimumprotocolversion cfdvcMinimumProtocolVersion :: Lens' CloudFrontDistributionViewerCertificate (Maybe (Val Text)) cfdvcMinimumProtocolVersion = lens _cloudFrontDistributionViewerCertificateMinimumProtocolVersion (\s a -> s { _cloudFrontDistributionViewerCertificateMinimumProtocolVersion = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-viewercertificate.html#cfn-cloudfront-distribution-viewercertificate-sslsupportmethod cfdvcSslSupportMethod :: Lens' CloudFrontDistributionViewerCertificate (Maybe (Val Text)) cfdvcSslSupportMethod = lens _cloudFrontDistributionViewerCertificateSslSupportMethod (\s a -> s { _cloudFrontDistributionViewerCertificateSslSupportMethod = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/CloudFrontDistributionViewerCertificate.hs
mit
4,757
0
12
350
538
305
233
42
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Buffer.Implementation -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- 'Buffer' implementation, wrapping Rope module Yi.Buffer.Implementation ( UIUpdate (..) , Update (..) , updateIsDelete , Point , Mark, MarkValue(..) , Size , Direction (..) , BufferImpl , Overlay, OvlLayer (..) , mkOverlay , overlayUpdate , applyUpdateI , isValidUpdate , reverseUpdateI , nelemsBI , sizeBI , newBI , solPoint , solPoint' , eolPoint' , charsFromSolBI , regexRegionBI , getMarkDefaultPosBI , modifyMarkBI , getMarkValueBI , getMarkBI , newMarkBI , deleteMarkValueBI , setSyntaxBI , addOverlayBI , delOverlayBI , delOverlayLayer , updateSyntax , getAst, focusAst , strokesRangesBI , getStream , getIndexedStream , lineAt , SearchExp , markPointAA , markGravityAA , mem ) where import Control.Applicative import Data.Array import Data.Binary #if __GLASGOW_HASKELL__ < 708 import Data.DeriveTH #else import GHC.Generics (Generic) #endif import Data.Function import Data.List (groupBy) import qualified Data.Map as M import Data.Maybe import Data.Monoid import Yi.Rope (YiString) import qualified Yi.Rope as R import qualified Data.Set as Set import Data.Typeable import Yi.Buffer.Basic import Yi.Regex import Yi.Region import Yi.Style import Yi.Syntax import Yi.Utils data MarkValue = MarkValue { markPoint :: !Point , markGravity :: !Direction} deriving (Ord, Eq, Show, Typeable) makeLensesWithSuffix "AA" ''MarkValue #if __GLASGOW_HASKELL__ < 708 $(derive makeBinary ''MarkValue) #else deriving instance Generic MarkValue instance Binary MarkValue #endif type Marks = M.Map Mark MarkValue data HLState syntax = forall cache. HLState !(Highlighter cache syntax) !cache data OvlLayer = UserLayer | HintLayer deriving (Ord, Eq) data Overlay = Overlay { overlayLayer :: OvlLayer, -- underscores to avoid 'defined but not used'. Remove if desired _overlayBegin :: MarkValue, _overlayEnd :: MarkValue, _overlayStyle :: StyleName } instance Eq Overlay where Overlay a b c _ == Overlay a' b' c' _ = a == a' && b == b' && c == c' instance Ord Overlay where compare (Overlay a b c _) (Overlay a' b' c' _) = compare a a' `mappend` compare b b' `mappend` compare c c' data BufferImpl syntax = FBufferData { mem :: !YiString -- ^ buffer text , marks :: !Marks -- ^ Marks for this buffer , markNames :: !(M.Map String Mark) , hlCache :: !(HLState syntax) -- ^ syntax highlighting state , overlays :: !(Set.Set Overlay) -- ^ set of (non overlapping) visual overlay regions , dirtyOffset :: !Point -- ^ Lowest modified offset since last recomputation of syntax } deriving Typeable dummyHlState :: HLState syntax dummyHlState = HLState noHighlighter (hlStartState noHighlighter) -- Atm we can't store overlays because stylenames are functions (can't be serialized) -- TODO: ideally I'd like to get rid of overlays entirely; although we could imagine them storing mere styles. instance Binary (BufferImpl ()) where put b = put (mem b) >> put (marks b) >> put (markNames b) get = FBufferData <$> get <*> get <*> get <*> pure dummyHlState <*> pure Set.empty <*> pure 0 -- | Mutation actions (also used the undo or redo list) -- -- For the undo/redo, we use the /partial checkpoint/ (Berlage, pg16) strategy to store -- just the components of the state that change. -- -- Note that the update direction is only a hint for moving the cursor -- (mainly for undo purposes); the insertions and deletions are always -- applied Forward. data Update = Insert {updatePoint :: !Point, updateDirection :: !Direction, insertUpdateString :: !YiString} | Delete {updatePoint :: !Point, updateDirection :: !Direction, deleteUpdateString :: !YiString} -- Note that keeping the text does not cost much: we keep the updates in the undo list; -- if it's a "Delete" it means we have just inserted the text in the buffer, so the update shares -- the data with the buffer. If it's an "Insert" we have to keep the data any way. deriving (Show, Typeable) #if __GLASGOW_HASKELL__ < 708 $(derive makeBinary ''Update) #else deriving instance Generic Update instance Binary Update #endif updateIsDelete :: Update -> Bool updateIsDelete Delete {} = True updateIsDelete Insert {} = False updateString :: Update -> YiString updateString (Insert _ _ s) = s updateString (Delete _ _ s) = s updateSize :: Update -> Size updateSize = Size . fromIntegral . R.length . updateString data UIUpdate = TextUpdate !Update | StyleUpdate !Point !Size #if __GLASGOW_HASKELL__ < 708 $(derive makeBinary ''UIUpdate) #else deriving instance Generic UIUpdate instance Binary UIUpdate #endif -------------------------------------------------- -- Low-level primitives. -- | New FBuffer filled from string. newBI :: YiString -> BufferImpl () newBI s = FBufferData s M.empty M.empty dummyHlState Set.empty 0 -- | Write string into buffer. insertChars :: YiString -> YiString -> Point -> YiString insertChars p cs (Point i) = left `R.append` cs `R.append` right where (left, right) = R.splitAt i p {-# INLINE insertChars #-} -- | Write string into buffer. deleteChars :: YiString -> Point -> Size -> YiString deleteChars p (Point i) (Size n) = left `R.append` right where (left, rest) = R.splitAt i p right = R.drop n rest {-# INLINE deleteChars #-} ------------------------------------------------------------------------ -- Mid-level insert/delete -- | Shift a mark position, supposing an update at a given point, by a given amount. -- Negative amount represent deletions. shiftMarkValue :: Point -> Size -> MarkValue -> MarkValue shiftMarkValue from by (MarkValue p gravity) = MarkValue shifted gravity where shifted | p < from = p | p == from = case gravity of Backward -> p Forward -> p' | otherwise {- p > from -} = p' where p' = max from (p +~ by) mapOvlMarks :: (MarkValue -> MarkValue) -> Overlay -> Overlay mapOvlMarks f (Overlay l s e v) = Overlay l (f s) (f e) v ------------------------------------- -- * "high-level" (exported) operations -- | Point of EOF sizeBI :: BufferImpl syntax -> Point sizeBI = Point . R.length . mem -- | Return @n@ Chars starting at @i@ of the buffer. nelemsBI :: Int -> Point -> BufferImpl syntax -> YiString nelemsBI n (Point i) = R.take n . R.drop i . mem getStream :: Direction -> Point -> BufferImpl syntax -> YiString getStream Forward (Point i) = R.drop i . mem getStream Backward (Point i) = R.reverse . R.take i . mem -- | TODO: This guy is a pretty big bottleneck and only one function -- uses it which in turn is only seldom used and most of the output is -- thrown away anyway. We could probably get away with never -- converting this to String here. The old implementation did so -- because it worked over ByteString but we don't have to. getIndexedStream :: Direction -> Point -> BufferImpl syntax -> [(Point,Char)] getIndexedStream Forward (Point p) = zip [Point p..] . R.toString . R.drop p . mem getIndexedStream Backward (Point p) = zip (dF (pred (Point p))) . R.toReverseString . R.take p . mem where dF n = n : dF (pred n) -- | Create an "overlay" for the style @sty@ between points @s@ and @e@ mkOverlay :: OvlLayer -> Region -> StyleName -> Overlay mkOverlay l r = Overlay l (MarkValue (regionStart r) Backward) (MarkValue (regionEnd r) Forward) -- | Obtain a style-update for a specific overlay overlayUpdate :: Overlay -> UIUpdate overlayUpdate (Overlay _l (MarkValue s _) (MarkValue e _) _) = StyleUpdate s (e ~- s) -- | Add a style "overlay" between the given points. addOverlayBI :: Overlay -> BufferImpl syntax -> BufferImpl syntax addOverlayBI ov fb = fb{overlays = Set.insert ov (overlays fb)} -- | Remove a previously added "overlay" delOverlayBI :: Overlay -> BufferImpl syntax -> BufferImpl syntax delOverlayBI ov fb = fb{overlays = Set.delete ov (overlays fb)} delOverlayLayer :: OvlLayer -> BufferImpl syntax -> BufferImpl syntax delOverlayLayer layer fb = fb{overlays = Set.filter ((/= layer) . overlayLayer) (overlays fb)} -- FIXME: this can be really inefficient. -- | Return style information for the range @(i,j)@ Style information -- is derived from syntax highlighting, active overlays and current regexp. The -- returned list contains tuples @(l,s,r)@ where every tuple is to -- be interpreted as apply the style @s@ from position @l@ to @r@ in -- the buffer. In each list, the strokes are guaranteed to be -- ordered and non-overlapping. The lists of strokes are ordered by -- decreasing priority: the 1st layer should be "painted" on top. strokesRangesBI :: (Point -> Point -> Point -> [Stroke]) -> Maybe SearchExp -> Region -> Point -> BufferImpl syntax -> [[Stroke]] strokesRangesBI getStrokes regex rgn point fb = result where i = regionStart rgn j = regionEnd rgn dropBefore = dropWhile (\s ->spanEnd s <= i) takeIn = takeWhile (\s -> spanBegin s <= j) groundLayer = [Span i mempty j] -- zero-length spans seem to break stroking in general, so filter them out! syntaxHlLayer = filter (\(Span b _m a) -> b /= a) $ getStrokes point i j layers2 = map (map overlayStroke) $ groupBy ((==) `on` overlayLayer) $ Set.toList $ overlays fb layer3 = case regex of Just re -> takeIn $ map hintStroke $ regexRegionBI re (mkRegion i j) fb Nothing -> [] result = map (map clampStroke . takeIn . dropBefore) (layer3 : layers2 ++ [syntaxHlLayer, groundLayer]) overlayStroke (Overlay _ sm em a) = Span (markPoint sm) a (markPoint em) clampStroke (Span l x r) = Span (max i l) x (min j r) hintStroke r = Span (regionStart r) (if point `nearRegion` r then strongHintStyle else hintStyle) (regionEnd r) ------------------------------------------------------------------------ -- Point based editing -- | Checks if an Update is valid isValidUpdate :: Update -> BufferImpl syntax -> Bool isValidUpdate u b = case u of (Delete p _ _) -> check p && check (p +~ updateSize u) (Insert p _ _) -> check p where check (Point x) = x >= 0 && x <= R.length (mem b) -- | Apply a /valid/ update applyUpdateI :: Update -> BufferImpl syntax -> BufferImpl syntax applyUpdateI u fb = touchSyntax (updatePoint u) $ fb {mem = p', marks = M.map shift (marks fb), overlays = Set.map (mapOvlMarks shift) (overlays fb)} -- FIXME: this is inefficient; find a way to use mapMonotonic -- (problem is that marks can have different gravities) where (p', amount) = case u of Insert pnt _ cs -> (insertChars p cs pnt, sz) Delete pnt _ _ -> (deleteChars p pnt sz, negate sz) sz = updateSize u shift = shiftMarkValue (updatePoint u) amount p = mem fb -- FIXME: remove collapsed overlays -- | Reverse the given update reverseUpdateI :: Update -> Update reverseUpdateI (Delete p dir cs) = Insert p (reverseDir dir) cs reverseUpdateI (Insert p dir cs) = Delete p (reverseDir dir) cs ------------------------------------------------------------------------ -- Line based editing -- | Line at the given point. (Lines are indexed from 1) lineAt :: Point -- ^ Line for which to grab EOL for -> BufferImpl syntax -> Int lineAt (Point p) fb = 1 + R.countNewLines (R.take p $ mem fb) -- | Point that starts the given line (Lines are indexed from 1) solPoint :: Int -> BufferImpl syntax -> Point solPoint line fb = Point $ R.length $ fst $ R.splitAtLine (line - 1) (mem fb) -- | Point that's at EOL. Notably, this puts you right before the -- newline character if one exists, and right at the end of the text -- if one does not. eolPoint' :: Point -- ^ Point from which we take the line to find the EOL of -> BufferImpl syntax -> Point eolPoint' p@(Point ofs) fb = Point . checkEol . fst . R.splitAtLine ln $ mem fb where ln = lineAt p fb -- In case we're somewhere without trailing newline, we need to -- stay where we are checkEol t = let l' = R.length t in case R.last t of -- We're looking at EOL and we weren't asking for EOL past -- this point, so back up one for good visual effect Just '\n' | l' > ofs -> l' - 1 -- We asked for EOL past the last newline so just go to the -- very end of content _ -> l' -- | Get begining of the line relatively to @point@. solPoint' :: Point -> BufferImpl syntax -> Point solPoint' point fb = solPoint (lineAt point fb) fb charsFromSolBI :: Point -> BufferImpl syntax -> YiString charsFromSolBI pnt fb = nelemsBI (fromIntegral $ pnt - sol) sol fb where sol = solPoint' pnt fb -- | Return indices of all strings in buffer matching regex, inside the given region. regexRegionBI :: SearchExp -> Region -> forall syntax. BufferImpl syntax -> [Region] regexRegionBI se r fb = case dir of Forward -> fmap (fmapRegion addPoint . matchedRegion) $ matchAll' $ R.toString bufReg Backward -> fmap (fmapRegion subPoint . matchedRegion) $ matchAll' $ R.toReverseString bufReg where matchedRegion arr = let (off,len) = arr!0 in mkRegion (Point off) (Point (off+len)) addPoint (Point x) = Point (p + x) subPoint (Point x) = Point (q - x) matchAll' = matchAll (searchRegex dir se) dir = regionDirection r Point p = regionStart r Point q = regionEnd r Size s = regionSize r bufReg = R.take s . R.drop p $ mem fb newMarkBI :: MarkValue -> BufferImpl syntax -> (BufferImpl syntax, Mark) newMarkBI initialValue fb = let maxId = fromMaybe 0 $ markId . fst . fst <$> M.maxViewWithKey (marks fb) newMark = Mark $ maxId + 1 fb' = fb { marks = M.insert newMark initialValue (marks fb)} in (fb', newMark) getMarkValueBI :: Mark -> BufferImpl syntax -> Maybe MarkValue getMarkValueBI m (FBufferData { marks = marksMap } ) = M.lookup m marksMap deleteMarkValueBI :: Mark -> BufferImpl syntax -> BufferImpl syntax deleteMarkValueBI m fb = fb { marks = M.delete m (marks fb) } getMarkBI :: String -> BufferImpl syntax -> Maybe Mark getMarkBI name FBufferData {markNames = nms} = M.lookup name nms -- | Modify a mark value. modifyMarkBI :: Mark -> (MarkValue -> MarkValue) -> (forall syntax. BufferImpl syntax -> BufferImpl syntax) modifyMarkBI m f fb = fb {marks = mapAdjust' f m (marks fb)} -- NOTE: we must insert the value strictly otherwise we can hold to whatever structure the value of the mark depends on. -- (often a whole buffer) setSyntaxBI :: ExtHL syntax -> BufferImpl oldSyntax -> BufferImpl syntax setSyntaxBI (ExtHL e) fb = touchSyntax 0 $ fb {hlCache = HLState e (hlStartState e)} touchSyntax :: Point -> BufferImpl syntax -> BufferImpl syntax touchSyntax touchedIndex fb = fb { dirtyOffset = min touchedIndex (dirtyOffset fb)} updateSyntax :: BufferImpl syntax -> BufferImpl syntax updateSyntax fb@FBufferData {dirtyOffset = touchedIndex, hlCache = HLState hl cache} | touchedIndex == maxBound = fb | otherwise = fb {dirtyOffset = maxBound, hlCache = HLState hl (hlRun hl getText touchedIndex cache) } where getText = Scanner 0 id (error "getText: no character beyond eof") (\idx -> getIndexedStream Forward idx fb) ------------------------------------------------------------------------ -- | Returns the requested mark, creating a new mark with that name (at the supplied position) if needed getMarkDefaultPosBI :: Maybe String -> Point -> BufferImpl syntax -> (BufferImpl syntax, Mark) getMarkDefaultPosBI name defaultPos fb@FBufferData {marks = mks, markNames = nms} = case flip M.lookup nms =<< name of Just m' -> (fb, m') Nothing -> let newMark = Mark (1 + max 1 (markId $ fst (M.findMax mks))) nms' = case name of Nothing -> nms Just nm -> M.insert nm newMark nms mks' = M.insert newMark (MarkValue defaultPos Forward) mks in (fb {marks = mks', markNames = nms'}, newMark) getAst :: WindowRef -> BufferImpl syntax -> syntax getAst w FBufferData {hlCache = HLState (SynHL {hlGetTree = gt}) cache} = gt cache w focusAst :: M.Map WindowRef Region -> BufferImpl syntax -> BufferImpl syntax focusAst r b@FBufferData {hlCache = HLState s@(SynHL {hlFocus = foc}) cache} = b {hlCache = HLState s (foc r cache)}
atsukotakahashi/wi
src/library/Yi/Buffer/Implementation.hs
gpl-2.0
17,713
0
21
4,425
4,498
2,370
2,128
309
3
module Probability.BayesianNetwork where import Notes import GraphTheory.Terms import Probability.ConditionalProbability.Macro import Probability.Independence.Terms import Probability.ProbabilityMeasure.Macro import Probability.RandomVariable.Macro import Probability.RandomVariable.Terms import Probability.BayesianNetwork.Graph import Probability.BayesianNetwork.Terms bayesianNetworkS :: Note bayesianNetworkS = section "Bayesian Networks" $ do bayesianNetworkDefinition bayesianNetworkExamples bayesianNetworkDefinition :: Note bayesianNetworkDefinition = de $ do lab bayesianNetworkDefinitionLabel s ["A", bayesianNetwork', "is a", directed, acyclic, graph, "that defines a joint distribution of", randomVariables, "and encodes independences and conditional independences as such."] todo "This should be defined way more rigorously" bayesianNetworkExamples :: Note bayesianNetworkExamples = do ex $ do bnFig $ BayesNet { bayesNetNodes = ["A", "B", "C"] , bayesNetEdges = [("A", "B"), ("B", "C")] } let [a, b, c] = ["A", "B", "C"] s ["Note that", m a, and, m c, "are", conditionallyIndependent, "given", m b] aligneqs (cprobss [a, c] [b]) [ (prob a * cprob b a * cprob c b) /: prob b , cprob a b * cprob c b ] ex $ do bnFig $ BayesNet { bayesNetNodes = ["A", "B", "C"] , bayesNetEdges = [("B", "A"), ("B", "C")] } let [a, b, c] = ["A", "B", "C"] s ["Note that", m a, and, m c, "are", conditionallyIndependent, "given", m b] aligneqs (cprobss [a, c] [b]) [ (cprob a b * prob b * cprob c b) /: prob b , cprob a b * cprob c b ] ex $ do bnFig $ BayesNet { bayesNetNodes = ["A", "B", "C"] , bayesNetEdges = [("A", "B"), ("C", "B")] } s ["Note that ", m a, and, m c, "are", independent, "but not", conditionallyIndependent, "given", m b] aligneqs (cprob a c) [ probs [a, b, c] /: cprobs b [a, c] , probs [a, c] ] aligneqs (cprobss [a, c] [b]) [ (prob a * cprobs b [a, c] * prob c) /: prob b , (prob a * probs [a, b] * cprobs b [a, c] * prob c) /: (prob b * probs [a, b]) , (prob a * cprob a b * cprobs b [a, c] * prob c * probs [c, b]) /: (probs [a, b] * probs [c, b]) , (cprob a b * cprobs b [a, c] * prob c * probs [c, b]) /: (cprob b a * probs [c, b]) , (cprob a b * cprob b c * cprobs b [a, c] * prob c * prob b) /: (cprob b a * probs [c, b]) , (cprob a b * cprob b c) * (cprobs b [a, c] * prob b) /: (cprob b a * cprob b c) ] ex $ do bnFig $ BayesNet { bayesNetNodes = ["A", "B", "C", "D", "E"] , bayesNetEdges = [("A", "C"), ("B", "C"), ("C", "D"), ("C", "E")] }
NorfairKing/the-notes
src/Probability/BayesianNetwork.hs
gpl-2.0
2,940
0
15
917
1,204
655
549
58
1
module Amoeba.Application.Assets.TestWorld (testWorld) where import Amoeba.GameLogic.Facade import qualified Data.Map as M res1, res2, res3 :: Resource Int res1 = toResource (0, 1000) res2 = toResource (100, 100) res3 = toResource (300, 2000) p1, p2 :: Point p1 = point 10 10 0 p2 = point 20 20 0 objectId1, objectId2 :: Int objectId1 = 1 objectId2 = 2 testWorldMap :: M.Map Point Object testWorldMap = M.fromList [ (p1, Object objectId1 1 humanPlayer res1 res2 res3) , (p2, Object objectId2 1 ai1Player res1 res2 res3)] testEffectMap :: EffectMap testEffectMap = M.empty testWorld :: World testWorld = World testWorldMap testEffectMap 1 1 Nothing
graninas/The-Amoeba-World
src/Amoeba/Application/Assets/TestWorld.hs
gpl-3.0
682
0
8
135
228
132
96
20
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Model.RobotConfiguration ( RobotConfiguration (..) ) where import Data.Aeson import GHC.Generics import Test.QuickCheck data RobotConfiguration = RobotConfiguration { name :: String , maxHitPoints :: Float , maxSpeed :: Float , acceleration :: Float , decelleration :: Float , maxSterlingSpeed :: Float , maxScanDistance :: Float , maxFireDistance :: Float , bulletSpeed :: Float , bulletDamage :: Float , cannonReloadingTime :: Float } deriving (Show, Eq, Generic) instance FromJSON RobotConfiguration instance ToJSON RobotConfiguration instance Arbitrary RobotConfiguration where arbitrary = RobotConfiguration <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
massimo-zaniboni/netrobots
robot_examples/haskell-servant/rest_api/lib/Model/RobotConfiguration.hs
gpl-3.0
1,007
0
16
186
196
116
80
27
0
import HsTri main = previewAuto tr_6 defaultSGEE
DanielSchuessler/hstri
scratch2.hs
gpl-3.0
50
0
5
8
14
7
7
2
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} import Control.Applicative ((<$>),(<*>),pure) import Control.Lens import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.Either import Control.Monad.Trans.Maybe import Data.Attoparsec.Char8 hiding (take) -- import Data.Attoparsec.Lazy import Data.Aeson import Data.Aeson.Encode.Pretty (encodePretty) import qualified Data.Aeson.Generic as G import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import Data.Data import Data.Function (on) import Data.List (lookup, sortBy) import Data.Maybe import Data.String import Data.Typeable import System.Environment (getArgs) -- import HEP.Automation.EventGeneration.Config import HEP.Storage.WebDAV.CURL import HEP.Storage.WebDAV.Type -- import HEP.Storage.WebDAV.Util import HEP.Util.Functions import HEP.Util.Either -- import HEP.Physics.Analysis.ATLAS.Common import HEP.Physics.Analysis.ATLAS.SUSY.SUSY_0L2to6JMET_8TeV import HEP.Physics.Analysis.Common.XSecNTotNum import HEP.Util.Work chisquareTTBar :: TotalSR Double -> Double chisquareTTBar TotalSR {..} = ((numAL - 870)^2) / (180^2) + ((numAM - 7.8)^2) / (2.8^2) + ((numBM - 2.2)^2) / (2.0^2) + ((numBT - 0.6)^2) / (0.7^2) + ((numCM - 50)^2) / (11^2) + ((numCT - 0.9)^2) / (0.9^2) + ((numDT - 5.8)^2) / (2.1^2) + ((numEL - 76)^2) / (19^2) + ((numEM - 20)^2) / (6^2) + ((numET - 1.7)^2) / (1.4^2) -- (\wdavcfg wdavrdir nm -> getXSecNCount wdavcfg wdavrdir nm >>= getJSONFileAndUpload wdavcfg wdavrdir nm) -- atlas_8TeV_0L2to6J_bkgtest -- testprint -- jestest = ([0,1..20], [0,1..10]) main = do args <- getArgs let n1 :: Int = read (args !! 0) n2 :: Int = read (args !! 1) nlst = (drop (n1-1) . take n2) [1..] rdir = "montecarlo/admproject/sm8/tt012" basename = "SM_tt012j_LHC8ATLAS_MLM_DefCut_AntiKT0.4_NoTau_Set" fn = basename ++ show n1 ++ "to" ++ show n2 ++ "_ATLAS8TeV0L2to6JBkgTest.json" bstr <- LB.readFile fn let Just (xsecn,lst) = G.decode bstr :: Maybe (CrossSectionAndCount,[(JESParam, TotalSR Double)]) totevts = numberOfEvent xsecn xsec = crossSectionInPb xsecn weight = 238.0 * 20300 / fromIntegral totevts lst' = flip map lst $ \(x,y)-> let z' = multiplyScalar weight y y' = chisquareTTBar z' in (x,y'/10.0,z') print xsecn mapM_ print (sortBy (compare `on` snd3) lst') {- r1 <- work (\wdavcfg wdavrdir nm -> getXSecNCount XSecPYTHIA wdavcfg wdavrdir nm >>= getJSONFileAndUpload wdavcfg wdavrdir nm) "config1.txt" rdir basename nlst return () -} {- r1 <- work (atlas_8TeV_0L2to6J_bkgtest jestest) "config1.txt" rdir basename nlst -- print r1 return () -} {- r <- work fetchXSecNHist "config1.txt" rdir basename nlst case r of Left err -> putStrLn err Right vs -> do -- return () let vs' = catMaybes vs let totevts = (sum . map (numberOfEvent.fst)) vs' mul = (*) <$> crossSectionInPb <*> fromIntegral . numberOfEvent totcross = (/ (fromIntegral totevts)) . sum . map (mul . fst) $ vs' -- -- if I use only LO (normally not do that) -- weight = {- 238.0 -} totcross * 20300 / fromIntegral totevts -- -- for 8 TeV ttbar (cross section from HATHOR ) -- weight = 238.0 * 20300 / fromIntegral totevts test a b = let hists = mapMaybe (lookup (JESParam a b)) . map snd $ vs' sumup k = (sum . mapMaybe (lookup k)) hists totsr :: TotalSR Int totsr = TotalSR { numAL = sumup AL , numAM = sumup AM , numBM = sumup BM , numBT = sumup BT , numCM = sumup CM , numCT = sumup CT , numDT = sumup DT , numEL = sumup EL , numEM = sumup EM , numET = sumup ET } in (JESParam a b, totsr) let xsecn = CrossSectionAndCount totcross totevts combined = (xsecn,[ test a b | a <- [0,1..20], b <- [0,1..10] ] ) fn = basename ++ show n1 ++ "to" ++ show n2 ++ "_ATLAS8TeV0L2to6JBkgTest.json" bstr = encodePretty combined LB.writeFile fn bstr -} fetchXSecNHist :: WebDAVConfig -> WebDAVRemoteDir -> String -> IO (Maybe (CrossSectionAndCount,[(JESParam,HistEType)])) fetchXSecNHist wdavcfg wdavrdir bname = do let fp1 = bname ++ "_ATLAS8TeV0L2to6JBkgTest.json" fp2 = bname ++ "_total_count.json" runMaybeT $ do (_,mr1) <- MaybeT . boolToMaybeM (doesFileExistInDAV wdavcfg wdavrdir fp1) . downloadFile True wdavcfg wdavrdir $ fp1 r1 <- liftM LB.pack (MaybeT . return $ mr1) (result :: [(JESParam, HistEType)]) <- MaybeT . return $ G.decode r1 (_,mr2) <- MaybeT . boolToMaybeM (doesFileExistInDAV wdavcfg wdavrdir fp2) . downloadFile True wdavcfg wdavrdir $ fp2 r2 <- liftM LB.pack (MaybeT . return $ mr2) (xsec :: CrossSectionAndCount) <- MaybeT . return $ G.decode r2 return (xsec,result)
wavewave/lhc-analysis-collection
analysis/findab_8TeV.hs
gpl-3.0
5,999
0
27
2,110
1,185
661
524
76
1
module Main where import Network.CGI import Text.XHtml import Network.Socket hiding (recv) import Network.Socket.ByteString (recv, sendAll) import qualified Data.ByteString.Char8 as C port = "3000" inputForm = ("The bot is unavailable at the moment due to a problem with the request/server. Please check back later or check the format of your request." ++ "<br />") greet n = do m <- liftIO (ask n) return ("<i>You: " ++ n ++ "</i><br />" ++ "Bot: " ++ m ++ "<br />") ask usermsg = withSocketsDo $ do addrinfos <- getAddrInfo Nothing (Just "") (Just port) let serveraddr = head addrinfos sock <- socket (addrFamily serveraddr) Stream defaultProtocol connect sock (addrAddress serveraddr) sendAll sock $ C.pack usermsg msg <- recv sock 1024 sClose sock return (C.unpack msg) cgiMain = do{ mn <- getInput "question" ; x <- maybe (return inputForm) greet mn ; output x } main = runCGI $ handleErrors cgiMain
saxenasaurabh/chatty
BotWeb.hs
gpl-3.0
1,057
10
13
300
316
157
159
24
1
{-# 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.Config.DescribeDeliveryChannelStatus -- 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. -- | Returns the current status of the specified delivery channel. If a delivery -- channel is not specified, this action returns the current status of all -- delivery channels associated with the account. -- -- <http://docs.aws.amazon.com/config/latest/APIReference/API_DescribeDeliveryChannelStatus.html> module Network.AWS.Config.DescribeDeliveryChannelStatus ( -- * Request DescribeDeliveryChannelStatus -- ** Request constructor , describeDeliveryChannelStatus -- ** Request lenses , ddcsDeliveryChannelNames -- * Response , DescribeDeliveryChannelStatusResponse -- ** Response constructor , describeDeliveryChannelStatusResponse -- ** Response lenses , ddcsrDeliveryChannelsStatus ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.Config.Types import qualified GHC.Exts newtype DescribeDeliveryChannelStatus = DescribeDeliveryChannelStatus { _ddcsDeliveryChannelNames :: List "DeliveryChannelNames" Text } deriving (Eq, Ord, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeDeliveryChannelStatus where type Item DescribeDeliveryChannelStatus = Text fromList = DescribeDeliveryChannelStatus . GHC.Exts.fromList toList = GHC.Exts.toList . _ddcsDeliveryChannelNames -- | 'DescribeDeliveryChannelStatus' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ddcsDeliveryChannelNames' @::@ ['Text'] -- describeDeliveryChannelStatus :: DescribeDeliveryChannelStatus describeDeliveryChannelStatus = DescribeDeliveryChannelStatus { _ddcsDeliveryChannelNames = mempty } -- | A list of delivery channel names. ddcsDeliveryChannelNames :: Lens' DescribeDeliveryChannelStatus [Text] ddcsDeliveryChannelNames = lens _ddcsDeliveryChannelNames (\s a -> s { _ddcsDeliveryChannelNames = a }) . _List newtype DescribeDeliveryChannelStatusResponse = DescribeDeliveryChannelStatusResponse { _ddcsrDeliveryChannelsStatus :: List "DeliveryChannelsStatus" DeliveryChannelStatus } deriving (Eq, Read, Show, Monoid, Semigroup) instance GHC.Exts.IsList DescribeDeliveryChannelStatusResponse where type Item DescribeDeliveryChannelStatusResponse = DeliveryChannelStatus fromList = DescribeDeliveryChannelStatusResponse . GHC.Exts.fromList toList = GHC.Exts.toList . _ddcsrDeliveryChannelsStatus -- | 'DescribeDeliveryChannelStatusResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ddcsrDeliveryChannelsStatus' @::@ ['DeliveryChannelStatus'] -- describeDeliveryChannelStatusResponse :: DescribeDeliveryChannelStatusResponse describeDeliveryChannelStatusResponse = DescribeDeliveryChannelStatusResponse { _ddcsrDeliveryChannelsStatus = mempty } -- | A list that contains the status of a specified delivery channel. ddcsrDeliveryChannelsStatus :: Lens' DescribeDeliveryChannelStatusResponse [DeliveryChannelStatus] ddcsrDeliveryChannelsStatus = lens _ddcsrDeliveryChannelsStatus (\s a -> s { _ddcsrDeliveryChannelsStatus = a }) . _List instance ToPath DescribeDeliveryChannelStatus where toPath = const "/" instance ToQuery DescribeDeliveryChannelStatus where toQuery = const mempty instance ToHeaders DescribeDeliveryChannelStatus instance ToJSON DescribeDeliveryChannelStatus where toJSON DescribeDeliveryChannelStatus{..} = object [ "DeliveryChannelNames" .= _ddcsDeliveryChannelNames ] instance AWSRequest DescribeDeliveryChannelStatus where type Sv DescribeDeliveryChannelStatus = Config type Rs DescribeDeliveryChannelStatus = DescribeDeliveryChannelStatusResponse request = post "DescribeDeliveryChannelStatus" response = jsonResponse instance FromJSON DescribeDeliveryChannelStatusResponse where parseJSON = withObject "DescribeDeliveryChannelStatusResponse" $ \o -> DescribeDeliveryChannelStatusResponse <$> o .:? "DeliveryChannelsStatus" .!= mempty
kim/amazonka
amazonka-config/gen/Network/AWS/Config/DescribeDeliveryChannelStatus.hs
mpl-2.0
5,083
0
10
882
558
335
223
69
1
{-# LANGUAGE OverloadedStrings #-} ------------------------------------------------------------------------------ -- | This module is where all the routes and handlers are defined for your -- site. The 'app' function is the initializer that combines everything -- together and is exported by this module. module Site ( app ) where ------------------------------------------------------------------------------ import Data.ByteString (ByteString) import Snap.Snaplet ------------------------------------------------------------------------------ import Api.Core import Application -- | The application's routes. routes :: [(ByteString, Handler App App ())] routes = [] ------------------------------------------------------------------------------ -- | The application initializer. app :: SnapletInit App App app = makeSnaplet "app" "An snaplet example application." Nothing $ do api' <- nestSnaplet "api" api apiInit addRoutes routes return $ App api'
japesinator/eve-api
src/Site.hs
mpl-2.0
1,012
0
9
165
128
72
56
14
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.StorageGateway.AddTagsToResource -- 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) -- -- This operation adds one or more tags to the specified resource. You use -- tags to add metadata to resources, which you can use to categorize these -- resources. For example, you can categorize resources by purpose, owner, -- environment, or team. Each tag consists of a key and a value, which you -- define. You can add tags to the following AWS Storage Gateway resources: -- -- - Storage gateways of all types -- -- - Storage Volumes -- -- - Virtual Tapes -- -- You can create a maximum of 10 tags for each resource. Virtual tapes and -- storage volumes that are recovered to a new gateway maintain their tags. -- -- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_AddTagsToResource.html AWS API Reference> for AddTagsToResource. module Network.AWS.StorageGateway.AddTagsToResource ( -- * Creating a Request addTagsToResource , AddTagsToResource -- * Request Lenses , attrResourceARN , attrTags -- * Destructuring the Response , addTagsToResourceResponse , AddTagsToResourceResponse -- * Response Lenses , attrrsResourceARN , attrrsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.StorageGateway.Types import Network.AWS.StorageGateway.Types.Product -- | AddTagsToResourceInput -- -- /See:/ 'addTagsToResource' smart constructor. data AddTagsToResource = AddTagsToResource' { _attrResourceARN :: !Text , _attrTags :: ![Tag] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AddTagsToResource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'attrResourceARN' -- -- * 'attrTags' addTagsToResource :: Text -- ^ 'attrResourceARN' -> AddTagsToResource addTagsToResource pResourceARN_ = AddTagsToResource' { _attrResourceARN = pResourceARN_ , _attrTags = mempty } -- | The Amazon Resource Name (ARN) of the resource you want to add tags to. attrResourceARN :: Lens' AddTagsToResource Text attrResourceARN = lens _attrResourceARN (\ s a -> s{_attrResourceARN = a}); -- | The key-value pair that represents the tag you want to add to the -- resource. The value can be an empty string. -- -- Valid characters for key and value are letters, spaces, and numbers -- representable in UTF-8 format, and the following special characters: + - -- = . _ : \/ \'. attrTags :: Lens' AddTagsToResource [Tag] attrTags = lens _attrTags (\ s a -> s{_attrTags = a}) . _Coerce; instance AWSRequest AddTagsToResource where type Rs AddTagsToResource = AddTagsToResourceResponse request = postJSON storageGateway response = receiveJSON (\ s h x -> AddTagsToResourceResponse' <$> (x .?> "ResourceARN") <*> (pure (fromEnum s))) instance ToHeaders AddTagsToResource where toHeaders = const (mconcat ["X-Amz-Target" =# ("StorageGateway_20130630.AddTagsToResource" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON AddTagsToResource where toJSON AddTagsToResource'{..} = object (catMaybes [Just ("ResourceARN" .= _attrResourceARN), Just ("Tags" .= _attrTags)]) instance ToPath AddTagsToResource where toPath = const "/" instance ToQuery AddTagsToResource where toQuery = const mempty -- | AddTagsToResourceOutput -- -- /See:/ 'addTagsToResourceResponse' smart constructor. data AddTagsToResourceResponse = AddTagsToResourceResponse' { _attrrsResourceARN :: !(Maybe Text) , _attrrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AddTagsToResourceResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'attrrsResourceARN' -- -- * 'attrrsResponseStatus' addTagsToResourceResponse :: Int -- ^ 'attrrsResponseStatus' -> AddTagsToResourceResponse addTagsToResourceResponse pResponseStatus_ = AddTagsToResourceResponse' { _attrrsResourceARN = Nothing , _attrrsResponseStatus = pResponseStatus_ } -- | The Amazon Resource Name (ARN) of the resource you want to add tags to. attrrsResourceARN :: Lens' AddTagsToResourceResponse (Maybe Text) attrrsResourceARN = lens _attrrsResourceARN (\ s a -> s{_attrrsResourceARN = a}); -- | The response status code. attrrsResponseStatus :: Lens' AddTagsToResourceResponse Int attrrsResponseStatus = lens _attrrsResponseStatus (\ s a -> s{_attrrsResponseStatus = a});
olorin/amazonka
amazonka-storagegateway/gen/Network/AWS/StorageGateway/AddTagsToResource.hs
mpl-2.0
5,551
0
13
1,202
684
414
270
88
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.Vision.Projects.Locations.Files.AsyncBatchAnnotate -- 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) -- -- Run asynchronous image detection and annotation for a list of generic -- files, such as PDF files, which may contain multiple pages and multiple -- images per page. Progress and results can be retrieved through the -- \`google.longrunning.Operations\` interface. \`Operation.metadata\` -- contains \`OperationMetadata\` (metadata). \`Operation.response\` -- contains \`AsyncBatchAnnotateFilesResponse\` (results). -- -- /See:/ <https://cloud.google.com/vision/ Cloud Vision API Reference> for @vision.projects.locations.files.asyncBatchAnnotate@. module Network.Google.Resource.Vision.Projects.Locations.Files.AsyncBatchAnnotate ( -- * REST Resource ProjectsLocationsFilesAsyncBatchAnnotateResource -- * Creating a Request , projectsLocationsFilesAsyncBatchAnnotate , ProjectsLocationsFilesAsyncBatchAnnotate -- * Request Lenses , plfabaParent , plfabaXgafv , plfabaUploadProtocol , plfabaAccessToken , plfabaUploadType , plfabaPayload , plfabaCallback ) where import Network.Google.Prelude import Network.Google.Vision.Types -- | A resource alias for @vision.projects.locations.files.asyncBatchAnnotate@ method which the -- 'ProjectsLocationsFilesAsyncBatchAnnotate' request conforms to. type ProjectsLocationsFilesAsyncBatchAnnotateResource = "v1p2beta1" :> Capture "parent" Text :> "files:asyncBatchAnnotate" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesRequest :> Post '[JSON] Operation -- | Run asynchronous image detection and annotation for a list of generic -- files, such as PDF files, which may contain multiple pages and multiple -- images per page. Progress and results can be retrieved through the -- \`google.longrunning.Operations\` interface. \`Operation.metadata\` -- contains \`OperationMetadata\` (metadata). \`Operation.response\` -- contains \`AsyncBatchAnnotateFilesResponse\` (results). -- -- /See:/ 'projectsLocationsFilesAsyncBatchAnnotate' smart constructor. data ProjectsLocationsFilesAsyncBatchAnnotate = ProjectsLocationsFilesAsyncBatchAnnotate' { _plfabaParent :: !Text , _plfabaXgafv :: !(Maybe Xgafv) , _plfabaUploadProtocol :: !(Maybe Text) , _plfabaAccessToken :: !(Maybe Text) , _plfabaUploadType :: !(Maybe Text) , _plfabaPayload :: !GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesRequest , _plfabaCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsFilesAsyncBatchAnnotate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plfabaParent' -- -- * 'plfabaXgafv' -- -- * 'plfabaUploadProtocol' -- -- * 'plfabaAccessToken' -- -- * 'plfabaUploadType' -- -- * 'plfabaPayload' -- -- * 'plfabaCallback' projectsLocationsFilesAsyncBatchAnnotate :: Text -- ^ 'plfabaParent' -> GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesRequest -- ^ 'plfabaPayload' -> ProjectsLocationsFilesAsyncBatchAnnotate projectsLocationsFilesAsyncBatchAnnotate pPlfabaParent_ pPlfabaPayload_ = ProjectsLocationsFilesAsyncBatchAnnotate' { _plfabaParent = pPlfabaParent_ , _plfabaXgafv = Nothing , _plfabaUploadProtocol = Nothing , _plfabaAccessToken = Nothing , _plfabaUploadType = Nothing , _plfabaPayload = pPlfabaPayload_ , _plfabaCallback = Nothing } -- | Optional. Target project and location to make a call. Format: -- \`projects\/{project-id}\/locations\/{location-id}\`. If no parent is -- specified, a region will be chosen automatically. Supported -- location-ids: \`us\`: USA country only, \`asia\`: East asia areas, like -- Japan, Taiwan, \`eu\`: The European Union. Example: -- \`projects\/project-A\/locations\/eu\`. plfabaParent :: Lens' ProjectsLocationsFilesAsyncBatchAnnotate Text plfabaParent = lens _plfabaParent (\ s a -> s{_plfabaParent = a}) -- | V1 error format. plfabaXgafv :: Lens' ProjectsLocationsFilesAsyncBatchAnnotate (Maybe Xgafv) plfabaXgafv = lens _plfabaXgafv (\ s a -> s{_plfabaXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). plfabaUploadProtocol :: Lens' ProjectsLocationsFilesAsyncBatchAnnotate (Maybe Text) plfabaUploadProtocol = lens _plfabaUploadProtocol (\ s a -> s{_plfabaUploadProtocol = a}) -- | OAuth access token. plfabaAccessToken :: Lens' ProjectsLocationsFilesAsyncBatchAnnotate (Maybe Text) plfabaAccessToken = lens _plfabaAccessToken (\ s a -> s{_plfabaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). plfabaUploadType :: Lens' ProjectsLocationsFilesAsyncBatchAnnotate (Maybe Text) plfabaUploadType = lens _plfabaUploadType (\ s a -> s{_plfabaUploadType = a}) -- | Multipart request metadata. plfabaPayload :: Lens' ProjectsLocationsFilesAsyncBatchAnnotate GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesRequest plfabaPayload = lens _plfabaPayload (\ s a -> s{_plfabaPayload = a}) -- | JSONP plfabaCallback :: Lens' ProjectsLocationsFilesAsyncBatchAnnotate (Maybe Text) plfabaCallback = lens _plfabaCallback (\ s a -> s{_plfabaCallback = a}) instance GoogleRequest ProjectsLocationsFilesAsyncBatchAnnotate where type Rs ProjectsLocationsFilesAsyncBatchAnnotate = Operation type Scopes ProjectsLocationsFilesAsyncBatchAnnotate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-vision"] requestClient ProjectsLocationsFilesAsyncBatchAnnotate'{..} = go _plfabaParent _plfabaXgafv _plfabaUploadProtocol _plfabaAccessToken _plfabaUploadType _plfabaCallback (Just AltJSON) _plfabaPayload visionService where go = buildClient (Proxy :: Proxy ProjectsLocationsFilesAsyncBatchAnnotateResource) mempty
brendanhay/gogol
gogol-vision/gen/Network/Google/Resource/Vision/Projects/Locations/Files/AsyncBatchAnnotate.hs
mpl-2.0
7,247
0
17
1,470
798
472
326
124
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.Calendar.ACL.Delete -- 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) -- -- Deletes an access control rule. -- -- /See:/ <https://developers.google.com/google-apps/calendar/firstapp Calendar API Reference> for @calendar.acl.delete@. module Network.Google.Resource.Calendar.ACL.Delete ( -- * REST Resource ACLDeleteResource -- * Creating a Request , aclDelete , ACLDelete -- * Request Lenses , adCalendarId , adRuleId ) where import Network.Google.AppsCalendar.Types import Network.Google.Prelude -- | A resource alias for @calendar.acl.delete@ method which the -- 'ACLDelete' request conforms to. type ACLDeleteResource = "calendar" :> "v3" :> "calendars" :> Capture "calendarId" Text :> "acl" :> Capture "ruleId" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Deletes an access control rule. -- -- /See:/ 'aclDelete' smart constructor. data ACLDelete = ACLDelete' { _adCalendarId :: !Text , _adRuleId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ACLDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'adCalendarId' -- -- * 'adRuleId' aclDelete :: Text -- ^ 'adCalendarId' -> Text -- ^ 'adRuleId' -> ACLDelete aclDelete pAdCalendarId_ pAdRuleId_ = ACLDelete' { _adCalendarId = pAdCalendarId_ , _adRuleId = pAdRuleId_ } -- | 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. adCalendarId :: Lens' ACLDelete Text adCalendarId = lens _adCalendarId (\ s a -> s{_adCalendarId = a}) -- | ACL rule identifier. adRuleId :: Lens' ACLDelete Text adRuleId = lens _adRuleId (\ s a -> s{_adRuleId = a}) instance GoogleRequest ACLDelete where type Rs ACLDelete = () type Scopes ACLDelete = '["https://www.googleapis.com/auth/calendar"] requestClient ACLDelete'{..} = go _adCalendarId _adRuleId (Just AltJSON) appsCalendarService where go = buildClient (Proxy :: Proxy ACLDeleteResource) mempty
rueshyna/gogol
gogol-apps-calendar/gen/Network/Google/Resource/Calendar/ACL/Delete.hs
mpl-2.0
3,053
0
14
727
387
233
154
60
1
module Data.IORef.Tools( atomicModifyIORef_ ) where import Data.IORef(IORef, atomicModifyIORef) atomicModifyIORef_ :: IORef a -> (a -> a) -> IO () atomicModifyIORef_ ref f = atomicModifyIORef ref $ \x -> (f x, ())
YoshikuniJujo/yjtools_haskell
Data/IORef/Tools.hs
lgpl-3.0
217
2
8
34
88
48
40
5
1
module Jammin where import Data.List import Data.Ord data Fruit = Peach | Plum | Apple | Blackberry deriving (Eq, Show, Ord) -- Cardinality = 4 * 2^64 - product type because of record syntax, Int in Haskell is 64 bits so 2^64 data JamJars = Jam {fruit :: Fruit, jars :: Int} deriving (Eq, Show, Ord) row1 :: JamJars row1 = Jam {fruit = Plum, jars = 2} row2 :: JamJars row2 = Jam {fruit = Apple, jars = 5} row3 :: JamJars row3 = Jam {fruit = Plum, jars = 7} row4 :: JamJars row4 = Jam {fruit = Blackberry, jars = 3} row5 :: JamJars row5 = Jam {fruit = Apple, jars = 10} row6 :: JamJars row6 = Jam {fruit = Peach, jars = 4} allJam :: [JamJars] allJam = [row1, row2, row3, row4, row5, row6] -- Function application required because sum(map(..)) thing -> sum (map(..) thing) -> sum([..]) -> Int totalJars :: [JamJars] -> Int totalJars = sum . map jars mostRow :: [JamJars] -> JamJars mostRow = head . reverse . sortBy (comparing jars) sortByFruit :: [JamJars] -> [JamJars] sortByFruit = sortBy (comparing fruit) groupJam :: [JamJars] -> [[JamJars]] groupJam = groupBy (\a b -> fruit a == fruit b) . sortByFruit
thewoolleyman/haskellbook
11/09/eric/Jammin.hs
unlicense
1,178
0
10
278
395
234
161
32
1
module Staircase.A282443 (a282443) where import Staircase.A282442 (a282442) a282443 n = a282442 n - 1
peterokagey/haskellOEIS
src/Staircase/A282443.hs
apache-2.0
103
0
6
15
36
20
16
3
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="bs-BA"> <title>TLS Debug | 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>
secdec/zap-extensions
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_bs_BA/helpset_bs_BA.hs
apache-2.0
970
83
52
159
396
209
187
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Model.SqlTypes where import Data.Maybe (isNothing) import Data.Text (Text) import Data.Time.Clock (UTCTime) import Database.Persist.TH ( persistLowerCase , mkMigrate , mkPersist , sqlSettings , share ) import Model.CoreTypes (Email) share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| User email Email password Text salt Text firstName Text lastName Text verifyCode Text Maybe disabled Bool absent Bool UniqueUserEmail email deriving Show Token userId UserId tokenId Text validUntil UTCTime UniqueTokenId TaskUser taskId TaskId userId UserId UniqueTaskUser taskId userId Turn userId UserId taskId TaskId startDate UTCTime finishedAt UTCTime Maybe Task title Text description Text frequency Int completionTime Int Invitation email Email code Text deriving Show UniqueInvitationEmail email |] userIsVerified :: User -> Bool userIsVerified = isNothing . userVerifyCode
flatrapp/core
app/Model/SqlTypes.hs
apache-2.0
1,677
0
7
658
120
75
45
21
1
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TypeOperators, FlexibleContexts #-} module Main where import Control.Monad import Flow import Kernel.Binning import Kernel.Data import Kernel.FFT import Kernel.Gridder import Kernel.IO -- ---------------------------------------------------------------------------- -- --- Functional --- -- ---------------------------------------------------------------------------- -- Abstract kernel signatures. createGrid :: Flow UVGrid createGrid = flow "create grid" grid :: Flow Vis -> Flow GCFs -> Flow UVGrid -> Flow UVGrid grid = flow "grid" idft :: Flow UVGrid -> Flow Image idft = flow "idft" gcf :: Flow Vis -> Flow GCFs gcf = flow "gcf" -- | Compound gridder actor gridder :: Flow Vis -> Flow GCFs -> Flow Image gridder vis gcfs = idft (grid vis gcfs createGrid) -- ---------------------------------------------------------------------------- -- --- Strategy --- -- ---------------------------------------------------------------------------- gridderStrat :: Config -> Strategy () gridderStrat cfg = do -- Make point domain for visibilities tdom <- makeRangeDomain 0 (cfgPoints cfg) -- Create data flow for tag, bind it to FFT plans let gpar = cfgGrid cfg gcfpar = cfgGCF cfg -- Data flows we want to calculate vis <- uniq $ flow "vis" let gcfs = gcf vis gridded = grid vis gcfs createGrid result = gridder vis gcfs -- Create ranged domains for grid coordinates udoms <- makeRangeDomain 0 (gridWidth gpar) vdoms <- makeRangeDomain 0 (gridHeight gpar) let uvdoms = (udoms, vdoms) -- Split and distribute over coordinate domain vdom <- split vdoms (gridTiles gpar) udom <- split udoms (gridTiles gpar) let uvdom = (udom, vdom) distribute vdom ParSchedule $ distribute udom ParSchedule $ do -- Read visibilities bind vis $ oskarReader tdom (cfgInput cfg) 0 0 -- Create w-binned domain, split wdoms <- makeBinDomain $ binSizer gpar tdom uvdom vis wdom <- split wdoms (gridBins gpar) -- Load GCFs distribute wdom SeqSchedule $ bind gcfs (gcfKernel gcfpar wdom) -- Bin visibilities (could distribute, but there's no benefit) rebind vis (binner gpar tdom uvdom wdom) -- Bind kernel rules bindRule createGrid (gridInit gcfpar uvdom) bindRule grid (gridKernel gpar gcfpar uvdoms wdom uvdom) -- Run gridding distributed calculate gridded -- Compute the result by detiling & iFFT on result tiles bind createGrid (gridInitDetile uvdoms) bind gridded (gridDetiling gcfpar uvdom uvdoms gridded createGrid) bindRule idft (ifftKern gpar uvdoms) calculate result -- Write out void $ bindNew $ imageWriter gpar (cfgOutput cfg) result main :: IO () main = do let gpar = GridPar { gridWidth = 2048 , gridHeight = 2048 , gridPitch = 2048 , gridTheta = 0.10 , gridFacets = 1 , gridTiles = 2 , gridBins = 10 } gcfpar = GCFPar { gcfSize = 16 , gcfOver = 8 , gcfFile = "gcf16.dat" } config = Config { cfgInput = "test_p00_s00_f00.vis" , cfgPoints = 32131 * 200 , cfgLong = 72.1 / 180 * pi -- probably wrong in some way , cfgLat = 42.6 / 180 * pi -- ditto , cfgOutput = "out.img" , cfgGrid = gpar , cfgGCF = gcfpar } dumpSteps $ gridderStrat config execStrategyDNA $ gridderStrat config
SKA-ScienceDataProcessor/RC
MS5/programs/gridding.hs
apache-2.0
3,694
0
13
1,072
852
432
420
72
1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# LANGUAGE BangPatterns, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} module Network.Riak.Protocol.GetServerInfoRequest (GetServerInfoRequest(..)) where import Prelude ((+), (/)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Text.ProtocolBuffers.Header as P' data GetServerInfoRequest = GetServerInfoRequest{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable) instance P'.Mergeable GetServerInfoRequest where mergeAppend GetServerInfoRequest GetServerInfoRequest = GetServerInfoRequest instance P'.Default GetServerInfoRequest where defaultValue = GetServerInfoRequest instance P'.Wire GetServerInfoRequest where wireSize ft' self'@(GetServerInfoRequest) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePut ft' self'@(GetServerInfoRequest) = case ft' of 10 -> put'Fields 11 -> do P'.putSize (P'.wireSize 10 self') put'Fields _ -> P'.wirePutErr ft' self' where put'Fields = do Prelude'.return () wireGet ft' = case ft' of 10 -> P'.getBareMessageWith update'Self 11 -> P'.getMessageWith update'Self _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> GetServerInfoRequest) GetServerInfoRequest where getVal m' f' = f' m' instance P'.GPB GetServerInfoRequest instance P'.ReflectDescriptor GetServerInfoRequest where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".Protocol.GetServerInfoRequest\", haskellPrefix = [MName \"Network\",MName \"Riak\"], parentModule = [MName \"Protocol\"], baseName = MName \"GetServerInfoRequest\"}, descFilePath = [\"Network\",\"Riak\",\"Protocol\",\"GetServerInfoRequest.hs\"], isGroup = False, fields = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False}"
janrain/riak-haskell-client
protobuf/src/Network/Riak/Protocol/GetServerInfoRequest.hs
apache-2.0
2,429
1
16
481
479
251
228
46
0
{-# OPTIONS_GHC -Wno-name-shadowing -Wno-orphans -Wno-unticked-promoted-constructors #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE JavaScriptFFI #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module CodeWorld.Driver where import qualified CodeWorld.CanvasM as CM import CodeWorld.Color import CodeWorld.DrawState import CodeWorld.Event import CodeWorld.Picture import Control.Concurrent import Control.Exception import Control.Monad import Control.Monad.Fix import Control.Monad.Loops import Control.Monad.Reader import Control.Monad.Ref import Data.Bool import Data.Char (chr) import Data.Dependent.Sum import Data.IORef import Data.List (zip4, intercalate) import Data.Maybe import Data.Serialize import Data.Serialize.Text () import Data.Text (Text) import qualified Data.Text as T import GHC.Fingerprint.Type import GHC.Generics import GHC.Stack import GHC.StaticPtr import Numeric (showFFloatAlt) import qualified Reflex as R import qualified Reflex.Host.Class as R import System.IO.Unsafe import System.Mem.StableName import System.Random import Text.Printf import Text.Read #ifdef ghcjs_HOST_OS import CodeWorld.CanvasM (MonadCanvas, CanvasM, runCanvasM) import CodeWorld.CollaborationUI (SetupPhase(..), Step(..), UIState) import qualified CodeWorld.CollaborationUI as CUI import CodeWorld.Message import CodeWorld.Prediction import Control.DeepSeq import Control.Monad.Identity import qualified Control.Monad.Trans.State as State import Data.Aeson (ToJSON(..), (.=), object) import Data.Hashable import qualified Data.JSString import qualified GHCJS.DOM.ClientRect as ClientRect import GHCJS.Concurrent (withoutPreemption) import GHCJS.DOM import GHCJS.DOM.Element import GHCJS.DOM.EventM import GHCJS.DOM.GlobalEventHandlers hiding (error, keyPress) import GHCJS.DOM.KeyboardEvent import GHCJS.DOM.MouseEvent import GHCJS.DOM.NonElementParentNode import GHCJS.DOM.Types (Window, Element, unElement) import GHCJS.Foreign.Callback import GHCJS.Marshal import GHCJS.Marshal.Pure import GHCJS.Types import JavaScript.Object import JavaScript.Web.AnimationFrame import qualified JavaScript.Web.Canvas as Canvas import qualified JavaScript.Web.Canvas.Internal as Canvas import qualified JavaScript.Web.Location as Loc import qualified JavaScript.Web.MessageEvent as WS import qualified JavaScript.Web.Performance as Performance import qualified JavaScript.Web.WebSocket as WS import Unsafe.Coerce #else import CodeWorld.CanvasM (MonadCanvas, runCanvasM) import Data.Time.Clock import qualified Graphics.Blank as Canvas import System.Environment #endif -- | Applies the affine transformation from the DrawState and prepares to draw -- with it. This does not set the color at the same time, because different -- pictures need to apply the color, if any, in different ways, often outside of -- the action that sets up the geometry. withDS :: MonadCanvas m => DrawState -> m a -> m a withDS (DrawState (AffineTransformation ta tb tc td te tf) _col) action = CM.saveRestore $ do CM.transform ta tb tc td te tf CM.beginPath action setColor :: MonadCanvas m => Color -> m () setColor (RGBA r g b a) = do CM.strokeColor (round $ r * 255) (round $ g * 255) (round $ b * 255) a CM.fillColor (round $ r * 255) (round $ g * 255) (round $ b * 255) a applyColor :: MonadCanvas m => DrawState -> m () applyColor ds = case getColorDS ds of Nothing -> setColor (RGBA 0 0 0 1) Just c -> setColor c -- | A slower way to draw a picture, which has some useful properties. It -- can draw images in non-standard colors, and apply transparent colors -- properly to overlapping compositions of basic shapes. There must be a -- color in the DrawState. viaOffscreen :: MonadCanvas m => Color -> (Color -> m ()) -> m () viaOffscreen (RGBA r g b a) pic = do w <- CM.getScreenWidth h <- CM.getScreenHeight when (w > 0.5 && h > 0.5) $ do img <- CM.newImage (round w) (round h) CM.withImage img $ do setupScreenContext (round w) (round h) pic (RGBA r g b 1) CM.saveRestore $ do px <- pixelSize CM.scale px (-px) CM.globalAlpha a CM.drawImage img (round (-w/2)) (round (-h/2)) (round w) (round h) followPath :: MonadCanvas m => [Point] -> Bool -> Bool -> m () followPath [] _ _ = return () followPath [_] _ _ = return () followPath ((sx, sy):ps) closed False = do CM.moveTo (sx, sy) forM_ ps $ \(x, y) -> CM.lineTo (x, y) when closed $ CM.closePath followPath [p1, p2] False True = followPath [p1, p2] False False followPath ps False True = do let [p1@(x1, y1), p2@(x2, y2), p3@(x3, y3)] = take 3 ps dprev = euclideanDistance p1 p2 dnext = euclideanDistance p2 p3 p = dprev / (dprev + dnext) cx = x2 + p * (x1 - x3) / 2 cy = y2 + p * (y1 - y3) / 2 CM.moveTo (x1, y1) CM.quadraticCurveTo (cx, cy) (x2, y2) forM_ (zip4 ps (tail ps) (tail $ tail ps) (tail $ tail $ tail ps)) $ \(p1@(x1, y1), p2@(x2, y2), p3@(x3, y3), p4@(x4, y4)) -> do let dp = euclideanDistance p1 p2 d1 = euclideanDistance p2 p3 d2 = euclideanDistance p3 p4 p = d1 / (d1 + d2) r = d1 / (dp + d1) cx1 = x2 + r * (x3 - x1) / 2 cy1 = y2 + r * (y3 - y1) / 2 cx2 = x3 + p * (x2 - x4) / 2 cy2 = y3 + p * (y2 - y4) / 2 CM.bezierCurveTo (cx1, cy1) (cx2, cy2) (x3, y3) let [p1@(x1, y1), p2@(x2, y2), p3@(x3, y3)] = reverse $ take 3 $ reverse ps dp = euclideanDistance p1 p2 d1 = euclideanDistance p2 p3 r = d1 / (dp + d1) cx = x2 + r * (x3 - x1) / 2 cy = y2 + r * (y3 - y1) / 2 CM.quadraticCurveTo (cx, cy) (x3, y3) followPath ps@(_:(sx, sy):_) True True = do CM.moveTo (sx, sy) let rep = cycle ps forM_ (zip4 ps (tail rep) (tail $ tail rep) (tail $ tail $ tail rep)) $ \(p1@(x1, y1), p2@(x2, y2), p3@(x3, y3), p4@(x4, y4)) -> do let dp = euclideanDistance p1 p2 d1 = euclideanDistance p2 p3 d2 = euclideanDistance p3 p4 p = d1 / (d1 + d2) r = d1 / (dp + d1) cx1 = x2 + r * (x3 - x1) / 2 cy1 = y2 + r * (y3 - y1) / 2 cx2 = x3 + p * (x2 - x4) / 2 cy2 = y3 + p * (y2 - y4) / 2 CM.bezierCurveTo (cx1, cy1) (cx2, cy2) (x3, y3) CM.closePath euclideanDistance :: Point -> Point -> Double euclideanDistance (x1, y1) (x2, y2) = sqrt $ square (x2 - x1) + square (y2 - y1) where square x = x * x drawFigure :: MonadCanvas m => DrawState -> Double -> m () -> m () drawFigure ds w figure = do withDS ds $ do figure when (w /= 0) $ do CM.lineWidth w applyColor ds CM.stroke when (w == 0) $ do CM.lineWidth =<< pixelSize applyColor ds CM.stroke fillFigure :: MonadCanvas m => DrawState -> m () -> m () fillFigure ds figure = do withDS ds $ figure applyColor ds CM.fill -------------------------------------------------------------------------------- drawPicture :: MonadCanvas m => Picture -> DrawState -> m () drawPicture (SolidClosedCurve _ pts) ds = drawPolygon pts True ds drawPicture (SolidPolygon _ pts) ds = drawPolygon pts False ds drawPicture (Polygon _ pts) ds = drawPath pts 0 True False ds drawPicture (ThickPolygon _ pts w) ds = drawPath pts w True False ds drawPicture (Rectangle _ w h) ds = drawPath (rectangleVertices w h) 0 True False ds drawPicture (SolidRectangle _ w h) ds = drawPolygon (rectangleVertices w h) False ds drawPicture (ThickRectangle _ lw w h) ds = drawPath (rectangleVertices w h) lw True False ds drawPicture (ClosedCurve _ pts) ds = drawPath pts 0 True True ds drawPicture (ThickClosedCurve _ pts w) ds = drawPath pts w True True ds drawPicture (Circle _ r) ds = drawArc 0 (2 * pi) r 0 ds drawPicture (SolidCircle _ r) ds = drawSector 0 (2 * pi) r ds drawPicture (ThickCircle _ lw r) ds = drawArc 0 (2 * pi) r lw ds drawPicture (Polyline _ pts) ds = drawPath pts 0 False False ds drawPicture (ThickPolyline _ pts w) ds = drawPath pts w False False ds drawPicture (Curve _ pts) ds = drawPath pts 0 False True ds drawPicture (ThickCurve _ pts w) ds = drawPath pts w False True ds drawPicture (Sector _ b e r) ds = drawSector b e r ds drawPicture (Arc _ b e r) ds = drawArc b e r 0 ds drawPicture (ThickArc _ b e r w) ds = drawArc b e r w ds drawPicture (Lettering _ txt) ds = drawText Plain Serif txt ds drawPicture (Blank _) _ = return () drawPicture (StyledLettering _ sty fnt txt) ds = drawText sty fnt txt ds drawPicture (Sketch _ name url w h) ds = drawImage name url w h ds drawPicture (CoordinatePlane _) ds = drawPicture coordinatePlanePic ds drawPicture (Color _ col p) ds | isSimplePic p || isOpaque col = drawPicture p (setColorDS col ds) | otherwise = viaOffscreen col $ \c -> drawPicture p (setColorDS c ds) drawPicture (Translate _ x y p) ds = drawPicture p (translateDS x y ds) drawPicture (Scale _ x y p) ds = drawPicture p (scaleDS x y ds) drawPicture (Dilate _ k p) ds = drawPicture p (scaleDS k k ds) drawPicture (Rotate _ r p) ds = drawPicture p (rotateDS r ds) drawPicture (Reflect _ r p) ds = drawPicture p (reflectDS r ds) drawPicture (Clip _ x y p) ds = do withDS ds $ followPath (rectangleVertices x y) True False CM.saveRestore $ CM.clip >> drawPicture p ds drawPicture (Pictures _ ps) ds = forM_ (reverse ps) $ \p -> drawPicture p ds drawPicture (PictureAnd _ ps) ds = forM_ (reverse ps) $ \p -> drawPicture p ds pictureContains :: MonadCanvas m => Picture -> DrawState -> Point -> m Bool pictureContains (SolidClosedCurve _ pts) ds pt = polygonContains pts True ds pt pictureContains (SolidPolygon _ pts) ds pt = polygonContains pts False ds pt pictureContains (Polygon _ pts) ds pt = pathContains pts 0 True False ds pt pictureContains (ThickPolygon _ pts w) ds pt = pathContains pts w True False ds pt pictureContains (Rectangle _ w h) ds pt = pathContains (rectangleVertices w h) 0 True False ds pt pictureContains (SolidRectangle _ w h) ds pt = polygonContains (rectangleVertices w h) False ds pt pictureContains (ThickRectangle _ lw w h) ds pt = pathContains (rectangleVertices w h) lw True False ds pt pictureContains (ClosedCurve _ pts) ds pt = pathContains pts 0 True True ds pt pictureContains (ThickClosedCurve _ pts w) ds pt = pathContains pts w True True ds pt pictureContains (Circle _ r) ds pt = arcContains 0 (2 * pi) r 0 ds pt pictureContains (SolidCircle _ r) ds pt = sectorContains 0 (2 * pi) r ds pt pictureContains (ThickCircle _ lw r) ds pt = arcContains 0 (2 * pi) r lw ds pt pictureContains (Polyline _ pts) ds pt = pathContains pts 0 False False ds pt pictureContains (ThickPolyline _ pts w) ds pt = pathContains pts w False False ds pt pictureContains (Curve _ pts) ds pt = pathContains pts 0 False True ds pt pictureContains (ThickCurve _ pts w) ds pt = pathContains pts w False True ds pt pictureContains (Sector _ b e r) ds pt = sectorContains b e r ds pt pictureContains (Arc _ b e r) ds pt = arcContains b e r 0 ds pt pictureContains (ThickArc _ b e r w) ds pt = arcContains b e r w ds pt pictureContains (Lettering _ txt) ds pt = textContains Plain Serif txt ds pt pictureContains (Blank _) _ _ = return False pictureContains (StyledLettering _ sty fnt txt) ds pt = textContains sty fnt txt ds pt pictureContains (Sketch _ name url w h) ds pt = imageContains name url w h ds pt pictureContains (CoordinatePlane _) ds pt = pictureContains coordinatePlanePic ds pt pictureContains (Color _ _ p) ds pt = pictureContains p ds pt pictureContains (Translate _ x y p) ds pt = pictureContains p (translateDS x y ds) pt pictureContains (Scale _ x y p) ds pt = pictureContains p (scaleDS x y ds) pt pictureContains (Dilate _ k p) ds pt = pictureContains p (scaleDS k k ds) pt pictureContains (Rotate _ r p) ds pt = pictureContains p (rotateDS r ds) pt pictureContains (Reflect _ r p) ds pt = pictureContains p (reflectDS r ds) pt pictureContains (Clip _ x y p) ds pt = (&&) <$> polygonContains (rectangleVertices x y) False ds pt <*> pictureContains p ds pt pictureContains (Pictures _ ps) ds pt = orM [pictureContains p ds pt | p <- ps] pictureContains (PictureAnd _ ps) ds pt = orM [pictureContains p ds pt | p <- ps] isSimplePic :: Picture -> Bool isSimplePic (Pictures _ []) = True isSimplePic (Pictures _ [p]) = isSimplePic p isSimplePic (Pictures _ _) = False isSimplePic (PictureAnd _ []) = True isSimplePic (PictureAnd _ [p]) = isSimplePic p isSimplePic (PictureAnd _ _) = False isSimplePic (Translate _ _ _ p) = isSimplePic p isSimplePic (Scale _ _ _ p) = isSimplePic p isSimplePic (Dilate _ _ p) = isSimplePic p isSimplePic (Rotate _ _ p) = isSimplePic p isSimplePic (Reflect _ _ p) = isSimplePic p isSimplePic (Clip _ _ _ p) = isSimplePic p isSimplePic (Color _ c p) = not (isOpaque c) || isSimplePic p isSimplePic _ = True isOpaque :: Color -> Bool isOpaque (RGBA _ _ _ 1) = True isOpaque _ = False drawPolygon :: MonadCanvas m => [Point] -> Bool -> DrawState -> m () drawPolygon ps smooth ds = fillFigure ds $ followPath ps True smooth polygonContains :: MonadCanvas m => [Point] -> Bool -> DrawState -> Point -> m Bool polygonContains ps smooth ds p = do withDS ds $ followPath ps True smooth CM.isPointInPath p drawPath :: MonadCanvas m => [Point] -> Double -> Bool -> Bool -> DrawState -> m () drawPath ps w closed smooth ds = drawFigure ds w $ followPath ps closed smooth pathContains :: MonadCanvas m => [Point] -> Double -> Bool -> Bool -> DrawState -> Point -> m Bool pathContains ps w closed smooth ds p = do s <- pixelSize drawFigure ds (max s w) $ followPath ps closed smooth CM.isPointInStroke p drawSector :: MonadCanvas m => Double -> Double -> Double -> DrawState -> m () drawSector b e r ds = do fillFigure ds $ CM.arc 0 0 (abs r) b e (b > e) >> CM.lineTo (0, 0) sectorContains :: MonadCanvas m => Double -> Double -> Double -> DrawState -> Point -> m Bool sectorContains b e r ds p = do withDS ds $ CM.arc 0 0 (abs r) b e (b > e) >> CM.lineTo (0, 0) CM.isPointInPath p drawArc :: MonadCanvas m => Double -> Double -> Double -> Double -> DrawState -> m () drawArc b e r w ds = do drawFigure ds w $ CM.arc 0 0 (abs r) b e (b > e) arcContains :: MonadCanvas m => Double -> Double -> Double -> Double -> DrawState -> Point -> m Bool arcContains b e r w ds p = do s <- pixelSize let width = max s w CM.lineWidth width drawFigure ds width $ CM.arc 0 0 (abs r) b e (b > e) CM.isPointInStroke p drawText :: MonadCanvas m => TextStyle -> Font -> Text -> DrawState -> m () drawText sty fnt txt ds = withDS ds $ do CM.scale (1/25) (-1/25) applyColor ds CM.font (fontString sty fnt) CM.fillText txt (0, 0) textContains :: MonadCanvas m => TextStyle -> Font -> Text -> DrawState -> Point -> m Bool textContains sty fnt txt ds p = do CM.font (fontString sty fnt) width <- (/ 25) <$> CM.measureText txt let height = 1 -- constant, defined in fontString withDS ds $ CM.rect ((-0.5) * width) ((-0.5) * height) width height CM.isPointInPath p fontString :: TextStyle -> Font -> Text fontString style font = stylePrefix style <> "25px " <> fontName font where stylePrefix Plain = "" stylePrefix Bold = "bold " stylePrefix Italic = "italic " fontName SansSerif = "sans-serif" fontName Serif = "serif" fontName Monospace = "monospace" fontName Handwriting = "cursive" fontName Fancy = "fantasy" fontName (NamedFont txt) = "\"" <> T.filter (/= '"') txt <> "\"" drawImage :: MonadCanvas m => Text -> Text -> Double -> Double -> DrawState -> m () drawImage name url imgw imgh ds = case getColorDS ds of -- Fast path: draw in original color. Nothing -> withDS ds $ do CM.scale 1 (-1) CM.drawImgURL name url imgw imgh -- Slow path: draw in a different color via an offscreen canvas. Just oc -> viaOffscreen oc $ \c -> do setColor c w <- CM.getScreenWidth h <- CM.getScreenHeight CM.fillRect (-w/2) (-h/2) w h CM.globalCompositeOperation "destination-in" withDS ds $ do CM.scale (1) (-1) CM.drawImgURL name url imgw imgh imageContains :: MonadCanvas m => Text -> Text -> Double -> Double -> DrawState -> Point -> m Bool imageContains _ _ imgw imgh ds p = withDS ds $ do CM.rect (-imgw / 2) (-imgh / 2) imgw imgh CM.isPointInPath p coordinatePlanePic :: Picture coordinatePlanePic = axes <> numbers <> guidelines where xline y = colored (RGBA 0 0 0 0.25) $ polyline [(-10, y), (10, y)] xaxis = colored (RGBA 0 0 0 0.75) $ polyline [(-10, 0), (10, 0)] axes = xaxis <> rotated (pi / 2) xaxis xguidelines = pictures [xline k | k <- [-10,-9 .. 10]] guidelines = xguidelines <> rotated (pi / 2) xguidelines numbers = xnumbers <> ynumbers xnumbers = pictures [ translated (fromIntegral k) 0.3 (scaled 0.5 0.5 (lettering (T.pack (show k)))) | k <- [-9,-8 .. 9] , k /= (0 :: Int) ] ynumbers = pictures [ translated 0.3 (fromIntegral k) (scaled 0.5 0.5 (lettering (T.pack (show k)))) | k <- [-9,-8 .. 9] , k /= (0 :: Int) ] -------------------------------------------------------------------------------- clearScreen :: MonadCanvas m => m () clearScreen = do w <- CM.getScreenWidth h <- CM.getScreenHeight px <- pixelSize CM.fillColor 255 255 255 1 CM.fillRect (-w/2 * px) (-h/2 * px) (w * px) (h * px) drawFrame :: MonadCanvas m => Picture -> m () drawFrame pic = clearScreen >> drawPicture pic initialDS pixelSize :: MonadCanvas m => m Double pixelSize = do cw <- CM.getScreenWidth ch <- CM.getScreenHeight return $ max (20 / realToFrac cw) (20 / realToFrac ch) setupScreenContext :: MonadCanvas m => Int -> Int -> m () setupScreenContext cw ch = do CM.translate (realToFrac cw / 2) (realToFrac ch / 2) s <- pixelSize CM.scale (1/s) (-1/s) CM.lineWidth 0 CM.textCenter CM.textMiddle -------------------------------------------------------------------------------- -- A NodeId a unique id for each node in a Picture, chosen by the order the node -- appears in DFS. Always >=0. newtype NodeId = NodeId { getNodeId :: Int} deriving (Eq, Ord, Enum, Show) getChildNodes :: Picture -> [Picture] getChildNodes (Color _ _ p) = [p] getChildNodes (Translate _ _ _ p) = [p] getChildNodes (Scale _ _ _ p) = [p] getChildNodes (Dilate _ _ p) = [p] getChildNodes (Rotate _ _ p) = [p] getChildNodes (Reflect _ _ p) = [p] getChildNodes (Clip _ _ _ p) = [p] getChildNodes (Pictures _ ps) = ps getChildNodes (PictureAnd _ ps) = ps getChildNodes _ = [] findTopShape :: MonadCanvas m => DrawState -> Picture -> Double -> Double -> m (Maybe NodeId) findTopShape ds pic x y = do (found, n) <- searchSingle ds pic x y return $ if found then Just (NodeId n) else Nothing where searchSingle ds (Color _ _ p) x y = fmap (+ 1) <$> searchSingle ds p x y searchSingle ds (Translate _ dx dy p) x y = fmap (+ 1) <$> searchSingle (translateDS dx dy ds) p x y searchSingle ds (Scale _ sx sy p) x y = fmap (+ 1) <$> searchSingle (scaleDS sx sy ds) p x y searchSingle ds (Dilate _ k p) x y = fmap (+ 1) <$> searchSingle (scaleDS k k ds) p x y searchSingle ds (Rotate _ a p) x y = fmap (+ 1) <$> searchSingle (rotateDS a ds) p x y searchSingle ds (Reflect _ a p) x y = fmap (+ 1) <$> searchSingle (reflectDS a ds) p x y searchSingle ds (Clip _ w h p) x y = do inClip <- polygonContains (rectangleVertices w h) False ds (x, y) fmap (+ 1) <$> case inClip of True -> searchSingle ds p x y False -> return (False, countNodes p) searchSingle ds (Pictures _ ps) x y = fmap (+ 1) <$> searchMulti ds ps x y searchSingle ds (PictureAnd _ ps) x y = fmap (+ 1) <$> searchMulti ds ps x y searchSingle ds p x y = do contained <- pictureContains p ds (x, y) case contained of True -> return (True, 0) False -> return (False, 1) searchMulti _ [] _ _ = return (False, 0) searchMulti ds (pic:pics) x y = do (found, count) <- searchSingle ds pic x y case found of True -> return (True, count) False -> fmap (+ count) <$> searchMulti ds pics x y countNodes p = 1 + sum (map countNodes (getChildNodes p)) -- If a picture is found, the result will include an array of the base picture -- and all transformations. findTopShapeFromPoint :: MonadCanvas m => Point -> Picture -> m (Maybe NodeId) findTopShapeFromPoint (x, y) pic = do cw <- CM.getScreenWidth ch <- CM.getScreenHeight img <- CM.newImage (round cw) (round ch) CM.withImage img $ do setupScreenContext (round cw) (round ch) findTopShape initialDS pic x y trim :: Int -> String -> String trim x y | x >= length y = y | otherwise = take mid y ++ "..." ++ (reverse $ take mid $ reverse y) where mid = (x - 3) `div` 2 showFloat :: Bool -> Double -> String showFloat needNegParens x | needNegParens && x < 0 = "(" ++ result ++ ")" | otherwise = result where result = stripZeros (showFFloatAlt (Just 4) x "") stripZeros = reverse . dropWhile (== '.') . dropWhile (== '0') . reverse showPoints :: [Point] -> String showPoints pts = "[" ++ intercalate ", " [ "(" ++ showFloat False x ++ ", " ++ showFloat False y ++ ")" | (x, y) <- pts ] ++ "]" showColor :: Color -> String showColor c@(RGBA r g b a) | c == black = "black" | c == white = "white" | c == red = "red" | c == green = "green" | c == blue = "blue" | c == yellow = "yellow" | c == orange = "orange" | c == brown = "brown" | c == pink = "pink" | c == purple = "purple" | c == gray = "gray" | haskellMode, a == 1 = printf "(RGB %s %s %s)" (showFloat True r) (showFloat True g) (showFloat True b) | a == 1 = printf "RGB(%s, %s, %s)" (showFloat False r) (showFloat False g) (showFloat False b) | haskellMode = printf "(RGBA %s %s %s %s)" (showFloat True r) (showFloat True g) (showFloat True b) (showFloat True a) | otherwise = printf "RGBA(%s, %s, %s, %s)" (showFloat False r) (showFloat False g) (showFloat False b) (showFloat False a) describePicture :: Picture -> String describePicture (Rectangle _ w h) | haskellMode = printf "rectangle %s %s" (showFloat True w) (showFloat True h) | otherwise = printf "rectangle(%s, %s)" (showFloat False w) (showFloat False h) describePicture (SolidRectangle _ w h) | haskellMode = printf "solidRectangle %s %s" (showFloat True w) (showFloat True h) | otherwise = printf "solidRectangle(%s, %s)" (showFloat False w) (showFloat False h) describePicture (ThickRectangle _ lw w h) | haskellMode = printf "thickRectangle %s %s %s" (showFloat True lw) (showFloat True w) (showFloat True h) | otherwise = printf "thickRectangle(%s, %s, %s)" (showFloat False w) (showFloat False h) (showFloat False lw) describePicture (Circle _ r) | haskellMode = printf "circle %s" (showFloat True r) | otherwise = printf "circle(%s)" (showFloat False r) describePicture (SolidCircle _ r) | haskellMode = printf "solidCircle %s" (showFloat True r) | otherwise = printf "solidCircle(%s)" (showFloat False r) describePicture (ThickCircle _ lw r) | haskellMode = printf "thickCircle %s %s" (showFloat True lw) (showFloat True r) | otherwise = printf "thickCircle(%s, %s)" (showFloat False r) (showFloat False lw) describePicture (SolidPolygon _ pts) | haskellMode = printf "solidPolygon %s" (showPoints pts) | otherwise = printf "solidPolygon(%s)" (showPoints pts) describePicture (SolidClosedCurve _ pts) | haskellMode = printf "solidClosedCurve %s" (showPoints pts) | otherwise = printf "solidClosedCurve(%s)" (showPoints pts) describePicture (Polygon _ pts) | haskellMode = printf "polygon %s" (showPoints pts) | otherwise = printf "polygon(%s)" (showPoints pts) describePicture (ThickPolygon _ pts w) | haskellMode = printf "thickPolygon %s %s" (showFloat True w) (showPoints pts) | otherwise = printf "thickPolygon(%s, %s)" (showPoints pts) (showFloat False w) describePicture (ClosedCurve _ pts) | haskellMode = printf "closedCurve %s" (showPoints pts) | otherwise = printf "closedCurve(%s)" (showPoints pts) describePicture (ThickClosedCurve _ pts w) | haskellMode = printf "thickClosedCurve %s %s" (showFloat True w) (showPoints pts) | otherwise = printf "thickClosedCurve(%s, %s)" (showPoints pts) (showFloat False w) describePicture (Polyline _ pts) | haskellMode = printf "polyline %s" (showPoints pts) | otherwise = printf "polyline(%s)" (showPoints pts) describePicture (ThickPolyline _ pts w) | haskellMode = printf "thickPolyline %s %s" (showFloat True w) (showPoints pts) | otherwise = printf "thickPolyline(%s, %s)" (showPoints pts) (showFloat False w) describePicture (Curve _ pts) | haskellMode = printf "curve %s" (showPoints pts) | otherwise = printf "curve(%s)" (showPoints pts) describePicture (ThickCurve _ pts w) | haskellMode = printf "thickCurve %s %s" (showFloat True w) (showPoints pts) | otherwise = printf "thickCurve(%s, %s)" (showPoints pts) (showFloat False w) describePicture (Sector _ b e r) | haskellMode = printf "sector %s %s %s" (showFloat True b) (showFloat True e) (showFloat True r) | otherwise = printf "sector(%s°, %s°, %s)" (showFloat False (180 * b / pi)) (showFloat False (180 * e / pi)) (showFloat False r) describePicture (Arc _ b e r) | haskellMode = printf "arc %s %s %s" (showFloat True b) (showFloat True e) (showFloat True r) | otherwise = printf "arc(%s°, %s°, %s)" (showFloat False (180 * b / pi)) (showFloat False (180 * e / pi)) (showFloat False r) describePicture (ThickArc _ b e r w) | haskellMode = printf "thickArc %s %s %s %s" (showFloat True w) (showFloat True b) (showFloat True e) (showFloat True r) | otherwise = printf "thickArc(%s°, %s°, %s, %s)" (showFloat False (180 * b / pi)) (showFloat False (180 * e / pi)) (showFloat False r) (showFloat False w) describePicture (Lettering _ txt) | haskellMode = printf "lettering %s" (show txt) | otherwise = printf "lettering(%s)" (show txt) describePicture (Blank _) = "blank" describePicture (StyledLettering _ style font txt) | haskellMode = printf "styledLettering %s %s %s" (showsPrec 10 style "") (showsPrec 10 font "") (show txt) | otherwise = printf "styledLettering(%s, %s, %s)" (show txt) (show font) (show style) describePicture (Color _ c _) | haskellMode = printf "colored %s" (showColor c) | otherwise = printf "colored(..., %s)" (showColor c) describePicture (Translate _ x y _) | haskellMode = printf "translated %s %s" (showFloat True x) (showFloat True y) | otherwise = printf "translated(..., %s, %s)" (showFloat False x) (showFloat False y) describePicture (Scale _ x y _) | haskellMode = printf "scaled %s %s" (showFloat True x) (showFloat True y) | otherwise = printf "scaled(..., %s, %s)" (showFloat False x) (showFloat False y) describePicture (Rotate _ angle _) | haskellMode = printf "rotated %s" (showFloat True angle) | otherwise = printf "rotated(..., %s°)" (showFloat False (180 * angle / pi)) describePicture (Reflect _ angle _) | haskellMode = printf "reflected %s" (showFloat True angle) | otherwise = printf "reflected(..., %s°)" (showFloat False (180 * angle / pi)) describePicture (Clip _ x y _) | haskellMode = printf "clipped %s %s" (showFloat True x) (showFloat True y) | otherwise = printf "rotated(..., %s, %s)" (showFloat False x) (showFloat False y) describePicture (Dilate _ k _) | haskellMode = printf "dilated %s" (showFloat True k) | otherwise = printf "dilated(..., %s)" (showFloat False k) describePicture (Sketch _ name _ _ _) = T.unpack name describePicture (CoordinatePlane _) = "coordinatePlane" describePicture (Pictures _ _) | haskellMode = "pictures" | otherwise = "pictures(...)" describePicture (PictureAnd _ _) | haskellMode = "(&)" | otherwise = "... & ..." getPictureSrcLoc :: Picture -> Maybe SrcLoc getPictureSrcLoc (SolidPolygon loc _) = loc getPictureSrcLoc (SolidClosedCurve loc _) = loc getPictureSrcLoc (Polygon loc _) = loc getPictureSrcLoc (ThickPolygon loc _ _) = loc getPictureSrcLoc (Rectangle loc _ _) = loc getPictureSrcLoc (SolidRectangle loc _ _) = loc getPictureSrcLoc (ThickRectangle loc _ _ _) = loc getPictureSrcLoc (ClosedCurve loc _) = loc getPictureSrcLoc (ThickClosedCurve loc _ _) = loc getPictureSrcLoc (Circle loc _) = loc getPictureSrcLoc (SolidCircle loc _) = loc getPictureSrcLoc (ThickCircle loc _ _) = loc getPictureSrcLoc (Polyline loc _) = loc getPictureSrcLoc (ThickPolyline loc _ _) = loc getPictureSrcLoc (Curve loc _) = loc getPictureSrcLoc (ThickCurve loc _ _) = loc getPictureSrcLoc (Sector loc _ _ _) = loc getPictureSrcLoc (Arc loc _ _ _) = loc getPictureSrcLoc (ThickArc loc _ _ _ _) = loc getPictureSrcLoc (Lettering loc _) = loc getPictureSrcLoc (Blank loc) = loc getPictureSrcLoc (StyledLettering loc _ _ _) = loc getPictureSrcLoc (Color loc _ _) = loc getPictureSrcLoc (Translate loc _ _ _) = loc getPictureSrcLoc (Scale loc _ _ _) = loc getPictureSrcLoc (Dilate loc _ _) = loc getPictureSrcLoc (Rotate loc _ _) = loc getPictureSrcLoc (Reflect loc _ _) = loc getPictureSrcLoc (Clip loc _ _ _) = loc getPictureSrcLoc (Sketch loc _ _ _ _) = loc getPictureSrcLoc (CoordinatePlane loc) = loc getPictureSrcLoc (Pictures loc _) = loc getPictureSrcLoc (PictureAnd loc _) = loc #ifdef ghcjs_HOST_OS -------------------------------------------------------------------------------- -- GHCJS implementation of drawing -- Debug Mode logic foreign import javascript unsafe "$1.drawImage($2, $3, $4, $5, $6);" canvasDrawImage :: Canvas.Context -> Element -> Int -> Int -> Int -> Int -> IO () foreign import javascript unsafe "$1.getContext('2d', { alpha: false })" getCodeWorldContext :: Canvas.Canvas -> IO Canvas.Context foreign import javascript unsafe "showCanvas()" showCanvas :: IO () canvasFromElement :: Element -> Canvas.Canvas canvasFromElement = Canvas.Canvas . unElement elementFromCanvas :: Canvas.Canvas -> Element elementFromCanvas = pFromJSVal . jsval createFrameRenderer :: Element -> IO (Picture -> IO ()) createFrameRenderer canvas = do offscreenCanvas <- Canvas.create 500 500 screen <- getCodeWorldContext (canvasFromElement canvas) return $ \pic -> withoutPreemption $ do setCanvasSize (elementFromCanvas offscreenCanvas) canvas rect <- getBoundingClientRect canvas withScreen (elementFromCanvas offscreenCanvas) rect (drawFrame pic) cw <- ClientRect.getWidth rect ch <- ClientRect.getHeight rect when (cw > 0.5 && ch > 0.5) $ canvasDrawImage screen (elementFromCanvas offscreenCanvas) 0 0 (round cw) (round ch) getTime :: IO Double getTime = (/ 1000) <$> Performance.now nextFrame :: IO Double nextFrame = (/ 1000) <$> waitForAnimationFrame data Node = Node { nodeId :: NodeId , nodeName :: String , nodeSrcLoc :: Maybe SrcLoc , nodeSubs :: SubNodes } data SubNodes = NoSubNodes | SubNode Node | SubNodes [Node] instance ToJSON Node where toJSON (Node id name srcLoc subs) = object $ ["id" .= getNodeId id , "name" .= name] <> srcLoc' <> subs' where srcLoc' = case srcLoc of Nothing -> [] Just loc -> [ "startLine" .= srcLocStartLine loc , "startCol" .= srcLocStartCol loc , "endLine" .= srcLocEndLine loc , "endCol" .= srcLocEndCol loc ] subs' = case subs of NoSubNodes -> [] SubNode node -> ["picture" .= node] SubNodes nodes -> ["pictures" .= nodes] pictureToNode :: Picture -> Node pictureToNode = flip State.evalState (NodeId 0) . go where go pic = case pic of Pictures _ ps -> nodeWithChildren pic ps PictureAnd _ ps -> nodeWithChildren pic ps Color _ _ p -> nodeWithChild pic p Translate _ _ _ p -> nodeWithChild pic p Scale _ _ _ p -> nodeWithChild pic p Dilate _ _ p -> nodeWithChild pic p Rotate _ _ p -> nodeWithChild pic p Reflect _ _ p -> nodeWithChild pic p Clip _ _ _ p -> nodeWithChild pic p SolidPolygon _ _ -> leafNode pic SolidClosedCurve _ _ -> leafNode pic Polygon _ _ -> leafNode pic ThickPolygon _ _ _ -> leafNode pic Rectangle _ _ _ -> leafNode pic SolidRectangle _ _ _ -> leafNode pic ThickRectangle _ _ _ _ -> leafNode pic ClosedCurve _ _ -> leafNode pic ThickClosedCurve _ _ _ -> leafNode pic Polyline _ _ -> leafNode pic ThickPolyline _ _ _ -> leafNode pic Curve _ _ -> leafNode pic ThickCurve _ _ _ -> leafNode pic Circle _ _ -> leafNode pic SolidCircle _ _ -> leafNode pic ThickCircle _ _ _ -> leafNode pic Sector _ _ _ _ -> leafNode pic Arc _ _ _ _ -> leafNode pic ThickArc _ _ _ _ _ -> leafNode pic StyledLettering _ _ _ _ -> leafNode pic Lettering _ _ -> leafNode pic CoordinatePlane _ -> leafNode pic Sketch _ _ _ _ _ -> leafNode pic Blank _ -> leafNode pic nodeWithChildren pic subs = node pic (SubNodes <$> traverse go subs) nodeWithChild pic sub = node pic (SubNode <$> go sub) leafNode pic = node pic (pure NoSubNodes) node pic getSubNodes = do nodeId <- State.get <* State.modify' succ let nodeName = trim 80 . describePicture $ pic let nodeSrcLoc = getPictureSrcLoc pic nodeSubs <- getSubNodes pure Node{..} foreign import javascript unsafe "/\\bmode=haskell\\b/.test(location.search)" haskellMode :: Bool withScreen :: Element -> ClientRect.ClientRect -> CanvasM a -> IO a withScreen canvas rect action = do cw <- realToFrac <$> ClientRect.getWidth rect ch <- realToFrac <$> ClientRect.getHeight rect ctx <- getCodeWorldContext (canvasFromElement canvas) runCanvasM (cw, ch) ctx $ CM.saveRestore $ do setupScreenContext (round cw) (round ch) action setCanvasSize :: Element -> Element -> IO () setCanvasSize target canvas = do rect <- getBoundingClientRect canvas cx <- ClientRect.getWidth rect cy <- ClientRect.getHeight rect setAttribute target ("width" :: JSString) (show (round cx :: Int)) setAttribute target ("height" :: JSString) (show (round cy :: Int)) #else -------------------------------------------------------------------------------- -- Stand-alone implementation of drawing haskellMode :: Bool haskellMode = True type Port = Int readPortFromEnv :: String -> Port -> IO Port readPortFromEnv envName defaultPort = do ms <- lookupEnv envName return (fromMaybe defaultPort (ms >>= readMaybe)) runBlankCanvas :: (Canvas.DeviceContext -> IO ()) -> IO () runBlankCanvas act = do port <- readPortFromEnv "CODEWORLD_API_PORT" 3000 let options = (fromIntegral port) { Canvas.events = ["mousedown", "mouseup", "mousemove", "keydown", "keyup"] } putStrLn $ printf "Open me on http://127.0.0.1:%d/" (Canvas.port options) Canvas.blankCanvas options $ \context -> do putStrLn "Program is starting..." act context #endif -------------------------------------------------------------------------------- -- Common event handling and core interaction code keyCodeToText :: Word -> Text keyCodeToText n = case n of _ | n >= 47 && n <= 90 -> fromAscii n _ | n >= 96 && n <= 105 -> fromNum (n - 96) _ | n >= 112 && n <= 135 -> "F" <> fromNum (n - 111) 3 -> "Cancel" 6 -> "Help" 8 -> "Backspace" 9 -> "Tab" 12 -> "5" 13 -> "Enter" 16 -> "Shift" 17 -> "Ctrl" 18 -> "Alt" 19 -> "Break" 20 -> "CapsLock" 27 -> "Esc" 32 -> " " 33 -> "PageUp" 34 -> "PageDown" 35 -> "End" 36 -> "Home" 37 -> "Left" 38 -> "Up" 39 -> "Right" 40 -> "Down" 42 -> "*" 43 -> "+" 44 -> "PrintScreen" 45 -> "Insert" 46 -> "Delete" 47 -> "Help" 91 -> "OS" 92 -> "OS" 93 -> "ContextMenu" 106 -> "*" 107 -> "+" 108 -> "," 109 -> "-" 110 -> "." 111 -> "/" 144 -> "NumLock" 145 -> "ScrollLock" 173 -> "-" 186 -> ";" 187 -> "=" 188 -> "," 189 -> "-" 190 -> "." 191 -> "/" 192 -> "`" 193 -> "IntlRo" 194 -> "," 219 -> "[" 220 -> "\\" 221 -> "]" 222 -> "'" 225 -> "AltGraph" 255 -> "IntlYen" _ -> "Unknown:" <> fromNum n where fromAscii n = T.singleton (chr (fromIntegral n)) fromNum n = T.pack (show n) isUniversallyConstant :: (a -> s -> s) -> s -> Bool isUniversallyConstant f old = unsafePerformIO $ falseOr $ do oldName <- makeStableName $! old genName <- makeStableName $! f undefined old return (genName == oldName) where falseOr x = x `catch` \(_ :: SomeException) -> return False ifDifferent :: (s -> s) -> s -> Maybe s ifDifferent f s0 = unsafePerformIO $ do oldName <- makeStableName $! s0 newName <- makeStableName $! s1 if newName == oldName then return Nothing else return (Just s1) where s1 = f s0 modifyMVarIfDifferent :: MVar s -> (s -> s) -> IO Bool modifyMVarIfDifferent var f = modifyMVar var $ \s0 -> do case ifDifferent f s0 of Nothing -> return (s0, False) Just s1 -> return (s1, True) data GameToken = FullToken { tokenDeployHash :: Text , tokenNumPlayers :: Int , tokenInitial :: StaticKey , tokenStep :: StaticKey , tokenEvent :: StaticKey , tokenDraw :: StaticKey } | SteplessToken { tokenDeployHash :: Text , tokenNumPlayers :: Int , tokenInitial :: StaticKey , tokenEvent :: StaticKey , tokenDraw :: StaticKey } | PartialToken { tokenDeployHash :: Text } deriving (Generic) deriving instance Generic Fingerprint instance Serialize Fingerprint instance Serialize GameToken #ifdef ghcjs_HOST_OS -------------------------------------------------------------------------------- -- GHCJS event handling and core interaction code screenCoordsToPoint :: Element -> Double -> Double -> IO Point screenCoordsToPoint canvas sx sy = do rect <- getBoundingClientRect canvas cx <- realToFrac <$> ClientRect.getLeft rect cy <- realToFrac <$> ClientRect.getTop rect cw <- realToFrac <$> ClientRect.getWidth rect ch <- realToFrac <$> ClientRect.getHeight rect let unitLen = min cw ch / 20 let midx = cx + cw / 2 let midy = cy + ch / 2 return ((sx - midx) / unitLen, (midy - sy) / unitLen) getMousePos :: IsMouseEvent e => Element -> EventM w e Point getMousePos canvas = do (ix, iy) <- mouseClientXY liftIO $ screenCoordsToPoint canvas (fromIntegral ix) (fromIntegral iy) onEvents :: Element -> (Event -> IO ()) -> IO () onEvents canvas handler = do Just window <- currentWindow _ <- on window keyDown $ do code <- getKeyCode =<< event let keyName = keyCodeToText code when (keyName /= "") $ do liftIO $ handler (KeyPress keyName) preventDefault stopPropagation key <- getKey =<< event when (T.length key == 1) $ do liftIO $ handler (TextEntry key) preventDefault stopPropagation _ <- on window keyUp $ do code <- getKeyCode =<< event let keyName = keyCodeToText code when (keyName /= "") $ do liftIO $ handler (KeyRelease keyName) preventDefault stopPropagation _ <- on window mouseDown $ do pos <- getMousePos canvas liftIO $ handler (PointerPress pos) _ <- on window mouseUp $ do pos <- getMousePos canvas liftIO $ handler (PointerRelease pos) _ <- on window mouseMove $ do pos <- getMousePos canvas liftIO $ handler (PointerMovement pos) return () encodeEvent :: (Timestamp, Maybe Event) -> String encodeEvent = show decodeEvent :: String -> Maybe (Timestamp, Maybe Event) decodeEvent = readMaybe data GameState s = Main (UIState SMain) | Connecting WS.WebSocket (UIState SConnect) | Waiting WS.WebSocket GameId PlayerId (UIState SWait) | Running WS.WebSocket GameId Timestamp PlayerId (Future s) gameTime :: GameState s -> Timestamp -> Double gameTime (Running _ _ tstart _ _) t = t - tstart gameTime _ _ = 0 -- It's worth trying to keep the canonical animation rate exactly representable -- as a float, to minimize the chance of divergence due to rounding error. gameRate :: Double gameRate = 1 / 16 gameStep :: (Double -> s -> s) -> Double -> GameState s -> GameState s gameStep _ t (Main s) = Main (CUI.step t s) gameStep _ t (Connecting ws s) = Connecting ws (CUI.step t s) gameStep _ t (Waiting ws gid pid s) = Waiting ws gid pid (CUI.step t s) gameStep step t (Running ws gid tstart pid s) = Running ws gid tstart pid (currentTimePasses step gameRate (t - tstart) s) gameDraw :: (Double -> s -> s) -> (PlayerId -> s -> Picture) -> GameState s -> Timestamp -> Picture gameDraw _ _ (Main s) _ = CUI.picture s gameDraw _ _ (Connecting _ s) _ = CUI.picture s gameDraw _ _ (Waiting _ _ _ s) _ = CUI.picture s gameDraw step draw (Running _ _ tstart pid s) t = draw pid (currentState step gameRate (t - tstart) s) handleServerMessage :: Int -> (StdGen -> s) -> (Double -> s -> s) -> (PlayerId -> Event -> s -> s) -> MVar (GameState s) -> ServerMessage -> IO () handleServerMessage numPlayers initial stepHandler eventHandler gsm sm = do modifyMVar_ gsm $ \gs -> do t <- getTime case (sm, gs) of (GameAborted, _) -> return initialGameState (JoinedAs pid gid, Connecting ws s) -> return (Waiting ws gid pid (CUI.startWaiting gid s)) (PlayersWaiting m n, Waiting ws gid pid s) -> return (Waiting ws gid pid (CUI.updatePlayers n m s)) (Started, Waiting ws gid pid _) -> do let s = initFuture (initial (mkStdGen (hash gid))) numPlayers return (Running ws gid t pid s) (OutEvent pid eo, Running ws gid tstart mypid s) -> case decodeEvent eo of Just (t', event) -> let ours = pid == mypid func = eventHandler pid <$> event -- might be a ping (Nothing) result | ours = s -- we already took care of our events | otherwise = addEvent stepHandler gameRate mypid t' func s in return (Running ws gid tstart mypid result) Nothing -> return (Running ws gid tstart mypid s) _ -> return gs return () gameHandle :: Int -> (StdGen -> s) -> (Double -> s -> s) -> (PlayerId -> Event -> s -> s) -> GameToken -> MVar (GameState s) -> Event -> IO () gameHandle numPlayers initial stepHandler eventHandler token gsm event = do gs <- takeMVar gsm case gs of Main s -> case CUI.event event s of ContinueMain s' -> do putMVar gsm (Main s') Create s' -> do ws <- connectToGameServer (handleServerMessage numPlayers initial stepHandler eventHandler gsm) sendClientMessage ws (NewGame numPlayers (encode token)) putMVar gsm (Connecting ws s') Join gid s' -> do ws <- connectToGameServer (handleServerMessage numPlayers initial stepHandler eventHandler gsm) sendClientMessage ws (JoinGame gid (encode token)) putMVar gsm (Connecting ws s') Connecting ws s -> case CUI.event event s of ContinueConnect s' -> do putMVar gsm (Connecting ws s') CancelConnect s' -> do WS.close Nothing Nothing ws putMVar gsm (Main s') Waiting ws gid pid s -> case CUI.event event s of ContinueWait s' -> do putMVar gsm (Waiting ws gid pid s') CancelWait s' -> do WS.close Nothing Nothing ws putMVar gsm (Main s') Running ws gid tstart pid f -> do t <- getTime let gameState0 = currentState stepHandler gameRate (t - tstart) f let eventFun = eventHandler pid event case ifDifferent eventFun gameState0 of Nothing -> putMVar gsm gs Just _ -> do sendClientMessage ws (InEvent (encodeEvent (gameTime gs t, Just event))) let f1 = addEvent stepHandler gameRate pid (t - tstart) (Just eventFun) f putMVar gsm (Running ws gid tstart pid f1) getWebSocketURL :: IO JSString getWebSocketURL = do loc <- Loc.getWindowLocation proto <- Loc.getProtocol loc hostname <- Loc.getHostname loc let url = case proto of "http:" -> "ws://" <> hostname <> ":9160/gameserver" "https:" -> "wss://" <> hostname <> "/gameserver" _ -> error "Unrecognized protocol" return url connectToGameServer :: (ServerMessage -> IO ()) -> IO WS.WebSocket connectToGameServer handleServerMessage = do let handleWSRequest m = do maybeSM <- decodeServerMessage m case maybeSM of Nothing -> return () Just sm -> handleServerMessage sm wsURL <- getWebSocketURL let req = WS.WebSocketRequest { url = wsURL , protocols = [] , onClose = Just $ \_ -> handleServerMessage GameAborted , onMessage = Just handleWSRequest } WS.connect req where decodeServerMessage :: WS.MessageEvent -> IO (Maybe ServerMessage) decodeServerMessage m = case WS.getData m of WS.StringData str -> do return $ readMaybe (Data.JSString.unpack str) _ -> return Nothing sendClientMessage :: WS.WebSocket -> ClientMessage -> IO () sendClientMessage ws msg = WS.send (encodeClientMessage msg) ws where encodeClientMessage :: ClientMessage -> JSString encodeClientMessage m = Data.JSString.pack (show m) initialGameState :: GameState s initialGameState = Main CUI.initial foreign import javascript unsafe "cw$deterministic_math();" enableDeterministicMath :: IO () runGame :: GameToken -> Int -> (StdGen -> s) -> (Double -> s -> s) -> (Int -> Event -> s -> s) -> (Int -> s -> Picture) -> IO () runGame token numPlayers initial stepHandler eventHandler drawHandler = do enableDeterministicMath let fullStepHandler dt = stepHandler dt . eventHandler (-1) (TimePassing dt) Just window <- currentWindow Just doc <- currentDocument Just canvas <- getElementById doc ("screen" :: JSString) setCanvasSize canvas canvas _ <- on window resize $ do liftIO $ setCanvasSize canvas canvas showCanvas frameRenderer <- createFrameRenderer canvas currentGameState <- newMVar initialGameState onEvents canvas $ gameHandle numPlayers initial fullStepHandler eventHandler token currentGameState let go t0 lastFrame = do gs <- readMVar currentGameState let pic = gameDraw fullStepHandler drawHandler gs t0 picFrame <- makeStableName $! pic when (picFrame /= lastFrame) $ frameRenderer pic t1 <- nextFrame modifyMVar_ currentGameState $ return . gameStep fullStepHandler t1 go t1 picFrame t0 <- nextFrame nullFrame <- makeStableName undefined go t0 nullFrame getDeployHash :: IO Text getDeployHash = pFromJSVal <$> js_getDeployHash foreign import javascript "/[&?]dhash=(.{22})/.exec(window.location.search)[1]" js_getDeployHash :: IO JSVal propagateErrors :: ThreadId -> IO () -> IO () propagateErrors tid action = action `catch` \ (e :: SomeException) -> throwTo tid e run :: s -> (Double -> s -> s) -> (e -> s -> s) -> (s -> Picture) -> (Double -> e) -> IO (e -> IO (), IO s) run initial stepHandler eventHandler drawHandler injectTime = do let fullStepHandler dt = stepHandler dt . eventHandler (injectTime dt) Just window <- currentWindow Just doc <- currentDocument Just canvas <- getElementById doc ("screen" :: JSString) needsRedraw <- newMVar () _ <- on window resize $ void $ liftIO $ do setCanvasSize canvas canvas tryPutMVar needsRedraw () setCanvasSize canvas canvas showCanvas frameRenderer <- createFrameRenderer canvas currentState <- newMVar initial eventHappened <- newMVar () let go t0 lastFrame lastStateName needsTime = do pic <- drawHandler <$> readMVar currentState picFrame <- makeStableName $! pic when (picFrame /= lastFrame) $ frameRenderer pic t1 <- case needsTime of True -> do t1 <- nextFrame let dt = min (t1 - t0) 0.25 when (dt > 0) $ void $ modifyMVarIfDifferent currentState (fullStepHandler dt) return t1 False -> do takeMVar eventHappened nextFrame nextState <- readMVar currentState nextStateName <- makeStableName $! nextState let nextNeedsTime = nextStateName /= lastStateName || needsTime && not (isUniversallyConstant fullStepHandler nextState) redrawResult <- tryTakeMVar needsRedraw nextFrame <- case redrawResult of Nothing -> return picFrame Just () -> makeStableName undefined go t1 nextFrame nextStateName nextNeedsTime t0 <- nextFrame nullFrame <- makeStableName undefined initialStateName <- makeStableName $! initial mainThread <- myThreadId drawThread <- forkIO $ propagateErrors mainThread $ go t0 nullFrame initialStateName True let sendEvent event = propagateErrors drawThread $ do changed <- modifyMVarIfDifferent currentState (eventHandler event) when changed $ void $ tryPutMVar eventHappened () getState = readMVar currentState return (sendEvent, getState) getNodeAtCoords :: Element -> Double -> Double -> Picture -> IO (Maybe NodeId) getNodeAtCoords canvas x y pic = do rect <- getBoundingClientRect canvas cx <- realToFrac <$> ClientRect.getLeft rect cy <- realToFrac <$> ClientRect.getTop rect cw <- realToFrac <$> ClientRect.getWidth rect ch <- realToFrac <$> ClientRect.getHeight rect -- It's safe to pass undefined for the context because -- findTopShapeFromPoint only draws to an offscreen buffer. runCanvasM (cw, ch) undefined $ findTopShapeFromPoint (x - cx, y - cy) pic drawPartialPic :: Element -> NodeId -> Picture -> IO () drawPartialPic canvas nodeId pic = do setCanvasSize canvas canvas let node = fromMaybe blank (getNode nodeId pic) frameRenderer <- createFrameRenderer canvas frameRenderer (node <> coordinatePlane) applySelectAndHighlights :: Maybe NodeId -> [NodeId] -> Picture -> Picture applySelectAndHighlights sel hs p = applyHighlights hs' p' where (p', hs') = applySelect sel (p, hs) applySelect :: Maybe NodeId -> (Picture, [NodeId]) -> (Picture, [NodeId]) applySelect Nothing (pic, highlights) = (pic, highlights) applySelect (Just (NodeId n)) (pic, highlights) = case getNode (NodeId n) pic of Nothing -> (pic, highlights) Just pic' -> (pic', [ NodeId (h - n) | NodeId h <- highlights ]) applyHighlights :: [NodeId] -> Picture -> Picture applyHighlights hs p = pictures [highlight h p | h <- hs] <> p highlight :: NodeId -> Picture -> Picture highlight n pic = case getTransformedNode n pic of Nothing -> blank Just shape -> colored (RGBA 0 0 0 0.25) shape indexNode :: Bool -> Int -> NodeId -> Picture -> Either Int Picture indexNode _ i (NodeId n) p | i == n = Right p | i > n = Left 0 indexNode True i n (Translate loc x y p) = Translate loc x y <$> indexNode True (i + 1) n p indexNode True i n (Scale loc x y p) = Scale loc x y <$> indexNode True (i + 1) n p indexNode True i n (Dilate loc k p) = Dilate loc k <$> indexNode True (i + 1) n p indexNode True i n (Rotate loc r p) = Rotate loc r <$> indexNode True (i + 1) n p indexNode True i n (Reflect loc r p) = Reflect loc r <$> indexNode True (i + 1) n p indexNode True i n (Clip loc x y p) = Clip loc x y <$> indexNode True (i + 1) n p indexNode keepTx i n p = go keepTx (i + 1) (getChildNodes p) where go _ i [] = Left i go keepTx i (pic:pics) = case indexNode keepTx i n pic of Left ii -> go keepTx ii pics Right p -> Right p getTransformedNode :: NodeId -> Picture -> Maybe Picture getTransformedNode n pic = either (const Nothing) Just (indexNode True 0 n pic) getNode :: NodeId -> Picture -> Maybe Picture getNode n pic = either (const Nothing) Just (indexNode False 0 n pic) data DebugState = DebugState { debugStateActive :: Bool , shapeHighlighted :: Maybe NodeId , shapeSelected :: Maybe NodeId } deriving (Eq, Show) debugStateInit :: DebugState debugStateInit = DebugState False Nothing Nothing startDebugState :: DebugState -> DebugState startDebugState = const (DebugState True Nothing Nothing) stopDebugState :: DebugState -> DebugState stopDebugState = const (DebugState False Nothing Nothing) highlightDebugState :: Maybe NodeId -> DebugState -> DebugState highlightDebugState n prev = case debugStateActive prev of True -> prev {shapeHighlighted = n} False -> DebugState False Nothing Nothing selectDebugState :: Maybe NodeId -> DebugState -> DebugState selectDebugState n prev = case debugStateActive prev of True -> prev {shapeSelected = n} False -> DebugState False Nothing Nothing drawDebugState :: DebugState -> Picture -> Picture -> Picture drawDebugState state inspectPic displayPic = case debugStateActive state of True -> applySelectAndHighlights (shapeSelected state) (maybeToList (shapeHighlighted state)) inspectPic False -> displayPic connectInspect :: Element -> IO Picture -> ((DebugState -> DebugState) -> IO ()) -> IO () connectInspect canvas samplePicture fireUpdate = do -- Sample the current user picture to search for a current node. getNodeCB <- syncCallback1' $ \pointJS -> do let obj = unsafeCoerce pointJS x <- pFromJSVal <$> getProp "x" obj y <- pFromJSVal <$> getProp "y" obj n <- getNodeAtCoords canvas x y =<< samplePicture return (pToJSVal (maybe (-1) getNodeId n)) -- Sample the current user picture to return the scene tree. getPicCB <- syncCallback' $ samplePicture >>= toJSVal_aeson . pictureToNode -- Sample the current user picture to draw to a canvas. drawCB <- syncCallback2 ContinueAsync $ \c n -> do let canvas = unsafeCoerce c :: Element let nodeId = NodeId (pFromJSVal n) drawPartialPic canvas nodeId =<< samplePicture -- Fire an event to change debug active state. setActiveCB <- syncCallback1 ContinueAsync $ \ active -> case pFromJSVal active of True -> fireUpdate startDebugState False -> fireUpdate stopDebugState -- Fire an event to change the highlight or selection. highlightCB <- syncCallback2 ContinueAsync $ \t n -> do let isHighlight = pFromJSVal t let nodeNum = pFromJSVal n let nodeId = if nodeNum < 0 then Nothing else Just (NodeId nodeNum) if isHighlight then fireUpdate (highlightDebugState nodeId) else fireUpdate (selectDebugState nodeId) js_initDebugMode getNodeCB setActiveCB getPicCB highlightCB drawCB foreign import javascript unsafe "initDebugMode($1,$2,$3,$4,$5)" js_initDebugMode :: Callback (JSVal -> IO JSVal) -> Callback (JSVal -> IO ()) -> Callback (IO JSVal) -> Callback (JSVal -> JSVal -> IO ()) -> Callback (JSVal -> JSVal -> IO ()) -> IO () -- Utility functions that apply a function in either the left or right half of a -- tuple. Crucially, if the function preserves sharing on its side, then the -- wrapper also preserves sharing. inLeft :: (a -> a) -> (a, b) -> (a, b) inLeft f ab = unsafePerformIO $ do let (a, b) = ab aName <- makeStableName $! a let a' = f a aName' <- makeStableName $! a' return $ if aName == aName' then ab else (a', b) inRight :: (b -> b) -> (a, b) -> (a, b) inRight f ab = unsafePerformIO $ do let (a, b) = ab bName <- makeStableName $! b let b' = f b bName' <- makeStableName $! b' return $ if bName == bName' then ab else (a, b') foreign import javascript interruptible "window.dummyVar = 0;" waitForever :: IO () -- Wraps the event and state from run so they can be paused by pressing the Inspect -- button. runInspect :: s -> (Double -> s -> s) -> (Event -> s -> s) -> (s -> Picture) -> (s -> Picture) -> IO () runInspect initial step event draw rawDraw = do -- Ensure that the first frame picture doesn't expose any type errors, -- before showing the canvas. This avoids showing a blank screen when -- there are deferred type errors that are effectively compile errors. evaluate $ rnf $ rawDraw initial Just doc <- currentDocument Just canvas <- getElementById doc ("screen" :: JSString) let debugInitial = (debugStateInit, initial) debugStep dt s@(debugState, _) = case debugStateActive debugState of True -> s False -> inRight (step dt) s debugEvent evt s@(debugState, _) = case (debugStateActive debugState, evt) of (_, Left f) -> inLeft f s (True, _) -> s (_, Right e) -> inRight (event e) s debugDraw (debugState, s) = drawDebugState debugState (rawDraw s) (draw s) debugRawDraw (_debugState, s) = rawDraw s (sendEvent, getState) <- run debugInitial debugStep debugEvent debugDraw (Right . TimePassing) onEvents canvas (sendEvent . Right) connectInspect canvas (debugRawDraw <$> getState) (sendEvent . Left) waitForever #else -------------------------------------------------------------------------------- -- Stand-Alone event handling and core interaction code getMousePos :: (Int, Int) -> (Double, Double) -> (Double, Double) getMousePos (w, h) (x, y) = ((x - mx) / unitLen, (my - y) / unitLen) where w' = fromIntegral w h' = fromIntegral h unitLen = min w' h' / 20 mx = w' / 2 my = h' / 2 toEvent :: (Int, Int) -> Canvas.Event -> Maybe Event toEvent rect Canvas.Event {..} | eType == "keydown" , Just code <- eWhich = Just $ KeyPress (keyCodeToText (fromIntegral code)) | eType == "keyup" , Just code <- eWhich = Just $ KeyRelease (keyCodeToText (fromIntegral code)) | eType == "mousedown" , Just pos <- getMousePos rect <$> ePageXY = Just $ PointerPress pos | eType == "mouseup" , Just pos <- getMousePos rect <$> ePageXY = Just $ PointerRelease pos | eType == "mousemove" , Just pos <- getMousePos rect <$> ePageXY = Just $ PointerMovement pos | otherwise = Nothing onEvents :: Canvas.DeviceContext -> (Int, Int) -> (Event -> IO ()) -> IO () onEvents context rect handler = void $ forkIO $ forever $ do maybeEvent <- toEvent rect <$> Canvas.wait context forM_ maybeEvent handler run :: s -> (Double -> s -> s) -> (Event -> s -> s) -> (s -> Picture) -> IO () run initial stepHandler eventHandler drawHandler = runBlankCanvas $ \context -> do let fullStepHandler dt = stepHandler dt . eventHandler (TimePassing dt) let cw = Canvas.width context let ch = Canvas.height context offscreenCanvas <- runCanvasM context $ CM.newImage cw ch currentState <- newMVar initial eventHappened <- newMVar () onEvents context (cw, ch) $ \event -> do modifyMVar_ currentState (return . eventHandler event) void $ tryPutMVar eventHappened () let go t0 lastFrame lastStateName needsTime = do pic <- drawHandler <$> readMVar currentState picFrame <- makeStableName $! pic when (picFrame /= lastFrame) $ runCanvasM context $ do CM.withImage offscreenCanvas $ CM.saveRestore $ do setupScreenContext cw ch drawFrame pic CM.drawImage offscreenCanvas 0 0 cw ch t1 <- case needsTime of True -> do tn <- getCurrentTime threadDelay $ max 0 (50000 - round ((tn `diffUTCTime` t0) * 1000000)) t1 <- getCurrentTime let dt = realToFrac (t1 `diffUTCTime` t0) when (dt > 0) $ modifyMVar_ currentState (return . fullStepHandler dt) return t1 False -> do takeMVar eventHappened getCurrentTime nextState <- readMVar currentState nextStateName <- makeStableName $! nextState let nextNeedsTime = nextStateName /= lastStateName || needsTime && not (isUniversallyConstant fullStepHandler nextState) go t1 picFrame nextStateName nextNeedsTime t0 <- getCurrentTime nullFrame <- makeStableName undefined initialStateName <- makeStableName $! initial go t0 nullFrame initialStateName True runInspect :: s -> (Double -> s -> s) -> (Event -> s -> s) -> (s -> Picture) -> (s -> Picture) -> IO () runInspect initial step event draw _rawDraw = run initial step event draw getDeployHash :: IO Text getDeployHash = error "game API unimplemented in stand-alone interface mode" runGame :: GameToken -> Int -> (StdGen -> s) -> (Double -> s -> s) -> (Int -> Event -> s -> s) -> (Int -> s -> Picture) -> IO () runGame = error "game API unimplemented in stand-alone interface mode" #endif -------------------------------------------------------------------------------- -- FRP implementation data ReactiveInput t = ReactiveInput { keyPress :: R.Event t Text, keyRelease :: R.Event t Text, textEntry :: R.Event t Text, pointerPress :: R.Event t Point, pointerRelease :: R.Event t Point, pointerPosition :: R.Dynamic t Point, pointerDown :: R.Dynamic t Bool, timePassing :: R.Event t Double } data ReactiveOutput = ReactiveOutput { userPictures :: [Picture], userTransform :: Picture -> Picture, systemPicture :: Picture } instance Semigroup ReactiveOutput where a <> b = ReactiveOutput { userPictures = userPictures a ++ userPictures b, userTransform = userTransform a . userTransform b, systemPicture = systemPicture a & systemPicture b } instance Monoid ReactiveOutput where mempty = ReactiveOutput [] id blank newtype ReactiveProgram t m a = ReactiveProgram { unReactiveProgram :: ReaderT (ReactiveInput t) (R.DynamicWriterT t ReactiveOutput m) a } deriving instance Functor m => Functor (ReactiveProgram t m) deriving instance Monad m => Applicative (ReactiveProgram t m) deriving instance Monad m => Monad (ReactiveProgram t m) deriving instance MonadFix m => MonadFix (ReactiveProgram t m) deriving instance R.MonadSample t m => R.MonadSample t (ReactiveProgram t m) deriving instance R.MonadHold t m => R.MonadHold t (ReactiveProgram t m) deriving instance R.PerformEvent t m => R.PerformEvent t (ReactiveProgram t m) deriving instance R.PostBuild t m => R.PostBuild t (ReactiveProgram t m) instance (MonadFix m, R.MonadHold t m, R.Adjustable t m) => R.Adjustable t (ReactiveProgram t m) where runWithReplace a0 a' = ReactiveProgram $ R.runWithReplace (unReactiveProgram a0) $ fmap unReactiveProgram a' traverseIntMapWithKeyWithAdjust f dm0 dm' = ReactiveProgram $ R.traverseIntMapWithKeyWithAdjust (\k v -> unReactiveProgram (f k v)) dm0 dm' traverseDMapWithKeyWithAdjust f dm0 dm' = ReactiveProgram $ R.traverseDMapWithKeyWithAdjust (\k v -> unReactiveProgram (f k v)) dm0 dm' traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = ReactiveProgram $ R.traverseDMapWithKeyWithAdjustWithMove (\k v -> unReactiveProgram (f k v)) dm0 dm' runReactiveProgram :: (R.Reflex t, MonadFix m) => ReactiveProgram t m () -> ReactiveInput t -> m (R.Dynamic t Picture, R.Dynamic t Picture) runReactiveProgram (ReactiveProgram program) input = do ((), output) <- R.runDynamicWriterT (runReaderT program input) return $ R.splitDynPure $ do pics <- userPictures <$> output let userPicture = case pics of [] -> blank [p] -> p ps -> pictures ps tform <- userTransform <$> output sysPic <- systemPicture <$> output return (userPicture, sysPic & tform userPicture) withReactiveInput :: ReactiveInput t -> (ReactiveProgram t m a -> ReactiveProgram t m a) withReactiveInput input (ReactiveProgram program) = ReactiveProgram (withReaderT (const input) program) getReactiveInput :: Monad m => ReactiveProgram t m (ReactiveInput t) getReactiveInput = ReactiveProgram ask systemDraw :: (R.Reflex t, Monad m) => R.Dynamic t Picture -> ReactiveProgram t m () systemDraw = ReactiveProgram . R.tellDyn . fmap (\a -> mempty { systemPicture = a }) transformUserPicture :: (R.Reflex t, Monad m) => R.Dynamic t (Picture -> Picture) -> ReactiveProgram t m () transformUserPicture = ReactiveProgram . R.tellDyn . fmap (\a -> mempty { userTransform = a }) -- | Type class for the builder monad of a CodeWorld/Reflex app. class (R.Reflex t, R.MonadHold t m, MonadFix m, R.PerformEvent t m, R.Adjustable t m, MonadIO (R.Performable m), R.PostBuild t m) => ReflexCodeWorld t m | m -> t where -- | Gets an Event of key presses. The event value is a logical key name. getKeyPress :: m (R.Event t Text) -- | Gets an Event of key presses. The event value is a logical key name. getKeyRelease :: m (R.Event t Text) -- | Gets an Event of text entered. The event value is the typed text. getTextEntry :: m (R.Event t Text) -- | Gets an event of pointer clicks. The event value is the location of -- the click. getPointerClick :: m (R.Event t Point) -- | Gets the Dynamic position of the pointer. getPointerPosition :: m (R.Dynamic t Point) -- | Gets a Dynamic indicator whether the pointer is held down. isPointerDown :: m (R.Dynamic t Bool) -- | Gets an Event indicating the passage of time. getTimePassing :: m (R.Event t Double) -- | Emits a given Dynamic picture to be drawn to the screen. draw :: R.Dynamic t Picture -> m () instance (R.Reflex t, R.MonadHold t m, MonadFix m, R.PerformEvent t m, R.Adjustable t m, MonadIO (R.Performable m), R.PostBuild t m) => ReflexCodeWorld t (ReactiveProgram t m) where getKeyPress = ReactiveProgram $ asks keyPress getKeyRelease = ReactiveProgram $ asks keyRelease getTextEntry = ReactiveProgram $ asks textEntry getPointerClick = ReactiveProgram $ asks pointerPress getPointerPosition = ReactiveProgram $ asks pointerPosition isPointerDown = ReactiveProgram $ asks pointerDown getTimePassing = ReactiveProgram $ asks timePassing draw = ReactiveProgram . R.tellDyn . fmap (\a -> mempty { userPictures = [a] }) splitDyn :: forall t a. R.Reflex t => R.Dynamic t (a -> Bool) -> R.Event t a -> (R.Event t a, R.Event t a) splitDyn predicate e = R.fanEither $ R.attachPromptlyDynWith f predicate e where f pred val = if pred val then Right val else Left val gateDyn :: forall t a. R.Reflex t => R.Dynamic t Bool -> R.Event t a -> R.Event t a gateDyn dyn e = R.switchDyn (bool R.never e <$> dyn) #ifdef ghcjs_HOST_OS createPhysicalReactiveInput :: forall t m. (R.MonadReflexCreateTrigger t m, R.Reflex t, R.MonadHold t m) => Window -> Element -> ([DSum (R.EventTrigger t) Identity] -> IO ()) -> m (ReactiveInput t) createPhysicalReactiveInput window canvas fire = do keyPress <- R.newEventWithTrigger $ \trigger -> on window keyDown $ do keyName <- keyCodeToText <$> (getKeyCode =<< event) when (keyName /= "") $ do liftIO $ fire [ trigger ==> keyName ] preventDefault stopPropagation textEntry <- R.newEventWithTrigger $ \trigger -> on window keyDown $ do key <- getKey =<< event when (T.length key == 1) $ do liftIO $ fire [trigger ==> key] preventDefault stopPropagation keyRelease <- R.newEventWithTrigger $ \trigger -> on window keyUp $ do keyName <- keyCodeToText <$> (getKeyCode =<< event) when (keyName /= "") $ do liftIO $ fire [trigger ==> keyName] preventDefault stopPropagation pointerPress <- R.newEventWithTrigger $ \trigger -> on window mouseDown $ do pos <- getMousePos canvas liftIO $ fire [trigger ==> pos] pointerRelease <- R.newEventWithTrigger $ \trigger -> on window mouseUp $ do pos <- getMousePos canvas liftIO $ fire [trigger ==> pos] pointerMovement <- R.newEventWithTrigger $ \trigger -> on window mouseMove $ do pos <- getMousePos canvas liftIO $ fire [trigger ==> pos] timePassing <- R.newEventWithTrigger $ \trigger -> do active <- newIORef True let timeStep t1 t2 = do stillActive <- readIORef active when stillActive $ do when (t2 > t1) $ fire [ trigger ==> min 0.25 ((t2 - t1) / 1000)] void $ inAnimationFrame ContinueAsync (timeStep t2) t0 <- nextFrame void $ inAnimationFrame ContinueAsync (timeStep t0) return (writeIORef active False) pointerPosition <- R.holdDyn (0, 0) pointerMovement pointerDown <- R.holdDyn False $ R.mergeWith (&&) [True <$ pointerPress, False <$ pointerRelease] return ReactiveInput{..} inspectLogicalInput :: forall t m. (R.Reflex t, R.MonadHold t m) => R.Dynamic t DebugState -> ReactiveInput t -> m (ReactiveInput t) inspectLogicalInput debugState physicalInput = do -- Physical inputs should either be frozen or dropped during debugging. let filterInDebugMode :: forall a. R.Event t a -> R.Event t a filterInDebugMode = gateDyn (not . debugStateActive <$> debugState) let freezeInDebugMode :: forall a. R.Dynamic t a -> a -> m (R.Dynamic t a) freezeInDebugMode dyn initial = R.holdDyn initial (filterInDebugMode (R.updated dyn)) logicalPointerPosition <- freezeInDebugMode (pointerPosition physicalInput) (0, 0) logicalPointerDown <- freezeInDebugMode (pointerDown physicalInput) False return $ ReactiveInput { keyPress = filterInDebugMode (keyPress physicalInput), keyRelease = filterInDebugMode (keyRelease physicalInput), textEntry = filterInDebugMode (textEntry physicalInput), pointerPress = filterInDebugMode (pointerPress physicalInput), pointerRelease = filterInDebugMode (pointerRelease physicalInput), pointerPosition = logicalPointerPosition, pointerDown = logicalPointerDown, timePassing = filterInDebugMode (timePassing physicalInput) } runReactive :: (forall t m. (R.Reflex t, R.MonadHold t m, MonadFix m, R.PerformEvent t m, R.Adjustable t m, MonadIO (R.Performable m), R.PostBuild t m) => (ReactiveInput t -> m (R.Dynamic t Picture, R.Dynamic t Picture))) -> IO () runReactive program = do showCanvas Just window <- currentWindow Just doc <- currentDocument Just canvas <- getElementById doc ("screen" :: JSString) setCanvasSize canvas canvas frameRenderer <- createFrameRenderer canvas pendingFrame <- liftIO $ newMVar Nothing let asyncRender pic = do old <- swapMVar pendingFrame (Just pic) when (isNothing old) $ void $ inAnimationFrame ContinueAsync $ \ _t -> do pic <- swapMVar pendingFrame Nothing maybe (return ()) frameRenderer pic (postBuild, postBuildTriggerRef) <- R.runSpiderHost R.newEventWithTriggerRef (debugUpdate, debugUpdateTriggerRef) <- R.runSpiderHost R.newEventWithTriggerRef debugState <- R.runSpiderHost $ R.holdUniqDyn =<< R.foldDyn ($) debugStateInit debugUpdate rec physicalInput <- R.runSpiderHost $ createPhysicalReactiveInput window canvas fireAndRedraw resizeEvent <- R.runSpiderHost $ R.newEventWithTrigger $ \trigger -> do on window resize $ liftIO $ fireAndRedraw [trigger ==> ()] logicalInput <- R.runSpiderHost $ inspectLogicalInput debugState physicalInput (inspectPicture, fireCommand) <- R.runSpiderHost $ R.hostPerformEventT $ do (inspectPicture, displayPicture) <- R.runPostBuildT (program logicalInput) postBuild let logicalPicture = drawDebugState <$> debugState <*> inspectPicture <*> displayPicture R.performEvent_ $ liftIO <$> R.mergeWith const [ (setCanvasSize canvas canvas >>) . asyncRender <$> R.tagPromptlyDyn logicalPicture resizeEvent, asyncRender <$> R.updated logicalPicture, asyncRender <$> R.tagPromptlyDyn logicalPicture postBuild ] return inspectPicture let fireAndRedraw events = R.runSpiderHost $ void $ R.runFireCommand fireCommand events (return ()) let fireDebugUpdateAndRedraw f = R.runSpiderHost $ do state <- readRef debugUpdateTriggerRef case state of Just trigger -> void $ R.runFireCommand fireCommand [trigger ==> f] (return ()) Nothing -> return () let samplePicture = R.runSpiderHost $ R.runHostFrame $ R.sample $ R.current inspectPicture connectInspect canvas samplePicture fireDebugUpdateAndRedraw maybePostBuildTrigger <- readRef postBuildTriggerRef case maybePostBuildTrigger of Just trigger -> R.runSpiderHost $ void $ R.runFireCommand fireCommand [trigger ==> ()] (return ()) Nothing -> return () waitForever #else runReactive :: (forall t m. (R.Reflex t, R.MonadHold t m, MonadFix m, R.PerformEvent t m, R.Adjustable t m, MonadIO (R.Performable m), R.PostBuild t m) => (ReactiveInput t -> m (R.Dynamic t Picture, R.Dynamic t Picture))) -> IO () runReactive program = runBlankCanvas $ \context -> do let cw = Canvas.width context let ch = Canvas.height context offscreenCanvas <- runCanvasM context $ CM.newImage cw ch let frame pic = runCanvasM context $ do CM.withImage offscreenCanvas $ CM.saveRestore $ do setupScreenContext cw ch drawFrame pic CM.drawImage offscreenCanvas 0 0 cw ch (postBuild, postBuildTriggerRef) <- R.runSpiderHost R.newEventWithTriggerRef (keyPress, keyPressTrigger) <- R.runSpiderHost R.newEventWithTriggerRef (textEntry, textEntryTrigger) <- R.runSpiderHost R.newEventWithTriggerRef (keyRelease, keyReleaseTrigger) <- R.runSpiderHost R.newEventWithTriggerRef (pointerPress, pointerPressTrigger) <- R.runSpiderHost R.newEventWithTriggerRef (pointerRelease, pointerReleaseTrigger) <- R.runSpiderHost R.newEventWithTriggerRef (pointerMovement, pointerMovementTrigger) <- R.runSpiderHost R.newEventWithTriggerRef (timePassing, timePassingTrigger) <- R.runSpiderHost R.newEventWithTriggerRef pointerPosition <- R.runSpiderHost $ R.holdDyn (0, 0) pointerMovement pointerDown <- R.runSpiderHost $ R.holdDyn False $ R.mergeWith (&&) [True <$ pointerPress, False <$ pointerRelease] let input = ReactiveInput{..} (_, fireCommand) <- R.runSpiderHost $ R.hostPerformEventT $ do (_inspectPicture, displayPicture) <- R.runPostBuildT (program input) postBuild R.performEvent_ $ liftIO <$> R.mergeWith const [ frame <$> R.updated displayPicture, frame <$> R.tagPromptlyDyn displayPicture postBuild ] return () let sendEvent :: forall a. IORef (Maybe (R.EventTrigger (R.SpiderTimeline R.Global) a)) -> a -> IO () sendEvent triggerRef val = do mtrigger <- readRef triggerRef case mtrigger of Just trigger -> R.runSpiderHost $ void $ R.runFireCommand fireCommand [trigger ==> val] (return ()) Nothing -> return () maybePostBuildTrigger <- readRef postBuildTriggerRef case maybePostBuildTrigger of Just trigger -> R.runSpiderHost $ void $ R.runFireCommand fireCommand [trigger ==> ()] (return ()) Nothing -> return () t0 <- getCurrentTime let go t1 = do events <- Canvas.flush context forM_ events $ \event -> case Canvas.eType event of "keydown" | Just code <- Canvas.eWhich event -> do let keyName = keyCodeToText (fromIntegral code) sendEvent keyPressTrigger keyName when (T.length keyName == 1) $ sendEvent textEntryTrigger keyName "keyup" | Just code <- Canvas.eWhich event -> do let keyName = keyCodeToText (fromIntegral code) sendEvent keyReleaseTrigger keyName "mousedown" | Just pos <- getMousePos (cw, ch) <$> Canvas.ePageXY event -> do sendEvent pointerPressTrigger pos "mouseup" | Just pos <- getMousePos (cw, ch) <$> Canvas.ePageXY event -> do sendEvent pointerReleaseTrigger pos "mousemove" | Just pos <- getMousePos (cw, ch) <$> Canvas.ePageXY event -> do sendEvent pointerMovementTrigger pos _ -> return () tn <- getCurrentTime threadDelay $ max 0 (50000 - (round ((tn `diffUTCTime` t0) * 1000000))) t2 <- getCurrentTime let dt = realToFrac (t2 `diffUTCTime` t1) sendEvent timePassingTrigger dt go t2 go t0 #endif
alphalambda/codeworld
codeworld-api/src/CodeWorld/Driver.hs
apache-2.0
82,700
51
28
22,944
25,207
12,424
12,783
985
58
{-# LANGUAGE OverloadedStrings #-} module Types where import Data.Text import Data.Time import System.Locale import Text.JSON data Post = Post { postId :: Int , postTitle :: Text , postText :: Text , postUrl :: Text , postDate :: LocalTime , postPublished :: Bool , postSpecial :: Bool , postTags :: [Text] } instance JSON Post where showJSON post = JSObject $ toJSObject [ ("id", showJSON $ postId post) , ("title", showJSON $ postTitle post) -- , ("text", showJSON $ postText post) , ("url", showJSON $ postUrl post) , ("date", showJSON $ postDate post) , ("published", showJSON $ postPublished post) , ("special", showJSON $ postSpecial post) , ("tags", showJSON $ postTags post) ] readJSON _ = error "Not implemented" instance JSON LocalTime where showJSON time = JSString $ toJSString $ formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%z" $ ZonedTime time $ hoursToTimeZone 3 -- TODO move timezone to config readJSON _ = error "Not implemented" data PostComment = PostComment { commentId :: Text , commentThread :: Int , commentParentId :: Maybe Text , commentBody :: Text , commentAuthorName :: Text , commentAuthorUrl :: Text , commentAuthorAvatar :: Text , commentDate :: LocalTime } newtype Tag = Tag (Text, Int) instance Eq Tag where Tag (tag1, _) == Tag (tag2, _) = tag1 == tag2 instance Ord Tag where compare (Tag (tag1, _)) (Tag (tag2, _)) = compare (toCaseFold tag1) (toCaseFold tag2)
dikmax/haskell-blog
src/Types.hs
bsd-2-clause
1,531
0
11
359
461
260
201
45
0
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QConicalGradient.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:30 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QConicalGradient ( QqqConicalGradient(..), QqConicalGradient(..) ,QqqConicalGradient_nf(..), QqConicalGradient_nf(..) ,setAngle ,qConicalGradient_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqqConicalGradient x1 where qqConicalGradient :: x1 -> IO (QConicalGradient ()) class QqConicalGradient x1 where qConicalGradient :: x1 -> IO (QConicalGradient ()) instance QqConicalGradient (()) where qConicalGradient () = withQConicalGradientResult $ qtc_QConicalGradient foreign import ccall "qtc_QConicalGradient" qtc_QConicalGradient :: IO (Ptr (TQConicalGradient ())) instance QqConicalGradient ((QConicalGradient t1)) where qConicalGradient (x1) = withQConicalGradientResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QConicalGradient1 cobj_x1 foreign import ccall "qtc_QConicalGradient1" qtc_QConicalGradient1 :: Ptr (TQConicalGradient t1) -> IO (Ptr (TQConicalGradient ())) instance QqqConicalGradient ((QPointF t1, Double)) where qqConicalGradient (x1, x2) = withQConicalGradientResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QConicalGradient2 cobj_x1 (toCDouble x2) foreign import ccall "qtc_QConicalGradient2" qtc_QConicalGradient2 :: Ptr (TQPointF t1) -> CDouble -> IO (Ptr (TQConicalGradient ())) instance QqConicalGradient ((PointF, Double)) where qConicalGradient (x1, x2) = withQConicalGradientResult $ withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QConicalGradient3 cpointf_x1_x cpointf_x1_y (toCDouble x2) foreign import ccall "qtc_QConicalGradient3" qtc_QConicalGradient3 :: CDouble -> CDouble -> CDouble -> IO (Ptr (TQConicalGradient ())) instance QqConicalGradient ((Double, Double, Double)) where qConicalGradient (x1, x2, x3) = withQConicalGradientResult $ qtc_QConicalGradient4 (toCDouble x1) (toCDouble x2) (toCDouble x3) foreign import ccall "qtc_QConicalGradient4" qtc_QConicalGradient4 :: CDouble -> CDouble -> CDouble -> IO (Ptr (TQConicalGradient ())) class QqqConicalGradient_nf x1 where qqConicalGradient_nf :: x1 -> IO (QConicalGradient ()) class QqConicalGradient_nf x1 where qConicalGradient_nf :: x1 -> IO (QConicalGradient ()) instance QqConicalGradient_nf (()) where qConicalGradient_nf () = withObjectRefResult $ qtc_QConicalGradient instance QqConicalGradient_nf ((QConicalGradient t1)) where qConicalGradient_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QConicalGradient1 cobj_x1 instance QqqConicalGradient_nf ((QPointF t1, Double)) where qqConicalGradient_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QConicalGradient2 cobj_x1 (toCDouble x2) instance QqConicalGradient_nf ((PointF, Double)) where qConicalGradient_nf (x1, x2) = withObjectRefResult $ withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QConicalGradient3 cpointf_x1_x cpointf_x1_y (toCDouble x2) instance QqConicalGradient_nf ((Double, Double, Double)) where qConicalGradient_nf (x1, x2, x3) = withObjectRefResult $ qtc_QConicalGradient4 (toCDouble x1) (toCDouble x2) (toCDouble x3) instance Qqangle (QConicalGradient a) (()) where qangle x0 () = withDoubleResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QConicalGradient_angle cobj_x0 foreign import ccall "qtc_QConicalGradient_angle" qtc_QConicalGradient_angle :: Ptr (TQConicalGradient a) -> IO CDouble instance Qqcenter (QConicalGradient a) (()) (IO (PointF)) where qcenter x0 () = withPointFResult $ \cpointf_ret_x cpointf_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QConicalGradient_center_qth cobj_x0 cpointf_ret_x cpointf_ret_y foreign import ccall "qtc_QConicalGradient_center_qth" qtc_QConicalGradient_center_qth :: Ptr (TQConicalGradient a) -> Ptr CDouble -> Ptr CDouble -> IO () instance Qqqcenter (QConicalGradient a) (()) (IO (QPointF ())) where qqcenter x0 () = withQPointFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QConicalGradient_center cobj_x0 foreign import ccall "qtc_QConicalGradient_center" qtc_QConicalGradient_center :: Ptr (TQConicalGradient a) -> IO (Ptr (TQPointF ())) setAngle :: QConicalGradient a -> ((Double)) -> IO () setAngle x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QConicalGradient_setAngle cobj_x0 (toCDouble x1) foreign import ccall "qtc_QConicalGradient_setAngle" qtc_QConicalGradient_setAngle :: Ptr (TQConicalGradient a) -> CDouble -> IO () instance QsetCenter (QConicalGradient a) ((Double, Double)) where setCenter x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QConicalGradient_setCenter1 cobj_x0 (toCDouble x1) (toCDouble x2) foreign import ccall "qtc_QConicalGradient_setCenter1" qtc_QConicalGradient_setCenter1 :: Ptr (TQConicalGradient a) -> CDouble -> CDouble -> IO () instance QsetCenter (QConicalGradient a) ((PointF)) where setCenter x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QConicalGradient_setCenter_qth cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QConicalGradient_setCenter_qth" qtc_QConicalGradient_setCenter_qth :: Ptr (TQConicalGradient a) -> CDouble -> CDouble -> IO () instance QqsetCenter (QConicalGradient a) ((QPointF t1)) where qsetCenter x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QConicalGradient_setCenter cobj_x0 cobj_x1 foreign import ccall "qtc_QConicalGradient_setCenter" qtc_QConicalGradient_setCenter :: Ptr (TQConicalGradient a) -> Ptr (TQPointF t1) -> IO () qConicalGradient_delete :: QConicalGradient a -> IO () qConicalGradient_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QConicalGradient_delete cobj_x0 foreign import ccall "qtc_QConicalGradient_delete" qtc_QConicalGradient_delete :: Ptr (TQConicalGradient a) -> IO ()
uduki/hsQt
Qtc/Gui/QConicalGradient.hs
bsd-2-clause
6,363
0
14
927
1,743
908
835
-1
-1
{-# LANGUAGE CPP #-} {-# OPTIONS_HADDOCK prune #-} -- | -- Module : Data.ByteString.Lazy.Char8 -- Copyright : (c) Don Stewart 2006 -- License : BSD-style -- -- Maintainer : dons@cse.unsw.edu.au -- Stability : experimental -- Portability : non-portable (imports Data.ByteString.Lazy) -- -- Manipulate /lazy/ 'ByteString's using 'Char' operations. All Chars will -- be truncated to 8 bits. It can be expected that these functions will -- run at identical speeds to their 'Data.Word.Word8' equivalents in -- "Data.ByteString.Lazy". -- -- This module is intended to be imported @qualified@, to avoid name -- clashes with "Prelude" functions. eg. -- -- > import qualified Data.ByteString.Lazy.Char8 as C -- module Data.ByteString.Lazy.Char8 ( -- * The @ByteString@ type ByteString, -- instances: Eq, Ord, Show, Read, Data, Typeable -- * Introducing and eliminating 'ByteString's empty, -- :: ByteString singleton, -- :: Char -> ByteString pack, -- :: String -> ByteString unpack, -- :: ByteString -> String fromChunks, -- :: [Strict.ByteString] -> ByteString toChunks, -- :: ByteString -> [Strict.ByteString] -- * Basic interface cons, -- :: Char -> ByteString -> ByteString cons', -- :: Char -> ByteString -> ByteString snoc, -- :: ByteString -> Char -> ByteString append, -- :: ByteString -> ByteString -> ByteString head, -- :: ByteString -> Char uncons, -- :: ByteString -> Maybe (Char, ByteString) last, -- :: ByteString -> Char tail, -- :: ByteString -> ByteString init, -- :: ByteString -> ByteString null, -- :: ByteString -> Bool length, -- :: ByteString -> Int64 -- * Transforming ByteStrings map, -- :: (Char -> Char) -> ByteString -> ByteString reverse, -- :: ByteString -> ByteString intersperse, -- :: Char -> ByteString -> ByteString intercalate, -- :: ByteString -> [ByteString] -> ByteString transpose, -- :: [ByteString] -> [ByteString] -- * Reducing 'ByteString's (folds) foldl, -- :: (a -> Char -> a) -> a -> ByteString -> a foldl', -- :: (a -> Char -> a) -> a -> ByteString -> a foldl1, -- :: (Char -> Char -> Char) -> ByteString -> Char foldl1', -- :: (Char -> Char -> Char) -> ByteString -> Char foldr, -- :: (Char -> a -> a) -> a -> ByteString -> a foldr1, -- :: (Char -> Char -> Char) -> ByteString -> Char -- ** Special folds concat, -- :: [ByteString] -> ByteString concatMap, -- :: (Char -> ByteString) -> ByteString -> ByteString any, -- :: (Char -> Bool) -> ByteString -> Bool all, -- :: (Char -> Bool) -> ByteString -> Bool maximum, -- :: ByteString -> Char minimum, -- :: ByteString -> Char -- * Building ByteStrings -- ** Scans scanl, -- :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString -- scanl1, -- :: (Char -> Char -> Char) -> ByteString -> ByteString -- scanr, -- :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString -- scanr1, -- :: (Char -> Char -> Char) -> ByteString -> ByteString -- ** Accumulating maps mapAccumL, -- :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString) mapAccumR, -- :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString) -- ** Infinite ByteStrings repeat, -- :: Char -> ByteString replicate, -- :: Int64 -> Char -> ByteString cycle, -- :: ByteString -> ByteString iterate, -- :: (Char -> Char) -> Char -> ByteString -- ** Unfolding ByteStrings unfoldr, -- :: (a -> Maybe (Char, a)) -> a -> ByteString -- * Substrings -- ** Breaking strings take, -- :: Int64 -> ByteString -> ByteString drop, -- :: Int64 -> ByteString -> ByteString splitAt, -- :: Int64 -> ByteString -> (ByteString, ByteString) takeWhile, -- :: (Char -> Bool) -> ByteString -> ByteString dropWhile, -- :: (Char -> Bool) -> ByteString -> ByteString span, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) break, -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) group, -- :: ByteString -> [ByteString] groupBy, -- :: (Char -> Char -> Bool) -> ByteString -> [ByteString] inits, -- :: ByteString -> [ByteString] tails, -- :: ByteString -> [ByteString] -- ** Breaking into many substrings split, -- :: Char -> ByteString -> [ByteString] splitWith, -- :: (Char -> Bool) -> ByteString -> [ByteString] -- ** Breaking into lines and words lines, -- :: ByteString -> [ByteString] words, -- :: ByteString -> [ByteString] unlines, -- :: [ByteString] -> ByteString unwords, -- :: ByteString -> [ByteString] -- * Predicates isPrefixOf, -- :: ByteString -> ByteString -> Bool -- isSuffixOf, -- :: ByteString -> ByteString -> Bool -- * Searching ByteStrings -- ** Searching by equality elem, -- :: Char -> ByteString -> Bool notElem, -- :: Char -> ByteString -> Bool -- ** Searching with a predicate find, -- :: (Char -> Bool) -> ByteString -> Maybe Char filter, -- :: (Char -> Bool) -> ByteString -> ByteString -- partition -- :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) -- * Indexing ByteStrings index, -- :: ByteString -> Int64 -> Char elemIndex, -- :: Char -> ByteString -> Maybe Int64 elemIndices, -- :: Char -> ByteString -> [Int64] findIndex, -- :: (Char -> Bool) -> ByteString -> Maybe Int64 findIndices, -- :: (Char -> Bool) -> ByteString -> [Int64] count, -- :: Char -> ByteString -> Int64 -- * Zipping and unzipping ByteStrings zip, -- :: ByteString -> ByteString -> [(Char,Char)] zipWith, -- :: (Char -> Char -> c) -> ByteString -> ByteString -> [c] -- unzip, -- :: [(Char,Char)] -> (ByteString,ByteString) -- * Ordered ByteStrings -- sort, -- :: ByteString -> ByteString -- * Low level conversions -- ** Copying ByteStrings copy, -- :: ByteString -> ByteString -- * Reading from ByteStrings readInt, readInteger, -- * I\/O with 'ByteString's -- ** Standard input and output getContents, -- :: IO ByteString putStr, -- :: ByteString -> IO () putStrLn, -- :: ByteString -> IO () interact, -- :: (ByteString -> ByteString) -> IO () -- ** Files readFile, -- :: FilePath -> IO ByteString writeFile, -- :: FilePath -> ByteString -> IO () appendFile, -- :: FilePath -> ByteString -> IO () -- ** I\/O with Handles hGetContents, -- :: Handle -> IO ByteString hGet, -- :: Handle -> Int64 -> IO ByteString hGetNonBlocking, -- :: Handle -> Int64 -> IO ByteString hPut, -- :: Handle -> ByteString -> IO () ) where -- Functions transparently exported import Data.ByteString.Lazy (fromChunks, toChunks ,empty,null,length,tail,init,append,reverse,transpose,cycle ,concat,take,drop,splitAt,intercalate,isPrefixOf,group,inits,tails,copy ,hGetContents, hGet, hPut, getContents ,hGetNonBlocking ,putStr, putStrLn, interact) -- Functions we need to wrap. import qualified Data.ByteString.Lazy as L import qualified Data.ByteString as S (ByteString) -- typename only import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as B import Data.ByteString.Lazy.Internal import Data.ByteString.Internal (w2c, c2w, isSpaceWord8) import Data.Int (Int64) import qualified Data.List as List import Prelude hiding (reverse,head,tail,last,init,null,length,map,lines,foldl,foldr,unlines ,concat,any,take,drop,splitAt,takeWhile,dropWhile,span,break,elem,filter ,unwords,words,maximum,minimum,all,concatMap,scanl,scanl1,foldl1,foldr1 ,readFile,writeFile,appendFile,replicate,getContents,getLine,putStr,putStrLn ,zip,zipWith,unzip,notElem,repeat,iterate,interact,cycle) import System.IO (hClose,openFile,IOMode(..)) #ifndef __NHC__ import Control.Exception (bracket) #else import IO (bracket) #endif #if __GLASGOW_HASKELL__ >= 608 import Data.String (IsString(..)) #endif #define STRICT1(f) f a | a `seq` False = undefined #define STRICT2(f) f a b | a `seq` b `seq` False = undefined #define STRICT3(f) f a b c | a `seq` b `seq` c `seq` False = undefined #define STRICT4(f) f a b c d | a `seq` b `seq` c `seq` d `seq` False = undefined #define STRICT5(f) f a b c d e | a `seq` b `seq` c `seq` d `seq` e `seq` False = undefined #define STRICT5_(f) f a b c d _ | a `seq` b `seq` c `seq` d `seq` False = undefined ------------------------------------------------------------------------ -- | /O(1)/ Convert a 'Char' into a 'ByteString' singleton :: Char -> ByteString singleton = L.singleton . c2w {-# INLINE singleton #-} #if __GLASGOW_HASKELL__ >= 608 instance IsString ByteString where fromString = pack {-# INLINE fromString #-} #endif -- | /O(n)/ Convert a 'String' into a 'ByteString'. pack :: [Char] -> ByteString pack = L.pack. List.map c2w -- | /O(n)/ Converts a 'ByteString' to a 'String'. unpack :: ByteString -> [Char] unpack = List.map w2c . L.unpack {-# INLINE unpack #-} -- | /O(1)/ 'cons' is analogous to '(:)' for lists. cons :: Char -> ByteString -> ByteString cons = L.cons . c2w {-# INLINE cons #-} -- | /O(1)/ Unlike 'cons', 'cons\'' is -- strict in the ByteString that we are consing onto. More precisely, it forces -- the head and the first chunk. It does this because, for space efficiency, it -- may coalesce the new byte onto the first \'chunk\' rather than starting a -- new \'chunk\'. -- -- So that means you can't use a lazy recursive contruction like this: -- -- > let xs = cons\' c xs in xs -- -- You can however use 'cons', as well as 'repeat' and 'cycle', to build -- infinite lazy ByteStrings. -- cons' :: Char -> ByteString -> ByteString cons' = L.cons' . c2w {-# INLINE cons' #-} -- | /O(n)/ Append a Char to the end of a 'ByteString'. Similar to -- 'cons', this function performs a memcpy. snoc :: ByteString -> Char -> ByteString snoc p = L.snoc p . c2w {-# INLINE snoc #-} -- | /O(1)/ Extract the first element of a ByteString, which must be non-empty. head :: ByteString -> Char head = w2c . L.head {-# INLINE head #-} -- | /O(1)/ Extract the head and tail of a ByteString, returning Nothing -- if it is empty. uncons :: ByteString -> Maybe (Char, ByteString) uncons bs = case L.uncons bs of Nothing -> Nothing Just (w, bs') -> Just (w2c w, bs') {-# INLINE uncons #-} -- | /O(1)/ Extract the last element of a packed string, which must be non-empty. last :: ByteString -> Char last = w2c . L.last {-# INLINE last #-} -- | /O(n)/ 'map' @f xs@ is the ByteString obtained by applying @f@ to each element of @xs@ map :: (Char -> Char) -> ByteString -> ByteString map f = L.map (c2w . f . w2c) {-# INLINE map #-} -- | /O(n)/ The 'intersperse' function takes a Char and a 'ByteString' -- and \`intersperses\' that Char between the elements of the -- 'ByteString'. It is analogous to the intersperse function on Lists. intersperse :: Char -> ByteString -> ByteString intersperse = L.intersperse . c2w {-# INLINE intersperse #-} -- | 'foldl', applied to a binary operator, a starting value (typically -- the left-identity of the operator), and a ByteString, reduces the -- ByteString using the binary operator, from left to right. foldl :: (a -> Char -> a) -> a -> ByteString -> a foldl f = L.foldl (\a c -> f a (w2c c)) {-# INLINE foldl #-} -- | 'foldl\'' is like foldl, but strict in the accumulator. foldl' :: (a -> Char -> a) -> a -> ByteString -> a foldl' f = L.foldl' (\a c -> f a (w2c c)) {-# INLINE foldl' #-} -- | 'foldr', applied to a binary operator, a starting value -- (typically the right-identity of the operator), and a packed string, -- reduces the packed string using the binary operator, from right to left. foldr :: (Char -> a -> a) -> a -> ByteString -> a foldr f = L.foldr (\c a -> f (w2c c) a) {-# INLINE foldr #-} -- | 'foldl1' is a variant of 'foldl' that has no starting value -- argument, and thus must be applied to non-empty 'ByteStrings'. foldl1 :: (Char -> Char -> Char) -> ByteString -> Char foldl1 f ps = w2c (L.foldl1 (\x y -> c2w (f (w2c x) (w2c y))) ps) {-# INLINE foldl1 #-} -- | 'foldl1\'' is like 'foldl1', but strict in the accumulator. foldl1' :: (Char -> Char -> Char) -> ByteString -> Char foldl1' f ps = w2c (L.foldl1' (\x y -> c2w (f (w2c x) (w2c y))) ps) -- | 'foldr1' is a variant of 'foldr' that has no starting value argument, -- and thus must be applied to non-empty 'ByteString's foldr1 :: (Char -> Char -> Char) -> ByteString -> Char foldr1 f ps = w2c (L.foldr1 (\x y -> c2w (f (w2c x) (w2c y))) ps) {-# INLINE foldr1 #-} -- | Map a function over a 'ByteString' and concatenate the results concatMap :: (Char -> ByteString) -> ByteString -> ByteString concatMap f = L.concatMap (f . w2c) {-# INLINE concatMap #-} -- | Applied to a predicate and a ByteString, 'any' determines if -- any element of the 'ByteString' satisfies the predicate. any :: (Char -> Bool) -> ByteString -> Bool any f = L.any (f . w2c) {-# INLINE any #-} -- | Applied to a predicate and a 'ByteString', 'all' determines if -- all elements of the 'ByteString' satisfy the predicate. all :: (Char -> Bool) -> ByteString -> Bool all f = L.all (f . w2c) {-# INLINE all #-} -- | 'maximum' returns the maximum value from a 'ByteString' maximum :: ByteString -> Char maximum = w2c . L.maximum {-# INLINE maximum #-} -- | 'minimum' returns the minimum value from a 'ByteString' minimum :: ByteString -> Char minimum = w2c . L.minimum {-# INLINE minimum #-} -- --------------------------------------------------------------------- -- Building ByteStrings -- | 'scanl' is similar to 'foldl', but returns a list of successive -- reduced values from the left. This function will fuse. -- -- > scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...] -- -- Note that -- -- > last (scanl f z xs) == foldl f z xs. scanl :: (Char -> Char -> Char) -> Char -> ByteString -> ByteString scanl f z = L.scanl (\a b -> c2w (f (w2c a) (w2c b))) (c2w z) -- | The 'mapAccumL' function behaves like a combination of 'map' and -- 'foldl'; it applies a function to each element of a ByteString, -- passing an accumulating parameter from left to right, and returning a -- final value of this accumulator together with the new ByteString. mapAccumL :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString) mapAccumL f = L.mapAccumL (\a w -> case f a (w2c w) of (a',c) -> (a', c2w c)) -- | The 'mapAccumR' function behaves like a combination of 'map' and -- 'foldr'; it applies a function to each element of a ByteString, -- passing an accumulating parameter from right to left, and returning a -- final value of this accumulator together with the new ByteString. mapAccumR :: (acc -> Char -> (acc, Char)) -> acc -> ByteString -> (acc, ByteString) mapAccumR f = L.mapAccumR (\acc w -> case f acc (w2c w) of (acc', c) -> (acc', c2w c)) ------------------------------------------------------------------------ -- Generating and unfolding ByteStrings -- | @'iterate' f x@ returns an infinite ByteString of repeated applications -- of @f@ to @x@: -- -- > iterate f x == [x, f x, f (f x), ...] -- iterate :: (Char -> Char) -> Char -> ByteString iterate f = L.iterate (c2w . f . w2c) . c2w -- | @'repeat' x@ is an infinite ByteString, with @x@ the value of every -- element. -- repeat :: Char -> ByteString repeat = L.repeat . c2w -- | /O(n)/ @'replicate' n x@ is a ByteString of length @n@ with @x@ -- the value of every element. -- replicate :: Int64 -> Char -> ByteString replicate w c = L.replicate w (c2w c) -- | /O(n)/ The 'unfoldr' function is analogous to the List \'unfoldr\'. -- 'unfoldr' builds a ByteString from a seed value. The function takes -- the element and returns 'Nothing' if it is done producing the -- ByteString or returns 'Just' @(a,b)@, in which case, @a@ is a -- prepending to the ByteString and @b@ is used as the next element in a -- recursive call. unfoldr :: (a -> Maybe (Char, a)) -> a -> ByteString unfoldr f = L.unfoldr $ \a -> case f a of Nothing -> Nothing Just (c, a') -> Just (c2w c, a') ------------------------------------------------------------------------ -- | 'takeWhile', applied to a predicate @p@ and a ByteString @xs@, -- returns the longest prefix (possibly empty) of @xs@ of elements that -- satisfy @p@. takeWhile :: (Char -> Bool) -> ByteString -> ByteString takeWhile f = L.takeWhile (f . w2c) {-# INLINE takeWhile #-} -- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@. dropWhile :: (Char -> Bool) -> ByteString -> ByteString dropWhile f = L.dropWhile (f . w2c) {-# INLINE dropWhile #-} -- | 'break' @p@ is equivalent to @'span' ('not' . p)@. break :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) break f = L.break (f . w2c) {-# INLINE break #-} -- | 'span' @p xs@ breaks the ByteString into two segments. It is -- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@ span :: (Char -> Bool) -> ByteString -> (ByteString, ByteString) span f = L.span (f . w2c) {-# INLINE span #-} {- -- | 'breakChar' breaks its ByteString argument at the first occurence -- of the specified Char. It is more efficient than 'break' as it is -- implemented with @memchr(3)@. I.e. -- -- > break (=='c') "abcd" == breakChar 'c' "abcd" -- breakChar :: Char -> ByteString -> (ByteString, ByteString) breakChar = L.breakByte . c2w {-# INLINE breakChar #-} -- | 'spanChar' breaks its ByteString argument at the first -- occurence of a Char other than its argument. It is more efficient -- than 'span (==)' -- -- > span (=='c') "abcd" == spanByte 'c' "abcd" -- spanChar :: Char -> ByteString -> (ByteString, ByteString) spanChar = L.spanByte . c2w {-# INLINE spanChar #-} -} -- -- TODO, more rules for breakChar* -- -- | /O(n)/ Break a 'ByteString' into pieces separated by the byte -- argument, consuming the delimiter. I.e. -- -- > split '\n' "a\nb\nd\ne" == ["a","b","d","e"] -- > split 'a' "aXaXaXa" == ["","X","X","X"] -- > split 'x' "x" == ["",""] -- -- and -- -- > intercalate [c] . split c == id -- > split == splitWith . (==) -- -- As for all splitting functions in this library, this function does -- not copy the substrings, it just constructs new 'ByteStrings' that -- are slices of the original. -- split :: Char -> ByteString -> [ByteString] split = L.split . c2w {-# INLINE split #-} -- | /O(n)/ Splits a 'ByteString' into components delimited by -- separators, where the predicate returns True for a separator element. -- The resulting components do not contain the separators. Two adjacent -- separators result in an empty component in the output. eg. -- -- > splitWith (=='a') "aabbaca" == ["","","bb","c",""] -- splitWith :: (Char -> Bool) -> ByteString -> [ByteString] splitWith f = L.splitWith (f . w2c) {-# INLINE splitWith #-} -- | The 'groupBy' function is the non-overloaded version of 'group'. groupBy :: (Char -> Char -> Bool) -> ByteString -> [ByteString] groupBy k = L.groupBy (\a b -> k (w2c a) (w2c b)) -- | /O(1)/ 'ByteString' index (subscript) operator, starting from 0. index :: ByteString -> Int64 -> Char index = (w2c .) . L.index {-# INLINE index #-} -- | /O(n)/ The 'elemIndex' function returns the index of the first -- element in the given 'ByteString' which is equal (by memchr) to the -- query element, or 'Nothing' if there is no such element. elemIndex :: Char -> ByteString -> Maybe Int64 elemIndex = L.elemIndex . c2w {-# INLINE elemIndex #-} -- | /O(n)/ The 'elemIndices' function extends 'elemIndex', by returning -- the indices of all elements equal to the query element, in ascending order. elemIndices :: Char -> ByteString -> [Int64] elemIndices = L.elemIndices . c2w {-# INLINE elemIndices #-} -- | The 'findIndex' function takes a predicate and a 'ByteString' and -- returns the index of the first element in the ByteString satisfying the predicate. findIndex :: (Char -> Bool) -> ByteString -> Maybe Int64 findIndex f = L.findIndex (f . w2c) {-# INLINE findIndex #-} -- | The 'findIndices' function extends 'findIndex', by returning the -- indices of all elements satisfying the predicate, in ascending order. findIndices :: (Char -> Bool) -> ByteString -> [Int64] findIndices f = L.findIndices (f . w2c) -- | count returns the number of times its argument appears in the ByteString -- -- > count == length . elemIndices -- > count '\n' == length . lines -- -- But more efficiently than using length on the intermediate list. count :: Char -> ByteString -> Int64 count c = L.count (c2w c) -- | /O(n)/ 'elem' is the 'ByteString' membership predicate. This -- implementation uses @memchr(3)@. elem :: Char -> ByteString -> Bool elem c = L.elem (c2w c) {-# INLINE elem #-} -- | /O(n)/ 'notElem' is the inverse of 'elem' notElem :: Char -> ByteString -> Bool notElem c = L.notElem (c2w c) {-# INLINE notElem #-} -- | /O(n)/ 'filter', applied to a predicate and a ByteString, -- returns a ByteString containing those characters that satisfy the -- predicate. filter :: (Char -> Bool) -> ByteString -> ByteString filter f = L.filter (f . w2c) {-# INLINE filter #-} {- -- | /O(n)/ and /O(n\/c) space/ A first order equivalent of /filter . -- (==)/, for the common case of filtering a single Char. It is more -- efficient to use /filterChar/ in this case. -- -- > filterChar == filter . (==) -- -- filterChar is around 10x faster, and uses much less space, than its -- filter equivalent -- filterChar :: Char -> ByteString -> ByteString filterChar c ps = replicate (count c ps) c {-# INLINE filterChar #-} {-# RULES "ByteString specialise filter (== x)" forall x. filter ((==) x) = filterChar x #-} {-# RULES "ByteString specialise filter (== x)" forall x. filter (== x) = filterChar x #-} -} -- | /O(n)/ The 'find' function takes a predicate and a ByteString, -- and returns the first element in matching the predicate, or 'Nothing' -- if there is no such element. find :: (Char -> Bool) -> ByteString -> Maybe Char find f ps = w2c `fmap` L.find (f . w2c) ps {-# INLINE find #-} {- -- | /O(n)/ A first order equivalent of /filter . (==)/, for the common -- case of filtering a single Char. It is more efficient to use -- filterChar in this case. -- -- > filterChar == filter . (==) -- -- filterChar is around 10x faster, and uses much less space, than its -- filter equivalent -- filterChar :: Char -> ByteString -> ByteString filterChar c = L.filterByte (c2w c) {-# INLINE filterChar #-} -- | /O(n)/ A first order equivalent of /filter . (\/=)/, for the common -- case of filtering a single Char out of a list. It is more efficient -- to use /filterNotChar/ in this case. -- -- > filterNotChar == filter . (/=) -- -- filterNotChar is around 3x faster, and uses much less space, than its -- filter equivalent -- filterNotChar :: Char -> ByteString -> ByteString filterNotChar c = L.filterNotByte (c2w c) {-# INLINE filterNotChar #-} -} -- | /O(n)/ 'zip' takes two ByteStrings and returns a list of -- corresponding pairs of Chars. If one input ByteString is short, -- excess elements of the longer ByteString are discarded. This is -- equivalent to a pair of 'unpack' operations, and so space -- usage may be large for multi-megabyte ByteStrings zip :: ByteString -> ByteString -> [(Char,Char)] zip ps qs | L.null ps || L.null qs = [] | otherwise = (head ps, head qs) : zip (L.tail ps) (L.tail qs) -- | 'zipWith' generalises 'zip' by zipping with the function given as -- the first argument, instead of a tupling function. For example, -- @'zipWith' (+)@ is applied to two ByteStrings to produce the list -- of corresponding sums. zipWith :: (Char -> Char -> a) -> ByteString -> ByteString -> [a] zipWith f = L.zipWith ((. w2c) . f . w2c) -- | 'lines' breaks a ByteString up into a list of ByteStrings at -- newline Chars. The resulting strings do not contain newlines. -- -- As of bytestring 0.9.0.3, this function is stricter than its -- list cousin. -- lines :: ByteString -> [ByteString] lines Empty = [] lines (Chunk c0 cs0) = loop0 c0 cs0 where -- this is a really performance sensitive function but the -- chunked representation makes the general case a bit expensive -- however assuming a large chunk size and normalish line lengths -- we will find line endings much more frequently than chunk -- endings so it makes sense to optimise for that common case. -- So we partition into two special cases depending on whether we -- are keeping back a list of chunks that will eventually be output -- once we get to the end of the current line. -- the common special case where we have no existing chunks of -- the current line loop0 :: S.ByteString -> ByteString -> [ByteString] loop0 c cs = case B.elemIndex (c2w '\n') c of Nothing -> case cs of Empty | B.null c -> [] | otherwise -> Chunk c Empty : [] (Chunk c' cs') | B.null c -> loop0 c' cs' | otherwise -> loop c' [c] cs' Just n | n /= 0 -> Chunk (B.unsafeTake n c) Empty : loop0 (B.unsafeDrop (n+1) c) cs | otherwise -> Empty : loop0 (B.unsafeTail c) cs -- the general case when we are building a list of chunks that are -- part of the same line loop :: S.ByteString -> [S.ByteString] -> ByteString -> [ByteString] loop c line cs = case B.elemIndex (c2w '\n') c of Nothing -> case cs of Empty -> let c' = revChunks (c : line) in c' `seq` (c' : []) (Chunk c' cs') -> loop c' (c : line) cs' Just n -> let c' = revChunks (B.unsafeTake n c : line) in c' `seq` (c' : loop0 (B.unsafeDrop (n+1) c) cs) {- This function is too strict! Consider, > prop_lazy = (L.unpack . head . lazylines $ L.append (L.pack "a\nb\n") (error "failed")) == "a" fails. Here's a properly lazy version of 'lines' for lazy bytestrings lazylines :: L.ByteString -> [L.ByteString] lazylines s | L.null s = [] | otherwise = let (l,s') = L.break ((==) '\n') s in l : if L.null s' then [] else lazylines (L.tail s') we need a similarly lazy, but efficient version. -} -- | 'unlines' is an inverse operation to 'lines'. It joins lines, -- after appending a terminating newline to each. unlines :: [ByteString] -> ByteString unlines [] = empty unlines ss = (concat $ List.intersperse nl ss) `append` nl -- half as much space where nl = singleton '\n' -- | 'words' breaks a ByteString up into a list of words, which -- were delimited by Chars representing white space. And -- -- > tokens isSpace = words -- words :: ByteString -> [ByteString] words = List.filter (not . L.null) . L.splitWith isSpaceWord8 {-# INLINE words #-} -- | The 'unwords' function is analogous to the 'unlines' function, on words. unwords :: [ByteString] -> ByteString unwords = intercalate (singleton ' ') {-# INLINE unwords #-} -- | readInt reads an Int from the beginning of the ByteString. If -- there is no integer at the beginning of the string, it returns -- Nothing, otherwise it just returns the int read, and the rest of the -- string. {- -- Faster: data MaybeS = NothingS | JustS {-# UNPACK #-} !Int {-# UNPACK #-} !ByteString -} readInt :: ByteString -> Maybe (Int, ByteString) {-# INLINE readInt #-} readInt Empty = Nothing readInt (Chunk x xs) = case w2c (B.unsafeHead x) of '-' -> loop True 0 0 (B.unsafeTail x) xs '+' -> loop False 0 0 (B.unsafeTail x) xs _ -> loop False 0 0 x xs where loop :: Bool -> Int -> Int -> S.ByteString -> ByteString -> Maybe (Int, ByteString) STRICT5_(loop) loop neg i n c cs | B.null c = case cs of Empty -> end neg i n c cs (Chunk c' cs') -> loop neg i n c' cs' | otherwise = case B.unsafeHead c of w | w >= 0x30 && w <= 0x39 -> loop neg (i+1) (n * 10 + (fromIntegral w - 0x30)) (B.unsafeTail c) cs | otherwise -> end neg i n c cs {-# INLINE end #-} end _ 0 _ _ _ = Nothing end neg _ n c cs = e `seq` e where n' = if neg then negate n else n c' = chunk c cs e = n' `seq` c' `seq` Just $! (n',c') -- in n' `seq` c' `seq` JustS n' c' -- | readInteger reads an Integer from the beginning of the ByteString. If -- there is no integer at the beginning of the string, it returns Nothing, -- otherwise it just returns the int read, and the rest of the string. readInteger :: ByteString -> Maybe (Integer, ByteString) readInteger Empty = Nothing readInteger (Chunk c0 cs0) = case w2c (B.unsafeHead c0) of '-' -> first (B.unsafeTail c0) cs0 >>= \(n, cs') -> return (-n, cs') '+' -> first (B.unsafeTail c0) cs0 _ -> first c0 cs0 where first c cs | B.null c = case cs of Empty -> Nothing (Chunk c' cs') -> first' c' cs' | otherwise = first' c cs first' c cs = case B.unsafeHead c of w | w >= 0x30 && w <= 0x39 -> Just $ loop 1 (fromIntegral w - 0x30) [] (B.unsafeTail c) cs | otherwise -> Nothing loop :: Int -> Int -> [Integer] -> S.ByteString -> ByteString -> (Integer, ByteString) STRICT5_(loop) loop d acc ns c cs | B.null c = case cs of Empty -> combine d acc ns c cs (Chunk c' cs') -> loop d acc ns c' cs' | otherwise = case B.unsafeHead c of w | w >= 0x30 && w <= 0x39 -> if d < 9 then loop (d+1) (10*acc + (fromIntegral w - 0x30)) ns (B.unsafeTail c) cs else loop 1 (fromIntegral w - 0x30) (fromIntegral acc : ns) (B.unsafeTail c) cs | otherwise -> combine d acc ns c cs combine _ acc [] c cs = end (fromIntegral acc) c cs combine d acc ns c cs = end (10^d * combine1 1000000000 ns + fromIntegral acc) c cs combine1 _ [n] = n combine1 b ns = combine1 (b*b) $ combine2 b ns combine2 b (n:m:ns) = let t = n+m*b in t `seq` (t : combine2 b ns) combine2 _ ns = ns end n c cs = let c' = chunk c cs in c' `seq` (n, c') -- | Read an entire file /lazily/ into a 'ByteString'. Use 'text mode' -- on Windows to interpret newlines readFile :: FilePath -> IO ByteString readFile f = openFile f ReadMode >>= hGetContents -- | Write a 'ByteString' to a file. writeFile :: FilePath -> ByteString -> IO () writeFile f txt = bracket (openFile f WriteMode) hClose (\hdl -> hPut hdl txt) -- | Append a 'ByteString' to a file. appendFile :: FilePath -> ByteString -> IO () appendFile f txt = bracket (openFile f AppendMode) hClose (\hdl -> hPut hdl txt) -- --------------------------------------------------------------------- -- Internal utilities -- reverse a list of possibly-empty chunks into a lazy ByteString revChunks :: [S.ByteString] -> ByteString revChunks cs = List.foldl' (flip chunk) Empty cs
markflorisson/hpack
testrepo/bytestring-0.9.1.9/Data/ByteString/Lazy/Char8.hs
bsd-3-clause
33,963
0
19
9,887
5,290
3,002
2,288
-1
-1
{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction, OverloadedStrings, PatternGuards #-} {-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-} module KeyFlags.Macros where import Control.Arrow ((***), (>>>)) import Data.Bits (Bits (..), (.&.)) import Data.Char (isAlpha, toLower) import Data.Char (isDigit) import Data.Data (Data, Typeable) import Data.Function (on) import Data.List (nubBy) import Data.Maybe (maybeToList) import qualified Data.Text as T import Language.Haskell.TH (ConQ, DecsQ, ExpQ, MatchQ, Strict (..)) import Language.Haskell.TH (Type (ConT), TypeQ, appE, charL, clause) import Language.Haskell.TH (conE, conP, conT, dataD, funD, integerL) import Language.Haskell.TH (Lit (..), lamCaseE, litE, litP, match, mkName) import Language.Haskell.TH (normalB, normalC, normalC, sigD, wildP) import Language.Haskell.TH (listE) import Numeric (readHex) type CodeTable = [(Either (T.Text, Lit) T.Text, Integer)] camelize :: T.Text -> T.Text camelize = T.concat . map T.toTitle . T.splitOn "_" class (Bits (Mask a), Eq (Mask a)) => Masked a where type Mask a toMask :: a -> Mask a compatible :: Masked a => a -> a -> Bool compatible a b = testCode a $ toMask b testCode :: Masked a => a -> Mask a -> Bool testCode a m = toMask a .&. m == toMask a procLR :: CodeTable -> CodeTable procLR table = let ls = collectSuffix "L" rs = collectSuffix "R" lrs = [ (Right n, b .&. b') | (n, b) <- ls , b' <- maybeToList $ lookup n rs ] in table ++ lrs where standalones = [(t, n) | (Right t, n) <- table ] collectSuffix suf = nubBy ((==) `on` fst) [ (pre, n) | (t, n) <- standalones , pre <- maybeToList $ T.stripSuffix suf t ] defineKeyCode :: String -> TypeQ -> CodeTable -> DecsQ defineKeyCode name0 typ table = do let name = T.unpack $ T.toTitle $ T.pack name0 enumName = mkName $ toLower (head name) : tail name ++ "s" funName = mkName $ "decode" ++ name ddef <- dataD (return []) (mkName name) [] (buildCons table) [''Show, ''Eq, ''Ord, ''Data, ''Typeable] fsig <- sigD funName [t| $typ -> Maybe $(conT $ mkName name) |] let decs = flip map table $ \ (val, num) -> clause [litP $ integerL num] (normalB $ [| Just $(buildVal val) |]) [] maskBody = lamCaseE $ map buildMatch table fdef <- funD funName $ decs ++ [clause [wildP] (normalB [| Nothing |]) []] inst <- [d| instance Masked $(conT $ mkName name) where type Mask $(conT $ mkName name) = $(typ) toMask = $(maskBody) |] esig <- sigD enumName [t| [$(conT $ mkName name)] |] enums <- funD enumName [ clause [] (normalB $ listE $ map (buildVal . fst) table) []] return $ [ddef, fsig, fdef, esig, enums] ++ inst buildMatch :: (Either (T.Text, Lit) T.Text, Integer) -> MatchQ buildMatch (Left (txt, ch), n) = match (conP (mkName $ T.unpack txt) [litP ch]) (normalB $ litE $ integerL n) [] buildMatch (Right txt, n) = match (conP (mkName $ T.unpack txt) []) (normalB $ litE $ integerL n) [] buildVal :: Either (T.Text, Lit) T.Text -> ExpQ buildVal (Left (txt, c)) = conE (mkName $ T.unpack txt) `appE` litE c buildVal (Right txt) = conE $ mkName $ T.unpack txt buildCons :: CodeTable -> [ConQ] buildCons = map (uncurry normalC) . nubBy ((==) `on` fst) . map (toCon . fst) where toCon i = let n = mkName $ T.unpack $ either fst id i sts = case i of Left (_, CharL _) -> [return (IsStrict, ConT ''Char)] Left (_, IntegerL _) -> [return (IsStrict, ConT ''Int)] _ -> [] in (n, sts) toConName :: T.Text -> Either (T.Text, Lit) T.Text toConName str | T.length str == 1 && isAlpha (T.head str) = Left ("Char", charL $ toLower $ T.head str) | Just num <- prefixed "KEY_" str = Left ("Char", num) | Just num <- prefixed "JIS_" str = Left ("JIS", num) | Just num <- prefixed "KEYPAD_" str = Left ("Keypad", num) | Just num <- readFn str = Left ("Fn", num) | otherwise = Right $ camelize str readFn :: T.Text -> Maybe Lit readFn t = case T.stripPrefix "F" t of Just s | T.all isDigit s -> Just $ integerL $ read $ T.unpack s _ -> Nothing prefixed :: T.Text -> T.Text -> Maybe Lit prefixed pre str = T.stripPrefix pre str >>= go where go "UNDERSCORE" = Just $ charL '_' go "ATMARK" = Just $ charL '@' go "BRACKET_LEFT" = Just $ charL '[' go "BRACKET_RIGHT" = Just $ charL ']' go "COLON" = Just $ charL ':' go "HAT" = Just $ charL '^' go "YEN" = Just $ charL '¥' go "DOLLAR" = Just $ charL '$' go "MINUS" = Just $ charL '-' go "EQUAL" = Just $ charL '=' go t | T.length t == 1 = Just $ charL $ T.head t | otherwise = Nothing parse :: T.Text -> CodeTable parse = T.lines >>> filter (\a -> not (T.null a) && not ("//" `T.isPrefixOf` a)) >>> map (T.breakOn " " >>> toConName *** (runReadS readHex . T.drop 2 . T.strip)) runReadS :: ReadS a -> T.Text -> a runReadS rd str = case rd $ T.unpack str of [(a, "")] -> a _ -> error $ "runReadS: " ++ show str
konn/hskk
cocoa/KeyFlags/Macros.hs
bsd-3-clause
5,480
0
18
1,601
2,229
1,169
1,060
113
11
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, ImplicitParams #-} {-# LANGUAGE RankNTypes, TypeInType #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Err -- Copyright : (c) The University of Glasgow, 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- The "GHC.Err" module defines the code for the wired-in error functions, -- which have a special type in the compiler (with \"open tyvars\"). -- -- We cannot define these functions in a module where they might be used -- (e.g., "GHC.Base"), because the magical wired-in type will get confused -- with what the typechecker figures out. -- ----------------------------------------------------------------------------- module GHC.Err( absentErr, error, errorWithoutStackTrace, undefined ) where import GHC.CString () import GHC.Types (Char, Levity) import GHC.Stack.Types import GHC.Prim import GHC.Integer () -- Make sure Integer is compiled first -- because GHC depends on it in a wired-in way -- so the build system doesn't see the dependency import {-# SOURCE #-} GHC.Exception( errorCallWithCallStackException ) -- | 'error' stops execution and displays an error message. error :: forall (v :: Levity). forall (a :: TYPE v). HasCallStack => [Char] -> a error s = raise# (errorCallWithCallStackException s ?callStack) -- Bleh, we should be using 'GHC.Stack.callStack' instead of -- '?callStack' here, but 'GHC.Stack.callStack' depends on -- 'GHC.Stack.popCallStack', which is partial and depends on -- 'error'.. Do as I say, not as I do. -- | A variant of 'error' that does not produce a stack trace. -- -- @since 4.9.0.0 errorWithoutStackTrace :: forall (v :: Levity). forall (a :: TYPE v). [Char] -> a errorWithoutStackTrace s = -- we don't have withFrozenCallStack yet, so we just inline the definition let ?callStack = freezeCallStack emptyCallStack in error s -- Note [Errors in base] -- ~~~~~~~~~~~~~~~~~~~~~ -- As of base-4.9.0.0, `error` produces a stack trace alongside the -- error message using the HasCallStack machinery. This provides -- a partial stack trace, containing the call-site of each function -- with a HasCallStack constraint. -- -- In base, however, the only functions that have such constraints are -- error and undefined, so the stack traces from partial functions in -- base will never contain a call-site in user code. Instead we'll -- usually just get the actual call to error. Base functions already -- have a good habit of providing detailed error messages, including the -- name of the offending partial function, so the partial stack-trace -- does not provide any extra information, just noise. Thus, we export -- the callstack-aware error, but within base we use the -- errorWithoutStackTrace variant for more hygienic error messages. -- | A special case of 'error'. -- It is expected that compilers will recognize this and insert error -- messages which are more appropriate to the context in which 'undefined' -- appears. undefined :: forall (v :: Levity). forall (a :: TYPE v). HasCallStack => a undefined = error "Prelude.undefined" -- | Used for compiler-generated error message; -- encoding saves bytes of string junk. absentErr :: a absentErr = errorWithoutStackTrace "Oops! The program has entered an `absent' argument!\n"
nushio3/ghc
libraries/base/GHC/Err.hs
bsd-3-clause
3,615
0
9
689
306
198
108
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} -- | -- Module : Data.Array.Accelerate.Math.DFT -- Copyright : [2012] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Compute the Discrete Fourier Transform (DFT) along the lower order dimension -- of an array. -- -- This uses a naïve algorithm which takes O(n^2) time. However, you can -- transform an array with an arbitrary extent, unlike with FFT which requires -- each dimension to be a power of two. -- -- The `dft` and `idft` functions compute the roots of unity as needed. If you -- need to transform several arrays with the same extent than it is faster to -- compute the roots once using `rootsOfUnity` or `inverseRootsOfUnity` -- respectively, then call `dftG` directly. -- -- You can also compute single values of the transform using `dftGS` -- module Data.Array.Accelerate.Math.DFT ( dft, idft, dftG, dftGS, ) where import Prelude as P hiding ((!!)) import Data.Array.Accelerate as A import Data.Array.Accelerate.Math.DFT.Roots import Data.Array.Accelerate.Math.Complex -- | Compute the DFT along the low order dimension of an array -- dft :: (Shape sh, Slice sh, Elt e, IsFloating e) => Acc (Array (sh:.Int) (Complex e)) -> Acc (Array (sh:.Int) (Complex e)) dft v = dftG (rootsOfUnity (shape v)) v -- | Compute the inverse DFT along the low order dimension of an array -- idft :: (Shape sh, Slice sh, Elt e, IsFloating e) => Acc (Array (sh:.Int) (Complex e)) -> Acc (Array (sh:.Int) (Complex e)) idft v = let sh = shape v n = indexHead sh roots = inverseRootsOfUnity sh scale = lift (A.fromIntegral n, constant 0) in A.map (/scale) $ dftG roots v -- | Generic function for computation of forward and inverse DFT. This function -- is also useful if you transform many arrays of the same extent, and don't -- want to recompute the roots for each one. -- -- The extent of the input and roots must match. -- dftG :: forall sh e. (Shape sh, Slice sh, Elt e, IsFloating e) => Acc (Array (sh:.Int) (Complex e)) -- ^ roots of unity -> Acc (Array (sh:.Int) (Complex e)) -- ^ input array -> Acc (Array (sh:.Int) (Complex e)) dftG roots arr = A.fold (+) (constant (0,0)) $ A.zipWith (*) arr' roots' where base = shape arr l = indexHead base extend = lift (base :. shapeSize base) -- Extend the entirety of the input arrays into a higher dimension, reading -- roots from the appropriate places and then reduce along this axis. -- -- In the calculation for 'roots'', 'i' is the index into the extended -- dimension, with corresponding base index 'ix' which we are attempting to -- calculate the single DFT value of. The rest proceeds as per 'dftGS'. -- arr' = A.generate extend (\ix' -> let i = indexHead ix' in arr !! i) roots' = A.generate extend (\ix' -> let ix :. i = unlift ix' sh :. n = unlift (fromIndex base i) :: Exp sh :. Exp Int k = indexHead ix in roots ! lift (sh :. (k*n) `mod` l)) -- | Compute a single value of the DFT. -- dftGS :: forall sh e. (Shape sh, Slice sh, Elt e, IsFloating e) => Exp (sh :. Int) -- ^ index of the value we want -> Acc (Array (sh:.Int) (Complex e)) -- ^ roots of unity -> Acc (Array (sh:.Int) (Complex e)) -- ^ input array -> Acc (Scalar (Complex e)) dftGS ix roots arr = let k = indexHead ix l = indexHead (shape arr) -- all the roots we need to multiply with roots' = A.generate (shape arr) (\ix' -> let sh :. n = unlift ix' :: Exp sh :. Exp Int in roots ! lift (sh :. (k*n) `mod` l)) in A.foldAll (+) (constant (0,0)) $ A.zipWith (*) arr roots'
robeverest/accelerate-fft
Data/Array/Accelerate/Math/DFT.hs
bsd-3-clause
4,276
0
20
1,300
1,013
554
459
48
1
{-# LANGUAGE OverloadedStrings #-} {- Use the 'unix' library to write the log file. Why not 'Handles' you ask? I believe it is because 'Handles' lock the file, and we want to be able to serve the file while it is still being written. -} module Network.IRC.Bot.PosixLogger where import Control.Concurrent.Chan import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.ByteString.Char8 (pack, unpack) import Data.Time.Calendar (Day(..)) import Data.Time.Clock (UTCTime(..), addUTCTime, getCurrentTime) import Data.Time.Format (formatTime) import Data.Time.Locale.Compat (defaultTimeLocale) import qualified Foreign.C.Error as C import Foreign.Ptr (castPtr) import Network.IRC (Command, Message(Message, msg_prefix, msg_command, msg_params), Prefix(NickName), UserName, encode, decode, joinChan, nick, user) import Network.IRC.Bot.Commands import System.Directory (createDirectoryIfMissing) import System.FilePath ((</>)) import System.Posix.ByteString ( Fd, OpenMode(WriteOnly), OpenFileFlags(append), closeFd, defaultFileFlags , openFd ) import System.Posix.IO.ByteString (fdWriteBuf) -- TODO: This should be modified so that a formatting filter can be applied to the log messages -- TODO: should be updated so that log file name matches channel -- TODO: should support multiple channels posixLogger :: Maybe FilePath -> ByteString -> Chan Message -> IO () posixLogger mLogDir channel logChan = do now <- getCurrentTime let logDay = utctDay now logFd <- openLog now logLoop logDay logFd where openLog :: UTCTime -> IO (Maybe Fd) openLog now = case mLogDir of Nothing -> return Nothing (Just logDir) -> do let logPath = logDir </> (formatTime defaultTimeLocale ((dropWhile (== '#') (unpack channel)) ++ "-%Y-%m-%d.txt") now) createDirectoryIfMissing True logDir fd <- openFd (pack logPath) WriteOnly (Just 0o0644) (defaultFileFlags { append = True }) return (Just fd) updateLogHandle :: UTCTime -> Day -> Maybe Fd -> IO (Day, Maybe Fd) updateLogHandle now logDay Nothing = return (logDay, Nothing) updateLogHandle now logDay (Just logFd) | logDay == (utctDay now) = return (logDay, Just logFd) | otherwise = do closeFd logFd nowHandle <- openLog now return (utctDay now, nowHandle) logLoop :: Day -> Maybe Fd -> IO () logLoop logDay mLogFd = do msg <- readChan logChan now <- getCurrentTime (logDay', mLogFd') <- updateLogHandle now logDay mLogFd let mPrivMsg = toPrivMsg msg case mPrivMsg of (Just (PrivMsg (Just (NickName nick _user _server)) receivers msg)) | channel `elem` receivers -> do let logMsg = B.concat [ pack (formatTime defaultTimeLocale "%X " now) , "<" , nick , "> " , msg , "\n" ] case mLogFd' of Nothing -> return () (Just logFd') -> fdWrites logFd' logMsg >> return () return () -- hPutStrLn logFd logMsg _ -> return () logLoop logDay' mLogFd' fdWrites :: Fd -> ByteString -> IO () fdWrites fd bs = B.useAsCStringLen bs $ \(cstring, len) -> if len <= 0 then return () else do c <- C.throwErrnoIfMinus1Retry "fdWrites" $ fdWriteBuf fd (castPtr cstring) (fromIntegral len) if (fromIntegral c) == (fromIntegral len) then return () else fdWrites fd (B.drop (fromIntegral c) bs)
eigengrau/haskell-ircbot
Network/IRC/Bot/PosixLogger.hs
bsd-3-clause
3,977
0
23
1,310
1,035
548
487
71
5
module Main where import Control.Concurrent.MVar import System.Win32.SystemServices.Services main = do mStop <- newEmptyMVar startServiceCtrlDispatcher "Test" 3000 (handler mStop) $ \_ _ h -> do setServiceStatus h running takeMVar mStop setServiceStatus h stopped handler mStop hStatus STOP = do setServiceStatus hStatus stopPending putMVar mStop () return True handler _ _ INTERROGATE = return True handler _ _ _ = return False running = SERVICE_STATUS WIN32_OWN_PROCESS RUNNING [ACCEPT_STOP] nO_ERROR 0 0 0 stopped = SERVICE_STATUS WIN32_OWN_PROCESS STOPPED [] nO_ERROR 0 0 0 stopPending = SERVICE_STATUS WIN32_OWN_PROCESS STOP_PENDING [ACCEPT_STOP] nO_ERROR 0 0 0
nick0x01/Win32-services
examples/simple.hs
bsd-3-clause
725
0
11
148
214
104
110
18
1
-- | -- Copyright : (c) Sam Truzjan 2013 -- License : BSD3 -- Maintainer : pxqr.sta@gmail.com -- Stability : experimental -- Portability : portable -- -- All stuff relate to command line options should be in this -- module: parsers, help, reasonable defaults. -- module UReader.Options ( Order (..) , Style (..) , Options (..) , getOptions ) where import Control.Monad import Data.Implicit import Data.Monoid import Network.URI import Options.Applicative import System.Directory import System.FilePath import UReader.Rendering import UReader.Outline styleParser :: Parser Style styleParser = Style <$> option ( long "order" <> short 'o' <> metavar "ORDER" <> value NewFirst <> showDefault <> help "Specifies entries order: either NewFirst or OldFirst" ) <*> switch ( long "description" <> short 'd' <> help "Include auxilary info like rss version and channel title" ) <*> switch ( long "merge" <> short 'm' <> help "Merge multiple feed info one by time" ) <*> switch ( long "unread" <> short 'u' <> help "Show only unread feed and ignore feed will shown in future" ) feedListParser :: Implicit_ FilePath => Parser FilePath feedListParser = strOption ( long "feeds" <> metavar "PATH" <> value param_ <> showDefault <> help "Path to file with list of feed urls" ) feedLinkParser :: Parser URI feedLinkParser = argument parseURI ( metavar "URI" <> help "URI to feed" ) intervalTime :: Parser Int intervalTime = option ( long "interval" <> short 'i' <> metavar "SECONDS" <> value 600 <> showDefault <> help "Minimal interval between feed updates" ) feedGroupParser :: Parser Selector feedGroupParser = optional $ argument Just ( metavar "GROUP" <> help "Feed group used to specify some subset of feeds" ) feedParentParser :: Parser String feedParentParser = argument Just ( metavar "GROUP" <> help "The group feed belongs to" ) feedTopicParser :: Parser String feedTopicParser = argument Just ( metavar "TOPIC" <> help "The main feed topic used as feed name" ) data Options = Add { feedList :: FilePath , feedParent :: String , feedTopic :: String , feedURI :: URI } | Batch { feedList :: FilePath , feedStyle :: Style , feedGroup :: Selector } | Preview { feedURI :: URI } | Stream { feedList :: FilePath , feedInterval :: Int , feedGroup :: Selector } | Index { feedList :: FilePath , feedGroup :: Selector } | Version deriving (Show, Eq) addParser :: Implicit_ String => Parser Options addParser = Add <$> feedListParser <*> feedParentParser <*> feedTopicParser <*> feedLinkParser addInfo :: Implicit_ String => ParserInfo Options addInfo = info (helper <*> addParser) modifier where modifier = progDesc "Add a feed to the feed list" streamParser :: Implicit_ String => Parser Options streamParser = Stream <$> feedListParser <*> intervalTime <*> feedGroupParser streamInfo :: Implicit_ String => ParserInfo Options streamInfo = info (helper <*> streamParser) modifier where modifier = progDesc "Show feed as never ending stream" feedParser :: Implicit_ String => Parser Options feedParser = Batch <$> feedListParser <*> styleParser <*> feedGroupParser feedInfo :: Implicit_ String => ParserInfo Options feedInfo = info (helper <*> feedParser) modifier where modifier = progDesc "Show all feeds specified in feed list" previewParser :: Parser Options previewParser = Preview <$> feedLinkParser previewInfo :: ParserInfo Options previewInfo = info (helper <*> previewParser) modifier where modifier = progDesc "Show feed specified by URI or file path" indexParser :: Implicit_ FilePath => Parser Options indexParser = Index <$> feedListParser <*> feedGroupParser indexInfo :: Implicit_ FilePath => ParserInfo Options indexInfo = info (helper <*> indexParser) modifier where modifier = progDesc "Show your feed list" versionParser :: Parser Options versionParser = flag' Version ( long "version" <> short 'V' <> hidden <> help "Show program version and exit" ) optionsParser :: Implicit_ String => Parser Options optionsParser = subparser $ mconcat [ command "add" addInfo , command "feed" feedInfo , command "index" indexInfo , command "stream" streamInfo , command "view" previewInfo ] optionsInfo :: Implicit_ String => ParserInfo Options optionsInfo = info (helper <*> (versionParser <|> optionsParser)) modifier where modifier = fullDesc <> header hdr <> progDesc desc hdr = "ureader is minimalistic CLI RSS reader" desc = "$ ureader COMMAND --help # for info about particular command" getDefaultFeeds :: IO FilePath getDefaultFeeds = do udir <- getAppUserDataDirectory "ureader" createDirectoryIfMissing False udir let configPath = udir </> "feeds" exist <- doesFileExist configPath unless exist $ do writeFile configPath "" return configPath getOptions :: IO Options getOptions = getDefaultFeeds >>= (execParser optionsInfo $~)
pxqr/ureader
src/UReader/Options.hs
bsd-3-clause
5,400
0
16
1,396
1,212
621
591
-1
-1
{- Church Encodings - - - - - - - - - - - - - By Risto Stevcev -} module Church where import Prelude hiding (succ, pred, and, or, not, exp, head, tail) -- Church Boolean (True) -- λt.λf.t true :: a -> a -> a true = \t -> \f -> t -- Church Boolean (False) -- λt.λf.f false :: a -> a -> a false = \t -> \f -> f -- Church AND -- λa.λb.a b false and :: (a1 -> (a -> a -> a) -> a0) -> a1 -> a0 and = \a -> \b -> a b false -- Church OR -- λa.λb.a true b or :: ((a -> a -> a) -> a1 -> a0) -> a1 -> a0 or = \a -> \b -> a true b -- Church NOT -- λp.λa.λb.p b a not = \p -> \a -> \b -> p b a -- Church XOR -- λa.λb.a (not b) b xor = \a -> \b -> a (not b) b -- Church Numeral: 0 -- λf.λx.x zero :: (a -> a) -> a -> a zero = \f -> \x -> x -- Church Numeral: 1 -- λf.λx.f x one :: (a -> a) -> a -> a one = \f -> \x -> f x -- Church Numeral: 2 -- λf.λx.f (f x) two :: (a -> a) -> a -> a two = \f -> \x -> f (f x) -- Church Numeral: 3 -- λf.λx.f (f (f x)) three :: (a -> a) -> a -> a three = \f -> \x -> f (f (f x)) -- Church Numeral: n (where n ∈ ℕ) -- num 0 = λf.λx.x -- num n = λf.λx.f (num (n-1) f x) num :: Integer -> (a -> a) -> a -> a; num 0 = \f -> \x -> x; num n = \f -> \x -> f (num (n-1) f x) -- Church Conditional (If/Else) -- λp.λa.λb.p a b ifelse :: (a -> a -> a) -> a -> a -> a ifelse = \p -> \a -> \b -> p a b -- Church Comparison (Check if 0) -- λn.n (λx.false) true is_zero :: ((a2 -> a -> a -> a) -> (a1 -> a1 -> a1) -> a0) -> a0 is_zero = \n -> n (\x -> false) true -- Convert Church Numeral to Haskell Integer -- λa.a (λb.b+1) (0) unchurch_num :: ((Integer -> Integer) -> Integer -> a) -> a unchurch_num = \a -> a (\b -> b + 1) (0) -- Convert Church Boolean to Haskell Bool -- (λa.λb.λc.c a b) True False unchurch_bool :: (Bool -> Bool -> a) -> a unchurch_bool = (\a -> \b -> \c -> c a b) True False -- Church Successor -- λn.λf.λx.f (n f x) succ :: ((a -> a) -> a -> a) -> (a -> a) -> a -> a succ = \n -> \f -> \x -> f (n f x) -- Church Predecessor -- λn.λf.λx.n (λg.λh.h (g f)) (λu.x) (λu.u) pred :: (((a3 -> a2) -> (a2 -> a1) -> a1) -> (a4 -> a5) -> (a6 -> a6) -> a) -> a3 -> a5 -> a pred = \n -> \f -> \x -> n (\g -> \h -> h (g f)) (\u -> x) (\u -> u) -- Church Addition -- λm.λn.λf.λx.m f (n f x) add :: (a2 -> a1 -> a) -> (a2 -> a3 -> a1) -> a2 -> a3 -> a add = \m -> \n -> \f -> \x -> m f (n f x) -- Church Multiplication -- λm.λn.λf.m (n f) mult :: (a1 -> a) -> (a2 -> a1) -> a2 -> a mult = \m -> \n -> \f -> m (n f) -- Church Exponentiation -- λm.λn.n m exp :: a1 -> (a1 -> a) -> a exp = \m -> \n -> n m -- Church Pairs -- λx.λy.λz.z x y pair :: a1 -> a2 -> (a1 -> a2 -> a) -> a pair = \x -> \y -> \z -> z x y -- Church Pairs (first item) -- λp.p -> (λx.λy.x) first :: ((a2 -> a1 -> a2) -> a) -> a first = \p -> p (\x -> \y -> x) -- Church Pairs (second item) -- λp.p -> (λx.λy.y) second :: ((a1 -> a2 -> a2) -> a) -> a second = \p -> p (\x -> \y -> y) -- Church Pairs (nil) -- pair true true nil :: ((a1 -> a1 -> a1) -> (a2 -> a2 -> a2) -> a) -> a nil = pair true true -- Church Comparison (is_nil) -- first (true for nil pair) is_nil :: ((a2 -> a1 -> a2) -> a) -> a is_nil = first -- Church Cons -- λh.λt.pair false (pair h t) cons :: a2 -> a3 -> ((a1 -> a1 -> a1) -> ((a2 -> a3 -> a4) -> a4) -> a) -> a cons = \h -> \t -> pair false (pair h t) -- Church Head -- λz.first (second z) head :: ((a3 -> a4 -> a4) -> (a2 -> a1 -> a2) -> a) -> a head = \z -> first (second z) -- Church Tail -- λz.second (second z) tail :: ((a3 -> a4 -> a4) -> (a1 -> a2 -> a2) -> a) -> a tail = \z -> second (second z)
Risto-Stevcev/haskell-church-encodings
Rank1Types/Church.hs
bsd-3-clause
3,639
0
15
960
1,628
927
701
60
1
module Main where import Control.DeepSeq import Control.Exception import Control.Monad.IO.Class import Data.IORef import Data.Proxy import Network.BSD (getHostByName, hostAddress) import Network.Socket (SockAddr(..)) import System.Environment import System.Exit import Text.Read import Game.Core import Game.GoreAndAsh import Game.GoreAndAsh.Actor import Game.GoreAndAsh.Network import Game.GoreAndAsh.Sync import FPS import Game simulationFPS :: Int simulationFPS = 60 parseArgs :: IO (String, Int) parseArgs = do args <- getArgs case args of [h, p] -> case readMaybe p of Nothing -> fail "Failed to parse port" Just pint -> return (h, pint) _ -> fail "Misuse of arguments: gore-and-ash-server HOST PORT" main :: IO () main = withModule (Proxy :: Proxy AppMonad) $ do gs <- newGameState $ runActor' mainWire gsRef <- newIORef gs fps <- makeFPSBounder simulationFPS (host, port) <- liftIO parseArgs firstStep fps host port gs gsRef `onCtrlC` exitHandler gsRef where -- | What to do on emergency exit exitHandler gsRef = do gs <- readIORef gsRef cleanupGameState gs exitSuccess -- | Resolve given hostname and port getAddr s p = do he <- getHostByName s return $ SockAddrInet p $ hostAddress he -- | Initialization step firstStep fps host port gs gsRef = do (_, gs') <- stepGame gs $ do networkSetDetailedLoggingM False syncSetLoggingM True syncSetRoleM SyncMaster addr <- liftIO $ getAddr host (fromIntegral port) networkBind (Just addr) 100 2 0 0 writeIORef gsRef gs' gameLoop fps gs' gsRef -- | Normal game loop gameLoop fps gs gsRef = do waitFPSBound fps (a, gs') <- stepGame gs (return ()) writeIORef gsRef gs' a `deepseq` gameLoop fps gs' gsRef -- | Executes given handler on Ctrl-C pressing onCtrlC :: IO a -> IO () -> IO a p `onCtrlC` q = catchJust isUserInterrupt p (const $ q >> p `onCtrlC` q) where isUserInterrupt :: AsyncException -> Maybe () isUserInterrupt UserInterrupt = Just () isUserInterrupt _ = Nothing
Teaspot-Studio/gore-and-ash-game
src/server/Main.hs
bsd-3-clause
2,155
0
17
529
660
331
329
61
3
{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE UnicodeSyntax #-} import Shake.It.Off main ∷ IO () main = shake $ do -- phony clean @> is non-unicode operator alternative "clean | clean the project" ∫ cabal ["clean"] -- building object rule #> is non-unicode operator alternative shakeExecutable ♯ do cabal ["install", "--only-dependencies"] cabal ["configure"] cabal ["build"] -- install phony depending on obj, @@> is non-unicode operator alternative -- ##> or ♯♯ is for dependent object rule, ◉ is just uncarry operator "install | install to system" ◉ [shakeExecutable] ∰ cabal ["install"] "test | build and test" ◉ [shakeExecutable] ∰ rawSystem shakeExecutable ["--version"] >>= checkExitCode "rebuild | clean and rebuild" ◉ ["clean"] ∰ do cabal ["configure"] cabal ["build"] where buildPath ∷ String buildPath = "dist/build/shake" shakeExecutable ∷ String shakeExecutable = if | os ∈ ["win32", "mingw32", "cygwin32"] → buildPath </> "shake.exe" | otherwise → buildPath </> "shake"
Heather/Shake.it.off
shake.it.hs
bsd-3-clause
1,129
0
12
260
221
114
107
24
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {- | The functions in this module correspond to the [Consul Event API](https://www.consul.io/api/event). This module is a WIP, feel free to contribute via the [repo on GitHub](https://github.com/AlphaHeavy/consul-haskell). __Missing Functions__ * `createEvent` * `listEvents` -} module Network.Consul.Client.Events ( createEvent , listEvents ) where import Import {- | Create (fire) a new Event Undefined, please feel free to contribute a solution for this missing function. @since 0.0.0.0 -} createEvent :: MonadIO m => ConsulClient -> SessionRequest -> m () createEvent = undefined {- | List Recent Events Undefined, please feel free to contribute a solution for this missing function. @since 0.0.0.0 -} listEvents :: MonadIO m => ConsulClient -> SessionRequest -> m () listEvents = undefined
alphaHeavy/consul-haskell
src/Network/Consul/Client/Events.hs
bsd-3-clause
952
0
9
148
86
50
36
12
1
{-# LANGUAGE OverloadedStrings #-} module Utils.Auth.JWT ( JWTConf(..) ,issued ,verify ) where import Data.Text as T import Data.Maybe import Data.Time as DT import Data.Time.Clock.POSIX as PClock import qualified Web.JWT as JWT data JWTConf = JWTConf { jwtExpired :: Int ,jwtSecret :: T.Text ,jwtPayload :: T.Text } timestamp :: IO Int timestamp = round <$> PClock.getPOSIXTime ifExpired :: Maybe (JWT.JWT JWT.VerifiedJWT) -> Int-> Bool ifExpired vj ts = fromJust $ vj >>= return . JWT.claims >>= \i-> if maybe (0) (round . toRational . JWT.secondsSinceEpoch ) (JWT.exp i) <= ts then return True else return False createClaims :: T.Text -> Int -> Int -> JWT.JWTClaimsSet createClaims payload ts et = JWT.def { JWT.exp = JWT.numericDate $ fromInteger $ toInteger et ,JWT.iat = JWT.numericDate $ fromInteger $ toInteger ts ,JWT.jti = JWT.stringOrURI payload } issued :: JWTConf -> IO JWT.JSON issued conf = do ts <- timestamp let et = ts + (jwtExpired conf) return $ JWT.encodeSigned JWT.HS256 (JWT.secret $ jwtSecret conf) $ createClaims (jwtPayload conf) ts et verify :: JWTConf -> T.Text -> IO (Maybe T.Text) verify conf claims = do ts <- timestamp let jwt = JWT.decodeAndVerifySignature (JWT.secret $ jwtSecret conf) claims case jwt of Nothing -> return Nothing _ -> if ifExpired jwt ts then return Nothing else return $ (jwt >>= return . JWT.claims >>= JWT.jti >>= return . JWT.stringOrURIToText )
DavidAlphaFox/sblog
src/Utils/Auth/JWT.hs
bsd-3-clause
1,503
0
17
324
544
287
257
43
3
module Paths_mysql ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,1,1,4], versionTags = []} bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/kevin/AACS/onping2.0/root/onping/.cabal-sandbox/bin" libdir = "/home/kevin/AACS/onping2.0/root/onping/.cabal-sandbox/lib/x86_64-linux-ghc-7.6.3/mysql-0.1.1.4" datadir = "/home/kevin/AACS/onping2.0/root/onping/.cabal-sandbox/share/x86_64-linux-ghc-7.6.3/mysql-0.1.1.4" libexecdir = "/home/kevin/AACS/onping2.0/root/onping/.cabal-sandbox/libexec" sysconfdir = "/home/kevin/AACS/onping2.0/root/onping/.cabal-sandbox/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "mysql_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "mysql_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "mysql_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "mysql_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "mysql_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
lhuang7/mysql
dist/dist-sandbox-bd9d9ce/build/autogen/Paths_mysql.hs
bsd-3-clause
1,498
0
10
182
371
213
158
28
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ThreeDFX.Tbuffer -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ThreeDFX.Tbuffer ( -- * Extension Support glGetThreeDFXTbuffer, gl_3DFX_tbuffer, -- * Functions glTbufferMask3DFX ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ThreeDFX/Tbuffer.hs
bsd-3-clause
605
0
4
86
44
34
10
6
0
----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Trans.RWS.Lazy -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology, 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : ross@soi.city.ac.uk -- Stability : experimental -- Portability : portable -- -- A monad transformer that combines 'ReaderT', 'WriterT' and 'StateT'. -- This version is lazy; for a strict version, see -- "Control.Monad.Trans.RWS.Strict", which has the same interface. ----------------------------------------------------------------------------- module Control.Monad.Trans.RWS.Lazy ( -- * The RWS monad RWS, rws, runRWS, evalRWS, execRWS, mapRWS, withRWS, -- * The RWST monad transformer RWST(..), evalRWST, execRWST, mapRWST, withRWST, -- * Reader operations ask, local, asks, -- * Writer operations tell, listen, listens, pass, censor, -- * State operations get, put, modify, gets, -- * Lifting other operations liftCallCC, liftCallCC', liftCatch, ) where import Control.Monad.IO.Class import Control.Monad.Trans.Class import Data.Functor.Identity import Control.Applicative import Control.Monad import Control.Monad.Fix import Data.Monoid -- | A monad containing an environment of type @r@, output of type @w@ -- and an updatable state of type @s@. type RWS r w s = RWST r w s Identity -- | Construct an RWS computation from a function. -- (The inverse of 'runRWS'.) rws :: (r -> s -> (a, s, w)) -> RWS r w s a rws f = RWST (\ r s -> Identity (f r s)) -- | Unwrap an RWS computation as a function. -- (The inverse of 'rws'.) runRWS :: RWS r w s a -> r -> s -> (a, s, w) runRWS m r s = runIdentity (runRWST m r s) evalRWS :: RWS r w s a -> r -> s -> (a, w) evalRWS m r s = let (a, _, w) = runRWS m r s in (a, w) execRWS :: RWS r w s a -> r -> s -> (s, w) execRWS m r s = let (_, s', w) = runRWS m r s in (s', w) mapRWS :: ((a, s, w) -> (b, s, w')) -> RWS r w s a -> RWS r w' s b mapRWS f = mapRWST (Identity . f . runIdentity) withRWS :: (r' -> s -> (r, s)) -> RWS r w s a -> RWS r' w s a withRWS = withRWST -- --------------------------------------------------------------------------- -- | A monad transformer adding reading an environment of type @r@, -- collecting an output of type @w@ and updating a state of type @s@ -- to an inner monad @m@. newtype RWST r w s m a = RWST { runRWST :: r -> s -> m (a, s, w) } evalRWST :: (Monad m) => RWST r w s m a -> r -> s -> m (a, w) evalRWST m r s = do ~(a, _, w) <- runRWST m r s return (a, w) execRWST :: (Monad m) => RWST r w s m a -> r -> s -> m (s, w) execRWST m r s = do ~(_, s', w) <- runRWST m r s return (s', w) mapRWST :: (m (a, s, w) -> n (b, s, w')) -> RWST r w s m a -> RWST r w' s n b mapRWST f m = RWST $ \r s -> f (runRWST m r s) withRWST :: (r' -> s -> (r, s)) -> RWST r w s m a -> RWST r' w s m a withRWST f m = RWST $ \r s -> uncurry (runRWST m) (f r s) instance (Functor m) => Functor (RWST r w s m) where fmap f m = RWST $ \r s -> fmap (\ ~(a, s', w) -> (f a, s', w)) $ runRWST m r s instance (Monoid w, Functor m, Monad m) => Applicative (RWST r w s m) where pure = return (<*>) = ap instance (Monoid w, Functor m, MonadPlus m) => Alternative (RWST r w s m) where empty = mzero (<|>) = mplus instance (Monoid w, Monad m) => Monad (RWST r w s m) where return a = RWST $ \_ s -> return (a, s, mempty) m >>= k = RWST $ \r s -> do ~(a, s', w) <- runRWST m r s ~(b, s'',w') <- runRWST (k a) r s' return (b, s'', w `mappend` w') fail msg = RWST $ \_ _ -> fail msg instance (Monoid w, MonadPlus m) => MonadPlus (RWST r w s m) where mzero = RWST $ \_ _ -> mzero m `mplus` n = RWST $ \r s -> runRWST m r s `mplus` runRWST n r s instance (Monoid w, MonadFix m) => MonadFix (RWST r w s m) where mfix f = RWST $ \r s -> mfix $ \ ~(a, _, _) -> runRWST (f a) r s instance (Monoid w) => MonadTrans (RWST r w s) where lift m = RWST $ \_ s -> do a <- m return (a, s, mempty) instance (Monoid w, MonadIO m) => MonadIO (RWST r w s m) where liftIO = lift . liftIO -- --------------------------------------------------------------------------- -- Reader operations -- | Fetch the value of the environment. ask :: (Monoid w, Monad m) => RWST r w s m r ask = RWST $ \r s -> return (r, s, mempty) -- | Execute a computation in a modified environment local :: (Monoid w, Monad m) => (r -> r) -> RWST r w s m a -> RWST r w s m a local f m = RWST $ \r s -> runRWST m (f r) s -- | Retrieve a function of the current environment. asks :: (Monoid w, Monad m) => (r -> a) -> RWST r w s m a asks f = do r <- ask return (f r) -- --------------------------------------------------------------------------- -- Writer operations -- | @'tell' w@ is an action that produces the output @w@. tell :: (Monoid w, Monad m) => w -> RWST r w s m () tell w = RWST $ \_ s -> return ((),s,w) -- | @'listen' m@ is an action that executes the action @m@ and adds its -- output to the value of the computation. listen :: (Monoid w, Monad m) => RWST r w s m a -> RWST r w s m (a, w) listen m = RWST $ \r s -> do ~(a, s', w) <- runRWST m r s return ((a, w), s', w) -- | @'listens' f m@ is an action that executes the action @m@ and adds -- the result of applying @f@ to the output to the value of the computation. -- -- * @'listens' f m = 'liftM' (id *** f) ('listen' m)@ listens :: (Monoid w, Monad m) => (w -> b) -> RWST r w s m a -> RWST r w s m (a, b) listens f m = do ~(a, w) <- listen m return (a, f w) -- | @'pass' m@ is an action that executes the action @m@, which returns -- a value and a function, and returns the value, applying the function -- to the output. pass :: (Monoid w, Monad m) => RWST r w s m (a, w -> w) -> RWST r w s m a pass m = RWST $ \r s -> do ~((a, f), s', w) <- runRWST m r s return (a, s', f w) -- | @'censor' f m@ is an action that executes the action @m@ and -- applies the function @f@ to its output, leaving the return value -- unchanged. -- -- * @'censor' f m = 'pass' ('liftM' (\\x -> (x,f)) m)@ censor :: (Monoid w, Monad m) => (w -> w) -> RWST r w s m a -> RWST r w s m a censor f m = pass $ do a <- m return (a, f) -- --------------------------------------------------------------------------- -- State operations -- | Fetch the current value of the state within the monad. get :: (Monoid w, Monad m) => RWST r w s m s get = RWST $ \_ s -> return (s, s, mempty) -- | @'put' s@ sets the state within the monad to @s@. put :: (Monoid w, Monad m) => s -> RWST r w s m () put s = RWST $ \_ _ -> return ((), s, mempty) -- | @'modify' f@ is an action that updates the state to the result of -- applying @f@ to the current state. modify :: (Monoid w, Monad m) => (s -> s) -> RWST r w s m () modify f = do s <- get put (f s) -- | Get a specific component of the state, using a projection function -- supplied. -- -- * @'gets' f = 'liftM' f 'get'@ gets :: (Monoid w, Monad m) => (s -> a) -> RWST r w s m a gets f = do s <- get return (f s) -- | Uniform lifting of a @callCC@ operation to the new monad. -- This version rolls back to the original state on entering the -- continuation. liftCallCC :: (Monoid w) => ((((a,s,w) -> m (b,s,w)) -> m (a,s,w)) -> m (a,s,w)) -> ((a -> RWST r w s m b) -> RWST r w s m a) -> RWST r w s m a liftCallCC callCC f = RWST $ \r s -> callCC $ \c -> runRWST (f (\a -> RWST $ \_ _ -> c (a, s, mempty))) r s -- | In-situ lifting of a @callCC@ operation to the new monad. -- This version uses the current state on entering the continuation. liftCallCC' :: (Monoid w) => ((((a,s,w) -> m (b,s,w)) -> m (a,s,w)) -> m (a,s,w)) -> ((a -> RWST r w s m b) -> RWST r w s m a) -> RWST r w s m a liftCallCC' callCC f = RWST $ \r s -> callCC $ \c -> runRWST (f (\a -> RWST $ \_ s' -> c (a, s', mempty))) r s -- | Lift a @catchError@ operation to the new monad. liftCatch :: (m (a,s,w) -> (e -> m (a,s,w)) -> m (a,s,w)) -> RWST l w s m a -> (e -> RWST l w s m a) -> RWST l w s m a liftCatch catchError m h = RWST $ \r s -> runRWST m r s `catchError` \e -> runRWST (h e) r s
ekmett/transformers
Control/Monad/Trans/RWS/Lazy.hs
bsd-3-clause
8,374
0
17
2,179
3,313
1,795
1,518
146
1
module LendingClub.Money where type Money = Double
WraithM/lendingclub
src/LendingClub/Money.hs
bsd-3-clause
52
0
4
8
12
8
4
2
0
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Hasmin.Parser.Primitives -- Copyright : (c) 2017 Cristian Adrián Ontivero -- License : BSD3 -- Stability : experimental -- Portability : unknown -- -- Parsers for very basic CSS grammar tokens. -- ----------------------------------------------------------------------------- module Hasmin.Parser.Primitives ( ident , escape , unicode , nmstart , nmchar , int , int' , digits ) where import Control.Applicative ((<|>), some, many) import Data.Attoparsec.Text (Parser, (<?>)) import Data.Monoid ((<>)) import Data.Text.Lazy.Builder (Builder) import Data.Text (Text) import qualified Data.Attoparsec.Text as A import qualified Data.Char as C import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as B -- TODO combine with unicode to make it more efficient -- escape: {unicode}|\\[^\n\r\f0-9a-f] escape :: Parser Builder escape = unicode <|> (mappend <$> (B.singleton <$> A.char '\\') <*> (B.singleton <$> A.satisfy cond)) <?> "not an escape token: {unicode}|\\\\[^\\n\\r\\f0-9a-f]" where cond c = c /= '\n' && c /= '\r' && c /= '\f' && (not . C.isHexDigit) c -- unicode \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])? unicode :: Parser Builder unicode = do backslash <- A.char '\\' hexChars <- A.takeWhile1 C.isHexDigit _ <- A.option mempty (A.string "\r\n" <|> (T.singleton <$> A.satisfy ws)) if T.length hexChars <= 6 then pure $ B.singleton backslash <> B.fromText hexChars else fail "unicode escaped character with length greater than 6" where ws x = x == ' ' || x == '\n' || x == '\r' || x == '\t' || x == '\f' -- ident: -?-?{nmstart}{nmchar}* ident :: Parser Text ident = do dash <- (B.fromText <$> A.string "--") <|> (B.singleton <$> A.char '-') <|> pure mempty ns <- nmstart nc <- mconcat <$> many nmchar pure $ TL.toStrict (B.toLazyText (dash <> ns <> nc)) -- nmstart: [_a-z]|{nonascii}|{escape} nmstart :: Parser Builder nmstart = B.singleton <$> A.satisfy (\c -> C.isAlpha c || (not . C.isAscii) c || c == '_') <|> escape <?> "not an nmstart token: [_a-z]|{nonascii}|{escape}" -- nmchar: [_a-z0-9-]|{nonascii}|{escape} nmchar :: Parser Builder nmchar = B.singleton <$> A.satisfy cond <|> escape where cond x = C.isAlphaNum x || x == '_' || x == '-' || (not . C.isAscii) x -- | \<integer\> data type parser, but into a String instead of an Int, for other -- parsers to use (e.g.: see the parsers int, or rational) int' :: Parser String int' = do sign <- A.char '-' <|> pure '+' d <- digits case sign of '+' -> pure d '-' -> pure (sign:d) _ -> error "int': parsed a number starting with other than [+|-]" -- | Parser for \<integer\>: [+|-][0-9]+ int :: Parser Int int = read <$> int' -- | Parser one or more digits. digits :: Parser String digits = some A.digit
contivero/hasmin
src/Hasmin/Parser/Primitives.hs
bsd-3-clause
3,078
0
17
682
809
436
373
63
3
module Birthdays.Contact.JSON( contactFromJSValue, contactToJSValue ) where import Prelude hiding (id) import Birthdays.Contact import Birthdays.JSON import Birthdays.Time instance JSON Contact where readJSON = contactFromJSValue showJSON = contactToJSValue contactFromJSValue :: JSValue -> Result Contact contactFromJSValue jsvalue = case jsvalue of JSObject o -> contactFromJSObject o _ -> Error "jvalue is not an object" where contactFromJSObject o = maybe (Error "Your JSON data is invalid") Ok $ (do id <- get_string "id" o lastName <- get_string "lastName" o firstName <- get_string "firstName" o birthDate <- get_day "birthDate" o return $ Contact id lastName firstName birthDate) contactToJSValue :: Contact -> JSValue contactToJSValue contact = JSObject $ toJSObject $ [("id", (JSString . toJSString . id) contact) ,("lastName", (JSString . toJSString . lastName) contact) ,("firstName",(JSString . toJSString . firstName) contact) ,("birthDate",(JSString . toJSString . showGregorian . birthDate) contact)]
rbelouin/haskell-contacts
src/Birthdays/Contact/JSON.hs
bsd-3-clause
1,264
0
12
379
315
164
151
25
2
{-# LANGUAGE FlexibleInstances #-} module Graphics.ChalkBoard.CBIR where import Graphics.ChalkBoard.Types (UI,RGB(..),RGBA(..)) import Graphics.ChalkBoard.Internals import Data.Binary import qualified Data.ByteString as BS import Data.ByteString (ByteString) import Control.Monad {-What do we need? * A way of creating a canvas * The canvas has size, pixels, depth, RGB/BW, opt alpha, perhaps 1-bit array. * We have ways of placing slices (rectangles?) of these canvases onto the 'screen'. Difference places, sizes, rotations. * Ways drawing these to a canvas * Ways of importing and exporting canvases -} type BufferId = Int -- make abstact later type StreamId = Int type FragFunctionId = Int data Depth = BitDepth -- 1 bit per pixel | G8BitDepth -- 8 bits per pixel (grey) | RGB24Depth -- (R,G,B), 8 bits per pixel | RGBADepth -- (R,G,B,A), 8 bits per pixel deriving (Show, Eq) -- In a sense, the Depth is the type of our CBBO. -- KM: I would say leave as 0-1 since that's what OpenGL defaults to anyway for colors. Plus then if you want to use it for something else like you did with PointMap?, you can. data Background = BackgroundBit Bool {- AG: does a pixel mean later 'draw this *color* (white/black), or draw this pixel *if* black? KM: I would say the "draw this pixel if true" approach might be faster? Then could use the 8Bit version if you want to force it to draw all pixels? -} | BackgroundG8Bit UI -- this may have the same issue? | BackgroundRGB24Depth RGB | BackgroundRGBADepth RGBA | BackgroundByteString ByteString instance Show Background where show (BackgroundBit b) = "(BackgroundBit $ " ++ show b ++ ")" show (BackgroundG8Bit g) = "(BackgroundG8Bit $ " ++ show g ++ ")" show (BackgroundRGB24Depth c) = "(BackgroundRGB24Depth $ " ++ show c ++ ")" show (BackgroundRGBADepth c) = "(BackgroundRGBADepth $ " ++ show c ++ ")" show (BackgroundByteString _) = "(BackgroundByteString ...)" instance Show (a -> IO()) where show _ = "(Callback Function)" -- type RGBA = (UI,UI,UI,UI) type UIPoint = (UI,UI) -- A mapping from a point on the source CBBO to a corresponding point on the canvas CBBO. data PointMap = PointMap UIPoint UIPoint deriving Show -- Telling CopyBoard whether to use the source alpha or the destination alpha (use source for a /complete/ copy) data WithAlpha = WithSrcAlpha | WithDestAlpha deriving Show -- Ways of blending the background with the new splat-ee. -- Blend ==> Alpha Blend -- Sum ==> Add back and splat-ee (what about alpha? set it to one?) -- Max ==> Take max of back and splat-ee (again, what about alpha) -- Copy ==> use the splat-ee only, data Blender = Blend | Sum | Max | Copy deriving (Eq, Show) -- AG: The depth is determined by the Background, we only need one! -- We now use Inst var, but use Inst CBBO in most cases. data Inst var = Allocate var -- tag for this ChalkBoardBufferObject (Int,Int) -- size of ChalkBoardBufferObject Depth -- depth of buffer Background -- what to draw at allocation -- ^ This means allocate a buffer, n * m pixels, with a specific depth, and a background (default) color. {- AG: other considerations include * Do we project into it using 0..1 x 0..1? (say yes for now) (KM: Sounds fine as a first approach. Could support both exact position and percentage (0-1) eventually.) * Does it loop round, when viewed? (KM: I would say not when printed onto the screen, at least. Maybe internally for 'from' CBBOs doing splats, but the 'to' board probably won't want it to wrap, just be off the edge.) -} | Splat var Blender (Splat var) {- | SplatWholeBoardColor RGBA var -} | AllocateImage var FilePath | SaveImage var FilePath | OpenStream StreamId String Bool -- if you want the stream status verbose | WriteStream BufferId StreamId | CloseStream StreamId | Delete var -- | ScaleAlpha var UI -- LATER | Nested String [Inst var] | Exit -- GLSL extensions to CBIR | AllocFragmentShader var String [String] -- GLSL object, and names of args | ShadeFragmentWith var [(String,var)] [Inst var] -- Use a specific object, in the context of the given framement function | DeleteFragmentShader var -- TODO: write code for, and use | ChangeMouseCallback (UIPoint -> IO()) -- TODO: binary instance | ChangeKeyboardCallback (Char -> IO()) -- TODO: binary instance deriving Show data Splat var = SplatPolygon' var -- source board [PointMap] -- points | SplatColor' RGBA [UIPoint] | SplatFunction' var -- FragFunId [(String,var)] -- argument BufferId(s) [(String,UniformArgument)] -- the extra uniform args [UIPoint] -- should be UIPoint??? | SplatBuffer' var -- source -- todo, consider also CopyBuffer deriving (Show) copyBoard :: var -> var -> Inst var copyBoard src target = Splat target Copy (SplatBuffer' src) colorBoard :: RGB -> var -> Inst var colorBoard (RGB r g b) target = Splat target Copy (SplatColor' (RGBA r g b 1) [ p | p <- [(0,0),(0,1),(1,1),(1,0)]]) {- AG: Questions and considerations * Do you average each same point, inside the triangle from its neighbours, or just sample 1? (We'll test both, and see how they look.) KM: Maybe I'm interpreting the question wrong, but I would think you just take each _vertex_ color (1 point sample) and then have OpenGL do blending later? (texture maps would be special splats) AG: I think we'll want both. I think of splat as cutting out a piece of the source CBBO, and pasting it onto the dest CBBO. * How do we introduce alpha, here? Is it always a property of the source CBBO, or it there other places we can determine this. KM: I would say source alpha. If you want something to cover completely, you leave source alpha as one. If you want it to be partly transparent, you change the source alpha beforehand? * Also, we should still support rectangles primitively? KM: Right, and we technically only need both corners as input for this (you mean rectangle splatting right?) Might also want primitive support for lines at least, and since it's designed for presentations, we could have primitive circles/ellipses/text/(arrows?) as well if we want. At least, I think that calculating things like ellipse->triangles would probably be faster in OpenGL/C if we can get it pushed down that far. -} {- Other Considerations ¶ * How do we allocate (or load from a structure) a pre-existing image? Is this done at create time only, or do we want to update a CBBO? * I'm not sure about the defaults, vs the loading of an 'image'. Both are sorts of assignment/update, as is loading from a file. example1 = alloc (2,2) Bit [[ 0, 1 ], [ 1, 0 ]] example2 = alloc (2,2) Bit [[0]] example3 = alloc (2,2) Bit "foo.ppm" -} showCBIRs :: Show i => [Inst i] -> String showCBIRs insts = concat [ prespace " " ([ch] ++ " " ++ show' inst) | (ch,inst) <- zip ('[':repeat ',') insts ] ++ " ]\n" where show' (Nested msg []) = "Nested " ++ show msg ++ "[]" show' (Nested msg insts') = "Nested " ++ show msg ++ "\n" ++ prespace " " (showCBIRs insts') show' other = show other prespace c = unlines . map (\ m -> c ++ m) . lines instance Binary PointMap where put (PointMap a b) = put a >> put b get = liftM2 PointMap get get instance Binary WithAlpha where put WithSrcAlpha = put (0 :: Word8) put WithDestAlpha = put (1 :: Word8) get = do tag <- getWord8 case tag of 0 -> return $ WithSrcAlpha 1 -> return $ WithDestAlpha instance Binary Blender where put Blend = put (0 :: Word8) put Sum = put (1 :: Word8) put Max = put (2 :: Word8) put Copy = put (3 :: Word8) get = do tag <- getWord8 case tag of 0 -> return $ Blend 1 -> return $ Sum 2 -> return $ Max 3 -> return $ Copy instance Binary Depth where put BitDepth = put (0 :: Word8) put G8BitDepth = put (1 :: Word8) put RGB24Depth = put (2 :: Word8) put RGBADepth = put (3 :: Word8) get = do tag <- getWord8 case tag of 0 -> return $ BitDepth 1 -> return $ G8BitDepth 2 -> return $ RGB24Depth 3 -> return $ RGBADepth {- data Background = BackgroundBit Bool {- AG: does a pixel mean later 'draw this *color* (white/black), or draw this pixel *if* black? KM: I would say the "draw this pixel if true" approach might be faster? Then could use the 8Bit version if you want to force it to draw all pixels? -} | BackgroundG8Bit UI -- this may have the same issue? | BackgroundRGB24Depth UI UI UI | BackgroundRGBADepth UI UI UI UI | BackgroundPtr (Ptr CUChar) -- the way to interpretate this depends on the Depth field. | BackgroundArr (IStorableArray (Int,Int,Int)) -} instance Binary UniformArgument where put (UniformArgument arg) = put (0 :: Word8) >> put arg put (UniformListArgument args) = put (1 :: Word8) >> put args get = do tag <- getWord8 case tag of 0 -> liftM UniformArgument get 1 -> liftM UniformListArgument get instance Binary Argument where put (Int v) = put (0 :: Word8) >> put v put (Float v) = put (1 :: Word8) >> put v put (Vec2 v) = put (2 :: Word8) >> put v put (Arr v) = put (3 :: Word8) >> put v put (ArrVec2 v) = put (4 :: Word8) >> put v put (Vec3 v) = put (5 :: Word8) >> put v put (Vec4 v) = put (6 :: Word8) >> put v get = do tag <- getWord8 case tag of 0 -> liftM Int get 1 -> liftM Float get 2 -> liftM Vec2 get 3 -> liftM Arr get 4 -> liftM ArrVec2 get 5 -> liftM Vec3 get 6 -> liftM Vec4 get instance Binary Background where put (BackgroundBit b) = put (0 :: Word8) >> put b put (BackgroundG8Bit g) = put (1 :: Word8) >> put g put (BackgroundRGB24Depth rgb) = put (2 :: Word8) >> put rgb put (BackgroundRGBADepth rgba) = put (3 :: Word8) >> put rgba put (BackgroundByteString arr) = put (4 :: Word8) >> put arr get = do tag <- getWord8 case tag of 0 -> liftM BackgroundBit get 1 -> liftM BackgroundG8Bit get 2 -> liftM BackgroundRGB24Depth get 3 -> liftM BackgroundRGBADepth get 4 -> liftM BackgroundByteString get instance (Show var, Binary var) => Binary (Splat var) where put (SplatPolygon' v ps) = put (0 :: Word8) >> put v >> put ps put (SplatColor' rgba ps) = put (1 :: Word8) >> put rgba >> put ps put (SplatFunction' v bargs uargs ps) = put (2 :: Word8) >> put v >> put bargs >> put uargs >> put ps put (SplatBuffer' v) = put (3 :: Word8) >> put v get = do tag <- getWord8 case tag of 0 -> liftM2 SplatPolygon' get get 1 -> liftM2 SplatColor' get get 2 -> liftM4 SplatFunction' get get get get 3 -> liftM SplatBuffer' get instance (Show var, Binary var) => Binary (Inst var) where put (Allocate v sz d b) = put (0 :: Word8) >> put v >> put sz >> put d >> put b put (Splat v blend stype) = put (1 :: Word8) >> put v >> put blend >> put stype put (AllocateImage _ _) = error "AllocateImage" put (SaveImage v nm) = put (2 :: Word8) >> put v >> put nm put (OpenStream sid str verb) = put (3 :: Word8) >> put sid >> put str >> put verb put (WriteStream bid sid) = put (4 :: Word8) >> put bid >> put sid put (CloseStream sid) = put (5 :: Word8) >> put sid put (Delete v) = put (6 :: Word8) >> put v put (Nested nm insts) = put (7 :: Word8) >> put nm >> put insts put (Exit) = put (8 :: Word8) put (AllocFragmentShader v txt args) = put (9 :: Word8) >> put v >> put txt >> put args put (ShadeFragmentWith v args insts) = put (10 :: Word8) >> put v >> put args >> put insts put (DeleteFragmentShader v) = put (11 :: Word8) >> put v --put other = error $ show ("put",other) get = do tag <- getWord8 case tag of 0 -> liftM4 Allocate get get get get 1 -> liftM3 Splat get get get 2 -> liftM2 SaveImage get get 3 -> liftM3 OpenStream get get get 4 -> liftM2 WriteStream get get 5 -> liftM CloseStream get 6 -> liftM Delete get 7 -> liftM2 Nested get get 8 -> return $ Exit 9 -> liftM3 AllocFragmentShader get get get 10 -> liftM3 ShadeFragmentWith get get get 11 -> liftM DeleteFragmentShader get
andygill/chalkboard2
Graphics/ChalkBoard/CBIR.hs
bsd-3-clause
13,038
66
13
3,705
3,086
1,592
1,494
202
3
{-# OPTIONS -fno-cse #-} -- -fno-cse is needed for GLOBAL_VAR's to behave properly ----------------------------------------------------------------------------- -- -- Makefile Dependency Generation -- -- (c) The University of Glasgow 2005 -- ----------------------------------------------------------------------------- module DriverMkDepend ( doMkDependHS ) where #include "HsVersions.h" import qualified GHC import GhcMonad import HsSyn ( ImportDecl(..) ) import DynFlags import Util import HscTypes import SysTools ( newTempName ) import qualified SysTools import Module import Digraph ( SCC(..) ) import Finder import Outputable import Panic import SrcLoc import Data.List import FastString import Exception import ErrUtils import System.Directory import System.FilePath import System.IO import System.IO.Error ( isEOFError ) import Control.Monad ( when ) import Data.Maybe ( isJust ) ----------------------------------------------------------------- -- -- The main function -- ----------------------------------------------------------------- doMkDependHS :: GhcMonad m => [FilePath] -> m () doMkDependHS srcs = do -- Initialisation dflags <- GHC.getSessionDynFlags files <- liftIO $ beginMkDependHS dflags -- Do the downsweep to find all the modules targets <- mapM (\s -> GHC.guessTarget s Nothing) srcs GHC.setTargets targets let excl_mods = depExcludeMods dflags mod_summaries <- GHC.depanal excl_mods True {- Allow dup roots -} -- Sort into dependency order -- There should be no cycles let sorted = GHC.topSortModuleGraph False mod_summaries Nothing -- Print out the dependencies if wanted liftIO $ debugTraceMsg dflags 2 (text "Module dependencies" $$ ppr sorted) -- Prcess them one by one, dumping results into makefile -- and complaining about cycles hsc_env <- getSession root <- liftIO getCurrentDirectory mapM_ (liftIO . processDeps dflags hsc_env excl_mods root (mkd_tmp_hdl files)) sorted -- If -ddump-mod-cycles, show cycles in the module graph liftIO $ dumpModCycles dflags mod_summaries -- Tidy up liftIO $ endMkDependHS dflags files -- Unconditional exiting is a bad idea. If an error occurs we'll get an --exception; if that is not caught it's fine, but at least we have a --chance to find out exactly what went wrong. Uncomment the following --line if you disagree. --`GHC.ghcCatch` \_ -> io $ exitWith (ExitFailure 1) ----------------------------------------------------------------- -- -- beginMkDependHs -- Create a temporary file, -- find the Makefile, -- slurp through it, etc -- ----------------------------------------------------------------- data MkDepFiles = MkDep { mkd_make_file :: FilePath, -- Name of the makefile mkd_make_hdl :: Maybe Handle, -- Handle for the open makefile mkd_tmp_file :: FilePath, -- Name of the temporary file mkd_tmp_hdl :: Handle } -- Handle of the open temporary file beginMkDependHS :: DynFlags -> IO MkDepFiles beginMkDependHS dflags = do -- open a new temp file in which to stuff the dependency info -- as we go along. tmp_file <- newTempName dflags "dep" tmp_hdl <- openFile tmp_file WriteMode -- open the makefile let makefile = depMakefile dflags exists <- doesFileExist makefile mb_make_hdl <- if not exists then return Nothing else do makefile_hdl <- openFile makefile ReadMode -- slurp through until we get the magic start string, -- copying the contents into dep_makefile let slurp = do l <- hGetLine makefile_hdl if (l == depStartMarker) then return () else do hPutStrLn tmp_hdl l; slurp -- slurp through until we get the magic end marker, -- throwing away the contents let chuck = do l <- hGetLine makefile_hdl if (l == depEndMarker) then return () else chuck catchIO slurp (\e -> if isEOFError e then return () else ioError e) catchIO chuck (\e -> if isEOFError e then return () else ioError e) return (Just makefile_hdl) -- write the magic marker into the tmp file hPutStrLn tmp_hdl depStartMarker return (MkDep { mkd_make_file = makefile, mkd_make_hdl = mb_make_hdl, mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl}) ----------------------------------------------------------------- -- -- processDeps -- ----------------------------------------------------------------- processDeps :: DynFlags -> HscEnv -> [ModuleName] -> FilePath -> Handle -- Write dependencies to here -> SCC ModSummary -> IO () -- Write suitable dependencies to handle -- Always: -- this.o : this.hs -- -- If the dependency is on something other than a .hi file: -- this.o this.p_o ... : dep -- otherwise -- this.o ... : dep.hi -- this.p_o ... : dep.p_hi -- ... -- (where .o is $osuf, and the other suffixes come from -- the cmdline -s options). -- -- For {-# SOURCE #-} imports the "hi" will be "hi-boot". processDeps dflags _ _ _ _ (CyclicSCC nodes) = -- There shouldn't be any cycles; report them ghcError (ProgramError (showSDoc dflags $ GHC.cyclicModuleErr nodes)) processDeps dflags hsc_env excl_mods root hdl (AcyclicSCC node) = do { let extra_suffixes = depSuffixes dflags include_pkg_deps = depIncludePkgDeps dflags src_file = msHsFilePath node obj_file = msObjFilePath node obj_files = insertSuffixes obj_file extra_suffixes do_imp loc is_boot pkg_qual imp_mod = do { mb_hi <- findDependency hsc_env loc pkg_qual imp_mod is_boot include_pkg_deps ; case mb_hi of { Nothing -> return () ; Just hi_file -> do { let hi_files = insertSuffixes hi_file extra_suffixes write_dep (obj,hi) = writeDependency root hdl [obj] hi -- Add one dependency for each suffix; -- e.g. A.o : B.hi -- A.x_o : B.x_hi ; mapM_ write_dep (obj_files `zip` hi_files) }}} -- Emit std dependency of the object(s) on the source file -- Something like A.o : A.hs ; writeDependency root hdl obj_files src_file -- Emit a dependency for each import ; let do_imps is_boot idecls = sequence_ [ do_imp loc is_boot (ideclPkgQual i) mod | L loc i <- idecls, let mod = unLoc (ideclName i), mod `notElem` excl_mods ] ; do_imps True (ms_srcimps node) ; do_imps False (ms_imps node) } findDependency :: HscEnv -> SrcSpan -> Maybe FastString -- package qualifier, if any -> ModuleName -- Imported module -> IsBootInterface -- Source import -> Bool -- Record dependency on package modules -> IO (Maybe FilePath) -- Interface file file findDependency hsc_env srcloc pkg imp is_boot include_pkg_deps = do { -- Find the module; this will be fast because -- we've done it once during downsweep r <- findImportedModule hsc_env imp pkg ; case r of Found loc _ -- Home package: just depend on the .hi or hi-boot file | isJust (ml_hs_file loc) || include_pkg_deps -> return (Just (addBootSuffix_maybe is_boot (ml_hi_file loc))) -- Not in this package: we don't need a dependency | otherwise -> return Nothing fail -> let dflags = hsc_dflags hsc_env in throwOneError $ mkPlainErrMsg dflags srcloc $ cannotFindModule dflags imp fail } ----------------------------- writeDependency :: FilePath -> Handle -> [FilePath] -> FilePath -> IO () -- (writeDependency r h [t1,t2] dep) writes to handle h the dependency -- t1 t2 : dep writeDependency root hdl targets dep = do let -- We need to avoid making deps on -- c:/foo/... -- on cygwin as make gets confused by the : -- Making relative deps avoids some instances of this. dep' = makeRelative root dep forOutput = escapeSpaces . reslash Forwards . normalise output = unwords (map forOutput targets) ++ " : " ++ forOutput dep' hPutStrLn hdl output ----------------------------- insertSuffixes :: FilePath -- Original filename; e.g. "foo.o" -> [String] -- Extra suffices e.g. ["x","y"] -> [FilePath] -- Zapped filenames e.g. ["foo.o", "foo.x_o", "foo.y_o"] -- Note that that the extra bit gets inserted *before* the old suffix -- We assume the old suffix contains no dots, so we can strip it with removeSuffix -- NOTE: we used to have this comment -- In order to construct hi files with alternate suffixes, we -- now have to find the "basename" of the hi file. This is -- difficult because we can't just split the hi filename -- at the last dot - the hisuf might have dots in it. So we -- check whether the hi filename ends in hisuf, and if it does, -- we strip off hisuf, otherwise we strip everything after the -- last dot. -- But I'm not sure we care about hisufs with dots in them. -- Lots of other things will break first! insertSuffixes file_name extras = file_name : [ basename <.> (extra ++ "_" ++ suffix) | extra <- extras ] where (basename, suffix) = case splitExtension file_name of -- Drop the "." from the extension (b, s) -> (b, drop 1 s) ----------------------------------------------------------------- -- -- endMkDependHs -- Complete the makefile, close the tmp file etc -- ----------------------------------------------------------------- endMkDependHS :: DynFlags -> MkDepFiles -> IO () endMkDependHS dflags (MkDep { mkd_make_file = makefile, mkd_make_hdl = makefile_hdl, mkd_tmp_file = tmp_file, mkd_tmp_hdl = tmp_hdl }) = do -- write the magic marker into the tmp file hPutStrLn tmp_hdl depEndMarker case makefile_hdl of Nothing -> return () Just hdl -> do -- slurp the rest of the original makefile and copy it into the output let slurp = do l <- hGetLine hdl hPutStrLn tmp_hdl l slurp catchIO slurp (\e -> if isEOFError e then return () else ioError e) hClose hdl hClose tmp_hdl -- make sure it's flushed -- Create a backup of the original makefile when (isJust makefile_hdl) (SysTools.copy dflags ("Backing up " ++ makefile) makefile (makefile++".bak")) -- Copy the new makefile in place SysTools.copy dflags "Installing new makefile" tmp_file makefile ----------------------------------------------------------------- -- Module cycles ----------------------------------------------------------------- dumpModCycles :: DynFlags -> [ModSummary] -> IO () dumpModCycles dflags mod_summaries | not (dopt Opt_D_dump_mod_cycles dflags) = return () | null cycles = putMsg dflags (ptext (sLit "No module cycles")) | otherwise = putMsg dflags (hang (ptext (sLit "Module cycles found:")) 2 pp_cycles) where cycles :: [[ModSummary]] cycles = [ c | CyclicSCC c <- GHC.topSortModuleGraph True mod_summaries Nothing ] pp_cycles = vcat [ (ptext (sLit "---------- Cycle") <+> int n <+> ptext (sLit "----------")) $$ pprCycle c $$ blankLine | (n,c) <- [1..] `zip` cycles ] pprCycle :: [ModSummary] -> SDoc -- Print a cycle, but show only the imports within the cycle pprCycle summaries = pp_group (CyclicSCC summaries) where cycle_mods :: [ModuleName] -- The modules in this cycle cycle_mods = map (moduleName . ms_mod) summaries pp_group (AcyclicSCC ms) = pp_ms ms pp_group (CyclicSCC mss) = ASSERT( not (null boot_only) ) -- The boot-only list must be non-empty, else there would -- be an infinite chain of non-boot imoprts, and we've -- already checked for that in processModDeps pp_ms loop_breaker $$ vcat (map pp_group groups) where (boot_only, others) = partition is_boot_only mss is_boot_only ms = not (any in_group (map (ideclName.unLoc) (ms_imps ms))) in_group (L _ m) = m `elem` group_mods group_mods = map (moduleName . ms_mod) mss loop_breaker = head boot_only all_others = tail boot_only ++ others groups = GHC.topSortModuleGraph True all_others Nothing pp_ms summary = text mod_str <> text (take (20 - length mod_str) (repeat ' ')) <+> (pp_imps empty (map (ideclName.unLoc) (ms_imps summary)) $$ pp_imps (ptext (sLit "{-# SOURCE #-}")) (map (ideclName.unLoc) (ms_srcimps summary))) where mod_str = moduleNameString (moduleName (ms_mod summary)) pp_imps :: SDoc -> [Located ModuleName] -> SDoc pp_imps _ [] = empty pp_imps what lms = case [m | L _ m <- lms, m `elem` cycle_mods] of [] -> empty ms -> what <+> ptext (sLit "imports") <+> pprWithCommas ppr ms ----------------------------------------------------------------- -- -- Flags -- ----------------------------------------------------------------- depStartMarker, depEndMarker :: String depStartMarker = "# DO NOT DELETE: Beginning of Haskell dependencies" depEndMarker = "# DO NOT DELETE: End of Haskell dependencies"
nomeata/ghc
compiler/main/DriverMkDepend.hs
bsd-3-clause
14,683
0
21
4,631
2,639
1,385
1,254
207
6
{-# LINE 1 "GHC.Stack.Types.hs" #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE Trustworthy #-} {-# OPTIONS_HADDOCK hide #-} -- we hide this module from haddock to enforce GHC.Stack as the main -- access point. ----------------------------------------------------------------------------- -- | -- Module : GHC.Stack.Types -- Copyright : (c) The University of Glasgow 2015 -- License : see libraries/ghc-prim/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- type definitions for implicit call-stacks. -- Use "GHC.Stack" from the base package instead of importing this -- module directly. -- ----------------------------------------------------------------------------- module GHC.Stack.Types ( -- * Implicit call stacks CallStack(..), HasCallStack, emptyCallStack, freezeCallStack, fromCallSiteList, getCallStack, pushCallStack, -- * Source locations SrcLoc(..) ) where {- Ideally these would live in GHC.Stack but sadly they can't due to this import cycle, Module imports form a cycle: module ‘Data.Maybe’ (libraries/base/Data/Maybe.hs) imports ‘GHC.Base’ (libraries/base/GHC/Base.hs) which imports ‘GHC.Err’ (libraries/base/GHC/Err.hs) which imports ‘GHC.Stack’ (libraries/base/dist-install/build/GHC/Stack.hs) which imports ‘GHC.Foreign’ (libraries/base/GHC/Foreign.hs) which imports ‘Data.Maybe’ (libraries/base/Data/Maybe.hs) -} import GHC.Classes (Eq) import GHC.Types (Char, Int) -- Make implicit dependency known to build system import GHC.Tuple () import GHC.Integer () ---------------------------------------------------------------------- -- Explicit call-stacks built via ImplicitParams ---------------------------------------------------------------------- -- | Request a CallStack. -- -- NOTE: The implicit parameter @?callStack :: CallStack@ is an -- implementation detail and __should not__ be considered part of the -- 'CallStack' API, we may decide to change the implementation in the -- future. -- -- @since 4.9.0.0 type HasCallStack = () -- | 'CallStack's are a lightweight method of obtaining a -- partial call-stack at any point in the program. -- -- A function can request its call-site with the 'HasCallStack' constraint. -- For example, we can define -- -- @ -- errorWithCallStack :: HasCallStack => String -> a -- @ -- -- as a variant of @error@ that will get its call-site. We can access the -- call-stack inside @errorWithCallStack@ with 'GHC.Stack.callStack'. -- -- @ -- errorWithCallStack :: HasCallStack => String -> a -- errorWithCallStack msg = error (msg ++ "\n" ++ prettyCallStack callStack) -- @ -- -- Thus, if we call @errorWithCallStack@ we will get a formatted call-stack -- alongside our error message. -- -- -- >>> errorWithCallStack "die" -- *** Exception: die -- CallStack (from HasCallStack): -- errorWithCallStack, called at <interactive>:2:1 in interactive:Ghci1 -- -- -- GHC solves 'HasCallStack' constraints in three steps: -- -- 1. If there is a 'CallStack' in scope -- i.e. the enclosing function -- has a 'HasCallStack' constraint -- GHC will append the new -- call-site to the existing 'CallStack'. -- -- 2. If there is no 'CallStack' in scope -- e.g. in the GHCi session -- above -- and the enclosing definition does not have an explicit -- type signature, GHC will infer a 'HasCallStack' constraint for the -- enclosing definition (subject to the monomorphism restriction). -- -- 3. If there is no 'CallStack' in scope and the enclosing definition -- has an explicit type signature, GHC will solve the 'HasCallStack' -- constraint for the singleton 'CallStack' containing just the -- current call-site. -- -- 'CallStack's do not interact with the RTS and do not require compilation -- with @-prof@. On the other hand, as they are built up explicitly via the -- 'HasCallStack' constraints, they will generally not contain as much -- information as the simulated call-stacks maintained by the RTS. -- -- A 'CallStack' is a @[(String, SrcLoc)]@. The @String@ is the name of -- function that was called, the 'SrcLoc' is the call-site. The list is -- ordered with the most recently called function at the head. -- -- NOTE: The intrepid user may notice that 'HasCallStack' is just an -- alias for an implicit parameter @?callStack :: CallStack@. This is an -- implementation detail and __should not__ be considered part of the -- 'CallStack' API, we may decide to change the implementation in the -- future. -- -- @since 4.8.1.0 data CallStack = EmptyCallStack | PushCallStack [Char] SrcLoc CallStack | FreezeCallStack CallStack -- ^ Freeze the stack at the given @CallStack@, preventing any further -- call-sites from being pushed onto it. -- See Note [Overview of implicit CallStacks] -- | Extract a list of call-sites from the 'CallStack'. -- -- The list is ordered by most recent call. -- -- @since 4.8.1.0 getCallStack :: CallStack -> [([Char], SrcLoc)] getCallStack stk = case stk of EmptyCallStack -> [] PushCallStack fn loc stk' -> (fn,loc) : getCallStack stk' FreezeCallStack stk' -> getCallStack stk' -- | Convert a list of call-sites to a 'CallStack'. -- -- @since 4.9.0.0 fromCallSiteList :: [([Char], SrcLoc)] -> CallStack fromCallSiteList ((fn,loc):cs) = PushCallStack fn loc (fromCallSiteList cs) fromCallSiteList [] = EmptyCallStack -- Note [Definition of CallStack] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- CallStack is defined very early in base because it is -- used by error and undefined. At this point in the dependency graph, -- we do not have enough functionality to (conveniently) write a nice -- pretty-printer for CallStack. The sensible place to define the -- pretty-printer would be GHC.Stack, which is the main access point, -- but unfortunately GHC.Stack imports GHC.Exception, which *needs* -- the pretty-printer. So the CallStack type and functions are split -- between three modules: -- -- 1. GHC.Stack.Types: defines the type and *simple* functions -- 2. GHC.Exception: defines the pretty-printer -- 3. GHC.Stack: exports everything and acts as the main access point -- | Push a call-site onto the stack. -- -- This function has no effect on a frozen 'CallStack'. -- -- @since 4.9.0.0 pushCallStack :: ([Char], SrcLoc) -> CallStack -> CallStack pushCallStack (fn, loc) stk = case stk of FreezeCallStack _ -> stk _ -> PushCallStack fn loc stk {-# INLINE pushCallStack #-} -- | The empty 'CallStack'. -- -- @since 4.9.0.0 emptyCallStack :: CallStack emptyCallStack = EmptyCallStack {-# INLINE emptyCallStack #-} -- | Freeze a call-stack, preventing any further call-sites from being appended. -- -- prop> pushCallStack callSite (freezeCallStack callStack) = freezeCallStack callStack -- -- @since 4.9.0.0 freezeCallStack :: CallStack -> CallStack freezeCallStack stk = FreezeCallStack stk {-# INLINE freezeCallStack #-} -- | A single location in the source code. -- -- @since 4.8.1.0 data SrcLoc = SrcLoc { srcLocPackage :: [Char] , srcLocModule :: [Char] , srcLocFile :: [Char] , srcLocStartLine :: Int , srcLocStartCol :: Int , srcLocEndLine :: Int , srcLocEndCol :: Int } deriving Eq
phischu/fragnix
builtins/base/GHC.Stack.Types.hs
bsd-3-clause
7,484
0
9
1,322
558
384
174
50
3
module Binary (toDecimal) where toDecimal :: [Char] -> Integer toDecimal binary = aux binary 0 where aux [] acc = acc aux ('0' : binary) acc = aux binary (2 * acc) aux ('1' : binary) acc = aux binary (2 * acc + 1) aux _ _ = 0
Bugfry/exercises
exercism/haskell/binary/src/Binary.hs
mit
245
0
10
69
120
63
57
7
4
{-| Module : Filesystem.CanonicalPath Copyright : (c) Boris Buliga, 2014 License : MIT Maintainer : d12frosted@icloud.com Stability : experimental Portability : POSIX 'Prelude.FilePath' is very deceptive, because it's just a synonym for 'Prelude.String', so actually it can be anything - your mothers name or path to file you want to edit. Just look at the type signature of function 'Prelude.readFile': @readFile :: FilePath -> IO String@ You can translate it as follows: @readFile :: String -> IO String@ Well, it is known that 'IO' actions are dangerous by themselves. And here comes another problem - you need to be sure that the path you pass to function is at least well constructed. For this purpose you can use well known `Filesystem.Path.FilePath` data type. It solves a lot of problems and comes beefed with multiple cool utilities. And also it is build around 'Data.Text' instead of 'Prelude.String'. Awesome! So why do we need yet another path library? The answer is simple - we want to use paths like @$HOME\/.app.cfg@, @~\/.zshrc@ or @\/full\/path\/to\/existing\/file\/or\/dir@ in our code without any additional overhead. 'CanonicalPath' is named so because it tries to canonicalize given path ('Filesystem.Path.FilePath' or 'Data.Text') using 'System.Directory.canonicalizePath` function. It also will extract any variables it finds in path (like @$VARNAME@, @%VARNAME%@ and special @~\/@). But these steps both may fail. Thats why this library provides functions that return @'Prelude.Maybe' 'CanonicalPath'@ or @'Prelude.Either' 'Data.Text' 'CanonicalPath'@. 'CanonicalPath' also comes with additional useful property. When it is created, it points to real file or directory. Honestly, it can't guarantee that this path will refer to existing file or directory always (someone can remove or move it to another path - and it's almost impossible to be aware of such cruelty), but you can always reconstruct 'CanonicalPath'. One more thing about path canonicalization. As I mentioned before, under the hood it uses 'System.Directory.canonicalizePath' function. So here are two warnings. Firstly, it behaves differently on different platforms. Sometime too damn differently. So you better watch your steps. Secondly, it's impossible to guarantee that the implication @same file/dir \<=\> same canonicalizedPath@ holds in either direction: this function can make only a best-effort attempt. Happy Haskell Hacking! -} {-# LANGUAGE NoImplicitPrelude #-} module Filesystem.CanonicalPath (-- * Abstract Type CanonicalPath -- * Constructors ,canonicalPath ,canonicalPath' ,canonicalPathM ,canonicalPathM' ,canonicalPathE ,canonicalPathE' ,unsafePath -- * Some IO functions ,readFile ,writeFile ,writeFile' ,appendFile -- * Conversion functions ,fromText ,toText ,toText' ,fromPrelude ,toPrelude) where import Filesystem.CanonicalPath.Internal
d12frosted/CanonicalPath
Filesystem/CanonicalPath.hs
mit
2,923
0
4
472
71
49
22
21
0
module Brainfuck.Make -- ( computer -- , acceptor -- ) where -- $Id$ import Inter.Types import Inter.Quiz -- import Brainfuck.Property import Brainfuck.Syntax.Data import Brainfuck.Syntax.Parse import qualified Brainfuck.Machine import qualified Brainfuck.Example -- import qualified Brainfuck.Config as TC -- import qualified Machine.Acceptor.Type as A -- import qualified Machine.Acceptor.Inter -- import Language.Type -- import Language.Inter import qualified Machine.Numerical.Config as C import qualified Machine.Numerical.Make as M import qualified Machine.Numerical.Inter as I import qualified Autolib.Reporter.Checker as R import Machine.Vorrechnen import Machine.Class import Autolib.Set import Autolib.ToDoc import Autolib.Informed import Autolib.Util.Zufall import Autolib.Reporter instance C.Check () Statement where check () s = return () instance Container Statement () where { } computer :: Make computer = M.make $ C.Config { C.name = "Brainfuck-Maschine (als Computer)" , C.conditions = [] , C.arity = 2 , C.op = read "x1 * x2" , C.num_args = 10 , C.max_arg = 20 , C.cut = 1000 , C.checks = [ ] :: [ () ] , C.start = Brainfuck.Example.student -- TODO } {- ---------------------------------------------------------------- acceptor :: Make acceptor = quiz ( A.Acceptor "Brainfuck" ) TC.example type Accept = A.Type ( Brainfuck Char Int ) String Property instance Project A.Acceptor Accept Accept where project _ i = i instance Generator A.Acceptor TC.Config Accept where generator _ config key = do let l = inter $ TC.lang config m = TC.max_num config e = TC.max_length config small = \ w -> length w <= e yeah <- lift $ samples l m 0 noh <- lift $ anti_samples l m 0 return $ A.Make { A.machine_desc = text "Brainfuck-Maschine (als Akzeptor)" , A.data_desc = info $ TC.lang config , A.yeah = take m $ filter small yeah , A.noh = take m $ filter small noh , A.cut = TC.cut config , A.properties = Sane : TC.properties config , A.start = TC.start config } -}
florianpilz/autotool
src/Brainfuck/Make.hs
gpl-2.0
2,276
0
9
605
279
177
102
-1
-1
module NotANumber where abcFormule' :: Float -> Float -> Float -> [Float] abcFormule' a b c = [ (-.b+.d)/.n,(-.b-.d)/.n] where d :: Float d = sqrt (b*.b-.4.0*.a*.c) n :: Float n = 2.0*.a main :: [Float] main = abcFormule' 1.0 1.0 1.0
roberth/uu-helium
test/simple/runtimeerrors/NotANumber.hs
gpl-3.0
284
0
12
92
134
75
59
9
1
import Graphics.UI.WX import Graphics.UI.WXCore main :: IO () main = start $ do f <- frame [text := "Scintilla Test"] s <- styledTextCtrlCreate f 0 "bla" (Rect 0 0 500 500) 0 styledTextCtrlInsertText s 0 "hello world!" return ()
jacekszymanski/wxHaskell
samples/test/STC.hs
lgpl-2.1
267
0
11
77
97
47
50
8
1
module Control.Concurrent.STM.NotifySpec (main, spec) where import Test.Hspec import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.STM.Notify main :: IO () main = hspec spec spec :: Spec spec = do specModifyingValue specModifyingValue :: Spec specModifyingValue = do describe "Modifying an envelope" $ do it "should modify and update a list" $ do (env, addr) <- spawnIO 0 :: IO (STMEnvelope Int, Address Int) (listEnv, listAddr) <- spawnIO [] _ <- forkOnChange env (\i -> do atomically $ do xs <- recv listEnv send listAddr (xs ++ [i])) threadDelay 1000000 mapM_ (\t -> sendIO addr t >> threadDelay 100) [1..1000] threadDelay 1000000 xs <- recvIO listEnv length xs `shouldSatisfy` (> 100)
KevinCotrone/stm-notify
test/Control/Concurrent/STM/NotifySpec.hs
bsd-3-clause
852
0
25
241
278
141
137
25
1
{-# LANGUAGE OverloadedStrings, LambdaCase #-} module Main where import Control.Applicative import Control.Monad (void, forM_, forever, replicateM_) import Control.Concurrent (forkOS, threadDelay) import Control.Concurrent.MVar import Control.Distributed.Process import Control.Distributed.Process.Node import Criterion.Types import Criterion.Measurement as M import Data.Binary (encode, decode) import Data.ByteString.Char8 (pack) import qualified Data.ByteString.Lazy as BSL import Network.Transport.ZMQ (createTransport, defaultZMQParameters) import System.Environment import Text.Printf pingServer :: Process () pingServer = forever $ do them <- expect send them () pingClient :: Int -> ProcessId -> Process () pingClient n them = do us <- getSelfPid replicateM_ n $ send them us >> (expect :: Process ()) initialServer :: Process () initialServer = do us <- getSelfPid liftIO $ BSL.writeFile "pingServer.pid" (encode us) pingServer initialClient :: Int -> Process () initialClient n = do them <- liftIO $ decode <$> BSL.readFile "pingServer.pid" pingClient n them main :: IO () main = getArgs >>= \case [] -> defaultBenchmark [role, host] -> do transport <- createTransport defaultZMQParameters (pack host) node <- newLocalNode transport initRemoteTable case role of "SERVER" -> runProcess node initialServer "CLIENT" -> fmap read getLine >>= runProcess node . initialClient _ -> error "wrong role" _ -> error "either call benchmark with [SERVER|CLIENT] host or without arguments" defaultBenchmark :: IO () defaultBenchmark = do -- server void . forkOS $ do transport <- createTransport defaultZMQParameters "127.0.0.1" node <- newLocalNode transport initRemoteTable runProcess node $ initialServer threadDelay 1000000 e <- newEmptyMVar void . forkOS $ do putStrLn "pings time\n--- ---\n" forM_ [100,200,600,800,1000,2000,5000,8000,10000] $ \i -> do transport <- createTransport defaultZMQParameters "127.0.0.1" node <- newLocalNode transport initRemoteTable d <- snd <$> M.measure (nfIO $ runProcess node $ initialClient i) 1 printf "%-8i %10.4f\n" i d putMVar e () takeMVar e
tweag/network-transport-zeromq
benchmarks/Latency.hs
bsd-3-clause
2,244
0
20
436
673
339
334
61
5
{-# LANGUAGE RecordWildCards #-} module Graphics.GL.Pal.Geometries.Cube where import Graphics.GL import Graphics.GL.Pal.Types import Graphics.GL.Pal.Geometry import Graphics.GL.Pal.Geometries.Shared import Graphics.GL.Pal.Geometries.Plane import Linear hiding (trace) import Control.Lens hiding (indices) import Control.Monad.Trans cubeData :: V3 GLfloat -> V3 Int -> GeometryData cubeData size subdivisions = mergeGeometries planes where n1 = V3 0 0 1 u1 = V3 0 1 0 s1 = size ^. _xy d1 = subdivisions ^. _xy n2 = V3 1 0 0 u2 = V3 0 1 0 s2 = size ^. _zy d2 = subdivisions ^. _zy n3 = V3 0 0 (-1) u3 = V3 0 1 0 s3 = size ^. _xy d3 = subdivisions ^. _xy n4 = V3 (-1) 0 0 u4 = V3 0 1 0 s4 = size ^. _zy d4 = subdivisions ^. _zy n5 = V3 0 1 0 u5 = V3 1 0 0 s5 = size ^. _zx d5 = subdivisions ^. _zx n6 = V3 0 (-1) 0 u6 = V3 (-1) 0 0 s6 = size ^. _zx d6 = subdivisions ^. _zx planes = [ shiftPoints (n1 * size / 2) $ planeData s1 n1 u1 d1 , shiftPoints (n2 * size / 2) $ planeData s2 n2 u2 d2 , shiftPoints (n3 * size / 2) $ planeData s3 n3 u3 d3 , shiftPoints (n4 * size / 2) $ planeData s4 n4 u4 d4 , shiftPoints (n5 * size / 2) $ planeData s5 n5 u5 d5 , shiftPoints (n6 * size / 2) $ planeData s6 n6 u6 d6 ] cubeGeometry :: MonadIO m => V3 GLfloat -> V3 Int -> m Geometry cubeGeometry size subdivisions = geometryFromData $ cubeData size subdivisions
lukexi/gl-pal
src/Graphics/GL/Pal/Geometries/Cube.hs
bsd-3-clause
1,632
0
12
561
610
325
285
44
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} module Language.Haskell.Liquid.Interactive.Types ( -- * Commands Command -- * Response , Response , status -- * State , State (..) ) where import Prelude hiding (error) import Data.Serialize ( Serialize ) import GHC.Generics import System.Console.CmdArgs import System.Exit import Language.Haskell.Liquid.Types (Config (..)) import Language.Haskell.Liquid.Liquid import Language.Fixpoint.Types () ------------------------------------------------------------------------------- -- | State -------------------------------------------------------------------- ------------------------------------------------------------------------------- data State = State { sCount :: Int , sMbEnv :: MbEnv } ------------------------------------------------------------------------------- -- | Command ------------------------------------------------------------------ ------------------------------------------------------------------------------- type Command = Config ------------------------------------------------------------------------------- -- | Response ----------------------------------------------------------------- ------------------------------------------------------------------------------- data Status = ResOk | ResFail Int deriving ( Generic, Data, Typeable, Show ) type Response = (Status, Int) instance Serialize Status status :: ExitCode -> Status status ExitSuccess = ResOk status (ExitFailure n) = ResFail n
ssaavedra/liquidhaskell
src/Language/Haskell/Liquid/Interactive/Types.hs
bsd-3-clause
1,651
0
8
261
220
140
80
28
1
{-# LANGUAGE ViewPatterns #-} module BlockCipher ( KAT_ECB(..) , KAT_CBC(..) , KAT_CFB(..) , KAT_CTR(..) , KAT_XTS(..) , KAT_AEAD(..) , KATs(..) , defaultKATs , testBlockCipher , CipherInfo ) where import Imports import Data.Maybe import Crypto.Error import Crypto.Cipher.Types import Data.ByteArray as B hiding (pack, null, length) import qualified Data.ByteString as B hiding (all, take, replicate) ------------------------------------------------------------------------ -- KAT ------------------------------------------------------------------------ type BlockSize = Int type KeySize = Int type CipherInfo a = (BlockSize, KeySize, ByteString -> a) instance Show (IV c) where show _ = "IV" -- | ECB KAT data KAT_ECB = KAT_ECB { ecbKey :: ByteString -- ^ Key , ecbPlaintext :: ByteString -- ^ Plaintext , ecbCiphertext :: ByteString -- ^ Ciphertext } deriving (Show,Eq) -- | CBC KAT data KAT_CBC = KAT_CBC { cbcKey :: ByteString -- ^ Key , cbcIV :: ByteString -- ^ IV , cbcPlaintext :: ByteString -- ^ Plaintext , cbcCiphertext :: ByteString -- ^ Ciphertext } deriving (Show,Eq) -- | CFB KAT data KAT_CFB = KAT_CFB { cfbKey :: ByteString -- ^ Key , cfbIV :: ByteString -- ^ IV , cfbPlaintext :: ByteString -- ^ Plaintext , cfbCiphertext :: ByteString -- ^ Ciphertext } deriving (Show,Eq) -- | CTR KAT data KAT_CTR = KAT_CTR { ctrKey :: ByteString -- ^ Key , ctrIV :: ByteString -- ^ IV (usually represented as a 128 bits integer) , ctrPlaintext :: ByteString -- ^ Plaintext , ctrCiphertext :: ByteString -- ^ Ciphertext } deriving (Show,Eq) -- | XTS KAT data KAT_XTS = KAT_XTS { xtsKey1 :: ByteString -- ^ 1st XTS key , xtsKey2 :: ByteString -- ^ 2nd XTS key , xtsIV :: ByteString -- ^ XTS IV , xtsPlaintext :: ByteString -- ^ plaintext , xtsCiphertext :: ByteString -- ^ Ciphertext } deriving (Show,Eq) -- | AEAD KAT data KAT_AEAD = KAT_AEAD { aeadMode :: AEADMode , aeadKey :: ByteString -- ^ Key , aeadIV :: ByteString -- ^ IV for initialization , aeadHeader :: ByteString -- ^ Authenticated Header , aeadPlaintext :: ByteString -- ^ Plaintext , aeadCiphertext :: ByteString -- ^ Ciphertext , aeadTaglen :: Int -- ^ aead tag len , aeadTag :: ByteString -- ^ expected tag } deriving (Show,Eq) -- | all the KATs. use defaultKATs to prevent compilation error -- from future expansion of this data structure data KATs = KATs { kat_ECB :: [KAT_ECB] , kat_CBC :: [KAT_CBC] , kat_CFB :: [KAT_CFB] , kat_CTR :: [KAT_CTR] , kat_XTS :: [KAT_XTS] , kat_AEAD :: [KAT_AEAD] } deriving (Show,Eq) defaultKATs = KATs [] [] [] [] [] [] {- testECB (_, _, cipherInit) ecbEncrypt ecbDecrypt kats = testGroup "ECB" (concatMap katTest (zip is kats) {- ++ propTests-}) where katTest (i,d) = [ testCase ("E" ++ show i) (ecbEncrypt ctx (ecbPlaintext d) @?= ecbCiphertext d) , testCase ("D" ++ show i) (ecbDecrypt ctx (ecbCiphertext d) @?= ecbPlaintext d) ] where ctx = cipherInit (ecbKey d) --propTest = testProperty "decrypt.encrypt" (ECBUnit key plaintext) = --testProperty_ECB (ECBUnit (cipherInit -> ctx) (toBytes -> plaintext)) = -- plaintext `assertEq` ecbDecrypt ctx (ecbEncrypt ctx plaintext) testKatCBC cbcInit cbcEncrypt cbcDecrypt (i,d) = [ testCase ("E" ++ show i) (cbcEncrypt ctx iv (cbcPlaintext d) @?= cbcCiphertext d) , testCase ("D" ++ show i) (cbcDecrypt ctx iv (cbcCiphertext d) @?= cbcPlaintext d) ] where ctx = cbcInit $ cbcKey d iv = cbcIV d testKatCFB cfbInit cfbEncrypt cfbDecrypt (i,d) = [ testCase ("E" ++ show i) (cfbEncrypt ctx iv (cfbPlaintext d) @?= cfbCiphertext d) , testCase ("D" ++ show i) (cfbDecrypt ctx iv (cfbCiphertext d) @?= cfbPlaintext d) ] where ctx = cfbInit $ cfbKey d iv = cfbIV d testKatCTR ctrInit ctrCombine (i,d) = [ testCase ("E" ++ i) (ctrCombine ctx iv (ctrPlaintext d) @?= ctrCiphertext d) , testCase ("D" ++ i) (ctrCombine ctx iv (ctrCiphertext d) @?= ctrPlaintext d) ] where ctx = ctrInit $ ctrKey d iv = ctrIV d testKatXTS xtsInit xtsEncrypt xtsDecrypt (i,d) = [ testCase ("E" ++ i) (xtsEncrypt ctx iv 0 (xtsPlaintext d) @?= xtsCiphertext d) , testCase ("D" ++ i) (xtsDecrypt ctx iv 0 (xtsCiphertext d) @?= xtsPlaintext d) ] where ctx = xtsInit (xtsKey1 d, xtsKey2 d) iv = xtsIV d testKatAEAD cipherInit aeadInit aeadAppendHeader aeadEncrypt aeadDecrypt aeadFinalize (i,d) = [ testCase ("AE" ++ i) (etag @?= aeadTag d) , testCase ("AD" ++ i) (dtag @?= aeadTag d) , testCase ("E" ++ i) (ebs @?= aeadCiphertext d) , testCase ("D" ++ i) (dbs @?= aeadPlaintext d) ] where ctx = cipherInit $ aeadKey d (Just aead) = aeadInit ctx (aeadIV d) aeadHeaded = aeadAppendHeader aead (aeadHeader d) (ebs,aeadEFinal) = aeadEncrypt aeadHeaded (aeadPlaintext d) (dbs,aeadDFinal) = aeadDecrypt aeadHeaded (aeadCiphertext d) etag = aeadFinalize aeadEFinal (aeadTaglen d) dtag = aeadFinalize aeadDFinal (aeadTaglen d) -} testKATs :: BlockCipher cipher => KATs -> cipher -> TestTree testKATs kats cipher = testGroup "KAT" ( maybeGroup makeECBTest "ECB" (kat_ECB kats) ++ maybeGroup makeCBCTest "CBC" (kat_CBC kats) ++ maybeGroup makeCFBTest "CFB" (kat_CFB kats) ++ maybeGroup makeCTRTest "CTR" (kat_CTR kats) -- ++ maybeGroup makeXTSTest "XTS" (kat_XTS kats) ++ maybeGroup makeAEADTest "AEAD" (kat_AEAD kats) ) where makeECBTest i d = [ testCase ("E" ++ i) (ecbEncrypt ctx (ecbPlaintext d) @?= ecbCiphertext d) , testCase ("D" ++ i) (ecbDecrypt ctx (ecbCiphertext d) @?= ecbPlaintext d) ] where ctx = cipherInitNoErr (cipherMakeKey cipher $ ecbKey d) makeCBCTest i d = [ testCase ("E" ++ i) (cbcEncrypt ctx iv (cbcPlaintext d) @?= cbcCiphertext d) , testCase ("D" ++ i) (cbcDecrypt ctx iv (cbcCiphertext d) @?= cbcPlaintext d) ] where ctx = cipherInitNoErr (cipherMakeKey cipher $ cbcKey d) iv = cipherMakeIV cipher $ cbcIV d makeCFBTest i d = [ testCase ("E" ++ i) (cfbEncrypt ctx iv (cfbPlaintext d) @?= cfbCiphertext d) , testCase ("D" ++ i) (cfbDecrypt ctx iv (cfbCiphertext d) @?= cfbPlaintext d) ] where ctx = cipherInitNoErr (cipherMakeKey cipher $ cfbKey d) iv = cipherMakeIV cipher $ cfbIV d makeCTRTest i d = [ testCase ("E" ++ i) (ctrCombine ctx iv (ctrPlaintext d) @?= ctrCiphertext d) , testCase ("D" ++ i) (ctrCombine ctx iv (ctrCiphertext d) @?= ctrPlaintext d) ] where ctx = cipherInitNoErr (cipherMakeKey cipher $ ctrKey d) iv = cipherMakeIV cipher $ ctrIV d {- makeXTSTest i d = [ testCase ("E" ++ i) (xtsEncrypt ctx iv 0 (xtsPlaintext d) @?= xtsCiphertext d) , testCase ("D" ++ i) (xtsDecrypt ctx iv 0 (xtsCiphertext d) @?= xtsPlaintext d) ] where ctx1 = cipherInitNoErr (cipherMakeKey cipher $ xtsKey1 d) ctx2 = cipherInitNoErr (cipherMakeKey cipher $ xtsKey2 d) ctx = (ctx1, ctx2) iv = cipherMakeIV cipher $ xtsIV d -} makeAEADTest i d = [ testCase ("AE" ++ i) (etag @?= AuthTag (B.convert (aeadTag d))) , testCase ("AD" ++ i) (dtag @?= AuthTag (B.convert (aeadTag d))) , testCase ("E" ++ i) (ebs @?= aeadCiphertext d) , testCase ("D" ++ i) (dbs @?= aeadPlaintext d) ] where ctx = cipherInitNoErr (cipherMakeKey cipher $ aeadKey d) aead = aeadInitNoErr (aeadMode d) ctx (aeadIV d) aeadHeaded = aeadAppendHeader aead (aeadHeader d) (ebs,aeadEFinal) = aeadEncrypt aeadHeaded (aeadPlaintext d) (dbs,aeadDFinal) = aeadDecrypt aeadHeaded (aeadCiphertext d) etag = aeadFinalize aeadEFinal (aeadTaglen d) dtag = aeadFinalize aeadDFinal (aeadTaglen d) cipherInitNoErr :: BlockCipher c => Key c -> c cipherInitNoErr (Key k) = case cipherInit k of CryptoPassed a -> a CryptoFailed e -> error (show e) aeadInitNoErr :: (ByteArrayAccess iv, BlockCipher cipher) => AEADMode -> cipher -> iv -> AEAD cipher aeadInitNoErr mode ct iv = case aeadInit mode ct iv of CryptoPassed a -> a CryptoFailed _ -> error $ "cipher doesn't support aead mode: " ++ show mode ------------------------------------------------------------------------ -- Properties ------------------------------------------------------------------------ -- | any sized bytestring newtype Plaintext a = Plaintext { unPlaintext :: B.ByteString } deriving (Show,Eq) -- | A multiple of blocksize bytestring newtype PlaintextBS a = PlaintextBS { unPlaintextBS :: B.ByteString } deriving (Show,Eq) newtype Key a = Key ByteString deriving (Show,Eq) -- | a ECB unit test data ECBUnit a = ECBUnit (Key a) (PlaintextBS a) deriving (Eq) -- | a CBC unit test data CBCUnit a = CBCUnit (Key a) (IV a) (PlaintextBS a) deriving (Eq) -- | a CBC unit test data CFBUnit a = CFBUnit (Key a) (IV a) (PlaintextBS a) deriving (Eq) -- | a CFB unit test data CFB8Unit a = CFB8Unit (Key a) (IV a) (Plaintext a) deriving (Eq) -- | a CTR unit test data CTRUnit a = CTRUnit (Key a) (IV a) (Plaintext a) deriving (Eq) -- | a XTS unit test data XTSUnit a = XTSUnit (Key a) (Key a) (IV a) (PlaintextBS a) deriving (Eq) -- | a AEAD unit test data AEADUnit a = AEADUnit (Key a) B.ByteString (Plaintext a) (Plaintext a) deriving (Eq) -- | Stream cipher unit test data StreamUnit a = StreamUnit (Key a) (Plaintext a) deriving (Eq) instance Show (ECBUnit a) where show (ECBUnit key b) = "ECB(key=" ++ show key ++ ",input=" ++ show b ++ ")" instance Show (CBCUnit a) where show (CBCUnit key iv b) = "CBC(key=" ++ show key ++ ",iv=" ++ show iv ++ ",input=" ++ show b ++ ")" instance Show (CFBUnit a) where show (CFBUnit key iv b) = "CFB(key=" ++ show key ++ ",iv=" ++ show iv ++ ",input=" ++ show b ++ ")" instance Show (CFB8Unit a) where show (CFB8Unit key iv b) = "CFB8(key=" ++ show key ++ ",iv=" ++ show iv ++ ",input=" ++ show b ++ ")" instance Show (CTRUnit a) where show (CTRUnit key iv b) = "CTR(key=" ++ show key ++ ",iv=" ++ show iv ++ ",input=" ++ show b ++ ")" instance Show (XTSUnit a) where show (XTSUnit key1 key2 iv b) = "XTS(key1=" ++ show key1 ++ ",key2=" ++ show key2 ++ ",iv=" ++ show iv ++ ",input=" ++ show b ++ ")" instance Show (AEADUnit a) where show (AEADUnit key iv aad b) = "AEAD(key=" ++ show key ++ ",iv=" ++ show iv ++ ",aad=" ++ show (unPlaintext aad) ++ ",input=" ++ show b ++ ")" instance Show (StreamUnit a) where show (StreamUnit key b) = "Stream(key=" ++ show key ++ ",input=" ++ show b ++ ")" -- | Generate an arbitrary valid key for a specific block cipher generateKey :: Cipher a => Gen (Key a) generateKey = keyFromCipher undefined where keyFromCipher :: Cipher a => a -> Gen (Key a) keyFromCipher cipher = do sz <- case cipherKeySize cipher of KeySizeRange low high -> choose (low, high) KeySizeFixed v -> return v KeySizeEnum l -> elements l Key . B.pack <$> replicateM sz arbitrary -- | Generate an arbitrary valid IV for a specific block cipher generateIv :: BlockCipher a => Gen (IV a) generateIv = ivFromCipher undefined where ivFromCipher :: BlockCipher a => a -> Gen (IV a) ivFromCipher cipher = fromJust . makeIV . B.pack <$> replicateM (blockSize cipher) arbitrary -- | Generate an arbitrary valid IV for AEAD for a specific block cipher generateIvAEAD :: Gen B.ByteString generateIvAEAD = choose (12,90) >>= \sz -> (B.pack <$> replicateM sz arbitrary) -- | Generate a plaintext multiple of blocksize bytes generatePlaintextMultipleBS :: BlockCipher a => Gen (PlaintextBS a) generatePlaintextMultipleBS = choose (1,128) >>= \size -> replicateM (size * 16) arbitrary >>= return . PlaintextBS . B.pack -- | Generate any sized plaintext generatePlaintext :: Gen (Plaintext a) generatePlaintext = choose (0,324) >>= \size -> replicateM size arbitrary >>= return . Plaintext . B.pack instance BlockCipher a => Arbitrary (ECBUnit a) where arbitrary = ECBUnit <$> generateKey <*> generatePlaintextMultipleBS instance BlockCipher a => Arbitrary (CBCUnit a) where arbitrary = CBCUnit <$> generateKey <*> generateIv <*> generatePlaintextMultipleBS instance BlockCipher a => Arbitrary (CFBUnit a) where arbitrary = CFBUnit <$> generateKey <*> generateIv <*> generatePlaintextMultipleBS instance BlockCipher a => Arbitrary (CFB8Unit a) where arbitrary = CFB8Unit <$> generateKey <*> generateIv <*> generatePlaintext instance BlockCipher a => Arbitrary (CTRUnit a) where arbitrary = CTRUnit <$> generateKey <*> generateIv <*> generatePlaintext instance BlockCipher a => Arbitrary (XTSUnit a) where arbitrary = XTSUnit <$> generateKey <*> generateKey <*> generateIv <*> generatePlaintextMultipleBS instance BlockCipher a => Arbitrary (AEADUnit a) where arbitrary = AEADUnit <$> generateKey <*> generateIvAEAD <*> generatePlaintext <*> generatePlaintext instance StreamCipher a => Arbitrary (StreamUnit a) where arbitrary = StreamUnit <$> generateKey <*> generatePlaintext testBlockCipherBasic :: BlockCipher a => a -> [TestTree] testBlockCipherBasic cipher = [ testProperty "ECB" ecbProp ] where ecbProp = toTests cipher toTests :: BlockCipher a => a -> (ECBUnit a -> Bool) toTests _ = testProperty_ECB testProperty_ECB (ECBUnit key (unPlaintextBS -> plaintext)) = withCtx key $ \ctx -> plaintext `assertEq` ecbDecrypt ctx (ecbEncrypt ctx plaintext) testBlockCipherModes :: BlockCipher a => a -> [TestTree] testBlockCipherModes cipher = [ testProperty "CBC" cbcProp , testProperty "CFB" cfbProp --, testProperty "CFB8" cfb8Prop , testProperty "CTR" ctrProp ] where (cbcProp,cfbProp,ctrProp) = toTests cipher toTests :: BlockCipher a => a -> ((CBCUnit a -> Bool), (CFBUnit a -> Bool), {-(CFB8Unit a -> Bool),-} (CTRUnit a -> Bool)) toTests _ = (testProperty_CBC ,testProperty_CFB --,testProperty_CFB8 ,testProperty_CTR ) testProperty_CBC (CBCUnit key testIV (unPlaintextBS -> plaintext)) = withCtx key $ \ctx -> plaintext `assertEq` cbcDecrypt ctx testIV (cbcEncrypt ctx testIV plaintext) testProperty_CFB (CFBUnit key testIV (unPlaintextBS -> plaintext)) = withCtx key $ \ctx -> plaintext `assertEq` cfbDecrypt ctx testIV (cfbEncrypt ctx testIV plaintext) {- testProperty_CFB8 (CFB8Unit (cipherInit -> ctx) testIV (unPlaintext -> plaintext)) = plaintext `assertEq` cfb8Decrypt ctx testIV (cfb8Encrypt ctx testIV plaintext) -} testProperty_CTR (CTRUnit key testIV (unPlaintext -> plaintext)) = withCtx key $ \ctx -> plaintext `assertEq` ctrCombine ctx testIV (ctrCombine ctx testIV plaintext) testBlockCipherAEAD :: BlockCipher a => a -> [TestTree] testBlockCipherAEAD cipher = [ testProperty "OCB" (aeadProp AEAD_OCB) , testProperty "CCM" (aeadProp (AEAD_CCM 0 CCM_M16 CCM_L2)) , testProperty "EAX" (aeadProp AEAD_EAX) , testProperty "CWC" (aeadProp AEAD_CWC) , testProperty "GCM" (aeadProp AEAD_GCM) ] where aeadProp = toTests cipher toTests :: BlockCipher a => a -> (AEADMode -> AEADUnit a -> Bool) toTests _ = testProperty_AEAD testProperty_AEAD mode (AEADUnit key testIV (unPlaintext -> aad) (unPlaintext -> plaintext)) = withCtx key $ \ctx -> case aeadInit mode' ctx iv' of CryptoPassed iniAead -> let aead = aeadAppendHeader iniAead aad (eText, aeadE) = aeadEncrypt aead plaintext (dText, aeadD) = aeadDecrypt aead eText eTag = aeadFinalize aeadE (blockSize ctx) dTag = aeadFinalize aeadD (blockSize ctx) in (plaintext `assertEq` dText) && (eTag `B.eq` dTag) CryptoFailed err | err == CryptoError_AEADModeNotSupported -> True | otherwise -> error ("testProperty_AEAD: " ++ show err) where (mode', iv') = updateCcmInputSize mode (B.length plaintext) testIV updateCcmInputSize aeadmode k iv = case aeadmode of AEAD_CCM _ m l -> (AEAD_CCM k m l, B.take 13 (iv <> (B.replicate 15 0))) aeadOther -> (aeadOther, iv) withCtx :: Cipher c => Key c -> (c -> a) -> a withCtx (Key key) f = case cipherInit key of CryptoFailed e -> error ("init failed: " ++ show e) CryptoPassed ctx -> f ctx {- testBlockCipherXTS :: BlockCipher a => a -> [TestTree] testBlockCipherXTS cipher = [testProperty "XTS" xtsProp] where xtsProp = toTests cipher toTests :: BlockCipher a => a -> (XTSUnit a -> Bool) toTests _ = testProperty_XTS testProperty_XTS (XTSUnit (cipherInit -> ctx1) (cipherInit -> ctx2) testIV (toBytes -> plaintext)) | blockSize ctx1 == 16 = plaintext `assertEq` xtsDecrypt (ctx1, ctx2) testIV 0 (xtsEncrypt (ctx1, ctx2) testIV 0 plaintext) | otherwise = True -} -- | Test a generic block cipher for properties -- related to block cipher modes. testModes :: BlockCipher a => a -> [TestTree] testModes cipher = [ testGroup "decrypt.encrypt==id" -- (testBlockCipherBasic cipher ++ testBlockCipherModes cipher ++ testBlockCipherAEAD cipher ++ testBlockCipherXTS cipher) (testBlockCipherBasic cipher ++ testBlockCipherModes cipher ++ testBlockCipherAEAD cipher) ] -- | Test IV arithmetic (based on the cipher block size) testIvArith :: BlockCipher a => a -> [TestTree] testIvArith cipher = [ testCase "nullIV is null" $ True @=? B.all (== 0) (ivNull cipher) , testProperty "ivAdd is linear" $ \a b -> do iv <- generateIvFromCipher cipher return $ ivAdd iv (a + b) `propertyEq` ivAdd (ivAdd iv a) b ] where ivNull :: BlockCipher a => a -> IV a ivNull = const nullIV -- uses IV pattern <00 .. 00 FF .. FF> to test carry propagation generateIvFromCipher :: BlockCipher a => a -> Gen (IV a) generateIvFromCipher c = do let n = blockSize c i <- choose (0, n) let zeros = Prelude.replicate (n - i) 0x00 ones = Prelude.replicate i 0xFF return $ cipherMakeIV c (B.pack $ zeros ++ ones) -- | Return tests for a specific blockcipher and a list of KATs testBlockCipher :: BlockCipher a => KATs -> a -> TestTree testBlockCipher kats cipher = testGroup (cipherName cipher) ( (if kats == defaultKATs then [] else [testKATs kats cipher]) ++ testModes cipher ++ testIvArith cipher ) cipherMakeKey :: Cipher cipher => cipher -> ByteString -> Key cipher cipherMakeKey _ bs = Key bs cipherMakeIV :: BlockCipher cipher => cipher -> ByteString -> IV cipher cipherMakeIV _ bs = fromJust $ makeIV bs maybeGroup :: (String -> t -> [TestTree]) -> TestName -> [t] -> [TestTree] maybeGroup mkTest groupName l | null l = [] | otherwise = [testGroup groupName (concatMap (\(i, d) -> mkTest (show i) d) $ zip nbs l)] where nbs :: [Int] nbs = [0..]
vincenthz/cryptonite
tests/BlockCipher.hs
bsd-3-clause
20,437
0
18
5,749
4,926
2,577
2,349
300
3
{-# LANGUAGE DeriveGeneric, StandaloneDeriving, BangPatterns #-} module Main where import qualified Data.ByteString.Lazy as L import Cabal24 (PackageDescription) import Criterion.Main import qualified Data.Binary as Binary import Data.Binary.Get (Get) import qualified Data.Binary.Get as Binary import GenericsBenchCache main :: IO () main = benchmark =<< readPackageDescriptionCache 100 benchmark :: [PackageDescription] -> IO () benchmark pds = do let lbs = encode pds !_ = L.length lbs str = show pds !_ = length str defaultMain [ bench "encode" (nf encode pds) , bench "decode" (nf decode lbs) , bench "decode null" (nf decodeNull lbs) , bgroup "embarrassment" [ bench "read" (nf readPackageDescription str) , bench "show" (nf show pds) ] ] encode :: [PackageDescription] -> L.ByteString encode = Binary.encode decode :: L.ByteString -> Int decode = length . (Binary.decode :: L.ByteString -> [PackageDescription]) decodeNull :: L.ByteString -> () decodeNull = Binary.runGet $ do n <- Binary.get :: Get Int go n where go 0 = return () go i = do x <- Binary.get :: Get PackageDescription x `seq` go (i-1) readPackageDescription :: String -> Int readPackageDescription = length . (read :: String -> [PackageDescription])
CloudI/CloudI
src/api/haskell/external/binary-0.8.7.0/benchmarks/GenericsBench.hs
mit
1,436
0
13
395
432
230
202
39
2
{-# LANGUAGE PatternGuards #-} -- | The IO in this module is only to evaluate an envrionment variable, -- the 'Env' itself it passed around purely. module Development.Make.Env(Env, newEnv, addEnv, askEnv) where import Development.Make.Type import Data.Maybe import qualified Data.HashMap.Strict as Map newtype Env = Env (Map.HashMap String (Assign,Expr)) newEnv :: [(String,String)] -> Env newEnv xs = Env $ Map.fromList [(a,(Equals,Lit b)) | (a,b) <- xs] addEnv :: String -> Assign -> Expr -> Env -> IO Env addEnv name ass val env@(Env e) = case ass of QuestionEquals -> if isJust $ Map.lookup name e then return env else addEnv name Equals val env Equals -> return $ Env $ Map.insert name (Equals,val) e ColonEquals -> do l <- askEnv env val; return $ Env $ Map.insert name (ColonEquals,Lit l) e PlusEquals -> case Map.lookup name e of Just (Equals,x) -> return $ Env $ Map.insert name (Equals,Concat [x,Lit " ",val]) e Just (ColonEquals,x) -> do l <- askEnv env val; return $ Env $ Map.insert name (ColonEquals,Concat [x,Lit " ",Lit l]) e _ -> addEnv name Equals val env askEnv :: Env -> Expr -> IO String askEnv (Env e) x = do res <- f [] x case simplifyExpr res of Lit x -> return x x -> error $ "Internal error in askEnv, " ++ show x where f seen (Var x) | x `elem` seen = error $ "Recursion in variables, " ++ show seen | Just (_,y) <- Map.lookup x e = f (x:seen) y | otherwise = return $ Lit "" f seen x = descendExprM (f seen) x
nh2/shake
Development/Make/Env.hs
bsd-3-clause
1,580
0
18
407
661
340
321
27
7
-- | File system process. Acts as a maintainer for the filesystem in -- question and can only do single-file torrents. It should be -- fairly easy to add Multi-file torrents by altering this file and -- the FS module. {-# LANGUAGE ScopedTypeVariables #-} module Process.FS ( FSPChannel , FSPMsg(..) , start ) where import Control.Concurrent import Control.Concurrent.STM import Control.Monad.Reader import Control.Monad.State import Data.Array import qualified Data.ByteString as B import Process import Torrent import qualified FS import Supervisor data FSPMsg = CheckPiece PieceNum (TMVar (Maybe Bool)) | WriteBlock PieceNum Block B.ByteString | ReadBlock PieceNum Block (TMVar B.ByteString) type FSPChannel = TChan FSPMsg data CF = CF { fspCh :: FSPChannel -- ^ Channel on which to receive messages } instance Logging CF where logName _ = "Process.FS" data ST = ST { fileHandles :: !FS.Handles -- ^ The file we are working on , pieceMap :: !FS.PieceMap -- ^ Map of where the pieces reside } -- INTERFACE ---------------------------------------------------------------------- start :: FS.Handles -> FS.PieceMap -> FSPChannel -> SupervisorChannel -> IO ThreadId start handles pm fspC supC = spawnP (CF fspC) (ST handles pm) ({-# SCC "FS" #-} catchP lp (defaultStopHandler supC)) where lp = do c <- asks fspCh msg <- liftIO . atomically $ readTChan c case msg of CheckPiece n v -> do pmap <- gets pieceMap let p = pmap ! n r <- gets fileHandles >>= (liftIO . FS.checkPiece p) liftIO . atomically $ putTMVar v (Just r) ReadBlock n blk v -> do debugP $ "Reading block #" ++ show n ++ "(" ++ show (blockOffset blk) ++ ", " ++ show (blockSize blk) ++ ")" -- TODO: Protection, either here or in the Peer code h <- gets fileHandles bs <- gets pieceMap >>= (liftIO . FS.readBlock n blk h) liftIO . atomically $ putTMVar v bs WriteBlock pn blk bs -> {-# SCC "FS_WriteBlock" #-} do -- TODO: Protection, either here or in the Peer code fh <- gets fileHandles pmap <- gets pieceMap liftIO $ FS.writeBlock fh pn blk pmap bs lp
rethab/combinatorrent
src/Process/FS.hs
bsd-2-clause
2,442
0
20
767
580
298
282
54
3
-- | -- Module : Data.Attoparsec -- Copyright : Bryan O'Sullivan 2007-2011 -- License : BSD3 -- -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : unknown -- -- Simple, efficient combinator parsing for 'ByteString' strings, -- loosely based on the Parsec library. module Data.Attoparsec ( module Data.Attoparsec.ByteString ) where import Data.Attoparsec.ByteString
ghcjs/haddock-internal
vendor/attoparsec-0.10.4.0/Data/Attoparsec.hs
bsd-2-clause
430
0
5
90
32
25
7
4
0
{-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} module NN.Examples.GoogLeNet where import Gen.Caffe.FillerParameter as FP import Gen.Caffe.InnerProductParameter as IP import Gen.Caffe.LayerParameter as LP import Control.Lens import Control.Monad import Data.Sequence (singleton) import Data.Word import NN import NN.Examples.ImageNet googleTrain = train & mirror' True & batchSize' 32 & cropSize' 224 googleTest = test & mirror' False & batchSize' 50 & cropSize' 224 googleMult = [def & lrMult' 1 & decayMult' 1, -- weights def & lrMult' 2 & decayMult' 0] -- biases googleConv = conv & param' googleMult & biasFillerC' (constant 0.2) googleLRN = lrn & localSize' 5 & alphaLRN' 0.0001 & betaLRN' 0.75 googlePool = maxPool & sizeP' 3 & strideP' 2 googleIP n = ip n & param' googleMult conv1 = googleConv & numOutputC' 64 & padC' 3 & kernelSizeC' 7 & strideC' 2 & weightFillerC' (xavier 0.1) conv2 = googleConv & numOutputC' 192 & padC' 1 & kernelSizeC' 3 & weightFillerC' (xavier 0.03) topPool = avgPool & sizeP' 7 & strideP' 1 topFc = googleIP 1000 & biasFillerIP' (constant 0) & weightFillerIP' (xavier 0.0) -- Weird, but in Caffe replication & _inner_product_param._Just.IP._weight_filler._Just._std .~ Nothing data Inception = Inception {_1x1, _3x3reduce, _3x3, _5x5reduce, _5x5, _poolProj :: Word32} inception :: Node -> Inception -> NetBuilder Node inception input Inception{..} = do columns' <- mapM sequential columns concat'' <- layer' concat' forM_ columns' $ \(bottom, top) -> do input >-> bottom top >-> concat'' return concat'' where columns = [ [googleConv & numOutputC' _1x1 & kernelSizeC' 1 & weightFillerC' (xavier 0.03), relu], [googleConv & numOutputC' _3x3reduce & kernelSizeC' 1 & weightFillerC' (xavier 0.09), relu, googleConv & numOutputC' _3x3 & kernelSizeC' 3 & weightFillerC' (xavier 0.03) & padC' 1, relu], [googleConv & numOutputC' _5x5reduce & kernelSizeC' 1 & weightFillerC' (xavier 0.2), relu, googleConv & numOutputC' _5x5 & kernelSizeC' 5 & weightFillerC' (xavier 0.03) & padC' 2, relu], [maxPool& sizeP' 3 & strideP' 3 & padP' 1, googleConv & numOutputC' _poolProj & kernelSizeC' 1 & weightFillerC' (xavier 0.1), relu]] intermediateClassifier :: Node -> NetBuilder () intermediateClassifier source = do (input, representation) <- sequential [pool1, conv1', relu, fc1, relu, dropout 0.7, fc2] source >-> input forM_ [accuracy 1, accuracy 5, softmax & _loss_weight <>~ singleton 0.3] $ attach (From representation) where pool1 = avgPool & sizeP' 5 & strideP' 3 conv1' = googleConv & numOutputC' 128 & kernelSizeC' 1 & weightFillerC' (xavier 0.08) fc1 = googleIP 1024 & weightFillerIP' (xavier 0.02) & biasFillerIP' (constant 0.2) fc2 = googleIP 1000 & weightFillerIP' (xavier 0.0009765625) & biasFillerIP' (constant 0) -- What to do at each row in the inner column? data Row = I Inception | Classifier | MaxPool insertRow :: Node -> Row -> NetBuilder Node insertRow input (I inceptor) = inception input inceptor insertRow input Classifier = do intermediateClassifier input return input insertRow input MaxPool = do node <- layer' googlePool input >-> node return node googLeNet :: NetBuilder () googLeNet = do (input, initial) <- sequential [conv1, relu, googlePool, googleLRN, conv2, relu, googleLRN, googlePool] top <- foldM insertRow initial [ I $ Inception 64 96 128 16 32 32, I $ Inception 128 128 192 32 96 64, MaxPool, I $ Inception 192 96 208 16 48 64, Classifier, I $ Inception 150 112 224 24 64 64, I $ Inception 128 128 256 24 64 64, I $ Inception 112 144 288 32 64 64, Classifier, I $ Inception 256 160 320 32 128 128, MaxPool, I $ Inception 256 160 320 32 128 128, I $ Inception 384 192 384 48 128 128] (_, representation) <- with top >- sequential [topPool, dropout 0.4, topFc] forM_ [accuracy 1, accuracy 5, softmax] $ attach (From representation) forM_ [googleTrain, googleTest] $ attach (To input) main :: IO () main = cli googLeNet
sjfloat/dnngraph
NN/Examples/GoogLeNet.hs
bsd-3-clause
4,422
1
13
1,125
1,498
752
746
-1
-1
-- | Dependency graph handling. module Distribution.MacOSX.DG ( DG(..), FDeps(..), dgEmpty, dgFDeps, dgAddPaths, dgAddFDeps ) where import Data.Graph.Inductive.Graph as G import Data.Graph.Inductive.Tree (Gr) import Data.List import Data.Maybe -- | A dependency graph is an ordinary fgl graph with 'FilePath's on -- its nodes, and directed edges. An edge from A to B indicates that -- A depends on B. data DG = DG (Gr FilePath ()) deriving Show -- | An FDeps represents some file and its list of library -- dependencies. data FDeps = FDeps FilePath [FilePath] deriving (Eq, Ord, Show) -- | Add a file dependency to a dependency graph. dgAddFDeps :: DG -> FDeps -> DG dgAddFDeps dg (FDeps src tgts) = dgAddDeps src tgts $ dg `dgAddPaths` (src:tgts) -- | Turn a dependency graph back into a list of FDeps. dgFDeps :: DG -> [FDeps] dgFDeps (DG g) = map mkFDep (G.labNodes g) where mkFDep :: G.LNode FilePath -> FDeps mkFDep (i, src) = FDeps src $ mapMaybe (G.lab g) (G.suc g i) -- | Create an empty dependency graph. dgEmpty :: DG dgEmpty = DG G.empty -- | Get the node number of a dependency graph node with a specified label. dgPathIdx :: DG -> FilePath -> Maybe Int dgPathIdx (DG g) p = case find (\x -> p == snd x) (G.labNodes g) of Just (i, _) -> Just i Nothing -> Nothing -- | Check if a certain path is already in a dependency graph. dgHasPath :: DG -> FilePath -> Bool dgHasPath dg p = case dgPathIdx dg p of Just _ -> True Nothing -> False -- | Add a list of paths as nodes to a dependency graph, dropping -- duplicates. dgAddPaths :: DG -> [FilePath] -> DG dgAddPaths = foldl dgAddPath -- | Add a single path as a node to a dependency graph, unless already -- present. dgAddPath :: DG -> FilePath -> DG dgAddPath dg@(DG g) p = if dg `dgHasPath` p then dg else DG $ G.insNode (head $ G.newNodes 1 g, p) g -- | Given a source path and a list of target paths, add a list of -- dependencies (ie edges) to a dependency graph. dgAddDeps :: FilePath -> [FilePath] -> DG -> DG dgAddDeps src tgts dg = foldl dgAddDep dg $ zip (repeat src) tgts -- | Add a (src, tgt) dependency (ie edge) to a dependency graph. dgAddDep :: DG -> (FilePath, FilePath) -> DG dgAddDep dg@(DG g) (src, tgt) = DG $ G.insEdge (getI src, getI tgt, ()) g where getI x = case dgPathIdx dg x of Just x' -> x' Nothing -> error "Can't happen" -- if called in context.
gimbo/cabal-macosx
Distribution/MacOSX/DG.hs
bsd-3-clause
2,543
0
11
650
697
380
317
43
2
module PFE4( PFE4MT,PFE4Info,runPFE4,clean4, getSt4ext,updSt4ext,setSt4ext,modEnv, typeCheckModule,rewriteAndTypeCheckModule, typeCheck,rewriteAndTypeCheck,topTypes,typeCheck',exTypeCheck, ) where import Prelude hiding (putStrLn,readFile,catch,ioError) --import Monad(when) import Data.List(intersect) import Data.Maybe(fromMaybe,isNothing) import HsConstants(mod_Prelude,mod_Ix) import HsModule(HsModuleI,ModuleName(..),hsModName) import HsModuleMaps(mapDecls) import TiModule(tcModuleGroup,representative,monomorphismRestriction) import TiNames(topName) import Relations(applyRel) import WorkModule(Ent(..)) import TiPNT() import TI(DeclsType,extendIEnv,extendEnv,concDeclsType,moduleContext,Typing(..),unzipTyped,run) import TiError(Error) import TiInstanceDB(Instance) import PNT(PNT(..)) import HsIdent(HsIdentI(..)) import TypedIds(IdTy(Value),NameSpace(..),namespace) import UniqueNames(noSrcLoc) import HasBaseName(getBaseName) import SourceNames(SN,fakeSN) import ScopeModule(origName) import PFE3(parseScopeSourceFile) import PFE3(PFE3MT,runPFE3,getSt3ext,updSt3ext,clean3) import PFE2(getExports) import PFE0(Upd,epput,newerThan,optSubGraph,sortCurrentModuleGraph,projPath,projectDir,maybeF,withProjectDir,moduleInfoPath,allModules) import PFE_Rewrites(getStdNames,prelValue,flRewrite) import PFE_Rewrite import PrettyPrint import qualified Lift import MUtils import ExceptMT --import StateMT(getSt,updSt_) import SimpleGraphs(reachable) import AbstractIO import FileUtils(updateFile') import DirUtils(optCreateDirectory,getModificationTimeMaybe,latestModTime,rmR) type ModuleTypeInfo i ds = (ClockTime,([(RewriteName,HsModuleI (SN ModuleName) i ds)], ([Instance i],DeclsType i))) type PFE4Info i ds = [(ModuleName,ModuleTypeInfo i ds)] modEnv :: PFE4Info i ds -> ModuleName -> Maybe (DeclsType i) modEnv pfe4info m = snd . snd . snd # lookup m pfe4info --id4 :: Upd (PFE4Info i ds) --id4 = id pfe4info0 = []::PFE4Info i ds type PFE4MT n i1 i2 ds1 ds2 ext m = PFE3MT n i1 ds1 (PFE4Info i2 ds2,ext) m -- Extra exeption monad transformer, -- to be able to keep the structured type for type errors. -- It's just only locally for now because of the extra lifting involved type ExPFE4MT n i1 i2 ds1 ds2 ext m = WithExcept (Error (HsIdentI i2)) (PFE4MT n i1 i2 ds1 ds2 ext m) runPFE4 ext = runPFE3 (pfe4info0,ext) getSt4 :: Monad m => ExPFE4MT n i1 i2 ds1 ds2 ext m (PFE4Info i2 ds2) updSt4 :: Monad m => Upd (PFE4Info i2 ds2)->ExPFE4MT n i1 i2 ds1 ds2 ext m () getSt4ext :: Monad m => PFE4MT n i1 i2 ds1 ds2 ext m ext updSt4ext :: Monad m => Upd ext->PFE4MT n i1 i2 ds1 ds2 ext m () getSt4 = fst # lift getSt3ext updSt4 = lift . updSt3ext . apFst setSt4 = updSt4 . const getSt4ext = snd # getSt3ext updSt4ext = updSt3ext . apSnd setSt4ext = updSt4ext . const expfe4 = id :: Upd (ExPFE4MT n i1 i2 ds1 ds2 ext m a) -- a type signature with holes pfe4 = id :: Upd (PFE4MT n i1 i2 ds1 ds2 ext m a) -- a type signature with holes typeCheckModule m = rewriteAndTypeCheckModule idRw m rewriteAndTypeCheckModule rewrite@(Rewrite rwname0 _) m = do --epput $ "rewriteAndTypeCheckModule"<+>m r <- lookuprw.fst.snd.fromJust' "PFE4.hs:108b" .lookup m # rewriteAndTypeCheck rewrite (Just [m]) --seq r $ epput $ "return from rewriteAndTypeCheckModule"<+>m return r where rwname = rwname0++"fl" lookuprw rws = fromJust' ("PFE4.hs:108a "++rwname++" "++show (map fst rws)) (lookup rwname rws) rewriteAndTypeCheck f = rewriteAndTypeCheck' f True typeCheck = typeCheck' True topTypes = typeCheck' False exTypeCheck = removeExcept . exRewriteAndTypeCheck' idRw True {- typeCheck' :: ... => Bool -> [ModuleName] -> t m (PFE4Info i2 ds) -} typeCheck' = rewriteAndTypeCheck' idRw rewriteAndTypeCheck' rewrite wantAST optms = pfe4 $ Lift.lift =<< removeExcept (exRewriteAndTypeCheck' rewrite wantAST optms) exRewriteAndTypeCheck' userRewrite wantAST optms = do subsg <- flip optSubGraph optms # lift sortCurrentModuleGraph oldTypes <- getSt4 stdNames <- lift getStdNames let rewrite = userRewrite `compRw` flRewrite types <- rewriteAndTypeCheck'' stdNames rewrite wantAST optms oldTypes subsg let newTypes = types++[old|old@(m,_)<-oldTypes,m `notElem` newms] newms = map fst types setSt4 newTypes return types rewriteAndTypeCheck'' stdNames (Rewrite rwname rwM) wantAST optms oldTypes subsg = expfe4 $ do lift $ optCreateDirectory `projPath` typesdir rewrite <- lift rwM tcSccs rewrite [] [] subsg where subg = map snd (concat subsg) ms = fromMaybe (map fst subg) optms rms = map (fst.snd.head) subsg -- representative from each scc tcSccs rewrite types updated [] = return types tcSccs rewrite types updated (scc:sccs) = do let sccms = map (fst.snd) scc wanted = wantAST && (not.null $ sccms `intersect` ms) --lift $ epput $ "wantAST="<>wantAST<+>"wanted="<>wanted (types',updated') <- tcScc rewrite wanted sccms types updated scc tcSccs rewrite (types'++types) (updated'++updated) sccs tcScc rewrite wanted mns types updated scc@(_:_) = if wanted && any isNothing [lookup rwname.fst.snd=<<lookup m oldTypes|m<-mns] || not (null updated_imports) then tcAgain else useOld where updated_imports = imports_approx `intersect` updated -- A coarse approximation to what is needed by a module: -- (Advantage: this is the right thing for instances) imports_approx = reachable subg mns useOld = do srct <- latestModTime srcfs let opt_oldtypes = mapM (flip lookup oldTypes) mns oldtt = minimum.map fst # opt_oldtypes if srct `newerThan` oldtt then do tt <- lift $ maybeF getModificationTimeMaybe typesf if srct `newerThan` tt then tcAgain else do --lift $ epput $ "Using old types:"<+>fsep mns types' <- readTypeFiles let t = fromJust' "PFE4.hs:177" tt -- !!! Type info is duplicated here: return ([(m,(t,([],types')))|m<-mns],[]) else return (zip mns (fromJust' "PFE4.hs:180" opt_oldtypes),[]) parseSCM = mapM ((mapDecls rewrite . snd # ) . parseScopeSourceFile .fst) tcAgain = do ms <- lift (parseSCM scc) lift $ epput $ "Type checking:"<+>fsep mns tms:>:types' <- tcScc' ms optdir <- lift projectDir (updated,t) <- case optdir of Nothing -> do --No access to the old types here, so we have to assume --they have changed!! (This should be easy to improve.) t <- getClockTime return (True,t) Just dir -> do updated <- updateTypeFiles dir types' t <- getModificationTime (typesf dir) return (updated,t) --lift $ epput $ [(getBaseName (hsModName tm),(show t,([(rwname,"()")],"()")))|tm<-tms] -- !!! Type info is duplicated here: return ([(getBaseName (hsModName tm),(t,([(rwname,tm)],types')))|tm<-tms], if updated then mns else []) tcScc' ms = do mono <- (/=Just "no") # maybeM (getEnv "PFE_monomorphism") --Lift.lift $ either raise return . run $ tcScc'' mono ms tcScc'' mono ms@(_:_) = monomorphismRestriction mono $ extendIEnv (concat insts) $ extendEnv (concDeclsType envs) $ moduleContext mns $ tcModuleGroup stdNames rewrite ms where (insts,envs) = unzip [mt|(m,(_,(_,mt)))<-types, m `elem` imports_approx,m `elem` rms] srcfs = map fst scc mn = representative mns -- pick one representative from the scc kindsf = kindsFile mn typesf = typesFile mn instsf = instsFile mn updateTypeFiles dir (insts,(kinds,types)) = do uk <- updateFile' (kindsf dir) (showTypings kinds) ut <- updateFile' (typesf dir) (showTypings types) ui <- updateFile' (instsf dir) (show insts) return (uk||ut||ui) readTypeFiles = do dir <- fromJust' "PFE4.hs:233" # lift projectDir kinds <- readTypings # readFile (kindsf dir) types <- readTypings # readFile (typesf dir) insts <- let path = instsf dir in read'' path # readFile path return (insts,(kinds,types)) showTypings xys = shl (length xs).shls (map (fmap pn) xs) . shls ys $ "" where shls xs r = foldr shl r xs shl x = shows x.showChar '\n' xs:>:ys = unzipTyped xys pn (PNT n _ _) = n -- hmm readTypings s = rdls (lines s) where rdls (n:ls) = uncurry zipTypings (splitAt (rd n) ls) zipTypings [] _ = [] zipTypings (x:xs) ~(y:ys) = (fmap pnt (rd x):>:rd y):zipTypings xs ys pnt n = PNT n Value noSrcLoc -- hmm! rd s = read'' "PFE4.readTypings" s -------------------------------------------------------------------------------- clean4 = withProjectDir clean where clean dir = do rmR [typesdir dir] clean3 -------------------------------------------------------------------------------- typesdir dir=dir++"types/" typesFile m dir = typesdir dir++moduleInfoPath m++".types" kindsFile m dir = typesdir dir++moduleInfoPath m++".kinds" instsFile m dir = typesdir dir++moduleInfoPath m++".insts" -------------------------------------------------------------------------------- instance CatchIO err m => CatchIO err (WithExcept e m) where m `catch` f = do r <- lift $ try $ removeExcept m case r of Left ioe -> f ioe Right ok -> either raise return ok ioError = lift . ioError
kmate/HaRe
old/tools/pfe/PFE4.hs
bsd-3-clause
9,594
94
28
2,098
2,943
1,607
1,336
-1
-1