code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Language.Calc.Options where
data Options = Options { optShowVersion :: Bool
, optShowOutScan :: Bool
, optShowOutParser :: Bool
, optShowHelp :: Bool
} deriving Show
defaultOptions :: Options
defaultOptions = Options { optShowVersion = False
, optShowOutScan = False
, optShowOutParser = False
, optShowHelp = False
}
| jfcmacro/calc | src/Language/Calc/Options.hs | bsd-3-clause | 547 | 0 | 8 | 271 | 79 | 51 | 28 | 11 | 1 |
{-# LANGUAGE DeriveFunctor, EmptyDataDecls, OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
module LXC.Compat (LXC(), withContainer, Container(..)) where
import ClassyPrelude.Yesod
data LXC a = LXC
instance Monad LXC where
return _ = LXC
_ >>= _ = LXC
deriving instance Functor LXC
instance Applicative LXC where
pure = return
(<*>) = ap
instance MonadIO LXC where
liftIO = const LXC
notImpl :: a
notImpl = error "Not implemented"
withContainer :: MonadIO m => Container -> LXC a -> m a
withContainer _ _ = return notImpl
data Container = Container { containerName :: String
, containerConfigPath :: Maybe String
} deriving (Show)
| konn/leport | leport-web/LXC/Compat.hs | bsd-3-clause | 748 | 0 | 9 | 207 | 193 | 106 | 87 | 24 | 1 |
-- UUAGC 0.9.50 (src-ag/HsToken.ag)
module HsToken where
{-# LINE 2 "./src-ag/HsToken.ag" #-}
import CommonTypes
import UU.Scanner.Position(Pos)
{-# LINE 10 "dist/build/HsToken.hs" #-}
-- HsToken -----------------------------------------------------
{-
alternatives:
alternative AGLocal:
child var : {Identifier}
child pos : {Pos}
child rdesc : {Maybe String}
alternative AGField:
child field : {Identifier}
child attr : {Identifier}
child pos : {Pos}
child rdesc : {Maybe String}
alternative HsToken:
child value : {String}
child pos : {Pos}
alternative CharToken:
child value : {String}
child pos : {Pos}
alternative StrToken:
child value : {String}
child pos : {Pos}
alternative Err:
child mesg : {String}
child pos : {Pos}
-}
data HsToken = AGLocal (Identifier) (Pos) ((Maybe String))
| AGField (Identifier) (Identifier) (Pos) ((Maybe String))
| HsToken (String) (Pos)
| CharToken (String) (Pos)
| StrToken (String) (Pos)
| Err (String) (Pos)
deriving ( Show)
-- HsTokens ----------------------------------------------------
{-
alternatives:
alternative Cons:
child hd : HsToken
child tl : HsTokens
alternative Nil:
-}
type HsTokens = [HsToken]
-- HsTokensRoot ------------------------------------------------
{-
alternatives:
alternative HsTokensRoot:
child tokens : HsTokens
-}
data HsTokensRoot = HsTokensRoot (HsTokens) | norm2782/uuagc | src-generated/HsToken.hs | bsd-3-clause | 1,819 | 0 | 9 | 663 | 164 | 103 | 61 | 12 | 0 |
-- Copyright 2006, Bjorn Bringert.
-- Copyright 2009, Henning Thielemann.
module Network.MoHWS.Server.Request where
import qualified Network.MoHWS.HTTP.Request as Request
import Network.BSD (HostEntry, )
import Network.Socket (HostAddress, PortNumber, )
-- | All the server's information about a request
data T body = Cons
{
clientRequest :: Request.T body,
clientAddress :: HostAddress,
clientName :: Maybe HostEntry,
requestHostName :: HostEntry,
serverURIPath :: String,
serverFilename :: FilePath,
serverPort :: PortNumber
}
deriving Show
instance Functor T where
fmap f req =
Cons {
clientAddress = clientAddress req,
clientName = clientName req,
requestHostName = requestHostName req,
serverURIPath = serverURIPath req,
serverFilename = serverFilename req,
serverPort = serverPort req,
clientRequest = fmap f $ clientRequest req
}
| xpika/mohws | src/Network/MoHWS/Server/Request.hs | bsd-3-clause | 992 | 0 | 10 | 265 | 199 | 120 | 79 | 23 | 0 |
-- |
-- Module: Math.NumberTheory.EisensteinIntegersTests
-- Copyright: (c) 2018 Alexandre Rodrigues Baldé
-- Licence: MIT
-- Maintainer: Alexandre Rodrigues Baldé <alexandrer_b@outlook.
--
-- Tests for Math.NumberTheory.EisensteinIntegers
--
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Math.NumberTheory.EisensteinIntegersTests
( testSuite
) where
import Prelude hiding (gcd, rem, quot, quotRem)
import Data.Euclidean
import Data.Maybe (fromJust, isJust)
import Data.Proxy
import Test.Tasty.QuickCheck as QC hiding (Positive(..), NonNegative(..))
import Test.QuickCheck.Classes
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (Assertion, assertEqual,
testCase)
import qualified Math.NumberTheory.Quadratic.EisensteinIntegers as E
import Math.NumberTheory.Primes
import Math.NumberTheory.TestUtils
-- | Check that @signum@ and @abs@ satisfy @z == signum z * abs z@, where @z@ is
-- an @EisensteinInteger@.
signumAbsProperty :: E.EisensteinInteger -> Bool
signumAbsProperty z = z == signum z * abs z
-- | Check that @abs@ maps an @EisensteinInteger@ to its associate in first
-- sextant.
absProperty :: E.EisensteinInteger -> Bool
absProperty z = isOrigin || (inFirstSextant && isAssociate)
where
z'@(x' E.:+ y') = abs z
isOrigin = z' == 0 && z == 0
-- The First sextant includes the positive real axis, but not the origin
-- or the line defined by the linear equation @y = (sqrt 3) * x@ in the
-- Cartesian plane.
inFirstSextant = x' > y' && y' >= 0
isAssociate = z' `elem` map (\e -> z * (1 E.:+ 1) ^ e) [0 .. 5]
-- | Verify that @rem@ produces a remainder smaller than the divisor with
-- regards to the Euclidean domain's function.
remProperty1 :: E.EisensteinInteger -> E.EisensteinInteger -> Bool
remProperty1 x y = (y == 0) || E.norm (x `rem` y) < E.norm y
-- | Verify that @quot@ and @rem@ are what `quotRem` produces.
quotRemProperty1 :: E.EisensteinInteger -> E.EisensteinInteger -> Bool
quotRemProperty1 x y = (y == 0) || q == q' && r == r'
where
(q, r) = quotRem x y
q' = quot x y
r' = rem x y
-- | Verify that @quotRemE@ produces the right quotient and remainder.
quotRemProperty2 :: E.EisensteinInteger -> E.EisensteinInteger -> Bool
quotRemProperty2 x y = (y == 0) || (x `quot` y) * y + (x `rem` y) == x
-- | Verify that @gcd z1 z2@ always divides @z1@ and @z2@.
gcdEProperty1 :: E.EisensteinInteger -> E.EisensteinInteger -> Bool
gcdEProperty1 z1 z2
= z1 == 0 && z2 == 0
|| z1 `rem` z == 0 && z2 `rem` z == 0
where
z = gcd z1 z2
-- | Verify that a common divisor of @z1, z2@ is a always divisor of @gcd z1 z2@.
gcdEProperty2 :: E.EisensteinInteger -> E.EisensteinInteger -> E.EisensteinInteger -> Bool
gcdEProperty2 z z1 z2
= z == 0
|| gcd z1' z2' `rem` z == 0
where
z1' = z * z1
z2' = z * z2
-- | A special case that tests rounding/truncating in GCD.
gcdESpecialCase1 :: Assertion
gcdESpecialCase1 = assertEqual "gcd" (1 E.:+ 1) $ gcd (12 E.:+ 23) (23 E.:+ 34)
findPrimesProperty1 :: Positive Int -> Bool
findPrimesProperty1 (Positive index) =
let -- Only retain primes that are of the form @6k + 1@, for some nonzero natural @k@.
prop prime = unPrime prime `mod` 6 == 1
p = (!! index) $ filter prop $ drop 3 primes
in isJust (isPrime (unPrime (E.findPrime p) :: E.EisensteinInteger))
-- | Checks that the @norm@ of the Euclidean domain of Eisenstein integers
-- is multiplicative i.e.
-- @forall e1 e2 in Z[ω] . norm(e1 * e2) == norm(e1) * norm(e2)@.
euclideanDomainProperty1 :: E.EisensteinInteger -> E.EisensteinInteger -> Bool
euclideanDomainProperty1 e1 e2 = E.norm (e1 * e2) == E.norm e1 * E.norm e2
-- | Checks that the numbers produced by @primes@ are actually Eisenstein
-- primes.
primesProperty1 :: Positive Int -> Bool
primesProperty1 (Positive index) = all (isJust . isPrime . (unPrime :: Prime E.EisensteinInteger -> E.EisensteinInteger)) $ take index E.primes
-- | Checks that the infinite list of Eisenstein primes @primes@ is ordered
-- by the numbers' norm.
primesProperty2 :: Positive Int -> Bool
primesProperty2 (Positive index) =
let isOrdered :: [Prime E.EisensteinInteger] -> Bool
isOrdered xs = all (\(x, y) -> E.norm (unPrime x) <= E.norm (unPrime y)) . zip xs $ tail xs
in isOrdered $ take index E.primes
-- | Checks that the numbers produced by @primes@ are all in the first
-- sextant.
primesProperty3 :: Positive Int -> Bool
primesProperty3 (Positive index) =
all (\e -> abs (unPrime e) == (unPrime e :: E.EisensteinInteger)) $ take index E.primes
-- | An Eisenstein integer is either zero or associated (i.e. equal up to
-- multiplication by a unit) to the product of its factors raised to their
-- respective exponents.
factoriseProperty1 :: E.EisensteinInteger -> Bool
factoriseProperty1 g = g == 0 || abs g == abs g'
where
factors = factorise g
g' = product $ map (\(p, k) -> unPrime p ^ k) factors
-- | Check that there are no factors with exponent @0@ in the factorisation.
factoriseProperty2 :: E.EisensteinInteger -> Bool
factoriseProperty2 z = z == 0 || all ((> 0) . snd) (factorise z)
-- | Check that no factor produced by @factorise@ is a unit.
factoriseProperty3 :: E.EisensteinInteger -> Bool
factoriseProperty3 z = z == 0 || all ((> 1) . E.norm . unPrime . fst) (factorise z)
factoriseSpecialCase1 :: Assertion
factoriseSpecialCase1 = assertEqual "should be equal"
[ (fromJust $ isPrime $ 2 E.:+ 1, 3)
, (fromJust $ isPrime $ 3 E.:+ 1, 1)
]
(factorise (15 E.:+ 12))
testSuite :: TestTree
testSuite = testGroup "EisensteinIntegers"
[ testSmallAndQuick "forall z . z == signum z * abs z" signumAbsProperty
, testSmallAndQuick "abs z rotates to the first sextant" absProperty
, testGroup "Division"
[ testSmallAndQuick "The remainder's norm is smaller than the divisor's"
remProperty1
, testSmallAndQuick "quotE and remE work properly" quotRemProperty1
, testSmallAndQuick "quotRemE works properly" quotRemProperty2
]
, testGroup "g.c.d."
[ testSmallAndQuick "The g.c.d. of two Eisenstein integers divides them"
gcdEProperty1
-- smallcheck takes too long
, QC.testProperty "Common divisor divides gcd"
gcdEProperty2
, testCase "g.c.d. (12 :+ 23) (23 :+ 34)" gcdESpecialCase1
]
, testSmallAndQuick "The Eisenstein norm function is multiplicative"
euclideanDomainProperty1
, testGroup "Primality"
[ testSmallAndQuick "findPrime returns prime"
findPrimesProperty1
, testSmallAndQuick "primes are actually prime"
primesProperty1
, testSmallAndQuick "primes is ordered"
primesProperty2
, testSmallAndQuick "primes are in the first sextant"
primesProperty3
]
, testGroup "Factorisation"
[ testSmallAndQuick "factorise produces correct results"
factoriseProperty1
, testSmallAndQuick "factorise produces no factors with exponent 0"
factoriseProperty2
, testSmallAndQuick "factorise produces no unit factors"
factoriseProperty3
, testCase "factorise 15:+12" factoriseSpecialCase1
]
, lawsToTest $ gcdDomainLaws (Proxy :: Proxy E.EisensteinInteger)
, lawsToTest $ euclideanLaws (Proxy :: Proxy E.EisensteinInteger)
]
| Bodigrim/arithmoi | test-suite/Math/NumberTheory/EisensteinIntegersTests.hs | mit | 7,581 | 0 | 17 | 1,771 | 1,691 | 914 | 777 | 112 | 1 |
module Web.Slack.Prelude
(
(<$>),
(<*>),
FromJSON(..),
Value(..),
(.:),
eitherDecode,
Generic,
Text,
unpack,
printf,
liftIO,
get,
hoistEither
)
where
import Control.Applicative((<$>), (<*>))
import Data.Aeson (FromJSON(..), Value(..), (.:), eitherDecode)
import GHC.Generics (Generic)
import Data.Text (Text, unpack)
import Text.Printf (printf)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.State (get)
import Control.Monad.Trans.Either (hoistEither)
| dhrosa/hslack | Web/Slack/Prelude.hs | mit | 612 | 0 | 6 | 193 | 176 | 119 | 57 | 23 | 0 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
module Unison.Type where
import Data.Aeson (ToJSON(..), FromJSON(..))
import Data.Aeson.TH
import Data.Maybe (fromMaybe)
import Data.Set (Set)
import Data.Text (Text)
import GHC.Generics
import Prelude.Extras (Eq1(..),Show1(..))
import Unison.Doc (Doc)
import Unison.Note (Noted)
import Unison.Reference (Reference)
import Unison.Symbol (Symbol(..))
import Unison.Var (Var)
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Unison.ABT as ABT
import qualified Unison.Doc as D
import qualified Unison.Dimensions as Dimensions
import qualified Unison.Hash as Hash
import qualified Unison.JSON as J
import qualified Unison.Kind as K
import qualified Unison.Reference as Reference
import qualified Unison.Symbol as Symbol
import qualified Unison.Var as Var
import qualified Unison.View as View
-- | Type literals
data Literal
= Number
| Text
| Vector
| Distance
| Ref Reference -- ^ A type literal uniquely defined by some nameless Hash
deriving (Eq,Ord,Generic)
deriveJSON defaultOptions ''Literal
-- | Base functor for types in the Unison language
data F a
= Lit Literal
| Arrow a a
| Ann a K.Kind
| App a a
| Constrain a () -- todo: constraint language
| Forall a
| Existential a
| Universal a
deriving (Eq,Foldable,Functor,Generic1,Traversable)
deriveJSON defaultOptions ''F
instance Eq1 F where (==#) = (==)
instance Show1 F where showsPrec1 = showsPrec
-- | Types are represented as ABTs over the base functor F, with variables in `v`
type Type v = AnnotatedType v ()
-- | Like `Type v`, but with an annotation of type `a` at every level in the tree
type AnnotatedType v a = ABT.Term F v a
-- An environment for looking up type references
type Env f v = Reference -> Noted f (Type v)
freeVars :: Type v -> Set v
freeVars = ABT.freeVars
data Monotype v = Monotype { getPolytype :: Type v } deriving (Eq)
instance Var v => Show (Monotype v) where
show = show . getPolytype
-- Smart constructor which checks if a `Type` has no `Forall` quantifiers.
monotype :: Ord v => Type v -> Maybe (Monotype v)
monotype t = Monotype <$> ABT.visit isMono t where
isMono (Forall' _ _) = Just Nothing
isMono _ = Nothing
-- some smart patterns
pattern Lit' l <- ABT.Tm' (Lit l)
pattern Arrow' i o <- ABT.Tm' (Arrow i o)
pattern Arrows' spine <- (unArrows -> Just spine)
pattern ArrowsP' spine <- (unArrows' -> Just spine)
pattern Ann' t k <- ABT.Tm' (Ann t k)
pattern App' f x <- ABT.Tm' (App f x)
pattern Apps' f args <- (unApps -> Just (f, args))
pattern AppsP' f args <- (unApps' -> Just (f, args))
pattern Constrain' t u <- ABT.Tm' (Constrain t u)
pattern Forall' v body <- ABT.Tm' (Forall (ABT.Abs' v body))
pattern ForallsP' vs body <- (unForalls' -> Just (vs, body))
pattern Existential' v <- ABT.Tm' (Existential (ABT.Var' v))
pattern Universal' v <- ABT.Tm' (Universal (ABT.Var' v))
unArrows :: Type v -> Maybe [Type v]
unArrows t =
case go t of [] -> Nothing; l -> Just l
where
go (Arrow' i o) = i : go o
go _ = []
unArrows' :: Type v -> Maybe [(Type v,Path)]
unArrows' t = addPaths <$> unArrows t
where addPaths ts = ts `zip` arrowPaths (length ts)
unForalls' :: Type v -> Maybe ([(v, Path)], (Type v, Path))
unForalls' (Forall' v body) = case unForalls' body of
Nothing -> Just ([(v, [])], (body, [Body])) -- todo, need a path for forall vars
Just (vs, (body,bodyp)) -> Just ((v, []) : vs, (body, Body:bodyp))
unForalls' _ = Nothing
unApps :: Type v -> Maybe (Type v, [Type v])
unApps t = case go t [] of [] -> Nothing; f:args -> Just (f,args)
where
go (App' i o) acc = go i (o:acc)
go fn args = fn:args
unApps' :: Type v -> Maybe ((Type v,Path), [(Type v,Path)])
unApps' t = addPaths <$> unApps t
where
addPaths (f,args) = case appPaths (length args) of
(fp,ap) -> ((f,fp), args `zip` ap)
appPaths :: Int -> (Path, [Path])
appPaths numArgs = (fnp, argsp)
where
fnp = replicate numArgs Fn
argsp = reverse . take numArgs $ iterate (Fn:) [Arg]
arrowPaths :: Int -> [Path]
arrowPaths spineLength =
(take (spineLength-1) $ iterate (Output:) [Input]) ++
[replicate spineLength Output]
matchExistential :: Eq v => v -> Type v -> Bool
matchExistential v (Existential' x) = x == v
matchExistential _ _ = False
matchUniversal :: Eq v => v -> Type v -> Bool
matchUniversal v (Universal' x) = x == v
matchUniversal _ _ = False
-- some smart constructors
lit :: Ord v => Literal -> Type v
lit l = ABT.tm (Lit l)
ref :: Ord v => Reference -> Type v
ref = lit . Ref
app :: Ord v => Type v -> Type v -> Type v
app f arg = ABT.tm (App f arg)
arrow :: Ord v => Type v -> Type v -> Type v
arrow i o = ABT.tm (Arrow i o)
ann :: Ord v => Type v -> K.Kind -> Type v
ann e t = ABT.tm (Ann e t)
forall :: Ord v => v -> Type v -> Type v
forall v body = ABT.tm (Forall (ABT.abs v body))
existential :: Ord v => v -> Type v
existential v = ABT.tm (Existential (ABT.var v))
universal :: Ord v => v -> Type v
universal v = ABT.tm (Universal (ABT.var v))
v' :: Var v => Text -> Type v
v' s = universal (ABT.v' s)
forall' :: Var v => [Text] -> Type v -> Type v
forall' vs body = foldr forall body (map ABT.v' vs)
constrain :: Ord v => Type v -> () -> Type v
constrain t u = ABT.tm (Constrain t u)
-- | Bind all free variables with an outer `forall`.
generalize :: Ord v => Type v -> Type v
generalize t = foldr forall t $ Set.toList (ABT.freeVars t)
data PathElement
= Fn -- ^ Points at type in a type application
| Arg -- ^ Points at the argument in a type application
| Input -- ^ Points at the left of an `Arrow`
| Output -- ^ Points at the right of an `Arrow`
| Body -- ^ Points at the body of a forall
deriving (Eq,Ord,Show)
type Path = [PathElement]
type ViewableType = Type (Symbol View.DFO)
defaultSymbol :: Reference -> Symbol View.DFO
defaultSymbol (Reference.Builtin t) = Symbol.prefix t
defaultSymbol (Reference.Derived h) = Symbol.prefix (Text.cons '#' $ short h)
where
short h = Text.take 8 . Hash.base64 $ h
toString :: ViewableType -> String
toString t = D.formatText (Dimensions.Width 80) (view defaultSymbol t)
view :: (Reference -> Symbol View.DFO) -> ViewableType -> Doc Text Path
view ref t = go no View.low t
where
no = const False
sym v = D.embed (Var.name v)
op :: ViewableType -> Symbol View.DFO
op t = case t of
Lit' (Ref r) -> ref r
Lit' l -> Symbol.annotate View.prefix . (\r -> Symbol.prefix r :: Symbol ()) . Text.pack . show $ l
Universal' v -> v
Existential' v -> v
_ -> Symbol.annotate View.prefix (Symbol.prefix "" :: Symbol ())
go :: (ViewableType -> Bool) -> View.Precedence -> ViewableType -> Doc Text Path
go inChain p t = case t of
ArrowsP' spine ->
let arr = D.breakable " " `D.append` D.embed "→ "
in D.parenthesize (p > View.low) . D.group . D.delimit arr $
[ D.sub' p (go no (View.increase View.low) s) | (s,p) <- spine ]
AppsP' (fn,fnP) args ->
let
Symbol _ name view = op fn
(taken, remaining) = splitAt (View.arity view) args
fmt (child,path) = (\p -> D.sub' path (go (fn ==) p child), path)
applied = fromMaybe unsaturated (View.instantiate view fnP name (map fmt taken))
unsaturated = D.sub' fnP $ go no View.high fn
in
(if inChain fn then id else D.group) $ case remaining of
[] -> applied
args -> D.parenthesize (p > View.high) . D.group . D.docs $
[ applied, D.breakable " "
, D.nest " " . D.group . D.delimit (D.breakable " ") $
[ D.sub' p (go no (View.increase View.high) s) | (s,p) <- args ] ]
ForallsP' vs (body,bodyp) ->
if p == View.low then D.sub' bodyp (go no p body)
else D.parenthesize True . D.group $
D.embed "∀ " `D.append`
D.delimit (D.embed " ") (map (sym . fst) vs) `D.append`
D.docs [D.embed ".", D.breakable " ", D.nest " " $ D.sub' bodyp (go no View.low body)]
Constrain' t _ -> go inChain p t
Ann' t _ -> go inChain p t -- ignoring kind annotations for now
Universal' v -> sym v
Existential' v -> D.embed ("'" `mappend` Var.name v)
Lit' _ -> D.embed (Var.name $ op t)
_ -> error $ "layout match failure"
deriveJSON defaultOptions ''PathElement
instance J.ToJSON1 F where
toJSON1 f = toJSON f
instance J.FromJSON1 F where
parseJSON1 j = parseJSON j
instance Show Literal where
show Number = "Number"
show Text = "Text"
show Vector = "Vector"
show Distance = "Distance"
show (Ref r) = show r
instance Show a => Show (F a) where
showsPrec p fa = go p fa where
go _ (Lit l) = showsPrec 0 l
go p (Arrow i o) =
showParen (p > 0) $ showsPrec (p+1) i <> s" -> " <> showsPrec p o
go p (Ann t k) =
showParen (p > 1) $ showsPrec 0 t <> s":" <> showsPrec 0 k
go p (App f x) =
showParen (p > 9) $ showsPrec 9 f <> s" " <> showsPrec 10 x
go p (Constrain t _) = showsPrec p t
go _ (Universal v) = showsPrec 0 v
go _ (Existential v) = s"'" <> showsPrec 0 v
go p (Forall body) = case p of
0 -> showsPrec p body
_ -> showParen True $ s"∀ " <> showsPrec 0 body
(<>) = (.)
s = showString
| CGenie/platform | shared/src/Unison/Type.hs | mit | 9,416 | 15 | 29 | 2,152 | 3,954 | 2,047 | 1,907 | 224 | 16 |
module Data.Graph.Inductive.Query (module Q) where
import Data.Graph.Inductive.Query.ArtPoint as Q
import Data.Graph.Inductive.Query.BCC as Q
import Data.Graph.Inductive.Query.BFS as Q
import Data.Graph.Inductive.Query.DFS as Q
import Data.Graph.Inductive.Query.Dominators as Q
import Data.Graph.Inductive.Query.GVD as Q
import Data.Graph.Inductive.Query.Indep as Q
import Data.Graph.Inductive.Query.MaxFlow as Q
import Data.Graph.Inductive.Query.MaxFlow2 as Q
import Data.Graph.Inductive.Query.Monad as Q
import Data.Graph.Inductive.Query.MST as Q
import Data.Graph.Inductive.Query.SP as Q
import Data.Graph.Inductive.Query.TransClos as Q
| antalsz/hs-to-coq | examples/graph/graph/Data/Graph/Inductive/Query.hs | mit | 702 | 0 | 4 | 119 | 144 | 114 | 30 | 14 | 0 |
-- {-# LANGUAGE #-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Data.NameM
-- Copyright : (c) Conal Elliott 2009
-- License : AGPLv3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Name supply monad. Non-abstract synonym for @State [String]@
----------------------------------------------------------------------
module Data.NameM (NameM, genName, runNameM, allNames) where
import Control.Monad.State
type NameM = State [String]
-- Generate a new variable name
genName :: State [x] x
genName = do x:xs' <- get
put xs'
return x
runNameM :: NameM a -> a
runNameM m = evalState m allNames
allNames :: [String]
allNames = map reverse (tail names)
where
names = "" : [ c:cs | cs <- names , c <- ['a' .. 'z'] ]
| sseefried/shady-gen | src/Data/NameM.hs | agpl-3.0 | 854 | 0 | 11 | 178 | 182 | 104 | 78 | 13 | 1 |
{-# LANGUAGE StandaloneDeriving #-}
{-# OPTIONS_GHC -Wall -fno-warn-orphans #-}
----------------------------------------------------------------------
-- |
-- Module : Graphics.Shady.Language.Equality
-- Copyright : (c) Conal Elliott 2009
-- License : GPL-3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Forms of equality
----------------------------------------------------------------------
module Graphics.Shady.Language.Equality
-- (SynEq(..),SynEq2(..))
where
{-
import Control.Applicative (Const(..))
infix 4 =-=, =--=
-- | Syntactic equality. Requires same argument type.
class SynEq f where
(=-=) :: HasType c => f c -> f c -> Bool
instance Eq x => SynEq (Const x) where (=-=) = (==)
-- | Higher-order variant of 'SynEq'. Can be defined via '(=-=)', or vice versa.
class SynEq2 f where
(=--=) :: SynEq v => f v c -> f v c -> Bool
deriving instance Eq a => Eq (Const a b)
-}
| conal/shady-gen | src/Shady/Language/Equality.hs | agpl-3.0 | 947 | 0 | 3 | 174 | 23 | 21 | 2 | 3 | 0 |
{-# LANGUAGE DeriveAnyClass #-}
module Haskus.Format.Elf.Segment
( Segment (..)
, SegmentType (..)
, SegmentFlag (..)
, SegmentFlags
, getSegment
, putSegment
-- * Internal
, getSegmentCount
, getSegmentTable
)
where
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Haskus.Format.Binary.Buffer
import Haskus.Format.Binary.Get
import Haskus.Format.Binary.Put
import Haskus.Format.Binary.BitSet as BitSet
import Haskus.Format.Binary.Enum
import Haskus.Format.Binary.Word
import Haskus.Format.Elf.PreHeader
import Haskus.Format.Elf.Header
import Haskus.Format.Elf.Section
data Segment = Segment
{ segmentType :: SegmentType -- ^ Segment type
, segmentFlags :: SegmentFlags -- ^ Segment flags
, segmentOffset :: Word64 -- ^ Segment offset in file
, segmentVirtualAddress :: Word64 -- ^ Segment virtual address
, segmentPhysicalAddress :: Word64 -- ^ Segment physical address
, segmentSizeInFile :: Word64 -- ^ Size of the segment in the file
, segmentSizeInMemory :: Word64 -- ^ Size of the segment in memory
, segmentAlignment :: Word64 -- ^ Segment alignment
}
deriving (Show)
data SegmentType
= SegmentTypeNone -- ^ Program header table entry unused
| SegmentTypeLoad -- ^ Loadable program segment
| SegmentTypeDynamic -- ^ Dynamic linking information
| SegmentTypeInterpreter -- ^ Program interpreter
| SegmentTypeInfo -- ^ Auxiliary information
| SegmentTypeSharedLib -- ^ Reserved
| SegmentTypeSegmentHeader -- ^ Entry for header table itself
| SegmentTypeTLS -- ^ Thread-local storage segment
| SegmentTypeGNU_EH_Frame -- ^ GCC .eh_frame_hdr segment
| SegmentTypeGNU_Stack -- ^ Indicates stack executability
| SegmentTypeGNU_ReadOnlyAfterReloc -- ^ Read-only after relocation
| SegmentTypeSunBSS -- ^ Sun Specific segment
| SegmentTypeSunStack -- ^ Sun stack segment
| SegmentTypeUnknown Word32 -- ^ Unknown segment type
deriving (Show,Eq)
data SegmentFlag
= SegmentFlagExecutable
| SegmentFlagWritable
| SegmentFlagReadable
deriving (Show,Eq,Enum,CBitSet)
type SegmentFlags = BitSet Word32 SegmentFlag
instance CEnum SegmentType where
fromCEnum x = case x of
SegmentTypeNone -> 0
SegmentTypeLoad -> 1
SegmentTypeDynamic -> 2
SegmentTypeInterpreter -> 3
SegmentTypeInfo -> 4
SegmentTypeSharedLib -> 5
SegmentTypeSegmentHeader -> 6
SegmentTypeTLS -> 7
SegmentTypeGNU_EH_Frame -> 0x6474e550
SegmentTypeGNU_Stack -> 0x6474e551
SegmentTypeGNU_ReadOnlyAfterReloc -> 0x6474e552
SegmentTypeSunBSS -> 0x6ffffffa
SegmentTypeSunStack -> 0x6ffffffb
SegmentTypeUnknown w -> fromIntegral w
toCEnum x = case x of
0 -> SegmentTypeNone
1 -> SegmentTypeLoad
2 -> SegmentTypeDynamic
3 -> SegmentTypeInterpreter
4 -> SegmentTypeInfo
5 -> SegmentTypeSharedLib
6 -> SegmentTypeSegmentHeader
7 -> SegmentTypeTLS
0x6474e550 -> SegmentTypeGNU_EH_Frame
0x6474e551 -> SegmentTypeGNU_Stack
0x6474e552 -> SegmentTypeGNU_ReadOnlyAfterReloc
0x6ffffffa -> SegmentTypeSunBSS
0x6ffffffb -> SegmentTypeSunStack
w -> SegmentTypeUnknown (fromIntegral w)
getSegment :: PreHeader -> Get Segment
getSegment hdr = do
let (_,_,gw32,_,gwN) = getGetters hdr
case preHeaderWordSize hdr of
WordSize32 -> do
typ <- toCEnum <$> gw32
off <- gwN
vaddr <- gwN
paddr <- gwN
fsz <- gwN
msz <- gwN
flgs <- BitSet.fromBits <$> gw32
algn <- gwN
return (Segment typ flgs off vaddr paddr fsz msz algn)
WordSize64 -> do
typ <- toCEnum <$> gw32
flgs <- BitSet.fromBits <$> gw32
off <- gwN
vaddr <- gwN
paddr <- gwN
fsz <- gwN
msz <- gwN
algn <- gwN
return (Segment typ flgs off vaddr paddr fsz msz algn)
putSegment :: PreHeader -> Segment -> Put
putSegment hdr s = do
let
(_,_,pw32,_,pwN) = getPutters hdr
typ = fromCEnum . segmentType $ s
flags = BitSet.toBits (segmentFlags s)
case preHeaderWordSize hdr of
WordSize32 -> do
pw32 typ
pwN (segmentOffset s)
pwN (segmentVirtualAddress s)
pwN (segmentPhysicalAddress s)
pwN (segmentSizeInFile s)
pwN (segmentSizeInMemory s)
pw32 flags
pwN (segmentAlignment s)
WordSize64 -> do
pw32 typ
pw32 flags
pwN (segmentOffset s)
pwN (segmentVirtualAddress s)
pwN (segmentPhysicalAddress s)
pwN (segmentSizeInFile s)
pwN (segmentSizeInMemory s)
pwN (segmentAlignment s)
-- | If the number of segment doesn't fit int 16 bits, then
-- 'headerSegmentEntryCount' is set to 0xffff and the field 'sectionInfo' of
-- section 0 contains the effective value.
getSegmentCount :: Buffer -> Header -> PreHeader -> Word64
getSegmentCount bs hdr pre =
if (headerSegmentEntryCount hdr /= 0xffff)
then fromIntegral (headerSegmentEntryCount hdr)
else fromIntegral (sectionInfo sec)
where
-- first section
sec = getFirstSection bs hdr pre
-- | Return the table of segments
getSegmentTable :: Buffer -> Header -> PreHeader -> Vector Segment
getSegmentTable bs h pre =
if cnt == 0
then Vector.empty
else fmap f offs
where
f o = runGetOrFail (getSegment pre) (bufferDrop o bs')
off = fromIntegral $ headerSegmentTableOffset h
bs' = bufferDrop off bs
sz = fromIntegral $ headerSegmentEntrySize h
cnt = fromIntegral $ getSegmentCount bs h pre
offs = Vector.fromList [ 0, sz .. (cnt-1) * sz]
| hsyl20/ViperVM | haskus-system/src/lib/Haskus/Format/Elf/Segment.hs | bsd-3-clause | 6,383 | 0 | 14 | 2,103 | 1,302 | 687 | 615 | 150 | 2 |
------------------------------------------------------------------------
-- |
-- Module : Kask.Data.Tree.Search
-- Copyright : (c) 2014 Konrad Grzanek
-- License : BSD-style (see the file LICENSE)
-- Created : 2014-10-25
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- (Rose) tree search and traversal algorithms
------------------------------------------------------------------------
module Kask.Data.Tree.Search
(
-- * Search abstraction
Adjs
, Goal
, Strategy
-- * Tree traversal mechanisms
, breadthFirstTreeLevels
, breadthFirstTreeList
-- * Tree search
, treeSearch
, breadthFirst
, depthFirst
)
where
import RIO
import RIO.List (iterate)
-- | The type of functions that generate children of a given (rose)
-- tree node.
type Adjs a = a -> [a]
-- | Goal of the tree search process.
type Goal a = a -> Bool
-- | A tree search strategy.
type Strategy a = [a] -- ^ states
-> [a] -- ^ children
-> [a] -- ^ updated states
-- | Returns a list of levels in a tree traversed breadth-first.
breadthFirstTreeLevels :: a -> Adjs a -> [[a]]
breadthFirstTreeLevels state adjs =
takeWhile (not . null) (iterate (concatMap adjs) [state])
-- | Returns a list of tree nodes traversed breadth-first.
breadthFirstTreeList :: a -> Adjs a -> [a]
breadthFirstTreeList state = concat . breadthFirstTreeLevels state
-- | A generic, strategy-agnostic tree search algorithm.
treeSearch :: Strategy a -> Adjs a -> Goal a -> [a] -> Maybe a
treeSearch _ _ _ [] = Nothing
treeSearch strategy adjs goal (x:xs)
| goal x = Just x
| otherwise = treeSearch strategy adjs goal (strategy xs (adjs x))
-- | Breadth-first search strategy.
breadthFirst :: Strategy a
breadthFirst = (++)
-- | Depth-first search strategy.
depthFirst :: Strategy a
depthFirst = flip (++)
| kongra/kask-base | src/Kask/Data/Tree/Search.hs | bsd-3-clause | 1,930 | 0 | 10 | 431 | 368 | 212 | 156 | 31 | 1 |
{-# LANGUAGE CPP, DefaultSignatures, FlexibleContexts #-}
-- |
-- Module: Data.Aeson.Types.Class
-- Copyright: (c) 2011-2015 Bryan O'Sullivan
-- (c) 2011 MailRank, Inc.
-- License: Apache
-- Maintainer: Bryan O'Sullivan <[email protected]>
-- Stability: experimental
-- Portability: portable
--
-- Types for working with JSON data.
module Data.Aeson.Types.Class
(
-- * Core JSON classes
FromJSON(..)
, ToJSON(..)
-- * Generic JSON classes
, GFromJSON(..)
, GToJSON(..)
, genericToJSON
, genericToEncoding
, genericParseJSON
-- * Object key-value pairs
, KeyValue(..)
-- * Functions needed for documentation
, typeMismatch
) where
import Data.Aeson.Types.Internal
import Data.Text (Text)
import GHC.Generics (Generic, Rep, from, to)
import qualified Data.Aeson.Encode.Builder as E
-- | Class of generic representation types ('Rep') that can be converted to
-- JSON.
class GToJSON f where
-- | This method (applied to 'defaultOptions') is used as the
-- default generic implementation of 'toJSON'.
gToJSON :: Options -> f a -> Value
-- | This method (applied to 'defaultOptions') can be used as the
-- default generic implementation of 'toEncoding'.
gToEncoding :: Options -> f a -> Encoding
-- | Class of generic representation types ('Rep') that can be converted from JSON.
class GFromJSON f where
-- | This method (applied to 'defaultOptions') is used as the
-- default generic implementation of 'parseJSON'.
gParseJSON :: Options -> Value -> Parser (f a)
-- | A configurable generic JSON creator. This function applied to
-- 'defaultOptions' is used as the default for 'toJSON' when the type
-- is an instance of 'Generic'.
genericToJSON :: (Generic a, GToJSON (Rep a)) => Options -> a -> Value
genericToJSON opts = gToJSON opts . from
-- | A configurable generic JSON encoder. This function applied to
-- 'defaultOptions' is used as the default for 'toEncoding' when the type
-- is an instance of 'Generic'.
genericToEncoding :: (Generic a, GToJSON (Rep a)) => Options -> a -> Encoding
genericToEncoding opts = gToEncoding opts . from
-- | A configurable generic JSON decoder. This function applied to
-- 'defaultOptions' is used as the default for 'parseJSON' when the
-- type is an instance of 'Generic'.
genericParseJSON :: (Generic a, GFromJSON (Rep a)) => Options -> Value -> Parser a
genericParseJSON opts = fmap to . gParseJSON opts
-- | A type that can be converted to JSON.
--
-- An example type and instance:
--
-- @
-- \-- Allow ourselves to write 'Text' literals.
-- {-\# LANGUAGE OverloadedStrings #-}
--
-- data Coord = Coord { x :: Double, y :: Double }
--
-- instance ToJSON Coord where
-- toJSON (Coord x y) = 'object' [\"x\" '.=' x, \"y\" '.=' y]
--
-- toEncoding (Coord x y) = 'pairs' (\"x\" '.=' x '<>' \"y\" '.=' y)
-- @
--
-- Instead of manually writing your 'ToJSON' instance, there are two options
-- to do it automatically:
--
-- * "Data.Aeson.TH" provides Template Haskell functions which will derive an
-- instance at compile time. The generated instance is optimized for your type
-- so will probably be more efficient than the following two options:
--
-- * The compiler can provide a default generic implementation for
-- 'toJSON'.
--
-- To use the second, simply add a @deriving 'Generic'@ clause to your
-- datatype and declare a 'ToJSON' instance for your datatype without giving
-- definitions for 'toJSON' or 'toEncoding'.
--
-- For example, the previous example can be simplified to a more
-- minimal instance:
--
-- @
-- {-\# LANGUAGE DeriveGeneric \#-}
--
-- import "GHC.Generics"
--
-- data Coord = Coord { x :: Double, y :: Double } deriving 'Generic'
--
-- instance ToJSON Coord where
-- toEncoding = 'genericToEncoding' 'defaultOptions'
-- @
--
-- Why do we provide an implementation for 'toEncoding' here? The
-- 'toEncoding' function is a relatively new addition to this class.
-- To allow users of older versions of this library to upgrade without
-- having to edit all of their instances or encounter surprising
-- incompatibilities, the default implementation of 'toEncoding' uses
-- 'toJSON'. This produces correct results, but since it performs an
-- intermediate conversion to a 'Value', it will be less efficient
-- than directly emitting an 'Encoding'. Our one-liner definition of
-- 'toEncoding' above bypasses the intermediate 'Value'.
--
-- If @DefaultSignatures@ doesn't give exactly the results you want,
-- you can customize the generic encoding with only a tiny amount of
-- effort, using 'genericToJSON' and 'genericToEncoding' with your
-- preferred 'Options':
--
-- @
-- instance ToJSON Coord where
-- toJSON = 'genericToJSON' 'defaultOptions'
-- toEncoding = 'genericToEncoding' 'defaultOptions'
-- @
class ToJSON a where
-- | Convert a Haskell value to a JSON-friendly intermediate type.
toJSON :: a -> Value
default toJSON :: (Generic a, GToJSON (Rep a)) => a -> Value
toJSON = genericToJSON defaultOptions
-- | Encode a Haskell value as JSON.
--
-- The default implementation of this method creates an
-- intermediate 'Value' using 'toJSON'. This provides
-- source-level compatibility for people upgrading from older
-- versions of this library, but obviously offers no performance
-- advantage.
--
-- To benefit from direct encoding, you /must/ provide an
-- implementation for this method. The easiest way to do so is by
-- having your types implement 'Generic' using the @DeriveGeneric@
-- extension, and then have GHC generate a method body as follows.
--
-- @
-- instance ToJSON Coord where
-- toEncoding = 'genericToEncoding' 'defaultOptions'
-- @
toEncoding :: a -> Encoding
toEncoding = Encoding . E.encodeToBuilder . toJSON
{-# INLINE toEncoding #-}
-- | A type that can be converted from JSON, with the possibility of
-- failure.
--
-- In many cases, you can get the compiler to generate parsing code
-- for you (see below). To begin, let's cover writing an instance by
-- hand.
--
-- There are various reasons a conversion could fail. For example, an
-- 'Object' could be missing a required key, an 'Array' could be of
-- the wrong size, or a value could be of an incompatible type.
--
-- The basic ways to signal a failed conversion are as follows:
--
-- * 'empty' and 'mzero' work, but are terse and uninformative
--
-- * 'fail' yields a custom error message
--
-- * 'typeMismatch' produces an informative message for cases when the
-- value encountered is not of the expected type
--
-- An example type and instance:
--
-- @
-- \-- Allow ourselves to write 'Text' literals.
-- {-\# LANGUAGE OverloadedStrings #-}
--
-- data Coord = Coord { x :: Double, y :: Double }
--
-- instance FromJSON Coord where
-- parseJSON ('Object' v) = Coord '<$>'
-- v '.:' \"x\" '<*>'
-- v '.:' \"y\"
--
-- \-- We do not expect a non-'Object' value here.
-- \-- We could use 'mzero' to fail, but 'typeMismatch'
-- \-- gives a much more informative error message.
-- parseJSON invalid = 'typeMismatch' \"Coord\" invalid
-- @
--
-- Instead of manually writing your 'FromJSON' instance, there are two options
-- to do it automatically:
--
-- * "Data.Aeson.TH" provides Template Haskell functions which will derive an
-- instance at compile time. The generated instance is optimized for your type
-- so will probably be more efficient than the following two options:
--
-- * The compiler can provide a default generic implementation for
-- 'parseJSON'.
--
-- To use the second, simply add a @deriving 'Generic'@ clause to your
-- datatype and declare a 'FromJSON' instance for your datatype without giving
-- a definition for 'parseJSON'.
--
-- For example, the previous example can be simplified to just:
--
-- @
-- {-\# LANGUAGE DeriveGeneric \#-}
--
-- import "GHC.Generics"
--
-- data Coord = Coord { x :: Double, y :: Double } deriving 'Generic'
--
-- instance FromJSON Coord
-- @
--
-- If @DefaultSignatures@ doesn't give exactly the results you want,
-- you can customize the generic decoding with only a tiny amount of
-- effort, using 'genericParseJSON' with your preferred 'Options':
--
-- @
-- instance FromJSON Coord where
-- parseJSON = 'genericParseJSON' 'defaultOptions'
-- @
class FromJSON a where
parseJSON :: Value -> Parser a
default parseJSON :: (Generic a, GFromJSON (Rep a)) => Value -> Parser a
parseJSON = genericParseJSON defaultOptions
-- | A key-value pair for encoding a JSON object.
class KeyValue kv where
(.=) :: ToJSON v => Text -> v -> kv
infixr 8 .=
-- | Fail parsing due to a type mismatch, with a descriptive message.
--
-- Example usage:
--
-- @
-- instance FromJSON Coord where
-- parseJSON ('Object' v) = {- type matches, life is good -}
-- parseJSON wat = 'typeMismatch' \"Coord\" wat
-- @
typeMismatch :: String -- ^ The name of the type you are trying to parse.
-> Value -- ^ The actual value encountered.
-> Parser a
typeMismatch expected actual =
fail $ "expected " ++ expected ++ ", encountered " ++ name
where
name = case actual of
Object _ -> "Object"
Array _ -> "Array"
String _ -> "String"
Number _ -> "Number"
Bool _ -> "Boolean"
Null -> "Null"
| neobrain/aeson | Data/Aeson/Types/Class.hs | bsd-3-clause | 9,453 | 0 | 11 | 2,012 | 815 | 528 | 287 | 53 | 6 |
{-# LANGUAGE TemplateHaskell, TypeOperators, GADTs, KindSignatures #-}
{-# LANGUAGE ViewPatterns, PatternGuards, LambdaCase #-}
{-# LANGUAGE FlexibleContexts, ConstraintKinds #-}
{-# LANGUAGE MagicHash, MultiWayIf, CPP #-}
{-# LANGUAGE Rank2Types #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
{-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : LambdaCCC.SReify
-- Copyright : (c) 2013 Tabula, Inc.
-- LICENSE : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Reify a Core expression into GADT
----------------------------------------------------------------------
#define OnlyLifted
module LambdaCCC.SReify (plugin) where
import Data.Functor ((<$>))
import Control.Applicative (Applicative(..))
import Data.Foldable (msum)
import Control.Monad ((<=<),unless)
import Control.Arrow (Arrow(..),(>>>),(<<<))
import Data.List (isPrefixOf,find)
import Data.Maybe (fromMaybe)
-- GHC
import PrelNames (eitherTyConName)
import HERMIT.Monad (newIdH)
import HERMIT.Core (localFreeIdsExpr,CoreProg(..),bindsToProg,progToBinds)
import HERMIT.External (External,external)
import HERMIT.GHC hiding (mkStringExpr)
import HERMIT.Kure -- hiding (apply)
-- Note that HERMIT.Dictionary re-exports HERMIT.Dictionary.*
import HERMIT.Dictionary
hiding (findTyConT, externals) -- Use our own findTyConT FOR NOW
import HERMIT.Plugin (hermitPlugin,phase,interactive)
import LambdaCCC.Misc ((<~))
import HERMIT.Extras hiding (observeR', triesL, labeled)
import qualified HERMIT.Extras as Ex
-- Drop TypeEncode for now.
-- import TypeEncode.Plugin (encodeOf, reConstructR, reCaseR)
-- import qualified TypeEncode.Plugin as Enc
{--------------------------------------------------------------------
Observing
--------------------------------------------------------------------}
-- (Observing, observeR', triesL, labeled)
observing :: Ex.Observing
observing = True
-- observeR' :: InCoreTC t => String -> RewriteC t
-- observeR' = Ex.observeR' observing
-- triesL :: InCoreTC t => [(String,RewriteC t)] -> RewriteC t
-- triesL = Ex.triesL observing
labelR :: InCoreTC t => String -> RewriteH t -> RewriteH t
labelR = curry (Ex.labeled observing)
-- TODO: stop uncurrying Ex.labeled
{--------------------------------------------------------------------
Standard types
--------------------------------------------------------------------}
-- TODO: Parametrize the rest of the module by 'standardTyT'.
-- TODO: Consider how to eliminate Encode as well. Then simplify to
-- standardTy :: Type -> Bool
-- A "standard type" is built up from `Unit`, `Bool`, `Int` (for now), pairs (of
-- standard types), sums, and functions, or Encode
standardTyT :: Type -> TransformU ()
-- standardTyT _ | trace "standardTyT" False = undefined
standardTyT (tcView -> Just ty) = standardTyT ty
standardTyT (TyConApp tc args) | standardTC tc
= mapM_ standardTyT args
#if 1
standardTyT ty@(TyConApp tc _) =
-- Treat Encode applications as standard.
do encodeTC <- findTyConT "LambdaCCC.Encode.Encode"
if tc == encodeTC then successT else nonStandardFail ty
#endif
standardTyT (FunTy arg res) =
standardTyT arg >> standardTyT res
standardTyT ty = nonStandardFail ty
nonStandardFail :: Type -> TransformU a
nonStandardFail ty =
do s <- showPprT <<< return ty
fail ("non-standard type:\n" ++ s)
standardTC :: TyCon -> Bool
standardTC tc =
(tc `elem` [unitTyCon, boolTyCon, intTyCon])
|| isPairTC tc
|| tyConName tc == eitherTyConName -- no eitherTyCon
-- TODO: Maybe I just want a standard outer shell.
-- TODO: Maybe use coreView instead of tcView? I think it's tcView we want,
-- since it just looks through type synonyms and not newtypes.
-- TODO: If I remove Encode, standardTy can be Type -> Bool
standardET :: FilterE
standardET = standardTyT =<< arr exprType
{--------------------------------------------------------------------
Reification
--------------------------------------------------------------------}
lamName :: Unop String
lamName = ("LambdaCCC.Lambda." ++)
findTyConE :: String -> TransformH a TyCon
findTyConE = findTyConT . lamName
appsE :: String -> [Type] -> [CoreExpr] -> TransformU CoreExpr
appsE = apps' . lamName
-- -- | Uncall a named function
-- unCallE :: String -> TransformH CoreExpr [CoreExpr]
-- unCallE = unCall . lamName
-- | Uncall a named function
unCallE1 :: String -> ReExpr
unCallE1 = unCall1 . lamName
-- A handy form for composition via <=<
appsE1 :: String -> [Type] -> CoreExpr -> TransformU CoreExpr
appsE1 str ts e = appsE str ts [e]
-- callNameLam :: String -> TransformH CoreExpr (CoreExpr, [CoreExpr])
-- callNameLam = callNameT . lamName
-- Some names
evalS, reifyS :: String
evalS = "evalEP"
reifyS = "reifyEP"
varPS, varPatS :: String
varPS = "varP#"
varPatS = "varPat#"
epS :: String
epS = "EP"
-- t ==> EP t
mkEP :: TransformH a Type
mkEP = do epTC <- findTyConE epS
return (TyConApp epTC [])
-- t ==> EP t
epOf :: Type -> TransformH a Type
epOf t = flip mkAppTy t <$> mkEP
-- epOf t = do epTC <- findTyConE epS
-- return (TyConApp epTC [t])
-- reify u ==> u
unReify :: ReExpr
unReify = unCallE1 reifyS
-- eval e ==> e
unEval :: ReExpr
unEval = unCallE1 evalS
-- reify (eval e) ==> e
reifyEval :: ReExpr
reifyEval = unReify >>> unEval
reifyOf :: CoreExpr -> TransformU CoreExpr
reifyOf e = standardTyT (exprType e) >>
appsE reifyS [exprType e] [e]
where
ty = exprType e
ki = typeKind ty
evalOf :: CoreExpr -> TransformU CoreExpr
evalOf e = appsE evalS [dropEP (exprType e)] [e]
isEP :: Type -> Bool
isEP (TyConApp (tyConName -> name) [_]) = uqName name == epS
isEP _ = False
dropEP :: Unop Type
dropEP (TyConApp (uqName . tyConName -> name) [t]) =
if name == epS then t
else error ("dropEP: not an EP: " ++ show name)
dropEP _ = error "dropEP: not a TyConApp"
reifyR :: ReExpr
reifyR = idR >>= reifyOf
evalR :: ReExpr
evalR = idR >>= evalOf
isAppT :: FilterE
isAppT = appT successT successT (const id)
{--------------------------------------------------------------------
Reification rewrites
--------------------------------------------------------------------}
-- reifyApp :: ReExpr
-- reifyApp =
-- -- inReify (labelR "castFloatAppR" castFloatAppR) <+
-- reifyAppSimple
-- -- Do separately, to handle non-apps
-- -- <+ inReify (isAppT >> labelR "unfoldR" unfoldR)
-- reify (u v) ==> reify u `appP` reify v .
-- Fails if v (and hence u) has a nonstandard type.
reifyApp :: ReExpr
reifyApp = labelR "reifyApp" $
do App u v <- unReify
Just (a,b) <- constT (return (splitFunTy_maybe (exprType u)))
u' <- reifyOf u
v' <- reifyOf v
appsE "appP" [b,a] [u', v'] -- note b,a
-- I've forgotten my motivation for reifyRulesPrefix. Omit for now.
#if 0
-- Apply a rule to a left application prefix
reifyRulesPrefix :: ReExpr
reifyRulesPrefix = labelR "reifyRulesPrefix" $
reifyRules <+ (reifyApp >>> appArgs reifyRulesPrefix idR)
-- Like appAllR, but on a reified app.
-- 'app ta tb f x ==> 'app ta tb (rf f) (rx s)'
appArgs :: Binop ReExpr
appArgs rf rx = appAllR (appAllR idR rf) rx
#endif
-- TODO: Use arr instead of (constT (return ...))
-- TODO: refactor so we unReify once and then try variations
varSubst :: [Var] -> TransformU (Unop CoreExpr)
varSubst vs = do vs' <- mapM varEval vs
return (subst (vs `zip` vs'))
where
varEval :: Var -> TransformU CoreExpr
varEval v = (evalOf <=< appsE1 varPS [varType v]) (varLitE v)
-- | reify (\ x -> e) ==> lamv x' (reify (e[x := eval (var x')]))
reifyLam :: ReExpr
reifyLam = labelR "reifyLam" $
do Lam v e <- unReify
guardMsg (not (isTyVar v)) "reifyLam: doesn't handle type lambda"
sub <- varSubst [v]
e' <- reifyOf (sub e)
appsE "lamvP#" [varType v, exprType e] [varLitE v,e']
reifyPolyLet :: ReExpr
reifyPolyLet = labelR "reifyPolyLet" $
unReify >>>
do Let (NonRec (isForAllTy . varType -> True) _) _ <- idR
letAllR reifyDef reifyR >>> letFloatLetR
-- reifyDef introduces foo_reified binding, which the letFloatLetR then moves up
-- one level. Typically (always?) the "foo = eval foo_reified" definition gets
-- inlined and then eliminated by the letElimR in reifyMisc.
-- | Turn a monomorphic let into a beta-redex.
reifyMonoLet :: ReExpr
reifyMonoLet = labelR "reifyMonoLet" $
unReify >>>
do Let (NonRec v@(isForAllTy . varType -> False) rhs) body <- idR
guardMsgM (worthLet rhs) "trivial let"
rhsE <- reifyOf rhs
sub <- varSubst [v]
bodyE <- reifyOf (sub body)
appsE "letvP#" [varType v, exprType body] [varLitE v, rhsE,bodyE]
-- Placeholder
worthLet :: CoreExpr -> TransformU Bool
worthLet _ = return True
-- Simpler but can lead to loops. Maybe fix by following with reifyLam.
--
-- reifyMonoLet =
-- inReify $
-- do Let (NonRec v@(isForAllTy . varType -> False) rhs) body <- idR
-- return (Lam v body `App` rhs)
reifyLetSubst :: ReExpr
reifyLetSubst = labelR "reifyLetSubst" $
inReify letSubstR
-- TODO: Perhaps combine reifyPolyLet and reifyMonoLet into reifyLet
#define SplitEval
#ifdef SplitEval
-- (\ vs -> e) ==> (\ vs -> eval (reify e)) in preparation for rewriting reify e.
-- For vs, take all leading type variables.
-- Fail if e is already an eval or if it has IO or EP type.
reifyRhs :: String -> ReExpr
reifyRhs nm = labelR ("reifyRhs " ++ nm) $
standardET >>
( typeEtaLong >>>
do (tvs,body) <- collectTyBinders <$> idR
eTy <- epOf (exprType body)
v <- constT $ newIdH (nm ++ "_reified") (mkForAllTys tvs eTy)
reified <- mkLams tvs <$> reifyOf body
evald <- evalOf (mkCoreApps (Var v) ((Type . TyVarTy) <$> tvs))
return $
Let (NonRec v reified) (mkLams tvs evald) )
reifyDef :: RewriteH CoreBind
reifyDef = do NonRec v _ <- idR
nonRecAllR idR (reifyRhs (uqVarName v))
reifyProg :: RewriteH CoreProg
reifyProg = progBindsT (const (tryR reifyDef >>> letFloatToProg)) concatProgs
#else
-- Apply a rewriter inside type lambdas, type-eta-expanding if necessary.
inTyLams :: Unop ReExpr
inTyLams r = r'
where
r' = readerT $ \ e ->
if | isTyLam e -> lamAllR idR r'
| isForAllTy (exprType e) -> etaExpandR "eta" >>> r'
| otherwise -> r
-- e ==> eval (reify e) in preparation for rewriting reify e.
-- Fail if e is already an eval or if it has IO or EP type.
-- If there are any type lambdas, skip over them.
reifyRhs :: ReExpr
reifyRhs = labelR "reifyRhs" $
inTyLams $
unlessDict >>> unlessEval >>> unlessTC "IO" >>> unlessTC epS >>>
reifyR >>> evalR
reifyDef :: RewriteH CoreBind
reifyDef = nonRecAllR idR reifyRhs
reifyProg :: RewriteH CoreProg
reifyProg = progBindsAnyR (const reifyDef)
#endif
reifyModGuts :: RewriteH ModGuts
reifyModGuts = modGutsR reifyProg
-- Rewrite inside of reify applications
inReify :: Unop ReExpr
inReify = reifyR <~ unReify
-- TODO: drop the non-E test, since we're already under a reify.
isWrapper :: Var -> Bool
isWrapper = ("$W" `isPrefixOf`) . uqVarName -- TODO: alternative?
reifyUnfold :: ReExpr
#if 1
reifyUnfold = labelR "reifyUnfold" $
inReify unfoldR
#else
reifyUnfold = labelR "reifyUnfold" $
inReify unfoldSimplify
unfoldSimplify :: ReExpr
unfoldSimplify = unfoldPredR (const . not . bad) >>> tryR simplifyE
where
bad v = isWrapper v -- || dictRelated (varType v)
#endif
#if 0
-- Now handled by reifyRs
castFloatAppsR :: ReExpr
castFloatAppsR = labelR "castFloatAppsR" $
go
where
go = castFloatAppR <+ (appAllR go idR >>> castFloatAppR)
#endif
-- reifyEncode :: ReExpr
-- reifyEncode = inReify encodeTypesR
reifyRuleNames :: [String]
reifyRuleNames = map ("reify/" ++)
[ "not","(&&)","(||)","xor","(+)","(*)","exl","exr","pair","inl","inr"
, "if","()","false","true"
, "toVecZ","unVecZ","toVecS","unVecS"
, "ZVec","(:<)","(:#)","L","B","unPair","unLeaf","unBranch"
, "square"
]
-- ,"if-bool","if-pair"
-- or: words "not (&&) (||) xor ..."
-- TODO: Is there a way not to redundantly specify this rule list?
-- Yes -- trust GHC to apply the rules later.
-- Keep for now, to help us see that whether reify applications vanish.
reifyRules :: ReExpr
reifyRules = labelR "reifyRules" $
rulesR reifyRuleNames >>> cleanupUnfoldR
-- reify (I# n) ==> intL (I# n)
reifyIntLit :: ReExpr
reifyIntLit = labelR "reifyIntLit" $
unReify >>> do _ <- callNameT "I#"
e <- idR
appsE "intL" [] [e]
reifySimplifiable :: ReExpr
reifySimplifiable = labelR "reifySimplifiable" $
inReify simplifyE' -- (extractR bashR)
where
simplifyE' = repeatR $
simplifyE <+ anybuE (caseFloatAppR <+ caseFloatCaseR)
-- Sadly, don't use bashR. It gives false positives (succeeding without change),
-- *and* it leads to lint errors and even to non-terminating exprType (or
-- close).
#ifndef OnlyLifted
reifyDecodeF :: ReExpr
reifyDecodeF = labelR "reifyDecodeF" $
unReify >>>
do -- (_,[Type a,Type b]) <- callNameT "TypeDecode.Encode.decodeF"
(Var f,[Type a,Type b]) <- callT
guardMsg (uqVarName f == "decodeF") "oops -- not decodeF"
apps' "Circat.Prim.DecodeP" [a,b] [] >>= appsE1 "kPrimEP" [FunTy a b]
reifyEncodeF :: ReExpr
reifyEncodeF = labelR "reifyEncodeF" $
unReify >>>
do -- (_,[Type a,Type b]) <- callNameT "TypeDecode.Encode.encodeF"
(Var f,[Type a,Type b]) <- callT
guardMsg (uqVarName f == "encodeF") "oops -- not encodeF"
apps' "Circat.Prim.EncodeP" [a,b] [] >>= appsE1 "kPrimEP" [FunTy a b]
reifyCodeF :: ReExpr
reifyCodeF = reifyEncodeF <+ reifyDecodeF
-- TODO: refactor
#endif
reifyCast :: ReExpr
-- reifyCast = labelR "reifyCast" $
-- unReify >>>
-- do e'@(Cast e co) <- idR
-- re <- reifyOf e
-- appsE "castEP" [exprType e,exprType e'] [Coercion co,re]
reifyCast = labelR "reifyCast" $
unReify >>>
do e'@(Cast e co) <- idR
case setNominalRole_maybe co of
Nothing -> fail "Couldn't setNominalRole"
Just coN ->
do re <- reifyOf e
appsE "castEP" [exprType e,exprType e'] [mkEqBox coN,re]
-- -- Cheat via UnivCo:
-- reifyCast = labelR "reifyCast" $
-- unReify >>>
-- do e'@(Cast e _) <- idR
-- let ty = exprType e
-- ty' = exprType e'
-- re <- reifyOf e
-- appsE "castEP" [ty,ty'] [mkEqBox (mkUnivCo Nominal ty ty'),re]
-- reifyCast = labelR "reifyCast" $
-- (unReify &&& arr exprType) >>>
-- do (Cast e _, ty) <- idR
-- re <- reifyOf e
-- apps' "Unsafe.Coerce.unsafeCoerce" [exprType re,ty] [re]
-- -- Equivalent but a bit prettier:
-- reifyCast = labelR "reifyCast" $
-- unReify >>>
-- do e'@(Cast e _) <- idR
-- re <- reifyOf e
-- appsE "castEP'" [exprType e,exprType e'] [re]
reifyCast' :: ReExpr
reifyCast' = inReify (catchesM castRs) <+ reifyCast
where
castRs =
[ labelR "castElimReflR" castElimReflR
, labelR "castElimSymR" castElimSymR
, labelR "castCastR" castCastR
, labelR "lamFloatCastR" lamFloatCastR
]
#if 0
-- Given reifyEP (m d), if m is a variable and d is a dictionary,
-- then anytdR inline >>> simplify.
reifyMethod :: ReExpr
reifyMethod = labelR "reifyMethod" $
inReify inlineMethod
inlineMethod :: ReExpr
inlineMethod = labelR "inlineMethod" $
do (Var _, _,[d]) <- callSplitT
guardMsg (isDictTy (exprType d)) "non-dictionary"
anytdE inlineR >>> simplifyE
-- TODO: Replace reifyMethod by inlineDict below.
dictRelated :: Type -> Bool
dictRelated ty = any isDictTy (ran:doms)
where
(doms,ran) = splitFunTys (dropForAlls ty)
-- | Inline dictionary maker or consumer
inlineDict :: ReExpr
inlineDict = labelR "inlineDict" $
inlineMatchingPredR (dictRelated . varType)
inlineWrapper :: ReExpr
inlineWrapper = labelR "inlineWrapper" $
inlineMatchingPredR isWrapper
#endif
-- Note: Given reify (m d a .. z), reifyApp whittles down to reify (m d).
-- TODO: Fix reifyMethod to work even when type arguments come after the
-- dictionary. I didn't think it could happen, but it does with fmap on
-- size-typed vectors. I think I want inlining *only* for the method and
-- dictionary, unlike what I'm doing above.
--
-- Idea: inline any variable whose type consumes or produces a dictionary.
-- reify of case on 0-tuple or 2-tuple
reifyTupCase :: ReExpr
reifyTupCase = labelR "reifyTupCase" $
do Case scrut@(exprType -> scrutT) wild bodyT [alt] <- unReify
(patE,rhs) <- reifyAlt wild alt
scrut' <- reifyOf scrut
appsE "lettP" [scrutT,bodyT] [patE,scrut',rhs]
where
-- Reify a case alternative, yielding a reified pattern and a reified
-- alternative body (RHS). Only unit and pair patterns. Others are
-- transformed away in the type-encode plugin.
reifyAlt :: Var -> CoreAlt -> TransformU (CoreExpr,CoreExpr)
reifyAlt wild (DataAlt ( isTupleTyCon . dataConTyCon -> True)
, vars, rhs ) =
do guardMsg (length vars `elem` [0,2])
"Only handles unit and pair patterns"
vPats <- mapM varPatT vars
sub <- varSubst (wild : vars)
pat <- if null vars then
appsE "UnitPat" [] []
else
appsE ":$" (varType <$> vars) vPats
pat' <- if wild `elemVarSet` localFreeIdsExpr rhs
then -- WARNING: untested as of 2014-03-11
appsE "asPat#" [varType wild] [varLitE wild,pat]
else
return pat
rhs' <- reifyOf (sub rhs)
return (pat', rhs')
where
varPatT :: Var -> TransformU CoreExpr
varPatT v = appsE varPatS [varType v] [varLitE v]
reifyAlt _ _ = fail "reifyAlt: Only handles pair patterns so far."
reifyUnfoldScrut :: ReExpr
reifyUnfoldScrut = labelR "reifyUnfoldScrut" $
inReify $
caseAllR unfoldR idR idR (const idR)
reifyEither :: ReExpr
#if 1
reifyEither = labelR "reifyEither" $
unReify >>>
do (_either, tys, funs@[_,_]) <- callNameSplitT "either"
funs' <- mapM reifyOf funs
appsE "eitherEP" tys funs'
-- Since 'either f g' has a function type, there could be more parameters.
-- I only want two. The others will get removed by reifyApp.
-- Important: reifyEither must come before reifyApp in reifyMisc, so that we can
-- see 'either' applied.
#else
eitherTy :: Type -> Type -> TransformU Type
eitherTy a b = do tc <- findTyConT "Either"
return (TyConApp tc [a,b])
unEitherTy :: Type -> TransformU (Type,Type)
unEitherTy (TyConApp tc [a,b]) =
do etc <- findTyConT "Either"
guardMsg (tyConName tc == tyConName etc)
"unEitherTy: not an Either"
return (a,b)
unEitherTy _ = fail "unEitherTy: wrong shape"
-- reify (case scrut of { Left lv -> le ; Right rv -> re }) ==>
-- appE (eitherE (reify (\ lv -> le)) (reify (\ rv -> re))) (reify scrut)
-- Now removed in the type-encode plugin
reifyEither = labelR "reifyEither" $
do Case scrut wild bodyT alts@[_,_] <- unReify
(lt,rt) <- unEitherTy (exprType scrut)
[le,re] <- mapM (reifyBranch wild) alts
e <- appsE "eitherEP" [lt,rt,bodyT] [le,re]
t <- eitherTy lt rt
scrut' <- reifyOf scrut
appsE "appP" [bodyT,t] [e,scrut']
where
reifyBranch :: Var -> CoreAlt -> TransformU CoreExpr
reifyBranch _wild (DataAlt _, [var], rhs) = reifyOf (Lam var rhs)
reifyBranch _ _ = error "reifyEither: bad branch"
-- TODO: check for wild in rhs. In that case, I guess I'll have to reify the Lam
-- manually in order to get the as pattern. Hm.
#endif
reifyCase :: ReExpr
reifyCase = inReify (labelR "caseReduceR" (caseReduceR True))
<+ reifyCaseWild
<+ reifyEither
<+ reifyTupCase
<+ onScrut unfoldR -- and simplify?
-- | reify (case scrut of wild t { _ -> body })
-- ==> reify (let wild = scrut in body)
-- May be followed by let-elimination.
-- Note: does not capture GHC's intent to reduce scrut to WHNF.
reifyCaseWild :: ReExpr
reifyCaseWild = labelR "reifyCaseWild" $
inReify $
do Case scrut wild _bodyTy [(DEFAULT,[],body)] <- idR
return $ Let (NonRec wild scrut) body
-- reifyConstruct :: ReExpr
-- reifyConstruct = inReify reConstructR
-- reifyCase :: ReExpr
-- reifyCase = inReify reCaseR
data NatTy = VZero | VSucc Type
sizedTy :: Type -> TransformU (TyCon, NatTy,Type)
sizedTy (TyConApp tc [len0,elemTy]) =
do z <- findTyConT "TypeUnary.TyNat.Z"
s <- findTyConT "TypeUnary.TyNat.S"
return $
( tc
, case fromMaybe len0 (tcView len0) of
TyConApp ((== z) -> True) [] -> VZero
TyConApp ((== s) -> True) [n] -> VSucc n
_ -> error "sizedTy: Vec not Z or S n. Investigate."
, elemTy )
sizedTy _ = fail "sizedTy: wrong # args"
-- Find a structural identity function on a unary-sized type, given the names of
-- the type and construction functions for zero and succ size.
sizedId :: (String,String,String) -> Type -> TransformU CoreExpr
sizedId (tcn,z,s) ty =
do (tc,size,a) <- sizedTy ty
tcv <- findTyConT tcn
guardMsg (tc == tcv) ("Not a " ++ tcn)
case size of
VZero -> appsE z [ a] []
VSucc n -> appsE s [n,a] []
-- Find a structural identity function on vectors
vecId :: Type -> TransformU CoreExpr
vecId = sizedId ("TypeUnary.Vec.Vec","idVecZ","idVecS")
-- Find a structural identity function on trees
treeId :: Type -> TransformU CoreExpr
treeId = sizedId ("Circat.RTree.Tree","idTreeZ","idTreeS")
pairId :: Type -> TransformU CoreExpr
pairId (TyConApp tc [a]) = do tcv <- findTyConT "Circat.Pair.Pair"
guardMsg (tc == tcv) ("Not a Pair")
appsE "idPair" [a] []
pairId _ = fail "pairId: wrong # args"
onScrut :: Unop ReExpr
onScrut r = caseAllR r idR idR (const idR)
onRhs :: ReExpr -> ReExpr
onRhs r = caseAllR idR idR idR (const (altAllR idR (const idR) r))
-- | reify a case of a known-size structure
reifyCaseSized :: ReExpr
reifyCaseSized = labelR "reifyCaseSized" $
inReify $
onScrut (do ty <- exprType <$> idR
idF <- (vecId ty <+ treeId ty <+ pairId ty)
arr (App idF) >>> unfoldR )
>>> tryR (caseFloatCaseR >>> onRhs (caseReduceUnfoldR True))
-- Temporary workaround. Remove when I get the reifyEP/(:<) rule working on
-- unwrapped (:<).
reifyVecS :: ReExpr
reifyVecS = labelR "reifyVecS" $
unReify >>>
do (Var f,[_sn,Type a,Type n,_co]) <- callT
guardMsg (uqVarName f == ":<") "Not a (:<)"
appsE "vecSEP" [n,a] []
-- reifyVecS = labelR "reifyVecS" $
-- unReify >>> unCallE ":<" >>>
-- do [_sn,Type a,Type n,_co] <- idR
-- appsE "vecSEP" [n,a] []
--
-- "callNameT failed: not a call to 'LambdaCCC.Lambda.:<."
-- Why? Wrappers.
reifyLeaf :: ReExpr
reifyLeaf = labelR "reifyLeaf" $
unReify >>>
do (Var f,[_sn,Type a,_co]) <- callT
guardMsg (uqVarName f == "L") "Not an L"
appsE "treeZEP" [a] []
reifyBranch :: ReExpr
reifyBranch = labelR "reifyBranch" $
unReify >>>
do (Var f,[_sn,Type a,Type n,_co]) <- callT
guardMsg (uqVarName f == "B") "Not a B"
appsE "treeSEP" [n,a] []
-- TODO: refactor or eliminate
reifyMisc :: ReExpr
reifyMisc = catchesM reifyRs
reifyRs :: [ReExpr]
reifyRs =
[ -- reifyRulesPrefix -- subsumes reifyRules
reifyRules -- before App
, reifyEval -- ''
, reifyEither -- ''
-- , reifyConstruct -- ''
-- , reifyMethod -- ''
, reifyApp
, reifyCast'
, reifyCase
, reifyLam
, reifyIntLit
#if 0
-- , inlineMethod
, labelR "inReify etaReduceR" (inReify etaReduceR)
, reifyMonoLet
, reifyLetSubst
, reifyPolyLet
, reifyCaseSized
, reifyVecS -- TEMP workaround
, reifyLeaf -- TEMP workaround
, reifyBranch -- TEMP workaround
, reifyUnfoldScrut
-- , labelR "inReify castFloatAppsR" (inReify castFloatAppsR)
, reifySimplifiable
#endif
, reifyUnfold
-- Non-reify rules
, labelR "castFloatAppR" castFloatAppR
]
-- Note: letElim is handy with reifyPolyLet to eliminate the "foo = eval
-- foo_reified", which is usually inaccessible.
-- reifyBash :: ReExpr
-- reifyBash = bashExtendedWithE reifyRs
reifyBash :: ReCore
reifyBash = bashExtendedWithR (promoteR <$> reifyRs)
{--------------------------------------------------------------------
Plugin
--------------------------------------------------------------------}
plugin :: Plugin
plugin = hermitPlugin (phase 0 . interactive externals)
externals :: [External]
externals =
[ externC "reify-rules" reifyRules
"convert some non-local vars to consts"
-- , externC "reify-rules-prefix" reifyRulesPrefix
-- "reify-rules on an application prefix"
, external "reify-rhs"
#ifdef SplitEval
(promoteR . reifyRhs :: String -> ReCore)
#else
(promoteR reifyRhs :: ReCore)
#endif
["reifyE the RHS of a definition, giving a let-intro name"]
, externC "reify-def" reifyDef "reifyE a definition"
, externC "reify-misc" reifyMisc "Simplify 'reify e'"
-- For debugging
, externC "unreify" unReify "Drop reify"
, externC "reify-it" reifyR "apply reify"
, externC "eval-it" evalR "apply eval"
, externC "reify-app" reifyApp "reify (u v) ==> reify u `appP` reify v"
, externC "reify-lam" reifyLam
"reify (\\ x -> e) ==> lamv x' (reify (e[x := eval (var x')]))"
, externC "reify-mono-let" reifyMonoLet "reify monomorphic let"
, externC "reify-poly-let" reifyPolyLet "reify polymorphic let"
, externC "reify-case-wild" reifyCaseWild "reify a evaluation-only case"
-- , externC "reify-construct" reifyConstruct "re-construct under reify"
-- , externC "reify-case" reifyCase "re-case under reify"
-- , externC "reify-method" reifyMethod "reify of a method application"
-- , externC "inline-method" inlineMethod "inline method application"
, externC "reify-cast'" reifyCast' "transform or reify a cast"
-- , externC "reify-cast-float-apps" (inReify castFloatAppsR)
-- "reify while floating casts"
, externC "reify-int-literal" reifyIntLit "reify an Int literal"
, externC "reify-eval" reifyEval "reify eval"
, externC "reify-unfold" reifyUnfold "reify an unfoldable"
, externC "reify-unfold-scrut" reifyUnfoldScrut "reify case with unfoldable scrutinee"
, externC "reify-case-sized" reifyCaseSized "case with a known-length vector scrutinee"
, externC "reify-vecs" reifyVecS "Temp workaround"
-- , externC "post-unfold" postUnfold "simplify after unfolding"
, externC "reify-tup-case" reifyTupCase "reify case with unit or pair pattern"
, externC "reify-simplifiable" reifySimplifiable "Simplify under reify"
, externC "reify-module" reifyModGuts "reify all top-level definitions"
-- , externC "inline-dict" inlineDict "inline a dictionary-related var"
-- , externC "inline-wrapper" inlineWrapper "inline a datacon wrapper"
, externC "type-eta-long" typeEtaLong "type-eta-long form"
, externC "reify-poly-let" reifyPolyLet "reify polymorphic 'let' expression"
-- , externC "re-simplify" reSimplify "simplifications to complement reification"
-- , externC "reify-encode" reifyEncode "type-encode under reify"
-- , externC "encode-types" encodeTypesR
-- "encode case expressions and constructor applications"
#ifndef OnlyLifted
, externC "reify-code" reifyCodeF "manual rewrites for reifying encodeF & decodeF"
#endif
, external "uncalle1" (promoteR . unCallE1 :: String -> ReCore) ["uncall a function"]
-- , externC "cast-float-apps" castFloatAppsR "float casts over apps"
, externC "simplify-expr" simplifyExprR "Invoke GHC's simplifyExpr"
, externC "reify-bash" reifyBash "reify & bash"
]
-- ++ Enc.externals
| capn-freako/lambda-ccc | src/LambdaCCC/Unused/SReify.hs | bsd-3-clause | 28,768 | 0 | 17 | 6,830 | 5,216 | 2,805 | 2,411 | 358 | 4 |
module Test.Hspec.Runner (module Test.Hspec.Core.Runner) where
import Test.Hspec.Core.Runner
| hspec/hspec | src/Test/Hspec/Runner.hs | mit | 103 | 0 | 5 | 17 | 24 | 17 | 7 | 2 | 0 |
{-# LANGUAGE LambdaCase #-}
import Data.List
import Data.Maybe
import Data.Ord
import Data.Array.Unboxed
import Data.Array.ST
import Control.Applicative
import Control.Monad
import Control.Monad.State.Lazy
import Control.Monad.ST
import qualified Data.ByteString.Char8 as B
data Point = Point { location :: (Int, Int)
, idx :: Int }
main = putStr . unlines . map (unwords . map show . sol) .
evalState getTestcases . B.words =<< B.getContents
where
getInt = fst . fromJust . B.readInt <$> state (\(x:xs) -> (x, xs))
getPoint i = do
x <- getInt
y <- getInt
return $ Point (x, y) i
getTestcase = do
n <- getInt
forM [1..n] getPoint
getTestcases =
getTestcase >>= \case
[] -> return []
tc -> (tc:) <$> getTestcases
sol :: [Point] -> [Int]
sol pts = elems $ runSTUArray $ do
ans <- newArray (1, length pts) 0
conquer (sortBy (comparing location) pts) ans
return ans
conquer :: [Point] -> STUArray s Int Int -> ST s [Point]
conquer [] _ = return []
conquer [p] _ = return [p]
conquer pts ans = do
l' <- conquer l ans
r' <- conquer r ans
merge l' r' 0 ans
where
(l, r) = splitAt (length pts `div` 2) pts
merge xs [] _ _ = return xs
merge [] ys acc ans = do
forM_ ys $ \p -> addRank ans (idx p) acc
return ys
merge (x:xs) (y:ys) acc ans
| (snd . location $ x) <= (snd . location $ y) =
(x:) <$> merge xs (y:ys) (acc+1) ans
| otherwise = do
addRank ans (idx y) acc
(y:) <$> merge (x:xs) ys acc ans
addRank arr idx val = do
newVal <- (val+) <$> readArray arr idx
writeArray arr idx newVal
| c910335/2D-Rank-Finding-Problem | main.hs | mit | 1,630 | 0 | 13 | 431 | 763 | 392 | 371 | 53 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-| Implementation of functions specific to configuration management.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.WConfd.ConfigVerify
( verifyConfig
, verifyConfigErr
) where
import Control.Monad.Error
import qualified Data.ByteString.UTF8 as UTF8
import qualified Data.Foldable as F
import qualified Data.Map as M
import qualified Data.Set as S
import Ganeti.Errors
import Ganeti.JSON (GenericContainer(..), Container)
import Ganeti.Objects
import Ganeti.Types
import Ganeti.Utils
import Ganeti.Utils.Validate
-- * Configuration checks
-- | A helper function that returns the key set of a container.
keysSet :: (Ord k) => GenericContainer k v -> S.Set k
keysSet = M.keysSet . fromContainer
-- | Checks that all objects are indexed by their proper UUID.
checkUUIDKeys :: (UuidObject a, Show a)
=> String -> Container a -> ValidationMonad ()
checkUUIDKeys what = mapM_ check . M.toList . fromContainer
where
check (uuid, x) = reportIf (uuid /= UTF8.fromString (uuidOf x))
$ what ++ " '" ++ show x
++ "' is indexed by wrong UUID '"
++ UTF8.toString uuid ++ "'"
-- | Checks that all linked UUID of given objects exist.
checkUUIDRefs :: (UuidObject a, Show a, F.Foldable f)
=> String -> String
-> (a -> [String]) -> f a -> Container b
-> ValidationMonad ()
checkUUIDRefs whatObj whatTarget linkf xs targets = F.mapM_ check xs
where
uuids = keysSet targets
check x = forM_ (linkf x) $ \uuid ->
reportIf (not $ S.member (UTF8.fromString uuid) uuids)
$ whatObj ++ " '" ++ show x ++ "' references a non-existing "
++ whatTarget ++ " UUID '" ++ uuid ++ "'"
-- | Checks consistency of a given configuration.
--
-- TODO: Currently this implements only some very basic checks.
-- Evenually all checks from Python ConfigWriter need to be moved here
-- (see issue #759).
verifyConfig :: ConfigData -> ValidationMonad ()
verifyConfig cd = do
let cluster = configCluster cd
nodes = configNodes cd
nodegroups = configNodegroups cd
instances = configInstances cd
networks = configNetworks cd
disks = configDisks cd
-- global cluster checks
let enabledHvs = clusterEnabledHypervisors cluster
hvParams = clusterHvparams cluster
reportIf (null enabledHvs)
"enabled hypervisors list doesn't have any entries"
-- we don't need to check for invalid HVS as they would fail to parse
let missingHvp = S.fromList enabledHvs S.\\ keysSet hvParams
reportIf (not $ S.null missingHvp)
$ "hypervisor parameters missing for the enabled hypervisor(s) "
++ (commaJoin . map hypervisorToRaw . S.toList $ missingHvp)
let enabledDiskTemplates = clusterEnabledDiskTemplates cluster
reportIf (null enabledDiskTemplates)
"enabled disk templates list doesn't have any entries"
-- we don't need to check for invalid templates as they wouldn't parse
let masterNodeName = clusterMasterNode cluster
reportIf (not $ UTF8.fromString masterNodeName
`S.member` keysSet (configNodes cd))
$ "cluster has invalid primary node " ++ masterNodeName
-- UUIDs
checkUUIDKeys "node" nodes
checkUUIDKeys "nodegroup" nodegroups
checkUUIDKeys "instances" instances
checkUUIDKeys "network" networks
checkUUIDKeys "disk" disks
-- UUID references
checkUUIDRefs "node" "nodegroup" (return . nodeGroup) nodes nodegroups
checkUUIDRefs "instance" "primary node" (maybe [] return . instPrimaryNode)
instances nodes
checkUUIDRefs "instance" "disks" instDisks instances disks
-- | Checks consistency of a given configuration.
-- If there is an error, throw 'ConfigVerifyError'.
verifyConfigErr :: (MonadError GanetiException m) => ConfigData -> m ()
verifyConfigErr cd =
case runValidate $ verifyConfig cd of
(_, []) -> return ()
(_, es) -> throwError $ ConfigVerifyError "Validation failed" es
| mbakke/ganeti | src/Ganeti/WConfd/ConfigVerify.hs | bsd-2-clause | 5,407 | 0 | 23 | 1,216 | 914 | 467 | 447 | 71 | 2 |
module SubHask.Algebra.Ring
where
import SubHask.Algebra
import SubHask.Category
import SubHask.Internal.Prelude
--------------------------------------------------------------------------------
-- | Every free module can be converted into a ring with this type.
-- Intuitively, this lets us use all our code designed for univariate operations on vectors.
newtype Componentwise v = Componentwise { unComponentwise :: v }
type instance Scalar (Componentwise v) = Scalar v
type instance Logic (Componentwise v) = Logic v
type instance Elem (Componentwise v) = Scalar v
type instance SetElem (Componentwise v) v' = Componentwise v'
instance IsMutable (Componentwise v)
instance Eq_ v => Eq_ (Componentwise v) where
(Componentwise v1)==(Componentwise v2) = v1==v2
instance Semigroup v => Semigroup (Componentwise v) where
(Componentwise v1)+(Componentwise v2) = Componentwise $ v1+v2
instance Monoid v => Monoid (Componentwise v) where
zero = Componentwise zero
instance Abelian v => Abelian (Componentwise v)
instance Cancellative v => Cancellative (Componentwise v) where
(Componentwise v1)-(Componentwise v2) = Componentwise $ v1-v2
instance Group v => Group (Componentwise v) where
negate (Componentwise v) = Componentwise $ negate v
instance FreeModule v => Rg (Componentwise v) where
(Componentwise v1)*(Componentwise v2) = Componentwise $ v1.*.v2
instance FiniteModule v => Rig (Componentwise v) where
one = Componentwise $ ones
instance FiniteModule v => Ring (Componentwise v)
instance (FiniteModule v, VectorSpace v) => Field (Componentwise v) where
(Componentwise v1)/(Componentwise v2) = Componentwise $ v1./.v2
-- instance (ValidLogic v, FiniteModule v) => IxContainer (Componentwise v) where
-- values (Componentwise v) = values v
| abailly/subhask | src/SubHask/Algebra/Ring.hs | bsd-3-clause | 1,797 | 0 | 8 | 291 | 538 | 272 | 266 | -1 | -1 |
compress :: [a] -> [a]
compress [] = []
compress [a] = [a]
compress (x:y:xs)
| (x == y) = compress (x:xs)
| otherwise = x : compress (y:xs)
{- Helium does not have a class Eq -}
| roberth/uu-helium | test/thompson/Thompson24.hs | gpl-3.0 | 193 | 0 | 9 | 53 | 108 | 56 | 52 | 6 | 1 |
module Arithmetic where
import Control.Concurrent
import Control.Concurrent.MVar
import System.IO.Unsafe
import Utilities
import Converter
import Stream
import Data.Ratio
import Trit
-- Negate a stream of Gray code
negateGray :: Gray -> Gray
negateGray = fl
-- Multiply a Gray code stream by 2
-- The stream must represent a real number in (-1/2, 1/2) only
mul2 :: Gray -> Gray
mul2 (x:1:xs) = (x:fl xs)
-- Division by 2, the result is to be in (-1/2, 1/2)
div2 :: Gray -> Gray
div2 (x:xs) = x:1:(fl xs)
-- Addition by 1, the input must be in (-1,0)
plusOne :: Gray -> Gray
plusOne (0:xs) = 1:fl xs
-- Subtraction by 1, the input must be in (0,1)
minusOne :: Gray -> Gray
minusOne (1:xs) = 0:fl xs
threadTesting :: Gray -> Gray -> IO Int
threadTesting xs ys = do
m <- newEmptyMVar
c1 <- forkIO (t1 m xs ys)
c2 <- forkIO (t2 m xs ys)
c3 <- forkIO (t3 m xs ys)
c4 <- forkIO (t4 m xs ys)
c5 <- forkIO (t5 m xs ys)
c6 <- forkIO (t6 m xs ys)
c <- takeMVar m
killThread c1
killThread c2
killThread c3
killThread c4
killThread c5
killThread c6
return c
addition :: Gray -> Gray -> IO Gray
addition xs ys = do
c <- threadTesting xs ys
case c of
1 -> do
let tx = tail xs
let ty = tail ys
t <- unsafeInterleaveIO (addition tx ty)
return (0:t)
2 -> do
let tx = tail xs
let ty = tail ys
t <- unsafeInterleaveIO (addition tx ty)
return (1:t)
3 -> do
let tx = tail xs
let ty = tail ys
cs <- unsafeInterleaveIO (addition tx (fl ty))
let c1 = cs !! 0
let c2 = tail cs
return (c1:1:fl c2)
4 -> do
let tx = tail xs
let ty = tail ys
(cs) <- unsafeInterleaveIO (addition (fl tx) ty)
let c1 = cs !! 0
let c2 = tail cs
return (c1:1:(fl c2))
5 -> do
let x1 = xs!!0
let y1 = ys!!0
let tx = (drop 2) xs
let ty = (drop 2) ys
cs <- unsafeInterleaveIO (addition (x1:(fl tx)) (y1:(fl ty)))
let c1 = cs !! 0
let c2 = tail cs
return (c1:(1:(fl c2)))
6 -> do
let x1 = xs !! 0
let tx = drop 3 xs
let ty = drop 2 ys
t <- unsafeInterleaveIO (addition (x1:1:tx) (1:fl ty))
return (0:t)
7 -> do
let x1 = xs !! 0
let tx = drop 3 xs
let ty = drop 2 ys
t <- unsafeInterleaveIO (addition (fl (x1:1:tx)) (1:(fl ty)))
return (1:t)
8 -> do
let x1 = xs !! 0
let y2 = ys !! 1
let tx = drop 3 xs
let ty = drop 3 ys
t <- unsafeInterleaveIO (addition (fl (x1:fl tx)) (fl (y2:fl ty)))
return (0:1:t)
9 -> do
let x1 = xs !! 0
let y2 = ys !! 1
let tx = drop 3 xs
let ty = drop 3 ys
t <- unsafeInterleaveIO (addition (x1:fl tx) (fl (y2:fl ty)))
return (1:1:t)
10 -> do
let y1 = ys !! 0
let ty = drop 3 ys
let tx = drop 2 xs
t <- unsafeInterleaveIO (addition (1:fl tx) (y1:1:ty))
return (0:t)
11 -> do
let y1 = ys !! 0
let ty = drop 3 ys
let tx = drop 2 xs
t <- unsafeInterleaveIO (addition (1:fl tx) (fl (y1:1:ty)))
return (1:t)
12 -> do
let y1 = ys !! 0
let x2 = xs !! 1
let tx = drop 3 xs
let ty = drop 3 ys
t <- unsafeInterleaveIO (addition (fl (x2:fl tx)) (fl (y1:fl ty)))
return (0:1:t)
13 -> do
let y1 = ys !! 0
let x2 = xs !! 1
let tx = drop 3 xs
let ty = drop 3 ys
t <- unsafeInterleaveIO (addition (fl (x2:fl tx)) (y1:fl ty))
return (1:1:t)
-- Compute (a-b)/2
substraction :: Gray -> Gray -> IO Gray
substraction xs ys = addition xs (negateGray ys)
t1 :: MVar Int -> Stream -> Stream -> IO()
t1 m (0:as) (0:bs) = putMVar m 1
t1 m (1:as) (1:bs) = putMVar m 2
t1 m (0:as) (1:bs) = putMVar m 3
t1 m (1:as) (0:bs) = putMVar m 4
t2 :: MVar Int -> Stream -> Stream -> IO()
t2 m (a:1:x) (b:1:y) = putMVar m 5
t2 m x y = yield
t3 m (a:1:0:x) (0:0:y) = putMVar m 6
t3 m (a:1:0:x) (1:0:y) = putMVar m 7
t3 m x y = yield
t4 m (a:1:0:x) (0:b:1:y) = putMVar m 8
t4 m (a:1:0:x) (1:b:1:y) = putMVar m 9
t4 m x y = yield
t5 m (0:0:x) (b:1:0:y) = putMVar m 10
t5 m (1:0:x) (b:1:0:y) = putMVar m 11
t5 m x y = yield
t6 m (0:a:1:x) (b:1:0:y) = putMVar m 12
t6 m (1:a:1:x) (b:1:0:y) = putMVar m 13
t6 m x y = yield
multiplyIO :: Gray -> Gray -> IO Gray
multiplyIO xs ys = do
s1 <- unsafeInterleaveIO (grayToSignIO xs)
s2 <- unsafeInterleaveIO (grayToSignIO ys)
let s = Trit.multiply s1 s2
let g = signToGray s
return g
start :: IO()
start = do
c <- unsafeInterleaveIO(multiplyIO z1 z1)
putStrLn (show c)
startA :: IO()
startA = do
c <- unsafeInterleaveIO(addition (1:1:z0) (1:1:z0))
putStrLn (show (take 30 c))
z0 = (0:z0)
z1 = (1:z1)
zl = 0:loop:z0
loop = loop
loop01 = 0:1:loop01
| sdiehl/ghc | testsuite/tests/concurrent/prog001/Arithmetic.hs | bsd-3-clause | 9,047 | 70 | 26 | 5,737 | 2,746 | 1,337 | 1,409 | 167 | 13 |
{-# LANGUAGE BangPatterns, CPP, FlexibleInstances, OverloadedStrings,
RecordWildCards, TypeSynonymInstances #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Main ( main ) where
import Control.Applicative
import Control.Exception (evaluate)
import Control.DeepSeq
import Criterion.Main
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as HM
import Control.Monad (mzero)
import Data.Text (Text)
import qualified Text.CSV.Lazy.ByteString as LazyCsv
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Csv
import qualified Data.Csv.Streaming as Streaming
#if !MIN_VERSION_bytestring(0,10,0)
instance NFData (B.ByteString) where
rnf !s = ()
#endif
data President = President
{ presidency :: !Int
, president :: !Text
, wikipediaEntry :: !ByteString
, tookOffice :: !ByteString
, leftOffice :: !ByteString
, party :: !Text
, homeState :: !Text
}
instance NFData President where
rnf (President {}) = ()
instance FromRecord President where
parseRecord v
| V.length v == 7 = President <$>
v .!! 0 <*>
v .!! 1 <*>
v .!! 2 <*>
v .!! 3 <*>
v .!! 4 <*>
v .!! 5 <*>
v .!! 6
| otherwise = mzero
-- | Unchecked version of '(.!)'.
(.!!) :: FromField a => Record -> Int -> Parser a
v .!! idx = parseField (V.unsafeIndex v idx)
{-# INLINE (.!!) #-}
infixl 9 .!!
instance ToRecord President where
toRecord (President {..}) =
record [toField presidency, toField president, toField wikipediaEntry,
toField tookOffice, toField leftOffice, toField party,
toField homeState]
instance FromNamedRecord President where
parseNamedRecord m = President <$>
m .: "Presidency" <*>
m .: "President" <*>
m .: "Wikipedia Entry" <*>
m .: "Took office" <*>
m .: "Left office" <*>
m .: "Party" <*>
m .: "Home State"
instance ToNamedRecord President where
toNamedRecord (President {..}) = namedRecord
[ "Presidency" .= presidency
, "President" .= president
, "Wikipedia Entry" .= wikipediaEntry
, "Took office" .= tookOffice
, "Left office" .= leftOffice
, "Party" .= party
, "Home State" .= homeState
]
fromStrict :: B.ByteString -> BL.ByteString
fromStrict s = BL.fromChunks [s]
type BSHashMap a = HM.HashMap B.ByteString a
instance NFData LazyCsv.CSVField where
rnf LazyCsv.CSVField {} = ()
rnf LazyCsv.CSVFieldError {} = ()
instance NFData LazyCsv.CSVError where
rnf (LazyCsv.IncorrectRow !_ !_ !_ xs) = rnf xs
rnf (LazyCsv.BlankLine _ _ _ field) = rnf field
rnf (LazyCsv.FieldError field) = rnf field
rnf (LazyCsv.DuplicateHeader _ _ s) = rnf s
rnf LazyCsv.NoData = ()
main :: IO ()
main = do
!csvData <- fromStrict `fmap` B.readFile "benchmarks/presidents.csv"
!csvDataN <- fromStrict `fmap` B.readFile
"benchmarks/presidents_with_header.csv"
let (Right !presidents) = V.toList <$> decodePresidents csvData
(Right (!hdr, !presidentsNV)) = decodePresidentsN csvDataN
!presidentsN = V.toList presidentsNV
evaluate (rnf [presidents, presidentsN])
defaultMain [
bgroup "positional"
[ bgroup "decode"
[ bench "presidents/without conversion" $ whnf idDecode csvData
, bench "presidents/with conversion" $ whnf decodePresidents csvData
, bgroup "streaming"
[ bench "presidents/without conversion" $ nf idDecodeS csvData
, bench "presidents/with conversion" $ nf decodePresidentsS csvData
]
]
, bgroup "encode"
[ bench "presidents/with conversion" $ whnf encode presidents
]
]
, bgroup "named"
[ bgroup "decode"
[ bench "presidents/without conversion" $ whnf idDecodeN csvDataN
, bench "presidents/with conversion" $ whnf decodePresidentsN csvDataN
]
, bgroup "encode"
[ bench "presidents/with conversion" $ whnf (encodeByName hdr) presidentsN
]
]
, bgroup "comparison"
[ bench "lazy-csv" $ nf LazyCsv.parseCSV csvData
]
]
where
decodePresidents :: BL.ByteString -> Either String (Vector President)
decodePresidents = decode NoHeader
decodePresidentsN :: BL.ByteString -> Either String (Header, Vector President)
decodePresidentsN = decodeByName
decodePresidentsS :: BL.ByteString -> Streaming.Records President
decodePresidentsS = Streaming.decode NoHeader
idDecode :: BL.ByteString -> Either String (Vector (Vector B.ByteString))
idDecode = decode NoHeader
idDecodeN :: BL.ByteString -> Either String (Header, Vector (BSHashMap B.ByteString))
idDecodeN = decodeByName
idDecodeS :: BL.ByteString -> Streaming.Records (Vector B.ByteString)
idDecodeS = Streaming.decode NoHeader
| treeowl/cassava | benchmarks/Benchmarks.hs | bsd-3-clause | 5,577 | 0 | 20 | 1,806 | 1,361 | 703 | 658 | 134 | 1 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE DataKinds, KindSignatures, PolyKinds #-}
pattern PATTERN = ()
data Proxy (tag :: k) (a :: *)
wrongLift :: Proxy PATTERN ()
wrongLift = undefined
| urbanslug/ghc | testsuite/tests/patsyn/should_fail/T9161-2.hs | bsd-3-clause | 194 | 0 | 6 | 33 | 47 | 28 | 19 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Futhark.IR.SeqMem
( SeqMem,
-- * Simplification
simplifyProg,
simpleSeqMem,
-- * Module re-exports
module Futhark.IR.Mem,
)
where
import Futhark.Analysis.PrimExp.Convert
import Futhark.IR.Mem
import Futhark.IR.Mem.Simplify
import qualified Futhark.IR.TypeCheck as TC
import qualified Futhark.Optimise.Simplify.Engine as Engine
import Futhark.Pass
import Futhark.Pass.ExplicitAllocations (BuilderOps (..), mkLetNamesB', mkLetNamesB'')
data SeqMem
instance RepTypes SeqMem where
type LetDec SeqMem = LetDecMem
type FParamInfo SeqMem = FParamMem
type LParamInfo SeqMem = LParamMem
type RetType SeqMem = RetTypeMem
type BranchType SeqMem = BranchTypeMem
type Op SeqMem = MemOp ()
instance ASTRep SeqMem where
expTypesFromPat = return . map snd . bodyReturnsFromPat
instance PrettyRep SeqMem
instance TC.CheckableOp SeqMem where
checkOp (Alloc size _) =
TC.require [Prim int64] size
checkOp (Inner ()) =
pure ()
instance TC.Checkable SeqMem where
checkFParamDec = checkMemInfo
checkLParamDec = checkMemInfo
checkLetBoundDec = checkMemInfo
checkRetType = mapM_ (TC.checkExtType . declExtTypeOf)
primFParam name t = return $ Param mempty name (MemPrim t)
matchPat = matchPatToExp
matchReturnType = matchFunctionReturnType
matchBranchType = matchBranchReturnType
matchLoopResult = matchLoopResultMem
instance BuilderOps SeqMem where
mkExpDecB _ _ = return ()
mkBodyB stms res = return $ Body () stms res
mkLetNamesB = mkLetNamesB' ()
instance TraverseOpStms SeqMem where
traverseOpStms _ = pure
instance BuilderOps (Engine.Wise SeqMem) where
mkExpDecB pat e = return $ Engine.mkWiseExpDec pat () e
mkBodyB stms res = return $ Engine.mkWiseBody () stms res
mkLetNamesB = mkLetNamesB''
instance TraverseOpStms (Engine.Wise SeqMem) where
traverseOpStms _ = pure
simplifyProg :: Prog SeqMem -> PassM (Prog SeqMem)
simplifyProg = simplifyProgGeneric simpleSeqMem
simpleSeqMem :: Engine.SimpleOps SeqMem
simpleSeqMem =
simpleGeneric (const mempty) $ const $ return ((), mempty)
| diku-dk/futhark | src/Futhark/IR/SeqMem.hs | isc | 2,244 | 0 | 9 | 372 | 587 | 319 | 268 | -1 | -1 |
module Tests(tests) where
import Distribution.TestSuite.QuickCheck
import Test.QuickCheck
import Data.List
import Test.QuickCheck.Monadic
import Control.Monad.Identity
import Agricola
import Update
import Data.Maybe
instance Arbitrary Building where
arbitrary = elements [Stall,Stable,Cottage
,HalfTimberedHouse,Storage,Shelter,OpenStable]
instance Arbitrary Animal where
arbitrary = elements [Sheep,Pig,Cow,Horse]
instance Arbitrary Alignment where
arbitrary = elements [H,V]
instance Arbitrary Border where
arbitrary = do al <- arbitrary
there <- arbitrary
return Border {_alignment = al, _isThere = there}
instance Arbitrary Tile where
arbitrary = do
b <- arbitrary
ta <- arbitrary `suchThat` maybe True ((> 0) . snd)
t <- arbitrary
e <- arbitrary
return Tile {_building = b, _tileanimals = ta, _trough = t, _isExpansion = e}
borderWithAl al = arbitrary `suchThat` ((al == ) ._alignment)
farmTiles numrows = vector
instance Arbitrary Farm where
arbitrary = do
n <- arbitrary :: Gen (Positive Integer)
arbitraryFarmWithAtLeast n
arbitraryFarmWithAtLeast :: Positive Integer -> Gen Farm
arbitraryFarmWithAtLeast (Positive nrows) = do
numrows <- fromInteger <$> (arbitrary :: Gen Integer) `suchThat` (>= nrows)
ts <- vectorOf 3 (vector numrows)
vs <- vectorOf 3 (vectorOf (numrows + 1) $ borderWithAl V)
hs <- vectorOf 4 (vectorOf numrows $ borderWithAl H)
return Farm {_tiles = ts, _vborders = vs , _hborders =hs}
legalLineVals :: Alignment -> (Integer,Integer)
legalLineVals V = (0,2)
legalLineVals H = (0,3)
leastNumRows :: Alignment -> NonNegative Integer -> Positive Integer
leastNumRows V (NonNegative m) = Positive (max m 1)
leastNumRows H (NonNegative m) = Positive (m + 1)
prop_borderGetSet :: Property
prop_borderGetSet = monadic runIdentity $ do
al <- pick arbitrary
nb <- pick $ arbitrary `suchThat` ((== al) . _alignment)
nnm@(NonNegative m) <- pick arbitrary
n <- pick $ choose $ legalLineVals al
farm <- pick $ arbitraryFarmWithAtLeast $ leastNumRows al nnm
assert $ _border al n m (_setBorder al n m farm nb) == nb
checkBorders :: Test
checkBorders = testGroup "Borders" [
testProperty "border can be fetched and set" prop_borderGetSet
]
prop_tileGetSet :: Property
prop_tileGetSet = monadic runIdentity $ do
t <- pick arbitrary
pm@(Positive m) <- pick arbitrary
n <- pick $ choose (0,2)
farm <- pick $ arbitraryFarmWithAtLeast pm
assert $ _tile n (m-1) (_setTile n (m-1) farm t) == t
-- This is mainly for forcing a playtrough
prop_canGetPositivePoints :: Property
prop_canGetPositivePoints = monadic runIdentity $ do
a <- pick infiniteList
assert $ any (\agri -> finalPlayerScore Red agri > 0 || finalPlayerScore Blue agri > 0) a
checkTiles :: Test
checkTiles = testGroup "Tiles" [
testProperty "tiles can be gotten and set" prop_tileGetSet
]
instance Arbitrary Color where
arbitrary = elements [Red,Blue]
instance Arbitrary Animals where
arbitrary = do
(NonNegative s) <- arbitrary
(NonNegative p) <- arbitrary
(NonNegative c) <- arbitrary
(NonNegative h) <- arbitrary
return $ Animals s p c h
instance Arbitrary Supply where
arbitrary = do
(NonNegative b) <- arbitrary
(NonNegative w) <- arbitrary
(NonNegative s) <- arbitrary
(NonNegative r) <- arbitrary
a <- arbitrary
return $ Supply b w s r a
maybeSensibleAction :: Agricola -> Gen Action
maybeSensibleAction agri
| _phase agri == Finished = return $ SetMessage $ finalScore agri
maybeSensibleAction agri
| isNothing (isProblem agri EndPhase) = return EndPhase
maybeSensibleAction agri
| isNothing (isProblem agri EndTurn) = return EndTurn
maybeSensibleAction agri
| hasAnimalsInSupply agri = do
an <- arbitrary
let col = _whoseTurn agri
let pf | col == Red = _farm $ _red agri
| otherwise = _farm $ _blue agri
n <- choose (0,farmrows pf)
m <- choose (0,farmcols pf)
elements [FreeAnimal an, PlaceAnimal an n m]
maybeSensibleAction _ = arbitrary
instance Arbitrary Agricola where
arbitrary = do
agri <- frequency [(1, return startingState), (1000 , arbitrary)]
sensb <- maybeSensibleAction agri
return $ fromJust $ tryTakeAction agri sensb
instance Arbitrary Good where
arbitrary = elements [Stone, Wood, Reed]
instance Arbitrary Action where
arbitrary = do
al <- arbitrary
al1 <- arbitrary
al2 <- arbitrary
n <- choose (0,5)
n1 <- choose (0,5)
n2 <- choose (0,5)
m <- choose (0,3)
m1 <- choose (0,3)
m2 <- choose (0,3)
animal <- arbitrary
build <- arbitrary
bool <- arbitrary
frequency [
(30 , return $ MultiAction [StartBuildingStoneWalls
, PlaceBorder al n m
, PlaceBorder al1 n1 m1
, SpendResources Stone 2
, PlaceBorder al2 n2 m2
])
, (30 , return $ MultiAction [StartBuildingWoodFences
, SpendResources Wood 1
, PlaceBorder al n m
, SpendResources Wood 1
, PlaceBorder al1 n1 m1
, SpendResources Wood 1
, PlaceBorder al2 n2 m2
])
, (5 , return $ PlaceBorder al n m)
, (5 , return TakeResources)
, (5 , return TakeSmallForest)
, (5 , return TakeBigForest)
, (5 , return TakeSmallQuarry)
, (5 , return TakeBigQuarry)
, (5, return $ MultiAction [TakeMillpond, PlaceAnimal Sheep n m])
, (5, return $ MultiAction [TakePigsAndSheep, PlaceAnimal Pig n m])
, (5, return $ MultiAction [TakeHorsesAndSheep, PlaceAnimal Horse n m])
, (5, return $ MultiAction [TakeCowsAndPigs, PlaceAnimal Cow n m])
, (5 , return TakeCowsAndPigs)
, (5 , return TakeHorsesAndSheep)
, (5 , return $ TakeAnimal n m)
, (10 , return $ PlaceAnimal animal n m)
, (5 , return $ PlaceTrough n m )
, (5, return $ MultiAction [TakeExpand, PlaceExpand bool])
, (20 , return $ MultiAction [StartBuilding build, PlaceBuilding build n m] )
]
checkPoints :: Test
checkPoints = testGroup "Points" [
testProperty "Positive points can be had" prop_canGetPositivePoints
]
tests :: IO [Test]
tests = return [checkBorders,checkTiles, checkPoints]
| Tritlo/Agricola | src-test/Tests.hs | mit | 6,945 | 1 | 15 | 2,147 | 2,215 | 1,129 | 1,086 | 161 | 1 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid (mappend)
import Hakyll
import Data.Maybe (fromMaybe)
import Control.Monad (liftM)
--------------------------------------------------------------------------------
config :: Configuration
config = defaultConfiguration {
destinationDirectory = "public"
}
main :: IO ()
main = hakyllWith config $ do
match "images/*" $ do
route idRoute
compile copyFileCompiler
match "css/*" $ do
route idRoute
compile compressCssCompiler
match (fromList ["about.rst", "contact.markdown"]) $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
match "posts/*" $ do
route $ setExtension "html"
compile $ do
item <- getUnderlying
metadata <- getMetadataField item "template"
case metadata of
Just temp -> pandocCompiler
>>= loadAndApplyTemplate (fromFilePath (temp :: String)) postCtx
Nothing -> pandocCompiler
>>= loadAndApplyTemplate "templates/post.html" postCtx
>>= loadAndApplyTemplate "templates/default.html" postCtx
create ["archive.html"] $ do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll "posts/*"
let archiveCtx =
listField "posts" postCtx (return posts) `mappend`
constField "title" "Archives" `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/archive.html" archiveCtx
>>= loadAndApplyTemplate "templates/default.html" archiveCtx
>>= relativizeUrls
match "index.html" $ do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll "posts/*"
let indexCtx =
listField "posts" postCtx (return posts) `mappend`
constField "title" "Home" `mappend`
defaultContext
getResourceBody
>>= applyAsTemplate indexCtx
>>= loadAndApplyTemplate "templates/default.html" indexCtx
>>= relativizeUrls
match "templates/*" $ compile templateBodyCompiler
--------------------------------------------------------------------------------
postCtx :: Context String
postCtx =
dateField "date" "%B %e, %Y" `mappend`
defaultContext
--------------------------------------------------------------------------------
| jackft/jackft.github.io | entropyfactor/site.hs | mit | 2,850 | 0 | 21 | 929 | 525 | 247 | 278 | 61 | 2 |
{-|
Module: Y2015.D08
Description: Advent of Code Day 08 Solutions.
License: MIT
Maintainer: @tylerjl
Solutions to the day 08 set of problems for <adventofcode.com>.
-}
module Y2015.D08 (difference, encoded) where
body :: [a] -> [a]
body [] = []
body [_] = []
body xs = tail $ init xs
hexChars :: String
hexChars = "0123456789abcdef"
escape :: String -> String
escape [] = []
escape [x] = [x]
escape (v:w:x:y:zs) | [v,w] == "\\x" && hex = '.' : escape zs
where hex = all (`elem` hexChars) [x,y]
escape (x:y:zs) | [x,y] == "\\\"" = '"' : escape zs
| [x,y] == "\\\\" = '\\' : escape zs
| otherwise = x : escape (y:zs)
encode :: String -> String
encode = (++) "\"" . (:) '"' . encode'
encode' :: String -> String
encode' [] = []
encode' (x:xs) | x == '"' = '\\' : '"' : encode' xs
| x == '\\' = "\\\\" ++ encode' xs
| otherwise = x : encode' xs
squish :: String -> String
squish = filter (/= '\n')
solve :: (Int -> Int -> Int) -> (String -> String) -> String -> Int
solve g f s = g (original s) (new s)
where original = length . squish
new = length . squish . unlines . map f . lines
-- |Finds the length difference between escaped and unescaped string
difference :: String -- ^ Input string with escapes
-> Int -- ^ Unescaped length difference
difference = solve (-) (escape . body)
-- |Same as 'encoded', but different
encoded :: String -- ^ Input string with escapes
-> Int -- ^ Length difference to encoded string
encoded = solve (flip (-)) encode
| tylerjl/adventofcode | src/Y2015/D08.hs | mit | 1,735 | 0 | 10 | 570 | 590 | 313 | 277 | 34 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Network.Server
-- Copyright : (c) Phil Hargett 2016
-- License : MIT (see LICENSE file)
--
-- Maintainer : [email protected]
-- Stability : $(Stability)
-- Portability : $(Portability)
--
--
-----------------------------------------------------------------------------
module Network.Server (
withServer
) where
-- local imports
-- external imports
import Control.Concurrent.STM
import Network.Endpoints
import Network.Transport
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
withServer :: IO Transport -> Name -> (Transport -> Endpoint -> IO a) -> IO a
withServer transportFactory name serverFn = do
-- just a hack until the underlying functions are rewritten
vResult <- atomically newEmptyTMVar
withTransport transportFactory $ \transport -> do
endpoint <- newEndpoint
withEndpoint transport endpoint $
withBinding transport endpoint name $ do
val <- serverFn transport endpoint
atomically $ putTMVar vResult val
atomically $ readTMVar vResult
| hargettp/paxos | src/Network/Server.hs | mit | 1,231 | 0 | 15 | 195 | 182 | 96 | 86 | 15 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
module MVC.Action where
import Control.Applicative
import Control.Concurrent.Async
import Control.Lens
import Control.Monad
import qualified Data.Attoparsec.ByteString.Char8 as AC
import qualified Data.ByteString.Char8 as C
import Data.Data
import Data.Default
import qualified Data.Foldable as F
import Data.IORef
import GHC.Generics
import MVC
import MVC.Effects
import MVC.Prelude
import MVC.Wrap
import Pipes.Extended
import qualified Pipes.Prelude as Pipes
data ActionComms
= ActionReady -- action is ready
| ActionDied -- action died (of its own accord)
| ActionKill -- kill action thread (without shutting down)
| ActionQuit -- quit the action (cancel thread)
| ActionShutDown -- thread successfully cancelled - safe to shutdown app
| ActionStart -- start the action (potentially cancelling a previous action)
deriving (Show, Read, Eq, Data, Typeable, Generic)
type ActionVC = Managed (View ActionComms, Controller ActionComms)
-- MVC wrapped IO thread
-- represents typical management of an action
data ActionConfig =
ActionConfig
{ _keepAlive :: Bool
, _restartDelay :: Double
, _beVerbose :: Bool
, _vcs :: ActionConfig -> ActionVC
}
makeLenses ''ActionConfig
vcDefaultCommMethod :: ActionConfig -> Managed (View ActionComms, Controller ActionComms)
vcDefaultCommMethod cfg =
(,) <$>
pure (if _beVerbose cfg then contramap show stdoutLines else mempty) <*>
stdinParsed parseActionComms
instance Default ActionConfig where
def = ActionConfig False 5.0 True vcDefaultCommMethod
parseActionComms :: AC.Parser ActionComms
parseActionComms = AC.string "q" *> return ActionQuit
<|> AC.string "s" *> return ActionStart
<|> do
res <- maybeRead . C.unpack <$> AC.takeByteString
case res of
Nothing -> mzero
Just a -> return a
vcHandleComms :: ActionConfig -> IO a -> Managed (View ActionComms, Controller ActionComms)
vcHandleComms cfg action = join $ managed $ \k -> do
ref <- newIORef Nothing
let cancelRef = lift (F.mapM_ cancel =<< readIORef ref)
(oC, iC, sealC) <- spawn' unbounded
(oV, iV, sealV) <- spawn' unbounded
let send' = void . atomically . send oC
aView <-
async $ runEffect $
fromInput iV >->
until' ActionQuit >->
forever ( do
x <- await
case x of
ActionQuit -> do
cancelRef
lift $ send' ActionShutDown
ActionStart -> do
cancelRef
aAction <- lift $ async (action >> send' ActionDied)
lift $ writeIORef ref (Just aAction)
lift $ send' ActionReady
ActionDied -> case _keepAlive cfg of
False ->
return ()
True -> do
lift $ sleep (_restartDelay cfg)
lift $ send' ActionStart
ActionKill ->
cancelRef
_ -> return ())
result <- k (return
( asSink (void . atomically . send oV)
, asInput iC
))
<* atomically sealC
<* atomically sealV
cancel aView
return result
runAction :: IO () -> IO ()
runAction action = runActionWith def action
runActionWith :: ActionConfig -> IO () -> IO ()
runActionWith cfg action =
runMVC ()
(asPipe $ until' ActionShutDown >-> cat)
(vcHandleComms cfg action <> view vcs cfg cfg)
runActionWith' :: ActionConfig -> IO a -> IO [ActionComms]
runActionWith' cfg action = do
r <- runMVCWrapped ()
(until' ActionShutDown >-> cat)
(vcHandleComms cfg action <> view vcs cfg cfg)
return $ _wrapOuts r
-- | send Start, wait for a Ready signal, run action, then send Quit
vcWrap :: IO a -> Managed (View ActionComms, Controller ActionComms)
vcWrap action = join $ managed $ \k -> do
(oC, iC, sealC) <- spawn' unbounded
(oV, iV, sealV) <- spawn' unbounded
let send' = void . atomically . send oC
send' ActionStart
aView <-
async $ runEffect $
fromInput iV >->
until' ActionQuit >->
forever ( do
x <- await
case x of
ActionReady -> do
_ <- lift action
lift $ send' ActionQuit
_ -> return ())
result <- k (return
( asSink (void . atomically . send oV)
, asInput iC
))
<* atomically sealC
<* atomically sealV
cancel aView
return result
runWrapWith :: ActionConfig -> IO () -> IO () -> IO ()
runWrapWith cfg outer inner =
runActionWith ( vcs %~ (\x -> x <> const (vcWrap inner)) $ cfg) outer
runWrapWith' :: ActionConfig -> IO () -> IO () -> IO [ActionComms]
runWrapWith' cfg outer inner =
runActionWith' ( vcs %~ (\x -> x <> const (vcWrap inner)) $ cfg) outer
timeOut :: Double -> Managed (View ActionComms, Controller ActionComms)
timeOut t = (,) <$> pure mempty <*> producer unbounded (yield ActionQuit >-> Pipes.chain (\_ -> sleep t))
{-
runWrapWithA :: ActionConfig -> IO () -> IO a -> IO a
runWrapWithA cfg outer inner =
runActionWith ( vcs %~ (\x -> x <> const (vcWrap inner)) $ cfg) outer
-}
| tonyday567/mvc-extended | src/MVC/Action.hs | mit | 5,457 | 0 | 26 | 1,525 | 1,537 | 765 | 772 | 139 | 6 |
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Monad
import System.Random
promptMessage :: Int -> IO ()
promptMessage tries =
if tries < 5
then putStrLn "Not correct, try again!"
else putStrLn "You have used up opportunities, quitting..."
guess :: Int -> Int -> IO Bool
guess tries actual =
if tries <= 5
then do (g :: Int) <- fmap read getLine
if g == actual
then return True
else promptMessage tries >> guess (tries + 1) actual
else return False
main :: IO ()
main =
do
putStrLn "Please guess a number between 1 and 10:"
rn <- randomRIO (1, 10)
b <- guess 1 rn
when b $ putStrLn $ "You are correct! The number is: " ++ show rn | hnfmr/beginning_haskell | ex9.1.hs | mit | 715 | 0 | 12 | 201 | 219 | 107 | 112 | 23 | 3 |
module Utility.Terminal (
Color (..),
Style (..),
Weight (..),
errorString,
infoString,
styledString
) where
data Color = Red | Green | Yellow | Blue | Magenta | Cyan | Black | White | Default deriving ( Show )
data Weight = Normal | Bold deriving ( Show )
data Style = Style Color Weight deriving ( Show )
startSeq :: String
startSeq = "\x1B["
resetCode :: String
resetCode = startSeq ++ "0m"
colorCode :: Color -> String
colorCode Red = "31"
colorCode Green = "32"
colorCode Yellow = "33"
colorCode Blue = "34"
colorCode Magenta = "35"
colorCode Cyan = "36"
colorCode Black = "48"
colorCode White = "37"
colorCode Default = "48"
weightCode :: Weight -> String
weightCode Normal = ""
weightCode Bold = ";1"
styleSeq :: Style -> String
styleSeq ( Style c w ) = startSeq ++ colorCode c ++ weightCode w ++ "m"
styledString :: Style -> String -> String
styledString s str = styleSeq s ++ str ++ resetCode
errorString :: String -> String
errorString = styledString ( Style Red Bold )
infoString :: String -> String
infoString = styledString ( Style Blue Normal )
| zjurelinac/Pljuska | Utility/Terminal.hs | mit | 1,143 | 0 | 8 | 274 | 368 | 202 | 166 | 35 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-|
Module : Data.Torrent.Bencode
Description : Types and functions for handling B-encoded data.
Copyright : (c) Kyle Butt, 2014
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : TypeFamilies
Bencode Data type and Bencode Catamporphisms, together with a serializer and a
deserializer.
-}
module Data.Torrent.Bencode
( Bencode(..)
, BencodeC(..)
, serialize
, deserialize
) where
import Control.Applicative
import qualified Data.Attoparsec.ByteString.Char8 as AP
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Lazy.Builder
import Data.ByteString.Lazy.Builder.ASCII
import Data.Int
import qualified Data.Map as M
import Data.Monoid
-- | ADT representing Bittorrent B-encoded data
data Bencode
= BeString B.ByteString -- ^ String
| BeInt Int64 -- ^ Int (Bittorrent doesn't specify a max int size,
-- but 64 bits should be sufficient)
| BeList [Bencode] -- ^ A list, consisting of B-encoded values
| BeDict (M.Map B.ByteString Bencode) -- ^ A map from strings to B-encoded
-- values
deriving (Show)
-- | A Catamorphism for B-encoded data.
-- Using this class rather than constructing Bencode allows the program to
-- avoid storing the intermediate representation and directly serialize the
-- data. Example, Instead of
-- @
-- -- BAD EXAMPLE
-- BeDict $ M.fromAssocs [(B.pack "complete", BeInt 10),
-- (B.pack "downloaded", BeInt 125),
-- (B.pack "incomplete", BeInt 15)]
-- @
-- You could use:
-- @
-- beDict $ beDictCataCons (B8.pack "complete") (beInt 10) $
-- beDictCataCons (B8.pack "downloaded") (beInt 125) $
-- beDictCataCons (B8.pack "incomplete") (beInt 15) beDictCataNil
-- @
-- The second example allows you to directly serialize the result without
-- constructing an intermediate data structure.
--
-- A BencodeC instance exists for Bencode to allow you to test code that
-- produces BencodeC expressions.
class BencodeC a
-- | ListIntermediate. Used by beList
-- A catamorphism for Bencoded data also includes a catamorphism for a list.
where
data Li a :: *
-- | DictIntermediate. Used by beDict
-- A catamorphism for Bencoded data also includes a catamorphism for a
-- dictionary.
data Di a :: *
beString :: B.ByteString -> a -- ^ Consume a ByteString as B-encoded data
beInt :: Int64 -> a -- ^ Consume an int as B-encoded data
beListCataNil :: Li a -- ^ Nil for the list catamorphism.
beListCataCons :: (a -> Li a -> Li a) -- ^ Cons for the list catamorphism
beDictCataNil :: Di a -- ^ Nil for the dict catamorphism
beDictCataCons :: (B.ByteString -> a -> Di a -> Di a)
-- ^ Cons-like function for the dict catamorphism. Takes a key and a value.
beList :: Li a -> a -- ^ Complete the list catamorphism and consume an Li as
-- B-encoded data
beDict :: Di a -> a -- ^ Complete the dict catamorphism and consume an Di as
-- B-encoded data
-- | Bencode is itself a Bencode Catamorphism.
-- In fact it's universal in that there's a natural map from this catamorphism
-- to any other.
instance BencodeC Bencode where
data Li Bencode = BeListRaw [Bencode] -- ^ Simple wrapper type.
data Di Bencode = BeDictRaw [(B.ByteString, Bencode)]
-- ^ This could be a map but since this is mainly for testing, this is simple.
beString = BeString
beInt = BeInt
beListCataNil = BeListRaw []
beListCataCons x (BeListRaw xs) = BeListRaw (x : xs)
beDictCataNil = BeDictRaw []
beDictCataCons k v (BeDictRaw kvs) = BeDictRaw ((k, v) : kvs)
beList (BeListRaw l) = BeList l
beDict (BeDictRaw kvs) = BeDict . M.fromList $ kvs
-- ^ Unwrap and then build a map.
-- | Builder is a Bencode Catamorphism.
-- Directly serialize the data via Data.ByteString.Lazy.Builder
instance BencodeC Builder where
data Li Builder = BuilderLi Builder -- ^ A wrapped builder.
data Di Builder = BuilderDi Builder -- ^ A wrapped builder.
beString = serialize . BeString
beInt = serialize . BeInt
beListCataNil = BuilderLi mempty
beListCataCons h (BuilderLi t) = BuilderLi (h <> t)
beDictCataNil = BuilderDi mempty
beDictCataCons k v (BuilderDi bldr) =
BuilderDi $ (serialize . BeString) k <> v <> bldr
-- | beList serializes the wrapped builder surrounded by 'l' and 'e'
beList (BuilderLi b) = char8 'l' <> b <> char8 'e'
-- | beDict serializes the wrapped builder surrounded by 'd' and 'e'
beDict (BuilderDi b) = char8 'd' <> b <> char8 'e'
-- | Serialize a Bencode value to a Data.ByteString.Lazy.Builder.
-- Used for testing and also pieces are used in the BencodeC instance for
-- Builder
serialize :: Bencode -> Builder
serialize (BeString str) =
int64Dec (fromIntegral $ B.length str) <> char8 ':' <> byteString str
serialize (BeInt i) = char8 'i' <> int64Dec i <> char8 'e'
serialize (BeList l) = char8 'l' <> mconcat (map serialize l) <> char8 'e'
serialize (BeDict m) = char8 'd' <> serializeMap m <> char8 'e'
where
serializeMap :: M.Map B.ByteString Bencode -> Builder
serializeMap =
M.foldrWithKey
(\k v bldr -> (serialize . BeString) k <> serialize v <> bldr)
mempty
-- | Fold over alternatives in a parser.
-- Rather than construct a list and then deconstruct it, simply pass the fold
-- directly to the parser.
-- Should be equivalent to
-- @
-- foldr cons nil <$> many v
-- @
foldAlt :: (a -> b -> b) -> b -> AP.Parser a -> AP.Parser b
foldAlt cons nil v = many_v
where
many_v = some_v <|> pure nil
some_v = cons <$> v <*> many_v
-- | Fold over alternatives in a parser, with a key as well.
-- Rather than construct a list of pairs and then deconstruct it, simply pass
-- the fold directly to the parser.
-- Should be equivalent to
-- @
-- foldr (uncurry cons) nil <$> many ((,) <$> k <*> v)
-- @
foldAltKey ::
(k -> a -> b -> b) -> b -> AP.Parser k -> AP.Parser a -> AP.Parser b
foldAltKey cons nil k v = many_kv
where
many_kv = some_kv <|> pure nil
some_kv = cons <$> k <*> v <*> many_kv
-- | Deserialize is a parser that produces an arbitrary Bencode Catamorphism.
-- for testing it can produce actual Bencode
deserialize :: (BencodeC a) => AP.Parser a
deserialize =
(beInt <$> (AP.char 'i' *> AP.decimal <* AP.char 'e')) <|>
(beList <$> (AP.char 'l' *> listCata <* AP.char 'e')) <|>
(beDict <$> (AP.char 'd' *> dictCata <* AP.char 'e')) <|>
(beString <$> parseString)
where
listCata = foldAlt beListCataCons beListCataNil deserialize
dictCata = foldAltKey beDictCataCons beDictCataNil parseString deserialize
parseString = (AP.decimal <* AP.char ':') >>= AP.take
| iteratee/haskell-tracker | Data/Torrent/Bencode.hs | mit | 6,856 | 0 | 14 | 1,571 | 1,293 | 709 | 584 | 84 | 1 |
{-
Base Package for Scheme compiler
-}
module Scheme (
module Scheme.Eval,
module Scheme.Lex,
module Scheme.Repl
-- module Scheme.Env
) where
import Scheme.Eval
import Scheme.Lex
import Scheme.Repl
-- import Scheme.Env
| johnellis1392/Haskell-Scheme | Scheme/Scheme.hs | mit | 239 | 0 | 5 | 49 | 42 | 28 | 14 | 7 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE KindSignatures #-}
module Numeric.Sampling.MCMC where
import Control.Applicative
import Control.Comonad
import Control.Comonad.Cofree
import Control.Lens
import Control.Monad
import Control.Monad.Random
import Data.Foldable
import Data.Traversable
import Linear.Affine
import Linear.Metric
import Linear.V2
import Linear.Vector
import Numeric.AD
import Numeric.AD.Types (AD, Mode)
import System.Random.MWC
import Numeric.Sampling.Util
import Numeric.Sampling.Types
rosen :: RealFloat a => C1Obj V2 a
rosen = naturalC1 $ \(P (V2 x y)) -> (1 - x)^2 + 100 * (y - x ^ 2)^2
naturalC1 :: (Traversable f, RealFloat a) => (forall a . RealFloat a => Obj f a) -> C1Obj f a
naturalC1 p = C1Obj p (unP . grad p)
-- | Compute the initial state space based on a differentiable function.
naturalS
:: (Num a, Traversable f)
=> (forall s. f (AD s a) -> AD s a)
-> Point f a -> StateS f a
naturalS f px@(P x) = StateS px (grad f x)
tryReject
:: (Fractional a, Ord a, Random a, MonadRandom m) =>
(b -> a) -> b -> b -> m b
tryReject f x0 x1 = do
coin <- getRandomR (0, 1)
return (if (coin < f x1 / f x0) then x1 else x0)
{-# INLINE tryReject #-}
-- | Refines an approximate sampler using a metropolis style rejection
-- step. This is only unbiased if the original sampler is symmetric,
-- i.e. @x' == jump x@ is equally likely as @x = jump x'@. This uses
-- direct division in computing the next step, so there may be
-- stability issues unless the base numeric type is compensated.
metropolis
:: (Fractional a, Ord a, Random a, MonadRandom m)
=> Obj f a -> Sampler m f a -> Sampler m f a
metropolis p jump x0 = jump x0 >>= tryReject p x0
{-# INLINE metropolis #-}
hamiltonian
:: (MonadRandom m, Fractional a, Ord a, Random a, Traversable f, Metric f)
=> Scalar f a -> Int
-> Flick m a -> C1Obj f a
-> Sampler m f a
hamiltonian eps n flick c1 x0 = do
st <- flickStateS flick x0
st' <- tryReject lik st (iter st)
return (st' ^. pos)
where
lik st = view fn c1 (st ^. pos) - (st ^. mom . to quadrance)/2
iter st = st ^?! dropping n (iterated $ leapfrog eps (c1 ^. grd))
{-# INLINE hamiltonian #-}
| tel/mcmc | src/Numeric/Sampling/MCMC.hs | mit | 2,222 | 0 | 13 | 470 | 791 | 413 | 378 | -1 | -1 |
module Test.Hierarchical
( tests
) where
import Control.Monad
import Data.Binary
import Data.List.Split
import qualified Data.Clustering.Hierarchical as C
import qualified Data.Vector as V
import System.Random.MWC
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import AI.Clustering.Hierarchical
import Test.Utils
tests :: TestTree
tests = testGroup "Hierarchical:"
[ testProperty "read/write test" testSerialization
, testCase "Single Linkage" testSingle
, testCase "Complete Linkage" testComplete
, testCase "Average Linkage" testAverage
, testCase "Weighted Linkage" testWeighted
]
isEqual :: Eq a => Dendrogram a -> C.Dendrogram a -> Bool
isEqual (Leaf x) (C.Leaf x') = x == x'
isEqual (Branch _ d x y) (C.Branch d' x' y') = abs (d - d') < 1e-8 &&
((isEqual x x' && isEqual y y') || (isEqual x y' && isEqual y x'))
isEqual _ _ = False
testSingle :: Assertion
testSingle = do
xs <- randVectors 500 5
let true = C.dendrogram C.SingleLinkage xs euclidean
test = hclust Single (V.fromList xs) euclidean
assertBool (unlines ["Expect: ", show true, "But see: ", show test]) $
isEqual test true
testComplete :: Assertion
testComplete = do
xs <- randVectors 500 5
let true = C.dendrogram C.CompleteLinkage xs euclidean
test = hclust Complete (V.fromList xs) euclidean
assertBool (unlines ["Expect: ", show true, "But see: ", show test]) $
isEqual test true
testAverage :: Assertion
testAverage = do
xs <- randVectors 500 5
let true = C.dendrogram C.UPGMA xs euclidean
test = hclust Average (V.fromList xs) euclidean
assertBool (unlines ["Expect: ", show true, "But see: ", show test]) $
isEqual test true
testWeighted :: Assertion
testWeighted = do
xs <- randVectors 500 5
let true = C.dendrogram C.FakeAverageLinkage xs euclidean
test = hclust Weighted (V.fromList xs) euclidean
assertBool (unlines ["Expect: ", show true, "But see: ", show test]) $
isEqual test true
--testSerialization :: Property
testSerialization :: [Double] -> Bool
testSerialization xs
| length xs <= 2 = True
| otherwise = let xs' = V.fromList $ map V.fromList $ init $ chunksOf 2 xs
dendro = fmap V.toList $ hclust Average xs' euclidean
in dendro == (decode . encode) dendro
| kaizhang/clustering | tests/Test/Hierarchical.hs | mit | 2,375 | 0 | 14 | 540 | 809 | 408 | 401 | 59 | 1 |
{-# LANGUAGE ConstrainedClassMethods #-}
{-# LANGUAGE QuasiQuotes, TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE Rank2Types #-}
-- | A Yesod plugin for Authentication via e-mail
--
-- This plugin works out of the box by only setting a few methods on the type class
-- that tell the plugin how to interoprate with your user data storage (your database).
-- However, almost everything is customizeable by setting more methods on the type class.
-- In addition, you can send all the form submissions via JSON and completely control the user's flow.
-- This is a standard registration e-mail flow
--
-- 1) A user registers a new e-mail address, and an e-mail is sent there
-- 2) The user clicks on the registration link in the e-mail
-- Note that at this point they are actually logged in (without a password)
-- That means that when they log out they will need to reset their password
-- 3) The user sets their password and is redirected to the site.
-- 4) The user can now
-- * logout and sign in
-- * reset their password
module Yesod.Auth.Email
( -- * Plugin
authEmail
, YesodAuthEmail (..)
, EmailCreds (..)
, saltPass
-- * Routes
, loginR
, registerR
, forgotPasswordR
, setpassR
, verifyR
, isValidPass
-- * Types
, Email
, VerKey
, VerUrl
, SaltedPass
, VerStatus
, Identifier
-- * Misc
, loginLinkKey
, setLoginLinkKey
-- * Default handlers
, defaultRegisterHandler
, defaultForgotPasswordHandler
, defaultSetPasswordHandler
) where
import Network.Mail.Mime (randomString)
import Yesod.Auth
import System.Random
import qualified Data.Text as TS
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Crypto.Hash.MD5 as H
import Data.ByteString.Base16 as B16
import Data.Text.Encoding (encodeUtf8, decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Text (Text)
import Yesod.Core
import qualified Yesod.PasswordStore as PS
import qualified Text.Email.Validate
import qualified Yesod.Auth.Message as Msg
import Control.Applicative ((<$>), (<*>))
import Control.Monad (void)
import Yesod.Form
import Data.Time (getCurrentTime, addUTCTime)
import Safe (readMay)
loginR, registerR, forgotPasswordR, setpassR :: AuthRoute
loginR = PluginR "email" ["login"]
registerR = PluginR "email" ["register"]
forgotPasswordR = PluginR "email" ["forgot-password"]
setpassR = PluginR "email" ["set-password"]
-- |
--
-- Since 1.4.5
verifyR :: Text -> Text -> AuthRoute -- FIXME
verifyR eid verkey = PluginR "email" ["verify", eid, verkey]
type Email = Text
type VerKey = Text
type VerUrl = Text
type SaltedPass = Text
type VerStatus = Bool
-- | An Identifier generalizes an email address to allow users to log in with
-- some other form of credentials (e.g., username).
--
-- Note that any of these other identifiers must not be valid email addresses.
--
-- Since 1.2.0
type Identifier = Text
-- | Data stored in a database for each e-mail address.
data EmailCreds site = EmailCreds
{ emailCredsId :: AuthEmailId site
, emailCredsAuthId :: Maybe (AuthId site)
, emailCredsStatus :: VerStatus
, emailCredsVerkey :: Maybe VerKey
, emailCredsEmail :: Email
}
class ( YesodAuth site
, PathPiece (AuthEmailId site)
, (RenderMessage site Msg.AuthMessage)
)
=> YesodAuthEmail site where
type AuthEmailId site
-- | Add a new email address to the database, but indicate that the address
-- has not yet been verified.
--
-- Since 1.1.0
addUnverified :: Email -> VerKey -> HandlerT site IO (AuthEmailId site)
-- | Send an email to the given address to verify ownership.
--
-- Since 1.1.0
sendVerifyEmail :: Email -> VerKey -> VerUrl -> HandlerT site IO ()
-- | Get the verification key for the given email ID.
--
-- Since 1.1.0
getVerifyKey :: AuthEmailId site -> HandlerT site IO (Maybe VerKey)
-- | Set the verification key for the given email ID.
--
-- Since 1.1.0
setVerifyKey :: AuthEmailId site -> VerKey -> HandlerT site IO ()
-- | Verify the email address on the given account.
--
-- Since 1.1.0
verifyAccount :: AuthEmailId site -> HandlerT site IO (Maybe (AuthId site))
-- | Get the salted password for the given account.
--
-- Since 1.1.0
getPassword :: AuthId site -> HandlerT site IO (Maybe SaltedPass)
-- | Set the salted password for the given account.
--
-- Since 1.1.0
setPassword :: AuthId site -> SaltedPass -> HandlerT site IO ()
-- | Get the credentials for the given @Identifier@, which may be either an
-- email address or some other identification (e.g., username).
--
-- Since 1.2.0
getEmailCreds :: Identifier -> HandlerT site IO (Maybe (EmailCreds site))
-- | Get the email address for the given email ID.
--
-- Since 1.1.0
getEmail :: AuthEmailId site -> HandlerT site IO (Maybe Email)
-- | Generate a random alphanumeric string.
--
-- Since 1.1.0
randomKey :: site -> IO Text
randomKey _ = do
stdgen <- newStdGen
return $ TS.pack $ fst $ randomString 10 stdgen
-- | Route to send user to after password has been set correctly.
--
-- Since 1.2.0
afterPasswordRoute :: site -> Route site
-- | Does the user need to provide the current password in order to set a
-- new password?
--
-- Default: if the user logged in via an email link do not require a password.
--
-- Since 1.2.1
needOldPassword :: AuthId site -> HandlerT site IO Bool
needOldPassword aid' = do
mkey <- lookupSession loginLinkKey
case mkey >>= readMay . TS.unpack of
Just (aidT, time) | Just aid <- fromPathPiece aidT, toPathPiece (aid `asTypeOf` aid') == toPathPiece aid' -> do
now <- liftIO getCurrentTime
return $ addUTCTime (60 * 30) time <= now
_ -> return True
-- | Check that the given plain-text password meets minimum security standards.
--
-- Default: password is at least three characters.
checkPasswordSecurity :: AuthId site -> Text -> HandlerT site IO (Either Text ())
checkPasswordSecurity _ x
| TS.length x >= 3 = return $ Right ()
| otherwise = return $ Left "Password must be at least three characters"
-- | Response after sending a confirmation email.
--
-- Since 1.2.2
confirmationEmailSentResponse :: Text -> HandlerT site IO TypedContent
confirmationEmailSentResponse identifier = do
mr <- getMessageRender
selectRep $ do
provideJsonMessage (mr msg)
provideRep $ authLayout $ do
setTitleI Msg.ConfirmationEmailSentTitle
[whamlet|<p>_{msg}|]
where
msg = Msg.ConfirmationEmailSent identifier
-- | Additional normalization of email addresses, besides standard canonicalization.
--
-- Default: Lower case the email address.
--
-- Since 1.2.3
normalizeEmailAddress :: site -> Text -> Text
normalizeEmailAddress _ = TS.toLower
-- | Handler called to render the registration page. The
-- default works fine, but you may want to override it in
-- order to have a different DOM.
--
-- Default: 'defaultRegisterHandler'.
--
-- Since: 1.2.6.
registerHandler :: AuthHandler site Html
registerHandler = defaultRegisterHandler
-- | Handler called to render the \"forgot password\" page.
-- The default works fine, but you may want to override it in
-- order to have a different DOM.
--
-- Default: 'defaultForgotPasswordHandler'.
--
-- Since: 1.2.6.
forgotPasswordHandler :: AuthHandler site Html
forgotPasswordHandler = defaultForgotPasswordHandler
-- | Handler called to render the \"set password\" page. The
-- default works fine, but you may want to override it in
-- order to have a different DOM.
--
-- Default: 'defaultSetPasswordHandler'.
--
-- Since: 1.2.6.
setPasswordHandler ::
Bool
-- ^ Whether the old password is needed. If @True@, a
-- field for the old password should be presented.
-- Otherwise, just two fields for the new password are
-- needed.
-> AuthHandler site TypedContent
setPasswordHandler = defaultSetPasswordHandler
authEmail :: YesodAuthEmail m => AuthPlugin m
authEmail =
AuthPlugin "email" dispatch $ \tm ->
[whamlet|
$newline never
<form method="post" action="@{tm loginR}">
<table>
<tr>
<th>_{Msg.Email}
<td>
<input type="email" name="email" required>
<tr>
<th>_{Msg.Password}
<td>
<input type="password" name="password" required>
<tr>
<td colspan="2">
<button type=submit .btn .btn-success>
_{Msg.LoginViaEmail}
<a href="@{tm registerR}" .btn .btn-default>
_{Msg.RegisterLong}
|]
where
dispatch "GET" ["register"] = getRegisterR >>= sendResponse
dispatch "POST" ["register"] = postRegisterR >>= sendResponse
dispatch "GET" ["forgot-password"] = getForgotPasswordR >>= sendResponse
dispatch "POST" ["forgot-password"] = postForgotPasswordR >>= sendResponse
dispatch "GET" ["verify", eid, verkey] =
case fromPathPiece eid of
Nothing -> notFound
Just eid' -> getVerifyR eid' verkey >>= sendResponse
dispatch "POST" ["login"] = postLoginR >>= sendResponse
dispatch "GET" ["set-password"] = getPasswordR >>= sendResponse
dispatch "POST" ["set-password"] = postPasswordR >>= sendResponse
dispatch _ _ = notFound
getRegisterR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) Html
getRegisterR = registerHandler
-- | Default implementation of 'registerHandler'.
--
-- Since: 1.2.6
defaultRegisterHandler :: YesodAuthEmail master => AuthHandler master Html
defaultRegisterHandler = do
email <- newIdent
tp <- getRouteToParent
lift $ authLayout $ do
setTitleI Msg.RegisterLong
[whamlet|
<p>_{Msg.EnterEmail}
<form method="post" action="@{tp registerR}">
<div id="registerForm">
<label for=#{email}>_{Msg.Email}:
<input ##{email} type="email" name="email" width="150" autofocus>
<button .btn>_{Msg.Register}
|]
registerHelper :: YesodAuthEmail master
=> Bool -- ^ allow usernames?
-> Route Auth
-> HandlerT Auth (HandlerT master IO) TypedContent
registerHelper allowUsername dest = do
y <- lift getYesod
midentifier <- lookupPostParam "email"
let eidentifier = case midentifier of
Nothing -> Left Msg.NoIdentifierProvided
Just x
| Just x' <- Text.Email.Validate.canonicalizeEmail (encodeUtf8 x) ->
Right $ normalizeEmailAddress y $ decodeUtf8With lenientDecode x'
| allowUsername -> Right $ TS.strip x
| otherwise -> Left Msg.InvalidEmailAddress
case eidentifier of
Left route -> loginErrorMessageI dest route
Right identifier -> do
mecreds <- lift $ getEmailCreds identifier
registerCreds <-
case mecreds of
Just (EmailCreds lid _ _ (Just key) email) -> return $ Just (lid, key, email)
Just (EmailCreds lid _ _ Nothing email) -> do
key <- liftIO $ randomKey y
lift $ setVerifyKey lid key
return $ Just (lid, key, email)
Nothing
| allowUsername -> return Nothing
| otherwise -> do
key <- liftIO $ randomKey y
lid <- lift $ addUnverified identifier key
return $ Just (lid, key, identifier)
case registerCreds of
Nothing -> loginErrorMessageI dest (Msg.IdentifierNotFound identifier)
Just (lid, verKey, email) -> do
render <- getUrlRender
let verUrl = render $ verifyR (toPathPiece lid) verKey
lift $ sendVerifyEmail email verKey verUrl
lift $ confirmationEmailSentResponse identifier
postRegisterR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
postRegisterR = registerHelper False registerR
getForgotPasswordR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) Html
getForgotPasswordR = forgotPasswordHandler
-- | Default implementation of 'forgotPasswordHandler'.
--
-- Since: 1.2.6
defaultForgotPasswordHandler :: YesodAuthEmail master => AuthHandler master Html
defaultForgotPasswordHandler = do
tp <- getRouteToParent
email <- newIdent
lift $ authLayout $ do
setTitleI Msg.PasswordResetTitle
[whamlet|
<p>_{Msg.PasswordResetPrompt}
<form method="post" action="@{tp forgotPasswordR}">
<div id="registerForm">
<label for=#{email}>_{Msg.ProvideIdentifier}
<input ##{email} type=text name="email" width="150" autofocus>
<button .btn>_{Msg.SendPasswordResetEmail}
|]
postForgotPasswordR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
postForgotPasswordR = registerHelper True forgotPasswordR
getVerifyR :: YesodAuthEmail site
=> AuthEmailId site
-> Text
-> HandlerT Auth (HandlerT site IO) TypedContent
getVerifyR lid key = do
realKey <- lift $ getVerifyKey lid
memail <- lift $ getEmail lid
mr <- lift getMessageRender
case (realKey == Just key, memail) of
(True, Just email) -> do
muid <- lift $ verifyAccount lid
case muid of
Nothing -> invalidKey mr
Just uid -> do
lift $ setCreds False $ Creds "email-verify" email [("verifiedEmail", email)] -- FIXME uid?
lift $ setLoginLinkKey uid
let msgAv = Msg.AddressVerified
selectRep $ do
provideRep $ do
lift $ setMessageI msgAv
fmap asHtml $ redirect setpassR
provideJsonMessage $ mr msgAv
_ -> invalidKey mr
where
msgIk = Msg.InvalidKey
invalidKey mr = messageJson401 (mr msgIk) $ lift $ authLayout $ do
setTitleI msgIk
[whamlet|
$newline never
<p>_{msgIk}
|]
postLoginR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
postLoginR = do
(identifier, pass) <- lift $ runInputPost $ (,)
<$> ireq textField "email"
<*> ireq textField "password"
mecreds <- lift $ getEmailCreds identifier
maid <-
case ( mecreds >>= emailCredsAuthId
, emailCredsEmail <$> mecreds
, emailCredsStatus <$> mecreds
) of
(Just aid, Just email, Just True) -> do
mrealpass <- lift $ getPassword aid
case mrealpass of
Nothing -> return Nothing
Just realpass -> return $
if isValidPass pass realpass
then Just email
else Nothing
_ -> return Nothing
let isEmail = Text.Email.Validate.isValid $ encodeUtf8 identifier
case maid of
Just email ->
lift $ setCredsRedirect $ Creds
(if isEmail then "email" else "username")
email
[("verifiedEmail", email)]
Nothing ->
loginErrorMessageI LoginR $
if isEmail
then Msg.InvalidEmailPass
else Msg.InvalidUsernamePass
getPasswordR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
getPasswordR = do
maid <- lift maybeAuthId
case maid of
Nothing -> loginErrorMessageI LoginR Msg.BadSetPass
Just _ -> do
needOld <- maybe (return True) (lift . needOldPassword) maid
setPasswordHandler needOld
-- | Default implementation of 'setPasswordHandler'.
--
-- Since: 1.2.6
defaultSetPasswordHandler :: YesodAuthEmail master => Bool -> AuthHandler master TypedContent
defaultSetPasswordHandler needOld = do
tp <- getRouteToParent
pass0 <- newIdent
pass1 <- newIdent
pass2 <- newIdent
mr <- lift getMessageRender
selectRep $ do
provideJsonMessage $ mr Msg.SetPass
provideRep $ lift $ authLayout $ do
setTitleI Msg.SetPassTitle
[whamlet|
$newline never
<h3>_{Msg.SetPass}
<form method="post" action="@{tp setpassR}">
<table>
$if needOld
<tr>
<th>
<label for=#{pass0}>Current Password
<td>
<input ##{pass0} type="password" name="current" autofocus>
<tr>
<th>
<label for=#{pass1}>_{Msg.NewPass}
<td>
<input ##{pass1} type="password" name="new" :not needOld:autofocus>
<tr>
<th>
<label for=#{pass2}>_{Msg.ConfirmPass}
<td>
<input ##{pass2} type="password" name="confirm">
<tr>
<td colspan="2">
<input type="submit" value=_{Msg.SetPassTitle}>
|]
postPasswordR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
postPasswordR = do
maid <- lift maybeAuthId
case maid of
Nothing -> loginErrorMessageI LoginR Msg.BadSetPass
Just aid -> do
tm <- getRouteToParent
needOld <- lift $ needOldPassword aid
if not needOld then confirmPassword aid tm else do
current <- lift $ runInputPost $ ireq textField "current"
mrealpass <- lift $ getPassword aid
case mrealpass of
Nothing ->
lift $ loginErrorMessage (tm setpassR) "You do not currently have a password set on your account"
Just realpass
| isValidPass current realpass -> confirmPassword aid tm
| otherwise ->
lift $ loginErrorMessage (tm setpassR) "Invalid current password, please try again"
where
msgOk = Msg.PassUpdated
confirmPassword aid tm = do
(new, confirm) <- lift $ runInputPost $ (,)
<$> ireq textField "new"
<*> ireq textField "confirm"
if new /= confirm
then loginErrorMessageI setpassR Msg.PassMismatch
else do
isSecure <- lift $ checkPasswordSecurity aid new
case isSecure of
Left e -> lift $ loginErrorMessage (tm setpassR) e
Right () -> do
salted <- liftIO $ saltPass new
y <- lift $ do
setPassword aid salted
deleteSession loginLinkKey
setMessageI msgOk
getYesod
mr <- lift getMessageRender
selectRep $ do
provideRep $
fmap asHtml $ lift $ redirect $ afterPasswordRoute y
provideJsonMessage (mr msgOk)
saltLength :: Int
saltLength = 5
-- | Salt a password with a randomly generated salt.
saltPass :: Text -> IO Text
saltPass = fmap (decodeUtf8With lenientDecode)
. flip PS.makePassword 14
. encodeUtf8
saltPass' :: String -> String -> String
saltPass' salt pass =
salt ++ T.unpack (TE.decodeUtf8 $ B16.encode $ H.hash $ TE.encodeUtf8 $ T.pack $ salt ++ pass)
isValidPass :: Text -- ^ cleartext password
-> SaltedPass -- ^ salted password
-> Bool
isValidPass ct salted =
PS.verifyPassword (encodeUtf8 ct) (encodeUtf8 salted) || isValidPass' ct salted
isValidPass' :: Text -- ^ cleartext password
-> SaltedPass -- ^ salted password
-> Bool
isValidPass' clear' salted' =
let salt = take saltLength salted
in salted == saltPass' salt clear
where
clear = TS.unpack clear'
salted = TS.unpack salted'
-- | Session variable set when user logged in via a login link. See
-- 'needOldPassword'.
--
-- Since 1.2.1
loginLinkKey :: Text
loginLinkKey = "_AUTH_EMAIL_LOGIN_LINK"
-- | Set 'loginLinkKey' to the current time.
--
-- Since 1.2.1
setLoginLinkKey :: (YesodAuthEmail site, MonadHandler m, HandlerSite m ~ site) => AuthId site -> m ()
setLoginLinkKey aid = do
now <- liftIO getCurrentTime
setSession loginLinkKey $ TS.pack $ show (toPathPiece aid, now)
| pikajude/yesod | yesod-auth/Yesod/Auth/Email.hs | mit | 21,109 | 0 | 24 | 6,389 | 3,973 | 2,044 | 1,929 | 341 | 10 |
module GitSystem(filesModifiedByCommitString,
gitLogString) where
import System.Process
import Git
filesModifiedByCommitString :: FilePath -> String -> IO String
filesModifiedByCommitString repoPath commitStr =
readProcess "git" ["-C", repoPath, "diff-tree", "--no-commit-id", "--name-only", "-r", commitStr] []
gitLogString :: FilePath -> IO String
gitLogString repoPath =
readProcess "git" ["-C", repoPath, "log"] []
| dillonhuff/GitVisualizer | src/GitSystem.hs | gpl-2.0 | 444 | 0 | 7 | 70 | 114 | 64 | 50 | 10 | 1 |
{- |
Module : Cover
Description : Cover relation between processes
Maintainer : [email protected]
This module defines a function @isCovered@ checking if a process is covered by
another.
The implementation consists of an improved version of Ullmann's sub-graph
isomorphism algorithm.
-}
module Language.PiCalc.Semantics.Cover(
module Language.PiCalc.Semantics.Cover
) where
import Language.PiCalc.Syntax
import Data.Array(bounds)
-- import Data.List (partition, minimumBy)
import Data.Map(Map,(!))
import qualified Data.Map as Map
import Data.Set(Set)
import qualified Data.Set as Set
import Data.MultiSet(MultiSet)
import qualified Data.MultiSet as MSet
-- TESTING -----------------------------------
-- import Text.PrettyPrint
import Language.PiCalc.Pretty
import Debug.Trace
----------------------------------------------
import Data.Graph
-- import Data.Array
import Data.Graph.Ullmann
import Language.PiCalc.Semantics.Substitutions
import Language.PiCalc.Syntax.Congruence
coveredBy :: StdNFTerm -> StdNFTerm -> Bool
coveredBy small big = not $ failedMatch $ coverMatches small big
coverMatches:: StdNFTerm -> StdNFTerm -> [Match]
coverMatches small big'
| isStdZero small = [emptyMatch]
| isStdZero big' = noMatch
| otherwise = subGraphIso semant candidates graphS graphB
where
big = renameStd trasl big'
(graphS, fstSeqS, vert2nodeS, name2vertS) = stdGraph small
(graphB, fstSeqB, vert2nodeB, name2vertB) = stdGraph big
lstSeqS = snd $ bounds graphS
lstSeqB = snd $ bounds graphB
semant = checkMatch vert2nodeB name2vertB vert2nodeS name2vertS
candidates = [ candidate i js | i <- Map.elems name2vertS, let js = Map.elems name2vertB]
++ [ candidate i js | i <- [fstSeqS..lstSeqS]
, let (Right fS) = vert2nodeS ! i
, let js = [ j | j <- [fstSeqB..lstSeqB]
, let (Right fB) = vert2nodeB ! j
, Set.size (restrNames fS) == Set.size (restrNames fB)
]
]
trasl x = x{unique=maxNameS + (unique x)}
maxNameS
| Map.null name2vertS = 0
| otherwise = 1 + (unique $ fst $ Map.findMax name2vertS)
stdGraph :: StdNFTerm -> (Graph, Vertex, Map Vertex (Either PiName StdFactor), Map PiName Vertex)
stdGraph (StdNF s)
| MSet.null s = (buildG (0,0) [], 0, Map.empty, Map.empty)
| otherwise = (buildG (fstIx, lastIx) edgeList, fstSeq, vert2node, name2vert)
where
nameNodes = zip [fstIx.. ] [Left n | n <- Set.toAscList names]
seqNodes = zip [fstSeq..] [Right f | f <- seqs]
name2vert = Map.fromDistinctAscList $ zip (Set.toAscList names) [fstIx..]
fstSeq = Set.size names
fstIx = 0
lastIx = fstSeq + (MSet.size s) -1
nodes = nameNodes ++ seqNodes
vert2node = Map.fromDistinctAscList $ nodes
edgeList = [ (name2vert ! x, j) |
(j,Right f) <- seqNodes,
x <- Set.elems $ restrNames f ]
names = Set.unions [restrNames f | f <- MSet.distinctElems s]
seqs = MSet.elems s
-- Precondition: all names have been matched when trying to match a seq term
checkMatch :: Map Vertex (Either PiName StdFactor)
-> Map PiName Vertex
-> Map Vertex (Either PiName StdFactor)
-> Map PiName Vertex
-> NodeSemantics
checkMatch v2nodeG name2vG v2nodeP name2vP match w v =
case (v2nodeP ! w, v2nodeG ! v) of
(Left _, Left _) -> True
(Right tP, Right tG) ->
-- let a = (rename globalise $ seqTerm tG)
-- b = (rename match2sub $ seqTerm tP)
-- c = congruent a b
-- in if c then traceShow a $ traceShow b $ c else c
congruent (rename globalise $ seqTerm tG) (rename match2sub $ seqTerm tP)
_ -> error "Name matched with seq!"
where
-- globalisation of names is necessary because when comparing seqterms after
-- applying subs names should be the same name (same unique).
-- So to make congruence require identification of those names we put the unique in the
-- static and make the name global.
-- TODO: find a better way to deal with this.
globalise x
| Map.member x name2vG = x{static = show $ unique x, isGlobal=True}
| otherwise = x
match2sub x =
case Map.lookup x name2vP of
Nothing -> x
Just j ->
case Map.lookup j match of
Just i ->
case Map.lookup i v2nodeG of
Just (Left y) -> y{static = show $ unique y, isGlobal=True}
Just (Right _) -> error "Name matched with sequential term!"
Nothing -> error "Node not in graph!"
Nothing -> error "Name not mapped!"
---------------------------------------------------------
-- TESTING
---------------------------------------------------------
-- coverMatches' small big'
-- | isStdZero small = [[]]
-- | isStdZero big' = []
-- | otherwise = map ((map resolveNodes) . Map.toList) $ subGraphIso semant candidates graphS graphB
-- where
-- big = renameStd trasl big'
-- (graphS, fstSeqS, vert2nodeS, name2vertS) = stdGraph small
-- (graphB, fstSeqB, vert2nodeB, name2vertB) = stdGraph big
-- lstSeqS = snd $ bounds graphS
-- lstSeqB = snd $ bounds graphB
-- semant = checkMatch vert2nodeB name2vertB vert2nodeS name2vertS
-- candidates = [ candidate i js | i <- Map.elems name2vertS, let js = Map.elems name2vertB]
-- ++ [ candidate i js | i <- [fstSeqS..lstSeqS]
-- , let (Right fS) = vert2nodeS ! i
-- , let js = [ j | j <- [fstSeqB..lstSeqB]
-- , let (Right fB) = vert2nodeB ! j
-- , Set.size (restrNames fS) == Set.size (restrNames fB)
-- ]
-- ]
-- trasl x = x{unique=maxNameS + (unique x)}
-- untrasl (Left x) = Left x{unique=unique x - maxNameS}
-- untrasl x = x
-- maxNameS
-- | Map.null name2vertS = 0
-- | otherwise = 1 + (unique $ fst $ Map.findMax name2vertS)
-- resolveNodes (v, w) = (vert2nodeS Map.! v, untrasl $ vert2nodeB Map.! w)
-- shMatches ms = unlines $ map (unlines.(map shM)) ms
-- where
-- shM (Left x, Left y) = (show x) ++ " --> " ++ (show y)
-- shM (Right x, Right y) = (show $ pretty $ seqTerm x) ++ " --> " ++ (show $ pretty $ seqTerm y) | bordaigorl/jamesbound | src/Language/PiCalc/Semantics/Cover.hs | gpl-2.0 | 6,565 | 0 | 19 | 1,891 | 1,330 | 714 | 616 | 81 | 7 |
-- Aufgabe 12.4
-- a)
data Expr = TermType Term | NTermType Term | Sum Expr Term | Dif Expr Term deriving Show
data Term = FactorType Factor | Prod Term Factor deriving Show
data Factor = Lit Int | ExprType Expr deriving Show
-- b)
-- Usage in GHCi?
-- Simple example:
-- evalTerm (Prod (FactorType (Lit 4)) (Lit 1))
--
-- We can see, Prod needs some arguments, that are to be found in Term
-- or Factor algebraic types respectivelly. So we need to give them to
-- the function
--
-- Advanced:
-- evalTerm (Prod (FactorType (Lit 4)) (ExprType (TermType (FactorType
-- (Lit 1)))))
--
-- That is actually the same, as the example before, we just do a
-- round-trip trough other algebraic types
evalExpr :: Expr -> Int
evalExpr (TermType a) = evalTerm a
evalExpr (NTermType a) = - (evalTerm a)
evalExpr (Sum a b) = (evalExpr a) + (evalTerm b)
evalExpr (Dif a b) = (evalExpr a) - (evalTerm b)
evalFactor :: Factor -> Int
evalFactor (Lit a) = a
evalFactor (ExprType a) = evalExpr a
evalTerm :: Term -> Int
evalTerm (FactorType a) = evalFactor a
evalTerm (Prod a b) = (evalTerm a) * (evalFactor b)
| KaliszAd/programmierung2012 | aufgabe12_4.hs | gpl-2.0 | 1,109 | 16 | 7 | 221 | 311 | 169 | 142 | 14 | 1 |
module Test.App.Logger (tests) where
import Test.Tasty
import Test.Tasty.HUnit
import qualified Data.Vector as Vector
import App.Logger
import App.Message
tests :: TestTree
tests = testGroup "Logger"
[ loggerAddMessageTests
, loggerNewestMessagesTests
]
loggerAddMessageTests = testGroup "loggerAddString"
[ testCase "add message to new logger" $
Vector.length (loggerMessages $ loggerAddString newLogger "Hello, Logger!") @?= 1
, testCase "add messages to the beginning of list" $
loggerMessages (loggerAddString (loggerAddString newLogger "1") "2")
@?= Vector.fromList (map messageFromString ["2", "1"])
]
loggerNewestMessagesTests = testGroup "loggerNewestMessages"
[ testCase "should return last messages" $
loggerNewestMessages
( foldl loggerAddString newLogger ["1", "2","3", "4", "5", "6", "7"] ) 5
@?= map messageFromString ["7","6","5","4","3"]
]
| triplepointfive/hapi | test/Test/App/Logger.hs | gpl-2.0 | 944 | 0 | 13 | 190 | 235 | 130 | 105 | 21 | 1 |
{-# LANGUAGE BangPatterns #-}
{- MD3.hs; Mun Hon Cheong ([email protected]) 2005
This module has functions to read and animate MD3 models.
credits go to Ben Humphrey who wrote the MD3 tutorial
Yet another module where i'm thinking of using
vertex buffer objects instead of vertex arrays
-}
module MD3 (
readModel,
readWeaponModel,
updateAnim,
setAnim,
MD3Model(..),
Model(..),
MD3Animation(..),
AnimState(..),
drawModel,
death1,
dead1,
death2,
dead2,
death3,
dead3,
gesture,
attack1,
attack2,
dropWeap,
raiseWeap,
stand,
stand2,
walkcr,
walk,
run,
back,
swim,
jump,
land,
jumpb,
landb,
idleLegs,
idlecrLegs,
turn
)where
import Graphics.UI.GLUT
import Foreign
import Foreign.C.Types
import Foreign.C.String
import System.IO hiding (withBinaryFile)
import Control.Exception ( bracket )
import Textures
import Data.HashTable
import Data.Maybe
import Data.List
import Data.Array
import Quaternion
import Data.IORef
import Foreign.Storable
import Foreign.Marshal.Array
-------------------------------------------------------------------------------
-- Types
data MD3Bone =
MD3Bone {
minPos :: (Float,Float,Float),
maxPos :: (Float,Float,Float),
bonePos :: (Float,Float,Float),
bscale :: Float,
creator :: String
} deriving Show
data MD3Header =
MD3Header {
fileID :: String,
version :: Int,
md3FileName :: String,
numFrames :: Int,
numTags :: Int,
numMeshes :: Int,
numMaxSkins :: Int,
headerSize :: Int,
tagStart :: Int,
tagEnd :: Int,
fileSize :: Int
} deriving Show
data MD3Tag =
MD3Tag {
tagName :: String,
tagPos :: (Float,Float,Float),
rotation :: (Float,Float,Float,Float)
} deriving Show
data MD3MeshHeader =
MD3MeshHeader {
meshID :: String,
strName :: String,
numMeshFrames :: Int,
numSkins :: Int,
numVertices :: Int,
numTriangles :: Int,
triStart :: Int,
meshHeaderSize:: Int,
uvStart :: Int,
vertexStart :: Int,
meshSize :: Int
} deriving Show
data MD3Vertex =
MD3Vertex {
vert :: (Float,Float,Float),
norm :: (CUChar,CUChar)
} deriving Show
data Model =
Model {
modelRef :: !MD3Model,
weapFire :: IORef (Maybe (IO())),
pitch :: IORef (Maybe (IO())),
upperState :: IORef AnimState,
lowerState :: IORef AnimState
}
data MD3Model =
MD3Model {
numOfTags :: Int,
modelObjects :: [MeshObject],
links :: [(MD3Model,IORef(AnimState))],
auxFunc :: IORef(Maybe (IO())),
auxFunc2 :: IORef(Maybe (IO())),
tags :: Array Int [((Float,Float,Float),
(Float,Float,Float,Float))]
} |
MD3Weapon {
wmodelObjects :: IORef [MeshObject]
}
data MeshObject =
MeshObject {
numOfVerts :: Int,
numOfFaces :: NumArrayIndices,
numTexVertex :: Int,
materialID :: Maybe TextureObject,
bHasTexture :: Bool,
objName :: String,
verticesp :: Array Int (Ptr Float),
normals :: [(Float,Float,Float)],
texCoordsl :: [((Float,Float),(Float,Float),(Float,Float))],
texCoords :: Ptr Float,
vertPtr :: Ptr Float,
numIndices :: GLsizei,
vertIndex :: Ptr CInt,
indexBuf :: BufferObject,
texBuf :: BufferObject,
vertBuf :: BufferObject
}
data MD3Animation =
MD3Animation {
animName :: String,
startFrame :: Int,
endFrame :: Int,
loopFrames :: Int,
fp :: Float
} deriving Show
data AnimState =
AnimState {
anims :: !(Array Int MD3Animation),
currentAnim :: !MD3Animation,
currentFrame :: !Int,
nextFrame :: !Int,
currentTime :: !Float,
lastTime :: !Float
}
type MD3Face = (Int,Int,Int)
type MD3TexCoord = (Float,Float)
-------------------------------------------------------------------------------
-- A list of animations stored in MD3 files
animList :: [String]
animList = ["BOTH_DEATH1", --The first twirling death animation
"BOTH_DEAD1", --The end of the first twirling death animation
"BOTH_DEATH2", --The second twirling death animation
"BOTH_DEAD2", --The end of the second twirling death animation
"BOTH_DEATH3", --The back flip death animation
"BOTH_DEAD3", --The end of the back flip death animation
"TORSO_GESTURE", --The torso's gesturing animation
"TORSO_ATTACK", --The torso's attack1 animation
"TORSO_ATTACK2", --The torso's attack2 animation
"TORSO_DROP", --The torso's weapon drop animation
"TORSO_RAISE", --The torso's weapon pickup animation
"TORSO_STAND", --The torso's idle stand animation
"TORSO_STAND2", --The torso's idle stand2 animation
"LEGS_WALKCR", --The legs's crouching walk animation
"LEGS_WALK", --The legs's walk animation
"LEGS_RUN", --The legs's run animation
"LEGS_BACK", --The legs's running backwards animation
"LEGS_SWIM", --The legs's swimming animation
"LEGS_JUMP", --The legs's jumping animation
"LEGS_LAND", --The legs's landing animation
"LEGS_JUMPB", --The legs's jumping back animation
"LEGS_LANDB", --The legs's landing back animation
"LEGS_IDLE", --The legs's idle stand animation
"LEGS_IDLECR", --The legs's idle crouching animation
"LEGS_TURN"] --The legs's turn animation
-- animation index
death1 :: Int
death1 = 0
dead1 :: Int
dead1 = 1
death2 :: Int
death2 = 2
dead2 :: Int
dead2 = 3
death3 :: Int
death3 = 4
dead3 :: Int
dead3 = 5
gesture :: Int
gesture = 6
attack1 :: Int
attack1 = 7
attack2 :: Int
attack2 = 8
dropWeap :: Int
dropWeap = 9
raiseWeap :: Int
raiseWeap = 10
stand :: Int
stand = 11
stand2 :: Int
stand2 = 12
walkcr :: Int
walkcr = 6
walk :: Int
walk = 7
run :: Int
run = 8
back :: Int
back = 9
swim :: Int
swim = 10
jump :: Int
jump = 11
land :: Int
land = 12
jumpb :: Int
jumpb = 13
landb :: Int
landb = 14
idleLegs :: Int
idleLegs = 15
idlecrLegs :: Int
idlecrLegs = 16
turn :: Int
turn = 17
-------------------------------------------------------------------------------
-- Functions for updating animations
-- sets the animation in the animation state
setAnim :: (Int,AnimState) -> AnimState
setAnim (animIndex,animState)
| (animName newAnim) == (animName (currentAnim animState)) = animState
| otherwise = AnimState {
anims = anims animState,
currentAnim = newAnim,
currentFrame = startFrame newAnim,
nextFrame = nextFrame animState,
currentTime = currentTime animState,
lastTime = lastTime animState
}
where newAnim = (anims animState)! animIndex
-- updates the animation
updateAnim :: (Int,Double,AnimState) -> (Bool,AnimState)
updateAnim (animIndex,time,animState)
| snd(Data.Array.bounds(anims animState)) == 0 =
let
(haslooped,nextNF) =
cycleFrame cAnim 0 1 (currentFrame animStateN)
(t,lastT,nextCF) =
updateTime (lastTime animStateN)
(currentFrame animStateN) nextNF cAnim time
in (haslooped,AnimState {
anims = anims animStateN ,
currentAnim = currentAnim animStateN,
currentFrame = nextCF + 0,
nextFrame = nextNF + 0,
currentTime = t + 0,
lastTime = lastT + 0
})
| otherwise =
let
(haslooped,nextNF) =
cycleFrame cAnim (startFrame cAnim)
(endFrame cAnim) (currentFrame animStateN)
(t,lastT,nextCF) =
updateTime (lastTime animStateN)
(currentFrame animStateN) nextNF cAnim time
in (haslooped,AnimState {
anims = anims animStateN,
currentAnim = currentAnim animStateN ,
currentFrame = nextCF + 0,
nextFrame = nextNF + 0,
currentTime = t + 0,
lastTime = lastT + 0
})
where
animStateN = setAnim (animIndex,animState)
cAnim = (currentAnim animStateN)
-- increment the frame
cycleFrame :: MD3Animation -> Int -> Int -> Int -> (Bool,Int)
cycleFrame _ startframe endframe currentframe
| currentframe == (endframe-2) = (True,nextFrme)
| nextFrme == 0 = (False,startframe)
| otherwise = (False,nextFrme)
where
nextFrme = (currentframe + 1) `mod` endframe
updateTime :: Float -> Int -> Int -> MD3Animation-> Double ->(Float,Float,Int)
updateTime lasttime currentframe nextframe anim presentTime =
let
animSpeed = (fp anim)
presentTimef = 1000*(realToFrac presentTime)
elapsedtime = presentTimef - lasttime
t = elapsedtime/animSpeed
in case ((realToFrac elapsedtime) >= animSpeed) of
True -> (t,presentTimef ,nextframe)
_ -> (t,lasttime,currentframe)
-------------------------------------------------------------------------------
-- renders the model
drawModel :: (MD3Model,IORef(AnimState)) -> IO( )
drawModel (model,stateRef) = do
texture Texture2D $= Enabled
--texture Texture2D $= Disabled
clientState TextureCoordArray $= Enabled
clientState VertexArray $= Enabled
--clientState VertexArray $= Disabled
--clientState TextureCoordArray $= Disabled
animState <- readIORef stateRef
mapM (drawObject animState) (modelObjects model)
let currentTag = (tags model)!(currentFrame animState)
let nextTag = (tags model)!(nextFrame animState)
aux <- readIORef (auxFunc model)
aux2 <- readIORef (auxFunc2 model)
case aux2 of
Just func -> func
Nothing -> return ()
recurseDraw (currentTime animState) aux (links model) currentTag nextTag
texture Texture2D $= Disabled
recurseDraw :: Float ->
Maybe (IO())-> [(MD3Model,IORef(AnimState))] ->
[((Float,Float,Float),(Float,Float,Float,Float))] ->
[((Float,Float,Float),(Float,Float,Float,Float))] -> IO()
recurseDraw _ _ [] _ _ = return ()
recurseDraw t func ((model,state):mss)
(((c1,c2,c3),quat1):ccqs) (((n1,n2,n3),quat2):ncqs) = do
let (i1,i2,i3) = (c1+(t*(n1-c1)), c2+(t*(n2-c2)), c3+(t*(n3-c3)))
let iquat = slerp quat1 quat2 t
mat <- quat2Mat iquat (i1,i2,i3)
unsafePreservingMatrix $ do
multMatrix mat
case func of
Just f -> f
Nothing -> return ()
drawModel (model,state)
recurseDraw t func mss ccqs ncqs
-- draws a mesh object with vertex arrays
drawObject :: AnimState -> MeshObject -> IO ()
drawObject animState obj = do
let curindex = (currentFrame animState)
let nextIndex = (nextFrame animState)
case (curindex /= nextIndex) of
True -> do
convertToVertArray
(currentTime animState)
((verticesp obj)!curindex)
((verticesp obj)!nextIndex)
(vertPtr obj) 0 (numOfVerts obj)
arrayPointer VertexArray $=
VertexArrayDescriptor 3 Float 0 (vertPtr obj)
_ -> do
arrayPointer VertexArray $=
VertexArrayDescriptor 3 Float 0 ((verticesp obj)!curindex)
{-clientState VertexArray $= Enabled
lockArrays $= (Just (0, (numOfFaces obj)))-}
arrayPointer TextureCoordArray $=
VertexArrayDescriptor 2 Float 0 (texCoords obj)
{-clientState TextureCoordArray $= Enabled
texture Texture2D $= Enabled-}
textureBinding Texture2D $= (materialID obj)
{-lockArrays $= (Just (0, (numOfFaces obj)))
drawElements Triangles (numOfFaces obj) UnsignedInt (vertIndex obj)-}
drawRangeElements Triangles (0,(numOfFaces obj))
(numOfFaces obj) UnsignedInt (vertIndex obj)
{-lockArrays $= Nothing
clientState VertexArray $= Disabled
clientState TextureCoordArray $= Disabled
texture Texture2D $= Disabled-}
convertToVertArray ::
Float -> Ptr Float -> Ptr Float -> Ptr Float -> Int -> Int ->IO()
convertToVertArray t cs ns arr ind limit
| ind == limit= return()
| otherwise = do
c <- peekElemOff cs ind
n <- peekElemOff ns ind
pokeElemOff arr ind (i c n)
convertToVertArray t cs ns arr (ind+1) limit
where i x y = x+(t*(y-x))
-------------------------------------------------------------------------------
-- reads the MD3 files
readMD3Header :: Handle -> IO MD3Header
readMD3Header handle = do
buf <- mallocBytes 108
hGetBuf handle buf 108
fID <- getString buf 4
ver <- peek (plusPtr (castPtr buf :: Ptr CInt) 4)
mfilename <- getString (plusPtr buf 8) 68
[i1,i2,i3,i4,i5,i6,i7,i8] <- getInts (plusPtr buf 76) 8
free buf
return $ MD3Header {
fileID = fID,
version = ver,
md3FileName = mfilename,
numFrames = i1,
numTags = i2,
numMeshes = i3,
numMaxSkins = i4,
headerSize = i5,
tagStart = i6,
tagEnd = i7,
fileSize = i8
}
-- - - - - - - - - - - - - - - - - - -
-- reads the .skin files
readMD3Skin :: FilePath -> IO [(String,String)]
readMD3Skin filepath = withBinaryFile filepath $ \handle -> do
contents <- hGetContents handle
let filteredStr = (words (replace contents))
let files = findfiles (stripTags filteredStr)
case (files == []) of
True -> return []
False -> return files
stripTags :: [String] -> [String]
stripTags [] = []
stripTags (s:ss)
| (head (words(map (replace' ['_']) s))) == "tag" = stripTags ss
| otherwise = s:(stripTags ss)
-- - - - - - - - - - - - - - - - - - -
-- reads the shader file for the weapon
readMD3Shader :: FilePath -> IO [String]
readMD3Shader filepath = withBinaryFile filepath $ \handle -> do
contents <- hGetContents handle
let filteredStr = (words (replace contents))
let files = map stripExt filteredStr
case (files == []) of
True -> return []
False -> return files
-- - - - - - - - - - - - - - - - - - -
-- used by readShader and readSkin
stripExt :: String -> String
stripExt str = (head (words(map (replace' ['.']) str)))
findfiles :: [String] -> [(String,String)]
findfiles [] = []
findfiles (s:ss) = (s,(stripExt(stripPath (head ss)))):(findfiles (tail ss))
replace :: String -> String
replace str = map (replace' [',','\n','\r']) str
replace' :: [Char] -> Char -> Char
replace' list char
| elem char list = ' '
| otherwise = char
stripPath :: String -> String
stripPath str = splitPath!!((length splitPath)-1)
where splitPath = (words (map (replace' ['/']) str))
-- - - - - - - - - - - - - - - - - - -
-- reads the textures
readMD3Textures ::
[FilePath] -> String ->
IO (HashTable String (Maybe TextureObject))
readMD3Textures files dir = do
texs <- mapM readMD3Skin files
let texF = concat texs
let unqtex = nub (map snd texF)
textures <- mapM getAndCreateTexture (map (dir++) unqtex)
let nmobj = concat $ map (assoc texF) (zip unqtex textures)
fromList hashString nmobj
assoc ::
[(String,String)] -> (String,Maybe TextureObject) ->
[(String,Maybe TextureObject)]
assoc list (c,d) = zip (map fst (filter ((c ==).snd) list)) (cycle[d])
-- - - - - - - - - - - - - - - - - - -
-- reads the entire model
readModel :: String -> Model -> IO (Model)
readModel modelname weaponModel = do
hash <- readMD3Textures
(map (("tga/models/players/"++modelname)++)
["/head_default.skin",
"/upper_default.skin",
"/lower_default.skin"])
("models/players/"++modelname++"/")
get elapsedTime
weaponAS <- noAnims
headAS <- noAnims
(upperanims,loweranims) <-
readAnimations ("tga/models/players/"++modelname++"/animation.cfg")
let lowerS = AnimState {
anims = loweranims,
currentAnim = loweranims!8,
currentFrame = (startFrame (loweranims!8)),
nextFrame = 0,
currentTime = 0,
lastTime = 0
}
let upperS = AnimState {
anims = upperanims,
currentAnim = upperanims!6,
currentFrame = (startFrame (upperanims!6)),
nextFrame = 0,
currentTime = 0,
lastTime = 0
}
lowerstate <- newIORef lowerS
upperstate <- newIORef upperS
hed <- readMD3 ("tga/models/players/"++modelname++"/head.md3") hash []
let weapon = modelRef weaponModel
upper <- readMD3
("tga/models/players/"++modelname++"/upper.md3")
hash [("tag_weapon",(weapon,weaponAS)),("tag_head",(hed,headAS))]
lower <- readMD3
("tga/models/players/"++modelname++"/lower.md3")
hash [("tag_torso",(upper,upperstate))]
return Model {
modelRef = lower,
pitch = auxFunc lower,
weapFire = auxFunc2 weapon,
upperState = upperstate,
lowerState = lowerstate
}
-- just returns an empty animation
noAnims :: IO (IORef(AnimState))
noAnims = do
let noanim =
MD3Animation {
animName = "",
startFrame = 0,
endFrame = 0,
loopFrames = 0,
fp = 0
}
let noanimState =
AnimState {
anims = listArray (0,0) [],
currentAnim = noanim,
currentFrame = 0,
nextFrame = 0,
currentTime = 0,
lastTime = 0
}
newIORef noanimState
-- - - - - - - - - - - - - - - - - - -
-- reads a .MD3 file
readMD3 :: FilePath ->
(HashTable String (Maybe TextureObject))->
[(String,(MD3Model,IORef(AnimState)))] -> IO MD3Model
readMD3 filePath hashtable lns = withBinaryFile filePath $ \handle -> do
header <- readMD3Header handle
readBones handle header
tag <- readTags handle header
objs <- readMeshes handle header hashtable
let splittedTags = splitTags (numTags header) tag
orderedlinks <- scanTag lns tag
let trimmedTags = trimTags (map fst orderedlinks) splittedTags
let trimmedArray = listArray (0,((length trimmedTags)-1)) trimmedTags
aux <- newIORef (Nothing)
aux2 <- newIORef (Nothing)
return MD3Model {
numOfTags = numTags header,
modelObjects = objs,
links = (map snd orderedlinks),
auxFunc = aux,
auxFunc2 = aux2,
tags = trimmedArray
}
scanTag :: [(String,(MD3Model,IORef(AnimState)))] -> [MD3Tag] -> IO [(Int,(MD3Model,IORef(AnimState)))]
scanTag [] _ = return []
scanTag ((s,m):sms) tgs = do
case (findIndex ((s==) . tagName)tgs) of
Just x -> do
rest <- (scanTag sms tgs)
return ((x,m):rest)
splitTags :: Int -> [MD3Tag] -> [[MD3Tag]]
splitTags _ [] = []
splitTags n tgs = (take n tgs):(splitTags n $ drop n tgs)
trimTags ::
[Int] ->
[[MD3Tag]] ->
[[((Float,Float,Float),(Float,Float,Float,Float))]]
trimTags _ [] = []
trimTags n (t:ts) = (map (getTagpos.(t!!)) n):(trimTags n ts)
where getTagpos u = (tagPos u, rotation u)
-- - - - - - - - - - - - - - - - - - -
-- read the weapon models
readWeaponModel :: FilePath -> FilePath -> IO Model
readWeaponModel filePath shader = do
weapon <- readWeapon filePath shader
anim <- noAnims
p <- newIORef (Nothing)
wf <- newIORef (Nothing)
return Model {
modelRef = weapon,
pitch = p,
weapFire = wf,
upperState =anim,
lowerState =anim
}
readWeapon :: FilePath -> FilePath -> IO MD3Model
readWeapon filePath shader = withBinaryFile filePath $ \handle -> do
header <- readMD3Header handle
weaponTex <- (readMD3Shader shader)
texObj <- mapM getAndCreateTexture (map ("tga/models/weapons/"++) weaponTex)
readBones handle header
readTags handle header
hash1 <- (fromList hashString [])
objs <- readMeshes handle header hash1
let objs2 = map attachTex (zip texObj objs)
let emptyList = listArray (0,0) []
aux <- newIORef (Nothing)
aux2 <- newIORef (Nothing)
return MD3Model {
numOfTags = 0,
modelObjects = objs2,
links = [],
auxFunc = aux,
auxFunc2 = aux2,
tags = emptyList
}
-- attaches the texture to the weapon
attachTex :: (Maybe TextureObject,MeshObject) -> MeshObject
attachTex (texObj,object) =
MeshObject {
numOfVerts = numOfVerts object,
numOfFaces = numOfFaces object,
numTexVertex = numTexVertex object,
materialID = texObj,
bHasTexture = True,
objName = objName object,
verticesp = verticesp object,
normals = normals object,
texCoordsl = texCoordsl object,
texCoords = texCoords object,
vertPtr = vertPtr object,
numIndices = numIndices object,
vertIndex = vertIndex object,
indexBuf = indexBuf object,
texBuf = texBuf object,
vertBuf = vertBuf object
}
-- - - - - - - - - - - - - - - - - - -
-- reads the mesh information
readMeshes ::
Handle -> MD3Header ->
(HashTable String (Maybe TextureObject)) -> IO [MeshObject]
readMeshes handle header hashTable= do
posn <- hTell handle
meshObjects <- readMeshData handle posn (numMeshes header) hashTable
return meshObjects
readMeshData ::
Handle -> Integer -> Int ->
(HashTable String (Maybe TextureObject)) -> IO [MeshObject]
readMeshData handle posn meshesLeft hashTable
| meshesLeft <= 0 = return []
| otherwise = do
header <- readMD3MeshHeader handle
readSkins handle header
faces <- readFaces handle posn header
texcoords <- readTexCoords handle posn header
vertices <- readVertices handle posn header
hSeek handle AbsoluteSeek (posn+(fromIntegral (meshSize header)))
object <- convertMesh header faces texcoords vertices hashTable
objects <-
readMeshData handle
(posn+(fromIntegral (meshSize header))) (meshesLeft-1) hashTable
return (object:objects)
-- - - - - - - - - - - - - - - - - - -
-- converts the vertex, texture, face information into
-- a meshobject
convertMesh :: MD3MeshHeader ->
[MD3Face] -> [MD3TexCoord] -> [MD3Vertex] ->
(HashTable String (Maybe TextureObject)) -> IO MeshObject
convertMesh header faceIndex texcoords vertices hashTable = do
let verts = map vert vertices
let scaledVerts = map devideBy64 verts
let keyframes = devideIntoKeyframes (numVertices header) scaledVerts
imPTR <- mapM (Foreign.Marshal.Array.newArray) (map convertVert keyframes)
let facesArrayp = listArray (0,((length imPTR)-1)) imPTR
uvs <- convertTex faceIndex texcoords
uvptr <- Foreign.Marshal.Array.newArray (convertTex2 texcoords)
indces <- Foreign.Marshal.Array.newArray (convertInd faceIndex)
vPtr <- mallocBytes ((length (head keyframes))*12)
[a] <- genObjectNames 1
{-bindBuffer ArrayBuffer $= Just a
bufferData ArrayBuffer $=
(fromIntegral (3*((length (head keyframes))*3)*4),
facesArrayp!0 , StaticDraw)
arrayPointer VertexArray $=
VertexArrayDescriptor 3 Float 0 nullPtr-}
[b] <- genObjectNames 1
{-bindBuffer ArrayBuffer $= Just b
bufferData ArrayBuffer $=
(fromIntegral (4*(length (convertTex2 texcoords))),
uvptr, StaticDraw)
arrayPointer TextureCoordArray $=
VertexArrayDescriptor 2 Float 0 nullPtr-}
[c] <- genObjectNames 1
{-bindBuffer ElementArrayBuffer $= Just c
bufferData ElementArrayBuffer $=
(fromIntegral ((fromIntegral (length (head faces)))*12),
indices, StaticDraw)
arrayPointer TextureCoordArray $=
VertexArrayDescriptor 2 Float 0 nullPtr-}
tex <- (Data.HashTable.lookup hashTable (strName header))
return MeshObject {
numOfVerts = (length (head keyframes))*3,
numOfFaces = 3*(fromIntegral (numTriangles header)),
numTexVertex = numVertices header,
materialID = fromJust tex,
bHasTexture = False,
objName = strName header,
verticesp = facesArrayp,
normals = [],
texCoords = uvptr,
texCoordsl = uvs,
vertPtr = vPtr,
numIndices = fromIntegral ((numTriangles header)*3),
vertIndex = indces,
indexBuf = c,
texBuf = b,
vertBuf = a
}
convertInd :: [(Int,Int,Int)] -> [CInt]
convertInd [] = []
convertInd ((i1,i2,i3):is) =
[fromIntegral i1,fromIntegral i2,fromIntegral i3]++(convertInd is)
convertTex2 :: [(Float,Float)] -> [Float]
convertTex2 [] = []
convertTex2 ((u,v):uvs) = [u,v]++(convertTex2 uvs)
convertVert :: [(Float,Float,Float)] -> [Float]
convertVert [] = []
convertVert ((x,y,z):xyzs) = [x,y,z]++(convertVert xyzs)
convertTex ::
[(Int,Int,Int)] ->
[(Float,Float)] ->
IO [((Float,Float),(Float,Float),(Float,Float))]
convertTex indces uvs = do
let uvarray = listArray (0,((length uvs)-1)) uvs
let uv = map (getUVs uvarray) indces
return uv
getUVs ::
Array Int (Float,Float) ->
(Int,Int,Int) ->
((Float,Float),(Float,Float),(Float,Float))
getUVs uvs (i1,i2,i3) = (uvs ! i1, uvs ! i2 , uvs ! i3)
devideIntoKeyframes :: Int ->
[(Float,Float,Float)] -> [[(Float,Float,Float)]]
devideIntoKeyframes _ [] = []
devideIntoKeyframes n verts =
(take n verts):(devideIntoKeyframes n (drop n verts))
devideBy64 :: (Float,Float,Float) -> (Float,Float,Float)
devideBy64 (x,y,z) = (x / 64,y /64,z / 64)
-- - - - - - - - - - - - - - - - - - -
-- reads the vertices
readVertices ::
Handle -> Integer -> MD3MeshHeader -> IO [MD3Vertex]
readVertices handle posn header = do
hSeek handle AbsoluteSeek (posn+(fromIntegral (vertexStart header)))
buf <- mallocBytes ((numMeshFrames header)*(numVertices header)*8)
hGetBuf handle buf ((numMeshFrames header)*(numVertices header)*8)
let ptrs = getPtrs buf ((numMeshFrames header)*(numVertices header)) 8
triangles <- mapM readVertex ptrs
free buf
return triangles
readVertex :: Ptr a -> IO MD3Vertex
readVertex ptr = do
[f1,f2,f3] <- peekArray 3 (castPtr ptr :: Ptr CShort)
[n1,n2] <- peekArray 2 (plusPtr (castPtr ptr :: Ptr CUChar) 6)
return MD3Vertex {
vert =(realToFrac f1,realToFrac f2,realToFrac f3),
norm = (n1,n2)
}
-- - - - - - - - - - - - - - - - - - -
-- reads the texture coordinates
readTexCoords :: Handle -> Integer -> MD3MeshHeader -> IO [MD3TexCoord]
readTexCoords handle posn header = do
hSeek handle AbsoluteSeek (posn+(fromIntegral (uvStart header)))
buf <- mallocBytes ((numVertices header)*8)
hGetBuf handle buf ((numVertices header)*8)
let ptrs = getPtrs buf (numVertices header) 8
texcoords <- mapM readTexCoord ptrs
free buf
return texcoords
readTexCoord :: Ptr a -> IO MD3TexCoord
readTexCoord ptr = do [f1,f2] <- getFloats ptr 2
return (f1,f2)
-- - - - - - - - - - - - - - - - - - -
-- reads the models faces
readFaces :: Handle -> Integer -> MD3MeshHeader -> IO [MD3Face]
readFaces handle posn header = do
hSeek handle AbsoluteSeek (posn+(fromIntegral (triStart header)))
buf <- mallocBytes ((numTriangles header)*12)
hGetBuf handle buf ((numTriangles header)*12)
let ptrs = getPtrs buf (numTriangles header) 12
faces <- mapM readFace ptrs
free buf
return faces
readFace :: Ptr a -> IO MD3Face
readFace ptr = do
[f1,f2,f3] <- getInts ptr 3
return (f1,f2,f3)
-- - - - - - - - - - - - - - - - - - -
-- reads the MD3 skins
readSkins ::Handle -> MD3MeshHeader -> IO [String]
readSkins handle header = do
buf <- mallocBytes ((numSkins header)*68)
hGetBuf handle buf ((numSkins header)*68)
let skinPtrs = getPtrs buf (numSkins header) 68
skins <- mapM readSkin skinPtrs
free buf
return skins
readSkin :: Ptr a -> IO String
readSkin buf = do
skin <- getString buf 68
return skin
-- - - - - - - - - - - - - - - - - - -
-- reads a meshheader
readMD3MeshHeader :: Handle -> IO MD3MeshHeader
readMD3MeshHeader handle = do
buf <- mallocBytes 108
hGetBuf handle buf 108
mID <- getString buf 4
meshName <- getString (plusPtr buf 4) 68
[i1,i2,i3,i4,i5,i6,i7,i8,i9] <- getInts (plusPtr buf 72) 9
free buf
return $
MD3MeshHeader {
meshID = mID,
strName = meshName,
numMeshFrames = i1,
numSkins = i2,
numVertices = i3,
numTriangles = i4,
triStart = i5,
meshHeaderSize= i6,
uvStart = i7,
vertexStart = i8,
meshSize = i9
}
-- - - - - - - - - - - - - - - - - - -
-- reads the tags
readTags :: Handle -> MD3Header -> IO [MD3Tag]
readTags handle header = do
buf <- mallocBytes (112*(numFrames header)*(numTags header))
hGetBuf handle buf (112*(numFrames header)*(numTags header))
let ptrs = getPtrs buf ((numFrames header)*(numTags header)) 112
tgs <- mapM readTag ptrs
free buf
return tgs
readTag :: Ptr a -> IO MD3Tag
readTag buf = do
tName <- getString buf 64
[f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12] <- getFloats (plusPtr buf 64) 12
let quat = mat2Quat ((f4,f5,f6),(f7,f8,f9),(f10,f11,f12))
return $ MD3Tag {
tagName = tName,
tagPos =(f1,f2,f3),
rotation = quat
}
-- - - - - - - - - - - - - - - - - - -
-- reads the bones which we don't use
readBones :: Handle -> MD3Header -> IO [MD3Bone]
readBones handle header = do
buf <- mallocBytes (56*(numFrames header))
hGetBuf handle buf (56*(numFrames header))
let ptrs = getPtrs buf (numFrames header) 56
bones <- mapM readBone ptrs
free buf
return bones
readBone :: Ptr a-> IO MD3Bone
readBone buf = do
[f1,f2,f3,f4,f5,f6,f7,f8,f9,f10] <- getFloats buf 10
string <- getString (plusPtr buf 40) 16
return MD3Bone {
minPos = (f1,f2,f3),
maxPos = (f4,f5,f6),
bonePos = (f7,f8,f9),
bscale = f10,
creator = string
}
-- - - - - - - - - - - - - - - - - - -
-- reads animations from the animation.cfg file
readAnimations ::
FilePath -> IO (Array Int MD3Animation,Array Int MD3Animation)
readAnimations filepath = withBinaryFile filepath $ \handle -> do
lnes <- readLines handle
animsl <- mapM readAnimation lnes
let anms = concat animsl
let upperAnims = filter (matchPrefix "TORSO") anms
let lowerAnims = filter (matchPrefix "LEGS") anms
let bothAnims = filter (matchPrefix "BOTH") anms
let fixedLower =
map (fixLower $ (startFrame $ head lowerAnims)-
(startFrame $ head upperAnims)) lowerAnims
return (listArray
(0,((length (bothAnims++upperAnims))-1))
(bothAnims++upperAnims),
listArray (0,((length (bothAnims++fixedLower))-1))
(bothAnims++fixedLower))
readAnimation :: String -> IO [MD3Animation]
readAnimation line
| length subStrings <= 0 = do
return []
| length subStrings >= 5 =
case (elem (subStrings !! 4) animList) of
True -> do
let startF = (read $ subStrings!!0):: Int
let numF = (read $ subStrings!!1):: Int
let loopF = (read $ subStrings!!2):: Int
let f = (read $ subStrings!!3):: Int
let aName = subStrings!!4
return [MD3Animation {
animName = aName,
startFrame = startF,
endFrame = startF + numF,
loopFrames = loopF,
fp = 1000 * (1 / realToFrac f)
}]
_ -> return []
| otherwise = do
return []
where
replc str = map (replace' ['/','\n','\r']) str
subStrings = (words (replc line))
fixLower :: Int -> MD3Animation -> MD3Animation
fixLower offset anim = MD3Animation {
animName = animName anim,
startFrame = (startFrame anim) - offset,
endFrame = (endFrame anim) - offset,
loopFrames = loopFrames anim,
fp = fp anim
}
matchPrefix :: String -> MD3Animation -> Bool
matchPrefix prefix anim =
prefix == head (words (map (replace' ['_']) (animName anim)))
readLines :: Handle -> IO [String]
readLines handle = do
eof <- hIsEOF handle
case (eof) of
False -> do
lne <- hGetLine handle
lnes <- readLines handle
return (lne:lnes)
_ -> return []
-------------------------------------------------------------------------------
withBinaryFile :: FilePath -> (Handle -> IO a) -> IO a
withBinaryFile filePath = bracket (openBinaryFile filePath ReadMode) hClose
toInts :: (Integral a)=>[a] -> [Int]
toInts a = map fromIntegral a
toFloats :: (Real a) => [a] -> [Float]
toFloats a = map realToFrac a
getInts :: Ptr a -> Int -> IO [Int]
getInts ptr n = do ints <- peekArray n (castPtr ptr:: Ptr CInt)
return $ toInts ints
getFloats :: Ptr a -> Int -> IO [Float]
getFloats ptr n = do floats <- peekArray n (castPtr ptr :: Ptr CFloat)
return $ toFloats floats
getString :: Ptr a -> Int -> IO String
getString ptr _ = do string <- peekCString (castPtr ptr :: Ptr CChar)
return string
getPtrs :: Ptr a -> Int -> Int -> [Ptr a]
getPtrs ptr lngth size= map ((plusPtr ptr).(size*)) [0.. (lngth-1)]
| elitak/frag | src/MD3.hs | gpl-2.0 | 39,074 | 2 | 18 | 14,747 | 10,622 | 5,675 | 4,947 | 860 | 2 |
{--
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
--}
import Data.Time.Calendar.WeekDate
import Data.Time.Calendar
is_sunday :: Day -> Bool
is_sunday day = x == 7 where
(_,_,x) = toWeekDate day
main = print $ length [ 1 | y <- [1901..2000], m <- [1..12], is_sunday (fromGregorian y m 1) ]
| goalieca/haskelling | 019.hs | gpl-3.0 | 809 | 0 | 11 | 192 | 114 | 62 | 52 | 6 | 1 |
import System.Random
import Control.Applicative
randomfloat = getStdRandom (randomR (0.0, 1.0))
randompoint = (,) <$> randomfloat <*> randomfloat
runM
| trehansiddharth/mlsciencebowl | uploads/chapter1.hs | gpl-3.0 | 155 | 0 | 8 | 22 | 50 | 27 | 23 | -1 | -1 |
module TransList(transList) where
import AbsWhile
import Data.Data -- Data
import Data.Generics.Schemes -- everywhere
import Data.Generics.Aliases -- mkT
transList :: Data a => a -> a
transList = everywhere (mkT tList)
tList :: Exp -> Exp
tList x = case x of
EListRep exps tl -> case tl of
NoTail -> foldr ECons (EVal VNil) exps
Tail atom -> foldr ECons (EVal (VAtom atom)) exps
EConsStar exps -> foldr1 ECons exps
EList exps -> foldr ECons (EVal VNil) exps
_ -> x
| tetsuo-jp/while-C-ocaml | src/desugar/TransList.hs | agpl-3.0 | 517 | 0 | 15 | 133 | 187 | 96 | 91 | 15 | 5 |
{-
Habit of Fate, a game to incentivize habit formation.
Copyright (C) 2017 Gregory Crosswhite
This program is free software: you can redistribute it and/or modify
it under version 3 of the terms of the GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UnicodeSyntax #-}
module HabitOfFate.Server.Requests.Web.NewGroup (handler) where
import HabitOfFate.Prelude
import qualified Data.Text.Lazy as Lazy
import Data.UUID (UUID)
import qualified Data.UUID as UUID
import System.Random (randomIO)
import Network.HTTP.Types.Status (temporaryRedirect307)
import Web.Scotty (ScottyM)
import qualified Web.Scotty as Scotty
import HabitOfFate.Server.Actions.Results
import HabitOfFate.Server.Common
handler ∷ Environment → ScottyM ()
handler _ =
Scotty.get "/groups/new" $
liftIO (randomIO ∷ IO UUID) <&> (UUID.toText >>> ("/groups/" ⊕) >>> Lazy.fromStrict)
>>=
setStatusAndRedirect temporaryRedirect307
| gcross/habit-of-fate | sources/library/HabitOfFate/Server/Requests/Web/NewGroup.hs | agpl-3.0 | 1,422 | 0 | 10 | 242 | 176 | 108 | 68 | 20 | 1 |
{-
This file is part of Tractor.
Tractor is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Tractor is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Tractor. If not, see <http://www.gnu.org/licenses/>.
-}
{- |
Module : KabuCom.Model
Description : schema of table
Copyright : (c) 2016 Akihiro Yamamoto
License : AGPLv3
Maintainer : https://github.com/ak1211
Stability : unstable
Portability : POSIX
Kabu.Com証券サイトデータベースのモデル
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module KabuCom.Model
( module KabuCom.Model
, module ModelDef
) where
import Data.Int (Int32)
import Data.Monoid (mempty, (<>))
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import qualified Data.Text.Lazy.Builder.Int as TLB
import qualified Data.Text.Lazy.Builder.RealFloat as TLB
import Data.Time (UTCTime)
import Database.Persist.TH
import ModelDef
share [mkPersist sqlSettings, mkMigrate "migrateKabuCom"] [persistLowerCase|
-- |
-- 資産テーブル
KabucomAsset
at UTCTime -- ^ 日付時間
evaluation Double -- ^ 保有株式評価合計
profit Double -- ^ 保有株式損益合計
--
moneySpare Int32 -- ^ 現物買付余力
cashBalance Int32 -- ^ 残高(保証金現金)
deriving Eq
-- |
-- 保有株式テーブル
KabucomStock
asset KabucomAssetId -- ^ 紐付け
at UTCTime -- ^ 日付時間
ticker TickerSymbol -- ^ ティッカー
caption String -- ^ 名前
count Int32 -- ^ 保有数
purchase Double -- ^ 取得単価
price Double -- ^ 現在値
deriving Eq
|]
-- |
-- 資産テーブルの要約
kabucomAssetDigest :: KabucomAsset -> String
kabucomAssetDigest KabucomAsset{..} =
TL.unpack . TLB.toLazyText $ mempty
<> TLB.fromString (show kabucomAssetAt) <> ", "
<> "評価合計 " <> TLB.realFloat kabucomAssetEvaluation <> ", "
<> "損益合計 " <> TLB.realFloat kabucomAssetProfit <> ", "
<> "現物買付余力 " <> TLB.decimal kabucomAssetMoneySpare <> ", "
<> "現金残高 " <> TLB.decimal kabucomAssetCashBalance <> ", "
-- |
-- 保有株式の要約
kabucomStockDigest :: KabucomStock -> String
kabucomStockDigest stk@KabucomStock{..} =
TL.unpack . TLB.toLazyText $ mempty
<> TLB.fromString (showTickerSymbol kabucomStockTicker) <> " "
<> TLB.fromString kabucomStockCaption <> ", "
<> "保有 " <> TLB.decimal kabucomStockCount <> ", "
<> "取得 " <> TLB.realFloat kabucomStockPurchase <> ", "
<> "現在 " <> TLB.realFloat kabucomStockPrice <> ", "
<> "損益 " <> TLB.realFloat (kabucomStockGain stk)
-- |
-- 保有株式の損益
kabucomStockGain :: KabucomStock -> Double
kabucomStockGain KabucomStock{..} =
(kabucomStockPrice - kabucomStockPurchase)
* realToFrac kabucomStockCount
| ak1211/tractor | src/KabuCom/Model.hs | agpl-3.0 | 4,145 | 0 | 22 | 1,186 | 445 | 251 | 194 | 45 | 1 |
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home
where
import Import
import Data.List
getHomeR :: Handler Html
getHomeR = do
master <- getYesod
coms <- runDB $ selectList [] [Desc CommentTime]
defaultLayout $ do
setTitle "Yacs :: Home"
$(widgetFile "home")
postHomeR :: Handler Html
postHomeR = error "you should not do this"
| nek0/yacs | Handler/Home.hs | agpl-3.0 | 364 | 0 | 12 | 68 | 98 | 48 | 50 | 13 | 1 |
{-
Habit of Fate, a game to incentivize habit formation.
Copyright (C) 2017 Gregory Crosswhite
This program is free software: you can redistribute it and/or modify
it under version 3 of the terms of the GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnicodeSyntax #-}
module HabitOfFate.Server.Requests.Shared.LoginOrCreate (handler) where
import HabitOfFate.Prelude
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TVar (readTVar, modifyTVar, newTVar)
import qualified Data.ByteString.Builder as Builder
import Data.Time.Clock (addUTCTime, getCurrentTime)
import Network.HTTP.Types.Status (conflict409, created201, temporaryRedirect307)
import System.Random (randomRIO)
import Text.Blaze.Html5 (AttributeValue, Html, (!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Web.Cookie (SetCookie(..), renderSetCookie, sameSiteStrict)
import Web.Scotty (ActionM, ScottyM)
import qualified Web.Scotty as Scotty
import HabitOfFate.Data.Account
import HabitOfFate.Logging
import HabitOfFate.Server.Actions.Queries
import HabitOfFate.Server.Actions.Results
import HabitOfFate.Server.Common
createAndReturnCookie ∷ Environment → Username → ActionM ()
createAndReturnCookie Environment{..} username = do
Cookie token ← liftIO $ do
current_time ← getCurrentTime
cookie ← (pack >>> Cookie) <$> (replicateM 20 $ randomRIO ('A','z'))
atomically $ do
let expiration_time = addUTCTime (30*86400) current_time
modifyTVar cookies_tvar $ insertMap cookie (expiration_time, username)
modifyTVar expirations_tvar $ insertSet (expiration_time, cookie)
pure cookie
def
{ setCookieName="token"
, setCookieValue=encodeUtf8 token
, setCookieHttpOnly=True
, setCookieSameSite=Just sameSiteStrict
, setCookieSecure=not test_mode
}
|> renderSetCookie
|> Builder.toLazyByteString
|> decodeUtf8
|> Scotty.setHeader "Set-Cookie"
handleCreateAccountApi ∷ Environment → ScottyM ()
handleCreateAccountApi environment@Environment{..} = do
Scotty.post "/api/create" $ do
username ← paramGuardingAgainstMissing "username"
password ← paramGuardingAgainstMissing "password"
logIO $ [i|Request to create an account for "#{username}".|]
liftIO >>> join $ do
new_account ← newAccount password
atomically $ do
accounts ← readTVar accounts_tvar
if member username accounts
then pure $ do
logIO $ [i|Account "#{username}" already exists!|]
Scotty.status conflict409
else do
account_tvar ← newTVar new_account
modifyTVar accounts_tvar $ insertMap username account_tvar
pure $ do
logIO $ [i|Account "#{username}" successfully created!|]
Scotty.status created201
createAndReturnCookie environment username
handleLoginApi ∷ Environment → ScottyM ()
handleLoginApi environment@Environment{..} = do
Scotty.post "/api/login" $ do
username ← paramGuardingAgainstMissing "username"
password ← paramGuardingAgainstMissing "password"
logIO $ [i|Request to log into an account with "#{username}".|]
account_tvar ←
(accounts_tvar |> readTVarMonadIO |> fmap (lookup username))
>>=
maybe (finishWithStatusMessage 404 "Not Found: No such account") return
(
readTVarMonadIO account_tvar
>>=
(
passwordIsValid password
>>>
bool (finishWithStatusMessage 403 "Forbidden: Invalid password") (logIO "Login successful.")
)
>>
createAndReturnCookie environment username
)
basicTextInput ∷ AttributeValue → AttributeValue → AttributeValue → Html → Html
basicTextInput type_ name placeholder =
(! A.type_ type_)
>>>
(! A.name name)
>>>
(! A.placeholder placeholder)
>>>
(! A.required "")
basicTextForm ∷ [Html → Html] → Html
basicTextForm =
foldMap
(\setAttributes →
H.input |> setAttributes |> (H.div ! A.class_ "fields")
)
handleCreateAccountWeb ∷ Environment → ScottyM ()
handleCreateAccountWeb environment@Environment{..} = do
Scotty.get "/create" action
Scotty.post "/create" action
where
action = do
username@(Username username_) ← Username <$> paramOrBlank "username"
password1 ← paramOrBlank "password1"
password2 ← paramOrBlank "password2"
error_message ∷ Text ←
if ((not . onull $ password1) && password1 == password2)
then do
logIO [i|Request to create an account for "#{username_}".|]
liftIO >>> join $ do
new_account ← newAccount password1
atomically $ do
accounts ← readTVar accounts_tvar
if member username accounts
then pure $ do
logIO [i|Account "#{username_}" already exists!|]
Scotty.status conflict409
pure "This account already exists."
else do
account_tvar ← newTVar new_account
modifyTVar accounts_tvar $ insertMap username account_tvar
pure $ do
logIO [i|Account "#{username_}" successfully created! Redirecting to /.|]
createAndReturnCookie environment username
Scotty.status temporaryRedirect307
Scotty.redirect "/"
else pure $
if onull username_
then
if onull password1
then ""
else "Did not specify username."
else
case (password1, password2) of
("", "") → "Did not type the password."
("", _) → "Did not type the password twice."
(_, "") → "Did not type the password twice."
_ | password1 == password2 → ""
_ | otherwise → "The passwords did not agree."
device ← getDevice
renderTopOnlyPage "Habit of Fate - Account Creation" (\_ → ["enter"]) [] Nothing
>>> ($ device)
>>> renderHtml
>>> Scotty.html $ \_ →
H.div ! A.class_ "enter" $ do
H.div ! A.class_ "tabs" $ do
H.span ! A.class_ "inactive" $ H.a ! A.href "/login" $ H.toHtml ("Login" ∷ Text)
H.span ! A.class_ "active" $ H.toHtml ("Create" ∷ Text)
H.form ! A.method "post" $ do
basicTextForm >>> H.div $
[ basicTextInput "text" "username" "Username" >>> (! A.value (H.toValue username_))
, basicTextInput "password" "password1" "Password"
, basicTextInput "password" "password2" "Password (again)"
]
when ((not <<< onull) error_message) $
H.div ! A.id "error-message" $ H.toHtml error_message
H.div $
H.input
! A.class_ "submit"
! A.type_ "submit"
! A.formmethod "post"
! A.value "Create Account"
handleLoginWeb ∷ Environment → ScottyM ()
handleLoginWeb environment@Environment{..} = do
Scotty.get "/login" action
Scotty.post "/login" action
where
action = do
username@(Username username_) ← Username <$> paramOrBlank "username"
password ← paramOrBlank "password"
error_message ∷ Text ←
if onull username_
then pure ""
else do
logIO [i|Request to log in "#{username_}".|]
accounts ← readTVarMonadIO accounts_tvar
case lookup username accounts of
Nothing → do
logIO [i|No account has username #{username_}.|]
pure "No account has that username."
Just account_tvar → do
account ← readTVarMonadIO account_tvar
if passwordIsValid password account
then do
logIO [i|Successfully logged in #{username_}. Redirecting to /.|]
createAndReturnCookie environment username
Scotty.status temporaryRedirect307
Scotty.redirect "/"
else do
logIO [i|Incorrect password for #{username_}.|]
pure "No account has that username."
device ← getDevice
let enter_device_stylesheets =
case device of
Desktop → ["enter_desktop"]
Mobile → []
renderTopOnlyPage "Habit of Fate - Login" (\_ → "enter_common":enter_device_stylesheets) [] Nothing
>>> ($ device)
>>> renderHtml
>>> Scotty.html $ \_ →
H.div ! A.class_ "enter" $ do
H.div ! A.class_ "tabs" $ do
H.span ! A.class_ "active" $ H.toHtml ("Login" ∷ Text)
H.span ! A.class_ "inactive" $ H.a ! A.href "/create" $ H.toHtml ("Create" ∷ Text)
H.form ! A.method "post" $ do
basicTextForm >>> H.div $
[ basicTextInput "text" "username" "Username" >>> (! A.value (H.toValue username_))
, basicTextInput "password" "password" "Password"
]
when ((not <<< onull) error_message) $
H.div ! A.id "error-message" $ H.toHtml error_message
H.div $
H.input
! A.class_ "submit"
! A.type_ "submit"
! A.formmethod "post"
! A.value "Login"
handler ∷ Environment → ScottyM ()
handler environment = do
handleCreateAccountApi environment
handleCreateAccountWeb environment
handleLoginApi environment
handleLoginWeb environment
| gcross/habit-of-fate | sources/library/HabitOfFate/Server/Requests/Shared/LoginOrCreate.hs | agpl-3.0 | 10,251 | 0 | 27 | 2,864 | 2,375 | 1,191 | 1,184 | 221 | 9 |
module Codewars.Kata.Anagram where
import Data.List
import Data.Char
isAnagramOf :: String -> String -> Bool
isAnagramOf a b = (filter f $ sort $ toUpper <$> a) == (filter f $ sort $ toUpper <$> b)
where ls = ['A' .. 'Z'] ++ ['0' .. '9']
f x = x `elem` ls
--
| ice1000/OI-codes | codewars/1-100/anagram-or-not.hs | agpl-3.0 | 271 | 0 | 10 | 64 | 118 | 66 | 52 | 7 | 1 |
module NotThe where
notThe :: String -> Maybe String
notThe "the" = Nothing
notThe "The" = Nothing
notThe x = Just x
replaceThe :: String -> String
replaceThe = unwords . fmap trans . words
where trans word = trans' (notThe word)
trans' Nothing = "a"
trans' (Just x) = x
countTheBeforeVowel :: String -> Integer
countTheBeforeVowel = foldCount 0 . words
where foldCount acc [] = acc
foldCount acc [_] = acc
foldCount acc (the:x:xs)
| (the == "the" || the == "The") && head x `elem` ['a','e','i','o','u','A','E','I','O','U'] = foldCount (acc + 1) xs
| otherwise = foldCount acc (x:xs)
isVowel :: Char -> Bool
isVowel c
| c `elem` ['a','e','i','o','u','A','E','I','O','U'] = True
| otherwise = False
filterVowels :: String -> String
filterVowels = filter isVowel
filterConsos :: String -> String
filterConsos = filter (not . isVowel)
countVowels :: String -> Int
countVowels = length . filterVowels
countConsos :: String -> Int
countConsos = length . filterConsos
newtype Word' = Word' String deriving (Eq, Show)
vowels :: String
vowels = "aeiou"
mkWord :: String -> Maybe Word'
mkWord s = if vowelsVsConsos s == GT
then Nothing
else Just $ Word' s
where vowelsVsConsos t = compare (countVowels t) (countConsos t)
| aniketd/learn.haskell | haskellbook/notthe.hs | unlicense | 1,450 | 0 | 15 | 440 | 518 | 276 | 242 | 37 | 3 |
module Sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing =
if (x <= y) then fstString x else sndString y
where x = "Singin"
y = "Somewhere"
| thewoolleyman/haskellbook | 05/09/maor/sing.hs | unlicense | 263 | 0 | 7 | 74 | 96 | 54 | 42 | 9 | 2 |
--
-- Copyright (C) 2012 Noriyuki OHKAWA
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
{-# LANGUAGE RankNTypes #-}
-- | Fluent Logger with Conduit Interface
module Network.Fluent.Conduit
( -- * Sinks
sinkFluent
, sinkFluentWithLogger
) where
import Network.Fluent.Logger ( FluentSettings, FluentLogger, newFluentLogger, closeFluentLogger, post )
import Network.Fluent.Logger.Packable ( Packable )
import Control.Monad.IO.Class ( liftIO )
import Data.ByteString ( ByteString )
import Data.Conduit ( bracketP, awaitForever, Consumer )
import Control.Monad.Trans.Resource ( MonadResource )
-- | Stream all incoming pair ( label, data ) to the given Fluent.
--
-- Since 0.3.0.0
--
sinkFluent :: (MonadResource m, Packable a) => FluentSettings -> Consumer (ByteString, a) m ()
sinkFluent set = bracketP
(newFluentLogger set)
(liftIO . closeFluentLogger)
sinkFluentWithLogger
-- | Stream all incoming pair ( label, data ) to the given Fluent logger.
--
-- Since 0.3.0.0
--
sinkFluentWithLogger :: (MonadResource m, Packable a) => FluentLogger -> Consumer (ByteString, a) m ()
sinkFluentWithLogger logger = awaitForever $ liftIO . uncurry (post logger)
| notogawa/fluent-logger-conduit | Network/Fluent/Conduit.hs | apache-2.0 | 1,733 | 0 | 8 | 319 | 257 | 159 | 98 | 18 | 1 |
import Data.List
pack [] = []
pack str@(s:_) =
let n = length $ filter (== s) str
r = filter (/= s) str
in
(s,n):(pack r)
ans ("0":_) = []
ans (n:x) =
let n' = read n :: Int
s = pack $ concat $ map words $ take n' x
s' = sortBy (\ (w0,n0) (w1,n1) -> let c = compare n1 n0
in if c /= EQ
then c
else compare w0 w1 ) s
c = head $ head $ drop n' x
r = drop (n'+1) x
a = map fst $ take 5 $ filter (\(w,n) -> c == (head w)) s'
t = ans r
in
if a == []
then "NA":t
else (unwords a):t
main = do
c <- getContents
let i = lines c
o = ans i
mapM_ putStrLn o
| a143753/AOJ | 0242.hs | apache-2.0 | 805 | 0 | 16 | 400 | 388 | 200 | 188 | 26 | 3 |
{-# LANGUAGE ExistentialQuantification #-}
-- |
-- Maintainer : Roman Smrž <[email protected]>
-- Stability : experimental
--
-- Experimental code providing a structure similar to the standard Map, which
-- is able to swap the data to a database on disk. Unlike 'Swapper', in can
-- swap both data and indices, and thus could be usable for data structures
-- with more items and lower difference between the size of data and indices
-- than 'Swapper', moreover the interface is cleaner without any accessory
-- functions.
--
-- However, this would ideally work with some database with persistent writable
-- snapshots and I was unable to find one I could use. The other, presently
-- used, possibility is to work with ordinary database (TokioCabinet with
-- interface from Swapper is used) and optimaze for "single-threaded" use,
-- similarily to the idea of DiffArray. The worse, multi-threaded use-case, as
-- well as using the cache to keep some of the values in memory, is however,
-- not yet implemented. Also, the only interface provided so far is for
-- creating, inserting and lookup.
module Data.Disk.SwapMap (
SwapMap,
mkSwapMap,
insert, lookup,
) where
import Prelude hiding (lookup)
import Control.Concurrent.MVar
import Control.DeepSeq
import Control.Monad
import Control.Parallel
import Data.Map (Map)
import qualified Data.Map as M
import Data.IORef
import Happstack.Data.Serialize
import System.Mem.Weak
import System.IO.Unsafe
import qualified System.IO as IO
import Data.Disk.Swapper.Cache
import qualified Data.Disk.Swapper.TokyoCabinet as TC
data (Ord k, Serialize k, Serialize a) => SwapMap k a = SwapMap (MVar (SwapMapData k a))
data SwapMapData k a = forall c. (Cache c k) => Current
{ smDB :: TC.Database
, smCache :: (MVar c)
, smMem :: (MVar (Map k (Weak a, MVar ())))
, smCopy :: IO (SwapMapData k a)
}
| Diff k (Maybe a) (MVar (SwapMapData k a))
isCurrent :: SwapMapData k a -> Bool
isCurrent (Diff _ _ _) = False
isCurrent _ = True
-- | Creates a 'SwapMap' object given a path prefix to database files and a
-- cache object.
mkSwapMap :: (Ord k, Serialize k, Serialize a, Cache c k)
=> FilePath -- ^ prefix for database files, currently need to point to an existing directory
-> c -- ^ cache object, presently unused
-> IO (SwapMap k a)
mkSwapMap dir cache = do
db <- TC.open $ dir ++ "/0.tcb"
mcache <- newMVar cache
mmem <- newMVar M.empty
counter <- newIORef 1
let copy odb = do
c <- atomicModifyIORef counter (\c -> (c+1,c))
let newname = dir ++ "/" ++ show c ++ ".tcb"
TC.copy odb newname
ndb <- TC.open newname
nmem <- newMVar M.empty
return $ Current ndb mcache nmem (copy ndb)
return . SwapMap =<< newMVar (Current db mcache mmem (copy db))
lookup :: (Show k, Ord k, Serialize k, Serialize a) => k -> SwapMap k a -> Maybe a
lookup key (SwapMap mdata) = unsafePerformIO $ do
smd <- takeMVar mdata
result <- internalLookup key smd
putMVar mdata smd
return result
internalLookup :: (Show k, Ord k, Serialize k, Serialize a) => k -> SwapMapData k a -> IO (Maybe a)
internalLookup key smd@(Current db _ mmem _) = modifyMVar mmem $ \mem ->
case M.lookup key mem of
Nothing -> load mem
Just (weak, lock) -> do
mbx <- deRefWeak weak
case mbx of
Nothing -> readMVar lock >> load mem
jx -> return (mem, jx)
where load mem = do
result <- return . fmap (fst.deserialize) =<< TC.get db (serialize key)
case result of
Just val -> do
IO.putStrLn $ "Loaded "++show key
weak <- smWeak smd key val
return (M.insert key weak mem, result)
Nothing -> return (mem, result)
internalLookup key (Diff key' val mnext)
| key' == key = return val
| otherwise = withMVar mnext (internalLookup key)
insert :: (Show k, Ord k, Serialize k, Serialize a, NFData a) => k -> a -> SwapMap k a -> SwapMap k a
insert key val (SwapMap mdata) = deepseq val `pseq` unsafePerformIO $ do
smd <- takeMVar mdata
case smd of
Current _ _ mmem _ -> do
IO.putStrLn $ "Creating "++show key
orig <- internalLookup key smd
weak <- smWeak smd key val
modifyMVar_ mmem (return . M.insert key weak)
ndata <- newMVar smd
putMVar mdata $ Diff key orig ndata
return $ SwapMap ndata
smWeak :: (Show k, Ord k, Serialize k, Serialize a) => SwapMapData k a -> k -> a -> IO (Weak a, MVar ())
smWeak smd key val = do
lock <- newEmptyMVar
liftM (flip (,) lock) $ mkWeakPtr val $ Just $ do
modifyMVar_ (smMem smd) $ \mem -> do
IO.putStrLn $ "Saving "++show key
TC.put (smDB smd) (serialize key) (serialize val)
IO.putStrLn $ "Saved "++show key
putMVar lock ()
return $ M.delete key mem
| roman-smrz/swapper | src/Data/Disk/SwapMap.hs | bsd-2-clause | 5,527 | 0 | 17 | 1,852 | 1,528 | 768 | 760 | 94 | 4 |
--
-- Copyright 2014, NICTA
--
-- This software may be distributed and modified according to the terms of
-- the BSD 2-Clause license. Note that NO WARRANTY is provided.
-- See "LICENSE_BSD2.txt" for details.
--
-- @TAG(NICTA_BSD)
--
-- Printer for C source format to be consumed by the CapDL initialiser.
-- Note: corresponds to the -c/--code argument.
{-# LANGUAGE CPP #-}
module CapDL.PrintC where
import CapDL.Model
import Control.Exception (assert)
import Data.List
import Data.List.Utils
import Data.Maybe (fromJust, fromMaybe)
import Data.Word
import Data.Map as Map
import Data.Set as Set
import Data.Bits
import Numeric (showHex)
import Text.PrettyPrint
(∈) = Set.member
(+++) :: String -> String -> String
s1 +++ s2 = s1 ++ "\n" ++ s2
hex :: Word -> String
hex x = "0x" ++ showHex x ""
maxObjects :: Int -> String
maxObjects count = "#define MAX_OBJECTS " ++ show count
memberArch :: Arch -> String
memberArch IA32 = ".arch = CDL_Arch_IA32,"
memberArch ARM11 = ".arch = CDL_Arch_ARM,"
memberNum :: Int -> String
memberNum n = ".num = " ++ show n ++ ","
showObjID :: Map ObjID Int -> ObjID -> String
showObjID xs id = (case Map.lookup id xs of
Just w -> show w
_ -> "INVALID_SLOT") ++ " /* " ++ fst id ++ " */"
showRights :: CapRights -> String
showRights rights =
"(" ++ intercalate "|" (["0"] ++ r ++ w ++ g) ++ ")"
where
r = if Read ∈ rights then ["seL4_CanRead"] else []
w = if Write ∈ rights then ["seL4_CanWrite"] else []
g = if Grant ∈ rights then ["seL4_CanGrant"] else []
showPorts :: Set Word -> String
showPorts ports =
show ((.|.) (shift start 16) end)
where
start = Set.findMin ports
end = Set.findMax ports
showPCI :: Word -> (Word, Word, Word) -> String
showPCI domainID (pciBus, pciDev, pciFun) =
hex $ shift domainID 16 .|. shift pciBus 8 .|. shift pciDev 3 .|. pciFun
-- Lookup-by-value on a dictionary. I feel like I need a shower.
lookupByValue :: Ord k => (a -> Bool) -> Map k a -> k
lookupByValue f m = head $ keys $ Map.filter f m
showCap :: Map ObjID Int -> Cap -> IRQMap -> String -> ObjMap Word -> String
showCap _ NullCap _ _ _ = "{.type = CDL_NullCap}"
showCap objs (UntypedCap id) _ _ _ =
"{.type = CDL_UntypedCap, .obj_id = " ++ showObjID objs id ++ "}"
showCap objs (EndpointCap id badge rights) _ is_orig _ =
"{.type = CDL_EPCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++
", .rights = " ++ showRights rights ++
", .data = { .tag = seL4_CapData_Badge, .badge = " ++ show badge ++ "}}"
showCap objs (NotificationCap id badge rights) _ is_orig _ =
"{.type = CDL_NotificationCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++
", .rights = " ++ showRights rights ++
", .data = { .tag = seL4_CapData_Badge, .badge = " ++ show badge ++
"}}"
showCap objs (ReplyCap id) _ _ _ =
"{.type = CDL_ReplyCap, .obj_id = " ++ showObjID objs id ++ "}"
-- XXX: Does it even make sense to give out a reply cap? How does init fake this?
showCap objs (MasterReplyCap id) _ _ _ =
"{.type = CDL_MasterReplyCap, .obj_id = " ++ showObjID objs id ++ "}"
-- XXX: As above.
showCap objs (CNodeCap id guard guard_size) _ is_orig _ =
"{.type = CDL_CNodeCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++
", .rights = seL4_AllRights, .data = CDL_CapData_MakeGuard(" ++
show guard_size ++ ", " ++ show guard ++ ")}"
showCap objs (TCBCap id) _ is_orig _ =
"{.type = CDL_TCBCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++
", .rights = seL4_AllRights}"
showCap _ IRQControlCap _ _ _ = "{.type = CDL_IRQControlCap}"
showCap _ (IRQHandlerCap id) irqNode is_orig _ =
"{.type = CDL_IRQHandlerCap, .obj_id = INVALID_OBJ_ID" ++
", .is_orig = " ++ is_orig ++
", .irq = " ++ show (lookupByValue (\x -> x == id) irqNode) ++ "}"
-- Caps have obj_ids, or IRQs, but not both.
showCap objs (FrameCap id rights _ cached maybe_mapping) _ is_orig _ =
"{.type = CDL_FrameCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++
", .rights = " ++ showRights rights ++
", .vm_attribs = " ++ (if cached then "seL4_ARCH_Default_VMAttributes" else "CDL_VM_CacheDisabled") ++
", .mapping_container_id = " ++ case maybe_mapping of {
Just (mapping_container, _) -> showObjID objs mapping_container;
_ -> "INVALID_OBJ_ID"
} ++
", .mapping_slot = " ++ case maybe_mapping of {
Just (_, mapping_slot) -> (show mapping_slot);
_ -> "0"
} ++ "}"
-- FIXME: I feel like I should be doing something with the ASID data here...
showCap objs (PTCap id _) _ is_orig _ =
"{.type = CDL_PTCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++ "}"
showCap objs (PDCap id _) _ is_orig _ =
"{.type = CDL_PDCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++ "}"
showCap _ ASIDControlCap _ _ _ =
"{.type = CDL_ASIDControlCap}"
showCap objs (ASIDPoolCap id _) _ _ _ =
"{.type = CDL_ASIDPoolCap, .obj_id = " ++ showObjID objs id ++ "}"
showCap objs (IOPortsCap id ports) _ is_orig _ =
"{.type = CDL_IOPortsCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++
", .data = { .tag = CDL_CapData_Raw, .data = " ++ showPorts ports ++ "}}"
showCap objs (IOSpaceCap id) _ is_orig ms =
"{.type = CDL_IOSpaceCap, .obj_id = " ++ showObjID objs id ++
", .is_orig = " ++ is_orig ++
", .data = { .tag = CDL_CapData_Raw, .data = " ++ showPCI dom pci ++ "}}"
where pci = pciDevice $ fromJust $ Map.lookup id ms
dom = domainID $ fromJust $ Map.lookup id ms
showCap objs (VCPUCap id) _ _ _ = "{.type = CDL_VCPUCap, .obj_id = " ++ showObjID objs id ++ "}"
showCap _ x _ _ _ = assert False $
"UNSUPPORTED CAP TYPE: " ++ show x
-- These are not supported by the initialiser itself.
showSlots :: Map ObjID Int -> ObjID -> [(Word, Cap)] -> IRQMap -> CDT -> ObjMap Word -> String
showSlots _ _ [] _ _ _ = ""
showSlots objs obj_id (x:xs) irqNode cdt ms =
"{" ++ show index ++ ", " ++ slot ++ "}," +++
showSlots objs obj_id xs irqNode cdt ms
where
index = fst x
slot = showCap objs (snd x) irqNode is_orig ms
is_orig = if (Map.notMember (obj_id, index) cdt) then "true" else "false"
memberSlots :: Map ObjID Int -> ObjID -> CapMap Word -> IRQMap -> CDT -> ObjMap Word -> String
memberSlots objs obj_id slots irqNode cdt ms =
".slots.num = " ++ show slot_count ++ "," +++
".slots.slot = (CDL_CapSlot[]) {" +++
showSlots objs obj_id (Map.toList slots) irqNode cdt ms +++
"},"
where
slot_count = Map.size slots
printInit :: [Word] -> String
printInit argv =
"{" ++ Data.List.Utils.join ", " (Data.List.map show argv) ++ "}"
showObjectFields :: Map ObjID Int -> ObjID -> KernelObject Word -> IRQMap -> CDT -> ObjMap Word -> String
showObjectFields _ _ Endpoint _ _ _ = ".type = CDL_Endpoint,"
showObjectFields _ _ Notification _ _ _ = ".type = CDL_Notification,"
showObjectFields objs obj_id (TCB slots faultEndpoint info domain argv) _ _ _ =
".type = CDL_TCB," +++
".tcb_extra = {" +++
".ipcbuffer_addr = " ++ show ipcbuffer_addr ++ "," +++
".priority = " ++ show priority ++ "," +++
".pc = " ++ show pc ++ "," +++
".sp = " ++ show stack ++ "," +++
".elf_name = " ++ show elf_name ++ "," +++
".init = (const seL4_Word[])" ++ printInit argv ++ "," +++
".init_sz = " ++ show (length argv) ++ "," +++
".domain = " ++ show domain ++ "," +++
".fault_ep = " ++ show fault_ep ++ "," +++
"}," +++
memberSlots objs obj_id slots Map.empty Map.empty Map.empty -- IRQ, cdt and obj map not required
where
ipcbuffer_addr = case info of {Just i -> ipcBufferAddr i; _ -> 0}
priority = case info of {Just i -> case prio i of {Just p -> p; _ -> 125}; _ -> 125}
pc = case info of {Just i -> case ip i of {Just v -> v; _ -> 0}; _ -> 0}
stack = case info of {Just i -> case sp i of {Just v -> v; _ -> 0}; _ -> 0}
elf_name = case info of {Just i -> case elf i of {Just e -> e; _ -> ""}; _ -> ""}
fault_ep = case faultEndpoint of {Just w -> w; _ -> 0}
showObjectFields objs obj_id (CNode slots sizeBits) irqNode cdt ms =
".type = " ++ t ++ "," +++
".size_bits = " ++ show sizeBits ++ "," +++
memberSlots objs obj_id slots irqNode cdt ms
where
-- IRQs are represented in CapDL as 0-sized CNodes. This is fine for
-- the model, but the initialiser needs to know what objects represent
-- interrupts to avoid trying to create them at runtime. It's a bit of
-- a hack to assume that any 0-sized CNode is an interrupt, but this is
-- an illegal size for a valid CNode so everything should work out.
t = if sizeBits == 0 then "CDL_Interrupt" else "CDL_CNode"
showObjectFields _ _ (Untyped size_bits paddr) _ _ _ =
".type = CDL_Untyped," +++
".size_bits = " ++ show sizeBits ++ "," +++
".paddr = (void*)" ++ hex (fromMaybe 0 paddr) ++ ","
where
sizeBits = case size_bits of {Just s -> s; _ -> -1}
showObjectFields objs obj_id (PT slots) _ _ _ =
".type = CDL_PT," +++
memberSlots objs obj_id slots Map.empty Map.empty Map.empty -- IRQ, cdt and obj map not required
showObjectFields objs obj_id (PD slots) _ _ _ =
".type = CDL_PD," +++
memberSlots objs obj_id slots Map.empty Map.empty Map.empty -- IRQ, cdt and obj map not required
showObjectFields _ _ (Frame size paddr) _ _ _ =
".type = CDL_Frame," +++
".size_bits = " ++ show (logBase 2 $ fromIntegral size) ++ "," +++
".paddr = (void*)" ++ hex (fromMaybe 0 paddr) ++ ","
showObjectFields _ _ (IOPorts size) _ _ _ =
".type = CDL_IOPorts," +++
".size_bits = " ++ show size ++ "," -- FIXME: This doesn't seem right.
showObjectFields objs obj_id (ASIDPool slots) _ _ _ =
".type = CDL_ASIDPool," +++
memberSlots objs obj_id slots Map.empty Map.empty Map.empty -- IRQ, cdt and obj map not required
showObjectFields _ _ (IODevice _ _ _) _ _ _ =
".type = CDL_IODevice,"
showObjectFields _ _ VCPU _ _ _ = ".type = CDL_VCPU,"
showObjectFields _ _ x _ _ _ = assert False $
"UNSUPPORTED OBJECT TYPE: " ++ show x
showObject :: Map ObjID Int -> (ObjID, KernelObject Word) -> IRQMap -> CDT -> ObjMap Word -> String
showObject objs obj irqNode cdt ms =
"{" +++
"#ifdef CONFIG_CAPDL_LOADER_PRINTF" +++ ".name = \"" ++ name ++ "\"," +++ "#endif" +++
showObjectFields objs id (snd obj) irqNode cdt ms +++
"}"
where
id = fst obj
name = fst id ++ (case snd id of
Just index -> "[" ++ show index ++ "]"
_ -> "")
showObjects :: Map ObjID Int -> Int -> [(ObjID, KernelObject Word)] -> IRQMap -> CDT -> ObjMap Word -> String
showObjects _ _ [] _ _ _ = ""
showObjects objs counter (x:xs) irqNode cdt ms =
"[" ++ show counter ++ "] = " ++ showObject objs x irqNode cdt ms ++ "," +++
showObjects objs (counter + 1) xs irqNode cdt ms
sizeOf :: Arch -> KernelObject Word -> Word
sizeOf _ (Frame vmSz _) = vmSz
sizeOf _ (Untyped (Just bSz) _) = 2 ^ bSz
sizeOf _ (CNode _ bSz) = 16 * 2 ^ bSz
sizeOf _ Endpoint = 16
sizeOf _ Notification = 16
sizeOf _ ASIDPool {} = 4 * 2^10
sizeOf _ IOPT {} = 4 * 2^10
sizeOf _ IODevice {} = 1
sizeOf IA32 TCB {} = 2^10
sizeOf IA32 PD {} = 4 * 2^10
sizeOf IA32 PT {} = 4 * 2^10
sizeOf ARM11 TCB {} = 512
sizeOf ARM11 PD {} = 16 * 2^10
sizeOf ARM11 PT {} = 2^10
sizeOf _ _ = 0
{- A custom sorting function for CapDL objects. Essentially we want to sort the
- objects in descending order of size for optimal runtime allocation, but we
- also want to give some rudimentary finer control to the user producing the
- input specification. For this, we sort the objects secondarily by their
- name. This means the spec creator can name their objects to induce a
- specific ordering for identically sized objects. This is primarily useful
- for getting physically contiguous frames.
-}
sorter :: Arch -> (ObjID, KernelObject Word) -> (ObjID, KernelObject Word) -> Ordering
sorter arch a b =
if a_size == b_size
then fst a `compare` fst b
else b_size `compare` a_size -- Arguments reversed for largest to smallest
where
a_size = sizeOf arch $ snd a
b_size = sizeOf arch $ snd b
memberObjects :: Map ObjID Int -> Arch -> [(ObjID, KernelObject Word)] -> IRQMap -> CDT ->
ObjMap Word -> String
memberObjects obj_ids _ objs irqNode cdt objs' =
".objects = (CDL_Object[]) {" +++
showObjects obj_ids 0 objs irqNode cdt objs' +++
"},"
-- Emit an array where each entry represents a given interrupt. Each is -1 if
-- that interrupt has no handler or else the object ID of the interrupt
-- (0-sized CNode).
memberIRQs :: Map ObjID Int -> IRQMap -> Arch -> String
memberIRQs objs irqNode _ =
".irqs = {" +++
(join ", " $ Data.List.map (\k -> show $ case Map.lookup k irqNode of
Just i -> fromJust $ Map.lookup i objs
_ -> -1) [0..(CONFIG_CAPDL_LOADER_MAX_IRQS - 1)]) +++
"},"
printC :: Model Word -> Idents CapName -> CopyMap -> Doc
printC (Model arch objs irqNode cdt _) _ _ =
text $
"/* Generated file. Your changes will be overwritten. */" +++
"" +++
"#include <capdl.h>" +++
"" +++
"#ifndef INVALID_SLOT" +++
"#define INVALID_SLOT (-1)" +++
"#endif" +++
"" +++
maxObjects objs_sz +++ -- FIXME: I suspect this is not the right list to measure.
"" +++
"CDL_Model capdl_spec = {" +++
memberArch arch +++
memberNum objs_sz +++
memberIRQs obj_ids irqNode arch +++
memberObjects obj_ids arch objs' irqNode cdt objs +++
"};"
where
objs_sz = length $ Map.toList objs
objs' = sortBy (sorter arch) $ Map.toList objs
obj_ids = Map.fromList $ flip zip [0..] $ Prelude.map fst objs'
| seL4/capDL-tool | CapDL/PrintC.hs | bsd-2-clause | 14,045 | 0 | 34 | 3,531 | 4,202 | 2,134 | 2,068 | 259 | 13 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QAbstractPrintDialog_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QAbstractPrintDialog_h where
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QAbstractPrintDialog ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractPrintDialog_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QAbstractPrintDialog_unSetUserMethod" qtc_QAbstractPrintDialog_unSetUserMethod :: Ptr (TQAbstractPrintDialog a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QAbstractPrintDialogSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractPrintDialog_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QAbstractPrintDialog ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractPrintDialog_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QAbstractPrintDialogSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractPrintDialog_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QAbstractPrintDialog ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractPrintDialog_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QAbstractPrintDialogSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QAbstractPrintDialog_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QAbstractPrintDialog setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QAbstractPrintDialog_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractPrintDialog_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setUserMethod" qtc_QAbstractPrintDialog_setUserMethod :: Ptr (TQAbstractPrintDialog a) -> CInt -> Ptr (Ptr (TQAbstractPrintDialog x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QAbstractPrintDialog :: (Ptr (TQAbstractPrintDialog x0) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QAbstractPrintDialog_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QAbstractPrintDialog setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QAbstractPrintDialog_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractPrintDialog_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QAbstractPrintDialog setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QAbstractPrintDialog_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractPrintDialog_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setUserMethodVariant" qtc_QAbstractPrintDialog_setUserMethodVariant :: Ptr (TQAbstractPrintDialog a) -> CInt -> Ptr (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QAbstractPrintDialog :: (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QAbstractPrintDialog_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QAbstractPrintDialog setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QAbstractPrintDialog_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QAbstractPrintDialog_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QAbstractPrintDialog ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QAbstractPrintDialog_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QAbstractPrintDialog_unSetHandler" qtc_QAbstractPrintDialog_unSetHandler :: Ptr (TQAbstractPrintDialog a) -> CWString -> IO (CBool)
instance QunSetHandler (QAbstractPrintDialogSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QAbstractPrintDialog_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qAbstractPrintDialogFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler1" qtc_QAbstractPrintDialog_setHandler1 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog1 :: (Ptr (TQAbstractPrintDialog x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qAbstractPrintDialogFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qexec_h (QAbstractPrintDialog ()) (()) where
exec_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_exec cobj_x0
foreign import ccall "qtc_QAbstractPrintDialog_exec" qtc_QAbstractPrintDialog_exec :: Ptr (TQAbstractPrintDialog a) -> IO CInt
instance Qexec_h (QAbstractPrintDialogSc a) (()) where
exec_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_exec cobj_x0
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qAbstractPrintDialogFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler2" qtc_QAbstractPrintDialog_setHandler2 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog2 :: (Ptr (TQAbstractPrintDialog x0) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qAbstractPrintDialogFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qaccept_h (QAbstractPrintDialog ()) (()) where
accept_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_accept cobj_x0
foreign import ccall "qtc_QAbstractPrintDialog_accept" qtc_QAbstractPrintDialog_accept :: Ptr (TQAbstractPrintDialog a) -> IO ()
instance Qaccept_h (QAbstractPrintDialogSc a) (()) where
accept_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_accept cobj_x0
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler3" qtc_QAbstractPrintDialog_setHandler3 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog3 :: (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QcloseEvent_h (QAbstractPrintDialog ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_closeEvent" qtc_QAbstractPrintDialog_closeEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QAbstractPrintDialogSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_closeEvent cobj_x0 cobj_x1
instance QcontextMenuEvent_h (QAbstractPrintDialog ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_contextMenuEvent" qtc_QAbstractPrintDialog_contextMenuEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QAbstractPrintDialogSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler4" qtc_QAbstractPrintDialog_setHandler4 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog4 :: (Ptr (TQAbstractPrintDialog x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> CInt -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
let x1int = fromCInt x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qdone_h (QAbstractPrintDialog ()) ((Int)) where
done_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_done cobj_x0 (toCInt x1)
foreign import ccall "qtc_QAbstractPrintDialog_done" qtc_QAbstractPrintDialog_done :: Ptr (TQAbstractPrintDialog a) -> CInt -> IO ()
instance Qdone_h (QAbstractPrintDialogSc a) ((Int)) where
done_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_done cobj_x0 (toCInt x1)
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler5" qtc_QAbstractPrintDialog_setHandler5 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog5 :: (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QAbstractPrintDialog ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_event cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_event" qtc_QAbstractPrintDialog_event :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QAbstractPrintDialogSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_event cobj_x0 cobj_x1
instance QkeyPressEvent_h (QAbstractPrintDialog ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_keyPressEvent" qtc_QAbstractPrintDialog_keyPressEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QAbstractPrintDialogSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_keyPressEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qAbstractPrintDialogFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler6" qtc_QAbstractPrintDialog_setHandler6 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog6 :: (Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qAbstractPrintDialogFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QAbstractPrintDialog ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_minimumSizeHint cobj_x0
foreign import ccall "qtc_QAbstractPrintDialog_minimumSizeHint" qtc_QAbstractPrintDialog_minimumSizeHint :: Ptr (TQAbstractPrintDialog a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QAbstractPrintDialogSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QAbstractPrintDialog ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QAbstractPrintDialog_minimumSizeHint_qth" qtc_QAbstractPrintDialog_minimumSizeHint_qth :: Ptr (TQAbstractPrintDialog a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QAbstractPrintDialogSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance Qreject_h (QAbstractPrintDialog ()) (()) where
reject_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_reject cobj_x0
foreign import ccall "qtc_QAbstractPrintDialog_reject" qtc_QAbstractPrintDialog_reject :: Ptr (TQAbstractPrintDialog a) -> IO ()
instance Qreject_h (QAbstractPrintDialogSc a) (()) where
reject_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_reject cobj_x0
instance QresizeEvent_h (QAbstractPrintDialog ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_resizeEvent" qtc_QAbstractPrintDialog_resizeEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QAbstractPrintDialogSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler7" qtc_QAbstractPrintDialog_setHandler7 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog7 :: (Ptr (TQAbstractPrintDialog x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QAbstractPrintDialog ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QAbstractPrintDialog_setVisible" qtc_QAbstractPrintDialog_setVisible :: Ptr (TQAbstractPrintDialog a) -> CBool -> IO ()
instance QsetVisible_h (QAbstractPrintDialogSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QAbstractPrintDialog ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_showEvent" qtc_QAbstractPrintDialog_showEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QAbstractPrintDialogSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_showEvent cobj_x0 cobj_x1
instance QqsizeHint_h (QAbstractPrintDialog ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_sizeHint cobj_x0
foreign import ccall "qtc_QAbstractPrintDialog_sizeHint" qtc_QAbstractPrintDialog_sizeHint :: Ptr (TQAbstractPrintDialog a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QAbstractPrintDialogSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_sizeHint cobj_x0
instance QsizeHint_h (QAbstractPrintDialog ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QAbstractPrintDialog_sizeHint_qth" qtc_QAbstractPrintDialog_sizeHint_qth :: Ptr (TQAbstractPrintDialog a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QAbstractPrintDialogSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QactionEvent_h (QAbstractPrintDialog ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_actionEvent" qtc_QAbstractPrintDialog_actionEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QAbstractPrintDialogSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_actionEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QAbstractPrintDialog ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_changeEvent" qtc_QAbstractPrintDialog_changeEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QAbstractPrintDialogSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_changeEvent cobj_x0 cobj_x1
instance QdevType_h (QAbstractPrintDialog ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_devType cobj_x0
foreign import ccall "qtc_QAbstractPrintDialog_devType" qtc_QAbstractPrintDialog_devType :: Ptr (TQAbstractPrintDialog a) -> IO CInt
instance QdevType_h (QAbstractPrintDialogSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_devType cobj_x0
instance QdragEnterEvent_h (QAbstractPrintDialog ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_dragEnterEvent" qtc_QAbstractPrintDialog_dragEnterEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QAbstractPrintDialogSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QAbstractPrintDialog ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_dragLeaveEvent" qtc_QAbstractPrintDialog_dragLeaveEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QAbstractPrintDialogSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_dragLeaveEvent cobj_x0 cobj_x1
instance QdragMoveEvent_h (QAbstractPrintDialog ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_dragMoveEvent" qtc_QAbstractPrintDialog_dragMoveEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QAbstractPrintDialogSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_dragMoveEvent cobj_x0 cobj_x1
instance QdropEvent_h (QAbstractPrintDialog ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_dropEvent" qtc_QAbstractPrintDialog_dropEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QAbstractPrintDialogSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_dropEvent cobj_x0 cobj_x1
instance QenterEvent_h (QAbstractPrintDialog ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_enterEvent" qtc_QAbstractPrintDialog_enterEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QAbstractPrintDialogSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_enterEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QAbstractPrintDialog ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_focusInEvent" qtc_QAbstractPrintDialog_focusInEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QAbstractPrintDialogSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QAbstractPrintDialog ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_focusOutEvent" qtc_QAbstractPrintDialog_focusOutEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QAbstractPrintDialogSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler8" qtc_QAbstractPrintDialog_setHandler8 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog8 :: (Ptr (TQAbstractPrintDialog x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QheightForWidth_h (QAbstractPrintDialog ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QAbstractPrintDialog_heightForWidth" qtc_QAbstractPrintDialog_heightForWidth :: Ptr (TQAbstractPrintDialog a) -> CInt -> IO CInt
instance QheightForWidth_h (QAbstractPrintDialogSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QAbstractPrintDialog ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_hideEvent" qtc_QAbstractPrintDialog_hideEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QAbstractPrintDialogSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_hideEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler9" qtc_QAbstractPrintDialog_setHandler9 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog9 :: (Ptr (TQAbstractPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qAbstractPrintDialogFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QAbstractPrintDialog ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QAbstractPrintDialog_inputMethodQuery" qtc_QAbstractPrintDialog_inputMethodQuery :: Ptr (TQAbstractPrintDialog a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QAbstractPrintDialogSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyReleaseEvent_h (QAbstractPrintDialog ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_keyReleaseEvent" qtc_QAbstractPrintDialog_keyReleaseEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QAbstractPrintDialogSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QAbstractPrintDialog ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_leaveEvent" qtc_QAbstractPrintDialog_leaveEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QAbstractPrintDialogSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_leaveEvent cobj_x0 cobj_x1
instance QmouseDoubleClickEvent_h (QAbstractPrintDialog ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_mouseDoubleClickEvent" qtc_QAbstractPrintDialog_mouseDoubleClickEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QAbstractPrintDialogSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QAbstractPrintDialog ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_mouseMoveEvent" qtc_QAbstractPrintDialog_mouseMoveEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QAbstractPrintDialogSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QAbstractPrintDialog ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_mousePressEvent" qtc_QAbstractPrintDialog_mousePressEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QAbstractPrintDialogSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QAbstractPrintDialog ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_mouseReleaseEvent" qtc_QAbstractPrintDialog_mouseReleaseEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QAbstractPrintDialogSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_mouseReleaseEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QAbstractPrintDialog ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_moveEvent" qtc_QAbstractPrintDialog_moveEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QAbstractPrintDialogSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QAbstractPrintDialog ()) (QAbstractPrintDialog x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qAbstractPrintDialogFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QAbstractPrintDialog_setHandler10" qtc_QAbstractPrintDialog_setHandler10 :: Ptr (TQAbstractPrintDialog a) -> CWString -> Ptr (Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog10 :: (Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QAbstractPrintDialog10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QAbstractPrintDialogSc a) (QAbstractPrintDialog x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QAbstractPrintDialog10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QAbstractPrintDialog10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QAbstractPrintDialog_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQAbstractPrintDialog x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qAbstractPrintDialogFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QAbstractPrintDialog ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_paintEngine cobj_x0
foreign import ccall "qtc_QAbstractPrintDialog_paintEngine" qtc_QAbstractPrintDialog_paintEngine :: Ptr (TQAbstractPrintDialog a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QAbstractPrintDialogSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QAbstractPrintDialog_paintEngine cobj_x0
instance QpaintEvent_h (QAbstractPrintDialog ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_paintEvent" qtc_QAbstractPrintDialog_paintEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QAbstractPrintDialogSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_paintEvent cobj_x0 cobj_x1
instance QtabletEvent_h (QAbstractPrintDialog ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_tabletEvent" qtc_QAbstractPrintDialog_tabletEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QAbstractPrintDialogSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_tabletEvent cobj_x0 cobj_x1
instance QwheelEvent_h (QAbstractPrintDialog ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QAbstractPrintDialog_wheelEvent" qtc_QAbstractPrintDialog_wheelEvent :: Ptr (TQAbstractPrintDialog a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QAbstractPrintDialogSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QAbstractPrintDialog_wheelEvent cobj_x0 cobj_x1
| uduki/hsQt | Qtc/Gui/QAbstractPrintDialog_h.hs | bsd-2-clause | 65,605 | 0 | 18 | 12,889 | 19,859 | 9,578 | 10,281 | -1 | -1 |
-- |
-- Module : Text.Megaparsec.Lexer
-- Copyright : © 2015 Megaparsec contributors
-- © 2007 Paolo Martini
-- © 1999–2001 Daan Leijen
-- License : BSD3
--
-- Maintainer : Mark Karpov <[email protected]>
-- Stability : experimental
-- Portability : non-portable (uses local universal quantification: PolymorphicComponents)
--
-- High-level parsers to help you write your lexer. The module doesn't
-- impose how you should write your parser, but certain approaches may be
-- more elegant than others. Especially important theme is parsing of write
-- space, comments and indentation.
--
-- This module is intended to be imported qualified:
--
-- > import qualified Text.Megaparsec.Lexer as L
module Text.Megaparsec.Lexer
( -- * White space and indentation
space
, lexeme
, symbol
, symbol'
, indentGuard
, skipLineComment
, skipBlockComment
-- * Character and string literals
, charLiteral
-- * Numbers
, integer
, decimal
, hexadecimal
, octal
, float
, number
, signed )
where
import Control.Applicative ((<|>), some)
import Control.Monad (void)
import Data.Char (readLitChar)
import Data.Maybe (listToMaybe)
import Text.Megaparsec.Combinator
import Text.Megaparsec.Pos
import Text.Megaparsec.Prim
import Text.Megaparsec.ShowToken
import qualified Text.Megaparsec.Char as C
-- White space and indentation
-- | @space spaceChar lineComment blockComment@ produces parser that can
-- parse white space in general. It's expected that you create such a parser
-- once and pass it to other functions in this module as needed (when you
-- see @spaceConsumer@ in documentation, usually it means that something
-- like 'space' is expected there).
--
-- @spaceChar@ is used to parse trivial space characters. You can use
-- 'C.spaceChar' from "Text.Megaparsec.Char" for this purpose as well as
-- your own parser (if you don't want automatically consume newlines, for
-- example).
--
-- @lineComment@ is used to parse line comments. You can use
-- 'skipLineComment' if you don't need anything special.
--
-- @blockComment@ is used to parse block (multi-line) comments. You can use
-- 'skipBlockComment' if you don't need anything special.
--
-- Parsing of white space is an important part of any parser. We propose a
-- convention where every lexeme parser assumes no spaces before the lexeme
-- and consumes all spaces after the lexeme; this is what the 'lexeme'
-- combinator does, and so it's enough to wrap every lexeme parser with
-- 'lexeme' to achieve this. Note that you'll need to call 'space' manually
-- to consume any white space before the first lexeme (i.e. at the beginning
-- of the file).
space :: MonadParsec s m Char
=> m () -- ^ A parser for a space character (e.g. 'C.spaceChar')
-> m () -- ^ A parser for a line comment (e.g. 'skipLineComment')
-> m () -- ^ A parser for a block comment (e.g. 'skipBlockComment')
-> m ()
space ch line block = hidden . skipMany $ choice [ch, line, block]
-- | This is wrapper for lexemes. Typical usage is to supply first argument
-- (parser that consumes white space, probably defined via 'space') and use
-- the resulting function to wrap parsers for every lexeme.
--
-- > lexeme = L.lexeme spaceConsumer
-- > integer = lexeme L.integer
lexeme :: MonadParsec s m Char => m () -> m a -> m a
lexeme spc p = p <* spc
-- | This is a helper to parse symbols, i.e. verbatim strings. You pass the
-- first argument (parser that consumes white space, probably defined via
-- 'space') and then you can use the resulting function to parse strings:
--
-- > symbol = L.symbol spaceConsumer
-- >
-- > parens = between (symbol "(") (symbol ")")
-- > braces = between (symbol "{") (symbol "}")
-- > angles = between (symbol "<") (symbol ">")
-- > brackets = between (symbol "[") (symbol "]")
-- > semicolon = symbol ";"
-- > comma = symbol ","
-- > colon = symbol ":"
-- > dot = symbol "."
symbol :: MonadParsec s m Char => m () -> String -> m String
symbol spc = lexeme spc . C.string
-- | Case-insensitive version of 'symbol'. This may be helpful if you're
-- working with case-insensitive languages.
symbol' :: MonadParsec s m Char => m () -> String -> m String
symbol' spc = lexeme spc . C.string'
-- | @indentGuard spaceConsumer test@ first consumes all white space
-- (indentation) with @spaceConsumer@ parser, then it checks column
-- position. It should satisfy supplied predicate @test@, otherwise the
-- parser fails with error message “incorrect indentation”. On success
-- current column position is returned.
--
-- When you want to parse block of indentation first run this parser with
-- predicate like @(> 1)@ — this will make sure you have some
-- indentation. Use returned value to check indentation on every subsequent
-- line according to syntax of your language.
indentGuard :: MonadParsec s m Char => m () -> (Int -> Bool) -> m Int
indentGuard spc p = do
spc
pos <- sourceColumn <$> getPosition
if p pos
then return pos
else fail "incorrect indentation"
-- | Given comment prefix this function returns parser that skips line
-- comments. Note that it stops just before newline character but doesn't
-- consume the newline. Newline is either supposed to be consumed by 'space'
-- parser or picked up manually.
skipLineComment :: MonadParsec s m Char => String -> m ()
skipLineComment prefix = p >> void (manyTill C.anyChar n)
where p = try $ C.string prefix
n = lookAhead C.newline
-- | @skipBlockComment start end@ skips non-nested block comment starting
-- with @start@ and ending with @end@.
skipBlockComment :: MonadParsec s m Char => String -> String -> m ()
skipBlockComment start end = p >> void (manyTill C.anyChar n)
where p = try $ C.string start
n = try $ C.string end
-- Character and string literals
-- | The lexeme parser parses a single literal character without
-- quotes. Purpose of this parser is to help with parsing of commonly used
-- escape sequences. It's your responsibility to take care of character
-- literal syntax in your language (by surrounding it with single quotes or
-- similar).
--
-- The literal character is parsed according to the grammar rules defined in
-- the Haskell report.
--
-- Note that you can use this parser as a building block to parse various
-- string literals:
--
-- > stringLiteral = char '"' >> manyTill L.charLiteral (char '"')
charLiteral :: MonadParsec s m Char => m Char
charLiteral = label "literal character" $ do
r@(x:_) <- lookAhead $ count' 1 8 C.anyChar
case listToMaybe (readLitChar r) of
Just (c, r') -> count (length r - length r') C.anyChar >> return c
Nothing -> unexpected (showToken x)
-- Numbers
-- | Parse an integer without sign in decimal representation (according to
-- format of integer literals described in Haskell report).
--
-- If you need to parse signed integers, see 'signed' combinator.
integer :: MonadParsec s m Char => m Integer
integer = decimal <?> "integer"
-- | The same as 'integer', but 'integer' is 'label'ed with “integer” label,
-- while this parser is labeled with “decimal integer”.
decimal :: MonadParsec s m Char => m Integer
decimal = nump "" C.digitChar <?> "decimal integer"
-- | Parse an integer in hexadecimal representation. Representation of
-- hexadecimal number is expected to be according to Haskell report except
-- for the fact that this parser doesn't parse “0x” or “0X” prefix. It is
-- reponsibility of the programmer to parse correct prefix before parsing
-- the number itself.
--
-- For example you can make it conform to Haskell report like this:
--
-- > hexadecimal = char '0' >> char' 'x' >> L.hexadecimal
hexadecimal :: MonadParsec s m Char => m Integer
hexadecimal = nump "0x" C.hexDigitChar <?> "hexadecimal integer"
-- | Parse an integer in octal representation. Representation of octal
-- number is expected to be according to Haskell report except for the fact
-- that this parser doesn't parse “0o” or “0O” prefix. It is responsibility
-- of the programmer to parse correct prefix before parsing the number
-- itself.
octal :: MonadParsec s m Char => m Integer
octal = nump "0o" C.octDigitChar <?> "octal integer"
-- | @nump prefix p@ parses /one/ or more characters with @p@ parser, then
-- prepends @prefix@ to returned value and tries to interpret the result as
-- an integer according to Haskell syntax.
nump :: MonadParsec s m Char => String -> m Char -> m Integer
nump prefix baseDigit = read . (prefix ++) <$> some baseDigit
-- | Parse a floating point value without sign. Representation of floating
-- point value is expected to be according to Haskell report.
--
-- If you need to parse signed floats, see 'signed'.
float :: MonadParsec s m Char => m Double
float = label "float" $ read <$> f
where f = do
d <- some C.digitChar
rest <- fraction <|> fExp
return $ d ++ rest
-- | This is a helper for 'float' parser. It parses fractional part of
-- floating point number, that is, dot and everything after it.
fraction :: MonadParsec s m Char => m String
fraction = do
void $ C.char '.'
d <- some C.digitChar
e <- option "" fExp
return $ '.' : d ++ e
-- | This helper parses exponent of floating point numbers.
fExp :: MonadParsec s m Char => m String
fExp = do
expChar <- C.char' 'e'
signStr <- option "" (pure <$> choice (C.char <$> "+-"))
d <- some C.digitChar
return $ expChar : signStr ++ d
-- | Parse a number: either integer or floating point. The parser can handle
-- overlapping grammars graciously.
number :: MonadParsec s m Char => m (Either Integer Double)
number = (Right <$> try float) <|> (Left <$> integer) <?> "number"
-- | @signed space p@ parser parses optional sign, then if there is a sign
-- it will consume optional white space (using @space@ parser), then it runs
-- parser @p@ which should return a number. Sign of the number is changed
-- according to previously parsed sign.
--
-- For example, to parse signed integer you can write:
--
-- > lexeme = L.lexeme spaceConsumer
-- > integer = lexeme L.integer
-- > signedInteger = signed spaceConsumer integer
signed :: (MonadParsec s m Char, Num a) => m () -> m a -> m a
signed spc p = ($) <$> option id (lexeme spc sign) <*> p
-- | Parse a sign and return either 'id' or 'negate' according to parsed
-- sign.
sign :: (MonadParsec s m Char, Num a) => m (a -> a)
sign = (C.char '+' *> return id) <|> (C.char '-' *> return negate)
| neongreen/megaparsec | Text/Megaparsec/Lexer.hs | bsd-2-clause | 10,535 | 0 | 15 | 2,095 | 1,524 | 834 | 690 | -1 | -1 |
-- | Maintainer: 2016 Evan Cofsky <[email protected]>
--
-- Functions running zfs processes.
module Propellor.Property.ZFS.Process where
import Propellor.Base
import Data.String.Utils (split)
import Data.List
-- | Gets the properties of a ZFS volume.
zfsGetProperties :: ZFS -> IO ZFSProperties
zfsGetProperties z =
let plist = fromPropertyList . map (\(_:k:v:_) -> (k, v)) . (map (split "\t"))
in plist <$> runZfs "get" [Just "-H", Just "-p", Just "all"] z
zfsExists :: ZFS -> IO Bool
zfsExists z = any id . map (isInfixOf (zfsName z))
<$> runZfs "list" [Just "-H"] z
-- | Runs the zfs command with the arguments.
--
-- Runs the command with -H which will skip the header line and
-- separate all fields with tabs.
--
-- Replaces Nothing in the argument list with the ZFS pool/dataset.
runZfs :: String -> [Maybe String] -> ZFS -> IO [String]
runZfs cmd args z = lines <$> uncurry readProcess (zfsCommand cmd args z)
-- | Return the ZFS command line suitable for readProcess or cmdProperty.
zfsCommand :: String -> [Maybe String] -> ZFS -> (String, [String])
zfsCommand cmd args z = ("zfs", cmd:(map (maybe (zfsName z) id) args))
| ArchiveTeam/glowing-computing-machine | src/Propellor/Property/ZFS/Process.hs | bsd-2-clause | 1,144 | 2 | 17 | 200 | 349 | 187 | 162 | 15 | 1 |
import Data.Maybe
-- fmap :: (a -> b) -> f a -> f b
onList = fmap (+ 1) [1,2,3]
onJust = fmap (+ 1) (Just 4)
onNothing = fmap (+ 1) Nothing
data MyTree a = Leaf a
| Node a (MyTree a) (MyTree a)
deriving (Show,Eq)
instance Functor MyTree where
fmap f (Leaf a) = Leaf (f a)
fmap f (Node a b c) = (Node (f a) (fmap f b) (fmap f c))
exampleTree :: MyTree Int
exampleTree = Node 5 (Node 3 (Leaf 2) (Leaf 1)) (Node 6 (Leaf 7) (Leaf 8))
| fffej/haskellprojects | misc/TypeClassopedia.hs | bsd-2-clause | 473 | 0 | 9 | 139 | 255 | 134 | 121 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
--------------------------------------------------------------------
-- |
-- Module : Text.Atom.Feed.Export
-- Copyright : (c) Galois, Inc. 2008
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <[email protected]>
-- Stability : provisional
-- Description: Convert from Atom to XML
--
--------------------------------------------------------------------
module Text.Atom.Feed.Export where
import Text.XML as XML
import Text.Feed.Util
import Text.Atom.Feed
import Data.Text hiding (map)
atom_prefix :: Maybe Text
atom_prefix = Nothing -- Just "atom"
atom_thr_prefix :: Maybe Text
atom_thr_prefix = Just "thr"
atomNS :: Text
atomNS = "http://www.w3.org/2005/Atom"
atomThreadNS :: Text
atomThreadNS = "http://purl.org/syndication/thread/1.0"
xmlns_atom :: Attr
xmlns_atom = (qn, atomNS)
where
qn = case atom_prefix of
Nothing -> Name { nameLocalName = "xmlns"
, nameNamespace = Nothing
, namePrefix = Nothing
}
Just s -> Name { nameLocalName = s
, nameNamespace = Nothing -- XXX: is this ok?
, namePrefix = Just "xmlns"
}
xmlns_atom_thread :: Attr
xmlns_atom_thread = (qn,atomThreadNS)
where
qn = case atom_thr_prefix of
Nothing -> Name { nameLocalName = "xmlns"
, nameNamespace = Nothing
, namePrefix = Nothing
}
Just s -> Name { nameLocalName = s
, nameNamespace = Nothing -- XXX: is this ok?
, namePrefix = Just "xmlns"
}
atomName :: Text -> Name
atomName nc = Name { nameLocalName = nc
, nameNamespace = Just atomNS
, namePrefix = atom_prefix
}
atomAttr :: Text -> Text -> Attr
atomAttr x y = ((atomName x), y)
atomNode :: Text -> [XML.Node] -> XML.Element
atomNode x xs = def { elementName = atomName x, elementNodes = xs }
atomLeaf :: Text -> Text -> XML.Element
atomLeaf tag txt = def
{ elementName = atomName tag
, elementNodes = [ NodeContent txt ]
}
atomThreadName :: Text -> Name
atomThreadName nc =
Name { nameLocalName = nc
, nameNamespace = Just atomThreadNS
, namePrefix = atom_thr_prefix
}
atomThreadAttr :: Text -> Text -> Attr
atomThreadAttr x y = ((atomThreadName x), y)
atomThreadNode :: Text -> [XML.Node] -> XML.Element
atomThreadNode x xs =
def { elementName = atomThreadName x, elementNodes = xs }
atomThreadLeaf :: Text -> Text -> XML.Element
atomThreadLeaf tag txt =
def { elementName = atomThreadName tag
, elementNodes = [ NodeContent txt ]
}
--------------------------------------------------------------------------------
xmlFeed :: Feed -> XML.Element
xmlFeed f = ( atomNode "feed"
$ map NodeElement
$ [ xmlTitle (feedTitle f) ]
++ [ xmlId (feedId f) ]
++ [ xmlUpdated (feedUpdated f) ]
++ map xmlLink (feedLinks f)
++ map xmlAuthor (feedAuthors f)
++ map xmlCategory (feedCategories f)
++ map xmlContributor (feedContributors f)
++ mb xmlGenerator (feedGenerator f)
++ mb xmlIcon (feedIcon f)
++ mb xmlLogo (feedLogo f)
++ mb xmlRights (feedRights f)
++ mb xmlSubtitle (feedSubtitle f)
++ map xmlEntry (feedEntries f)
++ feedOther f )
{ elementAttributes = [xmlns_atom] }
xmlEntry :: Entry -> XML.Element
xmlEntry e = ( atomNode "entry"
$ map NodeElement
$ [ xmlId (entryId e) ]
++ [ xmlTitle (entryTitle e) ]
++ [ xmlUpdated (entryUpdated e) ]
++ map xmlAuthor (entryAuthors e)
++ map xmlCategory (entryCategories e)
++ mb xmlContent (entryContent e)
++ map xmlContributor (entryContributor e)
++ map xmlLink (entryLinks e)
++ mb xmlPublished (entryPublished e)
++ mb xmlRights (entryRights e)
++ mb xmlSource (entrySource e)
++ mb xmlSummary (entrySummary e)
++ mb xmlInReplyTo (entryInReplyTo e)
++ mb xmlInReplyTotal (entryInReplyTotal e)
++ entryOther e )
{ elementAttributes = entryAttrs e }
xmlContent :: EntryContent -> XML.Element
xmlContent cont = case cont of
TextContent t -> (atomLeaf "content" t)
{ elementAttributes = [ atomAttr "type" "text" ] }
HTMLContent t -> (atomLeaf "content" t)
{ elementAttributes = [ atomAttr "type" "html" ] }
XHTMLContent x -> (atomNode "content" [ NodeElement x ])
{ elementAttributes = [ atomAttr "type" "xhtml" ] }
MixedContent mbTy cs -> (atomNode "content" cs)
{ elementAttributes = mb (atomAttr "type") mbTy }
ExternalContent mbTy src -> (atomNode "content" [])
{ elementAttributes = [ atomAttr "src" src ]
++ mb (atomAttr "type") mbTy }
xmlCategory :: Category -> XML.Element
xmlCategory c = (atomNode "category" (map NodeElement (catOther c)))
{ elementAttributes = [ atomAttr "term" (catTerm c) ]
++ mb (atomAttr "scheme") (catScheme c)
++ mb (atomAttr "label") (catLabel c)
}
xmlLink :: Link -> XML.Element
xmlLink l = (atomNode "link" (map NodeElement (linkOther l)))
{ elementAttributes = [ atomAttr "href" (linkHref l) ]
++ mb (atomAttr "rel" . either id id) (linkRel l)
++ mb (atomAttr "type") (linkType l)
++ mb (atomAttr "hreflang") (linkHrefLang l)
++ mb (atomAttr "title") (linkTitle l)
++ mb (atomAttr "length") (linkLength l)
++ linkAttrs l
}
xmlSource :: Source -> Element
xmlSource s = atomNode "source"
$ map NodeElement
$ sourceOther s
++ map xmlAuthor (sourceAuthors s)
++ map xmlCategory (sourceCategories s)
++ mb xmlGenerator (sourceGenerator s)
++ mb xmlIcon (sourceIcon s)
++ mb xmlId (sourceId s)
++ map xmlLink (sourceLinks s)
++ mb xmlLogo (sourceLogo s)
++ mb xmlRights (sourceRights s)
++ mb xmlSubtitle (sourceSubtitle s)
++ mb xmlTitle (sourceTitle s)
++ mb xmlUpdated (sourceUpdated s)
xmlGenerator :: Generator -> Element
xmlGenerator g = (atomLeaf "generator" (genText g))
{ elementAttributes = mb (atomAttr "uri") (genURI g)
++ mb (atomAttr "version") (genVersion g)
}
xmlAuthor :: Person -> XML.Element
xmlAuthor p = atomNode "author" (xmlPerson p)
xmlContributor :: Person -> XML.Element
xmlContributor c = atomNode "contributor" (xmlPerson c)
xmlPerson :: Person -> [XML.Node]
xmlPerson p = map NodeElement $
[ atomLeaf "name" (personName p) ]
++ mb (atomLeaf "uri") (personURI p)
++ mb (atomLeaf "email") (personEmail p)
++ personOther p
xmlInReplyTo :: InReplyTo -> XML.Element
xmlInReplyTo irt =
(atomThreadNode "in-reply-to" (replyToContent irt))
{ elementAttributes =
mb (atomThreadAttr "ref") (Just $ replyToRef irt)
++ mb (atomThreadAttr "href") (replyToHRef irt)
++ mb (atomThreadAttr "type") (replyToType irt)
++ mb (atomThreadAttr "source") (replyToSource irt)
++ replyToOther irt
}
xmlInReplyTotal :: InReplyTotal -> XML.Element
xmlInReplyTotal irt =
(atomThreadLeaf "total" (pack $ show $ replyToTotal irt))
{ elementAttributes = replyToTotalOther irt }
xmlId :: Text -> XML.Element
xmlId i = atomLeaf "id" i
xmlIcon :: URI -> XML.Element
xmlIcon i = atomLeaf "icon" i
xmlLogo :: URI -> XML.Element
xmlLogo l = atomLeaf "logo" l
xmlUpdated :: Date -> XML.Element
xmlUpdated u = atomLeaf "updated" u
xmlPublished :: Date -> XML.Element
xmlPublished p = atomLeaf "published" p
xmlRights :: TextContent -> XML.Element
xmlRights r = xmlTextContent "rights" r
xmlTitle :: TextContent -> XML.Element
xmlTitle r = xmlTextContent "title" r
xmlSubtitle :: TextContent -> XML.Element
xmlSubtitle s = xmlTextContent "subtitle" s
xmlSummary :: TextContent -> XML.Element
xmlSummary s = xmlTextContent "summary" s
xmlTextContent :: Text -> TextContent -> XML.Element
xmlTextContent tg t =
case t of
TextText s -> (atomLeaf tg s) { elementAttributes = [atomAttr "type" "text"] }
HTMLText s -> (atomLeaf tg s) { elementAttributes = [atomAttr "type" "html"] }
XHTMLText e -> (atomNode tg [NodeElement e])
{ elementAttributes = [atomAttr "type" "xhtml"] }
--------------------------------------------------------------------------------
mb :: (a -> b) -> Maybe a -> [b]
mb _ Nothing = []
mb f (Just x) = [f x]
| haskell-pkg-janitors/feed | Text/Atom/Feed/Export.hs | bsd-3-clause | 9,270 | 8 | 25 | 2,946 | 2,662 | 1,369 | 1,293 | 192 | 5 |
module Data.Bitmap.Types
( Dimensions
, Coordinates
, Depth(..)
, CompleteBitmapFormat(..)
, ImageBitmapFormat(..)
) where
-- | (width, height)
type Dimensions i = (i, i)
-- | (row, column)
type Coordinates i = (i, i)
-- | These are the color depths that the bitmap class supports
--
-- The depth does not necessarily indicate any particular order; instead the
-- components listed in the name indicate which components are contained in
-- each pixel.
data Depth =
Depth24RGB -- ^ 24 bit pixel consisting of one pixel per component and lacking an alpha component
--
-- Each pixel of this type thus requires three bytes to be fully represented. Implementations
-- are not required to pack the image data, however; they are free, for instance, to store each pixel
-- in 32-bit (4-byte) integers.
| Depth32RGBA -- ^ 32 bit pixel also consisting of one pixel per component but contains the alpha component
--
-- Four bytes are needed for pixels of this type to be fully represented.
deriving (Eq, Ord, Enum, Bounded, Show, Read, Typeable, Data)
-- | Formats that bitmaps that are instances of the 'Bitmap' class need to support; these formats include the necessary meta-information
data CompleteBitmapFormat =
CBF_BMPIU -- ^ Uncompressed BITMAPINFOHEADER BMP format (CompleteBitmapFormat_BitMaPInfoheaderUncompressed)
-- Due to being uncompressed, strings encoded in this format can grow large quite quickly.
-- This format is standard and widely supported, and can be read and written directly to and from a file, the extension
-- of which is typically ".bmp"
| CBF_BMPIU64 -- ^ Same as 'CBF_BMPIU' except that that final result is base-64 encoded and is thus suitable for human-readable strings defining a bitmap (CompleteBitmapFormat_BitMaPInfoheaderUncompressed)
--
-- Like 'CBF_BMPIU', strings encoded in this format can become large quick quickly, and even about a third more so, due to the more restrictive range of values.
deriving (Eq, Ord, Enum, Bounded, Show, Read, Typeable, Data)
-- | Formats for raw image data that don't include information such as dimensions
data ImageBitmapFormat = FooBar
| bairyn/bitmaps | src/Data/Bitmap/Data.hs | bsd-3-clause | 2,348 | 0 | 6 | 579 | 183 | 119 | 64 | 17 | 0 |
module Crypto.Hash.TX.Utils
( MD5Hash(..)
, SHA256Hash(..)
, md5HashFile, md5HashBS, md5HashLBS
, sha256HashFile, sha256HashBS, sha256HashLBS
) where
-- {{{1 imports
import Prelude
import qualified Crypto.Hash.MD5 as MD5
import qualified Crypto.Hash.SHA256 as SHA256
import qualified Data.ByteString.Lazy as LB
import Data.ByteString (ByteString)
import Data.SafeCopy (SafeCopy(..), contain, safeGet, safePut)
import Database.Persist (PersistField(..))
import Database.Persist.Sql (PersistFieldSql(..), SqlType(..))
import Data.Byteable (Byteable(..))
import Data.Binary (Binary(..))
-- }}}1
newtype MD5Hash = MD5Hash { unMD5Hash :: ByteString }
deriving (Show, Eq, Ord)
instance SafeCopy MD5Hash where
getCopy = contain $ MD5Hash <$> safeGet
putCopy (MD5Hash x) = contain $ safePut x
errorTypeName _ = "MD5Hash"
instance PersistField MD5Hash where
toPersistValue = toPersistValue . unMD5Hash
fromPersistValue = fmap MD5Hash . fromPersistValue
instance PersistFieldSql MD5Hash where
sqlType _ = SqlBlob
instance Byteable MD5Hash where
toBytes (MD5Hash x) = toBytes x
byteableLength (MD5Hash x) = byteableLength x
withBytePtr (MD5Hash x) f = withBytePtr x f
instance Binary MD5Hash where
put (MD5Hash x) = put x
get = MD5Hash <$> get
md5HashFile :: FilePath -> IO MD5Hash
md5HashFile = fmap md5HashLBS . LB.readFile
md5HashLBS :: LB.ByteString -> MD5Hash
md5HashLBS = MD5Hash . MD5.hashlazy
md5HashBS :: ByteString -> MD5Hash
md5HashBS = MD5Hash . MD5.hash
newtype SHA256Hash = SHA256Hash { unSHA256Hash :: ByteString }
deriving (Show, Eq, Ord)
instance SafeCopy SHA256Hash where
getCopy = contain $ SHA256Hash <$> safeGet
putCopy (SHA256Hash x) = contain $ safePut x
errorTypeName _ = "SHA256Hash"
instance PersistField SHA256Hash where
toPersistValue = toPersistValue . unSHA256Hash
fromPersistValue = fmap SHA256Hash . fromPersistValue
instance PersistFieldSql SHA256Hash where
sqlType _ = SqlBlob
instance Byteable SHA256Hash where
toBytes (SHA256Hash x) = toBytes x
byteableLength (SHA256Hash x) = byteableLength x
withBytePtr (SHA256Hash x) f = withBytePtr x f
instance Binary SHA256Hash where
put (SHA256Hash x) = put x
get = SHA256Hash <$> get
sha256HashFile :: FilePath -> IO SHA256Hash
sha256HashFile = fmap sha256HashLBS . LB.readFile
sha256HashLBS :: LB.ByteString -> SHA256Hash
sha256HashLBS = SHA256Hash . SHA256.hashlazy
sha256HashBS :: ByteString -> SHA256Hash
sha256HashBS = SHA256Hash . SHA256.hash
-- vim: set foldmethod=marker:
| txkaduo/hs-hash-utils | Crypto/Hash/TX/Utils.hs | bsd-3-clause | 2,803 | 0 | 8 | 680 | 748 | 414 | 334 | 63 | 1 |
module Frameworks.CoreFoundation.Range where
data Range = Range { rangeLocation, rangeLength :: Index }
| ekmett/objective-c | Frameworks/CoreFoundation/Range.hs | bsd-3-clause | 105 | 0 | 8 | 14 | 24 | 16 | 8 | 2 | 0 |
{-# OPTIONS_GHC -Wall #-}
module Homework.A.HanoiSpec where
import Homework.A.Hanoi
import Test.Hspec
a = "a"
b = "b"
c = "c"
spec :: Spec
spec = describe "Homework.A.Hanoi" $ do
describe "hanoi" $ do
it "solves the problem for 1 disc" $ do
hanoi 1 a b c `shouldBe` [(a,b)]
it "solves the problem for 2 discs" $ do
hanoi 2 a b c `shouldBe` [(a,c), (a,b), (c,b)]
it "solves the problem for 3 discs" $ do
hanoi 3 a b c `shouldBe` [(a,b), (a,c), (b,c), (a,b), (c,a), (c,b), (a,b)]
| nicolashery/cis194 | test/Homework/A/HanoiSpec.hs | bsd-3-clause | 516 | 0 | 16 | 127 | 244 | 140 | 104 | 16 | 1 |
{-|
Module : $Header$
Description : Adapter for communicating with Telegram via its http poll API.
Copyright : (c) Justus Adam, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
See http://marvin.readthedocs.io/en/latest/adapters.html#poll for documentation about this adapter.
=== Caveats:
'resolveUser' and 'resolveChannel' resolving are not yet supported in this adapter and always returns 'Nothing'. See <https://github.com/JustusAdam/marvin/issues/10 #10>.
-}
{-# LANGUAGE CPP #-}
module Marvin.Adapter.Telegram.Poll
( TelegramAdapter, Poll
, TelegramChat(..), ChatType(..)
, TelegramUser
, MkTelegram
, TelegramFileId
, TelegramRemoteFile, TelegramRemoteFileStruct
, TelegramLocalFile, TelegramLocalFileStruct
, HasLastName(lastName), HasId_(id_)
, HasFirstName(firstName), HasType_(type_), HasStruct(struct)
) where
import Control.Concurrent.Chan.Lifted
import Control.Concurrent.Lifted
import Control.Monad
import Control.Monad.Logger
import Data.Aeson hiding (Error, Success)
import Data.IORef.Lifted
import Lens.Micro.Platform
import Marvin.Adapter
import Marvin.Adapter.Telegram.Internal.Common
import Marvin.Internal.LensClasses
import Marvin.Interpolate.Text
import Network.HTTP.Client (managerResponseTimeout)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.Wreq
#if MIN_VERSION_http_client(0,5,0)
import Network.HTTP.Client (responseTimeoutMicro)
#else
responseTimeoutMicro = Just
#endif
data UpdateWithId = UpdateWithId {updateId :: Integer, updateContent :: TelegramUpdate Poll }
instance FromJSON UpdateWithId where
parseJSON = withObject "expected object" $ \o -> UpdateWithId <$> o .: "update_id" <*> parseJSON (Object o)
pollEventGetter :: Chan (TelegramUpdate Poll) -> AdapterM (TelegramAdapter Poll) ()
pollEventGetter msgChan = do
idRef <- newIORef Nothing
forever $ do
timeout <- lookupFromAdapterConfig "polling-timeout" >>= readTimeout
let defParams = ["timeout" := (timeout :: Int) ]
nextId <- readIORef idRef
let pollSettings = defaults & manager . _Left .~ tlsManagerSettings { managerResponseTimeout = responseTimeoutMicro ((timeout + 3) * 1000)}
response <- execAPIMethodWith pollSettings parseJSON "getUpdates" $ maybe defParams ((:defParams) . ("offset" :=)) nextId
case response of
Left err -> do
logErrorN $(isT "Unable to parse json: #{err}")
threadDelay 30000
Right (Error code desc) -> do
logErrorN $(isT "Sending message failed with #{code}: #{desc}")
threadDelay 30000
Right Success {result=[]} -> return ()
Right Success {result=updates} -> do
writeIORef idRef $ Just $ succ $ maximum $ map updateId updates
logDebugN "Writing messages"
writeList2Chan msgChan $ map updateContent updates
where
defaultTimeout = 120
readTimeout Nothing = return defaultTimeout
readTimeout (Just n)
| n < 0 = do
logErrorN $(isT "Telegram adapter poll timeout must be positive, was #{n} (using default timeout instead)")
return defaultTimeout
| otherwise = return n
-- | Use the telegram API by fetching updates via HTTP
data Poll
instance MkTelegram Poll where
mkAdapterId = "telegram-poll"
mkEventGetter = pollEventGetter
| JustusAdam/marvin | src/Marvin/Adapter/Telegram/Poll.hs | bsd-3-clause | 3,697 | 0 | 20 | 956 | 720 | 385 | 335 | -1 | -1 |
-- Exercise1.hs
module Exercise1 where
-- Exercise 1.
-- Add support for the backquote syntactic sugar: the Scheme standard details
-- what it should expand into (quasiquote/unquote).
import Control.Monad
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal -- (a b c ... . z)
| Number Integer
| String String
| Bool Bool
-- Begin helper functions (functions which don't return `LispVal`s):
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
spaces :: Parser ()
spaces = skipMany1 space
-- End helper functions.
-- Begin Lisp parsing functions:
parseString :: Parser LispVal
parseString = do
char '"'
x <- many (noneOf "\"") -- 0 or more non-doublequote characters.
char '"'
return $ String x
parseAtom :: Parser LispVal
parseAtom = do
first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = first:rest
return $ case atom of
"#t" -> Bool True
"#f" -> Bool False
_ -> Atom atom
parseNumber :: Parser LispVal
parseNumber = liftM (Number . read) $ many1 digit
-- End Lisp parsing functions.
-- Start recursive parsers:
parseList :: Parser LispVal
parseList = liftM List $ sepBy parseExpr spaces
parseDottedList :: Parser LispVal
parseDottedList = do
hd <- endBy parseExpr spaces
tl <- char '.' >> spaces >> parseExpr
return $ DottedList hd tl
parseQuoted :: Parser LispVal
parseQuoted = do
char '\''
x <- parseExpr
return $ List [Atom "quote", x]
-- TODO these could be refactored into a single fn.
parseQuasiQuoted :: Parser LispVal
parseQuasiQuoted = do
char '`'
x <- parseExpr
return $ List [Atom "quasiquote", x]
parseUnQuote :: Parser LispVal
parseUnQuote = do
char ','
x <- parseExpr
return $ List [Atom "unquote", x]
parseAtUnQuote :: Parser LispVal
parseAtUnQuote = do
string ",@"
x <- parseExpr
return $ List [Atom "at-unquote", x]
-- End recursive parsers.
parseExpr :: Parser LispVal
parseExpr = parseAtom
<|> parseString
<|> parseNumber
<|> parseQuoted
<|> parseQuasiQuoted
<|> (try parseUnQuote)
<|> parseAtUnQuote
-- TODO maybe refactor this into a general parseAnyList?
-- I just don't like the do and char actions included amidst the
-- self-contained parse[Atom/String/Number/Quoted] functions.
<|> do char '('
x <- try parseList <|> parseDottedList
char ')'
return x
-- Begin "main"/"driver" functions:
readExpr :: String -> String
readExpr input = case parse parseExpr "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"
main :: IO ()
main = do
(expr:_) <- getArgs
putStrLn (readExpr expr)
-- End "main"/"driver" functions.
| EFulmer/haskell-scheme-wikibook | src/Exercises/Ch2/Pt2/Exercise1.hs | bsd-3-clause | 3,012 | 0 | 11 | 828 | 730 | 361 | 369 | 78 | 3 |
{-
Copyright (c) 2004, Philippa Jane Cowderoy
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the original author nor the names of any
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-}
module ScriptSyntax (scriptLink, matchScriptLink) where
import Text.XHtml
import Text.ParserCombinators.Parsec
data ScriptParm = Field String | Value String String
scriptname = many1 alphaNum
fieldname = many1 alphaNum
parmstring = do char '"'
ps <- manyTill anyChar (char '"')
return ps
scriptparm = try (do f <- fieldname
char '='
p <- parmstring
return (Value f p)
)
<|>
do f <- fieldname
return (Field f)
scriptLink sn = do char '['
char ':'
s <- scriptname
char '|'
ps <- many (do p <- scriptparm
many (char ' ')
return p
)
char '|'
t <- manyTill anyChar (try $ do char ':'; char ']';)
t <- case t of
[] -> return s
_ -> return t
case ps of
[] -> linkToScript s t
ps -> return (form (
(foldl1 (\a b->a +++ br +++ b)
(map parmToField ps)
)
+++
input ! [thetype "submit", value t]
) ! [action (sn ++ "?script=" ++ s),
method "post"
]
)
where parmToField (Value f v) =
input ! [thetype "hidden",
name f,
value v
]
parmToField (Field f) =
(f ++ ": ")
+++
input ! [thetype "text",
name f,
value ""
]
linkToScript s t =
return (anchor (stringToHtml t)
! [href (sn ++ "?script=" ++ s)
]
)
matchScriptLink = do char '['
char ':'
s <- scriptname
char '|'
ps <- many (try (do f <- fieldname
char '='
p <- parmstring
spaces <- many (char ' ')
return (f ++ "=\""
++ p ++
"\"" ++
spaces
)
)
<|>
(do f <- fieldname
spaces <- many (char ' ')
return (f ++ spaces)
)
)
char '|'
t <- manyTill anyChar (try $ do char ':'; char ']';)
return (stringToHtml ("[:" ++ s ++ "|" ++
(concat ps) ++ "|"
++ t ++ ":]"
)
)
| nh2/flippi | src/ScriptSyntax.hs | bsd-3-clause | 5,215 | 4 | 22 | 2,757 | 793 | 374 | 419 | 71 | 4 |
{-# OPTIONS_GHC -XBangPatterns #-}
module Main where
import System.Random
import qualified Yaiba.Monomial as MMap
import qualified Yaiba.MonomialVec as MVec
import System.CPUTime
import Text.Printf
import Control.Monad
import Control.Parallel.Strategies
import Microbench
lim :: Int
lim = 10^6
randoList :: IO [([Int],[Int])]
randoList = do
gen <- newStdGen
let ns = randomRs (0,300) gen :: [Int]
return $ makePairs 10000 ns
makePairs 0 _ = []
makePairs n ns = let fst8 = take 8 ns
snd8 = take 8 (drop 8 ns)
rest = drop 16 ns
in (fst8,snd8):(makePairs (n-1) rest)
convMMap ns = map (\(x,y) -> (MMap.fromList x,MMap.fromList y)) ns
convMVec ns = map (\(x,y) -> (MVec.fromList x,MVec.fromList y)) ns
mmapMul ns = map (\(x,y) -> MMap.multiply x y) ns
mvecMul ns = map (\(x,y) -> MVec.multiply x y) ns
time :: IO t -> IO t
time a = do
start <- getCPUTime
v <- a
end <- getCPUTime
let diff = (fromIntegral (end - start)) / (10^12)
printf "Computation time: %0.5f sec\n" (diff :: Double)
return v
main = do
a <- randoList
b <- randoList
let !mmapa = convMMap a
let !mveca = convMVec b
let m = mmapMul mmapa
let v = mvecMul mveca
time $ m `seq` return ()
time $ v `seq` return ()
putStrLn "Done."
--putStrLn $ show b | jeremyong/Yaiba | Test/MonSpeedo.hs | bsd-3-clause | 1,318 | 0 | 14 | 323 | 593 | 305 | 288 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
module Language.Java.JVM.JavapParser where
import Language.Java.JVM.Types
import Control.Monad
import Data.Functor.Identity
import Data.List
import Data.Maybe
import Text.Parsec
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (javaStyle)
data TypeDecl=TypeDecl {
td_name::ClassName
,td_supers::[ClassName]
,td_decls::[JDecl]
}
deriving (Show,Read,Eq,Ord)
data JDecl=JMethodDecl {
d_name::String
,d_signature::String
,d_static::Bool
}
| JFieldDecl {
d_name::String
,d_signature::String
,d_static::Bool
}
deriving (Show,Read,Eq,Ord)
parseTypeDecl :: String -> Either ParseError TypeDecl
parseTypeDecl contents= parse typeDecl "unknown" contents
typeDecl ::ParsecT String u Identity TypeDecl
typeDecl=do
modifiers
choice [symbol "class",symbol "interface"]
name<-className
extends<-optionMaybe (do
symbol "extends"
classList
)
implements<-optionMaybe (do
symbol "implements"
classList
)
decls<-braces (do
decls<-many $ decl
return $ catMaybes decls)
return $ TypeDecl name (concat $ catMaybes [extends,implements]) decls
decl :: ParsecT String u Identity (Maybe JDecl)
decl = do
sta<-static
choice [(do
staticBlock
return Nothing)
,(do
className
(name,meth)<-choice [(do
parens (classList0)
return ("<init>",True)
),
(do
name <-identifier
p<-optionMaybe $ parens (classList0)
return (name,isJust p)
)
]
when meth (optional (do
symbol "throws"
classList
))
semi
sign<-signature
whiteSpace
return $ if meth
then Just $ JMethodDecl name sign sta
else Just $ JFieldDecl name sign sta
)]
--methodDecl :: ParsecT String u Identity (Bool -> Decl)
--methodDecl=do
-- className
-- name<-choice [(do
-- parens (classList0)
-- return "<init>"
-- ),
-- (do
-- name <-identifier
-- parens (classList0)
-- return name
-- )
-- ]
-- optional (do
-- symbol "throws"
-- classList
-- )
-- semi
-- sign<-signature
-- return $ MethodDecl name sign
--
--fieldDecl :: ParsecT String u Identity (Bool -> Decl)
--fieldDecl=do
-- className
-- name<-identifier
-- semi
-- sign<-signature
-- return $ FieldDecl name sign
signature :: ParsecT String u Identity String
signature=do
symbol "Signature"
colon
manyTill anyToken (try (newline))
staticBlock :: ParsecT String u Identity ()
staticBlock=do
braces whiteSpace
semi
signature
return ()
classList :: ParsecT String u Identity [ClassName]
classList=sepBy1 className comma
classList0 :: ParsecT String u Identity [ClassName]
classList0=sepBy className comma
className ::ParsecT String u Identity ClassName
className = do
-- names<-sepBy1 identifier dot
names<-sepBy1 (choice [try (symbol ".."), identifier]) dot
optionMaybe $ angles generics
optionMaybe $ brackets whiteSpace
return $ intercalate "/" (filter (/= "..") names)
genericsClassList :: ParsecT String u Identity [ClassName]
genericsClassList = sepBy1 className (symbol "&")
generic :: ParsecT String u Identity String
generic = do
name <- choice [symbol "?", className]
extends <- optionMaybe (symbol "extends" >> genericsClassList)
return name
generics ::ParsecT String u Identity [String]
generics = sepBy generic comma
static :: ParsecT String u Identity Bool
static = do
mds<-modifiers
return $ elem "static" mds
modifiers ::ParsecT String u Identity [String]
modifiers = many $ try $ choice [
try $ symbol "public"
,try $ symbol "protected"
,symbol "private"
,symbol "static"
,symbol "volatile"
,symbol "transient"
,symbol "final"
,symbol "native"]
lexer ::P.GenTokenParser String u Identity
lexer=P.makeTokenParser javaStyle
parens :: ParsecT String u Identity a -> ParsecT String u Identity a
parens = P.parens lexer
braces :: ParsecT String u Identity a -> ParsecT String u Identity a
braces = P.braces lexer
brackets :: ParsecT String u Identity a -> ParsecT String u Identity a
brackets = P.brackets lexer
angles :: ParsecT String u Identity a -> ParsecT String u Identity a
angles = P.angles lexer
identifier :: ParsecT String u Identity String
identifier = P.identifier lexer
symbol :: String -> ParsecT String u Identity String
symbol = P.symbol lexer
dot :: ParsecT String u Identity String
dot = P.dot lexer
comma :: ParsecT String u Identity String
comma = P.comma lexer
colon :: ParsecT String u Identity String
colon = P.colon lexer
semi :: ParsecT String u Identity String
semi = P.semi lexer
whiteSpace :: ParsecT String u Identity ()
whiteSpace = P.whiteSpace lexer | JPMoresmau/HJVM | src/Language/Java/JVM/JavapParser.hs | bsd-3-clause | 5,927 | 0 | 21 | 2,207 | 1,455 | 744 | 711 | 133 | 2 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Foundation where
import Import.NoFoundation as Import
import Database.Persist.Sql (ConnectionPool, runSqlPool)
import Text.Hamlet (hamletFile)
import Text.Jasmine (minifym)
import Yesod.Auth.Message (AuthMessage (InvalidLogin))
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Core.Types (Logger)
import qualified Yesod.Core.Unsafe as Unsafe
import Network.Wai (Request(..))
import Network.Socket (getNameInfo)
import Text.Julius (RawJS(..))
import Yesod.Auth.Owl
import Yesod.Auth.GoogleEmail
import Yesod.Form.Jquery
import Yesod.Goodies.PNotify
import BISocie.Helpers.Util
-- | The foundation datatype for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ appSettings :: AppSettings
, appStatic :: Static -- ^ Settings for static file serving.
, appConnPool :: ConnectionPool -- ^ Database connection pool.
, appHttpManager :: Manager
, appLogger :: Logger
}
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
instance HasHttpManager App where
getHttpManager = appHttpManager
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/routing-and-handlers
--
-- Note that this is really half the story; in Application.hs, mkYesodDispatch
-- generates the rest of the code. Please see the linked documentation for an
-- explanation for this split.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- S3はアクセス制限する
-- S3は基本公開ベースなので制限をするURIを提供してそこからgetFileRを呼ぶ
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . appSettings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = Just <$> defaultClientSessionBackend
120 -- timeout in minutes
"config/client_session_key.aes"
defaultLayout widget = do
mu <- maybeAuth
y <- getYesod
let (ApprootMaster approot') = approot
(title, parents) <- breadcrumbs
_current <- getCurrentRoute
let header = $(widgetFile "header")
footer = $(widgetFile "footer")
pc <- widgetToPageContent $ do
pnotify y
addScriptEither $ urlJqueryJs y
addScriptEither $ urlJqueryUiJs y
addStylesheetEither $ urlJqueryUiCss y
addScriptEither $ Left $ StaticR plugins_upload_jquery_upload_1_0_2_min_js
addScriptEither $ Left $ StaticR plugins_clockpick_jquery_clockpick_1_2_9_min_js
addStylesheetEither $ Left $ StaticR plugins_clockpick_jquery_clockpick_1_2_9_css
addScriptEither $ Left $ StaticR plugins_ajaxzip2_ajaxzip2_js
addScriptEither $ Left $ StaticR plugins_selection_jquery_selection_min_js
addScriptEither $ Left $ StaticR plugins_textchange_jquery_textchange_min_js
addScriptEither $ Left $ StaticR plugins_zClip_jquery_zclip_min_js
addScriptEither $ Left $ StaticR plugins_placeholder_jquery_placeholder_min_js
addScriptEither $ Left $ StaticR plugins_pnotify_jquery_pnotify_min_js
addStylesheetEither $ Left $ StaticR plugins_pnotify_jquery_pnotify_default_css
$(widgetFile "default-layout")
withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
isAuthorized FaviconR _ = return Authorized
isAuthorized RobotsR _ = return Authorized
isAuthorized (AuthR _) _ = return Authorized
isAuthorized (HomeR uid) _ = isMyOwn uid
isAuthorized ChangePasswordR _ = loggedInAuth
isAuthorized HumanNetworkR _ = checkUser canViewHumannetwork
isAuthorized UserLocationsR _ = checkUser canViewUserLocations
isAuthorized SystemBatchR _ = checkUser isAdmin
isAuthorized (SendReminderMailR _ _ _) _ = reqFromLocalhost
isAuthorized NewProjectR _ = checkUser canCreateProject
isAuthorized (ProjectR pid) _ = isParticipant' pid
isAuthorized CurrentScheduleR _ = loggedInAuth
isAuthorized (ScheduleR _ _) _ = loggedInAuth
isAuthorized (TaskR _ _ _) _ = loggedInAuth
isAuthorized ProjectListR _ = loggedInAuth
isAuthorized AssignListR _ = loggedInAuth
isAuthorized StatusListR _ = loggedInAuth
isAuthorized CrossSearchR _ = loggedInAuth
isAuthorized (IssueListR pid) _ = isParticipant' pid
isAuthorized (NewIssueR pid) _ = isParticipant pid
isAuthorized (IssueR pid _) _ = isParticipant' pid
isAuthorized (CommentR pid _) _ = isParticipant pid
isAuthorized (AttachedFileR cid _) _ = canReadComment cid
isAuthorized (CommentReadersR cid) _ = canReadComment cid
isAuthorized (ParticipantsListR pid) _ = isParticipant' pid
isAuthorized (ParticipantsR pid _) _ = isParticipant pid
isAuthorized (ProfileR uid) True = canEditUser uid
isAuthorized (ProfileR _) False = loggedInAuth
isAuthorized (AvatarImageR _) _ = loggedInAuth
isAuthorized (AvatarR uid) _ = canEditUser uid
isAuthorized UserListR _ = loggedInAuth
isAuthorized UsersR _ = checkUser isAdmin
isAuthorized (UserR _) _ = checkUser isAdmin
isAuthorized NewUserR _ = checkUser isAdmin
isAuthorized (DeleteUserR _) _ = checkUser isAdmin
isAuthorized _ _ = loggedInAuth
-- Maximum allowed length of the request body, in bytes.
maximumContentLength _ (Just (AvatarR _)) = Just (2 * 1024 * 1024) -- 2 megabytes for default
maximumContentLength _ (Just (AvatarImageR _)) = Just (2 * 1024 * 1024) -- 2 megabytes for default
maximumContentLength _ _ = Just (20 * 1024 * 1024) -- 20 megabytes for default
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent ext mime content = do
master <- getYesod
let staticDir = appStaticDir $ appSettings master
addStaticContentExternal
minifym
genFileName
staticDir
(StaticR . flip StaticRoute [])
ext
mime
content
where
-- Generate a unique filename based on the content itself
genFileName lbs = "autogen-" ++ base64md5 lbs
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog app _source level =
appShouldLogAll (appSettings app)
|| level == LevelWarn
|| level == LevelError
makeLogger = return . appLogger
-- Utility functions for isAuthorized
loggedInAuth :: Handler AuthResult
loggedInAuth = fmap (maybe AuthenticationRequired $ const Authorized) maybeAuthId
isMyOwn :: UserId -> Handler AuthResult
isMyOwn uid = do
self <- requireAuthId
if self == uid
then return Authorized
else do
r <- getMessageRender
return $ Unauthorized $ r MsgYouCannotAccessThisPage
checkUser :: (User -> Bool) -> Handler AuthResult
checkUser p = do
u <- requireAuth
if p $ entityVal u
then return Authorized
else do
r <- getMessageRender
return $ Unauthorized $ r MsgYouCannotAccessThisPage
reqFromLocalhost :: Handler AuthResult
reqFromLocalhost = do
req <- fmap reqWaiRequest getRequest
(Just rhostname, _) <- liftIO $ getNameInfo [] True True $ remoteHost req
if rhostname == "localhost"
then return Authorized
else do
r <- getMessageRender
return $ Unauthorized $ r MsgYouCannotAccessThisPage
isParticipant :: ProjectId -> Handler AuthResult
isParticipant pid = do
u <- requireAuth
mp <- runDB $ getBy $ UniqueParticipants pid (entityKey u)
if isJust mp
then return Authorized
else do
r <- getMessageRender
return $ Unauthorized $ r MsgYouCannotAccessThisPage
isParticipant' :: ProjectId -> Handler AuthResult
isParticipant' pid = do
u <- requireAuth
mp <- runDB $ getBy $ UniqueParticipants pid (entityKey u)
if isJust mp || isAdmin (entityVal u)
then return Authorized
else do
r <- getMessageRender
return $ Unauthorized $ r MsgYouCannotAccessThisPage
canReadComment :: CommentId -> Handler AuthResult
canReadComment cid = do
u <- requireAuth
b <- runDB $ do
c <- get404 cid
mp <- getBy $ UniqueParticipants (commentProject c) (entityKey u)
return $ isJust mp || isAdmin (entityVal u)
if b
then return Authorized
else do
r <- getMessageRender
return $ Unauthorized $ r MsgYouCannotAccessThisPage
canEditUser :: UserId -> Handler AuthResult
canEditUser uid = do
u' <- requireAuth
u <- runDB $ get404 uid
if entityVal u' `canEdit` u
then return Authorized
else do
r <- getMessageRender
return $ Unauthorized $ r MsgYouCannotEditThisData
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlBackend
runDB action = do
master <- getYesod
runSqlPool action $ appConnPool master
instance YesodPersistRunner App where
getDBRunner = defaultGetDBRunner appConnPool
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = RootR
-- Where to send a user after logout
logoutDest _ = RootR
authenticate creds = do
render <- getMessageRender
runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid u) ->
if userActive u
then do
lift $ setPNotify $ PNotify JqueryUI Success "Login" $ render MsgSuccessLogin
return $ Authenticated uid
else do
lift $ setPNotify $ PNotify JqueryUI Error "fail to Login" "Invalid login."
return $ UserError InvalidLogin
Nothing -> do
lift $ setPNotify $ PNotify JqueryUI Success "Login" $ render MsgSuccessLogin
fmap Authenticated $ insert $ initUser $ credsIdent creds
authPlugins _ = [ authOwl
, authGoogleEmail
]
authHttpManager = getHttpManager
loginHandler = lift $ defaultLayout $ do
setTitle "ログイン"
$(widgetFile "login")
instance YesodAuthPersist App
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
unsafeHandler :: App -> Handler a -> IO a
unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger
instance YesodAuthOwl App where
getOwlIdent = lift $ fmap (userIdent . entityVal) requireAuth
clientId _ = Import.clientId
owlPubkey _ = Import.owl_pub
myPrivkey _ = Import.bisocie_priv
endpoint_auth _ = Import.owl_auth_service_url
endpoint_pass _ = Import.owl_pass_service_url
instance YesodJquery App where
urlJqueryJs _ = Left $ StaticR js_jquery_1_4_4_min_js
urlJqueryUiJs _ = Left $ StaticR js_jquery_ui_1_8_9_custom_min_js
urlJqueryUiCss _ = Left $ StaticR css_jquery_ui_1_8_9_custom_css
instance YesodJqueryPnotify App where
instance YesodBreadcrumbs App where
breadcrumb RootR = return ("", Nothing)
breadcrumb HomeR{} = return ("ホーム", Nothing)
breadcrumb HumanNetworkR = do
(Entity uid _) <- requireAuth
return ("ヒューマンネットワーク", Just $ HomeR uid)
breadcrumb (ScheduleR y m) = do
(Entity uid _) <- requireAuth
return (showText y +++ "年" +++ showText m +++ "月のスケジュール", Just $ HomeR uid)
breadcrumb NewProjectR = do
(Entity uid _) <- requireAuth
return ("新規プロジェクト作成", Just $ HomeR uid)
breadcrumb (ProjectR pid) = do
uid <- requireAuthId
p <- runDB $ get404 pid
return (projectName p, Just $ HomeR uid)
breadcrumb (ParticipantsListR pid) = return ("参加者", Just $ ProjectR pid)
breadcrumb ParticipantsR{} = return ("", Nothing)
breadcrumb UserListR = return ("ユーザ一覧", Nothing)
breadcrumb CrossSearchR = do
(Entity uid _) <- requireAuth
return ("クロスサーチ", Just $ HomeR uid)
breadcrumb (IssueListR pid) = return ("タスク一覧", Just $ ProjectR pid)
breadcrumb (NewIssueR pid) = return ("タスク追加", Just $ ProjectR pid)
breadcrumb (IssueR pid ino) = do
(Entity _ issue) <- runDB $ getBy404 $ UniqueIssue pid ino
return (showText (issueNumber issue) +++ ": " +++ issueSubject issue, Just $ IssueListR pid)
breadcrumb CommentR{} = return ("", Nothing)
breadcrumb (ProfileR uid) = do
u <- runDB $ get404 uid
mode <- lookupGetParam "mode"
case mode of
Just "e" -> return (userFullName u +++ " プロフィール編集", Nothing)
_ -> return (userFullName u, Nothing)
-- the others
breadcrumb _ = return ("", Nothing)
| cutsea110/BISocie | Foundation.hs | bsd-3-clause | 13,372 | 0 | 19 | 2,985 | 3,301 | 1,618 | 1,683 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
type State = Int
data ST a b = S (b -> (a, b)) | F a | G (b -> a)
[lq| fresh :: ST {v:Int|v>=0} {v:Int|v>=0} |]
fresh :: ST Int Int
fresh = S $ \n -> (n, n+1)
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/state00.hs | bsd-3-clause | 217 | 0 | 9 | 56 | 93 | 56 | 37 | 7 | 1 |
{-# LANGUAGE FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.R.Lexer
-- Copyright : (c) 2010 David M. Rosenberg
-- License : BSD3
--
-- Maintainer : David Rosenberg <[email protected]>
-- Stability : experimental
-- Portability : portable
-- Created : 05/28/10
--
-- Description :
-- DESCRIPTION HERE.
-----------------------------------------------------------------------------
module Language.R.Lexer where
import Control.Monad
import Control.Monad.Error
import Control.Monad.Identity (Identity)
import Monad
import qualified Data.Map as Map
import Text.Parsec
import Text.Parsec.Pos
import Text.Parsec.String
import Text.Parsec.Combinator
import Text.Parsec.Char
import Text.Parsec.Prim
import Data.Char (toLower)
import qualified Text.Parsec.Token as T
import qualified Text.Parsec.Language as L
import Language.R.Token
import Language.R.SrcLocation
import Language.R.LexerUtils
-- | Provides a description of the basic grammatical construction of the
-- R language. Note that no reserved operators or identifiers are named
-- here.
rStyle :: L.LanguageDef st
rStyle = L.emptyDef
{ T.commentStart = ""
, T.commentEnd = ""
, T.commentLine = "#"
, T.nestedComments = False
, T.identStart = letter <|> char '.'
, T.identLetter = alphaNum <|> oneOf "._"
, T.opStart = T.opLetter L.emptyDef
, T.opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~(){}[];,"
, T.reservedOpNames= []
, T.reservedNames = []
, T.caseSensitive = True
}
-- | To alleviate confusion @Text.Parsec.Token@ functions are excluded
-- from the base global namespace and the language-derived analogs are
-- imported in.
rlang :: T.TokenParser st
rlang = T.makeTokenParser rStyle
identifier = T.identifier rlang
reserved = T.reserved rlang
operator = T.operator rlang
reservedOp = T.reservedOp rlang
charLiteral = T.charLiteral rlang
stringLiteral = T.stringLiteral rlang
natural = T.natural rlang
integer = T.integer rlang
float = T.float rlang
naturalOrFloat = T.naturalOrFloat rlang
decimal = T.decimal rlang
hexadecimal = T.hexadecimal rlang
octal = T.octal rlang
symbol = T.symbol rlang
lexeme = T.lexeme rlang
whiteSpace = T.whiteSpace rlang
parens = T.parens rlang
braces = T.braces rlang
angles = T.angles rlang
brackets = T.brackets rlang
squares = T.squares rlang
semi = T.semi rlang
comma = T.comma rlang
colon = T.colon rlang
dot = T.dot rlang
semiSep = T.semiSep rlang
semiSep1 = T.semiSep1 rlang
commaSep = T.commaSep rlang
commaSep1 = T.commaSep1 rlang
-- | @rTokenize@ represents the top level of the lexer combinator
-- hierarchy which repeatedly calls @lexRtok@.
rTokenize =
setState [] >>
whiteSpace >>
many lexRtok
-- | @lexRtok@ is the primary dispatching lexer combinator. It
-- simply tries each possible lexer function until one succeeds in
-- comsuming input. The order in which it dispatches the individual
-- lexing functions is relevant.
lexRtok = do
pos <- getPosition
st <- getState
tok <- try lexComment
<|> try lexSpecialConstant
<|> try lexInteger
<|> try lexComplex
<|> try lexNumeric
<|> try lexLogical
<|> try lexString
<|> try lexOperator
<|> try lexReserved
<|> try lexPunctuation
<|> try lexIdentifier
return tok
-- | The 8 'special' constant literal values
-- * NA_integer_
-- * NA_real_
-- * NA_complex_
-- * NA_character_
-- * NA
-- * NaN
-- * NULL
-- * Inf
-- are rescued early in order to prevent them from being lexed as
-- some other token. Note that there are two other 'special' constant
-- literals, @TRUE@ and @FALSE@. These other values will be
-- recorded as Logical tokens instead.
lexSpecialConstant :: ParsecT String u Control.Monad.Identity.Identity Token
lexSpecialConstant = do
startPos <- getPosition
tk <- choice [ try (string "NA_integer_")
, try (string "NA_real_")
, try (string "NA_complex_")
, try (string "NA_character_")
, try (string "NA")
, try (string "NaN")
, try (string "NULL")
, (string "Inf") ]
endPos <- getPosition
return $ SpecialConstantToken (mkSrcSpan' startPos endPos)
tk (read tk :: SpecialConstant)
-- | Comments in R go from any unquoted \'#\' until the end of the line
lexComment :: ParsecT String u Control.Monad.Identity.Identity Token
lexComment = do
startPos <- getPosition
char '#'
tk <- many (noneOf "\n\r")
endPos <- getPosition
return $ CommentToken (mkSrcSpan' startPos endPos) tk
-- | Integral values are only stored internally as integers if they
-- are written with the character 'L' directly after the last digit;
-- such as 123L. No space is permitted between the numerals and the
-- letter 'L'
lexInteger :: ParsecT String u Control.Monad.Identity.Identity Token
lexInteger = do
startPos <- getPosition
tk <- many digit
char 'L'
endPos <- getPosition
return $ IntegerToken (mkSrcSpan' startPos endPos) (tk ++ "L") (read tk :: Integer)
-- | Numeric literals are stored internally as a @Double@ and
-- represent the vast majority of numbers in R.
lexNumeric :: ParsecT String u Control.Monad.Identity.Identity Token
lexNumeric = do
startPos <- getPosition
tk <- naturalOrFloat
let tk' = either fromIntegral id tk :: Double
endPos <- getPosition
return $ NumericToken (mkSrcSpan' startPos endPos) (show tk) tk'
-- | TODO: Explain the confusing rules for @Complex@ literals.
lexComplex :: ParsecT String u Control.Monad.Identity.Identity Token
lexComplex = do
startPos <- getPosition
(re', im') <- do
re <- naturalOrFloat
char '+'
im <- naturalOrFloat
char 'i'
let re' = either fromIntegral id re :: Double
let im' = either fromIntegral id im :: Double
return (re', im')
endPos <- getPosition
return $ ComplexToken (mkSrcSpan' startPos endPos)
(show re' ++ " + " ++ show im' ++ "i") (re', im')
lexLogical :: ParsecT String u Control.Monad.Identity.Identity Token
lexLogical = do
startPos <- getPosition
tk <- choice [ try (string "TRUE"), (string "FALSE") ]
let tk' = read ((head tk) : (map Data.Char.toLower $ tail tk)) :: Bool
endPos <- getPosition
return $ LogicalToken (mkSrcSpan' startPos endPos) tk tk'
lexString :: ParsecT String u Control.Monad.Identity.Identity Token
lexString = do
startPos <- getPosition
tk <- quotedString
endPos <- getPosition
return $ StringToken (mkSrcSpan' startPos endPos) tk
lexOperator :: ParsecT String u Control.Monad.Identity.Identity Token
lexOperator = do
startPos <- getPosition
let ops = map snd rResOps
tk <- choice (map (\z -> try (string z)) ops)
endPos <- getPosition
let tk' = Map.lookup tk operatorMap
res <- case tk' of
Just x -> return x
Nothing -> return ErrorToken
return $ res (mkSrcSpan' startPos endPos)
{- <|> do
char '%'
symb <- many alphaNum
char '%'
return $ concat ["%", symb, "%"]
-}
lexReserved :: ParsecT String u Control.Monad.Identity.Identity Token
lexReserved = do
startPos <- getPosition
let rsrvd = map fst rFuncPrims
tk <- choice (map (\z -> try (string z)) rsrvd)
endPos <- getPosition
let tk' = Map.lookup tk reservedMap
res <- case tk' of
Just x -> return x
Nothing -> return ErrorToken
return $ res (mkSrcSpan' startPos endPos)
lexIdentifier :: ParsecT String u Control.Monad.Identity.Identity Token
lexIdentifier = do
startPos <- getPosition
tk <- identifier
endPos <- getPosition
return $ IdentifierToken (mkSrcSpan' startPos endPos) tk
lexPunctuation :: ParsecT String u Control.Monad.Identity.Identity Token
lexPunctuation = do
startPos <- getPosition
punc <- oneOf "()[]{};,"
let tk = Map.lookup (punc:"") punctMap
res <- case tk of
Just x -> return x
Nothing -> return ErrorToken
endPos <- getPosition
return $ res (mkSrcSpan' startPos endPos)
testParse = do
text <- readFile "checkRegion.R"
let res = runParser rTokenize [] "TEST" text
return res
rLex text =
let res = runParser rTokenize [] "rLex first pass" text
tokStream = either (\z -> []) id res
in tokStream
-- | Reserved operations which cannot be overwritten and require rearrangement
-- during the second pass.
data R_ResOp = BinMinus | BinPlus | UnNot | UnBinTilde
| UnHelp | BinSeq | BinMult | BinDiv | BinExp
| BinUndef | BinMod | BinIntDiv | BinMatMult
| BinOutPr | BinKronPr | BinIntrsct | BinLT
| BinGT | BinEQ | BinGE | BinLE | BinVecAnd
| BinAnd | BinVecOr | BinOr | BinAsnLeft
| BinAsnRight | BinElmnt | BinMemAsn
| BinSlot | BinElemnt | BinElemntAsn
| BinIndxAsn | BinEql | BinIndx
deriving (Read, Ord, Show, Eq, Enum)
-- | R *builtin* functions which cannot be overwritten and are not expressed
data R_Builtin = R_MathFn -- ^Mathematical functions
| R_PrgFn -- ^Language / programming functions
| R_DbgFn -- ^Debugging functions
| R_AsnFn -- ^Special syntax assignment functions
| R_nArgEff -- ^Functions taking arbitrary length argument lists
| R_CtrlFlow -- ^Control flow functions
deriving (Read, Show, Eq, Ord, Enum)
rResOps :: [(R_ResOp, String)]
rResOps =
[ (BinMinus, "-") -- Minus can be unary or binary
, (BinPlus, "+") -- Plus can be unary or binary
, (UnNot, "!") -- Unary not
, (UnBinTilde, "~") -- Tilde, used for model formulae, unary or binary
, (UnHelp, "?") -- Help
, (BinSeq, ":") -- Sequence, binary (in model formulae: interaction)
, (BinMult, "*") -- Multiplication, binary
, (BinDiv, "/") -- Division, binary
, (BinExp, "^") -- Exponentiation, binary
, (BinUndef, "%x%") -- Special binary operators, x can be replaced by any valid name
, (BinMod, "%%") -- Modulus, binary
, (BinIntDiv, "%/%") -- Integer divide, binary
, (BinMatMult, "%*%") -- Matrix product, binary
, (BinOutPr, "%o%") -- Outer product, binary
, (BinKronPr, "%x%") -- Kronecker product, binary
, (BinIntrsct, "%in%") -- Matching operator, binary (in model formulae: nesting)
, (BinLT, "<") -- Less than, binary
, (BinGT, ">") -- Greater than, binary
, (BinEQ, "==") -- Equal to, binary
, (BinGE, ">=") -- Greater than or equal to, binary
, (BinLE, "<=") -- Less than or equal to, binary
, (BinVecAnd, "&") -- And, binary, vectorized
, (BinAnd, "&&") -- And, binary, not vectorized
, (BinVecOr, "| ") -- Or, binary, vectorized
, (BinOr, "||") -- Or, binary, not vectorized
, (BinAsnLeft, "<-") -- Left assignment, binary
, (BinAsnRight, "->") -- Right assignment, binary
, (BinElmnt, "$") -- List subset, binary
, (BinMemAsn, "$<-")
, (BinSlot, "@")
, (BinIndx, "[")
, (BinElemnt, "[[")
, (BinElemntAsn, "[[<-")
, (BinIndxAsn, "[<-")
, (BinEql, "=")
]
resOps :: Map.Map R_ResOp String
resOps = Map.fromList rResOps
rFuncPrims :: [(String, R_Builtin)]
rFuncPrims =
[ ("abs" , R_MathFn)
, ("sign" , R_MathFn)
, ("sqrt" , R_MathFn)
, ("floor" , R_MathFn)
, ("ceiling" , R_MathFn)
, ("exp" , R_MathFn)
, ("expm1" , R_MathFn)
, ("log2" , R_MathFn)
, ("log10" , R_MathFn)
, ("log1p" , R_MathFn)
, ("cos" , R_MathFn)
, ("sin" , R_MathFn)
, ("tan" , R_MathFn)
, ("acos" , R_MathFn)
, ("asin" , R_MathFn)
, ("atan" , R_MathFn)
, ("cosh" , R_MathFn)
, ("sinh" , R_MathFn)
, ("tanh" , R_MathFn)
, ("acosh" , R_MathFn)
, ("asinh" , R_MathFn)
, ("atanh" , R_MathFn)
, ("gamma" , R_MathFn)
, ("lgamma" , R_MathFn)
, ("digamma" , R_MathFn)
, ("trigamma" , R_MathFn)
, ("cumsum" , R_MathFn)
, ("cumprod" , R_MathFn)
, ("cummax" , R_MathFn)
, ("cummin" , R_MathFn)
, ("Im" , R_MathFn)
, ("Re" , R_MathFn)
, ("Arg" , R_MathFn)
, ("Conj" , R_MathFn)
, ("Mod" , R_MathFn)
, ("nargs" , R_PrgFn)
, ("missing" , R_PrgFn)
, ("interactive" , R_PrgFn)
, ("is.xxx" , R_PrgFn)
, ("as.call" , R_PrgFn)
, ("as.character" , R_PrgFn)
, ("as.complex" , R_PrgFn)
, ("as.double" , R_PrgFn)
, ("as.environment" , R_PrgFn)
, ("as.integer" , R_PrgFn)
, ("as.logical as.raw" , R_PrgFn)
, (".Primitive" , R_PrgFn)
, (".Internal" , R_PrgFn)
, ("globalenv" , R_PrgFn)
, ("baseenv" , R_PrgFn)
, ("emptyenv" , R_PrgFn)
, ("pos.to.env" , R_PrgFn)
, ("unclass" , R_PrgFn)
, ("invisible" , R_PrgFn)
, ("seq_along" , R_PrgFn)
, ("seq_len" , R_PrgFn)
, ("browser" , R_DbgFn)
, ("proc.time" , R_DbgFn)
, ("gc.time" , R_DbgFn)
, ("tracemem" , R_DbgFn)
, ("retracemem" , R_DbgFn)
, ("untracemem" , R_DbgFn)
, ("length" , R_AsnFn)
, ("length<-" , R_AsnFn)
, ("class" , R_AsnFn)
, ("class<-" , R_AsnFn)
, ("oldClass" , R_AsnFn)
, ("oldClass<-" , R_AsnFn)
, ("attr" , R_AsnFn)
, ("attr<-" , R_AsnFn)
, ("attributes" , R_AsnFn)
, ("attributes<-" , R_AsnFn)
, ("names" , R_AsnFn)
, ("names<-" , R_AsnFn)
, ("dim" , R_AsnFn)
, ("dim<-" , R_AsnFn)
, ("dimnames" , R_AsnFn)
, ("dimnames<-" , R_AsnFn)
, ("environment<-" , R_AsnFn)
, ("levels<-" , R_AsnFn)
, ("storage.mode<-" , R_AsnFn)
-- , (":" , R_nArgEff)
-- , ("~" , R_nArgEff)
, ("c" , R_nArgEff)
, ("list" , R_nArgEff)
, ("call" , R_nArgEff)
, ("expression" , R_nArgEff)
, ("substitute" , R_nArgEff)
, ("UseMethod" , R_nArgEff)
, ("standardGeneric" , R_nArgEff)
, (".C" , R_nArgEff)
, (".Fortran" , R_nArgEff)
, (".Call" , R_nArgEff)
, (".External" , R_nArgEff)
, (".Call.graphics" , R_nArgEff)
, (".External.graphics" , R_nArgEff)
, (".subset" , R_nArgEff)
, (".subset2" , R_nArgEff)
, (".primTrace" , R_nArgEff)
, (".primUntrace" , R_nArgEff)
, ("round" , R_nArgEff)
, ("signif" , R_nArgEff)
, ("rep" , R_nArgEff)
, ("seq.int" , R_nArgEff)
, ("lazyLoadDBfetch" , R_nArgEff)
, ("break" , R_CtrlFlow)
, ("for" , R_CtrlFlow)
, ("function" , R_CtrlFlow)
, ("if" , R_CtrlFlow)
, ("next" , R_CtrlFlow)
, ("repeat" , R_CtrlFlow)
, ("return" , R_CtrlFlow)
, ("while" , R_CtrlFlow)
]
funcPrims :: Map.Map String R_Builtin
funcPrims = Map.fromList rFuncPrims
| rosenbergdm/language-r | src/Language/R/Lexer.hs | bsd-3-clause | 16,254 | 0 | 18 | 5,165 | 3,739 | 2,153 | 1,586 | 361 | 2 |
-- | This bitmap type is deprecated; use 'Data.Bitmap.String' instead
--
-- Bitmaps represented as strings
--
-- The module provides polymorphic support for representation of bitmaps as strings.
-- This module is designed to be most efficient with lazy bytestrings.
module Data.Bitmap.StringRGB24A4VR {-# DEPRECATED "Use Data.Bitmap.String instead" #-}
( BitmapStringRGB24A4VR
) where
import Data.Bitmap.StringRGB24A4VR.Internal
| bairyn/bitmaps | src/Data/Bitmap/StringRGB24A4VR.hs | bsd-3-clause | 439 | 0 | 4 | 65 | 26 | 20 | 6 | 3 | 0 |
-----------------------------------------------------------
-- |
-- Module : PrimQuery
-- Copyright : Daan Leijen (c) 1999, [email protected]
-- HWT Group (c) 2003, [email protected]
-- License : BSD-style
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non portable
--
-- PrimQuery defines the datatype of relational expressions
-- ('PrimQuery') and some useful functions on PrimQuery\'s
--
--
-----------------------------------------------------------
module Database.HaskellDB.PrimQuery (
-- * Type Declarations
-- ** Types
TableName, Attribute, Scheme, Assoc, Name
-- ** Data types
, PrimQuery(..), RelOp(..), SpecialOp(..)
, PrimExpr(..), OrderExpr(..)
, BinOp(..), UnOp(..), OrderOp(..), AggrOp(..)
, Literal(..)
-- * Function declarations
, extend, times
, attributes, attrInExpr, attrInOrder
, substAttr
, isAggregate, isConstant
, foldPrimQuery, foldPrimExpr
) where
import Data.List ((\\), union)
import Control.Exception (assert)
import System.Time (CalendarTime, formatCalendarTime)
import System.Locale (defaultTimeLocale, iso8601DateFormat)
import Text.PrettyPrint.HughesPJ
-----------------------------------------------------------
-- data definitions
-- PrimQuery is the data type of relational expressions.
-- Since 'Project' takes an association, it is actually a
-- projection- and rename-operator at once.
-----------------------------------------------------------
type TableName = String
type Attribute = String
type Name = String
type Scheme = [Attribute]
type Assoc = [(Attribute,PrimExpr)]
data PrimQuery = BaseTable TableName Scheme
| Project Assoc PrimQuery
| Restrict PrimExpr PrimQuery
| Group Assoc PrimQuery
| Binary RelOp PrimQuery PrimQuery
| Special SpecialOp PrimQuery
| Empty
deriving (Show)
data RelOp = Times
| Union
| UnionAll
| Intersect
| Divide
| Difference
deriving (Show)
data SpecialOp = Order [OrderExpr]
| Top Int
| Offset Int
deriving (Show)
data OrderExpr = OrderExpr OrderOp PrimExpr
deriving (Show)
data OrderOp = OpAsc | OpDesc
deriving (Show)
data PrimExpr = AttrExpr Attribute
| BinExpr BinOp PrimExpr PrimExpr
| UnExpr UnOp PrimExpr
| AggrExpr AggrOp PrimExpr
| ConstExpr Literal
| CaseExpr [(PrimExpr,PrimExpr)] PrimExpr
| ListExpr [PrimExpr]
| ParamExpr (Maybe Name) PrimExpr
| FunExpr Name [PrimExpr]
| CastExpr Name PrimExpr -- ^ Cast an expression to a given type.
deriving (Read,Show)
data Literal = NullLit
| DefaultLit -- ^ represents a default value
| BoolLit Bool
| StringLit String
| IntegerLit Integer
| DoubleLit Double
| DateLit CalendarTime
| OtherLit String -- ^ used for hacking in custom SQL
deriving (Read,Show)
data BinOp = OpEq | OpLt | OpLtEq | OpGt | OpGtEq | OpNotEq
| OpAnd | OpOr
| OpLike | OpIn
| OpOther String
| OpCat
| OpPlus | OpMinus | OpMul | OpDiv | OpMod
| OpBitNot | OpBitAnd | OpBitOr | OpBitXor
| OpAsg
deriving (Show,Read)
data UnOp = OpNot
| OpIsNull | OpIsNotNull
| OpLength
| UnOpOther String
deriving (Show,Read)
data AggrOp = AggrCount | AggrSum | AggrAvg | AggrMin | AggrMax
| AggrStdDev | AggrStdDevP | AggrVar | AggrVarP
| AggrOther String
deriving (Show,Read)
-- | Creates a projection of some attributes while
-- keeping all other attributes in the relation visible too.
extend :: Assoc -> PrimQuery -> PrimQuery
extend assoc query
= Project (assoc ++ assoc') query
where
assoc' = assocFromScheme (attributes query)
-- | Takes the cartesian product of two queries.
times :: PrimQuery -> PrimQuery -> PrimQuery
times (Empty) query = query
times query (Empty) = query
times query1 query2 =
assert (length (attributes query1 \\ attributes query2) ==
length (attributes query1))
Binary Times query1 query2
-- | Returns the schema (the attributes) of a query
attributes :: PrimQuery -> Scheme
attributes (Empty) = []
attributes (BaseTable nm attrs) = attrs
attributes (Project assoc q) = map fst assoc
attributes (Restrict expr q) = attributes q
attributes (Special op q) = attributes q
attributes (Binary op q1 q2) = case op of
Times -> attr1 `union` attr2
Union -> attr1
UnionAll -> attr1
Intersect -> attr1
Divide -> attr1
Difference -> attr1
where
attr1 = attributes q1
attr2 = attributes q2
attributes (Group _ qry) = attributes qry
-- | Returns a one-to-one association of a
-- schema. ie. @assocFromScheme ["name","city"]@ becomes:
-- @[("name",AttrExpr "name"), ("city",AttrExpr "city")]@
assocFromScheme :: Scheme -> Assoc
assocFromScheme scheme
= map (\attr -> (attr,AttrExpr attr)) scheme
-- | Returns all attributes in an expression.
attrInExpr :: PrimExpr -> Scheme
attrInExpr = concat . foldPrimExpr (attr,scalar,binary,unary,aggr,_case,list,param,func, cast)
where
attr name = [[name]]
scalar s = [[]]
binary op x y = x ++ y
unary op x = x
aggr op x = x
_case cs el = concat (uncurry (++) (unzip cs)) ++ el
list xs = concat xs
param _ _ = [[]]
func _ es = concat es
cast _ expr = expr
-- | Returns all attributes in a list of ordering expressions.
attrInOrder :: [OrderExpr] -> Scheme
attrInOrder os = concat [attrInExpr e | OrderExpr _ e <- os]
-- | Substitute attribute names in an expression.
substAttr :: Assoc -> PrimExpr -> PrimExpr
substAttr assoc
= foldPrimExpr (attr,ConstExpr,BinExpr,UnExpr,AggrExpr,CaseExpr,ListExpr,ParamExpr,FunExpr,CastExpr)
where
attr name = case (lookup name assoc) of
Just x -> x
Nothing -> AttrExpr name
-- | Determines if a primitive expression represents a constant
-- or is an expression only involving constants.
isConstant :: PrimExpr -> Bool
isConstant x = countAttr x == 0
where
countAttr = foldPrimExpr (const 1, const 0, binary, unary, aggr, _case, list,
const2 1, const2 1, cast)
where
_case cs el = sum (map (uncurry (+)) cs) + el
list = sum
const2 a _ _ = a
binary _ x y = x + y
unary _ x = x
aggr _ x = x
cast _ n = n
isAggregate :: PrimExpr -> Bool
isAggregate x = countAggregate x > 0
countAggregate :: PrimExpr -> Int
countAggregate
= foldPrimExpr (const 0, const 0, binary, unary, aggr, _case, list,(\_ _ -> 0), (\_ n -> sum n), cast)
where
binary op x y = x + y
unary op x = x
aggr op x = x + 1
_case cs el = sum (map (uncurry (+)) cs) + el
list xs = sum xs
cast _ e = e
-- | Fold on 'PrimQuery'
foldPrimQuery :: (t, TableName -> Scheme -> t, Assoc -> t -> t,
PrimExpr -> t -> t, RelOp -> t -> t -> t,
Assoc -> t -> t, SpecialOp -> t -> t) -> PrimQuery -> t
foldPrimQuery (empty,table,project,restrict,binary,group,special)
= fold
where
fold (Empty) = empty
fold (BaseTable name schema)
= table name schema
fold (Project assoc query)
= project assoc (fold query)
fold (Restrict expr query)
= restrict expr (fold query)
fold (Binary op query1 query2)
= binary op (fold query1) (fold query2)
fold (Group assocs query)
= group assocs (fold query)
fold (Special op query)
= special op (fold query)
-- | Fold on 'PrimExpr'
foldPrimExpr :: (Attribute -> t, Literal -> t, BinOp -> t -> t -> t,
UnOp -> t -> t, AggrOp -> t -> t,
[(t,t)] -> t -> t, [t] -> t, Maybe Name -> t -> t, Name -> [t] -> t, Name -> t -> t) -> PrimExpr -> t
foldPrimExpr (attr,scalar,binary,unary,aggr,_case,list,param,fun,cast)
= fold
where
fold (AttrExpr name) = attr name
fold (ConstExpr s) = scalar s
fold (BinExpr op x y)= binary op (fold x) (fold y)
fold (UnExpr op x) = unary op (fold x)
fold (AggrExpr op x) = aggr op (fold x)
fold (CaseExpr cs el) = _case (map (both fold) cs) (fold el)
fold (ListExpr xs) = list (map fold xs)
fold (ParamExpr n value) = param n (fold value)
fold (FunExpr n exprs) = fun n (map fold exprs)
fold (CastExpr n expr) = cast n (fold expr)
both f (x,y) = (f x, f y)
| m4dc4p/haskelldb | src/Database/HaskellDB/PrimQuery.hs | bsd-3-clause | 9,660 | 54 | 15 | 3,387 | 2,613 | 1,450 | 1,163 | 188 | 10 |
-- boilerplate {{{
module Data.SGF.Parse.Util where
import Control.Arrow
import Control.Monad.Error hiding (Error(..))
import qualified Control.Monad.Error as Either
import Control.Monad.State hiding (State(..))
import Control.Monad.Writer
import Data.Char
import Data.Encoding
import Data.Function
import Data.Ix
import Data.List
import Data.Maybe
import Data.Map (Map(..), fromList, keys)
import Data.Ord
import Data.Set (Set)
import Data.Tree
import Data.Word
import Text.Parsec hiding (State(..), choice, newline)
import Data.SGF.Parse.Encodings
import Data.SGF.Parse.Raw
import Data.SGF.Types hiding (name)
-- }}}
-- new types {{{
-- Header {{{
data Header = Header {
format :: Integer,
encoding :: DynEncoding
}
-- }}}
-- Error {{{
-- |
data ErrorType
= UnknownEncoding
| AmbiguousEncoding
| FormatUnsupported
| GameUnsupported
| OutOfBounds
| BadlyFormattedValue
| BadlyEncodedValue
| ConcurrentMoveAndSetup
| ConcurrentBlackAndWhiteMove
| ConcurrentAnnotations
| ExtraMoveAnnotations
deriving (Eq, Ord, Show, Read, Bounded, Enum)
-- Errors signify unrecoverable errors.
data Error
= KnownError { errorType :: ErrorType, errorPosition :: SourcePos }
| UnknownError { errorDescription :: Maybe String }
deriving (Eq, Ord, Show)
instance Either.Error Error where
noMsg = UnknownError Nothing
strMsg = UnknownError . Just
die :: Error -> Translator a
dieWithPos :: ErrorType -> SourcePos -> Translator a
dieWith :: ErrorType -> Property -> Translator a
dieWithJust :: ErrorType -> Maybe Property -> Translator a
die = lift . StateT . const . Left
dieWithPos e = die . KnownError e
dieWith e = dieWithPos e . position
dieWithJust e = dieWith e . fromJust
-- }}}
-- Warning {{{
-- by convention, a warning that does not end in a verb just "did the right thing" to correct the problem
-- |
-- Warnings signify recoverable errors.
data Warning
= DuplicatePropertyOmitted Property
| SquareSizeSpecifiedAsRectangle SourcePos
| DanglingEscapeCharacterOmitted SourcePos
| PropValueForNonePropertyOmitted Property
| UnknownPropertyPreserved String
| PointSpecifiedAsPointRange Property
| DuplicatePointsOmitted Property [Point]
| InvalidDatesClipped (Set PartialDate)
| AnnotationWithNoMoveOmitted Property
| ExtraGameInfoOmitted Property
| NestedRootPropertyOmitted Property
| MovelessAnnotationOmitted Property
| DuplicateSetupOperationsOmitted [Point]
| ExtraPositionalJudgmentOmitted (Judgment, Emphasis)
| DuplicateMarkupOmitted (Mark, Point)
| ExtraPropertyValuesOmitted Property
| DuplicateLabelOmitted (Point, String)
| UnknownNumberingIgnored Integer
deriving (Eq, Ord, Show)
-- }}}
-- State, Translator a, PTranslator a {{{
type State = Tree [Property]
type Translator a = WriterT [Warning] (StateT State (Either Error)) a
type PTranslator a = Property -> Translator a
transMap, transMapMulti :: PTranslator a -> String -> Translator (Maybe a)
transMap f = consumeSingle >=> transMap' f
transMapMulti f = consume >=> transMap' f
transMap' :: (a -> Translator b) -> (Maybe a -> Translator (Maybe b))
transMap' f = maybe (return Nothing) (liftM Just . f)
transMapList :: PTranslator [a] -> String -> Translator [a]
transMapList f = consume >=> maybe (return []) f
-- }}}
-- }}}
-- handy Translators {{{
-- helper functions {{{
duplicatesOn :: Ord b => (a -> b) -> [a] -> [a]
duplicatesOn f = map fst
. concatMap (drop 1)
. groupBy ((==) `on` snd)
. sortBy (comparing snd)
. map (id &&& f)
duplicateProperties :: State -> [Warning]
duplicateProperties = map DuplicatePropertyOmitted . duplicatesOn name . rootLabel
duplicates :: Translator ()
duplicates = get >>= tell . duplicateProperties
readNumber :: String -> SourcePos -> Translator Integer
readNumber "" _ = return 0
readNumber s pos | all isDigit s = return (read s)
| otherwise = dieWithPos BadlyFormattedValue pos
newline :: a -> (String -> a) -> (Char -> String -> a) -> String -> a
newline empty with without xs = case xs of
'\r':'\n':xs -> with xs
'\n':'\r':xs -> with xs
'\r': xs -> with xs
'\n': xs -> with xs
x : xs -> without x xs
[] -> empty
trim :: Char -> Char
trim x = if isSpace x then ' ' else x
descape :: Char -> SourcePos -> String -> Translator String
descape hard pos s = case s of
('\\':xs) -> newline' (tell [DanglingEscapeCharacterOmitted pos]) id xs
xs -> newline' (return ()) (hard:) xs
where
newline' warn prefix = newline (warn >> return "") (fmap prefix . descape hard pos) (\c -> fmap (trim c:) . descape hard pos)
decodeAndDescape :: Char -> Header -> PTranslator String
decodeAndDescape hard (Header { encoding = e }) (Property { values = v:_, position = pos }) =
case decodeWordStringExplicit e v of
Left exception -> dieWithPos BadlyEncodedValue pos
Right decoded -> descape hard pos decoded
splitColon :: [Word8] -> Maybe ( [Word8] , [Word8] )
splitColons :: [[Word8]] -> Maybe ([[Word8]], [[Word8]])
splitColons = fmap unzip . mapM splitColon
splitColon xs
| null xs = Nothing
| [enum ':' ] `isPrefixOf` xs = Just ([], drop 1 xs)
| [enum '\\'] `isPrefixOf` xs = continue 2
| otherwise = continue 1
where
continue n = fmap (first (take n xs ++)) (splitColon (drop n xs))
warnAboutDuplicatePoints :: Property -> [Point] -> Translator [Point]
warnAboutDuplicatePoints p ps = let ds = duplicatesOn id ps in do
when (not $ null ds) (tell [DuplicatePointsOmitted p ds])
return (nub ps)
checkPointList :: (PTranslator [Point] -> PTranslator [[Point]]) -> (PTranslator Point -> PTranslator [Point])
checkPointList listType a p = listType (mayBeCompoundPoint a) p >>= warnAboutDuplicatePoints p . concat
-- }}}
-- low-level {{{
has :: String -> Translator Bool
has s = gets (any ((s ==) . name) . rootLabel)
hasAny :: [String] -> Translator Bool
hasAny = fmap or . mapM has
consume :: String -> Translator (Maybe Property)
consume s = do
(v, rest) <- gets (partition ((== s) . name) . rootLabel)
modify (\s -> s { rootLabel = rest })
return (listToMaybe v)
consumeSingle :: String -> Translator (Maybe Property)
consumeSingle s = do
maybeProperty <- consume s
case maybeProperty of
Just p@(Property { values = (v:_:_) }) -> do
tell [ExtraPropertyValuesOmitted p]
return (Just p { values = [v] })
_ -> return maybeProperty
unknownProperties :: Translator (Map String [[Word8]])
unknownProperties = do
m <- gets (fromList . map (name &&& values) . rootLabel)
tell [UnknownPropertyPreserved name | name <- keys m]
return m
-- }}}
-- PTranslators and combinators {{{
number :: PTranslator Integer
number p@(Property { values = v:_ })
| enum '.' `elem` v = dieWith BadlyFormattedValue p
| otherwise = fmap floor (real p)
real :: PTranslator Rational
real (Property { values = v:_, position = pos })
| [enum '+'] `isPrefixOf` v = result 1
| [enum '-'] `isPrefixOf` v = fmap negate (result 1)
| otherwise = result 0
where
split i = second (drop 1) . break (== '.') . map enum . drop i $ v
result i = let (n, d) = split i in do
whole <- readNumber n pos
fract <- readNumber d pos
return (fromInteger whole + fromInteger fract / 10 ^ length d)
simple :: Header -> PTranslator String
text :: Header -> PTranslator String
simple = decodeAndDescape ' '
text = decodeAndDescape '\n'
none :: PTranslator ()
none (Property { values = [[]] }) = return ()
none p = tell [PropValueForNonePropertyOmitted p]
choice :: [([Word8], a)] -> PTranslator a
choice vs p@(Property { values = [] }) = dieWith BadlyFormattedValue p -- can't happen
choice vs p@(Property { values = v:_ }) = maybe (dieWith BadlyFormattedValue p) return (lookup v vs)
choice' :: [(String, a)] -> PTranslator a
choice' vs = choice [(map enum k, v) | (k', v) <- vs, k <- [k', map toLower k']]
double :: PTranslator Emphasis
color :: PTranslator Color
double = choice' [("1", Normal), ("2", Strong)]
color = choice' [("B", Black), ("W", White)]
compose :: PTranslator a -> PTranslator b -> PTranslator (a, b)
compose a b p@(Property { values = vs }) = case splitColons vs of
Nothing -> dieWith BadlyFormattedValue p
Just (as, bs) -> liftM2 (,) (a p { values = as }) (b p { values = bs })
listOf :: PTranslator a -> PTranslator [a]
listOf a p@(Property { values = vs }) = mapM a [p { values = [v] } | v <- vs]
elistOf :: PTranslator a -> PTranslator [a]
elistOf _ (Property { values = [[]] }) = return []
elistOf a p = listOf a p
mayBeCompoundPoint, listOfPoint, elistOfPoint :: PTranslator Point -> PTranslator [Point]
mayBeCompoundPoint a p@(Property { values = v:_ }) = case splitColon v of
Nothing -> fmap return $ a p
Just {} -> do
pointRange <- compose a a p { values = [v] }
when (uncurry (==) pointRange) (tell [PointSpecifiedAsPointRange p])
return (range pointRange)
listOfPoint = checkPointList listOf
elistOfPoint = checkPointList elistOf
-- }}}
-- }}}
| dmwit/sgf | Data/SGF/Parse/Util.hs | bsd-3-clause | 9,423 | 0 | 18 | 2,211 | 3,375 | 1,776 | 1,599 | 201 | 6 |
module Battleships.Game where
import System.Random -- for randoms
import System.IO -- for hFlush
import Prelude
import Data.List as List
import Data.Map as Map
import Data.Maybe as Maybe
type Unit = Int
type Coord = (Unit, Unit)
--Record:
nr_cols, nr_lines :: Int -- maximum value!
nr_cols = 10
nr_lines = 10
boats :: [Unit]
boats = [5,4,3,2,2,1,1]
dim :: Int
dim = 10
type Grid = Map Coord Cell
emptyGrid :: Grid
emptyGrid = fromList [((x,y), Empty) | x <- [1..dim], y <- [1..dim]]
computerGridTest :: IO Grid
computerGridTest = return $ fromList [((x,y), if(x*y `rem` 3 == 0) then Empty else Boat ) | x <- [1..dim], y <- [1..dim]]
-- one shot
shootComputer :: Grid -> IO Coord
shootComputer g = return $ fst (head (toList (Map.filter notShot g)))
where notShot Boat = True
notShot Empty = True
notShot _ = False
{-
-- computer shoots until it misses
shootingComputer :: Grid -> IO [(Coord, Cell)]
shootingComputer g = let f g cs = do shot <- shootComputer g
if look shot g /= BoatShot
then return ((shot, EmptyShot):cs)
else f (insert shot BoatShot g) ((shot, BoatShot):cs)
in f g []-}
look k m = a where (Just a) = Map.lookup k m
-- new cell state after shot
shootToCell :: Coord -> Grid -> Cell
shootToCell c g = case look c g of
Boat -> BoatShot
Empty -> EmptyShot
_ -> error "Already shot"
-- Computer shot
type Row = [Int]
-- one more constructor added ; so if the ship is Entirly taken down it should be marked so. "DeadShip"
data Cell = Boat | Empty | BoatShot | EmptyShot | DeadShip
deriving (Show, Eq)
-- we need functions to check the state of the cell ...
-- this function will check if the cell is empty
isEmpty :: Cell -> Bool
isEmpty Empty = True
isEmpty Boat = True
isEmpty _ = False
-- this function will check if the cell is EmptyShot
isEmptyShot :: Cell -> Bool
isEmptyShot EmptyShot = True
isEmptyShot _ = False
-- this function will check if the cell is Boat
isBoat :: Cell -> Bool
isBoat Boat = True
isBoat _ = False
-- this function will check if the cell is a BoatShot
isBoatShot :: Cell -> Bool
isBoatShot BoatShot = True
isBoatShot _ = False
-- types
type Pos = (Int, Int)
type Dir = Pos
-- checks if the (x,y) is within the Grid range
validRange :: Pos -> Grid -> Bool
validRange (x,y) g = nr_lines >= x && x>= 1 && nr_cols >= y && y >= 1
-- returns a list of all neighbours of a Cell
neighbours :: Pos -> [Pos]
neighbours (x,y) = [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]
-- returns a list of all valid neighbours of a Cell
validNeighbours :: Pos -> Grid -> [Pos]
validNeighbours p g = List.filter (\ q -> validRange q g) (neighbours p)
-- returns a list of positions of Cells filtered with a certain criteria
getPositions :: (Cell -> Bool) -> Grid -> [Pos]
getPositions p g = Map.keys (Map.filter p g)
-- returns a list of all BoatShot-Cells
getBoatShots = getPositions isBoatShot
-- returns a list of all Empty-Cells
getEmpties = getPositions isEmpty
-- computes the direction from a position and a position
posDiff :: Pos -> Pos -> Dir
posDiff (x1,y1) (x2,y2) = (x1-x2,y1-y2)
-- computes the position from a position and a Direction
posAdd :: Pos -> Dir -> Pos
posAdd (x1,y1) (x2,y2) = (x1+x2,y1+y2)
-- gets the status of the cell giving the cell's position in the grid
gridAt :: Grid -> Pos -> Cell
gridAt g p = g Map.! p
-- it looks for the next empty cell on the grid, and returns its position. or Nothing otherwise.
-- Nothing is returned if the position is of an invalid range or if it's an EmptyShot
nextEmpty :: Dir -> Pos -> Grid -> Maybe Pos
nextEmpty dir pos grid
| not (validRange pos grid) = Nothing
| isEmptyShot (gridAt grid pos) = Nothing
| isEmpty (gridAt grid pos) = Just pos
| otherwise = nextEmpty dir (posAdd pos dir) grid
-- it returns a random element of a list
randomFromList :: [a] -> IO a
randomFromList xs = do r <- randomRIO (0,length xs-1)
return (xs !! r)
-- it will return the position of a random empty cell
randomMove :: Grid -> IO Pos
randomMove grid = randomFromList (getEmpties grid)
--it returns the position the computer is supposed to hit next
computeMove :: Grid -> IO Pos
computeMove g = computeMove_aux g (getBoatShots g)
--it returns the position the computer is supposed to hit next
computeMove_aux g ll= case ll of -- a list of BoatShot cells
[] -> randomMove g -- if the list is empty then it would be a random move
-- else ; which means we have at least 1 element in the list that is a BoatShot
-- then we see if there is a BoatShot neighbour of that position
(p:l) -> case List.filter (\ q -> isBoatShot (gridAt g q)) (validNeighbours p g) of
-- if there is not a neighbour that is a BoatShot; then return a random neighbour -- that is valid
[] -> case (List.filter (\ q -> isEmpty (gridAt g q)) (validNeighbours p g)) of
[] -> computeMove_aux g l
_ -> randomFromList (List.filter (\ q -> isEmpty (gridAt g q)) (validNeighbours p g))
-- else; there is neighbour that is a BoatShot, then return the position of the next -- hit that is on the same line
(p':_) -> case (maybeToList (nextEmpty (posDiff p p') p g) ++
maybeToList (nextEmpty (posDiff p' p) p' g)) of
[] -> computeMove_aux g l
(a:_) -> return (head (maybeToList (nextEmpty (posDiff p p') p g) ++
maybeToList (nextEmpty (posDiff p' p) p' g)))
-- true if this board finished
finished :: Grid -> Bool
finished g = size (Map.filter (==Boat) g) == 0
-- Functions for testing:
testGrid :: Grid
testGrid = (Map.insert (10,5) BoatShot
(Map.insert (3,2) BoatShot
(Map.insert (3,1) BoatShot emptyGrid)))
| fokot/battleships | src/Battleships/Game.hs | bsd-3-clause | 6,422 | 0 | 23 | 2,006 | 1,681 | 913 | 768 | 96 | 5 |
--
-- Canonicalize.hs
--
-- Transform an expression into canonical form. This is essentially
-- a simplification, but the real goal is that identical expressions
-- will have identical representations after canonicalization.
--
-- Gregory Wright, 27 April 2011
--
module Math.Symbolic.Wheeler.Canonicalize (
canonicalize,
groupFactors
) where
import Data.List
import Data.Maybe
import Data.Ratio
import Math.Symbolic.Wheeler.Common
import Math.Symbolic.Wheeler.DummyIndices
import {-# SOURCE #-} Math.Symbolic.Wheeler.Expr
import Math.Symbolic.Wheeler.Numeric
import Math.Symbolic.Wheeler.NumericRational
import Math.Symbolic.Wheeler.SumOrd
import Math.Symbolic.Wheeler.SimpleSymbol
import Math.Symbolic.Wheeler.Symbol
import Math.Symbolic.Wheeler.TensorBasics
canonicalize :: Expr -> Expr
canonicalize = canonicalize' . canonicalizeTensorExpr_
canonicalize' :: Expr -> Expr
canonicalize' c@(Const _) = simplifyConstant c
canonicalize' s@(Symbol _) = s
canonicalize' (Product x) = simplifyProduct (Product (map canonicalize' x))
canonicalize' (Power b e) = simplifyPower (Power (canonicalize' b) (canonicalize' e))
canonicalize' (Sum x) = simplifySum (Sum (map canonicalize' x))
canonicalize' (Applic f a) = simplifyFunction (Applic f (canonicalize' a))
canonicalize' Undefined = Undefined
canonicalizeTensorExpr :: Expr -> Expr
canonicalizeTensorExpr e
| hasTensor e = uniqueDummies e
| otherwise = e
canonicalizeTensorExpr_ :: Expr -> Expr
canonicalizeTensorExpr_ e
| hasTensor e = uniqueDummies__ e
| otherwise = e
-- Test if a constant expression is numerically zero. Note that the expression
-- is not evaluated; the only thing that is checked is if it is a constant,
-- and the constant is zero.
isConstantZero :: Expr -> Bool
isConstantZero (Const (I 0)) = True
isConstantZero (Const (Q _ 0)) = False
isConstantZero (Const (Q 0 _)) = True
isConstantZero _ = False
isDivideByZero :: Expr -> Bool
isDivideByZero (Const (Q _ 0)) = True
isDivideByZero _ = False
isConstantOne :: Expr -> Bool
isConstantOne (Const (I 1)) = True
isConstantOne _ = False
isConstant :: Expr -> Bool
isConstant (Const _) = True
isConstant _ = False
isConstantInteger :: Expr -> Bool
isConstantInteger (Const (I _)) = True
isConstantInteger _ = False
isPositive :: Expr -> Bool
isPositive (Const (I n)) = n > 0
isPositive (Const (Q n d)) = (n % d) > 0
isPositive _ = False
isPlaceholder :: Expr -> Bool
isPlaceholder (Symbol (Simple s)) = simpleType s == Placeholder
isPlaceholder _ = False
-- simplifyConstant checks rationals for explicit division
-- by zero, otherwise it returns the argument unchanged.
simplifyConstant :: Expr -> Expr
simplifyConstant q@(Const (Q _ _)) = simplifyRNE q
simplifyConstant i@(Const (I _)) = i
simplifyConstant _ = error "simplifyConstant applied to non-constant expression"
-- 'simplifyProduct' implements the transformations given in Definition 3.37
-- of Cohen's "Computer Algebra and Symbolic Computation: Mathematical Methods",
-- p. 98.
simplifyProduct :: Expr -> Expr
simplifyProduct (Product fs) = sp (filter (not . isPlaceholder) fs)
where
sp fs'
| null fs' = Const 1
| elem Undefined fs' = Undefined
| any isDivideByZero fs' = Undefined
| elem (Const 0) fs' = Const 0
| null (tail fs') = head fs'
| otherwise =
let
simplifyProduct' :: [ Expr ] -> Expr
simplifyProduct' [] = Const 1
simplifyProduct' (x : []) = x
simplifyProduct' xs = Product xs
in
simplifyProduct' (simplifyFactors fs')
simplifyProduct _ = error "simplifyProduct applied to non-product expression"
simplifyFactors :: [ Expr ] -> [ Expr ]
simplifyFactors [] = []
simplifyFactors (Product fs : Product fs' : []) = mergeFactors fs fs'
simplifyFactors (Product fs : u : []) = mergeFactors fs [ u ]
simplifyFactors (u : Product fs : []) = mergeFactors [u] fs
simplifyFactors (u1 : u2 : [])
| isConstant u1 && isConstant u2 =
let
p = simplifyRNE (Product [u1,u2])
in
if p == (Const 1) then [] else [p]
| isConstantOne u1 = [u2]
| isConstantOne u2 = [u1]
-- A special case follows: I don't want tensor expressions to
-- be expressed as powers. Doing so would particularly
-- mess up canonicalized tensor patterns containing wildcards.
-- After I implement true index patterns this check "not (has Tensor ..."
-- can probably be removed.
| (basePart u1 == basePart u2) && not (hasTensor u1 || hasTensor u2) =
let
s = simplifySum (Sum [exponentPart u1, exponentPart u2])
p = simplifyPower (Power (basePart u1) s)
in
if p == (Const 1) then [] else [p]
| u2 < u1 = [u2, u1]
| otherwise = [u1, u2]
simplifyFactors (u : us) =
let
w = simplifyFactors us
factorList :: Expr -> [ Expr ]
factorList (Product vs) = vs
factorList x = [ x ]
in
mergeFactors (factorList u) w
mergeFactors :: [ Expr ] -> [ Expr ] -> [ Expr ]
mergeFactors [] [] = []
mergeFactors p [] = p
mergeFactors [] q = q
mergeFactors p q =
let
p' = groupFactors p
q' = groupFactors q
f = findCorrespondingFactors p' q'
c = lookup [] f
n = deleteBy (\(x, (_, _)) (y, (_, _)) -> x == y) ([], (undefined, undefined)) f
(_, (c', c'')) = if isJust c then ([], fromJust c) else ([], ([],[]))
mergedCommuting = mergeCommutingFactors c' c''
mergedNoncommuting = map (\(_, (y, z)) -> mergeNoncommutingFactors y z) n
in
mergedCommuting ++ concat mergedNoncommuting
-- This is the orginal definition of factor merge for commuting factors:
--
-- It depends on the argument expression lists being "admissible"
-- factors, which means that they can contain constants, symbols,
-- sums, powers or functions but not products.
--
mergeCommutingFactors :: [ Expr ] -> [ Expr ] -> [ Expr ]
mergeCommutingFactors [] [] = []
mergeCommutingFactors [] q = q
mergeCommutingFactors p [] = p
mergeCommutingFactors pp@(p : ps) qq@(q : qs) =
let
h = simplifyFactors [p, q]
in
if null h
then mergeCommutingFactors ps qs
else if null (tail h)
then (head h) : mergeCommutingFactors ps qs
else if head h == p
then p : mergeCommutingFactors ps qq
else q : mergeCommutingFactors pp qs
-- This version of works for non-commutative
-- expressions:
--
mergeNoncommutingFactors :: [ Expr ] -> [ Expr ] -> [ Expr ]
mergeNoncommutingFactors [] [] = []
mergeNoncommutingFactors [] q = q
mergeNoncommutingFactors p [] = p
mergeNoncommutingFactors p q =
let
ps = init p
p' = last p
q' = head q
qs = tail q
h = simplifyFactors [p', q']
in
if null h
then mergeNoncommutingFactors ps qs
else if null (tail h)
then mergeNoncommutingFactors ps ((head h) : qs)
else if head h == p'
then mergeNoncommutingFactors ps (p' : q)
else mergeNoncommutingFactors ps (q' : p' : qs)
-- XXX FIXME XXX
-- This function doesn't work properly.
-- Is it in fact incorrect? - 14 May 12
--
findCorrespondingFactors :: [ ([ String ], [ Expr ]) ]
-> [ ([ String ], [ Expr ]) ]
-> [ ([ String ], ([ Expr ], [ Expr ])) ]
findCorrespondingFactors [] [] = []
findCorrespondingFactors p [] = map (\(x, y) -> (x, (y, []))) p
findCorrespondingFactors [] q = map (\(x, y) -> (x, ([], y))) q
findCorrespondingFactors (p : ps) qs =
let
c = lookup (fst p) qs
qs' = if isJust c
then deleteBy (\(x, _) (y, _) -> x == y) (fst p, undefined) qs
else qs
in
if isJust c
then (\(x, y) z -> (x, (y, z ))) p (fromJust c) : findCorrespondingFactors ps qs'
else (\(x, y) -> (x, (y, []))) p : findCorrespondingFactors ps qs'
-- Group the factors in an expression list by representation
-- space. The return value is a list of the names of the representation
-- spaces and the expressions that live on those spaces. Ordinary
-- commuting factors live in the anonymous space, whose name
-- is the empty list.
--
-- If there are no commuting factors, prefix a pair
-- of empty lists to indicate this.
--
groupFactors :: [ Expr ] -> [ ([ String ], [ Expr ]) ]
groupFactors es =
let
es' = groupExprs es
es'' = map (\x -> (repSpaces (head x), x)) es'
in
if isJust (lookup [] es'') then es'' else ([], []) : es''
groupExprs :: [ Expr ] -> [[ Expr ]]
groupExprs [] = []
groupExprs pp@(p : _) =
let
(p', q') = partition (\x -> repSpaces x == repSpaces p) pp
in
p' : groupExprs q'
basePart :: Expr -> Expr
basePart (Const _) = Undefined
basePart (Power b _) = b
basePart x = x
exponentPart :: Expr -> Expr
exponentPart (Const _) = Undefined
exponentPart (Power _ e) = e
exponentPart _ = Const (I 1)
-- Simplify powers:
simplifyPower :: Expr -> Expr
simplifyPower p@(Power b e)
| b == Undefined || e == Undefined = Undefined
| isConstantZero b = if isPositive e then Const (I 0) else Undefined
| isConstantOne b = Const (I 1)
| isConstantInteger e = simplifyIntegerPower p
| otherwise = p
simplifyPower _ = error "simplifyPower applied to non-power"
-- 'simplifyIntegerPower' handles the case in which an expression is
-- raised to an integer power.
-- For products of non-commuting factors, there are still bugs.
-- The order of factors should be reversed only for negative integer
-- powers. For any other integer power of non-commuting factors,
-- should I just leave the expression unchanged?
--
simplifyIntegerPower :: Expr -> Expr
simplifyIntegerPower (Power (Const (I b)) (Const (I e))) = simplifyRNE (Power (Const (I b)) (Const (I e)))
simplifyIntegerPower (Power (Const (Q n d)) (Const (I e))) = simplifyRNE (Power (Const (Q n d)) (Const (I e)))
simplifyIntegerPower (Power _ (Const (I 0))) = Const 1
simplifyIntegerPower (Power b (Const (I 1))) = b
simplifyIntegerPower (Power (Power r s) e@(Const (I _))) =
let
p = simplifyProduct (Product [s, e])
in
if isConstantInteger p
then simplifyIntegerPower (Power r p)
else (Power r p)
simplifyIntegerPower (Power (Product fs) e@(Const (I _))) =
let
fs' = groupFactors fs
cfs = fromJust (lookup [] fs') -- lookup will never return Nothing
-- because a [] association is always
-- returned by groupFactors
ncfs = deleteBy (\(x, _) (y, _) -> x == y) ([], undefined) fs'
r = if null cfs
then []
else map (\f -> simplifyIntegerPower (Power f e)) cfs
r' = if null ncfs
then []
else [ (Power (Product (concatMap snd ncfs)) e) ]
r'' = simplifyProduct (Product r)
-- Unwrap a commuting product:
commutingProduct (Const 1) = []
commutingProduct (Product cs) = cs
commutingProduct cs = [ cs ]
in
Product (commutingProduct r'' ++ r')
simplifyIntegerPower (Power b e@(Const (I _))) = Power b e
simplifyIntegerPower _ = error "simplifyIntegerPower applied to non-power"
-- 'simplifySum' parallels 'simplyProduct'. It is outlined but
-- not completely defined on p. 105 of Cohen.
--
simplifySum :: Expr -> Expr
simplifySum (Sum ts) = ss (filter (not . isPlaceholder) ts)
where ss ts'
| elem Undefined ts' = Undefined
| null (tail ts') = head ts'
| otherwise =
let
simplifySum' :: [ Expr ] -> Expr
simplifySum' [] = Const 0
simplifySum' (t : []) = t
simplifySum' tt = Sum tt
in
simplifySum' (simplifyTerms ts')
simplifySum _ = error "simplifySum applied to non-sum"
simplifyTerms :: [ Expr ] -> [ Expr ]
simplifyTerms [] = []
simplifyTerms (Sum ts : Sum ts' : []) = mergeTerms ts ts'
simplifyTerms (Sum ts : u : []) = mergeTerms ts [u]
simplifyTerms (u : Sum ts : []) = mergeTerms [u] ts
simplifyTerms (u1 : u2 : [])
| isConstant u1 && isConstant u2 =
let
p = simplifyRNE (Sum [u1, u2])
in
if p == (Const 0) then [] else [p]
| isConstantZero u1 = [u2]
| isConstantZero u2 = [u1]
| termPart u1 == termPart u2 =
let
s = simplifySum (Sum [constantPart u1, constantPart u2])
p = simplifyProduct (Product [termPart u1, s])
in
if p == Const 0 then [] else [p]
| (sumCompare u2 u1) == LT = [u2, u1]
| otherwise = [u1, u2]
simplifyTerms (u : us) =
let
w = simplifyTerms us
termList :: Expr -> [ Expr ]
termList (Sum vs) = vs
termList x = [ x ]
in
mergeTerms (termList u) w
mergeTerms :: [ Expr ] -> [ Expr ] -> [ Expr ]
mergeTerms [] [] = []
mergeTerms [] q = q
mergeTerms p [] = p
mergeTerms pp@(p : ps) qq@(q : qs) =
let
h = simplifyTerms [p, q]
in
if null h
then mergeTerms ps qs
else if null (tail h)
then (head h) : mergeTerms ps qs
else if head h == p
then p : mergeTerms ps qq
else q : mergeTerms pp qs
constantPart :: Expr -> Expr
constantPart (Const _) = Undefined
constantPart (Symbol _) = Const 1
constantPart (Sum _) = Const 1
constantPart (Power _ _) = Const 1
constantPart (Applic _ _) = Const 1
constantPart (Product []) = Undefined
constantPart (Product (u : _)) = if isConstant u then u else Const 1
constantPart Undefined = Undefined
termPart :: Expr -> Expr
termPart (Const _) = Undefined
termPart x@(Symbol _) = Product [x]
termPart x@(Sum _) = Product [x]
termPart x@(Power _ _) = Product [x]
termPart x@(Applic _ _) = Product [x]
termPart (Product []) = Undefined
termPart x@(Product (u : us)) = if isConstant u then Product us else x
termPart Undefined = Undefined
-- 'simplifyfunction' is the identity unless one of the
-- arguments is undefined, in which case the entire expression
-- in undefined:
simplifyFunction :: Expr -> Expr
simplifyFunction (Applic _ Undefined) = Undefined
simplifyFunction g@(Applic _ _) = g
simplifyFunction _ = error "simplifyFunction applied to non-function"
| gwright83/Wheeler | src/Math/Symbolic/Wheeler/Canonicalize.hs | bsd-3-clause | 15,405 | 0 | 16 | 4,851 | 4,903 | 2,550 | 2,353 | 297 | 6 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
--
-- RegTypes.hs --- General Purpose Timer (TIM2 to TIM5) register types
--
-- Copyright (C) 2013, Galois, Inc.
-- All Rights Reserved.
--
module Ivory.BSP.STM32.Peripheral.GTIM2345.RegTypes where
import Ivory.Language
-- Compare Mode bit field definitions:
[ivory|
bitdata CCMRMode :: Bits 3
= ccmr_mode_frzn as 0
| ccmr_mode_chact as 1
| ccmr_mode_chinact as 2
| ccmr_mode_ocreftog as 3
| ccmr_mode_ocreflo as 4
| ccmr_mode_ocrefhi as 5
| ccmr_mode_pwm1 as 6
| ccmr_mode_pwm2 as 7
|]
-- Capture/Compare Selection bit field definitions:
[ivory|
bitdata CCSMode :: Bits 2
= ccs_mode_out as 0
| ccs_mode_in1 as 1
| ccs_mode_in2 as 2
| ccs_mode_intrc as 3
|]
| GaloisInc/ivory-tower-stm32 | ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/GTIM2345/RegTypes.hs | bsd-3-clause | 856 | 0 | 4 | 187 | 41 | 33 | 8 | 8 | 0 |
import System.Environment (getArgs)
import Data.Bits ((.&.), (.|.), bit)
import Data.List (sort)
import Data.List.Split (splitOn)
hor :: [Int]
hor = [0x42, 0x84, 0x108, 0x210,
0x840, 0x1080, 0x2100, 0x4200,
0x10800, 0x21000, 0x42000, 0x84000,
0x210000, 0x420000, 0x840000, 0x1080000,
0x1806, 0x300c, 0x6018,
0x300c0, 0x60180, 0xc0300,
0x601800, 0xc03000, 0x1806000,
0x7000e, 0xe001c,
0xe001c0, 0x1c00380,
0x1e0001e]
ver :: [Int]
ver = [0x6, 0xc, 0x18, 0x30,
0xc0, 0x180, 0x300, 0x600,
0x1800, 0x3000, 0x6000, 0xc000,
0x30000, 0x60000, 0xc0000, 0x180000,
0x14a, 0x294, 0x528,
0x2940, 0x5280, 0xa500,
0x52800, 0xa5000, 0x14a000,
0x4a52, 0x94a4,
0x94a40, 0x129480,
0x118c62]
builders :: Int -> Int -> [Int] -> [Int] -> Int
builders _ _ [] [] = 0
builders x y (a:as) (b:bs) | (.&.) x a == a && (.&.) y b == b = succ (builders x y as bs)
| otherwise = builders x y as bs
buildersteam :: Int -> Int -> [String] -> Int
buildersteam x y [] = builders x y hor ver
buildersteam x y (z:zs) | a + 1 == b = buildersteam ((.|.) x (bit a)) y zs
| otherwise = buildersteam x ((.|.) y (bit a)) zs
where s = sort . map read $ words z
a = head s
b = last s
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . buildersteam 0 0 . splitOn " | ") $ lines input
| nikai3d/ce-challenges | moderate/builders_team.hs | bsd-3-clause | 1,628 | 0 | 13 | 571 | 639 | 358 | 281 | 42 | 1 |
{-# OPTIONS_GHC -fdefer-typed-holes #-}
----------------------------------------------------------------------------------------------------
-- |
-- Module : Numeric.Algebra.Elementary.Solve
-- Copyright : William Knop 2015
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- Solver for elementary algebraic expressions.
--
-- __/TODO:/__ Everything.
--
-- __/TODO:/__ Write exports.
module Numeric.Algebra.Elementary.Solve where
import Numeric.Algebra.Elementary.AST
| altaic/algebra-elementary | src/Numeric/Algebra/Elementary/Solve.hs | bsd-3-clause | 547 | 0 | 4 | 83 | 30 | 26 | 4 | 3 | 0 |
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MonadComprehensions #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
-- | A module for PATRICIA tries with configurable spans.
module Trie.Vector where
import Prelude hiding (lookup, span)
import Control.DeepSeq (NFData (..), deepseq)
import Data.Bits
import Data.List (foldl')
import Data.Monoid (Monoid, (<>))
import Data.Proxy (Proxy (..))
import Data.Vector (Vector, (!))
import qualified Data.Vector as Vector
import Data.Word (Word64)
import GHC.Stack (HasCallStack)
import GHC.TypeLits
import Text.Printf (printf)
-- | A PATRICIA trie that inspects an @Int@ key 's' bits at a time.
data Trie (s :: Nat) a = Empty
| Leaf !Int a
-- ^ Each leaf stores the whole key along with
-- the value for that key.
| Branch !Int !Int !(Vector (Trie s a))
-- ^ Each branch stores \(2^s\) children along
-- with a prefix and the index of the leading
-- bit branched on.
deriving (Eq, Ord)
instance Show a => Show (Trie s a) where
show Empty = "Empty"
show (Leaf k v) = printf "Leaf %d %s" k (show v)
show (Branch prefix index children) = printf "Branch 0b%b %d %s" prefix index (show children)
instance NFData (Trie s a) where
rnf Empty = ()
rnf (Leaf !k !v) = ()
rnf (Branch !_ !_ children) = rnf children `seq` ()
isEmpty :: Trie s a -> Bool
isEmpty Empty = True
isEmpty _ = False
isLeaf :: Trie s a -> Bool
isLeaf Leaf{} = True
isLeaf _ = False
-- | Get the span of a tree from its type. (The given argument is discarded!)
span :: forall s a. KnownNat s => Trie s a -> Int
span _ = fromInteger $ natVal (Proxy :: Proxy s)
{-# INLINE span #-}
width :: Int
width = finiteBitSize (0 :: Int)
-- TODO: There's probably a better way to do this…
-- | Masks out everything less significant and including the bit at the given index.
--
-- Example:
-- @
-- getPrefix 3 0b111111111 6 = 0b111000000
-- @
getPrefix :: Int -> Int -> Int
getPrefix key index = key .&. ((- 1) `shiftL` index)
-- | Get the chunk of the key for the given bit index, shifted all the
-- way right.
--
-- For example, with a span of 8, the key @011000111100@ is broken up
-- into @01 10 00 11 11 00@, indexed from the least-significant chunk
-- starting with 0.
--
-- Keep in mind that the total number of bits in a key depends on your
-- platform—probably 32 or 64.)
getChunk :: Int -- ^ span of tree (# of bits to read at a time)
-> Int -- ^ key
-> Int -- ^ which chunk of the key to get
-> Int
getChunk span (fromIntegral -> key) index =
(fromIntegral @Word $ key `shiftR` (index * span)) .&. (bit span - 1)
-- note that we convert the Int key to a Word to get a logical
-- (unsigned) right shift.
-- | A "smart constructor" that consolidates paths that either end or
-- don't branch (ie have exactly one child leaf).
branch :: Int -> Int -> Vector (Trie s a) -> Trie s a
branch prefix index children = case Vector.foldl' go (Just Empty) children of
Just x -> x
Nothing -> Branch prefix index children
where go (Just Empty) x = Just x
go x Empty = x
go _ _ = Nothing
{-# INLINE branch #-}
countTrailingNonZeros :: Int -> Int
countTrailingNonZeros n = finiteBitSize n - countLeadingZeros n
-- | Gets the index on which a tree of span s branches on the given key.
-- The key has to be positive!
getIndex :: Int -> Int -> Int
getIndex s x = let n = countTrailingNonZeros x - 1 in n + s - (n `rem` s)
lookup :: (HasCallStack, KnownNat s) => Int -> Trie s a -> Maybe a
lookup _ Empty = Nothing
lookup k (Leaf k' v) = [v | k == k']
lookup k t@(Branch prefix index children)
| getPrefix k index /= prefix = Nothing
| otherwise = lookup k (children ! chunk)
where chunk = getChunk (span t) k index
-- | A helper function that combines two trees with two *different*,
-- *non-overlapping* prefixes. Make sure the prefixes don't overlap
-- before using this function!
combine :: KnownNat s => Int -> Trie s a -> Int -> Trie s a -> Trie s a
combine p₁ t₁ p₂ t₂ = branch prefix index newChildren
where newChildren = Vector.generate s go
where go x | x == getChunk s p₁ index = t₁
| x == getChunk s p₂ index = t₂
| otherwise = Empty
index = getIndex s $ p₁ `xor` p₂
prefix = getPrefix p₁ index
s = span t₁
-- -- | A faster version of combine that does not collapse lone Empty and
-- -- Leaf nodes.
-- combine' :: (HasCallStack, KnownNat s)
-- => Int -> Trie s a -> Int -> Trie s a -> Trie s a
-- combine' p₁ t₁ p₂ t₂ = Branch prefix index newChildren
-- where newChildren = Vector.update empties [ (getChunk s p₁ index, t₁)
-- , (getChunk s p₂ index, t₂) ]
-- empties = Vector.replicate (2^s) Empty
-- index = getIndex s $ p₁ `xor` p₂
-- prefix = getPrefix p₁ index
-- s = span t₁
insertWith :: forall s a. (HasCallStack, KnownNat s)
=> (a -> a -> a) -> Int -> a -> Trie s a -> Trie s a
insertWith (⊗) !k v Empty = Leaf k v
insertWith (⊗) !k v t@(Leaf k' v')
| k == k' = Leaf k (v ⊗ v')
| otherwise = combine k (Leaf k v) k' (Leaf k' v')
insertWith (⊗) !k v trie@(Branch prefix index children)
| getPrefix k index == prefix = branch prefix index newChildren
| otherwise = combine k (Leaf k v) prefix trie
where newChildren =
modify children (getChunk s k index) (insertWith (⊗) k v)
s = span trie
insert :: forall s a. KnownNat s => Int -> a -> Trie s a -> Trie s a
insert = insertWith const
fromList :: KnownNat s => [(Int, a)] -> Trie s a
fromList = foldr (\ (k, v) t -> insert k v t) Empty
-- TODO: figure out how to do this properly?
modify :: HasCallStack => Vector a -> Int -> (a -> a) -> Vector a
modify v i f = Vector.update v [(i, f $ v ! i)]
toList :: KnownNat s => Trie s a -> [(Int, a)]
toList Empty = []
toList (Leaf k v) = [(k, v)]
toList (Branch _ _ children) = Vector.toList children >>= toList
keys :: KnownNat s => Trie s a -> [Int]
keys = map fst . toList
values :: KnownNat s => Trie s a -> [a]
values = map snd . toList
-- TODO: Figure out ordering in insert case
mergeWith :: KnownNat s => (a -> a -> a) -> Trie s a -> Trie s a -> Trie s a
mergeWith _ Empty t = t
mergeWith _ t Empty = t
mergeWith f (Leaf k v) t = insertWith f k v t
mergeWith f t (Leaf k v) = insertWith f k v t
-- t_1 instead of t₁ to deal with GHC parsing bug with visible type
-- applications
mergeWith f t_1@(Branch p₁ i₁ cs₁) t_2@(Branch p₂ i₂ cs₂)
-- prefixes exactly the same:
| i₁ == i₂ && p₁ == p₂ = branch p₁ i₁ $ Vector.zipWith (mergeWith f) cs₁ cs₂
-- branching on t_1:
| i₁ > i₂ && getPrefix p₂ i₁ == p₁ = branch p₁ i₁ $
modify cs₁ (getChunk s p₂ i₁) (mergeWith (flip f) t_2)
-- branching on t_2:
| i₂ > i₁ && getPrefix p₁ i₂ == p₂ = branch p₂ i₂ $
modify cs₂ (getChunk s p₁ i₂) (mergeWith f t_1)
-- prefixes don't overlap:
| otherwise = combine p₁ t_1 p₂ t_2
where s = span t_1
merge :: KnownNat s => Trie s a -> Trie s a -> Trie s a
merge = mergeWith const
-- Utility functions
b :: Int -> IO ()
b i = printf "%b\n" i
| TikhonJelvis/different-tries | src/Trie/Vector.hs | bsd-3-clause | 8,037 | 96 | 13 | 2,402 | 2,367 | 1,231 | 1,136 | -1 | -1 |
module Reverse where
-- Chapter 3 exercise
dropLast :: [a] -> [a]
dropLast x = take (len - 1) x
where len = length x
rvrs :: [a] -> [a]
rvrs [] = []
rvrs x = last : rvrs (dropLast x)
where len = length x
last = x !! (len - 1)
main :: IO ()
main = print $ rvrs "Curry is awesome."
| tkasu/haskellbook-adventure | app/Reverse.hs | bsd-3-clause | 309 | 0 | 9 | 95 | 146 | 78 | 68 | 11 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
module Pos.Diffusion.Full.Update
( sendVote
, sendUpdateProposal
, updateListeners
, updateOutSpecs
) where
import Universum
import qualified Network.Broadcast.OutboundQueue as OQ
import Pos.Chain.Update (UpId, UpdateProposal, UpdateVote, mkVoteId)
import Pos.Communication.Limits (mlUpdateProposalAndVotes,
mlUpdateVote)
import Pos.Infra.Communication.Protocol (EnqueueMsg, MkListeners,
MsgType (..), NodeId, Origin (..), OutSpecs)
import Pos.Infra.Communication.Relay (InvReqDataParams (..),
MempoolParams (..), Relay (..), invReqDataFlowTK,
relayListeners, relayPropagateOut)
import Pos.Infra.Network.Types (Bucket)
import Pos.Logic.Types (Logic (..))
import qualified Pos.Logic.Types as KV (KeyVal (..))
import Pos.Util.Trace (Severity, Trace)
-- Send UpdateVote to given addresses.
sendVote
:: Trace IO (Severity, Text)
-> EnqueueMsg
-> UpdateVote
-> IO ()
sendVote logTrace enqueue vote =
void $ invReqDataFlowTK
logTrace
"UpdateVote"
enqueue
(MsgMPC OriginSender)
(mkVoteId vote)
vote
-- Send UpdateProposal to given address.
sendUpdateProposal
:: Trace IO (Severity, Text)
-> EnqueueMsg
-> UpId
-> UpdateProposal
-> [UpdateVote]
-> IO ()
sendUpdateProposal logTrace enqueue upid proposal votes = do
void $ invReqDataFlowTK
logTrace
"UpdateProposal"
enqueue
(MsgMPC OriginSender)
upid
(proposal, votes)
updateListeners
:: Trace IO (Severity, Text)
-> Logic IO
-> OQ.OutboundQ pack NodeId Bucket
-> EnqueueMsg
-> MkListeners
updateListeners logTrace logic oq enqueue = relayListeners logTrace oq enqueue (usRelays logic)
-- | Relays for data related to update system
usRelays :: Logic IO -> [Relay]
usRelays logic = [proposalRelay logic, voteRelay logic]
-- | 'OutSpecs' for the update system, to keep up with the 'InSpecs'/'OutSpecs'
-- motif required for communication.
-- The 'Logic m' isn't *really* needed, it's just an artefact of the design.
updateOutSpecs :: Logic IO -> OutSpecs
updateOutSpecs logic = relayPropagateOut (usRelays logic)
----------------------------------------------------------------------------
-- UpdateProposal relays
----------------------------------------------------------------------------
proposalRelay :: Logic IO -> Relay
proposalRelay logic =
InvReqData
NoMempool $
InvReqDataParams
{ invReqMsgType = MsgMPC
, contentsToKey = KV.toKey kv
, handleInv = \_ -> KV.handleInv kv
, handleReq = \_ -> KV.handleReq kv
, handleData = \_ -> KV.handleData kv
, irdpMkLimit = mlUpdateProposalAndVotes <$> getAdoptedBVData logic
}
where
kv = postUpdate logic
----------------------------------------------------------------------------
-- UpdateVote listeners
----------------------------------------------------------------------------
voteRelay :: Logic IO -> Relay
voteRelay logic =
InvReqData
NoMempool $
InvReqDataParams
{ invReqMsgType = MsgMPC
, contentsToKey = KV.toKey kv
, handleInv = \_ -> KV.handleInv kv
, handleReq = \_ -> KV.handleReq kv
, handleData = \_ -> KV.handleData kv
, irdpMkLimit = pure mlUpdateVote
}
where
kv = postVote logic
| input-output-hk/pos-haskell-prototype | lib/src/Pos/Diffusion/Full/Update.hs | mit | 3,628 | 0 | 11 | 954 | 748 | 427 | 321 | 84 | 1 |
module Nancy.Core.Env where
import qualified Data.Map as Map
import Text.PrettyPrint
import Text.PrettyPrint.HughesPJClass
import Control.Monad.Identity
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.Writer
newtype Env v = Env (Map.Map String v)
deriving (Eq, Show)
instance (Pretty v) => Pretty (Env v) where
pPrint (Env m) =
braces $ vcat prettyEnv
where prettyEnv = Map.foldlWithKey (\a k v -> nest 2 (pPrint k <+> text "=>" <+> pPrint v):a) [] m
empty :: Env v
empty = Env Map.empty
save :: String -> v -> Env v -> Env v
save k v (Env m) = Env $ Map.insert k v m
load :: String -> Env v -> Maybe v
load k (Env m) = Map.lookup k m
loadE :: String -> e -> Env v -> ReaderT y (ExceptT e Identity) v
loadE s e (Env m) =
case Map.lookup s m of
(Just v) -> return v
Nothing -> throwError e
loadES :: String -> e -> Env v -> ReaderT y (ExceptT e (WriterT [String] Identity)) v
loadES s e (Env m) =
case Map.lookup s m of
(Just v) -> return v
Nothing -> throwError e
keys :: Env v -> [String]
keys (Env m) = Map.keys m
| jgardella/nancy | src/Nancy/Core/Env.hs | mit | 1,086 | 0 | 16 | 240 | 518 | 264 | 254 | 32 | 2 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, GeneralizedNewtypeDeriving, FlexibleInstances #-}
module Database.Redis.Simple (
runRedis,
auth,
echo,
ping,
quit,
select,
del,
dump,
exists,
expire,
expireAt,
keys,
migrate,
move,
objectRefCount,
objectEncoding,
objectIdleTime,
persist,
pExpire,
pExpireAt,
pTtl,
randomKey,
rename,
renameNx,
restore,
sort,
sortStore,
ttl,
getType,
hDel,
hExists,
hGet,
hGetAll,
hIncrBy,
hIncrByFloat,
hKeys,
hLen,
hMGet,
hMSet,
hSet,
hSetNX,
hVals,
blPop,
brPop,
brPopLPush,
lIndex,
lInsertBefore,
lInsertAfter,
lLen,
lPop,
lPush,
lPushX,
lRange,
lRem,
lSet,
lTrim,
rPop,
rPopLPush,
rPush,
rPushX,
eval,
evalSha,
scriptExists,
scriptFlush,
scriptKill,
scriptLoad,
bgRewriteAof,
bgSave,
configGet,
configResetStat,
configSet,
dbSize,
debugObject,
flushAll,
flushDb,
info,
lastSave,
save,
slaveOf,
slowLogGet,
slowLogLen,
slowLogReset,
time,
sAdd,
sCard,
sDiff,
sDiffStore,
sInter,
sInterStore,
sIsMember,
sMembers,
sMove,
sPop,
sRandMember,
sRem,
sUnion,
sUnionStore,
zAdd,
zCard,
zCount,
zIncrBy,
zInterStore,
zInterStoreWeights,
zRange,
zRangeWithScores,
zRangeByScore,
zRangeByScoreWithScores,
zRangeByScoreLimit,
zRangeByScoreWithScoresLimit,
zRank,
zRem,
zRemRangeByRank,
zRemRangeByScore,
zRevRange,
zRevRangeWithScores,
zRevRangeByScore,
zRevRangeByScoreWithScores,
zRevRangeByScoreLimit,
zRevRangeByScoreWithScoresLimit,
zRevRank,
zScore,
zUnionStore,
zUnionStoreWeights,
append,
bitCount,
bitCountRange,
bitOpAnd,
bitOpOr,
bitOpXor,
bitOpNot,
decr,
decrBy,
get,
getBit,
getRange,
getSet,
incr,
incrBy,
incrByFloat,
mGet,
mSet,
mSetNx,
pSetEx,
set,
setBit,
setEx,
setNx,
setRange,
strLen,
watch,
unwatch,
multiExec,
publish,
pubSub,
sendRequest,
R.Connection,
R.ConnectInfo(..),
R.defaultConnectInfo,
R.PortID(..),
R.connect,
R.Status(..),
R.ConnectionLostException,
R.RedisResult(..),
R.Reply,
R.PubSub(..),
R.Message(..),
R.TxResult(..),
Redis(..),
RedisTx(..)
) where
import Control.Applicative
import Control.Monad.Trans
import Control.Monad.Trans.Either
import Data.ByteString (ByteString)
import qualified Database.Redis as R
class WrappedRedis m mi r | m -> mi r where
wrap :: mi (r a) -> m a
unwrap :: m a -> mi (r a)
newtype Redis a = Redis { fromRedis :: EitherT R.Reply R.Redis a }
deriving (Functor, Applicative, Monad, MonadIO)
newtype RedisTx a = RedisTx { fromRedisTx :: R.RedisTx (R.Queued a) }
instance Functor RedisTx where
fmap f m = RedisTx $ fmap (fmap f) $ fromRedisTx m
instance Applicative RedisTx where
pure = RedisTx . pure . pure
l <*> r = RedisTx $ (fromRedisTx l >>= \txl -> fromRedisTx r >>= \txr -> return $ txl <*> txr)
instance WrappedRedis Redis R.Redis (Either R.Reply) where
wrap = Redis . EitherT
unwrap = runEitherT . fromRedis
instance WrappedRedis RedisTx R.RedisTx R.Queued where
wrap = RedisTx
unwrap = fromRedisTx
runRedis :: R.Connection -> Redis a -> IO (Either R.Reply a)
runRedis conn m = R.runRedis conn $ runEitherT $ fromRedis m
auth :: ByteString -> Redis R.Status
auth = Redis . EitherT . R.auth
echo :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m ByteString
echo = wrap . R.echo
ping :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
ping = wrap R.ping
quit :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
quit = wrap R.quit
select :: (R.RedisCtx mi r, WrappedRedis m mi r) => Integer -> m R.Status
select = wrap . R.select
del :: (R.RedisCtx mi r, WrappedRedis m mi r) => [ByteString] -> m Integer
del = wrap . R.del
dump :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m ByteString
dump = wrap . R.dump
exists :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Bool
exists = wrap . R.exists
expire :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m Bool
expire k = wrap . R.expire k
expireAt :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m Bool
expireAt k = wrap . R.expireat k
keys :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m [ByteString]
keys = wrap . R.keys
migrate :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> ByteString -> Integer -> Integer -> m R.Status
migrate host port key dest timeout = wrap $ R.migrate host port key dest timeout
move :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m Bool
move k = wrap . R.move k
objectRefCount :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
objectRefCount = wrap . R.objectRefcount
objectEncoding :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m ByteString
objectEncoding = wrap . R.objectEncoding
objectIdleTime :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
objectIdleTime = wrap . R.objectIdletime
persist :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Bool
persist = wrap . R.persist
pExpire :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m Bool
pExpire k = wrap . R.pexpire k
pExpireAt :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m Bool
pExpireAt k = wrap . R.pexpireat k
pTtl :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
pTtl = wrap . R.pttl
randomKey :: (R.RedisCtx mi r, WrappedRedis m mi r) => m (Maybe ByteString)
randomKey = wrap R.randomkey
rename :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m R.Status
rename k = wrap . R.rename k
renameNx :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Bool
renameNx k = wrap . R.renamenx k
restore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> ByteString -> m R.Status
restore k t v = wrap $ R.restore k t v
sort :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> R.SortOpts -> m [ByteString]
sort k = wrap . R.sort k
sortStore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> R.SortOpts -> m Integer
sortStore k dest o = wrap $ R.sortStore k dest o
ttl :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
ttl = wrap . R.ttl
getType :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m R.RedisType
getType = wrap . R.getType
hDel :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
hDel k = wrap . R.hdel k
hExists :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Bool
hExists k = wrap . R.hexists k
hGet :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m (Maybe ByteString)
hGet k = wrap . R.hget k
hGetAll :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m [(ByteString, ByteString)]
hGetAll = wrap . R.hgetall
hIncrBy :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> Integer -> m Integer
hIncrBy k f i = wrap $ R.hincrby k f i
hIncrByFloat :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> Double -> m Double
hIncrByFloat k f i = wrap $ R.hincrbyfloat k f i
hKeys :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m [ByteString]
hKeys = wrap . R.hkeys
hLen :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
hLen = wrap . R.hlen
hMGet :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m [Maybe ByteString]
hMGet k = wrap . R.hmget k
hMSet :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [(ByteString, ByteString)] -> m R.Status
hMSet k = wrap . R.hmset k
hSet :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> ByteString -> m Bool
hSet k f v = wrap $ R.hset k f v
hSetNX :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> ByteString -> m Bool
hSetNX k f v = wrap $ R.hsetnx k f v
hVals :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m [ByteString]
hVals = wrap . R.hvals
blPop :: (R.RedisCtx mi r, WrappedRedis m mi r) => [ByteString] -> Integer -> m (Maybe (ByteString, ByteString))
blPop ks = wrap . R.blpop ks
brPop :: (R.RedisCtx mi r, WrappedRedis m mi r) => [ByteString] -> Integer -> m (Maybe (ByteString, ByteString))
brPop ks = wrap . R.brpop ks
brPopLPush :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> Integer -> m (Maybe ByteString)
brPopLPush src dest t = wrap $ R.brpoplpush src dest t
lIndex :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m (Maybe ByteString)
lIndex k = wrap . R.lindex k
lInsertBefore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> ByteString -> m Integer
lInsertBefore k p v = wrap $ R.linsertBefore k p v
lInsertAfter :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> ByteString -> m Integer
lInsertAfter k p v = wrap $ R.linsertAfter k p v
lLen :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
lLen = wrap . R.llen
lPop :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m (Maybe ByteString)
lPop = wrap . R.lpop
lPush :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
lPush k = wrap . R.lpush k
lPushX :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Integer
lPushX k = wrap . R.lpushx k
lRange :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m [ByteString]
lRange k l r = wrap $ R.lrange k l r
lRem :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> ByteString -> m Integer
lRem k c v = wrap $ R.lrem k c v
lSet :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> ByteString -> m R.Status
lSet k i v = wrap $ R.lset k i v
lTrim :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m R.Status
lTrim k l r = wrap $ R.ltrim k l r
rPop :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m (Maybe ByteString)
rPop = wrap . R.rpop
rPopLPush :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m (Maybe ByteString)
rPopLPush k = wrap . R.rpoplpush k
rPush :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
rPush k = wrap . R.rpush k
rPushX :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Integer
rPushX k = wrap . R.rpushx k
eval :: (R.RedisCtx mi r, WrappedRedis m mi r, R.RedisResult a) => ByteString -> [ByteString] -> [ByteString] -> m a
eval s ks args = wrap $ R.eval s ks args
evalSha :: (R.RedisCtx mi r, WrappedRedis m mi r, R.RedisResult a) => ByteString -> [ByteString] -> [ByteString] -> m a
evalSha s ks args = wrap $ R.evalsha s ks args
scriptExists :: (R.RedisCtx mi r, WrappedRedis m mi r) => [ByteString] -> m [Bool]
scriptExists = wrap . R.scriptExists
scriptFlush :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
scriptFlush = wrap R.scriptFlush
scriptKill :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
scriptKill = wrap R.scriptKill
scriptLoad :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m ByteString
scriptLoad = wrap . R.scriptLoad
bgRewriteAof :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
bgRewriteAof = wrap R.bgrewriteaof
bgSave :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
bgSave = wrap R.bgsave
configGet :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m [(ByteString, ByteString)]
configGet = wrap . R.configGet
configResetStat :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
configResetStat = wrap R.configResetstat
configSet :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m R.Status
configSet param val = wrap $ R.configSet param val
dbSize :: (R.RedisCtx mi r, WrappedRedis m mi r) => m Integer
dbSize = wrap R.dbsize
debugObject :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m ByteString
debugObject = wrap . R.debugObject
flushAll :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
flushAll = wrap R.flushall
flushDb :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
flushDb = wrap R.flushdb
info :: (R.RedisCtx mi r, WrappedRedis m mi r) => m ByteString
info = wrap R.info
lastSave :: (R.RedisCtx mi r, WrappedRedis m mi r) => m Integer
lastSave = wrap R.lastsave
save :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
save = wrap R.save
slaveOf :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m R.Status
slaveOf k = wrap . R.slaveof k
slowLogGet :: (R.RedisCtx mi r, WrappedRedis m mi r) => Integer -> m [R.Slowlog]
slowLogGet = wrap . R.slowlogGet
slowLogLen :: (R.RedisCtx mi r, WrappedRedis m mi r) => m Integer
slowLogLen = wrap R.slowlogLen
slowLogReset :: (R.RedisCtx mi r, WrappedRedis m mi r) => m R.Status
slowLogReset = wrap R.slowlogReset
time :: (R.RedisCtx mi r, WrappedRedis m mi r) => m (Integer, Integer)
time = wrap R.time
sAdd :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
sAdd k = wrap . R.sadd k
sCard :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
sCard = wrap . R.scard
sDiff :: (R.RedisCtx mi r, WrappedRedis m mi r) => [ByteString] -> m [ByteString]
sDiff = wrap . R.sdiff
sDiffStore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
sDiffStore k = wrap . R.sdiffstore k
sInter :: (R.RedisCtx mi r, WrappedRedis m mi r) => [ByteString] -> m [ByteString]
sInter = wrap . R.sinter
sInterStore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
sInterStore k = wrap . R.sinterstore k
sIsMember :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Bool
sIsMember k = wrap . R.sismember k
sMembers :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m [ByteString]
sMembers = wrap . R.smembers
sMove :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> ByteString -> m Bool
sMove k f t = wrap $ R.smove k f t
sPop :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m (Maybe ByteString)
sPop = wrap . R.spop
sRandMember :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m (Maybe ByteString)
sRandMember = wrap . R.srandmember
sRem :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
sRem k = wrap . R.srem k
sUnion :: (R.RedisCtx mi r, WrappedRedis m mi r) => [ByteString] -> m [ByteString]
sUnion = wrap . R.sunion
sUnionStore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
sUnionStore k = wrap . R.sunionstore k
zAdd :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [(Double, ByteString)] -> m Integer
zAdd k = wrap . R.zadd k
zCard :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
zCard = wrap . R.zcard
zCount :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> m Integer
zCount k l h = wrap $ R.zcount k l h
zIncrBy :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> ByteString -> m Double
zIncrBy k i v = wrap $ R.zincrby k i v
zInterStore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> R.Aggregate -> m Integer
zInterStore k vs a = wrap $ R.zinterstore k vs a
zInterStoreWeights :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [(ByteString, Double)] -> R.Aggregate -> m Integer
zInterStoreWeights k vws a = wrap $ R.zinterstoreWeights k vws a
zRange :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m [ByteString]
zRange k l r = wrap $ R.zrange k l r
zRangeWithScores :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m [(ByteString, Double)]
zRangeWithScores k l r = wrap $ R.zrangeWithscores k l r
zRangeByScore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> m [ByteString]
zRangeByScore k l h = wrap $ R.zrangebyscore k l h
zRangeByScoreWithScores :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> m [(ByteString, Double)]
zRangeByScoreWithScores k l h = wrap $ R.zrangebyscoreWithscores k l h
zRangeByScoreLimit :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> Integer -> Integer -> m [ByteString]
zRangeByScoreLimit k max min offset count = wrap $ R.zrangebyscoreLimit k max min offset count
zRangeByScoreWithScoresLimit :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> Integer -> Integer -> m [(ByteString, Double)]
zRangeByScoreWithScoresLimit k max min offset count = wrap $ R.zrangebyscoreWithscoresLimit k max min offset count
zRank :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m (Maybe Integer)
zRank k = wrap . R.zrank k
zRem :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
zRem k = wrap . R.zrem k
zRemRangeByRank :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m Integer
zRemRangeByRank k o c = wrap $ R.zremrangebyrank k o c
zRemRangeByScore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> m Integer
zRemRangeByScore k l h = wrap $ R.zremrangebyscore k l h
zRevRange :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m [ByteString]
zRevRange k o c = wrap $ R.zrevrange k o c
zRevRangeWithScores :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m [(ByteString, Double)]
zRevRangeWithScores k l r = wrap $ R.zrevrangeWithscores k l r
zRevRangeByScore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> m [ByteString]
zRevRangeByScore k l h = wrap $ R.zrevrangebyscore k l h
zRevRangeByScoreWithScores :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> m [(ByteString, Double)]
zRevRangeByScoreWithScores k l h = wrap $ R.zrevrangebyscoreWithscores k l h
zRevRangeByScoreLimit :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> Integer -> Integer -> m [ByteString]
zRevRangeByScoreLimit k l r o c = wrap $ R.zrevrangebyscoreLimit k l r o c
zRevRangeByScoreWithScoresLimit :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> Double -> Integer -> Integer -> m [(ByteString, Double)]
zRevRangeByScoreWithScoresLimit k l r o c = wrap $ R.zrevrangebyscoreWithscoresLimit k l r o c
zRevRank :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m (Maybe Integer)
zRevRank k = wrap . R.zrevrank k
zScore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m (Maybe Double)
zScore k = wrap . R.zscore k
zUnionStore :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> R.Aggregate -> m Integer
zUnionStore dest ks a = wrap $ R.zunionstore dest ks a
zUnionStoreWeights :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [(ByteString, Double)] -> R.Aggregate -> m Integer
zUnionStoreWeights k vws a = wrap $ R.zunionstoreWeights k vws a
append :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Integer
append k = wrap . R.append k
bitCount :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
bitCount = wrap . R.bitcount
bitCountRange :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m Integer
bitCountRange k l r = wrap $ R.bitcountRange k l r
bitOpAnd :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
bitOpAnd k = wrap . R.bitopAnd k
bitOpOr :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
bitOpOr k = wrap . R.bitopOr k
bitOpXor :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> [ByteString] -> m Integer
bitOpXor k = wrap . R.bitopXor k
bitOpNot :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Integer
bitOpNot k = wrap . R.bitopNot k
decr :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
decr = wrap . R.decr
decrBy :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m Integer
decrBy k = wrap . R.decrby k
get :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m (Maybe ByteString)
get = wrap . R.get
getBit :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m Integer
getBit k = wrap . R.getbit k
getRange :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> Integer -> m ByteString
getRange k f t = wrap $ R.getrange k f t
getSet :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m (Maybe ByteString)
getSet k v = wrap $ R.getset k v
incr :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
incr = wrap . R.incr
incrBy :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> m Integer
incrBy k = wrap . R.incrby k
incrByFloat :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Double -> m Double
incrByFloat k = wrap . R.incrbyfloat k
mGet :: (R.RedisCtx mi r, WrappedRedis m mi r) => [ByteString] -> m [Maybe ByteString]
mGet = wrap . R.mget
mSet :: (R.RedisCtx mi r, WrappedRedis m mi r) => [(ByteString, ByteString)] -> m R.Status
mSet = wrap . R.mset
mSetNx :: (R.RedisCtx mi r, WrappedRedis m mi r) => [(ByteString, ByteString)] -> m Bool
mSetNx = wrap . R.msetnx
pSetEx :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> ByteString -> m R.Status
pSetEx k t v = wrap $ R.psetex k t v
set :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m R.Status
set k v = wrap $ R.set k v
setBit :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> ByteString -> m Integer
setBit k i v = wrap $ R.setbit k i v
setEx :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> ByteString -> m R.Status
setEx k t v = wrap $ R.setex k t v
setNx :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Bool
setNx k v = wrap $ R.setnx k v
setRange :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> Integer -> ByteString -> m Integer
setRange k i v = wrap $ R.setrange k i v
strLen :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> m Integer
strLen = wrap . R.strlen
watch :: [ByteString] -> Redis R.Status
watch = wrap . R.watch
unwatch :: Redis R.Status
unwatch = wrap R.unwatch
multiExec :: RedisTx a -> Redis (R.TxResult a)
multiExec m = Redis $ EitherT $ fmap Right $ R.multiExec $ fromRedisTx m
publish :: (R.RedisCtx mi r, WrappedRedis m mi r) => ByteString -> ByteString -> m Integer
publish chan msg = wrap $ R.publish chan msg
pubSub :: R.PubSub -> (R.Message -> IO R.PubSub) -> Redis ()
pubSub p f = Redis $ EitherT $ fmap Right $ R.pubSub p f
sendRequest :: (R.RedisCtx mi r, WrappedRedis m mi r, R.RedisResult a) => [ByteString] -> m a
sendRequest = wrap . R.sendRequest
| SaneApp/hedis-simple | src/Database/Redis/Simple.hs | mit | 22,889 | 0 | 13 | 4,439 | 9,936 | 5,171 | 4,765 | 503 | 1 |
{-# language DeriveDataTypeable #-}
module Brainfuck.Syntax.Data where
import Autolib.Size
import Data.Typeable
data Statement
= Block [ Statement ]
| Plus
| Minus
| MRight
| MLeft
| Input
| Output
| Loop [ Statement ]
| Null -- kommentare und co
deriving ( Eq, Ord, Typeable )
instance Size Statement where
size s = 1 -- FIXME
| florianpilz/autotool | src/Brainfuck/Syntax/Data.hs | gpl-2.0 | 401 | 0 | 7 | 130 | 92 | 56 | 36 | 17 | 0 |
{-# LANGUAGE
FlexibleInstances
, TypeSynonymInstances
#-}
{- |
Module : ./OMDoc/XmlInterface.hs
Description : OMDoc-XML conversion
Copyright : (c) Ewaryst Schulz, DFKI 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
The transformation of the OMDoc intermediate representation to and from xml.
The import from xml does not validate the xml, hence if you encounter strange
errors, do not forget to check the xml structure first.
-}
module OMDoc.XmlInterface where
import OMDoc.DataTypes
import Common.Utils (splitBy)
import Common.Result
import Common.Percent
import Data.Maybe
import Data.List
import Control.Monad (liftM, when)
import Common.XmlParser (XmlParseable, parseXml)
import Text.XML.Light
-- * Names and other constants
-- | The implemented OMDoc version
omdoc_current_version :: String
omdoc_current_version = "1.6"
toQN :: String -> QName
toQN s = blank_name { qName = s }
toQNOM :: String -> QName
toQNOM s = blank_name { qName = s , qPrefix = Just "om" }
-- | often used element names
el_omdoc, el_theory, el_view, el_structure, el_type, el_adt, el_sortdef
, el_constructor, el_argument, el_insort, el_selector, el_open, el_component
, el_conass, el_constant, el_notation, el_text, el_definition, el_omobj
, el_ombind, el_oms, el_ombvar, el_omattr, el_omatp, el_omv, el_oma :: QName
el_omdoc = toQN "omdoc"
el_theory = toQN "theory"
el_view = toQN "view"
el_structure = toQN "structure"
el_type = toQN "type"
el_adt = toQN "adt"
el_sortdef = toQN "sortdef"
el_constructor = toQN "constructor"
el_argument = toQN "argument"
el_insort = toQN "insort"
el_selector = toQN "selector"
el_conass = toQN "conass"
el_open = toQN "open"
el_constant = toQN "constant"
el_notation = toQN "notation"
el_text = toQN "text"
el_definition = toQN "definition"
el_component = toQN "component"
el_omobj = toQN "OMOBJ"
el_ombind = toQNOM "OMBIND"
el_oms = toQNOM "OMS"
el_ombvar = toQNOM "OMBVAR"
el_omattr = toQNOM "OMATTR"
el_omatp = toQNOM "OMATP"
el_omv = toQNOM "OMV"
el_oma = toQNOM "OMA"
at_version, at_module, at_name, at_meta, at_role, at_type, at_total, at_for
, at_from, at_to, at_value, at_base, at_as, at_precedence, at_fixity, at_index
, at_associativity, at_style, at_implicit :: QName
at_version = toQN "version"
at_module = toQN "module"
at_name = toQN "name"
at_meta = toQN "meta"
at_role = toQN "role"
at_type = toQN "type"
at_total = toQN "total"
at_for = toQN "for"
at_from = toQN "from"
at_to = toQN "to"
at_value = toQN "value"
at_base = toQN "base"
at_as = toQN "as"
at_precedence = toQN "precedence"
at_fixity = toQN "fixity"
at_associativity = toQN "associativity"
at_style = toQN "style"
at_implicit = toQN "implicit"
at_index = toQN "index"
attr_om :: Attr
attr_om = Attr (blank_name { qName = "om" , qPrefix = Just "xmlns" })
"http://www.openmath.org/OpenMath"
-- * Top level from/to xml functions
{- |
This class defines the interface to read from and write to XML
-}
class XmlRepresentable a where
-- | render instance to an XML Element
toXml :: a -> Content
-- | read instance from an XML Element
fromXml :: Element -> Result (Maybe a)
{-
-- for testing the performance without the xml lib we use the show and read funs
xmlOut :: Show a => a -> String
xmlOut = show
xmlIn :: String -> Result OMDoc
xmlIn = return . read
-}
xmlOut :: XmlRepresentable a => a -> String
xmlOut obj = case toXml obj of
Elem e -> ppTopElement e
c -> ppContent c
xmlIn :: XmlParseable a => a -> IO (Result OMDoc)
xmlIn s = do
res <- parseXml s
return $ case res of
Right e -> fromXml e >>= maybe (fail "xmlIn") return
Left msg -> fail msg
listToXml :: XmlRepresentable a => [a] -> [Content]
listToXml = map toXml
listFromXml :: XmlRepresentable a => [Content] -> Result [a]
listFromXml elms = fmap catMaybes $ mapR fromXml (onlyElems elms)
mkElement :: QName -> [Attr] -> [Content] -> Content
mkElement qn atts elems = Elem $ Element qn atts elems Nothing
makeComment :: String -> Content
makeComment s = Text $ CData CDataRaw ("<!-- " ++ s ++ " -->") Nothing
inAContent :: QName -> [Attr] -> Maybe Content -> Content
inAContent qn a c = mkElement qn a $ maybeToList c
inContent :: QName -> Maybe Content -> Content
inContent qn = inAContent qn []
toOmobj :: Content -> Content
toOmobj c = inAContent el_omobj [attr_om] $ Just c
-- * Encoding/Decoding
{- url escaping and unescaping.
We use ? and / as special characters, so we need them to be encoded in names -}
urlEscape :: String -> String
urlEscape = encodeBut (`notElem` "%/?")
urlUnescape :: String -> String
urlUnescape = decode
-- to- and from-string functions
showCDName :: OMCD -> OMName -> String
showCDName omcd omname = concat [showCD omcd, "?", showOMName omname]
showCD :: OMCD -> String
showCD cd = let [x, y] = cdToList cd
in concat [x, "?", y]
showOMName :: OMName -> String
showOMName on = intercalate "/" $ path on ++ [name on]
readCD :: Show a => a -> String -> OMCD
readCD _ s = case splitBy '?' s of
[b, cd] -> cdFromList [b, cd]
_ -> error $ "readCD: The value " ++
"has to contain exactly one '?'"
readCDName :: String -> OMQualName
readCDName s = case splitBy '?' s of
(b : cd : n : []) -> ( cdFromList [b, cd]
, readOMName n)
_ -> error $ "readCDName: The value " ++
"has to contain exactly two '?'"
readOMName :: String -> OMName
readOMName s = let l = splitBy '/' s
in OMName (last l) $ init l
-- encoding
{- only uri-fields need to be %-encoded, the following attribs are uri-fields:
theory@meta
include@from
structure@from
view@from
view@to
@base
-}
tripleEncodeOMS :: OMCD -> OMName -> [Attr]
tripleEncodeOMS omcd omname
= pairEncodeCD omcd ++ [Attr at_name $ showOMName omname]
pairEncodeCD :: OMCD -> [Attr]
pairEncodeCD cd = let [base, modl] = cdToMaybeList cd
in catMaybes [ fmap (Attr at_base . urlEscape) base
, fmap (Attr at_module) modl]
-- decoding
tripleDecodeOMS :: String -> String -> String -> (OMCD, OMName)
tripleDecodeOMS cd base nm =
let cdl = filter (not . null) [cd, urlUnescape base]
in if null cd && not (null base)
then error "tripleDecodeOMS: base not empty but cd not given!"
else (CD cdl, readOMName nm)
warnIfNothing :: String -> (Maybe a -> b) -> Maybe a -> Result b
warnIfNothing s f v = do
warnIf s $ isNothing v
return $ f v
warnIf :: String -> Bool -> Result ()
warnIf s b = when b $ justWarn () s
elemIsOf :: Element -> QName -> Bool
elemIsOf e qn = let en = elName e in
(qName en, qPrefix en) == (qName qn, qPrefix qn)
oneOfMsg :: Element -> [QName] -> String
oneOfMsg e l = let printName = qName in
concat [ "Couldn't find expected element {"
, intercalate ", " (map printName l), "}"
, maybe "" ((" at line " ++) . show) (elLine e)
, " but found ", printName $ elName e, "."
]
-- * Monad and Maybe interaction
justReturn :: Monad m => a -> m (Maybe a)
justReturn = return . Just
fmapMaybe :: Monad m => (a -> m b) -> Maybe a -> m (Maybe b)
fmapMaybe f v = encapsMaybe $ fmap f v
fmapFromMaybe :: Monad m => (a -> m (Maybe b)) -> Maybe a -> m (Maybe b)
fmapFromMaybe f = flattenMaybe . fmapMaybe f
encapsMaybe :: Monad m => Maybe (m a) -> m (Maybe a)
encapsMaybe v = case v of
Just x -> x >>= justReturn
_ -> return Nothing
flattenMaybe :: Monad m => m (Maybe (Maybe a)) -> m (Maybe a)
flattenMaybe = liftM (fromMaybe Nothing)
{- | Function to extract the Just values from maybes with a default missing
error in case of Nothing -}
missingMaybe :: String -> String -> Maybe a -> a
missingMaybe el misses =
fromMaybe (error $ el ++ " element must have a " ++ misses ++ ".")
-- -- -- -- -- XmlRepresentable Class instances for OMDoc types -- -- -- -- --
-- | The root instance for representing OMDoc in XML
instance XmlRepresentable OMDoc where
toXml (OMDoc omname elms) =
mkElement
el_omdoc [Attr at_version omdoc_current_version, Attr at_name omname]
$ listToXml elms
fromXml e
| elemIsOf e el_omdoc =
do
nm <- warnIfNothing "No name in omdoc element." (fromMaybe "")
$ findAttr at_name e
vs <- warnIfNothing "No version in omdoc element."
(fromMaybe "1.6") $ findAttr at_version e
warnIf "Wrong OMDoc version." $ vs /= omdoc_current_version
tls <- listFromXml $ elContent e
justReturn $ OMDoc nm tls
| otherwise = fail "OMDoc fromXml: toplevel element is no omdoc."
-- | toplevel OMDoc elements to XML and back
instance XmlRepresentable TLElement where
toXml (TLTheory tname meta elms) =
mkElement
el_theory (Attr at_name tname : case meta of
Nothing -> []
Just mtcd -> [Attr at_meta $ urlEscape $ showCD mtcd])
$ listToXml elms
toXml (TLView nm from to morph) =
mkElement
el_view [Attr at_name nm, Attr at_from $ urlEscape $ showCD from,
Attr at_to $ urlEscape $ showCD to]
$ map assignmentToXml morph
fromXml e
| elemIsOf e el_theory =
let nm = missingMaybe "Theory" "name" $ findAttr at_name e
mt = fmap (readCD (elLine e) . urlUnescape) $ findAttr at_meta e
in do
tcl <- listFromXml $ elContent e
justReturn $ TLTheory nm mt tcl
| elemIsOf e el_view =
let musthave at s = missingMaybe "View" s $ findAttr at e
nm = musthave at_name "name"
from = readCD (elLine e) $ urlUnescape $ musthave at_from "from"
to = readCD (elLine e) $ urlUnescape $ musthave at_to "to"
in do
morph <- mapR xmlToAssignment (findChildren el_conass e)
justReturn $ TLView nm from to morph
| otherwise = return Nothing
-- | theory constitutive OMDoc elements to XML and back
instance XmlRepresentable TCElement where
toXml (TCSymbol sname symtype role defn) =
constantToXml sname (show role) symtype defn
toXml (TCNotation (cd, nm) val mStl) =
inAContent
el_notation
( [Attr at_for $ urlEscape $ showCDName cd nm, Attr at_role "constant"]
++ maybe [] ((: []) . Attr at_style) mStl )
$ Just $ inAContent el_text [Attr at_value val] Nothing
toXml (TCSmartNotation (cd, nm) fixity assoc prec implicit) =
inAContent
el_notation
( [ Attr at_for $ urlEscape $ showCDName cd nm
, Attr at_role "application", Attr at_fixity $ show fixity
, Attr at_precedence $ show prec ]
++ (if implicit == 0 then [] else [Attr at_implicit $ show implicit])
++ (if assoc == NoneAssoc then [] else [Attr at_associativity
$ show assoc]) )
Nothing
toXml (TCFlexibleNotation (cd, nm) prec comps) =
mkElement
el_notation
[ Attr at_for $ urlEscape $ showCDName cd nm, Attr at_role "application"
, Attr at_precedence $ show prec ] $ map notationComponentToXml comps
toXml (TCADT sds) = mkElement el_adt [] $ listToXml sds
toXml (TCComment c) = makeComment c
toXml (TCImport nm from morph) =
mkElement
el_structure [Attr at_name nm, Attr at_from $ urlEscape $ showCD from]
$ map assignmentToXml morph
fromXml e
| elemIsOf e el_constant =
let musthave = missingMaybe "Constant"
nm = musthave "name" $ findAttr at_name e
role = maybe Obj read $ findAttr at_role e
in do
typ <- fmap (musthave "typ") $ omelementFrom el_type e
defn <- omelementFrom el_definition e
justReturn $ TCSymbol nm typ role defn
| elemIsOf e el_notation =
let musthave = missingMaybe "Notation"
nm = urlUnescape $ musthave "for" $ findAttr at_for e
role = musthave "role" $ findAttr at_role e
mStl = findAttr at_style e
text = musthave "text" $ findChild el_text e
val = musthave "value" $ findAttr at_value text
in if role == "constant"
then justReturn $ TCNotation (readCDName nm) val mStl
else return Nothing
| elemIsOf e el_structure =
let musthave at s = missingMaybe "Structure" s $ findAttr at e
nm = musthave at_name "name"
from = readCD (elLine e) $ urlUnescape $ musthave at_from "from"
in do
morph <- mapR xmlToAssignment
$ filterChildrenName (`elem` [el_conass, el_open]) e
justReturn $ TCImport nm from morph
| elemIsOf e el_adt =
do
sds <- listFromXml $ elContent e
justReturn $ TCADT sds
| otherwise =
fail $ oneOfMsg e [el_constant, el_structure, el_adt, el_notation]
-- | OMDoc - Algebraic Data Types
instance XmlRepresentable OmdADT where
toXml (ADTSortDef n b cs) =
mkElement el_sortdef
[Attr at_name n, Attr at_type $ show b]
$ listToXml cs
toXml (ADTConstr n args) =
mkElement el_constructor [Attr at_name n] $ listToXml args
toXml (ADTArg t sel) =
mkElement el_argument [] $ typeToXml t : case sel of
Nothing -> []
Just s -> [toXml s]
toXml (ADTSelector n total) =
mkElement el_selector [Attr at_name n, Attr at_total $ show total] []
toXml (ADTInsort (d, n)) =
mkElement el_insort [Attr at_for $ showCDName d n] []
fromXml e
| elemIsOf e el_sortdef =
let musthave s at = missingMaybe "Sortdef" s $ findAttr at e
nm = musthave "name" at_name
typ = read $ musthave "type" at_type
in do
entries <- listFromXml $ elContent e
justReturn $ ADTSortDef nm typ entries
| elemIsOf e el_constructor =
do
let nm = missingMaybe "Constructor" "name" $ findAttr at_name e
entries <- listFromXml $ elContent e
justReturn $ ADTConstr nm entries
| elemIsOf e el_argument =
do
typ <- fmap (missingMaybe "Argument" "typ")
$ omelementFrom el_type e
sel <- fmapFromMaybe fromXml $ findChild el_selector e
justReturn $ ADTArg typ sel
| elemIsOf e el_selector =
let musthave s at = missingMaybe "Selector" s $ findAttr at e
nm = musthave "name" at_name
total = read $ musthave "total" at_total
in justReturn $ ADTSelector nm total
| elemIsOf e el_insort =
do
let nm = missingMaybe "Insort" "for" $ findAttr at_for e
justReturn $ ADTInsort $ readCDName nm
| otherwise =
fail $ oneOfMsg e [ el_sortdef, el_constructor, el_argument
, el_selector, el_insort]
-- | OpenMath elements to XML and back
instance XmlRepresentable OMElement where
toXml (OMS (d, n)) = mkElement el_oms (tripleEncodeOMS d n) []
toXml (OMV n) = mkElement el_omv [Attr at_name (name n)] []
toXml (OMATTT elm attr) = mkElement el_omattr [] [toXml attr, toXml elm]
toXml (OMA args) = mkElement el_oma [] $ listToXml args
toXml (OMBIND symb vars body) =
mkElement el_ombind []
[ toXml symb
, mkElement el_ombvar [] $ listToXml vars
, toXml body]
fromXml e
| elemIsOf e el_oms =
let nm = missingMaybe "OMS" "name" $ findAttr at_name e
omcd = fromMaybe "" $ findAttr at_module e
cdb = fromMaybe "" $ findAttr at_base e
in justReturn $ OMS $ tripleDecodeOMS omcd cdb nm
| elemIsOf e el_omv =
let nm = missingMaybe "OMV" "name" $ findAttr at_name e
in justReturn $ OMV $ readOMName nm
| elemIsOf e el_omattr =
let [atp, el] = elChildren e
musthave = missingMaybe "OMATTR"
in do
atp' <- fromXml atp
el' <- fromXml el
justReturn $ OMATTT (musthave "attributed value" el')
(musthave "attribution" atp')
| elemIsOf e el_oma =
do
entries <- listFromXml $ elContent e
justReturn $ OMA entries
| elemIsOf e el_ombind =
let [bd, bvar, body] = elChildren e
musthave = missingMaybe "OMBIND"
in do
bd' <- fromXml bd
bvar' <- listFromXml $ elContent bvar
body' <- fromXml body
justReturn $ OMBIND (musthave "binder" bd') bvar'
(musthave "body" body')
| otherwise =
fail $ oneOfMsg e [el_oms, el_omv, el_omattr, el_oma, el_ombind]
-- | Helper instance for OpenMath attributes
instance XmlRepresentable OMAttribute where
toXml (OMAttr e1 e2) = mkElement el_omatp [] [toXml e1, toXml e2]
fromXml e
| elemIsOf e el_omatp =
do
[key, val] <- listFromXml $ elContent e
justReturn $ OMAttr key val
| otherwise =
fail $ oneOfMsg e [el_omatp]
-- * fromXml methods
{- | If the child element with given name contains an OMOBJ xml element,
this is transformed to an OMElement. -}
omelementFrom :: QName -> Element -> Result (Maybe OMElement)
omelementFrom qn e = fmapFromMaybe omelementFromOmobj $ findChild qn e
omelementFromOmobj :: Element -> Result (Maybe OMElement)
omelementFromOmobj e = fmapMaybe omobjToOMElement $ findChild el_omobj e
-- | Get an OMElement from an OMOBJ xml element
omobjToOMElement :: Element -> Result OMElement
omobjToOMElement e = case elChildren e of
[om] ->
do
omelem <- fromXml om
case omelem of
Nothing -> fail
$ "omobjToOMElement: " ++
"No OpenMath element found."
Just x -> return x
_ -> fail "OMOBJ element must have a unique child."
-- | The input is assumed to be a conass element
xmlToAssignment :: Element -> Result (OMName, OMImage)
xmlToAssignment e
| elName e == el_open =
let musthave = missingMaybe "Open"
nm = musthave "name" $ findAttr at_name e
alias = musthave "as" $ findAttr at_as e
in return (readOMName nm, Left alias)
| elName e == el_conass =
let musthave = missingMaybe "Conass"
nm = musthave "name" $ findAttr at_name e
in do
omel <- omelementFromOmobj e
return (readOMName nm, Right $ musthave "OMOBJ element" omel)
| otherwise = fail $ oneOfMsg e [el_conass, el_open]
-- * toXml methods
typeToXml :: OMElement -> Content
typeToXml t = inContent el_type $ Just $ toOmobj $ toXml t
assignmentToXml :: (OMName, OMImage) -> Content
assignmentToXml (from, to) =
case to of
Left s ->
mkElement el_open [Attr at_name $ showOMName from, Attr at_as s] []
Right obj ->
inAContent el_conass [Attr at_name $ showOMName from]
$ Just . toOmobj . toXml $ obj
constantToXml :: String -> String -> OMElement -> Maybe OMElement -> Content
constantToXml n r tp prf =
Elem $ Element el_constant
[Attr at_name n, Attr at_role r]
(typeToXml tp
: map (inContent el_definition . Just . toOmobj . toXml)
(maybeToList prf))
Nothing
notationComponentToXml :: NotationComponent -> Content
notationComponentToXml (TextComp val) = mkElement el_text [Attr at_value val] []
notationComponentToXml (ArgComp ind prec) =
mkElement el_component [ Attr at_index $ show ind
, Attr at_precedence $ show prec] []
| spechub/Hets | OMDoc/XmlInterface.hs | gpl-2.0 | 20,517 | 0 | 17 | 6,345 | 5,986 | 2,951 | 3,035 | 425 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE Rank2Types #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Config.Simple
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- A simplified configuration interface for Yi.
--
-- This module provides a simple configuration API, allowing users to
-- start with an initial configuration and imperatively (monadically)
-- modify it. Some common actions (keybindings, selecting modes,
-- choosing the frontend) have been given special commands
-- ('globalBindKeys', 'setFrontendPreferences', 'addMode', and so on).
--
-- A simple configuration might look like the following:
--
-- @
-- import Yi.Config.Simple
-- import qualified Yi.Mode.Haskell as Haskell
-- -- note: don't import "Yi", or else there will be name clashes
--
-- main = 'configMain' 'defaultEmacsConfig' $ do
-- 'fontSize' '%=' 'Just' 10
-- 'modeBindKeys' Haskell.cleverMode ('metaCh' \'q\' '?>>!' 'reload')
-- 'globalBindKeys' ('metaCh' \'r\' '?>>!' 'reload')
-- @
--
-- A lot of the fields here are specified with the 'Field' type. To write
-- a field, use ('%='). To read, use 'get'. For modification, use
-- ('modify'). For example, the functions @foo@ and @bar@ are equivalent:
--
-- @
-- foo = 'modify' 'layoutManagers' 'reverse'
-- bar = do
-- lms <- 'get' 'layoutManagers'
-- 'layoutManagers' '%=' 'reverse' lms
-- @
module Yi.Config.Simple (
-- * The main interface
ConfigM,
configMain,
Field,
-- * Modes, commands, and keybindings
globalBindKeys,
modeBindKeys,
modeBindKeysByName,
addMode,
modifyMode,
modifyModeByName,
-- * Evaluation of commands
evaluator,
#ifdef HINT
ghciEvaluator,
#endif
publishedActionsEvaluator,
publishAction,
publishedActions,
-- * Appearance
fontName,
fontSize,
scrollWheelAmount,
scrollStyle,
ScrollStyle(..),
cursorStyle,
CursorStyle(..),
Side(..),
scrollBarSide,
autoHideScrollBar,
autoHideTabBar,
lineWrap,
windowFill,
theme,
-- ** Layout
layoutManagers,
-- * Debugging
debug,
-- * Startup hooks
runOnStartup,
runAfterStartup,
-- * Advanced
-- $advanced
startActions,
initialActions,
defaultKm,
inputPreprocess,
modes,
regionStyle,
killringAccumulate,
bufferUpdateHandler,
-- * Module exports
-- we can't just export 'module Yi', because then we would get
-- clashes with Yi.Config
module Yi.Boot,
module Yi.Buffer,
module Yi.Core,
module Yi.Dired,
module Yi.Editor,
module Yi.File,
module Yi.Config,
module Yi.Config.Default,
module Yi.Keymap,
module Yi.Keymap.Keys,
module Yi.Layout,
module Yi.Search,
module Yi.Style,
module Yi.Style.Library,
module Yi.Misc,
) where
import Lens.Micro.Platform (Lens', (.=), (%=), (%~), use, lens)
import Control.Monad.State hiding (modify, get)
import Data.Maybe(mapMaybe)
import qualified Data.Text as T
import Text.Printf(printf)
import Yi.Boot
import Yi.Buffer hiding (modifyMode)
import Yi.Config.Default
import Yi.Config.Misc
import Yi.Config.Simple.Types
import Yi.Core
import Yi.Dired
import Yi.Editor
import Yi.Eval
import Yi.File
import Yi.Keymap
import Yi.Keymap.Keys
import Yi.Layout
import Yi.Misc
import Yi.Search
import Yi.Style
import Yi.Style.Library
import Yi.Utils
-- we do explicit imports because we reuse a lot of the names
import Yi.Config(Config, UIConfig, startFrontEndA, configUIA,
startActionsA, initialActionsA, defaultKmA,
configInputPreprocessA, modeTableA, debugModeA,
configRegionStyleA, configKillringAccumulateA,
bufferUpdateHandlerA, configFontNameA,
configFontSizeA, configScrollWheelAmountA,
configScrollStyleA, configCursorStyleA,
CursorStyle(..), configLeftSideScrollBarA,
configAutoHideScrollBarA, configAutoHideTabBarA,
configLineWrapA, configWindowFillA, configThemeA,
layoutManagersA, configVarsA,
)
--------------- Main interface
-- newtype ConfigM a (imported)
-- | Starts with the given initial config, makes the described
-- modifications, then starts yi.
configMain :: Config -> ConfigM () -> IO ()
configMain c m = yi =<< execStateT (runConfigM m) c
------------------------- Modes, commands, and keybindings
-- | Adds the given key bindings to the `global keymap'. The bindings
-- will override existing bindings in the case of a clash.
globalBindKeys :: Keymap -> ConfigM ()
globalBindKeys a = (defaultKmA . topKeymapA) %= (||> a)
-- | @modeBindKeys mode keys@ adds the keybindings in @keys@ to all
-- modes with the same name as @mode@.
--
-- As with 'modifyMode', a mode by the given name must already be
-- registered, or the function will have no effect, and issue a
-- command-line warning.
modeBindKeys :: Mode syntax -> Keymap -> ConfigM ()
modeBindKeys mode keys =
ensureModeRegistered "modeBindKeys" (modeName mode) boundKeys
where
boundKeys = modeBindKeysByName (modeName mode) keys
-- | @modeBindKeysByName name keys@ adds the keybindings in @keys@ to
-- all modes with name @name@ (if it is registered). Consider using
-- 'modeBindKeys' instead.
modeBindKeysByName :: T.Text -> Keymap -> ConfigM ()
modeBindKeysByName name k =
ensureModeRegistered "modeBindKeysByName" name modMode
where
f :: (KeymapSet -> KeymapSet) -> KeymapSet -> KeymapSet
f mkm km = topKeymapA %~ (||> k) $ mkm km
modMode = modifyModeByName name (modeKeymapA %~ f)
-- | Register the given mode. It will be preferred over any modes
-- already defined.
addMode :: Mode syntax -> ConfigM ()
addMode m = modeTableA %= (AnyMode m :)
-- | @modifyMode mode f@ modifies all modes with the same name as
-- @mode@, using the function @f@.
--
-- Note that the @mode@ argument is only used by its 'modeName'. In
-- particular, a mode by the given name must already be registered, or
-- this function will have no effect, and issue a command-line
-- warning.
--
-- @'modifyMode' mode f = 'modifyModeByName' ('modeName' mode) f@
modifyMode :: Mode syntax
-> (forall syntax'. Mode syntax' -> Mode syntax')
-> ConfigM ()
modifyMode mode f = ensureModeRegistered "modifyMode" (modeName mode) modMode
where
modMode = modifyModeByName (modeName mode) f
-- | @modifyModeByName name f@ modifies the mode with name @name@
-- using the function @f@. Consider using 'modifyMode' instead.
modifyModeByName :: T.Text
-> (forall syntax. Mode syntax -> Mode syntax)
-> ConfigM ()
modifyModeByName name f =
ensureModeRegistered "modifyModeByName" name $ modeTableA %= fmap (onMode g)
where
g :: forall syntax. Mode syntax -> Mode syntax
g m | modeName m == name = f m
| otherwise = m
-- helper functions
warn :: String -> String -> ConfigM ()
warn caller msg = io $ putStrLn $ printf "Warning: %s: %s" caller msg
-- the putStrLn shouldn't be necessary, but it doesn't print anything
-- if it's not there...
isModeRegistered :: T.Text -> ConfigM Bool
isModeRegistered name =
any (\(AnyMode mode) -> modeName mode == name) <$> use modeTableA
-- ensure the given mode is registered, and if it is, then run the given action.
ensureModeRegistered :: String -> T.Text -> ConfigM () -> ConfigM ()
ensureModeRegistered caller name m = do
isRegistered <- isModeRegistered name
if isRegistered
then m
else warn caller (printf "mode \"%s\" is not registered." (T.unpack name))
--------------------- Appearance
-- | 'Just' the font name, or 'Nothing' for default.
fontName :: Field (Maybe String)
fontName = configUIA . configFontNameA
-- | 'Just' the font size, or 'Nothing' for default.
fontSize :: Field (Maybe Int)
fontSize = configUIA . configFontSizeA
-- | Amount to move the buffer when using the scroll wheel.
scrollWheelAmount :: Field Int
scrollWheelAmount = configUIA . configScrollWheelAmountA
-- | 'Just' the scroll style, or 'Nothing' for default.
scrollStyle :: Field (Maybe ScrollStyle)
scrollStyle = configUIA . configScrollStyleA
-- | See 'CursorStyle' for documentation.
cursorStyle :: Field CursorStyle
cursorStyle = configUIA . configCursorStyleA
data Side = LeftSide | RightSide
-- | Which side to display the scroll bar on.
scrollBarSide :: Field Side
scrollBarSide = configUIA . configLeftSideScrollBarA . fromBool
where
fromBool :: Lens' Bool Side
fromBool = lens (\b -> if b then LeftSide else RightSide)
(\_ s -> case s of { LeftSide -> True; RightSide -> False })
-- | Should the scroll bar autohide?
autoHideScrollBar :: Field Bool
autoHideScrollBar = configUIA . configAutoHideScrollBarA
-- | Should the tab bar autohide?
autoHideTabBar :: Field Bool
autoHideTabBar = configUIA . configAutoHideTabBarA
-- | Should lines be wrapped?
lineWrap :: Field Bool
lineWrap = configUIA . configLineWrapA
-- | The character with which to fill empty window space. Usually
-- \'~\' for vi-like editors, \' \' for everything else.
windowFill :: Field Char
windowFill = configUIA . configWindowFillA
-- | UI colour theme.
theme :: Field Theme
theme = configUIA . configThemeA
---------- Layout
-- | List of registered layout managers. When cycling through layouts,
-- this list will be consulted.
layoutManagers :: Field [AnyLayoutManager]
layoutManagers = layoutManagersA
------------------------ Debugging
-- | Produce a .yi.dbg file with debugging information?
debug :: Field Bool
debug = debugModeA
----------- Startup hooks
-- | Run when the editor is started (this is run after all actions
-- which have already been registered)
runOnStartup :: Action -> ConfigM ()
runOnStartup action = runManyOnStartup [action]
-- | List version of 'runOnStartup'.
runManyOnStartup :: [Action] -> ConfigM ()
runManyOnStartup actions = startActions %= (++ actions)
-- | Run after the startup actions have completed, or on reload (this
-- is run after all actions which have already been registered)
runAfterStartup :: Action -> ConfigM ()
runAfterStartup action = runManyAfterStartup [action]
-- | List version of 'runAfterStartup'.
runManyAfterStartup :: [Action] -> ConfigM ()
runManyAfterStartup actions = initialActions %= (++ actions)
------------------------ Advanced
{- $advanced
These fields are here for completeness -- that is, to expose all the
functionality of the "Yi.Config" module. However, most users probably
need not use these fields, typically because they provide advanced
functinality, or because a simpler interface for the common case is
available above.
-}
-- | Actions to run when the editor is started. Consider using
-- 'runOnStartup' or 'runManyOnStartup' instead.
startActions :: Field [Action]
startActions = startActionsA
-- | Actions to run after startup or reload. Consider using
-- 'runAfterStartup' or 'runManyAfterStartup' instead.
initialActions :: Field [Action]
initialActions = initialActionsA
-- | Default keymap to use.
defaultKm :: Field KeymapSet
defaultKm = defaultKmA
-- | ?
inputPreprocess :: Field (P Event Event)
inputPreprocess = configInputPreprocessA
-- | List of modes by order of preference. Consider using 'addMode',
-- 'modeBindKeys', or 'modifyMode' instead.
modes :: Field [AnyMode]
modes = modeTableA
-- | Set to 'Exclusive' for an emacs-like behaviour. Consider starting
-- with 'defaultEmacsConfig', 'defaultVimConfig', or
-- 'defaultCuaConfig' to instead.
regionStyle :: Field RegionStyle
regionStyle = configRegionStyleA
-- | Set to 'True' for an emacs-like behaviour, where all deleted text
-- is accumulated in a killring. Consider starting with
-- 'defaultEmacsConfig', 'defaultVimConfig', or 'defaultCuaConfig'
-- instead.
killringAccumulate :: Field Bool
killringAccumulate = configKillringAccumulateA
-- | ?
bufferUpdateHandler :: Field [[Update] -> BufferM ()]
bufferUpdateHandler = bufferUpdateHandlerA
| siddhanathan/yi | yi-core/src/Yi/Config/Simple.hs | gpl-2.0 | 12,302 | 0 | 13 | 2,545 | 1,879 | 1,105 | 774 | 187 | 3 |
{-# LANGUAGE OverloadedStrings #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ELB.Types
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.ELB.Types
(
-- * Service Configuration
eLB
-- * Errors
, _PolicyNotFoundException
, _AccessPointNotFoundException
, _DuplicatePolicyNameException
, _InvalidConfigurationRequestException
, _SubnetNotFoundException
, _LoadBalancerAttributeNotFoundException
, _InvalidSubnetException
, _DuplicateTagKeysException
, _DuplicateListenerException
, _TooManyTagsException
, _PolicyTypeNotFoundException
, _DuplicateAccessPointNameException
, _InvalidSecurityGroupException
, _ListenerNotFoundException
, _InvalidEndPointException
, _InvalidSchemeException
, _TooManyAccessPointsException
, _TooManyPoliciesException
, _CertificateNotFoundException
-- * AccessLog
, AccessLog
, accessLog
, alEmitInterval
, alS3BucketPrefix
, alS3BucketName
, alEnabled
-- * AdditionalAttribute
, AdditionalAttribute
, additionalAttribute
, aaValue
, aaKey
-- * AppCookieStickinessPolicy
, AppCookieStickinessPolicy
, appCookieStickinessPolicy
, acspPolicyName
, acspCookieName
-- * BackendServerDescription
, BackendServerDescription
, backendServerDescription
, bsdPolicyNames
, bsdInstancePort
-- * ConnectionDraining
, ConnectionDraining
, connectionDraining
, cdTimeout
, cdEnabled
-- * ConnectionSettings
, ConnectionSettings
, connectionSettings
, csIdleTimeout
-- * CrossZoneLoadBalancing
, CrossZoneLoadBalancing
, crossZoneLoadBalancing
, czlbEnabled
-- * HealthCheck
, HealthCheck
, healthCheck
, hcTarget
, hcInterval
, hcTimeout
, hcUnhealthyThreshold
, hcHealthyThreshold
-- * Instance
, Instance
, instance'
, iInstanceId
-- * InstanceState
, InstanceState
, instanceState
, isInstanceId
, isState
, isReasonCode
, isDescription
-- * LBCookieStickinessPolicy
, LBCookieStickinessPolicy
, lBCookieStickinessPolicy
, lbcspPolicyName
, lbcspCookieExpirationPeriod
-- * Listener
, Listener
, listener
, lInstanceProtocol
, lSSLCertificateId
, lProtocol
, lLoadBalancerPort
, lInstancePort
-- * ListenerDescription
, ListenerDescription
, listenerDescription
, ldPolicyNames
, ldListener
-- * LoadBalancerAttributes
, LoadBalancerAttributes
, loadBalancerAttributes
, lbaCrossZoneLoadBalancing
, lbaAccessLog
, lbaAdditionalAttributes
, lbaConnectionSettings
, lbaConnectionDraining
-- * LoadBalancerDescription
, LoadBalancerDescription
, loadBalancerDescription
, lbdSourceSecurityGroup
, lbdCanonicalHostedZoneName
, lbdSecurityGroups
, lbdHealthCheck
, lbdLoadBalancerName
, lbdCreatedTime
, lbdVPCId
, lbdSubnets
, lbdAvailabilityZones
, lbdBackendServerDescriptions
, lbdCanonicalHostedZoneNameId
, lbdInstances
, lbdScheme
, lbdListenerDescriptions
, lbdDNSName
, lbdPolicies
-- * Policies
, Policies
, policies
, pOtherPolicies
, pLBCookieStickinessPolicies
, pAppCookieStickinessPolicies
-- * PolicyAttribute
, PolicyAttribute
, policyAttribute
, paAttributeValue
, paAttributeName
-- * PolicyAttributeDescription
, PolicyAttributeDescription
, policyAttributeDescription
, padAttributeValue
, padAttributeName
-- * PolicyAttributeTypeDescription
, PolicyAttributeTypeDescription
, policyAttributeTypeDescription
, patdAttributeType
, patdCardinality
, patdDefaultValue
, patdAttributeName
, patdDescription
-- * PolicyDescription
, PolicyDescription
, policyDescription
, pdPolicyName
, pdPolicyAttributeDescriptions
, pdPolicyTypeName
-- * PolicyTypeDescription
, PolicyTypeDescription
, policyTypeDescription
, ptdPolicyTypeName
, ptdDescription
, ptdPolicyAttributeTypeDescriptions
-- * SourceSecurityGroup
, SourceSecurityGroup
, sourceSecurityGroup
, ssgOwnerAlias
, ssgGroupName
-- * Tag
, Tag
, tag
, tagValue
, tagKey
-- * TagDescription
, TagDescription
, tagDescription
, tdLoadBalancerName
, tdTags
-- * TagKeyOnly
, TagKeyOnly
, tagKeyOnly
, tkoKey
) where
import Network.AWS.ELB.Types.Product
import Network.AWS.ELB.Types.Sum
import Network.AWS.Prelude
import Network.AWS.Sign.V4
-- | API version '2012-06-01' of the Amazon Elastic Load Balancing SDK configuration.
eLB :: Service
eLB =
Service
{ _svcAbbrev = "ELB"
, _svcSigner = v4
, _svcPrefix = "elasticloadbalancing"
, _svcVersion = "2012-06-01"
, _svcEndpoint = defaultEndpoint eLB
, _svcTimeout = Just 70
, _svcCheck = statusSuccess
, _svcError = parseXMLError
, _svcRetry = retry
}
where
retry =
Exponential
{ _retryBase = 5.0e-2
, _retryGrowth = 2
, _retryAttempts = 5
, _retryCheck = check
}
check e
| has (hasCode "ThrottlingException" . hasStatus 400) e =
Just "throttling_exception"
| has (hasCode "Throttling" . hasStatus 400) e = Just "throttling"
| has (hasStatus 503) e = Just "service_unavailable"
| has (hasStatus 500) e = Just "general_server_error"
| has (hasStatus 509) e = Just "limit_exceeded"
| otherwise = Nothing
-- | One or more of the specified policies do not exist.
_PolicyNotFoundException :: AsError a => Getting (First ServiceError) a ServiceError
_PolicyNotFoundException =
_ServiceError . hasStatus 400 . hasCode "PolicyNotFound"
-- | The specified load balancer does not exist.
_AccessPointNotFoundException :: AsError a => Getting (First ServiceError) a ServiceError
_AccessPointNotFoundException =
_ServiceError . hasStatus 400 . hasCode "LoadBalancerNotFound"
-- | A policy with the specified name already exists for this load balancer.
_DuplicatePolicyNameException :: AsError a => Getting (First ServiceError) a ServiceError
_DuplicatePolicyNameException =
_ServiceError . hasStatus 400 . hasCode "DuplicatePolicyName"
-- | The requested configuration change is not valid.
_InvalidConfigurationRequestException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidConfigurationRequestException =
_ServiceError . hasStatus 409 . hasCode "InvalidConfigurationRequest"
-- | One or more of the specified subnets do not exist.
_SubnetNotFoundException :: AsError a => Getting (First ServiceError) a ServiceError
_SubnetNotFoundException =
_ServiceError . hasStatus 400 . hasCode "SubnetNotFound"
-- | The specified load balancer attribute does not exist.
_LoadBalancerAttributeNotFoundException :: AsError a => Getting (First ServiceError) a ServiceError
_LoadBalancerAttributeNotFoundException =
_ServiceError . hasStatus 400 . hasCode "LoadBalancerAttributeNotFound"
-- | The specified VPC has no associated Internet gateway.
_InvalidSubnetException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidSubnetException =
_ServiceError . hasStatus 400 . hasCode "InvalidSubnet"
-- | A tag key was specified more than once.
_DuplicateTagKeysException :: AsError a => Getting (First ServiceError) a ServiceError
_DuplicateTagKeysException =
_ServiceError . hasStatus 400 . hasCode "DuplicateTagKeys"
-- | A listener already exists for the specified 'LoadBalancerName' and
-- 'LoadBalancerPort', but with a different 'InstancePort', 'Protocol', or
-- 'SSLCertificateId'.
_DuplicateListenerException :: AsError a => Getting (First ServiceError) a ServiceError
_DuplicateListenerException =
_ServiceError . hasStatus 400 . hasCode "DuplicateListener"
-- | The quota for the number of tags that can be assigned to a load balancer
-- has been reached.
_TooManyTagsException :: AsError a => Getting (First ServiceError) a ServiceError
_TooManyTagsException = _ServiceError . hasStatus 400 . hasCode "TooManyTags"
-- | One or more of the specified policy types do not exist.
_PolicyTypeNotFoundException :: AsError a => Getting (First ServiceError) a ServiceError
_PolicyTypeNotFoundException =
_ServiceError . hasStatus 400 . hasCode "PolicyTypeNotFound"
-- | The specified load balancer name already exists for this account.
_DuplicateAccessPointNameException :: AsError a => Getting (First ServiceError) a ServiceError
_DuplicateAccessPointNameException =
_ServiceError . hasStatus 400 . hasCode "DuplicateLoadBalancerName"
-- | One or more of the specified security groups do not exist.
_InvalidSecurityGroupException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidSecurityGroupException =
_ServiceError . hasStatus 400 . hasCode "InvalidSecurityGroup"
-- | The load balancer does not have a listener configured at the specified
-- port.
_ListenerNotFoundException :: AsError a => Getting (First ServiceError) a ServiceError
_ListenerNotFoundException =
_ServiceError . hasStatus 400 . hasCode "ListenerNotFound"
-- | The specified endpoint is not valid.
_InvalidEndPointException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidEndPointException =
_ServiceError . hasStatus 400 . hasCode "InvalidInstance"
-- | The specified value for the schema is not valid. You can only specify a
-- scheme for load balancers in a VPC.
_InvalidSchemeException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidSchemeException =
_ServiceError . hasStatus 400 . hasCode "InvalidScheme"
-- | The quota for the number of load balancers has been reached.
_TooManyAccessPointsException :: AsError a => Getting (First ServiceError) a ServiceError
_TooManyAccessPointsException =
_ServiceError . hasStatus 400 . hasCode "TooManyLoadBalancers"
-- | The quota for the number of policies for this load balancer has been
-- reached.
_TooManyPoliciesException :: AsError a => Getting (First ServiceError) a ServiceError
_TooManyPoliciesException =
_ServiceError . hasStatus 400 . hasCode "TooManyPolicies"
-- | The specified SSL ID does not refer to a valid SSL certificate in AWS
-- Identity and Access Management (IAM).
_CertificateNotFoundException :: AsError a => Getting (First ServiceError) a ServiceError
_CertificateNotFoundException =
_ServiceError . hasStatus 400 . hasCode "CertificateNotFound"
| fmapfmapfmap/amazonka | amazonka-elb/gen/Network/AWS/ELB/Types.hs | mpl-2.0 | 10,878 | 0 | 13 | 2,240 | 1,634 | 917 | 717 | 238 | 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.EC2.ReleaseAddress
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Releases the specified Elastic IP address.
--
-- After releasing an Elastic IP address, it is released to the IP address
-- pool and might be unavailable to you. Be sure to update your DNS records
-- and any servers or devices that communicate with the address. If you
-- attempt to release an Elastic IP address that you already released,
-- you\'ll get an 'AuthFailure' error if the address is already allocated
-- to another AWS account.
--
-- [EC2-Classic, default VPC] Releasing an Elastic IP address automatically
-- disassociates it from any instance that it\'s associated with. To
-- disassociate an Elastic IP address without releasing it, use
-- DisassociateAddress.
--
-- [Nondefault VPC] You must use DisassociateAddress to disassociate the
-- Elastic IP address before you try to release it. Otherwise, Amazon EC2
-- returns an error ('InvalidIPAddress.InUse').
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-ReleaseAddress.html AWS API Reference> for ReleaseAddress.
module Network.AWS.EC2.ReleaseAddress
(
-- * Creating a Request
releaseAddress
, ReleaseAddress
-- * Request Lenses
, raAllocationId
, raPublicIP
, raDryRun
-- * Destructuring the Response
, releaseAddressResponse
, ReleaseAddressResponse
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'releaseAddress' smart constructor.
data ReleaseAddress = ReleaseAddress'
{ _raAllocationId :: !(Maybe Text)
, _raPublicIP :: !(Maybe Text)
, _raDryRun :: !(Maybe Bool)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ReleaseAddress' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'raAllocationId'
--
-- * 'raPublicIP'
--
-- * 'raDryRun'
releaseAddress
:: ReleaseAddress
releaseAddress =
ReleaseAddress'
{ _raAllocationId = Nothing
, _raPublicIP = Nothing
, _raDryRun = Nothing
}
-- | [EC2-VPC] The allocation ID. Required for EC2-VPC.
raAllocationId :: Lens' ReleaseAddress (Maybe Text)
raAllocationId = lens _raAllocationId (\ s a -> s{_raAllocationId = a});
-- | [EC2-Classic] The Elastic IP address. Required for EC2-Classic.
raPublicIP :: Lens' ReleaseAddress (Maybe Text)
raPublicIP = lens _raPublicIP (\ s a -> s{_raPublicIP = a});
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
raDryRun :: Lens' ReleaseAddress (Maybe Bool)
raDryRun = lens _raDryRun (\ s a -> s{_raDryRun = a});
instance AWSRequest ReleaseAddress where
type Rs ReleaseAddress = ReleaseAddressResponse
request = postQuery eC2
response = receiveNull ReleaseAddressResponse'
instance ToHeaders ReleaseAddress where
toHeaders = const mempty
instance ToPath ReleaseAddress where
toPath = const "/"
instance ToQuery ReleaseAddress where
toQuery ReleaseAddress'{..}
= mconcat
["Action" =: ("ReleaseAddress" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"AllocationId" =: _raAllocationId,
"PublicIp" =: _raPublicIP, "DryRun" =: _raDryRun]
-- | /See:/ 'releaseAddressResponse' smart constructor.
data ReleaseAddressResponse =
ReleaseAddressResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ReleaseAddressResponse' with the minimum fields required to make a request.
--
releaseAddressResponse
:: ReleaseAddressResponse
releaseAddressResponse = ReleaseAddressResponse'
| olorin/amazonka | amazonka-ec2/gen/Network/AWS/EC2/ReleaseAddress.hs | mpl-2.0 | 4,601 | 0 | 11 | 893 | 543 | 333 | 210 | 67 | 1 |
module Ast.UsedNamesSpec where
import Control.Exception
import Data.Foldable
import Data.List
import Test.Hspec
import Ast.UsedNames
spec :: Spec
spec = do
let errs :: [(String, ())]
errs =
("errorNyiData", errorNyiData ()) :
("errorNyiOutputable", errorNyiOutputable ()) :
[]
forM_ errs $ \ (name, err) -> do
describe name $ do
it "explains that this is not yet implemented" $ do
seq err (return ()) `shouldThrow` \ (ErrorCall message) ->
"not yet implemented" `isInfixOf` message
it "points to the issue tracker" $ do
seq err (return ()) `shouldThrow` \ (ErrorCall message) ->
"https://github.com/soenkehahn/dead-code-detection/issues" `isInfixOf`
message
| froozen/dead-code-detection | test/Ast/UsedNamesSpec.hs | bsd-3-clause | 811 | 0 | 21 | 244 | 227 | 121 | 106 | 22 | 1 |
-- |
-- Module : Foundation.Primitives.Types.AsciiString
-- License : BSD-style
-- Maintainer : Haskell Foundation
-- Stability : experimental
-- Portability : portable
--
-- A AsciiString type backed by a `ASCII` encoded byte array and all the necessary
-- functions to manipulate the string.
--
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module Basement.Types.AsciiString
( AsciiString(..)
, MutableAsciiString(..)
-- * Binary conversion
, fromBytesUnsafe
, fromBytes
) where
import Basement.Compat.Base
import Basement.Compat.Semigroup
import Basement.Types.Char7
import Basement.UArray.Base
import qualified Basement.Types.Char7 as Char7
import qualified Basement.UArray as A (all, unsafeRecast)
-- | Opaque packed array of characters in the ASCII encoding
newtype AsciiString = AsciiString { toBytes :: UArray Char7 }
deriving (Typeable, Semigroup, Monoid, Eq, Ord)
newtype MutableAsciiString st = MutableAsciiString (MUArray Char7 st)
deriving (Typeable)
instance Show AsciiString where
show = fmap Char7.toChar . toList
instance IsString AsciiString where
fromString = fromList . fmap Char7.fromCharMask
instance IsList AsciiString where
type Item AsciiString = Char7
fromList = AsciiString . fromList
toList (AsciiString chars) = toList chars
-- | Convert a Byte Array representing ASCII data directly to an AsciiString without checking for ASCII validity
--
-- If the input contains invalid Char7 value (anything above 0x7f),
-- it will trigger runtime async errors when processing data.
--
-- In doubt, use 'fromBytes'
fromBytesUnsafe :: UArray Word8 -> AsciiString
fromBytesUnsafe = AsciiString . A.unsafeRecast
-- | Convert a Byte Array representing ASCII checking validity.
--
-- If the byte array is not valid, then Nothing is returned
fromBytes :: UArray Word8 -> Maybe AsciiString
fromBytes arr
| A.all (\x -> x < 0x80) arr = Just $ AsciiString $ A.unsafeRecast arr
| otherwise = Nothing
| vincenthz/hs-foundation | basement/Basement/Types/AsciiString.hs | bsd-3-clause | 2,216 | 0 | 11 | 477 | 347 | 205 | 142 | 34 | 1 |
--------------------------------------------------------------------------
-- Copyright (c) 2007-2010, ETH Zurich.
-- All rights reserved.
--
-- This file is distributed under the terms in the attached LICENSE file.
-- If you do not find this file, copies can be found by writing to:
-- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
--
-- Arguments to major Hake targets
--
--------------------------------------------------------------------------
module Args where
import HakeTypes
data Args = Args {
buildFunction :: [String] -> String -> Args -> HRule,
target :: String,
cFiles :: [String],
generatedCFiles :: [String],
cxxFiles :: [String],
generatedCxxFiles :: [String],
assemblyFiles :: [String],
flounderDefs :: [String],
flounderBindings :: [String], -- built stubs for all enabled backends
flounderExtraDefs :: [(String, [String])],
flounderExtraBindings :: [(String, [String])], -- build stubs for specific backends
flounderTHCDefs :: [String], -- TODO: this can probably be subsumed into the above?
flounderTHCStubs :: [String], -- TODO: this can probably be subsumed into the above?
mackerelDevices :: [String],
addCFlags :: [String],
addCxxFlags :: [String],
omitCFlags :: [String],
omitCxxFlags :: [String],
addIncludes :: [String],
omitIncludes :: [String],
addLinkFlags :: [String],
addLibraries :: [String],
addGeneratedDependencies :: [String],
architectures :: [String]
}
defaultArgs = Args {
buildFunction = defaultBuildFn,
target = "",
cFiles = [],
generatedCFiles = [],
cxxFiles = [],
generatedCxxFiles = [],
assemblyFiles = [],
flounderDefs = [],
flounderBindings = [],
flounderExtraDefs = [],
flounderExtraBindings = [],
flounderTHCDefs = [],
flounderTHCStubs = [],
mackerelDevices = [],
addCFlags = [],
addCxxFlags = [],
omitCFlags = [],
omitCxxFlags = [],
addIncludes = [],
omitIncludes = [],
addLinkFlags = [],
addLibraries = [],
addGeneratedDependencies = [],
architectures = allArchitectures
}
allArchitectures = [ "x86_64", "x86_32", "armv5", "arm11mp", "scc", "xscale", "armv7", "armv7-m", "k1om" ]
allArchitectureFamilies = [ "x86_64", "x86_32", "arm", "scc", "k1om" ]
-- architectures that currently support THC
thcArchitectures = ["x86_64", "x86_32", "scc"]
-- all known flounder backends that we might want to generate defs for
allFlounderBackends
= [ "lmp", "ump", "ump_ipi", "loopback", "rpcclient", "msgbuf", "multihop", "ahci" ]
defaultBuildFn :: [String] -> String -> Args -> HRule
defaultBuildFn _ f _ =
Error ("Bad use of default Args in " ++ f)
showArgs :: String -> Args -> String
showArgs prefix a =
prefix ++ "Args:"
++ "\n target: " ++ (show $ target a)
++ "\n cFiles: " ++ (show $ cFiles a)
++ "\n generatedCFiles: " ++ (show $ generatedCFiles a)
++ "\n cxxFiles: " ++ (show $ cxxFiles a)
++ "\n generatedCxxFiles " ++ (show $ generatedCxxFiles a)
++ "\n assemblyFiles: " ++ (show $ assemblyFiles a)
++ "\n flounderDefs: " ++ (show $ flounderDefs a)
++ "\n flounderBindings: " ++ (show $ flounderBindings a)
++ "\n flounderExtraDefs: " ++ (show $ flounderExtraDefs a)
++ "\n flounderExtraBindings: " ++ (show $ flounderExtraBindings a)
++ "\n flounderTHCDefs: " ++ (show $ flounderTHCDefs a)
++ "\n flounderTHCStubs: " ++ (show $ flounderTHCStubs a)
++ "\n addCFlags: " ++ (show $ addCFlags a)
++ "\n addCxxFlags: " ++ (show $ addCxxFlags a)
++ "\n omitCFlags: " ++ (show $ omitCFlags a)
++ "\n omitCxxFlags: " ++ (show $ omitCxxFlags a)
++ "\n addIncludes: " ++ (show $ addIncludes a)
++ "\n omitIncludes: " ++ (show $ omitIncludes a)
++ "\n addLinkFlags: " ++ (show $ addLinkFlags a)
++ "\n addLibraries: " ++ (show $ addLibraries a)
++ "\n addDeps: " ++ (show $ addGeneratedDependencies a)
++ "\n architectures: " ++ (show $ architectures a)
++ "\n"
| mslovy/barrelfish | hake/Args.hs | mit | 4,350 | 0 | 51 | 1,177 | 1,033 | 606 | 427 | 86 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
module Test.Common.TestHandler (testHandler) where
------------------------------------------------------------------------------
import Control.Concurrent (threadDelay)
import Control.Exception (throwIO)
import Control.Monad (liftM)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Data.ByteString.Builder (Builder, byteString)
import Data.ByteString.Builder.Extra (flush)
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import Data.List (sort)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import Data.Monoid (Monoid (mappend, mconcat, mempty))
------------------------------------------------------------------------------
import Snap.Core (Request (rqParams, rqURI), Snap, getParam, getRequest, logError, modifyResponse, redirect, route, rqClientAddr, rqClientPort, setContentLength, setContentType, setHeader, setResponseBody, setResponseCode, setTimeout, transformRequestBody, writeBS, writeBuilder, writeLBS)
import Snap.Internal.Debug ()
import Snap.Util.FileServe (serveDirectory)
import Snap.Util.FileUploads (PartInfo (partContentType, partFileName), allowWithMaximumSize, defaultUploadPolicy, disallow, handleFileUploads)
import Snap.Util.GZip (noCompression, withCompression)
import System.Directory (createDirectoryIfMissing)
import System.IO.Streams (OutputStream)
import qualified System.IO.Streams as Streams
import Test.Common.Rot13 (rot13)
------------------------------------------------------------------------------
-- timeout handling
------------------------------------------------------------------------------
timeoutTickleHandler :: Snap ()
timeoutTickleHandler = do
noCompression -- FIXME: remove this when zlib-bindings and
-- zlib-enumerator support gzip stream flushing
modifyResponse $ setResponseBody (trickleOutput 10)
. setContentType "text/plain"
setTimeout 2
badTimeoutTickleHandler :: Snap ()
badTimeoutTickleHandler = do
noCompression -- FIXME: remove this when zlib-bindings and
-- zlib-enumerator support gzip stream flushing
modifyResponse $ setResponseBody (trickleOutput 10)
. setContentType "text/plain"
setTimeout 2
trickleOutput :: Int -> OutputStream Builder -> IO (OutputStream Builder)
trickleOutput n os = do
Streams.fromList dots >>= Streams.mapM f >>= Streams.supplyTo os
return os
where
dots = replicate n ".\n"
f x = threadDelay 1000000 >> return (byteString x `mappend` flush)
------------------------------------------------------------------------------
pongHandler :: Snap ()
pongHandler = modifyResponse $
setResponseBody body .
setContentType "text/plain" .
setContentLength 4
where
body os = do Streams.write (Just $ byteString "PONG") os
return os
echoUriHandler :: Snap ()
echoUriHandler = do
req <- getRequest
writeBS $ rqURI req
echoHandler :: Snap ()
echoHandler = transformRequestBody return
rot13Handler :: Snap ()
rot13Handler = transformRequestBody (Streams.map rot13)
bigResponseHandler :: Snap ()
bigResponseHandler = do
let sz = 4000000
let s = L.take sz $ L.cycle $ L.fromChunks [S.replicate 400000 '.']
modifyResponse $ setContentLength $ fromIntegral sz
writeLBS s
responseHandler :: Snap ()
responseHandler = do
!code <- liftM (read . S.unpack . fromMaybe "503") $ getParam "code"
modifyResponse $ setResponseCode code
writeBS $ S.pack $ show code
uploadForm :: Snap ()
uploadForm = do
modifyResponse $ setContentType "text/html"
writeBS form
where
form = S.concat [ "<html><head><title>Upload a file</title></head><body>\n"
, "<p>Upload some <code>text/plain</code> files:</p>\n"
, "<form method='post' "
, "enctype='multipart/form-data' "
, "action='/upload/handle'>\n"
, "<input type='file' "
, "accept='text/plain' "
, "multiple='true' "
, "name='file'></input>\n"
, "<input type='submit' name='Submit'></input>\n"
, "</form></body></html>" ]
uploadHandler :: Snap ()
uploadHandler = do
logError "uploadHandler"
liftIO $ createDirectoryIfMissing True tmpdir
files <- handleFileUploads tmpdir defaultUploadPolicy partPolicy hndl
let m = sort files
params <- liftM (Prelude.map (\(a,b) -> (a,S.concat b)) .
Map.toAscList .
rqParams) getRequest
modifyResponse $ setContentType "text/plain"
writeBuilder $ buildRqParams params `mappend` buildFiles m
where
f p = fromMaybe "-" $ partFileName p
hndl _ (Left e) = throwIO e
hndl partInfo (Right fp) = do
!c <- liftIO $ S.readFile fp
return $! (f partInfo, c)
builder _ [] = mempty
builder ty ((k,v):xs) =
mconcat [ byteString ty
, byteString ":\n"
, byteString k
, byteString "\nValue:\n"
, byteString v
, byteString "\n\n"
, builder ty xs ]
buildRqParams = builder "Param"
buildFiles = builder "File"
tmpdir = "dist/filetmp"
partPolicy partInfo = if partContentType partInfo == "text/plain"
then allowWithMaximumSize 200000
else disallow
serverHeaderHandler :: Snap ()
serverHeaderHandler = modifyResponse $ setHeader "Server" "foo"
chunkedResponse :: Snap ()
chunkedResponse = writeBS "chunked"
remoteAddrPort :: Snap ()
remoteAddrPort = do
rq <- getRequest
let addr = rqClientAddr rq
let port = rqClientPort rq
let out = S.concat [ addr, ":", S.pack (show port) ]
modifyResponse $ setContentLength $ fromIntegral $ S.length out
writeBS out
testHandler :: Snap ()
testHandler = withCompression $
route [ ("pong" , pongHandler )
, ("redirect" , redirect "/pong" )
, ("echo" , echoHandler )
, ("rot13" , rot13Handler )
, ("echoUri" , echoUriHandler )
, ("remoteAddrPort" , remoteAddrPort )
, ("fileserve" , noCompression >>
serveDirectory "testserver/static")
, ("bigresponse" , bigResponseHandler )
, ("respcode/:code" , responseHandler )
, ("upload/form" , uploadForm )
, ("upload/handle" , uploadHandler )
, ("timeout/tickle" , timeoutTickleHandler )
, ("timeout/badtickle" , badTimeoutTickleHandler )
, ("server-header" , serverHeaderHandler )
, ("chunked" , chunkedResponse )
]
| k-bx/snap-server | test/Test/Common/TestHandler.hs | bsd-3-clause | 7,608 | 0 | 17 | 2,455 | 1,600 | 858 | 742 | 144 | 4 |
module Distribution.Simple.HaskellSuite where
import Control.Monad
import Data.Maybe
import Data.Version
import qualified Data.Map as M (empty)
import Distribution.Simple.Program
import Distribution.Simple.Compiler as Compiler
import Distribution.Simple.Utils
import Distribution.Simple.BuildPaths
import Distribution.Verbosity
import Distribution.Text
import Distribution.Package
import Distribution.InstalledPackageInfo hiding (includeDirs)
import Distribution.Simple.PackageIndex as PackageIndex
import Distribution.PackageDescription
import Distribution.Simple.LocalBuildInfo
import Distribution.System (Platform)
import Distribution.Compat.Exception
import Language.Haskell.Extension
import Distribution.Simple.Program.Builtin
configure
:: Verbosity -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity mbHcPath hcPkgPath conf0 = do
-- We have no idea how a haskell-suite tool is named, so we require at
-- least some information from the user.
hcPath <-
let msg = "You have to provide name or path of a haskell-suite tool (-w PATH)"
in maybe (die msg) return mbHcPath
when (isJust hcPkgPath) $
warn verbosity "--with-hc-pkg option is ignored for haskell-suite"
(comp, confdCompiler, conf1) <- configureCompiler hcPath conf0
-- Update our pkg tool. It uses the same executable as the compiler, but
-- all command start with "pkg"
(confdPkg, _) <- requireProgram verbosity haskellSuitePkgProgram conf1
let conf2 =
updateProgram
confdPkg
{ programLocation = programLocation confdCompiler
, programDefaultArgs = ["pkg"]
}
conf1
return (comp, Nothing, conf2)
where
configureCompiler hcPath conf0' = do
let
haskellSuiteProgram' =
haskellSuiteProgram
{ programFindLocation = \v p -> findProgramOnSearchPath v p hcPath }
-- NB: cannot call requireProgram right away — it'd think that
-- the program is already configured and won't reconfigure it again.
-- Instead, call configureProgram directly first.
conf1 <- configureProgram verbosity haskellSuiteProgram' conf0'
(confdCompiler, conf2) <- requireProgram verbosity haskellSuiteProgram' conf1
extensions <- getExtensions verbosity confdCompiler
languages <- getLanguages verbosity confdCompiler
(compName, compVersion) <-
getCompilerVersion verbosity confdCompiler
let
comp = Compiler {
compilerId = CompilerId (HaskellSuite compName) compVersion,
compilerAbiTag = Compiler.NoAbiTag,
compilerCompat = [],
compilerLanguages = languages,
compilerExtensions = extensions,
compilerProperties = M.empty
}
return (comp, confdCompiler, conf2)
hstoolVersion :: Verbosity -> FilePath -> IO (Maybe Version)
hstoolVersion = findProgramVersion "--hspkg-version" id
numericVersion :: Verbosity -> FilePath -> IO (Maybe Version)
numericVersion = findProgramVersion "--compiler-version" (last . words)
getCompilerVersion :: Verbosity -> ConfiguredProgram -> IO (String, Version)
getCompilerVersion verbosity prog = do
output <- rawSystemStdout verbosity (programPath prog) ["--compiler-version"]
let
parts = words output
name = concat $ init parts -- there shouldn't be any spaces in the name anyway
versionStr = last parts
version <-
maybe (die "haskell-suite: couldn't determine compiler version") return $
simpleParse versionStr
return (name, version)
getExtensions :: Verbosity -> ConfiguredProgram -> IO [(Extension, Compiler.Flag)]
getExtensions verbosity prog = do
extStrs <-
lines `fmap`
rawSystemStdout verbosity (programPath prog) ["--supported-extensions"]
return
[ (ext, "-X" ++ display ext) | Just ext <- map simpleParse extStrs ]
getLanguages :: Verbosity -> ConfiguredProgram -> IO [(Language, Compiler.Flag)]
getLanguages verbosity prog = do
langStrs <-
lines `fmap`
rawSystemStdout verbosity (programPath prog) ["--supported-languages"]
return
[ (ext, "-G" ++ display ext) | Just ext <- map simpleParse langStrs ]
-- Other compilers do some kind of a packagedb stack check here. Not sure
-- if we need something like that as well.
getInstalledPackages :: Verbosity -> PackageDBStack -> ProgramConfiguration
-> IO InstalledPackageIndex
getInstalledPackages verbosity packagedbs conf =
liftM (PackageIndex.fromList . concat) $ forM packagedbs $ \packagedb ->
do str <-
getDbProgramOutput verbosity haskellSuitePkgProgram conf
["dump", packageDbOpt packagedb]
`catchExit` \_ -> die $ "pkg dump failed"
case parsePackages str of
Right ok -> return ok
_ -> die "failed to parse output of 'pkg dump'"
where
parsePackages str =
let parsed = map parseInstalledPackageInfo (splitPkgs str)
in case [ msg | ParseFailed msg <- parsed ] of
[] -> Right [ pkg | ParseOk _ pkg <- parsed ]
msgs -> Left msgs
splitPkgs :: String -> [String]
splitPkgs = map unlines . splitWith ("---" ==) . lines
where
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith p xs = ys : case zs of
[] -> []
_:ws -> splitWith p ws
where (ys,zs) = break p xs
buildLib
:: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do
-- In future, there should be a mechanism for the compiler to request any
-- number of the above parameters (or their parts) — in particular,
-- pieces of PackageDescription.
--
-- For now, we only pass those that we know are used.
let odir = buildDir lbi
bi = libBuildInfo lib
srcDirs = hsSourceDirs bi ++ [odir]
dbStack = withPackageDB lbi
language = fromMaybe Haskell98 (defaultLanguage bi)
conf = withPrograms lbi
pkgid = packageId pkg_descr
runDbProgram verbosity haskellSuiteProgram conf $
[ "compile", "--build-dir", odir ] ++
concat [ ["-i", d] | d <- srcDirs ] ++
concat [ ["-I", d] | d <- [autogenModulesDir lbi, odir] ++ includeDirs bi ] ++
[ packageDbOpt pkgDb | pkgDb <- dbStack ] ++
[ "--package-name", display pkgid ] ++
concat [ ["--package-id", display ipkgid ]
| (ipkgid, _) <- componentPackageDeps clbi ] ++
["-G", display language] ++
concat [ ["-X", display ex] | ex <- usedExtensions bi ] ++
cppOptions (libBuildInfo lib) ++
[ display modu | modu <- libModules lib ]
installLib
:: Verbosity
-> LocalBuildInfo
-> FilePath -- ^install location
-> FilePath -- ^install location for dynamic libraries
-> FilePath -- ^Build location
-> PackageDescription
-> Library
-> ComponentLocalBuildInfo
-> IO ()
installLib verbosity lbi targetDir dynlibTargetDir builtDir pkg lib _clbi = do
let conf = withPrograms lbi
runDbProgram verbosity haskellSuitePkgProgram conf $
[ "install-library"
, "--build-dir", builtDir
, "--target-dir", targetDir
, "--dynlib-target-dir", dynlibTargetDir
, "--package-id", display $ packageId pkg
] ++ map display (libModules lib)
registerPackage
:: Verbosity
-> ProgramConfiguration
-> PackageDBStack
-> InstalledPackageInfo
-> IO ()
registerPackage verbosity progdb packageDbs installedPkgInfo = do
(hspkg, _) <- requireProgram verbosity haskellSuitePkgProgram progdb
runProgramInvocation verbosity $
(programInvocation hspkg
["update", packageDbOpt $ last packageDbs])
{ progInvokeInput = Just $ showInstalledPackageInfo installedPkgInfo }
initPackageDB :: Verbosity -> ProgramConfiguration -> FilePath -> IO ()
initPackageDB verbosity conf dbPath =
runDbProgram verbosity haskellSuitePkgProgram conf
["init", dbPath]
packageDbOpt :: PackageDB -> String
packageDbOpt GlobalPackageDB = "--global"
packageDbOpt UserPackageDB = "--user"
packageDbOpt (SpecificPackageDB db) = "--package-db=" ++ db
| tolysz/prepare-ghcjs | spec-lts8/cabal/Cabal/Distribution/Simple/HaskellSuite.hs | bsd-3-clause | 8,207 | 0 | 21 | 1,849 | 1,986 | 1,032 | 954 | 172 | 4 |
<?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="ar-SA">
<title>Report Generation</title>
<maps>
<homeID>reports</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> | kingthorin/zap-extensions | addOns/reports/src/main/javahelp/org/zaproxy/addon/reports/resources/help_ar_SA/helpset_ar_SA.hs | apache-2.0 | 966 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
--------------------------------------------------------------------------------
-- | Deal with Cmm registers
--
module LlvmCodeGen.Regs (
lmGlobalRegArg, lmGlobalRegVar, alwaysLive,
stgTBAA, baseN, stackN, heapN, rxN, otherN, tbaa, getTBAA
) where
#include "HsVersions.h"
import Llvm
import CmmExpr
import DynFlags
import FastString
import Outputable ( panic )
import Unique
-- | Get the LlvmVar function variable storing the real register
lmGlobalRegVar :: DynFlags -> GlobalReg -> LlvmVar
lmGlobalRegVar dflags = pVarLift . lmGlobalReg dflags "_Var"
-- | Get the LlvmVar function argument storing the real register
lmGlobalRegArg :: DynFlags -> GlobalReg -> LlvmVar
lmGlobalRegArg dflags = lmGlobalReg dflags "_Arg"
{- Need to make sure the names here can't conflict with the unique generated
names. Uniques generated names containing only base62 chars. So using say
the '_' char guarantees this.
-}
lmGlobalReg :: DynFlags -> String -> GlobalReg -> LlvmVar
lmGlobalReg dflags suf reg
= case reg of
BaseReg -> ptrGlobal $ "Base" ++ suf
Sp -> ptrGlobal $ "Sp" ++ suf
Hp -> ptrGlobal $ "Hp" ++ suf
VanillaReg 1 _ -> wordGlobal $ "R1" ++ suf
VanillaReg 2 _ -> wordGlobal $ "R2" ++ suf
VanillaReg 3 _ -> wordGlobal $ "R3" ++ suf
VanillaReg 4 _ -> wordGlobal $ "R4" ++ suf
VanillaReg 5 _ -> wordGlobal $ "R5" ++ suf
VanillaReg 6 _ -> wordGlobal $ "R6" ++ suf
VanillaReg 7 _ -> wordGlobal $ "R7" ++ suf
VanillaReg 8 _ -> wordGlobal $ "R8" ++ suf
SpLim -> wordGlobal $ "SpLim" ++ suf
FloatReg 1 -> floatGlobal $"F1" ++ suf
FloatReg 2 -> floatGlobal $"F2" ++ suf
FloatReg 3 -> floatGlobal $"F3" ++ suf
FloatReg 4 -> floatGlobal $"F4" ++ suf
FloatReg 5 -> floatGlobal $"F5" ++ suf
FloatReg 6 -> floatGlobal $"F6" ++ suf
DoubleReg 1 -> doubleGlobal $ "D1" ++ suf
DoubleReg 2 -> doubleGlobal $ "D2" ++ suf
DoubleReg 3 -> doubleGlobal $ "D3" ++ suf
DoubleReg 4 -> doubleGlobal $ "D4" ++ suf
DoubleReg 5 -> doubleGlobal $ "D5" ++ suf
DoubleReg 6 -> doubleGlobal $ "D6" ++ suf
XmmReg 1 -> xmmGlobal $ "XMM1" ++ suf
XmmReg 2 -> xmmGlobal $ "XMM2" ++ suf
XmmReg 3 -> xmmGlobal $ "XMM3" ++ suf
XmmReg 4 -> xmmGlobal $ "XMM4" ++ suf
XmmReg 5 -> xmmGlobal $ "XMM5" ++ suf
XmmReg 6 -> xmmGlobal $ "XMM6" ++ suf
YmmReg 1 -> ymmGlobal $ "YMM1" ++ suf
YmmReg 2 -> ymmGlobal $ "YMM2" ++ suf
YmmReg 3 -> ymmGlobal $ "YMM3" ++ suf
YmmReg 4 -> ymmGlobal $ "YMM4" ++ suf
YmmReg 5 -> ymmGlobal $ "YMM5" ++ suf
YmmReg 6 -> ymmGlobal $ "YMM6" ++ suf
ZmmReg 1 -> zmmGlobal $ "ZMM1" ++ suf
ZmmReg 2 -> zmmGlobal $ "ZMM2" ++ suf
ZmmReg 3 -> zmmGlobal $ "ZMM3" ++ suf
ZmmReg 4 -> zmmGlobal $ "ZMM4" ++ suf
ZmmReg 5 -> zmmGlobal $ "ZMM5" ++ suf
ZmmReg 6 -> zmmGlobal $ "ZMM6" ++ suf
_other -> panic $ "LlvmCodeGen.Reg: GlobalReg (" ++ (show reg)
++ ") not supported!"
-- LongReg, HpLim, CCSS, CurrentTSO, CurrentNusery, HpAlloc
-- EagerBlackholeInfo, GCEnter1, GCFun, BaseReg, PicBaseReg
where
wordGlobal name = LMNLocalVar (fsLit name) (llvmWord dflags)
ptrGlobal name = LMNLocalVar (fsLit name) (llvmWordPtr dflags)
floatGlobal name = LMNLocalVar (fsLit name) LMFloat
doubleGlobal name = LMNLocalVar (fsLit name) LMDouble
xmmGlobal name = LMNLocalVar (fsLit name) (LMVector 4 (LMInt 32))
ymmGlobal name = LMNLocalVar (fsLit name) (LMVector 8 (LMInt 32))
zmmGlobal name = LMNLocalVar (fsLit name) (LMVector 16 (LMInt 32))
-- | A list of STG Registers that should always be considered alive
alwaysLive :: [GlobalReg]
alwaysLive = [BaseReg, Sp, Hp, SpLim, HpLim, node]
-- | STG Type Based Alias Analysis hierarchy
stgTBAA :: [(Unique, LMString, Maybe Unique)]
stgTBAA
= [ (topN, fsLit "top", Nothing)
, (stackN, fsLit "stack", Just topN)
, (heapN, fsLit "heap", Just topN)
, (rxN, fsLit "rx", Just heapN)
, (baseN, fsLit "base", Just topN)
-- FIX: Not 100% sure about 'others' place. Might need to be under 'heap'.
-- OR I think the big thing is Sp is never aliased, so might want
-- to change the hieracy to have Sp on its own branch that is never
-- aliased (e.g never use top as a TBAA node).
, (otherN, fsLit "other", Just topN)
]
-- | Id values
topN, stackN, heapN, rxN, baseN, otherN :: Unique
topN = getUnique (fsLit "LlvmCodeGen.Regs.topN")
stackN = getUnique (fsLit "LlvmCodeGen.Regs.stackN")
heapN = getUnique (fsLit "LlvmCodeGen.Regs.heapN")
rxN = getUnique (fsLit "LlvmCodeGen.Regs.rxN")
baseN = getUnique (fsLit "LlvmCodeGen.Regs.baseN")
otherN = getUnique (fsLit "LlvmCodeGen.Regs.otherN")
-- | The TBAA metadata identifier
tbaa :: LMString
tbaa = fsLit "tbaa"
-- | Get the correct TBAA metadata information for this register type
getTBAA :: GlobalReg -> Unique
getTBAA BaseReg = baseN
getTBAA Sp = stackN
getTBAA Hp = heapN
getTBAA (VanillaReg _ _) = rxN
getTBAA _ = topN
| lukexi/ghc-7.8-arm64 | compiler/llvmGen/LlvmCodeGen/Regs.hs | bsd-3-clause | 5,473 | 0 | 11 | 1,605 | 1,432 | 733 | 699 | 92 | 43 |
module RenameParamIn2 where
{- add1 n xs = foldl (+) n xs -}
add1 n xs = (case ((+), n, xs) of
(f, z, []) -> z
(f, z, (x : xs)) -> add1 ( ((+) n x)) xs)
{- by the rule above:
foldl f (f z x) xs = add1 (f z x) xs -}
| kmate/HaRe | old/testing/generativeFold/RenameParamIn2_TokOut.hs | bsd-3-clause | 263 | 0 | 12 | 105 | 91 | 55 | 36 | 4 | 2 |
module Prelude where
data Int
data Bool = False|True
--f x = (x::Int,x::Bool)
g = \ x->x::Int
| forste/haReFork | tools/base/tests/tiTest9.hs | bsd-3-clause | 97 | 0 | 5 | 20 | 31 | 20 | 11 | -1 | -1 |
{-# LANGUAGE CPP, ForeignFunctionInterface #-}
module Data.HashMap.PopCount
( popCount
) where
#if __GLASGOW_HASKELL__ >= 704
import Data.Bits (popCount)
#else
import Data.Word (Word)
import Foreign.C (CUInt)
#endif
#if __GLASGOW_HASKELL__ < 704
foreign import ccall unsafe "popc.h popcount" c_popcount :: CUInt -> CUInt
popCount :: Word -> Int
popCount w = fromIntegral (c_popcount (fromIntegral w))
#endif | pacak/cuddly-bassoon | unordered-containers-0.2.8.0/Data/HashMap/PopCount.hs | bsd-3-clause | 419 | 0 | 9 | 65 | 78 | 46 | 32 | 8 | 1 |
-- !!! Desugaring sections with function-type arguments
-- Although this is really a desugaring test, the problem is
-- only tickled by the simplifier
-- type Foo a b = a -> (b -> a) -> b
module ShouldCompile where
(++++) :: (a -> (b -> a) -> b) -> (a -> (b -> a) -> b) -> a -> (b -> a) -> b
x ++++ y = y
g a xs = map (++++ a) xs
h b xs = map (b ++++) xs
| ghc-android/ghc | testsuite/tests/simplCore/should_compile/simpl001.hs | bsd-3-clause | 360 | 0 | 11 | 91 | 123 | 69 | 54 | 5 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.